From 6443a5c44211acd891f41f4b3c9a4515b2474cc8 Mon Sep 17 00:00:00 2001 From: CRT Date: Fri, 16 Oct 2026 06:14:02 +0800 Subject: [PATCH 001/344] neutral names in docs, tests and comments (no real app or project names) --- apps/desktop/src-tauri/tests/d5.rs | 6 +++--- apps/desktop/src-tauri/tests/machine.rs | 14 +++++++------- docs/desktop-release.md | 2 +- tests/desktop-dist.test.ts | 6 +++--- tests/machine.test.ts | 24 ++++++++++++------------ tests/onboard.test.ts | 2 +- tests/template-answers.test.ts | 2 +- 7 files changed, 28 insertions(+), 28 deletions(-) diff --git a/apps/desktop/src-tauri/tests/d5.rs b/apps/desktop/src-tauri/tests/d5.rs index 7d20dce..27fd060 100644 --- a/apps/desktop/src-tauri/tests/d5.rs +++ b/apps/desktop/src-tauri/tests/d5.rs @@ -55,12 +55,12 @@ fn updater_has_a_real_minisign_key_and_only_storebound_dev() { #[test] fn open_deep_link_takes_one_plain_absolute_path() { let p = |s: &str| deep_link_open_path(&Url::parse(s).unwrap()); - let abs = if cfg!(windows) { "C:%5Cgames%5CDemo App" } else { "%2FUsers%2Fyou%2Fgames%2FDemo App" }; - let want = if cfg!(windows) { "C:\\games\\Demo App" } else { "/Users/you/games/Demo App" }; + let abs = if cfg!(windows) { "C:%5Cgames%5Cdemo-app" } else { "%2FUsers%2Fyou%2Fgames%2Fdemo-app" }; + let want = if cfg!(windows) { "C:\\games\\demo-app" } else { "/Users/you/games/demo-app" }; assert_eq!(p(&format!("storebound://open?path={abs}")), Some(PathBuf::from(want))); assert_eq!(p(&format!("storebound://open/?path={abs}")), Some(PathBuf::from(want))); for bad in [ - "storebound://open?path=games%2FDemo App".to_string(), + "storebound://open?path=games%2Fdemo-app".to_string(), "storebound://open?path=".to_string(), "storebound://open".to_string(), format!("storebound://open?path={abs}&path={abs}"), diff --git a/apps/desktop/src-tauri/tests/machine.rs b/apps/desktop/src-tauri/tests/machine.rs index 78d76ad..3dde508 100644 --- a/apps/desktop/src-tauri/tests/machine.rs +++ b/apps/desktop/src-tauri/tests/machine.rs @@ -46,7 +46,7 @@ fn ids_match_the_cli() { // cli/lib/workspace.ts accountId and cli/lib/registry.ts folderId give the same values assert_eq!(profiles::account_id(AccountKind::Apple, "acme"), "747351dbf2569d17"); assert_eq!(profiles::account_id(AccountKind::Play, "default"), "82a8c2561d950999"); - assert_eq!(registry::folder_id("/w/Star Dash"), "f4994b9746e7eb18"); + assert_eq!(registry::folder_id("/w/star-dash"), "c27311c5023dc3ba"); assert!(profiles::valid_name("default") && profiles::valid_name("acme-games.2") && !profiles::valid_name("../x") && !profiles::valid_name("-a")); assert_eq!(profiles::slug("Acme Games: Play!"), "acme-games-play"); assert_eq!(profiles::slug("???"), "account"); @@ -133,19 +133,19 @@ fn project(id: &str, path: &str, play: Option<&str>) -> Project { fn the_folder_list_is_the_machines() { let dir = tempfile::tempdir().unwrap(); let file = dir.path().join("projects.json"); - let mut st = State { projects: vec![project("aaaaaaaaaaaaaaaa", "/w/Star Dash", Some("acc"))], ..State::default() }; + let mut st = State { projects: vec![project("aaaaaaaaaaaaaaaa", "/w/star-dash", Some("acc"))], ..State::default() }; // first start: the app's list becomes the shared one assert!(!registry::sync(&mut st, &file).unwrap()); assert_eq!(registry::read(&file).unwrap()[0].id, "aaaaaaaaaaaaaaaa"); // the CLI adds a folder (storebound desktop / apps add): the app shows it, the first keeps its accounts let mut list = registry::read(&file).unwrap(); - list.push(Entry { id: registry::folder_id("/w/a game"), path: "/w/a game".into(), name: "a game".into(), added: "t".into() }); + list.push(Entry { id: registry::folder_id("/w/demo-game"), path: "/w/demo-game".into(), name: "demo-game".into(), added: "t".into() }); registry::write(&file, &list).unwrap(); assert!(registry::sync(&mut st, &file).unwrap()); - assert_eq!(st.projects.iter().map(|p| p.path.as_str()).collect::>(), vec!["/w/Star Dash", "/w/a game"]); + assert_eq!(st.projects.iter().map(|p| p.path.as_str()).collect::>(), vec!["/w/star-dash", "/w/demo-game"]); assert_eq!(st.projects[0].play_account.as_deref(), Some("acc")); // the CLI removes one (apps remove): it leaves the app with its overrides - st.overrides.ignored.push(format!("project:{}", registry::folder_id("/w/a game"))); + st.overrides.ignored.push(format!("project:{}", registry::folder_id("/w/demo-game"))); registry::write(&file, &list[..1]).unwrap(); assert!(registry::sync(&mut st, &file).unwrap()); assert_eq!(st.projects.len(), 1); @@ -155,7 +155,7 @@ fn the_folder_list_is_the_machines() { registry::write(&file, &[list[0].clone(), Entry { id: registry::folder_id("/w/cli"), path: "/w/cli".into(), name: "cli".into(), added: String::new() }]).unwrap(); registry::publish(&st, &file, &[]).unwrap(); let paths: Vec = registry::read(&file).unwrap().into_iter().map(|e| e.path).collect(); - assert_eq!(paths, vec!["/w/Star Dash", "/w/third", "/w/cli"]); + assert_eq!(paths, vec!["/w/star-dash", "/w/third", "/w/cli"]); // bad entries are dropped, not the whole file assert_eq!(registry::parse(r#"{"projects":[{"path":"rel"},{"path":"/a","id":"XYZ"},{"path":"/a"}]}"#).iter().map(|e| e.id.clone()).collect::>(), vec![registry::folder_id("/a")]); } @@ -173,7 +173,7 @@ fn store_only_apps_join_their_profiles_account_and_survive_folder_writes() { assert_eq!(apps.iter().map(|a| a.app_id.as_str()).collect::>(), vec!["6400000999", "com.example.legacy"]); assert_eq!(apps[1].bundle_id.as_deref(), Some("com.example.legacy")); // the app writes its folder list: the store-only entries stay - let mut st = State { projects: vec![project("aaaaaaaaaaaaaaaa", "/w/Star Dash", None)], ..State::default() }; + let mut st = State { projects: vec![project("aaaaaaaaaaaaaaaa", "/w/star-dash", None)], ..State::default() }; registry::publish(&st, &file, &[]).unwrap(); assert_eq!(registry::read_store_apps(&file).len(), 2); assert!(registry::sync(&mut st, &file).is_ok()); diff --git a/docs/desktop-release.md b/docs/desktop-release.md index 81eccac..05a2222 100644 --- a/docs/desktop-release.md +++ b/docs/desktop-release.md @@ -316,7 +316,7 @@ candidate on a tag (Jenkins still publishes site/, and `publish` storebound.dev/ 3. **Windows runner on the VDS (done).** Windows Server 2022 Standard (evaluation) in a KVM virtual machine, in Docker (`dockurr/windows:6.05`), `/srv/windows-runner/`. Forgejo runner 13.2.0 (`vds-windows`, label `windows:host`, capacity 1, job timeout 3 h), registered at the **CRT user level**: every CRT repository can use - it (storebound, Demo App, ...). + it (storebound, demo-app, ...). - **Resources:** 8 vCPUs, 12 GB RAM, a 150 GB disk (`storage/data.img`, sparse). `restart: unless-stopped`. - **Network:** nothing public. The web viewer (8006), RDP (3389) and the VM's OpenSSH (22, as host port 2223) are bound to 127.0.0.1 on the VDS; use an SSH tunnel (`ssh -L 8006:127.0.0.1:8006 root@`, then diff --git a/tests/desktop-dist.test.ts b/tests/desktop-dist.test.ts index ba1fb10..ff2771d 100644 --- a/tests/desktop-dist.test.ts +++ b/tests/desktop-dist.test.ts @@ -126,9 +126,9 @@ describe('the installed app', () => { expect(findInstalled('linux', {}, at([]), '/home/you', () => ['storeboundish.AppImage'])).toBeNull(); }); test('opened with the folder as a deep link, never through a shell', () => { - const link = openFolderLink('/Users/you/games/Demo App & co'); - expect(link).toBe('storebound://open?path=%2FUsers%2Fyou%2Fgames%2FDemo App%20%26%20co'); - expect(new URL(link).searchParams.get('path')).toBe('/Users/you/games/Demo App & co'); + const link = openFolderLink('/Users/you/games/demo-app & co'); + expect(link).toBe('storebound://open?path=%2FUsers%2Fyou%2Fgames%2Fdemo-app%20%26%20co'); + expect(new URL(link).searchParams.get('path')).toBe('/Users/you/games/demo-app & co'); expect(openCommand('darwin', { path: '/Applications/storebound.app', how: 'bundle' }, link)).toEqual(['open', '-b', 'dev.storebound.desktop', link]); expect(openCommand('darwin', { path: '/Applications/storebound.app', how: 'bundle' }, null)).toEqual(['open', '-b', 'dev.storebound.desktop']); expect(openCommand('win32', { path: 'C:\\x\\storebound-desktop.exe', how: 'exe' }, link)).toEqual(['C:\\x\\storebound-desktop.exe', link]); diff --git a/tests/machine.test.ts b/tests/machine.test.ts index e3da940..2d12675 100644 --- a/tests/machine.test.ts +++ b/tests/machine.test.ts @@ -66,7 +66,7 @@ describe('credentials: one machine, many projects', () => { writeFileSync(join(creds, 'default.json'), JSON.stringify({ ASC_KEY_ID: 'DEFAULT000', ASC_ISSUER_ID: 'iss', ASC_P8: PEM('x') })); expect(defaultProfile()).toBe('teamB'); // the project's own keys beat the pointer; a profile the project names beats both; env beats all - const a = project(base, 'Star Dash'); + const a = project(base, 'star-dash'); expect(ascKey(a).keyId).toBe('ABCDE12345'); const file = join(a, '.storebound', 'credentials.json'); writeFileSync(file, JSON.stringify({ ...JSON.parse(readFileSync(file, 'utf8')), account: 'teamA' })); @@ -84,7 +84,7 @@ describe('credentials: one machine, many projects', () => { })); test('project-only values from the project, store keys from the profile, env over everything', () => machine(({ creds, base }) => { - const a = project(base, 'Star Dash'); + const a = project(base, 'star-dash'); // the project's own keys work without any profile expect(ascKey(a).keyId).toBe('ABCDE12345'); mkdirSync(creds, { recursive: true }); @@ -113,7 +113,7 @@ describe('credentials: one machine, many projects', () => { })); test('accounts import: two projects with the same Apple key and Play account -> one profile, 0600 files, projects stay valid', () => machine(({ creds, base }) => { - const a = project(base, 'Star Dash'), b = project(base, 'a game'); + const a = project(base, 'star-dash'), b = project(base, 'demo-game'); const dry = planImport(a); expect(dry.profile).toBe('default'); expect(dry.reuse).toBe(false); @@ -136,7 +136,7 @@ describe('credentials: one machine, many projects', () => { const projA = JSON.parse(readFileSync(join(a, '.storebound', 'credentials.json'), 'utf8')); expect(projA.account).toBe('default'); expect(projA.ASC_KEY_ID).toBeUndefined(); - expect(projA.ANDROID_KEYSTORE).toBe('Star Dash.jks'); + expect(projA.ANDROID_KEYSTORE).toBe('star-dash.jks'); expect(ascKey(a).pem).toContain('apple-secret-sentinel'); expect(playServiceAccount(a).client_email).toBe('release@example.com'); // the second project with the same account: the same profile, its files unchanged @@ -145,7 +145,7 @@ describe('credentials: one machine, many projects', () => { expect(second.reuse).toBe(true); expect(second.writes.filter(w => w.path.startsWith(creds)).map(w => w.action)).toEqual(['same']); applyImport(second); - expect(JSON.parse(readFileSync(join(b, '.storebound', 'credentials.json'), 'utf8')).ANDROID_KEYSTORE_PASSWORD).toBe('a game-pw'); + expect(JSON.parse(readFileSync(join(b, '.storebound', 'credentials.json'), 'utf8')).ANDROID_KEYSTORE_PASSWORD).toBe('demo-game-pw'); expect(ascKey(b).keyId).toBe('ABCDE12345'); // running it again changes nothing expect(planImport(b).writes.every(w => w.action === 'same')).toBe(true); @@ -157,13 +157,13 @@ describe('credentials: one machine, many projects', () => { expect(third.profile).toBe('other-studio'); applyImport(third); expect(ascKey(c).keyId).toBe('ZZZZZ99999'); - expect(ascKey(a).keyId).toBe('ABCDE12345'); // "account": "default" still points Star Dash at its own + expect(ascKey(a).keyId).toBe('ABCDE12345'); // "account": "default" still points star-dash at its own expect(useProfile(c, 'default')).toContain('credentials.json'); expect(() => useProfile(c, 'missing')).toThrow(/no profile/); })); test('the import command prints paths and names, never key values', () => machine(({ base }) => { - const a = project(base, 'Star Dash'); + const a = project(base, 'star-dash'); const r = Bun.spawnSync(['bun', join(ROOT, 'cli', 'index.ts'), 'accounts', 'import', '--dry', '--dir', a], { env: { ...process.env, STOREBOUND_NO_NETWORK: '1' } }); const out = r.stdout.toString() + r.stderr.toString(); expect(r.exitCode).toBe(0); @@ -179,14 +179,14 @@ describe('credentials: one machine, many projects', () => { describe('the machine\'s app folder list', () => { test('add, re-add, remove; ids are the desktop export ids; bad entries are dropped', () => machine(({ base }) => { const r0 = { version: 1 as const, projects: [] }; - const { registry, added } = withFolder(r0, '/w/Star Dash', 'Star Dash', 't'); + const { registry, added } = withFolder(r0, '/w/star-dash', 'Star Dash', 't'); expect(added).toBe(true); - expect(registry.projects[0]!.id).toBe(desktopProjectId('/w/Star Dash')); - expect(withFolder(registry, '/w/Star Dash/', undefined, 't').added).toBe(false); - expect(withoutFolder(registry, folderId('/w/Star Dash')).removed?.name).toBe('Star Dash'); + expect(registry.projects[0]!.id).toBe(desktopProjectId('/w/star-dash')); + expect(withFolder(registry, '/w/star-dash/', undefined, 't').added).toBe(false); + expect(withoutFolder(registry, folderId('/w/star-dash')).removed?.name).toBe('Star Dash'); expect(parseRegistry('{"projects":[{"path":"relative"},{"path":"/a","id":"zz"},{"path":"/a"}]}').projects.map(p => [p.path, p.id])).toEqual([['/a', folderId('/a')]]); expect(parseRegistry('not json').projects).toEqual([]); - const dir = project(base, 'a game'); + const dir = project(base, 'demo-game'); expect(addFolder(dir).added).toBe(true); expect(addFolder(dir).added).toBe(false); expect(readRegistry().projects.map(p => p.path)).toEqual([dir]); diff --git a/tests/onboard.test.ts b/tests/onboard.test.ts index 5273bd3..a0263eb 100644 --- a/tests/onboard.test.ts +++ b/tests/onboard.test.ts @@ -317,7 +317,7 @@ describe('store-only apps in the machine list', () => { expect(reg.storeApps).toEqual([{ id: storeAppId('apple', '6400000999'), store: 'apple', appId: '6400000999', account: 'teamA', name: 'Demo App', bundleId: null, added: reg.storeApps![0]!.added }]); expect(reg.projects).toEqual([]); // a folder added later keeps the store-only entry - const f = withFolder(reg, '/w/Star Dash', undefined, 't').registry; + const f = withFolder(reg, '/w/star-dash', undefined, 't').registry; expect(f.storeApps).toHaveLength(1); expect(parseRegistry(JSON.stringify(f)).storeApps).toHaveLength(1); const again = await capture(() => apps(parseArgs(['add', '--store', 'apple', '--app-id', '6400000999', '--account', 'teamA', '--name', 'Demo App'], []))); diff --git a/tests/template-answers.test.ts b/tests/template-answers.test.ts index 01eac32..92f2d61 100644 --- a/tests/template-answers.test.ts +++ b/tests/template-answers.test.ts @@ -51,7 +51,7 @@ describe('template answers', () => { }); test('a config from before `unanswered` is recognised by the template values; [] means answered', () => { - const legacy = { app: { name: 'Demo Blast', copyright: '2026 Example Studio' }, apple: { bundleId: 'x', info: { reviewNotes: 'mine', ageRating: { advertising: true } } }, + const legacy = { app: { name: 'DEMO BLAST', copyright: '2026 Example Studio' }, apple: { bundleId: 'x', info: { reviewNotes: 'mine', ageRating: { advertising: true } } }, dataSafety: { collectsData: true, encryptedInTransit: true, accountCreation: ['PSL_ACM_NONE'], data: { PSL_APPROX_LOCATION: { shared: true, collect: ['analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] }, PSL_USER_INTERACTION: { shared: true, collect: ['analytics', 'advertising'], share: ['analytics', 'advertising'] }, From 1f47b10fa9d18a6c38b2c8d1036f14b25e1f4036 Mon Sep 17 00:00:00 2001 From: CRT Date: Fri, 16 Oct 2026 06:33:40 +0800 Subject: [PATCH 002/344] CHANGELOG: Unreleased for 0.8.10 --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5eed096..a057109 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- **Neutral names only.** Docs, pitfalls, tests and comments use example names instead of the projects that reported + issues; the history was rewritten the same way. Older npm versions are withdrawn. +- **Releases:** a candidate whose build jobs were cancelled by a newer push says so and gives the tag move and + `--resume` line. + ## 0.8.9 · 2026-10-15 - **Play edits Play will not send for review are committed anyway.** After a rejection, with other pending changes or From b6c4beaadaf7de711a4bbce81fcc945b5c758e79 Mon Sep 17 00:00:00 2001 From: CRT Date: Fri, 16 Oct 2026 06:34:51 +0800 Subject: [PATCH 003/344] release: the CHANGELOG cut is checked before any version copy changes, and in the dry run (an empty Unreleased left every copy bumped and the next run refused 'not newer') --- tools/release.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tools/release.ts b/tools/release.ts index 162654c..2e82dbf 100644 --- a/tools/release.ts +++ b/tools/release.ts @@ -275,6 +275,8 @@ async function main(): Promise { push ${branch}, push ${tag}; then in parallel: Mac build + notarize -> ${out.replace(HOME, '~')}; macOS acceptance (${accCached ? 'cached' : 'runs now'}, key ${key.slice(0, 12)}); Forgejo ci (candidate of the bump commit) + release.yml (promotion); add, verify, publish to ${rehearsal ? 'the rehearsal channel' : 'stable'} via ${host}; ${rehearsal ? 'app copied to a scratch folder; then the tag, release, candidates, branch and storebound.dev files of the rehearsal are deleted' : 'update /Applications/storebound.app; print npm publish + npm deprecate'}`); + // the dry run catches what the bump would refuse + if (!rehearsal && !resume) { try { cutChangelog(readFileSync(join(ROOT, 'CHANGELOG.md'), 'utf8'), version, '2000-01-01'); } catch (e) { fail((e as Error).message); } } if (!yes) { console.log('\ndry run: nothing changed (--yes to release)'); return; } const accP = TESTS ? phase('macOS acceptance (cache or 3 runs)', () => macAcceptance(key, logDir)) : Promise.resolve(''); @@ -285,8 +287,10 @@ async function main(): Promise { let sha = resume ? head : ''; if (!resume) await phase('bump + fast gate + commit + push', async () => { if (rehearsal) sh(['git', 'checkout', '-q', '-b', branch]); + // the CHANGELOG cut is checked before any file changes (an empty Unreleased once left every version copy bumped) + const cut = rehearsal ? null : cutChangelog(readFileSync(join(ROOT, 'CHANGELOG.md'), 'utf8'), version, new Date().toISOString().slice(0, 10)); setVersion(version); - if (!rehearsal) writeFileSync(join(ROOT, 'CHANGELOG.md'), cutChangelog(readFileSync(join(ROOT, 'CHANGELOG.md'), 'utf8'), version, new Date().toISOString().slice(0, 10))); + if (cut) writeFileSync(join(ROOT, 'CHANGELOG.md'), cut); const code = TESTS ? await bg('ci:quick', ['bun', 'run', 'ci:quick'], join(logDir, 'ci-quick.log'), { timeoutMs: 15 * 60_000 }) : 0; if (code !== 0) { // nothing was committed or pushed: put the checkout back as it was From b84538e4cbc5f7e44028d61a9da81d39c4a1261b Mon Sep 17 00:00:00 2001 From: CRT Date: Fri, 16 Oct 2026 06:35:47 +0800 Subject: [PATCH 004/344] storebound 0.8.10: version in package.json and every copy, CHANGELOG 0.8.10 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 15c9829..5fc9ade 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.9", + "version": "0.8.10", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 3a85e34..6857433 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.9", + "version": "0.8.10", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index ae30b5d..75d7f88 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.9", + "version": "0.8.10", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index a057109..22b2166 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.10 · 2026-10-15 + - **Neutral names only.** Docs, pitfalls, tests and comments use example names instead of the projects that reported issues; the history was rewritten the same way. Older npm versions are withdrawn. - **Releases:** a candidate whose build jobs were cancelled by a newer push says so and gives the tag move and diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 92e6d9e..bcae79f 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.9", + "version": "0.8.10", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 65a8b87..87043b5 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4010,7 +4010,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.9" +version = "0.8.10" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index ae6fb03..6a1c818 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.9" +version = "0.8.10" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 06d5c3a..05b3f58 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.9", + "version": "0.8.10", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index 028f947..0d59cd7 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.9", + "version": "0.8.10", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index bb80e79..57cb296 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.9", + "version": "0.8.10", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From 9059b2b32afe661b126c1950bb76e90696a6172f Mon Sep 17 00:00:00 2001 From: CRT Date: Fri, 16 Oct 2026 07:17:19 +0800 Subject: [PATCH 005/344] background tests: ci.yml runs the CI and the acceptance matrix on every push again but nothing waits for them (the gate no longer waits for the parent's run, which a release's own bump push cancels; the record job needs only the installers); tools/ci-status.ts reports main's newest test run and release.ts prints a red one as a warning --- .forgejo/workflows/ci.yml | 16 +++++++-------- tests/ci-status.test.ts | 12 +++++++++++ tools/ci-status.ts | 41 ++++++++++++++++++++++++++++++++++++++ tools/release-candidate.ts | 4 ++-- tools/release.ts | 6 ++++++ 5 files changed, 69 insertions(+), 10 deletions(-) create mode 100644 tests/ci-status.test.ts create mode 100644 tools/ci-status.ts diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml index ddf4ff2..09f0171 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -50,15 +50,15 @@ jobs: EVENT: ${{ github.event_name }} SHA: ${{ github.sha }} run: | - if [ "$EVENT" = pull_request ]; then echo "reuse=false" >> "$GITHUB_OUTPUT"; echo "pull request: everything runs"; exit 0; fi - curl -fsSL https://bun.sh/install | bash -s "bun-v${BUN_VERSION}" >/dev/null - export PATH="$HOME/.bun/bin:$PATH" - bun tools/release-candidate.ts gate --sha "$SHA" --wait 40 + # tests never gate a release (the owner's decision 2026-10-16): no waiting on the parent's run, which the + # release's own bump push cancels; every commit builds its installers and runs the tests in the background + echo "reuse=false" >> "$GITHUB_OUTPUT"; echo "from=" >> "$GITHUB_OUTPUT"; echo "tests run in the background; installers build for this commit" - # off by the owner's decision (2026-10-15: no CI, no acceptance runs); the jobs stay for a manual comeback + # background tests (the owner's decision 2026-10-16): they run on every push and report, but the record job (the + # release candidate) never waits for them; `bun tools/release.ts` and `bun tools/ci-status.ts` print a red result ci: needs: gate - if: false + if: github.event_name != 'pull_request' || true # runner label: ubuntu-22.04:docker://ghcr.io/catthehacker/ubuntu:act-22.04 runs-on: ubuntu-22.04 timeout-minutes: 60 @@ -78,7 +78,7 @@ jobs: # (tools/release.ts, cached per CLI key). acceptance: needs: gate - if: false + if: github.event_name != 'pull_request' || true strategy: fail-fast: false matrix: @@ -288,7 +288,7 @@ jobs: retention-days: 7 record: - needs: [gate, ci, acceptance, linux, windows] + needs: [gate, linux, windows] if: ${{ always() && github.event_name != 'pull_request' && needs.gate.result == 'success' && needs.linux.result == 'success' && needs.windows.result == 'success' }} runs-on: ubuntu-22.04 timeout-minutes: 30 diff --git a/tests/ci-status.test.ts b/tests/ci-status.test.ts new file mode 100644 index 0000000..4810e42 --- /dev/null +++ b/tests/ci-status.test.ts @@ -0,0 +1,12 @@ +import { expect, test } from 'bun:test'; +import { testState } from '../tools/ci-status'; + +const t = (name: string, status: string, run: number, sha: string) => ({ id: 1, name, run_number: run, workflow_id: 'ci.yml', head_sha: sha, status }); +const url = (n: number) => `run/${n}`; + +test('background test state: newest commit with test jobs; a cancelled run falls back to the older commit', () => { + expect(testState([t('ci', 'success', 2, 'b'), t('acceptance (bun)', 'failure', 2, 'b'), t('linux', 'success', 2, 'b')], ['b'], url)).toEqual({ sha: 'b', run: 'run/2', state: 'red', failed: ['acceptance (bun)'], running: [] }); + expect(testState([t('ci', 'cancelled', 3, 'c'), t('ci', 'success', 2, 'b')], ['c', 'b'], url).state).toBe('green'); + expect(testState([t('ci', 'running', 3, 'c')], ['c'], url)).toMatchObject({ state: 'running', running: ['ci'] }); + expect(testState([t('linux', 'success', 3, 'c')], ['c'], url).state).toBe('none'); +}); diff --git a/tools/ci-status.ts b/tools/ci-status.ts new file mode 100644 index 0000000..a287720 --- /dev/null +++ b/tools/ci-status.ts @@ -0,0 +1,41 @@ +#!/usr/bin/env bun +// The background tests of main (ci.yml's ci and acceptance jobs): they never gate a release (the owner's decision, +// 2026-10-16), so this reports them. Check it at the start of a session and fix a red result in the next patch. +// bun tools/ci-status.ts the newest main run that has test jobs: green, red (which jobs) or running +// bun tools/ci-status.ts --json +import { spawnSync } from 'node:child_process'; +import { runUrl, tasks, type Task } from './release-candidate'; + +const TEST = /^(ci|acceptance\b)/; + +export interface TestState { sha: string; run: string; state: 'green' | 'red' | 'running' | 'none'; failed: string[]; running: string[] } + +/** The state of the newest run (of the given commits, newest first) that has test jobs. Pure. */ +export function testState(all: Task[], shas: string[], url: (n: number) => string): TestState { + for (const sha of shas) { + const mine = all.filter(t => t.head_sha === sha && t.workflow_id === 'ci.yml' && TEST.test(t.name)); + if (!mine.length) continue; + const latest = Math.max(...mine.map(t => t.run_number)); + const jobs = mine.filter(t => t.run_number === latest); + // a run cancelled by a newer push proves nothing: look at the older commit + if (jobs.every(t => t.status === 'cancelled')) continue; + const failed = jobs.filter(t => t.status === 'failure').map(t => t.name); + const running = jobs.filter(t => !['success', 'skipped', 'failure', 'cancelled'].includes(t.status)).map(t => t.name); + return { sha, run: url(latest), state: failed.length ? 'red' : running.length ? 'running' : 'green', failed, running }; + } + return { sha: shas[0] ?? '', run: '', state: 'none', failed: [], running: [] }; +} + +export async function mainTests(): Promise { + spawnSync('git', ['fetch', '-q', 'origin', 'main']); + const shas = (spawnSync('git', ['log', '-20', '--format=%H', 'origin/main'], { encoding: 'utf8' }).stdout ?? '').split('\n').filter(Boolean); + return testState(await tasks(), shas, runUrl); +} + +if (import.meta.main) { + const s = await mainTests(); + if (process.argv.includes('--json')) console.log(JSON.stringify(s, null, 2)); + else console.log(s.state === 'none' ? 'no test run on the last 20 commits of main' + : `${s.state}: ${s.sha.slice(0, 10)} ${s.run}${s.failed.length ? ` (failed: ${s.failed.join(', ')})` : ''}${s.running.length ? ` (running: ${s.running.join(', ')})` : ''}`); + process.exit(s.state === 'red' ? 1 : 0); +} diff --git a/tools/release-candidate.ts b/tools/release-candidate.ts index a1cdea8..414c181 100644 --- a/tools/release-candidate.ts +++ b/tools/release-candidate.ts @@ -117,7 +117,7 @@ function fail(msg: string): never { console.error(`release-candidate: ${msg}`); const t0 = Date.now(); const say = (m: string) => console.log(`[${String(Math.round((Date.now() - t0) / 1000)).padStart(4)}s] ${m}`); const sha256 = (f: string) => createHash('sha256').update(readFileSync(f)).digest('hex'); -const runUrl = (n: number) => `${BASE}/${REPO}/actions/runs/${n}`; +export const runUrl = (n: number) => `${BASE}/${REPO}/actions/runs/${n}`; function git(args: string[], allowFail = false): string { const r = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8', maxBuffer: 64 << 20 }); @@ -135,7 +135,7 @@ export function changesBetween(base: string, head: string): Change[] { }); } -async function tasks(): Promise { +export async function tasks(): Promise { const all: Task[] = []; for (let page = 1; page <= 3; page++) { const r = await api<{ workflow_runs?: Task[] }>('GET', `/actions/tasks?limit=50&page=${page}`); diff --git a/tools/release.ts b/tools/release.ts index 2e82dbf..de981a5 100644 --- a/tools/release.ts +++ b/tools/release.ts @@ -275,6 +275,12 @@ async function main(): Promise { push ${branch}, push ${tag}; then in parallel: Mac build + notarize -> ${out.replace(HOME, '~')}; macOS acceptance (${accCached ? 'cached' : 'runs now'}, key ${key.slice(0, 12)}); Forgejo ci (candidate of the bump commit) + release.yml (promotion); add, verify, publish to ${rehearsal ? 'the rehearsal channel' : 'stable'} via ${host}; ${rehearsal ? 'app copied to a scratch folder; then the tag, release, candidates, branch and storebound.dev files of the rehearsal are deleted' : 'update /Applications/storebound.app; print npm publish + npm deprecate'}`); + // background tests never gate a release; a red result is printed so the next patch fixes it + try { + const { mainTests } = await import('./ci-status'); + const t = await mainTests(); + if (t.state === 'red') say(`WARNING: background tests are red on ${t.sha.slice(0, 10)} (${t.failed.join(', ')}): ${t.run}; releasing anyway, fix it in the next patch`); + } catch (e) { say(`background tests: not read (${(e as Error).message.slice(0, 120)})`); } // the dry run catches what the bump would refuse if (!rehearsal && !resume) { try { cutChangelog(readFileSync(join(ROOT, 'CHANGELOG.md'), 'utf8'), version, '2000-01-01'); } catch (e) { fail((e as Error).message); } } if (!yes) { console.log('\ndry run: nothing changed (--yes to release)'); return; } From d6070cc18578c34683d3fd547de00d8dd5210668 Mon Sep 17 00:00:00 2001 From: CRT Date: Fri, 16 Oct 2026 07:48:55 +0800 Subject: [PATCH 006/344] release: when the published version is still missing from the registry after 2 minutes, publish once more (0.8.10's publish answered 0 and left nothing) --- tools/release.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tools/release.ts b/tools/release.ts index de981a5..f32af01 100644 --- a/tools/release.ts +++ b/tools/release.ts @@ -425,7 +425,19 @@ async function npmRelease(version: string, token: string): Promise { // the registry lags a little after a publish; wait (timeout, heartbeat) until it serves the version as latest const end = Date.now() + 5 * 60_000; let last = 0; + let again = false; for (;;) { + // a publish that answered 0 once left no version on the registry (0.8.10): publish once more when the version is + // still missing after 2 minutes (a second publish of a version that landed answers "cannot publish over") + if (!again && Date.now() > end - 3 * 60_000) { + const v = spawnSync('npm', ['view', `storebound@${version}`, 'version'], { encoding: 'utf8', timeout: 30_000 }); + if (!(v.stdout ?? '').trim()) { + again = true; + say(`npm: ${version} is not on the registry yet: publishing once more`); + const p2 = npmRun(['publish'], token); + if (p2.code !== 0 && !/previously published|cannot publish over/i.test(p2.out)) fail(`npm publish (second try) failed: ${p2.out.trim().split('\n').slice(-4).join(' ')}`); + } + } const r = spawnSync('npm', ['view', 'storebound', 'dist-tags.latest'], { encoding: 'utf8', timeout: 30_000 }); if ((r.stdout ?? '').trim() === version) break; if (Date.now() > end) fail(`npm: ${version} published but the registry still serves ${(r.stdout ?? '').trim()} as latest after 5 min`); From 824758179bd190590cce2375e201b10c366a7032 Mon Sep 17 00:00:00 2001 From: CRT Date: Sat, 17 Oct 2026 12:50:06 +0800 Subject: [PATCH 007/344] review access: guest-play apps rejected by Play as a login wall (empty name field, disabled Continue, a code link on the first screen): check warns for a Play app with a first-run gate or IAP and no reviewAccess.instructions; with guest steps the play-sign-in-details plan declares one entry without credentials, the dialog's required full-access box as the owner's step; store-pitfalls 73 --- CHANGELOG.md | 5 ++ cli/check.ts | 10 +++- cli/lib/console-plan.ts | 4 +- cli/lib/console-play-plans.ts | 47 ++++++++++++--- cli/lib/profile.ts | 13 +++- cli/lib/scan/rules.ts | 3 + docs/pitfalls.md | 1 + skills/review-access/SKILL.md | 5 ++ skills/store-pitfalls/SKILL.md | 25 ++++++++ tests/console-play-plans.test.ts | 4 +- tests/guest-login-wall.test.ts | 100 +++++++++++++++++++++++++++++++ 11 files changed, 202 insertions(+), 15 deletions(-) create mode 100644 tests/guest-login-wall.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 22b2166..0b29f45 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- **Guest-play apps rejected as a login wall (Play).** `reviewAccess.instructions` with `signInRequired: false` holds + guest steps: `storebound check` warns when a Play app has a first-run gate (name entry, code / transfer entry) or + in-app purchases and no steps, and the `play-sign-in-details` plan then declares one entry without credentials, + the dialog's required full-access box as the owner's step (store-pitfalls 73). + ## 0.8.10 · 2026-10-15 - **Neutral names only.** Docs, pitfalls, tests and comments use example names instead of the projects that reported diff --git a/cli/check.ts b/cli/check.ts index 1cc8934..4039912 100644 --- a/cli/check.ts +++ b/cli/check.ts @@ -23,7 +23,8 @@ import { dataSafetyIssues, dataSafetyRows } from './lib/data-safety'; import { credentialStatus, reviewDemoAccount } from './lib/credentials'; import { log, printJson, warn } from './lib/log'; import { profileIssues } from './lib/profile'; -import { detectProject } from './lib/scan/project'; +import { detectProject, grepOwn, where } from './lib/scan/project'; +import { SIGNALS } from './lib/scan/rules'; import { reviewShotProblem } from './apple/iap-review'; import { allSubscriptions } from './lib/subscriptions'; import { type CopyFile, validateCopy } from './shots/lib'; @@ -205,7 +206,12 @@ export async function run(ctx: Ctx): Promise { if (file) for (const i of versionSourceIssues(file)) note(`play: ${versionSourceMessage(i, relative(ctx.loaded.root, file), t.framework)}`); } catch { /* no Gradle project here (yet): play build says so */ } } - for (const i of profileIssues(config,{ demoAccount: !!reviewDemoAccount(ctx.loaded.root) })) { + // first-run gate (name / code entry) in a Play app without reviewer steps: read from the code only when it matters + let firstRunGate: string[] = []; + if (config.play && !config.reviewAccess?.signInRequired && !config.reviewAccess?.instructions?.trim()) { + try { const f = facts ?? detectProject(ctx.loaded.root); firstRunGate = grepOwn(f, SIGNALS.firstRunGate, 3).hits.map(where); } catch { /* no project sources here */ } + } + for (const i of profileIssues(config, { demoAccount: !!reviewDemoAccount(ctx.loaded.root), firstRunGate })) { if (i.level === 'error') problems.push(i.msg); else warn('check', i.msg); } // Play steps without an API: the App category (Store settings) and the App content answers the owner still owes diff --git a/cli/lib/console-plan.ts b/cli/lib/console-plan.ts index 84eb872..3afc200 100644 --- a/cli/lib/console-plan.ts +++ b/cli/lib/console-plan.ts @@ -9,7 +9,7 @@ import { consoleLink, consoleUrl } from './console-links'; import { playCategoryOf, type ShipConfig } from './config'; import type { ProjectSignals } from './project-signals'; import { type Answer, type AnswerValue, consoleAnswers, type FormId, formMeta, isPlanOnly, type PlanFormId, type Store, valueText } from './console-answers'; -import { APP_CONTENT_CAPTURE, APP_CONTENT_CARDS, appContentStart, PLAY_MATERIAL_FACT, playAppPage, playOnlyPart, SEND_FOR_REVIEW, SEND_FOR_REVIEW_WHERE, startLabel } from './console-play-plans'; +import { APP_CONTENT_CAPTURE, APP_CONTENT_CARDS, appContentStart, PLAY_FULL_ACCESS_BOX, PLAY_MATERIAL_FACT, playAppPage, playOnlyPart, SEND_FOR_REVIEW, SEND_FOR_REVIEW_WHERE, startLabel } from './console-play-plans'; import { FORM_BUTTONS, formDef, type Name, NEVER_PRESS, PLAY_NEVER_PRESS, playAppList, playCreateApp, setUpTexts, typeLabels } from './console-forms'; import { PLAY_CREATE_CAPTURE } from './console-verify'; import { APPLE_PURPOSES } from './console-answers'; @@ -445,6 +445,8 @@ function ownerBatchOf(form: PlanFormId, cfg: ShipConfig, p: PlanIds, answers: Pl const open = answers.filter(a => (a.status === 'ask-owner' || a.status === 'owner-check') && !a.id.endsWith('credentials')); if (open.length) out.push({ when: 'before', kind: 'answers', text: `Answer ${open.length} question(s) in ONE batch (askOwner), then write the answers into storebound.config.ts and rerun the plan: ${open.map(a => a.question).join('; ')}` }); if (answers.some(a => a.status === 'ask-owner' && a.id.endsWith('credentials'))) out.push({ when: 'before', kind: 'credentials', text: 'Put the App Review demo account into .storebound/credentials.json (reviewDemoAccount: username, password) so the agent types it without printing it; or type the username and password into the Sign in details card yourself', where: `${consoleLink('play.app-access', '> Add instructions')}` }); + if (answers.some(a => a.status === 'agreement' && /fullAccess$/.test(a.id))) + out.push({ when: 'after', kind: 'agreement', text: `When the agent stops in the Sign in details "Add instructions" dialog: tick the required box "${PLAY_FULL_ACCESS_BOX}" (the agent then presses Add and Save)`, where: `${consoleLink('play.app-access', '> Add instructions')}` }); const iarc = answers.some(a => a.status === 'agreement' && /iarcTerms$/.test(a.id)); if (iarc) out.push({ when: 'before', kind: 'agreement', text: IARC_TERMS, where: iarcWhere(cfg, p) }); if (form === 'play-app-record') { diff --git a/cli/lib/console-play-plans.ts b/cli/lib/console-play-plans.ts index b851e61..9490373 100644 --- a/cli/lib/console-play-plans.ts +++ b/cli/lib/console-play-plans.ts @@ -209,13 +209,34 @@ function adsDeclaration(config: ShipConfig, p: PlanIds): Part { }; } +/** Play's Add instructions dialog: "Any other information required to access your app" holds at most 500 characters. */ +export const PLAY_ACCESS_INFO_MAX = 500; +/** The name of the one entry a guest-play app declares (no account, no credentials). */ +export const GUEST_ENTRY_NAME = 'Guest play (no account needed)'; +/** The Add instructions dialog's required box: an agreement, ticked by the owner only. */ +export const PLAY_FULL_ACCESS_BOX = 'Sign in details in this declaration provide full access to all the features and content within this app, including premium or paid content'; + function signInDetails(config: ShipConfig, p: PlanIds): Part { const ra = config.reviewAccess; const all = 'All functionality in my app is available without any access restrictions', some = 'All or some functionality in my app is restricted'; - const out: PlanAnswer[] = [ra ? ans('access', 'Is any functionality restricted (sign-in, membership, location)?', ra.signInRequired, 'certain', 'reviewAccess.signInRequired', { control: 'radio', action: 'pick', label: ra.signInRequired ? some : all, where: 'Sign in details (App access)' }) - : ans('access', 'Is any functionality restricted (sign-in, membership, location)?', null, 'ask-owner', 'reviewAccess.signInRequired', { control: 'radio', where: 'Sign in details', note: 'Set reviewAccess { signInRequired } (review-access skill).' })]; - if (ra?.signInRequired) { - out.push(ra.instructions ? ans('instructions', 'Instructions for the reviewer', ra.instructions, 'certain', 'reviewAccess.instructions', { control: 'text', action: 'type', label: 'Any other information required to access your app', where: 'Add instructions' }) + const info = 'Any other information required to access your app'; + // a guest-play app with reviewer steps (signInRequired false + instructions): Play rejected such a game as a login + // wall ("provide valid login credentials") while it was declared unrestricted, so it is declared restricted with + // one entry that has no credentials and says how to get in as a guest + const guest = !!ra && !ra.signInRequired && !!ra.instructions?.trim(); + const restricted = !!ra && (ra.signInRequired || guest); + const q = 'Is any functionality restricted (sign-in, membership, location)?'; + const out: PlanAnswer[] = [ra ? ans('access', q, restricted, 'certain', guest ? 'reviewAccess.instructions (guest steps, no sign-in)' : 'reviewAccess.signInRequired', { control: 'radio', action: 'pick', label: restricted ? some : all, where: 'Sign in details (App access)', + ...(guest ? { note: 'No sign-in, but guest steps: answered restricted so the reviewer reads them (Play rejected a guest-play game declared unrestricted as a login wall).' } : {}) }) + : ans('access', q, null, 'ask-owner', 'reviewAccess.signInRequired', { control: 'radio', where: 'Sign in details', note: 'Set reviewAccess { signInRequired } (review-access skill).' })]; + const long = (t: string) => t.length > PLAY_ACCESS_INFO_MAX ? { note: `${t.length} characters: Play takes at most ${PLAY_ACCESS_INFO_MAX}; shorten reviewAccess.instructions.` } : {}; + if (guest) { + const steps = ra!.instructions!.trim(); + out.push(ans('entryName', 'Name of the instructions entry', GUEST_ENTRY_NAME, 'certain', 'reviewAccess.signInRequired false', { control: 'text', action: 'type', label: GUEST_ENTRY_NAME, where: 'Add instructions: Name' })); + out.push(ans('credentials', 'Username and password', null, 'certain', 'reviewAccess.signInRequired false', { control: 'text', where: 'Add instructions: Username, Password', text: 'leave both empty (no account)', note: 'Guest play: no credentials exist; type nothing into Username or Password.' })); + out.push(ans('instructions', 'Instructions for the reviewer', steps, steps.length > PLAY_ACCESS_INFO_MAX ? 'owner-check' : 'certain', 'reviewAccess.instructions', { control: 'text', action: 'type', label: info, where: 'Add instructions: Any other information', ...long(steps) })); + } else if (ra?.signInRequired) { + out.push(ra.instructions ? ans('instructions', 'Instructions for the reviewer', ra.instructions, 'certain', 'reviewAccess.instructions', { control: 'text', action: 'type', label: info, where: 'Add instructions', ...long(ra.instructions) }) : ans('instructions', 'Instructions for the reviewer', null, 'ask-owner', 'reviewAccess.instructions', { note: 'Set reviewAccess.instructions (how to sign in and reach the main features).' })); // with reviewDemoAccount in .storebound/credentials.json the agent types it (never printed: not in chat, logs, the // plan or a commit); without it the owner types the username and password (or adds it there first) @@ -228,22 +249,30 @@ function signInDetails(config: ShipConfig, p: PlanIds): Part { control: 'text', where: 'Add instructions: Username, Password', note: `reviewDemoAccount: ${p.demoAccount === undefined ? 'not checked' : 'MISSING'}. The owner adds it to .storebound/credentials.json before the run (then the agent types it, never printed), or types the username and password into the card themselves. storebound never prints them.` })); } + // the dialog's required declaration box: an agreement, so the owner ticks it (agents never tick declarations) + if (restricted) out.push(ans('fullAccess', 'Do these sign in details give full access to every feature and content, including premium or paid content?', null, 'agreement', 'Play Add instructions dialog (required)', { control: 'checkbox', label: PLAY_FULL_ACCESS_BOX, where: 'Add instructions dialog, required box' })); + const add = 'Add instructions'; return { title: 'Play Console: Sign in details (App access)', start: start(config, p, 'app-content/testing-credentials', appContentReach('Sign in details')), steps: steps([ { text: `Open App content > Sign in details: ${start(config, p, 'app-content/testing-credentials', []).url}` }, { text: 'Pick whether any functionality is restricted (material radio: JS click on the inner [role=radio]).', answers: ['access'] }, + guest && { text: `Guest steps (no sign-in): press "${add}", type the Name "${GUEST_ENTRY_NAME}", leave Username and Password empty, and type reviewAccess.instructions into "${info}" (at most ${PLAY_ACCESS_INFO_MAX} characters).`, click: [add], answers: ['entryName', 'credentials', 'instructions'] }, ra?.signInRequired && { text: p.demoAccount - ? 'Restricted: press "Add instructions", type the instructions, then type the Username and Password from .storebound/credentials.json (reviewDemoAccount; click each field and type: never echo them in chat or logs).' - : 'Restricted: press "Add instructions", type the instructions; the Username and Password are the owner\'s (no reviewDemoAccount in .storebound/credentials.json: in the owner batch).', click: ['Add instructions'], answers: ['instructions', 'credentials'] }, + ? `Restricted: press "${add}", type the instructions, then type the Username and Password from .storebound/credentials.json (reviewDemoAccount; click each field and type: never echo them in chat or logs).` + : `Restricted: press "${add}", type the instructions; the Username and Password are the owner's (no reviewDemoAccount in .storebound/credentials.json: in the owner batch).`, click: [add], answers: ['instructions', 'credentials'] }, + restricted && { text: `Leave the required box "${PLAY_FULL_ACCESS_BOX}" unticked and stop: the owner ticks it (a declaration). Then press "Add" (closes the dialog; the entry is listed).`, click: ['Add'], answers: ['fullAccess'] }, { text: DECLARATION_SAVE }, { text: 'Verify: read the page text and pipe it to `storebound console verify play-sign-in-details --from-text -`.' }, ]), answers: out, - ...declarationButtons('Sign in details', [{ button: 'Add instructions', class: 'navigation', where: 'Sign in details: opens the instructions dialog' }]), - uiFacts: ['Verified 2026-10-12: the Sign in details card (App access) is /app-content/testing-credentials.', 'Credentials are never in the config, the plan or chat: the agent types them from .storebound/credentials.json (reviewDemoAccount) without printing them; without that entry the owner types them.', PLAY_MATERIAL_FACT], - verify: pageVerify('play-sign-in-details', ['The selected radio matches reviewAccess.signInRequired; with a sign-in, one set of instructions is listed.']), + ...declarationButtons('Sign in details', [{ button: add, class: 'navigation', where: 'Sign in details: opens the instructions dialog' }, + ...(restricted ? [{ button: 'Add', class: 'navigation', where: 'Add instructions dialog: lists the entry on the card (nothing is stored before Save)' }] : [])]), + uiFacts: ['Verified 2026-10-12: the Sign in details card (App access) is /app-content/testing-credentials.', 'Credentials are never in the config, the plan or chat: the agent types them from .storebound/credentials.json (reviewDemoAccount) without printing them; without that entry the owner types them.', + `The Add instructions dialog: Name, Username, Password, "${info}" (at most ${PLAY_ACCESS_INFO_MAX} characters) and the required box "${PLAY_FULL_ACCESS_BOX}" (the owner's).`, + 'A guest-play game declared "no restrictions" was rejected as a login wall (empty name field, Continue disabled, an "I have a code" link on the first screen): with guest steps the card says restricted with one entry without credentials.', PLAY_MATERIAL_FACT], + verify: pageVerify('play-sign-in-details', [guest ? `Restricted is selected; one entry "${GUEST_ENTRY_NAME}" with no username or password is listed.` : 'The selected radio matches reviewAccess.signInRequired; with a sign-in, one set of instructions is listed.']), guidance: [`Open: Policy and programs > App content > Sign in details (App access): ${start(config, p, 'app-content/testing-credentials', []).url}`], }; } diff --git a/cli/lib/profile.ts b/cli/lib/profile.ts index 154982c..5d6ae24 100644 --- a/cli/lib/profile.ts +++ b/cli/lib/profile.ts @@ -7,7 +7,9 @@ import { allSubscriptions } from './subscriptions'; export interface ProfileIssue { level: 'error' | 'warn'; msg: string } -export function profileIssues(config: ShipConfig, o: { demoAccount: boolean }): ProfileIssue[] { +/** firstRunGate: where the code shows a first-run gate (name entry, code / transfer entry, account transfer UI), from + * scan's SIGNALS.firstRunGate; check fills it for a Play app without reviewer instructions. */ +export function profileIssues(config: ShipConfig, o: { demoAccount: boolean; firstRunGate?: string[] }): ProfileIssue[] { const out: ProfileIssue[] = []; const err = (msg: string) => out.push({ level: 'error', msg }); const warn = (msg: string) => out.push({ level: 'warn', msg }); @@ -29,6 +31,15 @@ export function profileIssues(config: ShipConfig, o: { demoAccount: boolean }): if (!o.demoAccount) err('App Review needs a demo account (sign-in required) · add reviewDemoAccount to .storebound/credentials.json · review-access skill'); if (!config.reviewAccess.instructions) warn('reviewAccess.instructions: tell the reviewer how to sign in and where the main features are'); } else if (accounts && config.reviewAccess === undefined) warn('the app has accounts: set reviewAccess { signInRequired } so App Review and Play App access get a demo account when needed'); + // a guest-play app (no sign-in) rejected by Play as a login wall: an empty name field with Continue disabled and an + // "I have a code" link on the first screen read as a sign-in. Guest steps in reviewAccess.instructions turn Play's + // Sign in details into a "restricted" entry without credentials that tells the reviewer how to get in. + const gate = o.firstRunGate ?? []; + const iap = !!config.products?.length || allSubscriptions(config.subscriptions).length > 0; + if (config.play && !config.reviewAccess?.signInRequired && !config.reviewAccess?.instructions?.trim() && (gate.length || iap)) + warn(`Play may reject as a login wall; add guest steps: ${[gate.length && `first-run gate in the code (${gate.slice(0, 2).join(', ')})`, iap && 'in-app purchases'].filter(Boolean).join(' and ')} with no reviewAccess.instructions. Set reviewAccess.instructions to English steps for a reviewer without an account (e.g. "No account needed: tap Continue, the name is pre-filled; the code link is only for moving progress"); the play-sign-in-details plan then declares a guest entry (store-pitfalls: guest-play apps rejected as a login wall)`); + const steps = config.reviewAccess?.instructions?.trim() ?? ''; + if (config.play && steps.length > 500) warn(`reviewAccess.instructions: ${steps.length} characters; Play's Sign in details "Any other information" takes at most 500`); const subs = allSubscriptions(config.subscriptions); if (subs.length) { if (!config.app.termsUrl) err('subscriptions: set app.termsUrl (Terms of Use / EULA, linked in the app and the metadata; Apple 3.1.2)'); diff --git a/cli/lib/scan/rules.ts b/cli/lib/scan/rules.ts index 75df08a..861722a 100644 --- a/cli/lib/scan/rules.ts +++ b/cli/lib/scan/rules.ts @@ -132,6 +132,9 @@ export const SIGNALS = { // body / schema / type (not a quoted constant or label), an email validation, an email endpoint or an email sign-in // call. Accounts alone never mean email (a username with a device token has none). email: userLine(/type\s*[:=]\s*["'{]*email["'}]|inputMode=["']email["']|keyboardType=["']?email-address|autoComplete=["']email|textContentType=["']?(emailAddress|\.emailAddress)|UITextContentType\.emailAddress|\.keyboardType\(\.emailAddress\)|keyboardType\s*=\s*\.emailAddress|TextInputType\.emailAddress|TYPE_TEXT_VARIATION_EMAIL_ADDRESS|KeyboardType\.Email\b|(?`](Enter (your |a )?(player |nick ?|user ?)?name|Choose (a |your )?(player |nick ?|user ?)?name|Pick (a |your )?(player |nick ?)?name|What'?s your name|I have a code|Enter (a |your )?(transfer|recovery|restore) code|(Transfer|Recovery|Restore) code|Transfer (your )?(account|progress|save)|Restore (your )?progress)|\b(transferCode|recoveryCode|restoreCode|accountTransfer|transferAccount|TransferCode|RecoveryCode)\b/i), deleteAccount: codeLine(/deleteUser\b|\buser\.delete\(|currentUser\??\.delete\(|\bdeleteAccount\b|delete_account|DeleteAccount|delete-account|["'>]Delete (my |your )?account|\brevokeToken\b|auth\.admin\.deleteUser|Hesab(ı|ımı) sil/i), restore: /restoreCompletedTransactions|AppStore\.sync\(|restorePurchases|restoreTransactions|RestoreTransactions|getAvailablePurchases|\brestorePurchase\b|\.restore\(\)|Restore Purchases|syncPurchases|Purchases\.shared\.restore|store\.restore\b|queryPurchasesAsync/i, subscriptionCode: /subscriptionPeriod|Product\.SubscriptionInfo|\.autoRenewable\b|entitlements\.active|SubscriptionStoreView|ProductType\.Subscription|ProductType\.SUBS|BillingClient\.ProductType\.SUBS/, diff --git a/docs/pitfalls.md b/docs/pitfalls.md index 44a6d2c..638eba3 100644 --- a/docs/pitfalls.md +++ b/docs/pitfalls.md @@ -9,6 +9,7 @@ fails without the fix. | # | date | lesson | guard | |---|---|---|---| +| 73 | 2026-10 | A game with guest play (no sign-in; `reviewAccess.signInRequired: false`, Play Sign in details "No restrictions") was rejected by Play: "Play Console Requirements: provide valid login credentials". The first screen had an empty player-name field with Continue disabled until a name was typed and an "I Have a Code" link to a transfer / recovery code dialog; the reviewer read it as a login wall. | `profileIssues` (`cli/lib/profile.ts`, called by `check` with `SIGNALS.firstRunGate` hits from `cli/lib/scan/rules.ts`): warns "Play may reject as a login wall; add guest steps" for a Play app with a first-run gate or IAP and no `reviewAccess.instructions`, and when the steps exceed 500 characters. The `play-sign-in-details` plan (`cli/lib/console-play-plans.ts`): with guest steps "restricted" and one entry "Guest play (no account needed)" without credentials, the steps in "Any other information", the dialog's required full-access box as an owner step; Add and Save the agent's. `tests/guest-login-wall.test.ts`. | | 72 | 2026-10 | A game: after Play production 1.0.0 (3) was rejected (Broken Functionality), the fix 1.0.1 (5) went through upload and track updates, then edits.validate answered 400 "Changes cannot be sent for review automatically. Please set the query parameter changesNotSentForReview to true". Play refuses the automatic send after a rejection, with other pending changes or managed publishing. | `cli/play/client.ts` (edit flow) with `cli/play/review-pending.ts`: on exactly that 400 the same edit is validated and committed again with changesNotSentForReview=true (a dry run validates that way and says so), the Publishing overview deep link is printed (the owner's button), the commit is recorded in .storebound/ and `play status` shows it; `--not-sent-for-review` on play release / upload / rollout / listing / images (MCP `not_sent_for_review`). `tests/play-not-sent-for-review.test.ts`. Only edits.commit takes changesNotSentForReview: validate answers 400 "Unknown name ... Cannot bind query parameter" (the fake store does too). | | 71 | 2026-10 | Messages sent the owner to console pages as plain text paths ("App Store Connect > App Information > Age Rating", "Play Console > App content") without a link; the owner had to find the app and the page by hand. | `cli/lib/console-links.ts`: every message carries the absolute deep link (app list / developer chooser when ids are unknown), `url` in finding JSON, an Open button in the desktop; `tests/console-links.test.ts` fails on a console path in cli/ or templates/ without an https URL; agent rule 11 in AGENTS.md. | | 70 | 2026-10 | A game: the app's first in-app purchase (a starter pack) was not in the 1.0.0 review submission (its items held only the appStoreVersion); it stayed READY_TO_SUBMIT and was noticed after two days in WAITING_FOR_REVIEW. Apple reviews the first product of a type only with an app version; approved without it, it is not sellable. | `firstProductGaps` (`cli/lib/review-submit.ts`, read by `cli/apple/first-products.ts`): WARN in `apple status` (text and --json), `release status` and the desktop checks; blocker in `validate` / `release plan` and the `apple submit` plan; `iap-review` says "ready, not submitted yet". `tests/first-products.test.ts`. | diff --git a/skills/review-access/SKILL.md b/skills/review-access/SKILL.md index 305a89b..7bba606 100644 --- a/skills/review-access/SKILL.md +++ b/skills/review-access/SKILL.md @@ -40,3 +40,8 @@ creates the account and pastes it into that file. storebound prints it masked (` - A password change or an expired trial on the demo account means a rejection: tell the owner to keep it stable. - Region locks, IP allow-lists or SMS checks block reviewers; switch them off for the demo account. - If sign-in is optional (everything works signed out), set `signInRequired: false`; the demo fields are cleared. +- No sign-in but a first screen that can look like one (a name to type before Continue, an "I have a code" link, + in-app purchases): keep `signInRequired: false` and write guest steps into `reviewAccess.instructions` (English, at + most 500 characters). Play's Sign in details then gets one entry "Guest play (no account needed)" without + credentials (`storebound console plan play-sign-in-details`); a guest-play game declared "no restrictions" was + rejected as a login wall (store-pitfalls 73). Pre-fill the name so Continue is enabled at once. diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 423f16f..28a176b 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -852,3 +852,28 @@ that fails without the fix (see CONTRIBUTING.md). - **Guard:** `isReviewRefused` and the edit flow in `cli/play/client.ts` / `cli/play/review-pending.ts` (only that 400; no other request is repeated, the same edit id), `play status` (text and `reviewPending` in --json); `tests/play-not-sent-for-review.test.ts` (fake Play refuses validate / commit once). + +## 73. Guest-play apps rejected as a login wall +- **Symptom:** Play rejects a game that has no sign-in under "Play Console Requirements: provide valid login + credentials". The config said `reviewAccess: { signInRequired: false }` and Sign in details answered "All + functionality in my app is available without any access restrictions". +- **Cause:** the reviewer's screenshot was the first-run screen: an empty required player-name field, the Continue + button disabled until a name is typed, and an "I Have a Code" link that opens a transfer / recovery code dialog. + To a reviewer an empty field plus a disabled button plus a code entry looks like a sign-in, and "no restrictions" + gave them nothing to follow. +- **Do (console):** write English guest steps into `reviewAccess.instructions` (keep `signInRequired: false`; at most + 500 characters), e.g. "No account needed. Open the app, the player name is pre-filled: tap Continue. 'I Have a Code' + is optional (moves progress from another device); skip it." `storebound console plan play-sign-in-details` then + answers "All or some functionality in my app is restricted" with one entry named "Guest play (no account needed)", + Username and Password empty and the steps in "Any other information required to access your app". The agent presses + Add instructions, fills the dialog and stops: the dialog's required box "Sign in details in this declaration provide + full access to all the features and content within this app, including premium or paid content" is a declaration + the owner ticks (agents never tick declarations). Then the agent presses Add and Save; Send changes for review stays + the owner's. App Review gets the same steps in its notes. +- **Do (in the app):** pre-fill a suggested name so Continue is enabled at once, and make the code entry clearly + optional ("Moving from another device? I have a code"), never the first thing a new player must do. +- **Guard:** `storebound check` warns "Play may reject as a login wall; add guest steps" for a Play app with a + first-run gate in the code (name entry, code / transfer entry, account transfer UI: `SIGNALS.firstRunGate`) or + in-app purchases and no `reviewAccess.instructions`, and when the steps are longer than 500 characters + (`cli/lib/profile.ts`). The plan's guest path is in `cli/lib/console-play-plans.ts` (`signInDetails`); + `tests/guest-login-wall.test.ts`. diff --git a/tests/console-play-plans.test.ts b/tests/console-play-plans.test.ts index 9bf7eb0..aab8f04 100644 --- a/tests/console-play-plans.test.ts +++ b/tests/console-play-plans.test.ts @@ -185,11 +185,11 @@ describe('agent-only Play plans: shape, URLs, never-press lists, the owner batch // in .storebound/credentials.json: the agent types it, never printed (no value in the plan) expect(cred).toMatchObject({ status: 'certain', value: null, action: 'type', text: 'from .storebound/credentials.json (never printed)' }); expect(cred.note).toContain('reviewDemoAccount: present'); - expect(p.ownerBatch.map(o => o.kind)).toEqual(['final']); + expect(p.ownerBatch.map(o => o.kind)).toEqual(['agreement', 'final']); // kept out of .storebound: the owner types it (in the owner batch, before the run) const own = consolePlan('play-sign-in-details', { ...base, reviewAccess: { signInRequired: true, instructions: 'Sign in with the demo account.' } } as ShipConfig, { demoAccount: false }); expect(own.answers.find(a => a.id === 'credentials')).toMatchObject({ status: 'ask-owner', value: null }); - expect(own.ownerBatch.map(o => [o.when, o.kind])).toEqual([['before', 'credentials'], ['after', 'final']]); + expect(own.ownerBatch.map(o => [o.when, o.kind])).toEqual([['before', 'credentials'], ['after', 'agreement'], ['after', 'final']]); expect(JSON.stringify(own)).not.toMatch(/password"\s*:/i); expect(consolePlan('play-sign-in-details', base).answers.map(a => a.status)).toEqual(['ask-owner']); }); diff --git a/tests/guest-login-wall.test.ts b/tests/guest-login-wall.test.ts new file mode 100644 index 0000000..8390298 --- /dev/null +++ b/tests/guest-login-wall.test.ts @@ -0,0 +1,100 @@ +// A guest-play game (no sign-in) that Play rejected as a login wall ("provide valid login credentials"): the first +// screen had an empty name field, Continue disabled until a name was typed and an "I have a code" link. The guardrails: +// `storebound check` warns when such an app has no reviewer steps, and the play-sign-in-details plan declares one entry +// without credentials when reviewAccess.instructions holds the guest steps. Pure; every id is a placeholder. +import { describe, expect, test } from 'bun:test'; +import type { ShipConfig } from '../cli/lib/config'; +import { consolePlan } from '../cli/lib/console-plan'; +import { GUEST_ENTRY_NAME, PLAY_ACCESS_INFO_MAX, PLAY_FULL_ACCESS_BOX } from '../cli/lib/console-play-plans'; +import { verifyPlayDeclaration } from '../cli/lib/console-verify'; +import { profileIssues } from '../cli/lib/profile'; +import { SIGNALS } from '../cli/lib/scan/rules'; + +const base = { + app: { name: 'Example Game', profile: 'game', privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', website: 'https://example.com', contactEmail: 'support@example.com' }, + languages: [{ id: 'en', play: 'en-US', apple: 'en-US' }], + play: { packageName: 'com.example.game', developerId: '4444', appId: '9876' }, +} as ShipConfig; +const STEPS = 'No account needed. 1) Open the app. 2) The player name is pre-filled: tap Continue. 3) "I Have a Code" is optional (moves progress from another device); skip it. Every feature works as a guest.'; +const guest = { ...base, reviewAccess: { signInRequired: false, instructions: STEPS } } as ShipConfig; + +describe('check: guest-play apps that Play may read as a login wall', () => { + const msg = 'Play may reject as a login wall; add guest steps'; + const warns = (c: ShipConfig, firstRunGate?: string[]) => profileIssues(c, { demoAccount: false, firstRunGate }).filter(i => i.level === 'warn').map(i => i.msg); + + test('a first-run gate in the code or IAP without instructions warns', () => { + const noSteps = { ...base, reviewAccess: { signInRequired: false } } as ShipConfig; + expect(warns(noSteps, ['src/onboarding.tsx:12']).find(m => m.startsWith(msg))).toContain('src/onboarding.tsx:12'); + const iap = { ...noSteps, products: [{ id: 'com.example.game.coins', type: 'consumable', usd: 0.99, listings: { en: { title: 'Coins', description: 'Coins' } } }] } as ShipConfig; + expect(warns(iap).find(m => m.startsWith(msg))).toContain('in-app purchases'); + // no reviewAccess at all is the same: nothing tells the reviewer how to get in + expect(warns(base, ['src/a.ts:1']).some(m => m.startsWith(msg))).toBe(true); + }); + + test('quiet with guest steps, without a gate, for a sign-in app and without Play', () => { + expect(warns(guest, ['src/onboarding.tsx:12']).some(m => m.startsWith(msg))).toBe(false); + expect(warns({ ...base, reviewAccess: { signInRequired: false } } as ShipConfig, []).some(m => m.startsWith(msg))).toBe(false); + expect(warns({ ...base, reviewAccess: { signInRequired: true, instructions: 'Sign in with the demo account.' } } as ShipConfig, ['src/a.ts:1']).some(m => m.startsWith(msg))).toBe(false); + const { play: _, ...noPlay } = base; + expect(warns({ ...noPlay, apple: { bundleId: 'com.example.game' } } as ShipConfig, ['src/a.ts:1']).some(m => m.startsWith(msg))).toBe(false); + }); + + test('instructions longer than Play\'s 500 characters warn', () => { + expect(warns({ ...base, reviewAccess: { signInRequired: false, instructions: 'x'.repeat(PLAY_ACCESS_INFO_MAX + 1) } } as ShipConfig).join('\n')).toContain('at most 500'); + }); + + test('the first-run gate signal: name entry, code / transfer entry, account transfer UI', () => { + for (const t of [ + '', "label: 'Choose a player name',", 'I Have a Code', "title: 'Enter transfer code'", + 'const transferCode = useState("")', "'Transfer your progress'", 'Recovery code', "button('Restore progress')", + ]) expect({ t, hit: SIGNALS.firstRunGate.test(t) }).toEqual({ t, hit: true }); + for (const t of [ + "import { transferCode } from './transfer';", 'const playerName = save.name;', '// enter your name later', 'const code = 42;', "'Your name is shown on the leaderboard'", + ]) expect({ t, hit: SIGNALS.firstRunGate.test(t) }).toEqual({ t, hit: false }); + }); +}); + +describe('plan play-sign-in-details: guest steps', () => { + test('instructions with no sign-in: restricted, one entry without credentials, the box is the owner\'s', () => { + const p = consolePlan('play-sign-in-details', guest); + expect(p.answers.find(a => a.id === 'access')).toMatchObject({ value: true, status: 'certain', label: 'All or some functionality in my app is restricted' }); + expect(p.answers.find(a => a.id === 'entryName')).toMatchObject({ value: GUEST_ENTRY_NAME, status: 'certain', action: 'type' }); + expect(p.answers.find(a => a.id === 'credentials')).toMatchObject({ value: null, status: 'certain', text: 'leave both empty (no account)' }); + expect(p.answers.find(a => a.id === 'credentials')!.action).toBeUndefined(); + expect(p.answers.find(a => a.id === 'instructions')).toMatchObject({ value: STEPS, status: 'certain', label: 'Any other information required to access your app' }); + expect(p.answers.find(a => a.id === 'fullAccess')).toMatchObject({ status: 'agreement', value: null, control: 'checkbox', label: PLAY_FULL_ACCESS_BOX }); + expect(p.answers.find(a => a.id === 'fullAccess')!.action).toBeUndefined(); + // the agent presses Add instructions, Add and Save; the box and Send changes for review are the owner's + expect(p.buttons.allowed.map(b => b.button)).toEqual(expect.arrayContaining(['Add instructions', 'Add', 'Save'])); + expect(p.buttons.final).toBe('Send changes for review'); + expect(p.buttons.neverPress).toContain('Send changes for review'); + expect(p.ownerBatch.map(o => [o.when, o.kind])).toEqual([['after', 'agreement'], ['after', 'final']]); + expect(p.ownerBatch[0]!.text).toContain(PLAY_FULL_ACCESS_BOX); + expect(p.askOwner.join('\n')).toContain('the owner ticks it'); + const text = p.steps.map(s => s.text).join('\n'); + expect(text).toContain(`"${GUEST_ENTRY_NAME}"`); + expect(text).toContain('leave Username and Password empty'); + expect(text).toMatch(/unticked and stop/); + }); + + test('verify reads the entry name and the steps back, never the box', () => { + const page = `Sign in details\nAll or some functionality in my app is restricted\n${GUEST_ENTRY_NAME}\n${STEPS}`; + const r = verifyPlayDeclaration('play-sign-in-details', guest, page); + expect(r.rows.filter(x => x.status === 'match').map(x => x.item)).toEqual(['Is any functionality restricted (sign-in, membership, location)?', 'Name of the instructions entry', 'Instructions for the reviewer']); + expect(r.rows.some(x => /full access/.test(x.item))).toBe(false); + expect(r.mismatches).toBe(0); + }); + + test('steps over 500 characters are an owner check', () => { + const p = consolePlan('play-sign-in-details', { ...base, reviewAccess: { signInRequired: false, instructions: 'x'.repeat(PLAY_ACCESS_INFO_MAX + 1) } } as ShipConfig); + expect(p.answers.find(a => a.id === 'instructions')).toMatchObject({ status: 'owner-check' }); + }); + + test('no instructions: the "No restrictions" path stays', () => { + const p = consolePlan('play-sign-in-details', { ...base, reviewAccess: { signInRequired: false } } as ShipConfig); + expect(p.answers.map(a => [a.id, a.value])).toEqual([['access', false]]); + expect(p.answers[0]!.label).toBe('All functionality in my app is available without any access restrictions'); + expect(p.buttons.allowed.map(b => b.button)).not.toContain('Add'); + expect(p.ownerBatch.map(o => o.kind)).toEqual(['final']); + }); +}); From 37cda2a39a9bf4bd4cef8814edd8857727a06a43 Mon Sep 17 00:00:00 2001 From: CRT Date: Sat, 17 Oct 2026 14:29:27 +0800 Subject: [PATCH 008/344] storebound 0.8.11: version in package.json and every copy, CHANGELOG 0.8.11 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 5fc9ade..a907655 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.10", + "version": "0.8.11", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 6857433..bfebae0 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.10", + "version": "0.8.11", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 75d7f88..895ed6b 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.10", + "version": "0.8.11", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b29f45..ea83304 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.11 · 2026-10-17 + - **Guest-play apps rejected as a login wall (Play).** `reviewAccess.instructions` with `signInRequired: false` holds guest steps: `storebound check` warns when a Play app has a first-run gate (name entry, code / transfer entry) or in-app purchases and no steps, and the `play-sign-in-details` plan then declares one entry without credentials, diff --git a/apps/desktop/package.json b/apps/desktop/package.json index bcae79f..e80441c 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.10", + "version": "0.8.11", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 87043b5..278a311 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4010,7 +4010,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.10" +version = "0.8.11" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 6a1c818..1087058 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.10" +version = "0.8.11" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 05b3f58..7728afe 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.10", + "version": "0.8.11", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index 0d59cd7..7ce7b1f 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.10", + "version": "0.8.11", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index 57cb296..4aafe9e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.10", + "version": "0.8.11", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From 9ba97b7e2923714ba93b3b5e11b5c554b8184d56 Mon Sep 17 00:00:00 2001 From: CRT Date: Sat, 17 Oct 2026 15:59:44 +0800 Subject: [PATCH 009/344] release: candidate downloads go through Cloudflare first (the direct route to the origin was throttled per connection: one AppImage took 20+ min there, 3 MB/s through Cloudflare), the origin only as a fallback; a heartbeat logs the bytes every 30 s --- tools/forgejo-release.ts | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/tools/forgejo-release.ts b/tools/forgejo-release.ts index 352e376..b6c126f 100644 --- a/tools/forgejo-release.ts +++ b/tools/forgejo-release.ts @@ -162,15 +162,32 @@ export async function api(method: string, path: string, body?: unknown, raw = } } -/** Download one asset (drafts need the token) to a file; through the origin like uploads when it is set. */ +/** Download one asset (drafts need the token) to a file. Through Cloudflare first: its 100 MB limit is on request + * bodies (uploads), and the direct route to the origin was throttled per connection to ~30 KB/s (an 0.8.11 release + * sat 20 minutes on one AppImage while Cloudflare gave 3 MB/s). The origin is the fallback. A heartbeat logs the + * bytes every 30 s; curl's own --max-time bounds each try. */ export async function downloadAsset(url: string, dest: string): Promise { const ip = origin(); const dir = mkdtempSync(join(tmpdir(), 'forgejo-dl-')); try { writeFileSync(join(dir, 'h'), `Authorization: ${auth()}\n`, { mode: 0o600 }); const host = new URL(BASE).host; - const r = spawnSync('curl', ['-sS', '-L', '--fail', '--max-time', '1800', ...(ip ? ['--resolve', `${host}:443:${ip.includes(':') ? `[${ip}]` : ip}`] : []), '-H', `@${join(dir, 'h')}`, '-o', dest, url], { encoding: 'utf8' }); - if (r.status !== 0) fail(`download ${basename(dest)}: curl exit ${r.status}: ${r.stderr.slice(0, 300)}`); + const routes: string[][] = [[], ...(ip ? [['--resolve', `${host}:443:${ip.includes(':') ? `[${ip}]` : ip}`]] : [])]; + let last = ''; + for (const [i, route] of routes.entries()) { + const t0 = Date.now(); + const p = Bun.spawn(['curl', '-sS', '-L', '--fail', '--max-time', '1800', ...route, '-H', `@${join(dir, 'h')}`, '-o', dest, url], { stdout: 'ignore', stderr: 'pipe' }); + const beat = setInterval(() => { + let n = 0; try { n = statSync(dest).size; } catch { /* not started */ } + console.log(` download ${basename(dest)} (${i ? 'origin' : 'cloudflare'}): ${(n / 1e6).toFixed(1)} MB after ${Math.round((Date.now() - t0) / 1000)} s`); + }, 30_000); + const code = await p.exited; + clearInterval(beat); + if (code === 0) return; + last = `curl exit ${code}: ${(await new Response(p.stderr).text()).slice(0, 300)}`; + if (i + 1 < routes.length) console.log(` download ${basename(dest)}: ${last}; trying the origin`); + } + fail(`download ${basename(dest)}: ${last}`); } finally { rmSync(dir, { recursive: true, force: true }); } } From 61cb3338e815df3442f2eec486d67cd2cacfb39e Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 18 Oct 2026 01:26:32 +0800 Subject: [PATCH 010/344] scan: remote config, feature flags and remote paywalls not told to review (App Review 2.3.1, Play Deceptive behavior): remote-features finding for both stores, medium, with deep links, unless the review notes mention them; check prints it as a warning, validate carries it; warn only, the templates get a commented example line; code obfuscators a low note, minify alone nothing; store-pitfalls 74 --- CHANGELOG.md | 8 ++ cli/check.ts | 10 ++- cli/lib/embedded.ts | 6 +- cli/lib/scan/rules.ts | 54 ++++++++++++- cli/lib/scan/sdks.ts | 71 +++++++++++++++- docs/pitfalls.md | 1 + skills/review-rejections/SKILL.md | 3 + skills/store-pitfalls/SKILL.md | 22 +++++ skills/store-subscriptions/SKILL.md | 3 + templates/profiles/app/storebound.config.ts | 2 + .../subscription-app/storebound.config.ts | 2 + templates/storebound.config.ts | 2 + tests/remote-features.test.ts | 80 +++++++++++++++++++ 13 files changed, 258 insertions(+), 6 deletions(-) create mode 100644 tests/remote-features.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index ea83304..128d4c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## Unreleased +- **Remote config and remote paywalls (App Review 2.3.1, Play Deceptive behavior).** `storebound scan` (and + `validate`; `check` as a warning) reports `remote-features` for both stores when the app ships a remote config / + feature flag SDK (Firebase Remote Config, Statsig, LaunchDarkly, GrowthBook, Optimizely, PostHog feature flags, + Unleash, ConfigCat, Amplitude Experiment, Split) or a remote paywall (RevenueCat Paywalls, Superwall, Adapty, + Qonversion, Purchasely, Apphud) and the review notes do not mention it. Warn only: storebound never writes the note; + the config templates carry a commented example line. Code obfuscators are a low note, minify alone nothing + (store-pitfalls 74). + ## 0.8.11 · 2026-10-17 - **Guest-play apps rejected as a login wall (Play).** `reviewAccess.instructions` with `signInRequired: false` holds diff --git a/cli/check.ts b/cli/check.ts index 4039912..3f1e5d4 100644 --- a/cli/check.ts +++ b/cli/check.ts @@ -24,7 +24,7 @@ import { credentialStatus, reviewDemoAccount } from './lib/credentials'; import { log, printJson, warn } from './lib/log'; import { profileIssues } from './lib/profile'; import { detectProject, grepOwn, where } from './lib/scan/project'; -import { SIGNALS } from './lib/scan/rules'; +import { remoteFeatureFindings, SIGNALS } from './lib/scan/rules'; import { reviewShotProblem } from './apple/iap-review'; import { allSubscriptions } from './lib/subscriptions'; import { type CopyFile, validateCopy } from './shots/lib'; @@ -214,6 +214,14 @@ export async function run(ctx: Ctx): Promise { for (const i of profileIssues(config, { demoAccount: !!reviewDemoAccount(ctx.loaded.root), firstRunGate })) { if (i.level === 'error') problems.push(i.msg); else warn('check', i.msg); } + // remote config / feature flags / remote paywalls not told to review (2.3.1, Play Deceptive behavior): a warning only + if (config.apple || config.play) { + try { + const f = facts ?? detectProject(ctx.loaded.root); + for (const r of remoteFeatureFindings(f, config, { apple: !!config.apple, play: !!config.play })) + if (r.severity !== 'low' && !(config.scan?.ignore ?? []).some(i => i.rule === r.rule && (!i.store || i.store === r.store))) note(`${r.store}: ${r.title} (${r.guideline}; ${r.evidence.map(where).join(', ')}). ${r.fix}`); + } catch { /* no project sources here */ } + } // Play steps without an API: the App category (Store settings) and the App content answers the owner still owes const pc = playConsoleReminders(config); for (const w of pc.warnings) note(w); diff --git a/cli/lib/embedded.ts b/cli/lib/embedded.ts index 40b0cff..7ef0ac0 100644 --- a/cli/lib/embedded.ts +++ b/cli/lib/embedded.ts @@ -17,16 +17,16 @@ export const TEMPLATE_TEXT: Record = { "profiles/app/listing.md": "# Example App · Google Play listing copy\n\nSource for `storebound play listing` (title, short + full description) and `storebound play release` (release notes).\nRules the parser follows:\n- every `## ...` section with a `` line is a listing; one section can serve several Play codes\n- under it, `### ...` headings that contain **title** (optional, defaults to `app.name`), **short**, **full** and\n **what's new**, each followed by one fenced block\n- limits (checked before anything is sent): title 30, short 80, full 4000, what's new 500 characters\nOnly claim what the app really does. No prices, no \"best / #1\", no other apps' names.\n\n---\n\n## English (en-US)\n\n\n### Play short description (max 80)\n```\nWhat the app does for people, in one plain line\n```\n\n### Play full description (max 4000)\n```\nFirst paragraph: the job the app does and why it is easier with it, in two or three sentences.\n\nFEATURES\n• Lists and notes that sync across your devices\n• Share a list with family or friends\n• Export your data or delete your account in Settings, any time\n\nFree to use. An account is optional and only needed for sync and sharing.\n```\n\n### What's new (max 500)\n```\nFirst release. Thanks for trying it!\n```\n\n## Türkçe (tr-TR)\n\n\n### Play kısa açıklama · short (max 80)\n```\nUygulamanın insanlar için ne yaptığını anlatan sade bir cümle\n```\n\n### Play tam açıklama · full (max 4000)\n```\nİlk paragraf: uygulamanın gördüğü iş ve onunla neden daha kolay olduğu, iki üç cümlede.\n\nÖZELLİKLER\n• Tüm cihazlarında eşitlenen listeler ve notlar\n• Bir listeyi ailen ya da arkadaşlarınla paylaş\n• Verilerini dışa aktar ya da hesabını Ayarlar'dan istediğin an sil\n\nÜcretsiz. Hesap isteğe bağlıdır; yalnızca eşitleme ve paylaşım için gerekir.\n```\n\n### Yenilikler · what's new (max 500)\n```\nİlk sürüm. Denediğin için teşekkürler!\n```\n", "profiles/app/privacy-policy.html": "\n\n\n\n\nPrivacy Policy · Example Studio\n\n\n\n\n
\n \n\n
\n

Privacy Policy

\n

Example Studio · applies to all our apps · last updated 2026-01-01

\n\n

We collect what an app needs to work for you, never sell personal data and show no ads. This page explains what\n each app collects, why, and what you can do about it.

\n\n

What our apps use

\n
\n \n \n \n \n \n
AppServiceWhat and whyYour choice
Example AppAccount (our servers)Email address, account id and the lists and notes you create: to sign you in and sync your content between your devices.The account is optional; export or delete it in Settings > Account
Example AppAnalytics (e.g. a privacy-friendly analytics SDK)Random install id, screens used, device model, OS version: to improve the app.Settings > Analytics off
Example AppCrash reportingCrash logs and device model: to fix crashes.-
Example AppApp storesPurchases and subscriptions are handled by Google Play / the App Store; we never see payment details.-
\n\n

Deleting your account

\n

In the app: Settings > Account > Delete account. Without the app: example.com/delete-account.\n We delete your account and its content within 30 days; backups roll over within 90 days. A store subscription is\n not cancelled by deleting the account: cancel it in your Google Play or App Store subscriptions.

\n\n

Children

\n

Our apps are not directed at children under 13. We do not knowingly collect personal data from children. If you\n believe a child sent us data, contact us and we will delete it.

\n\n

Retention and your rights

\n

We keep account data while the account exists and analytics data for up to 24 months. You can ask for a copy or\n the deletion of your data by writing to privacy@example.com; we answer\n within 30 days.

\n\n

Security

\n

All network traffic of our apps uses HTTPS; passwords are stored only as salted hashes.

\n\n

Changes

\n

When an app starts collecting something new we update this page and its date first.

\n\n

Contact

\n

Example Studio · privacy@example.com

\n
\n\n
\n

Gizlilik Politikası

\n

Example Studio · tüm uygulamalarımız için geçerlidir · son güncelleme 2026-01-01

\n

Yalnızca uygulamanın sizin için çalışması gereken verileri topluyoruz, kişisel verileri asla satmıyoruz ve reklam\n göstermiyoruz. Yukarıdaki tablo her uygulamanın neyi neden topladığını gösterir.

\n

Hesabınızı silmek

\n

Uygulamada: Ayarlar > Hesap > Hesabı sil. Uygulama olmadan: example.com/delete-account.\n Mağaza aboneliği hesap silinince iptal olmaz; Google Play veya App Store aboneliklerinizden iptal edin.

\n

Haklarınız

\n

Verilerinizin bir kopyasını veya silinmesini privacy@example.com adresine\n yazarak isteyebilirsiniz; 30 gün içinde yanıtlıyoruz.

\n
\n
\n\n\n", "profiles/app/shots-copy.json": "{\n \"en\": {\n \"home\": { \"eyebrow\": \"Example App\", \"title\": [\"Everything in order,\", \"in one calm place\"], \"sub\": \"Lists and notes, synced on all your devices.\" },\n \"detail\": { \"eyebrow\": \"Get it done\", \"title\": [\"See what is left\", \"at a glance\"], \"sub\": \"Tap to tick, swipe to reorder.\" },\n \"share\": { \"eyebrow\": \"Together\", \"title\": [\"Share a list,\", \"plan together\"], \"sub\": \"Invite people by link and edit live.\" },\n \"privacy\": { \"eyebrow\": \"Your data\", \"title\": [\"Private by default,\", \"yours to export\"], \"sub\": \"Export your data or delete your account in Settings.\" }\n },\n \"tr\": {\n \"home\": { \"eyebrow\": \"Example App\", \"title\": [\"Her şey düzenli,\", \"tek sakin bir yerde\"], \"sub\": \"Listeler ve notlar, tüm cihazlarında eşitlenir.\" },\n \"detail\": { \"eyebrow\": \"Bitir\", \"title\": [\"Kalanları\", \"bir bakışta gör\"], \"sub\": \"Dokun işaretle, sürükle sırala.\" },\n \"share\": { \"eyebrow\": \"Birlikte\", \"title\": [\"Listeyi paylaş,\", \"birlikte planla\"], \"sub\": \"Bağlantıyla davet et, canlı düzenleyin.\" },\n \"privacy\": { \"eyebrow\": \"Verilerin\", \"title\": [\"Varsayılan olarak gizli,\", \"dışa aktarması senin\"], \"sub\": \"Verilerini dışa aktar ya da hesabını Ayarlar'dan sil.\" }\n }\n}\n", - "profiles/app/storebound.config.ts": "// storebound config for one app (profile \"app\": a utility / productivity app with an optional account and an\n// analytics SDK, no ads). Every answer below is a starting point: edit it to match your app. Credentials NEVER go\n// here (env vars or .storebound/credentials.json, gitignored). Paths are relative to this file.\n// The type import is optional: it only works when storebound is installed in the project (bun add -d storebound).\nimport type { ShipConfig } from 'storebound';\n\nconst config: ShipConfig = {\n // Every compliance answer below is the TEMPLATE's, not yours. While an area is listed here, check / validate block\n // and nothing sends it to a store. Derive the answers from the code (storebound scan --write; for an app that is\n // already live: storebound onboard --declarations), answer the rest, then remove the area from this list.\n unanswered: ['dataSafety', 'appPrivacy', 'reviewNotes', 'ageRating', 'accounts', 'reviewAccess'],\n\n app: {\n name: 'Example App',\n profile: 'app',\n copyright: '2026 Example Studio',\n privacyPolicyUrl: 'https://example.com/privacy',\n // termsUrl: 'https://example.com/terms', // Terms of Use; required once you sell subscriptions\n supportUrl: 'https://example.com/support',\n marketingUrl: 'https://example.com',\n website: 'https://example.com',\n contactEmail: 'support@example.com',\n },\n\n // Accounts (account-deletion skill). Remove this block if the app has no sign-up / sign-in at all.\n // Apple 5.1.1(v): deletion must start inside the app. Google Play: in the app AND on a public web page.\n accounts: {\n enabled: true,\n deletionUrl: 'https://example.com/delete-account', // public page, no login needed to request deletion\n inApp: 'Settings > Account > Delete account', // goes into the App Review notes\n // How people sign up: 'username' (a name picked in the app, no password, no email), 'username-password',\n // 'email-password', 'email-link', 'phone', 'oauth', 'other'. `storebound scan` proposes the account data and\n // dataSafety.accountCreation from it; only the 'email-*' methods mean an email address.\n signUp: ['email-password'],\n },\n\n // Sign-in for store reviewers (review-access skill). The demo account itself lives ONLY in\n // .storebound/credentials.json (\"reviewDemoAccount\") or REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD.\n reviewAccess: {\n signInRequired: true, // false if every feature works without signing in\n instructions: 'Sign in with the demo account. Sample data is already there; nothing needs a second device.',\n },\n\n // id = your folder / copy key; play = Play language code(s); apple = App Store Connect locale\n languages: [\n { id: 'en', play: 'en-US', apple: 'en-US' },\n { id: 'tr', play: 'tr-TR', apple: 'tr' },\n ],\n\n play: {\n packageName: 'com.example.app',\n defaultLanguage: 'en-US',\n listing: 'store/listing.md',\n icon: 'store/icons/play-512.png',\n },\n\n apple: {\n bundleId: 'com.example.app',\n // name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there (\"already being used\"); default app.name\n listing: 'store/appstore.md',\n // Export compliance (export-compliance skill): decide it, then uncomment. false ONLY if the app uses no encryption\n // beyond the OS (HTTPS through the system, standard sign-in).\n // usesNonExemptEncryption: false,\n // ipad: true,\n info: {\n categories: { primary: 'PRODUCTIVITY', secondary: 'UTILITIES' },\n ageRating: {}, // every content question NONE / false; change what applies (user-generated content, web access ...)\n contentRights: 'DOES_NOT_USE_THIRD_PARTY_CONTENT',\n free: true,\n reviewNotes: [\n 'Example App keeps lists and notes in sync across devices. An account is optional on the first screen.',\n 'Privacy policy and Terms: Settings > About.',\n ].join('\\n\\n'),\n },\n },\n\n // In-app purchases (optional): a one-time \"Pro\" unlock, for example. Subscriptions: see the subscription-app profile\n // (storebound init --profile subscription-app) or the store-subscriptions skill.\n // products: [{ id: 'com.example.app.pro', type: 'non_consumable', usd: 4.99,\n // listings: { en: { title: 'Pro', description: 'Unlimited lists and themes.' } }, reviewScreenshot: 'store/iap-review/pro.png' }],\n\n // Google Play Data safety. Types not listed = not collected. Typical app with accounts + an analytics SDK acting as\n // your processor (collected, not shared). Edit to match what your app and its SDKs really do.\n dataSafety: {\n collectsData: true,\n encryptedInTransit: true,\n // Sign-up methods. Google does not publish these ids: compare with Play Console > App content > Data safety >\n // Export to CSV before the first import. The delete-account URL (PSL_ACCOUNT_DELETION_URL) comes from\n // accounts.deletionUrl; `storebound check` names any other row Play requires.\n accountCreation: ['PSL_ACM_USER_ID_PASSWORD'],\n // Can people delete their data without deleting the account (a data-only page)? true needs partialDeletionUrl.\n // Play's \"can users request deletion?\" is answered yes by accounts.deletionUrl. Ask the owner.\n partialDeletion: false,\n data: {\n PSL_EMAIL: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_ACCOUNT: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_GENERATED_CONTENT: { shared: false, collect: ['functionality'] },\n PSL_USER_INTERACTION: { shared: false, collect: ['analytics'] },\n PSL_CRASH_LOGS: { shared: false, collect: ['analytics'] },\n PSL_PERFORMANCE_DIAGNOSTICS: { shared: false, collect: ['analytics'] },\n PSL_DEVICE_ID: { shared: false, collect: ['analytics'] },\n },\n },\n\n renders: 'store/renders',\n\n shots: {\n style: 'app', // calm gradient, device frame, headline + subline (game: sparkles and badges)\n copy: 'store/shots/copy.json',\n frames: 'store/shots/frames', // /phone/.png, /tablet/.png\n out: 'store/renders',\n // fonts: { title: 'Inter', body: 'Inter' }, // the app style default\n scenes: [\n { id: 'home', palette: 'mist', frames: [{ src: 'home.png' }] },\n { id: 'detail', palette: 'mint', frames: [{ src: 'detail.png' }] },\n { id: 'share', palette: 'sky', frames: [{ src: 'share.png' }] },\n { id: 'privacy', palette: 'slate', frames: [{ src: 'settings.png' }] },\n ],\n feature: { frame: 'home.png', palette: 'mist' },\n // Raw frames from a web build, the iOS Simulator (ios-sim) or an Android emulator (android-emu): sign in to a demo\n // account with realistic sample data, never real user data (store-screenshots skill).\n capture: {\n baseUrl: 'http://127.0.0.1:5173',\n query: 'lang={lang}&demo=1',\n shots: {\n 'home': { path: '/', delayMs: 1000, device: 'both' },\n 'detail': { path: '/lists/1', delayMs: 1000, device: 'both' },\n 'share': { path: '/lists/1/share', delayMs: 1000, device: 'both' },\n 'settings': { path: '/settings', delayMs: 1000, device: 'both' },\n },\n },\n },\n\n icons: {\n composite: 'store/icon/icon.png',\n foreground: 'store/icon/foreground.png',\n background: 'store/icon/background.png',\n out: 'store/icons',\n },\n};\n\nexport default config;\n", + "profiles/app/storebound.config.ts": "// storebound config for one app (profile \"app\": a utility / productivity app with an optional account and an\n// analytics SDK, no ads). Every answer below is a starting point: edit it to match your app. Credentials NEVER go\n// here (env vars or .storebound/credentials.json, gitignored). Paths are relative to this file.\n// The type import is optional: it only works when storebound is installed in the project (bun add -d storebound).\nimport type { ShipConfig } from 'storebound';\n\nconst config: ShipConfig = {\n // Every compliance answer below is the TEMPLATE's, not yours. While an area is listed here, check / validate block\n // and nothing sends it to a store. Derive the answers from the code (storebound scan --write; for an app that is\n // already live: storebound onboard --declarations), answer the rest, then remove the area from this list.\n unanswered: ['dataSafety', 'appPrivacy', 'reviewNotes', 'ageRating', 'accounts', 'reviewAccess'],\n\n app: {\n name: 'Example App',\n profile: 'app',\n copyright: '2026 Example Studio',\n privacyPolicyUrl: 'https://example.com/privacy',\n // termsUrl: 'https://example.com/terms', // Terms of Use; required once you sell subscriptions\n supportUrl: 'https://example.com/support',\n marketingUrl: 'https://example.com',\n website: 'https://example.com',\n contactEmail: 'support@example.com',\n },\n\n // Accounts (account-deletion skill). Remove this block if the app has no sign-up / sign-in at all.\n // Apple 5.1.1(v): deletion must start inside the app. Google Play: in the app AND on a public web page.\n accounts: {\n enabled: true,\n deletionUrl: 'https://example.com/delete-account', // public page, no login needed to request deletion\n inApp: 'Settings > Account > Delete account', // goes into the App Review notes\n // How people sign up: 'username' (a name picked in the app, no password, no email), 'username-password',\n // 'email-password', 'email-link', 'phone', 'oauth', 'other'. `storebound scan` proposes the account data and\n // dataSafety.accountCreation from it; only the 'email-*' methods mean an email address.\n signUp: ['email-password'],\n },\n\n // Sign-in for store reviewers (review-access skill). The demo account itself lives ONLY in\n // .storebound/credentials.json (\"reviewDemoAccount\") or REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD.\n reviewAccess: {\n signInRequired: true, // false if every feature works without signing in\n instructions: 'Sign in with the demo account. Sample data is already there; nothing needs a second device.',\n },\n\n // id = your folder / copy key; play = Play language code(s); apple = App Store Connect locale\n languages: [\n { id: 'en', play: 'en-US', apple: 'en-US' },\n { id: 'tr', play: 'tr-TR', apple: 'tr' },\n ],\n\n play: {\n packageName: 'com.example.app',\n defaultLanguage: 'en-US',\n listing: 'store/listing.md',\n icon: 'store/icons/play-512.png',\n },\n\n apple: {\n bundleId: 'com.example.app',\n // name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there (\"already being used\"); default app.name\n listing: 'store/appstore.md',\n // Export compliance (export-compliance skill): decide it, then uncomment. false ONLY if the app uses no encryption\n // beyond the OS (HTTPS through the system, standard sign-in).\n // usesNonExemptEncryption: false,\n // ipad: true,\n info: {\n categories: { primary: 'PRODUCTIVITY', secondary: 'UTILITIES' },\n ageRating: {}, // every content question NONE / false; change what applies (user-generated content, web access ...)\n contentRights: 'DOES_NOT_USE_THIRD_PARTY_CONTENT',\n free: true,\n reviewNotes: [\n 'Example App keeps lists and notes in sync across devices. An account is optional on the first screen.',\n 'Privacy policy and Terms: Settings > About.',\n // With remote config or feature flags (storebound scan warns, 2.3.1) you may add a line like:\n // 'Some features are configured remotely with : ; none is switched on after review without a new submission.',\n ].join('\\n\\n'),\n },\n },\n\n // In-app purchases (optional): a one-time \"Pro\" unlock, for example. Subscriptions: see the subscription-app profile\n // (storebound init --profile subscription-app) or the store-subscriptions skill.\n // products: [{ id: 'com.example.app.pro', type: 'non_consumable', usd: 4.99,\n // listings: { en: { title: 'Pro', description: 'Unlimited lists and themes.' } }, reviewScreenshot: 'store/iap-review/pro.png' }],\n\n // Google Play Data safety. Types not listed = not collected. Typical app with accounts + an analytics SDK acting as\n // your processor (collected, not shared). Edit to match what your app and its SDKs really do.\n dataSafety: {\n collectsData: true,\n encryptedInTransit: true,\n // Sign-up methods. Google does not publish these ids: compare with Play Console > App content > Data safety >\n // Export to CSV before the first import. The delete-account URL (PSL_ACCOUNT_DELETION_URL) comes from\n // accounts.deletionUrl; `storebound check` names any other row Play requires.\n accountCreation: ['PSL_ACM_USER_ID_PASSWORD'],\n // Can people delete their data without deleting the account (a data-only page)? true needs partialDeletionUrl.\n // Play's \"can users request deletion?\" is answered yes by accounts.deletionUrl. Ask the owner.\n partialDeletion: false,\n data: {\n PSL_EMAIL: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_ACCOUNT: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_GENERATED_CONTENT: { shared: false, collect: ['functionality'] },\n PSL_USER_INTERACTION: { shared: false, collect: ['analytics'] },\n PSL_CRASH_LOGS: { shared: false, collect: ['analytics'] },\n PSL_PERFORMANCE_DIAGNOSTICS: { shared: false, collect: ['analytics'] },\n PSL_DEVICE_ID: { shared: false, collect: ['analytics'] },\n },\n },\n\n renders: 'store/renders',\n\n shots: {\n style: 'app', // calm gradient, device frame, headline + subline (game: sparkles and badges)\n copy: 'store/shots/copy.json',\n frames: 'store/shots/frames', // /phone/.png, /tablet/.png\n out: 'store/renders',\n // fonts: { title: 'Inter', body: 'Inter' }, // the app style default\n scenes: [\n { id: 'home', palette: 'mist', frames: [{ src: 'home.png' }] },\n { id: 'detail', palette: 'mint', frames: [{ src: 'detail.png' }] },\n { id: 'share', palette: 'sky', frames: [{ src: 'share.png' }] },\n { id: 'privacy', palette: 'slate', frames: [{ src: 'settings.png' }] },\n ],\n feature: { frame: 'home.png', palette: 'mist' },\n // Raw frames from a web build, the iOS Simulator (ios-sim) or an Android emulator (android-emu): sign in to a demo\n // account with realistic sample data, never real user data (store-screenshots skill).\n capture: {\n baseUrl: 'http://127.0.0.1:5173',\n query: 'lang={lang}&demo=1',\n shots: {\n 'home': { path: '/', delayMs: 1000, device: 'both' },\n 'detail': { path: '/lists/1', delayMs: 1000, device: 'both' },\n 'share': { path: '/lists/1/share', delayMs: 1000, device: 'both' },\n 'settings': { path: '/settings', delayMs: 1000, device: 'both' },\n },\n },\n },\n\n icons: {\n composite: 'store/icon/icon.png',\n foreground: 'store/icon/foreground.png',\n background: 'store/icon/background.png',\n out: 'store/icons',\n },\n};\n\nexport default config;\n", "profiles/app/workflows/beta.yml": "# storebound flow \"beta\": a TestFlight / internal testing build for your testers.\n# storebound flow run beta VERSION=1.2.0 [--apply]\ndescription: Next build to TestFlight and Play internal testing\nparams:\n VERSION: \"1.0.0\"\n GROUP: \"Internal\"\nsteps:\n - id: check\n run: check\n - id: next-build\n if: apple\n run: apple next-build\n capture: BUILD\n - id: build\n if: apple\n run: apple build --version ${VERSION} --build-number ${BUILD}\n - id: upload\n if: apple\n run: apple upload --no-wait --build ${BUILD} --allow-existing\n - id: wait\n if: apple\n run: apple testflight wait --build ${BUILD} --version ${VERSION}\n - id: what-to-test\n if: apple\n run: apple testflight what-to-test --build ${BUILD}\n - id: distribute\n if: apple\n run: apple testflight distribute --build ${BUILD} --group ${GROUP}\n - id: play-build\n if: play\n run: play build --version-name ${VERSION}\n - id: play-upload\n if: play\n run: play upload --track internal\n - id: external\n owner: \"External testers: storebound apple testflight distribute --build ${BUILD} --group --submit-review (Beta App Review is your call)\"\n", "profiles/app/workflows/release.yml": "# storebound flow \"release\": one version of the app on both stores, up to your Submit click.\n# storebound flow run release VERSION=1.2.0 reads run, writes run as dry runs (nothing changes)\n# storebound flow run release VERSION=1.2.0 --apply writes run for real; each command still asks you first\n# storebound flow run release --resume --apply continue after fixing a failed step\n# Steps are storebound commands (no \"storebound\" prefix). `if: apple` / `if: play` skip a store the config does not\n# have; `owner:` steps are never run, they list what you click. Edit freely: this file is yours.\ndescription: Build, upload and check one version on both stores, then your Submit click\nparams:\n VERSION: \"1.0.0\"\nsteps:\n - id: next-build\n if: apple\n run: apple next-build\n capture: BUILD\n - id: build\n if: apple\n run: apple build --version ${VERSION} --build-number ${BUILD}\n - id: upload\n if: apple\n run: apple upload --no-wait --build ${BUILD} --allow-existing\n - id: wait\n if: apple\n run: apple testflight wait --build ${BUILD} --version ${VERSION}\n - id: play-build\n if: play\n run: play build --version-name ${VERSION}\n - id: play-upload\n if: play\n run: play upload --track internal\n - id: whats-new\n if: exists store/whats-new\n run: whats-new apply\n - id: listing\n if: apple\n run: apple listing --version ${VERSION} --build ${BUILD}\n - id: validate\n run: validate\n - id: scan\n run: scan\n - id: plan\n run: release plan ${VERSION}\n - id: submit\n owner: \"App Store Connect: Submit for Review (version ${VERSION}, build ${BUILD}). Play Console: promote the internal release and Send changes for review\"\n", "profiles/subscription-app/app-privacy.md": "# Example App · App Store \"App Privacy\" answers\n\nApp Store Connect > your app > App Privacy (https://appstoreconnect.apple.com/apps, then the app; `storebound console plan apple-app-privacy` gives the deep link). **Web UI only, there is no API.** Fill it from this table, then press\n**Publish** (saving alone does not publish it). Keep it consistent with the privacy policy and the Play Data safety\nanswers (`dataSafety` in `storebound.config.ts`). **Edit to match your app.**\n\nTypical subscription app: account (email), content synced to your backend, auto-renewable subscriptions checked by\nyour server, an analytics SDK acting as your processor, no ads, no tracking.\n\n**Do you or your third-party partners collect data from this app?** Yes\n\n**Tracking**: No (no ad SDK, no data broker, nothing combined with other companies' data for advertising). If that\nchanges, add the App Tracking Transparency prompt first.\n\n| data type | collected | used to track | linked to the user | purposes |\n|---|---|---|---|---|\n| Contact Info > Email Address | yes (account) | no | yes | App Functionality |\n| Identifiers > User ID | yes (account id) | no | yes | App Functionality, Analytics |\n| User Content > Other User Content (lists, notes) | yes (synced) | no | yes | App Functionality |\n| Usage Data > Product Interaction | yes (analytics) | no | yes if tied to the account, else no | Analytics |\n| Purchases > Purchase History (subscription status) | yes | no | yes | App Functionality |\n| Diagnostics > Crash Data | yes | no | no | App Functionality, Analytics |\n| Diagnostics > Performance Data | yes | no | no | Analytics |\n\n\"Linked to you\" is **Yes** for what you store under the account. Not collected (typical): Location, Health and\nFitness, Financial Info, Contacts, Photos or Videos (unless people attach them), Browsing and Search History,\nSensitive Info.\n\nPer data type the UI asks, in order: purposes > \"Is this data linked to the user's identity?\" > \"Do you or your\nthird-party partners use this data for tracking purposes?\".\n", "profiles/subscription-app/appstore.md": "# Example App · App Store listing copy\n\nSource for `storebound apple listing`. One `## ` section per locale (the first word is the locale code:\n`en-US`, `tr`, `de-DE`, `ja`, `zh-Hans`, `ar-SA`, ...), one fenced block per `### `, field names exactly:\n`name` (optional, defaults to `apple.name`, else `app.name`), `subtitle` (30), `promotionalText` (170), `keywords` (100 characters, comma\nseparated, no spaces after commas, do not repeat the app name), `description` (4000), `whatsNew` (optional; not allowed\non the first version). Shared values (privacy policy, support and marketing URL) come from `storebound.config.ts`.\n\n---\n\n## en-US · English (U.S.)\n\n### subtitle\n```\nLists and notes, in sync\n```\n\n### promotionalText\n```\nOne or two sentences you can change any time without a new version.\n```\n\n### keywords\n```\ntodo,checklist,groceries,planner,notes,shared,family,organizer,tasks,sync\n```\n\n### description\n```\nFirst paragraph: the job the app does and why it is easier with it.\n\nFEATURES\n• Lists and notes that sync across your devices\n• Share a list with family or friends\n• Export your data or delete your account in Settings, any time\n\nFree to use with up to 3 lists. Example Pro unlocks unlimited lists, sharing and themes: yearly with a 1-week free trial, or monthly. Payment is charged to your store account; the subscription renews automatically unless cancelled at least 24 hours before the end of the period, and you can manage or cancel it in your account settings.\n\nTerms of Use: https://example.com/terms\nPrivacy Policy: https://example.com/privacy\n```\n\n## tr · Türkçe\n\n### subtitle\n```\nListeler ve notlar, eşitli\n```\n\n### promotionalText\n```\nYeni sürüm göndermeden istediğin zaman değiştirebileceğin bir iki cümle.\n```\n\n### keywords\n```\nyapılacaklar,kontrol,market,planlayıcı,not,paylaşım,aile,düzen,görev\n```\n\n### description\n```\nİlk paragraf: uygulamanın gördüğü iş ve onunla neden daha kolay olduğu.\n\nÖZELLİKLER\n• Tüm cihazlarında eşitlenen listeler ve notlar\n• Bir listeyi ailen ya da arkadaşlarınla paylaş\n• Verilerini dışa aktar ya da hesabını Ayarlar'dan istediğin an sil\n\n3 listeye kadar ücretsiz. Example Pro sınırsız liste, paylaşım ve tema açar: 1 hafta ücretsiz denemeli yıllık ya da aylık. Ödeme mağaza hesabınızdan alınır; abonelik, dönem bitmeden en az 24 saat önce iptal edilmezse otomatik yenilenir; hesap ayarlarınızdan yönetebilir ya da iptal edebilirsiniz.\n\nKullanım Koşulları: https://example.com/terms\nGizlilik Politikası: https://example.com/privacy\n```\n", "profiles/subscription-app/declarations.md": "# Example App · store declarations (answers to copy into the consoles)\n\nStarting answers for a typical **subscription app**: auto-renewable subscriptions (free trial on the yearly plan), an account (email + password, or sign in\nwith a provider), an analytics SDK acting as your processor, data synced to your own backend, no ads, no chat with\nstrangers, general audience. **Edit every line to match your app**: these are your statements to the stores. Everything\nmarked **UI** has no API: Play Console > your app > Policy and programs > **App content** (https://play.google.com/console), and App Store Connect for\nApple. Data safety (Play) has an API: `storebound play data-safety`.\n\n## Google Play · App content (UI)\n\n| declaration | answer |\n|---|---|\n| Privacy policy | your policy URL (same one in the listing and inside the app) |\n| App access | \"All or some functionality is restricted\": add the demo account (username, password) and the steps from `reviewAccess.instructions`; credentials must work at all times, no 2FA / OTP (review-access skill) |\n| Ads | No, my app does not contain ads |\n| Content rating | IARC questionnaire, below |\n| Target audience and content | 18 and over (or 13+ if teens use it); \"Could your app unintentionally appeal to children?\" No (only if true) |\n| News app | No |\n| Data safety | `storebound play data-safety`, then check the summary; with accounts: the delete-account URL (`accounts.deletionUrl`) |\n| Government apps | No |\n| Financial features | My app doesn't provide any financial features |\n| Health apps | No health features |\n| Advertising ID | No (unless an SDK in your app reads it: check the SDK docs and your merged manifest) |\n| Store settings | App, category (Productivity, Tools, ...); contact email + website |\n\n## Account deletion (account-deletion skill)\n\n- In the app: Settings > Account > Delete account deletes the account and its data (not only \"deactivate\").\n- On the web: `accounts.deletionUrl` lets people request deletion without the app; Play asks for it in Data safety.\n- With subscriptions: say that deleting the account does not cancel the store subscription, and how to cancel.\n\n## IARC content rating (Play UI; Apple has its own form, `storebound apple appinfo`)\n\nCategory: not a game (e.g. Utility, Productivity, Communication, or Social Networking if people share content with\nothers). Typical answers for a lists / notes app:\n\n| topic | answer |\n|---|---|\n| Violence, sexuality, language, controlled substances | No |\n| Gambling (simulated / real money) | No |\n| Users interact or exchange content | Yes only if people can share with others outside their own invitations; then also moderation and reporting |\n| Shares location with other users | No |\n| Digital purchases | Yes (subscriptions) |\n| Unrestricted internet / browser | No |\n\nExpected: PEGI 3, ESRB Everyone, IARC 3+. Apple age rating 4+ (all content questions None) unless users share\ncontent publicly.\n\n## App Store (UI-only parts)\n\n- App record: App Store Connect > Apps > + > New App (https://appstoreconnect.apple.com/apps). No API.\n- App Privacy: `app-privacy.md`, then **Publish**.\n- App Review information: `storebound apple review-details` sends the contact, the demo account (from\n `.storebound/credentials.json`, masked in the log) and the notes.\n- Export compliance (export-compliance skill): `ITSAppUsesNonExemptEncryption = NO` only if true.\n- Guideline 5.1.1: the privacy policy link must also be reachable **inside the app**; 5.1.1(v): account deletion\n inside the app.\n\n## Subscriptions (store-subscriptions skill)\n\n- Purchase screen (both stores): plan name, length, the full renewal price per period (most prominent), what is\n included, free trial length and what is charged after it, how to cancel, Restore Purchases, links to the Terms of Use\n and the Privacy Policy. Apple 3.1.2; Google Play subscriptions policy.\n- Metadata: the App Store description (or a custom EULA in App Information > License Agreement) links the Terms of\n Use; the Privacy Policy URL field is set by `storebound apple listing`.\n- First subscriptions are submitted together with an app version (App Store Connect: add them to the version on its\n page before Submit for Review), like first in-app purchases.\n- App Review notes say where the paywall is and that sandbox purchases work with the demo account.\n- Play: base plans and offers must be active before people can buy; new subscribers see the converted regional prices.\n", "profiles/subscription-app/listing.md": "# Example App · Google Play listing copy\n\nSource for `storebound play listing` (title, short + full description) and `storebound play release` (release notes).\nRules the parser follows:\n- every `## ...` section with a `` line is a listing; one section can serve several Play codes\n- under it, `### ...` headings that contain **title** (optional, defaults to `app.name`), **short**, **full** and\n **what's new**, each followed by one fenced block\n- limits (checked before anything is sent): title 30, short 80, full 4000, what's new 500 characters\nOnly claim what the app really does. No prices, no \"best / #1\", no other apps' names.\n\n---\n\n## English (en-US)\n\n\n### Play short description (max 80)\n```\nWhat the app does for people, in one plain line\n```\n\n### Play full description (max 4000)\n```\nFirst paragraph: the job the app does and why it is easier with it, in two or three sentences.\n\nFEATURES\n• Lists and notes that sync across your devices\n• Share a list with family or friends\n• Export your data or delete your account in Settings, any time\n\nFree to use with up to 3 lists. Example Pro unlocks unlimited lists, sharing and themes: yearly with a 1-week free trial, or monthly. Payment is charged to your store account; the subscription renews automatically unless cancelled at least 24 hours before the end of the period, and you can manage or cancel it in your account settings.\n\nTerms of Use: https://example.com/terms\nPrivacy Policy: https://example.com/privacy\n```\n\n### What's new (max 500)\n```\nFirst release. Thanks for trying it!\n```\n\n## Türkçe (tr-TR)\n\n\n### Play kısa açıklama · short (max 80)\n```\nUygulamanın insanlar için ne yaptığını anlatan sade bir cümle\n```\n\n### Play tam açıklama · full (max 4000)\n```\nİlk paragraf: uygulamanın gördüğü iş ve onunla neden daha kolay olduğu, iki üç cümlede.\n\nÖZELLİKLER\n• Tüm cihazlarında eşitlenen listeler ve notlar\n• Bir listeyi ailen ya da arkadaşlarınla paylaş\n• Verilerini dışa aktar ya da hesabını Ayarlar'dan istediğin an sil\n\n3 listeye kadar ücretsiz. Example Pro sınırsız liste, paylaşım ve tema açar: 1 hafta ücretsiz denemeli yıllık ya da aylık. Ödeme mağaza hesabınızdan alınır; abonelik, dönem bitmeden en az 24 saat önce iptal edilmezse otomatik yenilenir; hesap ayarlarınızdan yönetebilir ya da iptal edebilirsiniz.\n\nKullanım Koşulları: https://example.com/terms\nGizlilik Politikası: https://example.com/privacy\n```\n\n### Yenilikler · what's new (max 500)\n```\nİlk sürüm. Denediğin için teşekkürler!\n```\n", - "profiles/subscription-app/storebound.config.ts": "// storebound config for one app (profile \"subscription-app\": accounts plus auto-renewable subscriptions, an\n// analytics SDK, no ads). Every answer below is a starting point: edit it to match your app. Credentials NEVER go\n// here (env vars or .storebound/credentials.json, gitignored). Paths are relative to this file.\n// The type import is optional: it only works when storebound is installed in the project (bun add -d storebound).\nimport type { ShipConfig } from 'storebound';\n\nconst config: ShipConfig = {\n // Every compliance answer below is the TEMPLATE's, not yours. While an area is listed here, check / validate block\n // and nothing sends it to a store. Derive the answers from the code (storebound scan --write; for an app that is\n // already live: storebound onboard --declarations), answer the rest, then remove the area from this list.\n unanswered: ['dataSafety', 'appPrivacy', 'reviewNotes', 'ageRating', 'accounts', 'reviewAccess'],\n\n app: {\n name: 'Example App',\n profile: 'subscription-app',\n copyright: '2026 Example Studio',\n privacyPolicyUrl: 'https://example.com/privacy',\n termsUrl: 'https://example.com/terms', // Terms of Use (EULA): in the app and the metadata (Apple 3.1.2)\n supportUrl: 'https://example.com/support',\n marketingUrl: 'https://example.com',\n website: 'https://example.com',\n contactEmail: 'support@example.com',\n },\n\n // Accounts (account-deletion skill). Remove this block if the app has no sign-up / sign-in at all.\n // Apple 5.1.1(v): deletion must start inside the app. Google Play: in the app AND on a public web page.\n accounts: {\n enabled: true,\n deletionUrl: 'https://example.com/delete-account', // public page, no login needed to request deletion\n inApp: 'Settings > Account > Delete account', // goes into the App Review notes\n // How people sign up: 'username' (a name picked in the app, no password, no email), 'username-password',\n // 'email-password', 'email-link', 'phone', 'oauth', 'other'. `storebound scan` proposes the account data and\n // dataSafety.accountCreation from it; only the 'email-*' methods mean an email address.\n signUp: ['email-password'],\n },\n\n // Sign-in for store reviewers (review-access skill). The demo account itself lives ONLY in\n // .storebound/credentials.json (\"reviewDemoAccount\") or REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD.\n reviewAccess: {\n signInRequired: true, // false if every feature works without signing in\n instructions: 'Sign in with the demo account. Sample data is already there; nothing needs a second device.',\n },\n\n // id = your folder / copy key; play = Play language code(s); apple = App Store Connect locale\n languages: [\n { id: 'en', play: 'en-US', apple: 'en-US' },\n { id: 'tr', play: 'tr-TR', apple: 'tr' },\n ],\n\n play: {\n packageName: 'com.example.app',\n defaultLanguage: 'en-US',\n listing: 'store/listing.md',\n icon: 'store/icons/play-512.png',\n },\n\n apple: {\n bundleId: 'com.example.app',\n // name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there (\"already being used\"); default app.name\n listing: 'store/appstore.md',\n // Export compliance (export-compliance skill): decide it, then uncomment. false ONLY if the app uses no encryption\n // beyond the OS (HTTPS through the system, standard sign-in).\n // usesNonExemptEncryption: false,\n // ipad: true,\n info: {\n categories: { primary: 'PRODUCTIVITY', secondary: 'UTILITIES' },\n ageRating: {}, // every content question NONE / false; change what applies (user-generated content, web access ...)\n contentRights: 'DOES_NOT_USE_THIRD_PARTY_CONTENT',\n free: true,\n reviewNotes: [\n 'Example App keeps lists and notes in sync across devices. Pro (yearly with a 1-week free trial, or monthly) unlocks unlimited lists, sharing and themes.',\n 'Subscriptions: Settings > Pro (or the paywall after the third list). Restore Purchases is on the paywall and in Settings > Pro.',\n 'Privacy policy and Terms of Use: on the paywall and in Settings > About.',\n ].join('\\n\\n'),\n },\n },\n\n // Auto-renewable subscriptions (store-subscriptions skill): `storebound apple subscriptions`, `storebound play\n // subscriptions`. Apple: one group, levels rank the plans (1 = highest). Play: one subscription per entry with one\n // auto-renewing base plan. Prices: USD base, Apple equalizes from the USA, Play converts per region; overrides set a\n // region by hand. The disclosure (price per period, renewal, how to cancel, Terms + Privacy links) belongs on the\n // purchase screen and in the descriptions.\n subscriptions: [\n {\n name: 'Example Pro',\n listings: { en: { name: 'Example Pro' }, tr: { name: 'Example Pro' } },\n subscriptions: [\n {\n id: 'com.example.app.pro_yearly', period: 'P1Y', level: 1, usd: 29.99,\n listings: {\n en: { title: 'Pro yearly', description: 'Unlimited lists, sharing and themes.', benefits: ['Unlimited lists', 'Shared lists', 'All themes'] },\n tr: { title: 'Pro yıllık', description: 'Sınırsız liste, paylaşım ve tema.', benefits: ['Sınırsız liste', 'Paylaşılan listeler', 'Tüm temalar'] },\n },\n intro: { type: 'free', duration: 'P1W' }, // 1 week free trial for new subscribers\n reviewScreenshot: 'store/iap-review/paywall.png',\n },\n {\n id: 'com.example.app.pro_monthly', period: 'P1M', level: 2, usd: 3.99,\n overrides: [{ region: 'TR', currency: 'TRY', price: 99.99 }],\n listings: {\n en: { title: 'Pro monthly', description: 'Unlimited lists, sharing and themes.', benefits: ['Unlimited lists', 'Shared lists', 'All themes'] },\n tr: { title: 'Pro aylık', description: 'Sınırsız liste, paylaşım ve tema.', benefits: ['Sınırsız liste', 'Paylaşılan listeler', 'Tüm temalar'] },\n },\n reviewScreenshot: 'store/iap-review/paywall.png',\n },\n ],\n },\n ],\n\n // Google Play Data safety. Types not listed = not collected. Typical app with accounts + an analytics SDK acting as\n // your processor (collected, not shared). Edit to match what your app and its SDKs really do.\n dataSafety: {\n collectsData: true,\n encryptedInTransit: true,\n // Sign-up methods. Google does not publish these ids: compare with Play Console > App content > Data safety >\n // Export to CSV before the first import. The delete-account URL (PSL_ACCOUNT_DELETION_URL) comes from\n // accounts.deletionUrl; `storebound check` names any other row Play requires.\n accountCreation: ['PSL_ACM_USER_ID_PASSWORD'],\n // Can people delete their data without deleting the account (a data-only page)? true needs partialDeletionUrl.\n // Play's \"can users request deletion?\" is answered yes by accounts.deletionUrl. Ask the owner.\n partialDeletion: false,\n data: {\n PSL_EMAIL: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_ACCOUNT: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_GENERATED_CONTENT: { shared: false, collect: ['functionality'] },\n PSL_USER_INTERACTION: { shared: false, collect: ['analytics'] },\n PSL_CRASH_LOGS: { shared: false, collect: ['analytics'] },\n PSL_PERFORMANCE_DIAGNOSTICS: { shared: false, collect: ['analytics'] },\n PSL_DEVICE_ID: { shared: false, collect: ['analytics'] },\n PSL_PURCHASE_HISTORY: { shared: false, collect: ['functionality'] }, // subscription status tied to the account\n },\n },\n\n renders: 'store/renders',\n\n shots: {\n style: 'app', // calm gradient, device frame, headline + subline (game: sparkles and badges)\n copy: 'store/shots/copy.json',\n frames: 'store/shots/frames', // /phone/.png, /tablet/.png\n out: 'store/renders',\n // fonts: { title: 'Inter', body: 'Inter' }, // the app style default\n scenes: [\n { id: 'home', palette: 'mist', frames: [{ src: 'home.png' }] },\n { id: 'detail', palette: 'mint', frames: [{ src: 'detail.png' }] },\n { id: 'share', palette: 'sky', frames: [{ src: 'share.png' }] },\n { id: 'privacy', palette: 'slate', frames: [{ src: 'settings.png' }] },\n ],\n feature: { frame: 'home.png', palette: 'mist' },\n // Raw frames from a web build, the iOS Simulator (ios-sim) or an Android emulator (android-emu): sign in to a demo\n // account with realistic sample data, never real user data (store-screenshots skill).\n capture: {\n baseUrl: 'http://127.0.0.1:5173',\n query: 'lang={lang}&demo=1',\n shots: {\n 'home': { path: '/', delayMs: 1000, device: 'both' },\n 'detail': { path: '/lists/1', delayMs: 1000, device: 'both' },\n 'share': { path: '/lists/1/share', delayMs: 1000, device: 'both' },\n 'settings': { path: '/settings', delayMs: 1000, device: 'both' },\n },\n },\n },\n\n icons: {\n composite: 'store/icon/icon.png',\n foreground: 'store/icon/foreground.png',\n background: 'store/icon/background.png',\n out: 'store/icons',\n },\n};\n\nexport default config;\n", + "profiles/subscription-app/storebound.config.ts": "// storebound config for one app (profile \"subscription-app\": accounts plus auto-renewable subscriptions, an\n// analytics SDK, no ads). Every answer below is a starting point: edit it to match your app. Credentials NEVER go\n// here (env vars or .storebound/credentials.json, gitignored). Paths are relative to this file.\n// The type import is optional: it only works when storebound is installed in the project (bun add -d storebound).\nimport type { ShipConfig } from 'storebound';\n\nconst config: ShipConfig = {\n // Every compliance answer below is the TEMPLATE's, not yours. While an area is listed here, check / validate block\n // and nothing sends it to a store. Derive the answers from the code (storebound scan --write; for an app that is\n // already live: storebound onboard --declarations), answer the rest, then remove the area from this list.\n unanswered: ['dataSafety', 'appPrivacy', 'reviewNotes', 'ageRating', 'accounts', 'reviewAccess'],\n\n app: {\n name: 'Example App',\n profile: 'subscription-app',\n copyright: '2026 Example Studio',\n privacyPolicyUrl: 'https://example.com/privacy',\n termsUrl: 'https://example.com/terms', // Terms of Use (EULA): in the app and the metadata (Apple 3.1.2)\n supportUrl: 'https://example.com/support',\n marketingUrl: 'https://example.com',\n website: 'https://example.com',\n contactEmail: 'support@example.com',\n },\n\n // Accounts (account-deletion skill). Remove this block if the app has no sign-up / sign-in at all.\n // Apple 5.1.1(v): deletion must start inside the app. Google Play: in the app AND on a public web page.\n accounts: {\n enabled: true,\n deletionUrl: 'https://example.com/delete-account', // public page, no login needed to request deletion\n inApp: 'Settings > Account > Delete account', // goes into the App Review notes\n // How people sign up: 'username' (a name picked in the app, no password, no email), 'username-password',\n // 'email-password', 'email-link', 'phone', 'oauth', 'other'. `storebound scan` proposes the account data and\n // dataSafety.accountCreation from it; only the 'email-*' methods mean an email address.\n signUp: ['email-password'],\n },\n\n // Sign-in for store reviewers (review-access skill). The demo account itself lives ONLY in\n // .storebound/credentials.json (\"reviewDemoAccount\") or REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD.\n reviewAccess: {\n signInRequired: true, // false if every feature works without signing in\n instructions: 'Sign in with the demo account. Sample data is already there; nothing needs a second device.',\n },\n\n // id = your folder / copy key; play = Play language code(s); apple = App Store Connect locale\n languages: [\n { id: 'en', play: 'en-US', apple: 'en-US' },\n { id: 'tr', play: 'tr-TR', apple: 'tr' },\n ],\n\n play: {\n packageName: 'com.example.app',\n defaultLanguage: 'en-US',\n listing: 'store/listing.md',\n icon: 'store/icons/play-512.png',\n },\n\n apple: {\n bundleId: 'com.example.app',\n // name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there (\"already being used\"); default app.name\n listing: 'store/appstore.md',\n // Export compliance (export-compliance skill): decide it, then uncomment. false ONLY if the app uses no encryption\n // beyond the OS (HTTPS through the system, standard sign-in).\n // usesNonExemptEncryption: false,\n // ipad: true,\n info: {\n categories: { primary: 'PRODUCTIVITY', secondary: 'UTILITIES' },\n ageRating: {}, // every content question NONE / false; change what applies (user-generated content, web access ...)\n contentRights: 'DOES_NOT_USE_THIRD_PARTY_CONTENT',\n free: true,\n reviewNotes: [\n 'Example App keeps lists and notes in sync across devices. Pro (yearly with a 1-week free trial, or monthly) unlocks unlimited lists, sharing and themes.',\n 'Subscriptions: Settings > Pro (or the paywall after the third list). Restore Purchases is on the paywall and in Settings > Pro.',\n 'Privacy policy and Terms of Use: on the paywall and in Settings > About.',\n // With a remote paywall or feature flags (storebound scan warns, 2.3.1) you may add a line like:\n // 'Paywall designs and the prices shown are tested remotely with ; what Pro unlocks does not change after review.',\n ].join('\\n\\n'),\n },\n },\n\n // Auto-renewable subscriptions (store-subscriptions skill): `storebound apple subscriptions`, `storebound play\n // subscriptions`. Apple: one group, levels rank the plans (1 = highest). Play: one subscription per entry with one\n // auto-renewing base plan. Prices: USD base, Apple equalizes from the USA, Play converts per region; overrides set a\n // region by hand. The disclosure (price per period, renewal, how to cancel, Terms + Privacy links) belongs on the\n // purchase screen and in the descriptions.\n subscriptions: [\n {\n name: 'Example Pro',\n listings: { en: { name: 'Example Pro' }, tr: { name: 'Example Pro' } },\n subscriptions: [\n {\n id: 'com.example.app.pro_yearly', period: 'P1Y', level: 1, usd: 29.99,\n listings: {\n en: { title: 'Pro yearly', description: 'Unlimited lists, sharing and themes.', benefits: ['Unlimited lists', 'Shared lists', 'All themes'] },\n tr: { title: 'Pro yıllık', description: 'Sınırsız liste, paylaşım ve tema.', benefits: ['Sınırsız liste', 'Paylaşılan listeler', 'Tüm temalar'] },\n },\n intro: { type: 'free', duration: 'P1W' }, // 1 week free trial for new subscribers\n reviewScreenshot: 'store/iap-review/paywall.png',\n },\n {\n id: 'com.example.app.pro_monthly', period: 'P1M', level: 2, usd: 3.99,\n overrides: [{ region: 'TR', currency: 'TRY', price: 99.99 }],\n listings: {\n en: { title: 'Pro monthly', description: 'Unlimited lists, sharing and themes.', benefits: ['Unlimited lists', 'Shared lists', 'All themes'] },\n tr: { title: 'Pro aylık', description: 'Sınırsız liste, paylaşım ve tema.', benefits: ['Sınırsız liste', 'Paylaşılan listeler', 'Tüm temalar'] },\n },\n reviewScreenshot: 'store/iap-review/paywall.png',\n },\n ],\n },\n ],\n\n // Google Play Data safety. Types not listed = not collected. Typical app with accounts + an analytics SDK acting as\n // your processor (collected, not shared). Edit to match what your app and its SDKs really do.\n dataSafety: {\n collectsData: true,\n encryptedInTransit: true,\n // Sign-up methods. Google does not publish these ids: compare with Play Console > App content > Data safety >\n // Export to CSV before the first import. The delete-account URL (PSL_ACCOUNT_DELETION_URL) comes from\n // accounts.deletionUrl; `storebound check` names any other row Play requires.\n accountCreation: ['PSL_ACM_USER_ID_PASSWORD'],\n // Can people delete their data without deleting the account (a data-only page)? true needs partialDeletionUrl.\n // Play's \"can users request deletion?\" is answered yes by accounts.deletionUrl. Ask the owner.\n partialDeletion: false,\n data: {\n PSL_EMAIL: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_ACCOUNT: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_GENERATED_CONTENT: { shared: false, collect: ['functionality'] },\n PSL_USER_INTERACTION: { shared: false, collect: ['analytics'] },\n PSL_CRASH_LOGS: { shared: false, collect: ['analytics'] },\n PSL_PERFORMANCE_DIAGNOSTICS: { shared: false, collect: ['analytics'] },\n PSL_DEVICE_ID: { shared: false, collect: ['analytics'] },\n PSL_PURCHASE_HISTORY: { shared: false, collect: ['functionality'] }, // subscription status tied to the account\n },\n },\n\n renders: 'store/renders',\n\n shots: {\n style: 'app', // calm gradient, device frame, headline + subline (game: sparkles and badges)\n copy: 'store/shots/copy.json',\n frames: 'store/shots/frames', // /phone/.png, /tablet/.png\n out: 'store/renders',\n // fonts: { title: 'Inter', body: 'Inter' }, // the app style default\n scenes: [\n { id: 'home', palette: 'mist', frames: [{ src: 'home.png' }] },\n { id: 'detail', palette: 'mint', frames: [{ src: 'detail.png' }] },\n { id: 'share', palette: 'sky', frames: [{ src: 'share.png' }] },\n { id: 'privacy', palette: 'slate', frames: [{ src: 'settings.png' }] },\n ],\n feature: { frame: 'home.png', palette: 'mist' },\n // Raw frames from a web build, the iOS Simulator (ios-sim) or an Android emulator (android-emu): sign in to a demo\n // account with realistic sample data, never real user data (store-screenshots skill).\n capture: {\n baseUrl: 'http://127.0.0.1:5173',\n query: 'lang={lang}&demo=1',\n shots: {\n 'home': { path: '/', delayMs: 1000, device: 'both' },\n 'detail': { path: '/lists/1', delayMs: 1000, device: 'both' },\n 'share': { path: '/lists/1/share', delayMs: 1000, device: 'both' },\n 'settings': { path: '/settings', delayMs: 1000, device: 'both' },\n },\n },\n },\n\n icons: {\n composite: 'store/icon/icon.png',\n foreground: 'store/icon/foreground.png',\n background: 'store/icon/background.png',\n out: 'store/icons',\n },\n};\n\nexport default config;\n", "shots-copy.json": "{\n \"en\": {\n \"hero\": { \"title\": [\"Tap. Match.\", \"Repeat!\"], \"badges\": [[\"100+ levels\", \"and more every update\"], [\"Play offline\", \"No account needed\"]] },\n \"play\": { \"eyebrow\": \"Play\", \"title\": [\"Easy to learn,\", \"hard to put down\"], \"sub\": \"One thumb, short rounds, big satisfying moments.\", \"badges\": [[\"Quick rounds\", \"Two minutes each\"], [\"Great!\"]] },\n \"levels\": { \"eyebrow\": \"Worlds\", \"title\": [\"Explore new\", \"worlds\"], \"sub\": \"A fresh look and new rules every ten levels.\", \"badges\": [[\"10 worlds\", \"A new one every 10 levels\"]] },\n \"stars\": { \"eyebrow\": \"Stars\", \"title\": [\"Play smart,\", \"grab 3 stars\"], \"sub\": \"Finish with moves to spare and collect every star.\", \"badges\": [[\"3 stars\"]] }\n },\n \"tr\": {\n \"hero\": { \"title\": [\"Dokun. Eşleştir.\", \"Tekrarla!\"], \"badges\": [[\"100+ bölüm\", \"her güncellemede yenileri\"], [\"İnternetsiz\", \"hesap gerekmez\"]] },\n \"play\": { \"eyebrow\": \"Oyna\", \"title\": [\"Öğrenmesi kolay,\", \"bırakması zor\"], \"sub\": \"Tek parmak, kısa turlar, büyük keyifli anlar.\", \"badges\": [[\"Kısa turlar\", \"Her biri iki dakika\"], [\"Harika!\"]] },\n \"levels\": { \"eyebrow\": \"Dünyalar\", \"title\": [\"Yeni dünyaları\", \"keşfet\"], \"sub\": \"Her on bölümde yeni bir görünüm ve yeni kurallar.\", \"badges\": [[\"10 dünya\", \"Her 10 bölümde yeni biri\"]] },\n \"stars\": { \"eyebrow\": \"Yıldızlar\", \"title\": [\"Akıllı oyna,\", \"3 yıldızı kap\"], \"sub\": \"Hamle artırarak bitir, tüm yıldızları topla.\", \"badges\": [[\"3 yıldız\"]] }\n },\n \"es\": {\n \"hero\": { \"title\": [\"Toca. Combina.\", \"¡Repite!\"], \"badges\": [[\"100+ niveles\", \"y más en cada versión\"], [\"Sin conexión\", \"Sin cuenta\"]] },\n \"play\": { \"eyebrow\": \"Juega\", \"title\": [\"Fácil de aprender,\", \"difícil de soltar\"], \"sub\": \"Un pulgar, rondas cortas, grandes momentos.\", \"badges\": [[\"Rondas cortas\", \"Dos minutos cada una\"], [\"¡Genial!\"]] },\n \"levels\": { \"eyebrow\": \"Mundos\", \"title\": [\"Explora\", \"nuevos mundos\"], \"sub\": \"Un aspecto nuevo y nuevas reglas cada diez niveles.\", \"badges\": [[\"10 mundos\", \"Uno nuevo cada 10 niveles\"]] },\n \"stars\": { \"eyebrow\": \"Estrellas\", \"title\": [\"Juega con cabeza,\", \"logra 3 estrellas\"], \"sub\": \"Termina con movimientos de sobra y consigue todas las estrellas.\", \"badges\": [[\"3 estrellas\"]] }\n },\n \"ja\": {\n \"hero\": { \"title\": [\"タップして、そろえて、\", \"もう一回!\"], \"badges\": [[\"100以上のステージ\", \"アップデートで追加\"], [\"オフラインで遊べる\", \"アカウント不要\"]] },\n \"play\": { \"eyebrow\": \"プレイ\", \"title\": [\"かんたんなのに\", \"やめられない\"], \"sub\": \"片手で遊べる短いラウンド、気持ちいい瞬間がたくさん。\", \"badges\": [[\"短いラウンド\", \"1回2分\"], [\"すごい!\"]] },\n \"levels\": { \"eyebrow\": \"ワールド\", \"title\": [\"新しいワールドを\", \"冒険しよう\"], \"sub\": \"10ステージごとに新しい見た目と新しいルール。\", \"badges\": [[\"10のワールド\", \"10ステージごとに追加\"]] },\n \"stars\": { \"eyebrow\": \"スター\", \"title\": [\"かしこく遊んで\", \"星を3つゲット\"], \"sub\": \"手数を残してクリアし、すべての星を集めよう。\", \"badges\": [[\"星3つ\"]] }\n },\n \"ar\": {\n \"hero\": { \"title\": [\"انقر. طابق.\", \"كرّر!\"], \"badges\": [[\"أكثر من 100 مرحلة\", \"والمزيد مع كل تحديث\"], [\"العب دون اتصال\", \"دون حساب\"]] },\n \"play\": { \"eyebrow\": \"العب\", \"title\": [\"سهلة التعلّم،\", \"صعبة التوقف\"], \"sub\": \"إبهام واحد، جولات قصيرة، ولحظات ممتعة.\", \"badges\": [[\"جولات قصيرة\", \"دقيقتان لكل جولة\"], [\"رائع!\"]] },\n \"levels\": { \"eyebrow\": \"العوالم\", \"title\": [\"استكشف\", \"عوالم جديدة\"], \"sub\": \"شكل جديد وقواعد جديدة كل عشر مراحل.\", \"badges\": [[\"10 عوالم\", \"عالم جديد كل 10 مراحل\"]] },\n \"stars\": { \"eyebrow\": \"النجوم\", \"title\": [\"العب بذكاء،\", \"واجمع 3 نجوم\"], \"sub\": \"أنهِ المرحلة بحركات متبقية واجمع كل النجوم.\", \"badges\": [[\"3 نجوم\"]] }\n }\n}\n", - "storebound.config.ts": "// storebound config for one game. Everything game-specific lives here; credentials NEVER do (they go in env vars or\n// .storebound/credentials.json, which must stay gitignored). Paths are relative to this file.\n// The type import is optional: it only works when storebound is installed in the project (bun add -d ).\nimport type { ShipConfig } from 'storebound';\n\nconst config: ShipConfig = {\n // Every compliance answer below is the TEMPLATE's, not yours. While an area is listed here, check / validate block\n // and nothing sends it to a store. Derive the answers from the code (storebound scan --write; for an app that is\n // already live: storebound onboard --declarations), answer the rest, then remove the area from this list.\n unanswered: ['dataSafety', 'appPrivacy', 'reviewNotes', 'ageRating'],\n\n app: {\n name: 'Example Game',\n profile: 'game',\n copyright: '2026 Example Studio',\n privacyPolicyUrl: 'https://example.com/privacy',\n supportUrl: 'https://example.com',\n marketingUrl: 'https://example.com',\n // Developer website on Play: the same domain must serve /app-ads.txt if the game shows ads\n website: 'https://example.com',\n contactEmail: 'support@example.com',\n },\n\n // id = your folder / copy key; play = Play language code(s); apple = App Store Connect locale\n languages: [\n { id: 'en', play: 'en-US', apple: 'en-US' },\n { id: 'tr', play: 'tr-TR', apple: 'tr' },\n { id: 'es', play: ['es-ES', 'es-419'], apple: 'es-ES' },\n { id: 'ja', play: 'ja-JP', apple: 'ja' },\n { id: 'ar', play: 'ar', apple: 'ar-SA', rtl: true },\n ],\n\n play: {\n packageName: 'com.example.game',\n defaultLanguage: 'en-US',\n listing: 'store/listing.md',\n icon: 'store/icons/play-512.png',\n // read by `storebound scan` (fill in what is true for your account and app):\n // accountType: 'personal', accountCreated: 'YYYY-MM-DD', // new personal accounts: 12 testers x 14 days closed test\n // targetAges: ['13-15', '16-17', '18+'], // App content > Target audience; under 13 = Families policy\n },\n\n apple: {\n bundleId: 'com.example.game',\n // name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there (\"already being used\"); default app.name\n // appId: '1234567890', // Apple ID of the app record; looked up by bundle id when left out\n listing: 'store/appstore.md',\n reviewShots: 'store/iap-review',\n // Export compliance (export-compliance skill). false ONLY if the game uses no encryption beyond the OS (HTTPS through\n // the system). Left unset on purpose: decide it, then uncomment. Same answer as ITSAppUsesNonExemptEncryption.\n // usesNonExemptEncryption: false,\n // ipad: true, // the app runs on iPad: 13\" iPad screenshots (2064 x 2752, ipad13) are rendered, checked and uploaded\n // iphoneMedium: true, // optional 6.3\" iPhone set (1206 x 2622, iphone-medium); off: Apple scales the 6.5\" set down\n // screenshotTypes: ['APP_IPHONE_67'], // what `storebound validate` requires per locale (default; + APP_IPAD_PRO_3GEN_129 with ipad)\n // TestFlight (`storebound apple testflight`, testflight skill). Tester emails live in .storebound/testers.csv only.\n testflight: {\n groups: [\n { name: 'Team', internal: true, allBuilds: true },\n { name: 'Friends' },\n ],\n description: { en: 'Example Game beta: try the new levels and tell us what feels too hard.' },\n },\n info: {\n categories: { primary: 'GAMES', primarySubOne: 'GAMES_CASUAL', primarySubTwo: 'GAMES_PUZZLE', secondary: 'ENTERTAINMENT' },\n ageRating: { advertising: true }, // everything else NONE / false\n contentRights: 'DOES_NOT_USE_THIRD_PARTY_CONTENT',\n free: true,\n reviewNotes: [\n 'Single-player game. No account or login is needed; there is no user-generated content or chat.',\n 'In-app purchases: Home > Shop. Restore Purchases is in Settings.',\n 'Ads: optional rewarded videos and interstitials between rounds. The App Tracking Transparency prompt is shown before the ad SDK starts.',\n 'Privacy policy: Settings > Privacy.',\n ].join('\\n\\n'),\n },\n },\n\n // Price changes later for many products / regions: storebound prices export, edit store/prices.csv, prices import --dry.\n // prices: { csv: 'store/prices.csv', baseTerritory: 'USA' },\n\n // Same ids on both stores. Prices: USD base; Play converts per region, Apple equalizes from the USA. Overrides set a\n // region by hand (Apple needs an existing price point with exactly that value).\n products: [\n {\n id: 'com.example.game.remove_ads', type: 'non_consumable', usd: 2.99,\n overrides: [{ region: 'TR', currency: 'TRY', price: 99.99 }],\n listings: {\n en: { title: 'Remove Ads', description: 'Removes interstitial ads for good.' },\n tr: { title: 'Reklamları Kaldır', description: 'Ara reklamları kalıcı olarak kaldırır.' },\n },\n reviewScreenshot: 'store/iap-review/shop.png',\n },\n {\n id: 'com.example.game.coins_small', type: 'consumable', usd: 0.99,\n listings: {\n en: { title: '500 Coins', description: 'A small bag of coins.' },\n tr: { title: '500 Altın', description: 'Küçük bir kese altın.' },\n },\n reviewScreenshot: 'store/iap-review/shop.png',\n },\n ],\n\n // Google Play Data safety. Types not listed = not collected. Purposes: functionality, analytics, communications,\n // fraud, advertising, personalization, account. Typical F2P game with an analytics SDK + ad mediation:\n dataSafety: {\n collectsData: true,\n encryptedInTransit: true,\n // No accounts: PSL_ACM_NONE. A guest account with a name picked on the device and a server token (no password, no\n // email): accounts { enabled: true, signUp: ['username'], ... } and ['PSL_ACM_USER_ID_OTHER_AUTH'] here (Play's\n // \"Username and other authentication\"; `storebound scan` proposes it). With accounts Play also requires the\n // delete-account URL (from accounts.deletionUrl). That page also answers \"can users request that their data is\n // deleted?\" with yes (dataDeletion: 'yes' | 'no' | 'auto90' only for apps without one). partialDeletion: true +\n // partialDeletionUrl when a page deletes data without deleting the account. `storebound check` compares every row with Play's\n // current form (cli/data/play-data-safety-form.csv).\n accountCreation: ['PSL_ACM_NONE'],\n data: {\n PSL_APPROX_LOCATION: { shared: true, collect: ['analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_USER_INTERACTION: { shared: true, collect: ['analytics', 'advertising'], share: ['analytics', 'advertising'] },\n PSL_OTHER_APP_ACTIVITY: { shared: false, collect: ['functionality'] },\n PSL_PERFORMANCE_DIAGNOSTICS: { shared: true, collect: ['analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_DEVICE_ID: { shared: true, collect: ['functionality', 'analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_PURCHASE_HISTORY: { shared: false, collect: ['functionality', 'fraud'] },\n },\n },\n\n // Ads: `storebound validate --play` checks /app-ads.txt for these lines (copy them from your mediation\n // dashboard's app-ads.txt page). Placeholder line below; replace it.\n // ads: { appAdsTxt: ['example-network.com, pub-0000000000000000, DIRECT, 0000000000000000'] },\n\n renders: 'store/renders',\n\n shots: {\n copy: 'store/shots/copy.json',\n frames: 'store/shots/frames', // /phone/.png, /tablet/.png\n out: 'store/renders',\n logo: 'store/shots/logo.png', // optional: hero scene + feature graphic\n // Google Fonts; both cover Latin Extended (tr, pl, cs, ro ...) and Vietnamese. `shots fonts` checks every glyph of the\n // copy; a character the font lacks needs a font that has it or fallback: ['Noto Sans Display'] (else shots check fails).\n fonts: { title: 'Paytone One', body: 'Montserrat' },\n // phone: { w: 440, h: 902, dpr: 3 }, // raw frame size in CSS px (screen below a 54 px status bar)\n // tablet: { w: 1032, h: 1352, dpr: 2 }, // default with apple.ipad (13\" iPad below its 24 px bar), else 800 x 1240\n scenes: [\n { id: 'hero', palette: 'fire', hero: true, over: 34, frames: [{ src: 'hero.png', rotate: -4 }],\n badges: [{ y: 0.42, side: 'l', icon: 'flag', iconBg: 'red', rot: -4 }, { y: 0.66, side: 'r', icon: 'offline', iconBg: 'red', rot: 3 }] },\n { id: 'play', palette: 'violet', frames: [{ src: 'gameplay.png', rotate: 3 }],\n badges: [{ y: 0.3, side: 'l', icon: 'bolt', iconBg: 'gold', rot: -3 }, { y: 0.7, side: 'r', hot: true, rot: 4 }] },\n { id: 'levels', palette: 'sky', frames: [{ src: 'level-b.png', scale: 0.82 }, { src: 'level-a.png', x: -31, dy: 10, scale: 0.7, rotate: -8 }, { src: 'level-c.png', x: 31, dy: 10, scale: 0.7, rotate: 8 }],\n badges: [{ y: 0.66, side: 'r', icon: 'map', iconBg: 'blue', rot: 3 }] },\n { id: 'stars', palette: 'gold', frames: [{ src: 'results.png', rotate: -3 }],\n badges: [{ y: 0.42, side: 'l', stars: true, rot: -3 }] },\n ],\n feature: { frame: 'hero.png', palette: 'fire' },\n capture: {\n baseUrl: 'http://127.0.0.1:5173',\n query: 'lang={lang}&noads=1&seed=1',\n shots: {\n 'hero': { path: '/?level=12', waitFor: \"window.game && game.state === 'playing'\", delayMs: 1500, device: 'both' },\n 'gameplay': { path: '/?level=3', delayMs: 2500, device: 'both' },\n 'level-a': { path: '/?level=20', delayMs: 2000 },\n 'level-b': { path: '/?level=40', delayMs: 2000 },\n 'level-c': { path: '/?level=60', delayMs: 2000 },\n 'results': { path: '/?level=5&result=3', delayMs: 2000, device: 'both' },\n },\n },\n },\n\n icons: {\n composite: 'store/icon/icon.png', // 1024 opaque\n foreground: 'store/icon/foreground.png', // 1024 RGBA, subject on transparent\n background: 'store/icon/background.png', // 1024 opaque\n out: 'store/icons',\n web: 'public/icons',\n // capacitorAssets: 'native/assets',\n // capacitorCommand: 'bunx @capacitor/assets generate --assetPath native/assets',\n // androidRes: 'native/android/app/src/main/res',\n },\n};\n\nexport default config;\n", + "storebound.config.ts": "// storebound config for one game. Everything game-specific lives here; credentials NEVER do (they go in env vars or\n// .storebound/credentials.json, which must stay gitignored). Paths are relative to this file.\n// The type import is optional: it only works when storebound is installed in the project (bun add -d ).\nimport type { ShipConfig } from 'storebound';\n\nconst config: ShipConfig = {\n // Every compliance answer below is the TEMPLATE's, not yours. While an area is listed here, check / validate block\n // and nothing sends it to a store. Derive the answers from the code (storebound scan --write; for an app that is\n // already live: storebound onboard --declarations), answer the rest, then remove the area from this list.\n unanswered: ['dataSafety', 'appPrivacy', 'reviewNotes', 'ageRating'],\n\n app: {\n name: 'Example Game',\n profile: 'game',\n copyright: '2026 Example Studio',\n privacyPolicyUrl: 'https://example.com/privacy',\n supportUrl: 'https://example.com',\n marketingUrl: 'https://example.com',\n // Developer website on Play: the same domain must serve /app-ads.txt if the game shows ads\n website: 'https://example.com',\n contactEmail: 'support@example.com',\n },\n\n // id = your folder / copy key; play = Play language code(s); apple = App Store Connect locale\n languages: [\n { id: 'en', play: 'en-US', apple: 'en-US' },\n { id: 'tr', play: 'tr-TR', apple: 'tr' },\n { id: 'es', play: ['es-ES', 'es-419'], apple: 'es-ES' },\n { id: 'ja', play: 'ja-JP', apple: 'ja' },\n { id: 'ar', play: 'ar', apple: 'ar-SA', rtl: true },\n ],\n\n play: {\n packageName: 'com.example.game',\n defaultLanguage: 'en-US',\n listing: 'store/listing.md',\n icon: 'store/icons/play-512.png',\n // read by `storebound scan` (fill in what is true for your account and app):\n // accountType: 'personal', accountCreated: 'YYYY-MM-DD', // new personal accounts: 12 testers x 14 days closed test\n // targetAges: ['13-15', '16-17', '18+'], // App content > Target audience; under 13 = Families policy\n },\n\n apple: {\n bundleId: 'com.example.game',\n // name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there (\"already being used\"); default app.name\n // appId: '1234567890', // Apple ID of the app record; looked up by bundle id when left out\n listing: 'store/appstore.md',\n reviewShots: 'store/iap-review',\n // Export compliance (export-compliance skill). false ONLY if the game uses no encryption beyond the OS (HTTPS through\n // the system). Left unset on purpose: decide it, then uncomment. Same answer as ITSAppUsesNonExemptEncryption.\n // usesNonExemptEncryption: false,\n // ipad: true, // the app runs on iPad: 13\" iPad screenshots (2064 x 2752, ipad13) are rendered, checked and uploaded\n // iphoneMedium: true, // optional 6.3\" iPhone set (1206 x 2622, iphone-medium); off: Apple scales the 6.5\" set down\n // screenshotTypes: ['APP_IPHONE_67'], // what `storebound validate` requires per locale (default; + APP_IPAD_PRO_3GEN_129 with ipad)\n // TestFlight (`storebound apple testflight`, testflight skill). Tester emails live in .storebound/testers.csv only.\n testflight: {\n groups: [\n { name: 'Team', internal: true, allBuilds: true },\n { name: 'Friends' },\n ],\n description: { en: 'Example Game beta: try the new levels and tell us what feels too hard.' },\n },\n info: {\n categories: { primary: 'GAMES', primarySubOne: 'GAMES_CASUAL', primarySubTwo: 'GAMES_PUZZLE', secondary: 'ENTERTAINMENT' },\n ageRating: { advertising: true }, // everything else NONE / false\n contentRights: 'DOES_NOT_USE_THIRD_PARTY_CONTENT',\n free: true,\n reviewNotes: [\n 'Single-player game. No account or login is needed; there is no user-generated content or chat.',\n 'In-app purchases: Home > Shop. Restore Purchases is in Settings.',\n 'Ads: optional rewarded videos and interstitials between rounds. The App Tracking Transparency prompt is shown before the ad SDK starts.',\n 'Privacy policy: Settings > Privacy.',\n // With remote config, feature flags or a remotely changed paywall (storebound scan warns, 2.3.1) you may add:\n // 'Shop offers and prices shown come from and change remotely; no feature is switched on or off after review.',\n ].join('\\n\\n'),\n },\n },\n\n // Price changes later for many products / regions: storebound prices export, edit store/prices.csv, prices import --dry.\n // prices: { csv: 'store/prices.csv', baseTerritory: 'USA' },\n\n // Same ids on both stores. Prices: USD base; Play converts per region, Apple equalizes from the USA. Overrides set a\n // region by hand (Apple needs an existing price point with exactly that value).\n products: [\n {\n id: 'com.example.game.remove_ads', type: 'non_consumable', usd: 2.99,\n overrides: [{ region: 'TR', currency: 'TRY', price: 99.99 }],\n listings: {\n en: { title: 'Remove Ads', description: 'Removes interstitial ads for good.' },\n tr: { title: 'Reklamları Kaldır', description: 'Ara reklamları kalıcı olarak kaldırır.' },\n },\n reviewScreenshot: 'store/iap-review/shop.png',\n },\n {\n id: 'com.example.game.coins_small', type: 'consumable', usd: 0.99,\n listings: {\n en: { title: '500 Coins', description: 'A small bag of coins.' },\n tr: { title: '500 Altın', description: 'Küçük bir kese altın.' },\n },\n reviewScreenshot: 'store/iap-review/shop.png',\n },\n ],\n\n // Google Play Data safety. Types not listed = not collected. Purposes: functionality, analytics, communications,\n // fraud, advertising, personalization, account. Typical F2P game with an analytics SDK + ad mediation:\n dataSafety: {\n collectsData: true,\n encryptedInTransit: true,\n // No accounts: PSL_ACM_NONE. A guest account with a name picked on the device and a server token (no password, no\n // email): accounts { enabled: true, signUp: ['username'], ... } and ['PSL_ACM_USER_ID_OTHER_AUTH'] here (Play's\n // \"Username and other authentication\"; `storebound scan` proposes it). With accounts Play also requires the\n // delete-account URL (from accounts.deletionUrl). That page also answers \"can users request that their data is\n // deleted?\" with yes (dataDeletion: 'yes' | 'no' | 'auto90' only for apps without one). partialDeletion: true +\n // partialDeletionUrl when a page deletes data without deleting the account. `storebound check` compares every row with Play's\n // current form (cli/data/play-data-safety-form.csv).\n accountCreation: ['PSL_ACM_NONE'],\n data: {\n PSL_APPROX_LOCATION: { shared: true, collect: ['analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_USER_INTERACTION: { shared: true, collect: ['analytics', 'advertising'], share: ['analytics', 'advertising'] },\n PSL_OTHER_APP_ACTIVITY: { shared: false, collect: ['functionality'] },\n PSL_PERFORMANCE_DIAGNOSTICS: { shared: true, collect: ['analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_DEVICE_ID: { shared: true, collect: ['functionality', 'analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_PURCHASE_HISTORY: { shared: false, collect: ['functionality', 'fraud'] },\n },\n },\n\n // Ads: `storebound validate --play` checks /app-ads.txt for these lines (copy them from your mediation\n // dashboard's app-ads.txt page). Placeholder line below; replace it.\n // ads: { appAdsTxt: ['example-network.com, pub-0000000000000000, DIRECT, 0000000000000000'] },\n\n renders: 'store/renders',\n\n shots: {\n copy: 'store/shots/copy.json',\n frames: 'store/shots/frames', // /phone/.png, /tablet/.png\n out: 'store/renders',\n logo: 'store/shots/logo.png', // optional: hero scene + feature graphic\n // Google Fonts; both cover Latin Extended (tr, pl, cs, ro ...) and Vietnamese. `shots fonts` checks every glyph of the\n // copy; a character the font lacks needs a font that has it or fallback: ['Noto Sans Display'] (else shots check fails).\n fonts: { title: 'Paytone One', body: 'Montserrat' },\n // phone: { w: 440, h: 902, dpr: 3 }, // raw frame size in CSS px (screen below a 54 px status bar)\n // tablet: { w: 1032, h: 1352, dpr: 2 }, // default with apple.ipad (13\" iPad below its 24 px bar), else 800 x 1240\n scenes: [\n { id: 'hero', palette: 'fire', hero: true, over: 34, frames: [{ src: 'hero.png', rotate: -4 }],\n badges: [{ y: 0.42, side: 'l', icon: 'flag', iconBg: 'red', rot: -4 }, { y: 0.66, side: 'r', icon: 'offline', iconBg: 'red', rot: 3 }] },\n { id: 'play', palette: 'violet', frames: [{ src: 'gameplay.png', rotate: 3 }],\n badges: [{ y: 0.3, side: 'l', icon: 'bolt', iconBg: 'gold', rot: -3 }, { y: 0.7, side: 'r', hot: true, rot: 4 }] },\n { id: 'levels', palette: 'sky', frames: [{ src: 'level-b.png', scale: 0.82 }, { src: 'level-a.png', x: -31, dy: 10, scale: 0.7, rotate: -8 }, { src: 'level-c.png', x: 31, dy: 10, scale: 0.7, rotate: 8 }],\n badges: [{ y: 0.66, side: 'r', icon: 'map', iconBg: 'blue', rot: 3 }] },\n { id: 'stars', palette: 'gold', frames: [{ src: 'results.png', rotate: -3 }],\n badges: [{ y: 0.42, side: 'l', stars: true, rot: -3 }] },\n ],\n feature: { frame: 'hero.png', palette: 'fire' },\n capture: {\n baseUrl: 'http://127.0.0.1:5173',\n query: 'lang={lang}&noads=1&seed=1',\n shots: {\n 'hero': { path: '/?level=12', waitFor: \"window.game && game.state === 'playing'\", delayMs: 1500, device: 'both' },\n 'gameplay': { path: '/?level=3', delayMs: 2500, device: 'both' },\n 'level-a': { path: '/?level=20', delayMs: 2000 },\n 'level-b': { path: '/?level=40', delayMs: 2000 },\n 'level-c': { path: '/?level=60', delayMs: 2000 },\n 'results': { path: '/?level=5&result=3', delayMs: 2000, device: 'both' },\n },\n },\n },\n\n icons: {\n composite: 'store/icon/icon.png', // 1024 opaque\n foreground: 'store/icon/foreground.png', // 1024 RGBA, subject on transparent\n background: 'store/icon/background.png', // 1024 opaque\n out: 'store/icons',\n web: 'public/icons',\n // capacitorAssets: 'native/assets',\n // capacitorCommand: 'bunx @capacitor/assets generate --assetPath native/assets',\n // androidRes: 'native/android/app/src/main/res',\n },\n};\n\nexport default config;\n", "testers.csv": "email,first_name,last_name,groups\n", "web/appstore.svg": "App Store", "web/googleplay.svg": "Google Play", diff --git a/cli/lib/scan/rules.ts b/cli/lib/scan/rules.ts index 861722a..1757172 100644 --- a/cli/lib/scan/rules.ts +++ b/cli/lib/scan/rules.ts @@ -44,7 +44,8 @@ import { itms91064, LISTED_SDKS, REQUIRED_REASON_APIS, trackingIssue, trackingPr import { IOS_PERMISSIONS, vaguePurpose } from './permissions'; import { playRules } from './play-rules'; import { grep, grepOwn, type Hit, lineOf, type ProjectFacts } from './project'; -import { versionAtLeast } from './sdks'; +import { matchesSdk, OBFUSCATORS, REMOTE_CODE, REMOTE_SDKS, type RemoteSdkDef, versionAtLeast } from './sdks'; +import { reviewNotes } from '../review-details'; export type Severity = 'blocker' | 'high' | 'medium' | 'low'; export type ScanStore = 'apple' | 'play'; @@ -199,6 +200,54 @@ function listingHits(file: { path: string; text: string } | undefined, re: RegEx return out; } +/** Review notes that already tell App Review about remote config, flags, experiments or remotely changed paywalls. */ +export const REMOTE_NOTE = /remote[ -]?config|feature[ -]?flags?|\bA\/B\b|paywall (tests?|experiments?|designs?)|experiments?\b|remotely/i; + +/** + * App Review 2.3.1 (hidden, dormant or undocumented features) and Play Deceptive Behavior: remote config / feature + * flag SDKs and remote paywalls in the dependencies or own sources, unless the review notes (apple.info.reviewNotes, + * reviewAccess.instructions, which also go to Play App access, accounts.inApp) mention them. Warns only: storebound + * never writes the note; whether and how to document it is the developer's call. Code obfuscators get a low note + * (minify / R8 alone never). Pure. + */ +export function remoteFeatureFindings(p: Pick, c: ShipConfig | null, stores: { apple: boolean; play: boolean }): ScanFinding[] { + const out: ScanFinding[] = []; + const found = new Map(); + const put = (id: string, name: string, kind: RemoteSdkDef['kind'], hits: Hit[]) => { + if (!hits.length) return; + const e = found.get(id) ?? { name, kind, hits: [] }; + e.hits.push(...hits); + found.set(id, e); + }; + for (const s of REMOTE_SDKS) { + const deps = p.deps.filter(d => matchesSdk(d, s)); + if (!deps.length) continue; + if (s.needsCode && !grepOwn(p, codeLine(s.needsCode), 1).hits.length) continue; + put(s.id, s.name, s.kind, deps.slice(0, 2).map(d => ({ file: d.file, line: d.line, text: `${s.name}: ${d.name}${d.version ? ` ${d.version}` : ''}` }))); + } + for (const s of REMOTE_CODE) if (!found.has(s.id)) put(s.id, s.name, s.kind, grepOwn(p, codeLine(s.re), 1).hits); + if (found.size && !REMOTE_NOTE.test(c ? reviewNotes(c) : '')) { + const list = [...found.values()]; + const names = list.map(x => x.name).join(', '); + const paywall = list.some(x => x.kind === 'paywall'); + const what = paywall && list.some(x => x.kind === 'remote-config') ? 'remote config / feature flags and remote paywalls' : paywall ? 'remote paywalls' : 'remote config / feature flags'; + const evidence = list.flatMap(x => x.hits.slice(0, 1)).slice(0, 4); + const fix = (where: string) => `Say in the review notes that paywall designs / prices shown / these flags change remotely (${names}), and document any feature that can be switched on or off remotely; a change of business model (soft -> hard paywall, features moved behind a subscription) needs a new review and a description update (paid functionality must be disclosed). Paywall tests and designs alone are fine once App Review knows. ${where}`; + if (stores.apple) + out.push({ rule: 'remote-features', guideline: '2.3.1', store: 'apple', severity: 'medium', title: `${what} (${names}) not mentioned in the App Review notes`, evidence, + fix: fix(`Notes: apple.info.reviewNotes, sent with storebound apple review-details; ${consoleLink('asc.version', '> App Review Information')}.`), url: consoleUrl('asc.version'), skill: 'review-rejections', ref: APPLE_GUIDELINES }); + if (stores.play) + out.push({ rule: 'remote-features', guideline: 'Play: Deceptive behavior', store: 'play', severity: 'medium', title: `${what} (${names}) not mentioned to Play review`, evidence, + fix: fix(`Play: reviewAccess.instructions go to ${consoleLink('play.app-access')} ("Any other information"), and the listing description must match what the app does.`), url: consoleUrl('play.app-access'), skill: 'review-rejections', ref: PLAY_POLICY }); + } + const obf = OBFUSCATORS.flatMap(o => p.deps.filter(d => matchesSdk(d, o)).slice(0, 1).map(d => ({ file: d.file, line: d.line, text: `${o.name}: ${d.name}` }))); + if (obf.length) for (const store of (['apple', 'play'] as const).filter(s => stores[s])) + out.push({ rule: 'obfuscation', guideline: store === 'apple' ? '2.3.1' : 'Play: Deceptive behavior', store, severity: 'low', title: 'Code obfuscator in the build: fine for protecting code, never for hiding features from review', evidence: obf.slice(0, 3), + fix: 'Note only: obfuscating code is allowed, hiding behaviour with it is not (Apple 2.3.1 names obfuscation as grounds for removal). Make sure every feature the app has is visible to the reviewer and in the review notes. ProGuard / R8 minify alone is normal.', + skill: 'review-rejections', ref: store === 'apple' ? APPLE_GUIDELINES : PLAY_POLICY }); + return out; +} + export function scanRules(inp: ScanInput): ScanFinding[] { const { facts: p, config: c } = inp; const out: ScanFinding[] = []; @@ -587,6 +636,9 @@ export function scanRules(inp: ScanInput): ScanFinding[] { fix: 'Pick your own reverse-domain package name (it can never change after the first upload) and set it in the Gradle applicationId and play.packageName.', skill: 'play-first-release', ref: 'https://developer.android.com/build/configure-app-module' }); + // ---- remotely switchable features, remote paywalls, obfuscation (2.3.1, Play Deceptive behavior) ---- + out.push(...remoteFeatureFindings(p, c, { apple, play })); + // ---- the other Google Play policies (play-rules.ts) ---- if (play) playRules(inp, { add: f => add({ ...f, store: 'play' }), cfg, sdkHits, listingHits, creates, restorable, paySdk }); diff --git a/cli/lib/scan/sdks.ts b/cli/lib/scan/sdks.ts index 36de524..078776d 100644 --- a/cli/lib/scan/sdks.ts +++ b/cli/lib/scan/sdks.ts @@ -181,11 +181,80 @@ export const SDKS: SdkDef[] = [ match: { npm: ['@capacitor/push-notifications', 'expo-notifications', '@react-native-community/push-notification-ios', 'react-native-push-notification'], pub: ['flutter_local_notifications'], unity: ['com.unity.mobile.notifications'] } }, ]; +// ---- remotely switchable features and remote paywalls (App Review 2.3.1, Play Deceptive Behavior) ---- +// Not in SDKS: they add no data types of their own to the declarations; scan only asks that App Review hears about +// them. Checked 2026-10-18 against each vendor's install docs. +export interface RemoteSdkDef { + id: string; + name: string; + /** remote-config: feature flags / remote config / experiments; paywall: paywall designs, offers or prices set remotely. */ + kind: 'remote-config' | 'paywall'; + match: Partial>; + /** Only with this in the own sources (an SDK that also does other things, e.g. PostHog analytics). */ + needsCode?: RegExp; + docs: string; +} + +export const REMOTE_SDKS: RemoteSdkDef[] = [ + { id: 'firebase-remote-config', name: 'Firebase Remote Config', kind: 'remote-config', docs: 'https://firebase.google.com/docs/remote-config', + match: { cocoapods: ['FirebaseRemoteConfig', 'Firebase/RemoteConfig'], spm: ['firebase-ios-sdk#FirebaseRemoteConfig'], gradle: ['com.google.firebase:firebase-config', 'com.google.firebase:firebase-config-ktx'], + npm: ['@react-native-firebase/remote-config', '@capacitor-firebase/remote-config'], pub: ['firebase_remote_config'], unity: ['com.google.firebase.remote-config', 'FirebaseRemoteConfig'] } }, + { id: 'statsig', name: 'Statsig', kind: 'remote-config', docs: 'https://docs.statsig.com/', + match: { cocoapods: ['Statsig'], spm: ['statsig-kit'], gradle: ['com.statsig:android-sdk'], npm: ['statsig-react-native', 'statsig-js', '@statsig/js-client', '@statsig/react-native-bindings', '@statsig/expo-bindings'], pub: ['statsig'] } }, + { id: 'launchdarkly', name: 'LaunchDarkly', kind: 'remote-config', docs: 'https://docs.launchdarkly.com/sdk', + match: { cocoapods: ['LaunchDarkly'], spm: ['launchdarkly/ios-client-sdk'], gradle: ['com.launchdarkly:launchdarkly-android-client-sdk'], + npm: ['@launchdarkly/react-native-client-sdk', 'launchdarkly-react-native-client-sdk', 'launchdarkly-js-client-sdk', '@launchdarkly/js-client-sdk'], pub: ['launchdarkly_flutter_client_sdk'] } }, + { id: 'growthbook', name: 'GrowthBook', kind: 'remote-config', docs: 'https://docs.growthbook.io/', + match: { cocoapods: ['GrowthBook-IOS'], spm: ['growthbook-swift'], gradle: ['io.growthbook.sdk:GrowthBook'], npm: ['@growthbook/growthbook', '@growthbook/growthbook-react'], pub: ['growthbook_sdk_flutter'] } }, + { id: 'optimizely', name: 'Optimizely', kind: 'remote-config', docs: 'https://docs.developers.optimizely.com/feature-experimentation/docs', + match: { cocoapods: ['OptimizelySwiftSDK'], spm: ['optimizely/swift-sdk'], gradle: ['com.optimizely.ab:android-sdk'], npm: ['@optimizely/react-sdk', '@optimizely/optimizely-sdk', '@optimizely/react-native-sdk'], pub: ['optimizely_flutter_sdk'] } }, + { id: 'posthog-flags', name: 'PostHog feature flags', kind: 'remote-config', docs: 'https://posthog.com/docs/feature-flags', + needsCode: /\b(isFeatureEnabled|getFeatureFlag|getFeatureFlagPayload|useFeatureFlag|useFeatureFlagEnabled|onFeatureFlags|reloadFeatureFlags)\b/, + match: { cocoapods: ['PostHog'], spm: ['posthog-ios'], gradle: ['com.posthog:posthog-android', 'com.posthog.android:posthog'], npm: ['posthog-react-native', 'posthog-js'], pub: ['posthog_flutter'] } }, + { id: 'unleash', name: 'Unleash', kind: 'remote-config', docs: 'https://docs.getunleash.io/', + match: { cocoapods: ['UnleashProxyClientSwift'], spm: ['unleash-proxy-client-swift'], gradle: ['io.getunleash:unleash-android'], npm: ['unleash-proxy-client', '@unleash/proxy-client-react'], pub: ['unleash_proxy_client_flutter'] } }, + { id: 'configcat', name: 'ConfigCat', kind: 'remote-config', docs: 'https://configcat.com/docs/', + match: { cocoapods: ['ConfigCat'], spm: ['configcat/swift-sdk'], gradle: ['com.configcat:configcat-android-client'], npm: ['configcat-js', 'configcat-react', 'configcat-js-ssr', '@configcat/sdk'], pub: ['configcat_client'] } }, + { id: 'amplitude-experiment', name: 'Amplitude Experiment', kind: 'remote-config', docs: 'https://amplitude.com/docs/feature-experiment', + match: { cocoapods: ['AmplitudeExperiment'], spm: ['experiment-ios-client'], gradle: ['com.amplitude:experiment-android-client'], npm: ['@amplitude/experiment-js-client', '@amplitude/experiment-react-native-client'] } }, + { id: 'split', name: 'Split', kind: 'remote-config', docs: 'https://help.split.io/', + match: { cocoapods: ['Split'], spm: ['splitio/ios-client'], gradle: ['io.split.client:android-client'], npm: ['@splitsoftware/splitio', '@splitsoftware/splitio-react-native', '@splitsoftware/splitio-react'], pub: ['splitio'] } }, + // paywalls whose design, products or prices are set from a dashboard + { id: 'revenuecat-paywalls', name: 'RevenueCat Paywalls', kind: 'paywall', docs: 'https://www.revenuecat.com/docs/tools/paywalls', + match: { cocoapods: ['RevenueCatUI'], spm: ['purchases-ios#RevenueCatUI'], gradle: ['com.revenuecat.purchases:purchases-ui'], npm: ['react-native-purchases-ui', '@revenuecat/purchases-capacitor-ui'], pub: ['purchases_ui_flutter'] } }, + { id: 'superwall', name: 'Superwall', kind: 'paywall', docs: 'https://superwall.com/docs', + match: { cocoapods: ['SuperwallKit'], spm: ['Superwall-iOS'], gradle: ['com.superwall.sdk:superwall-android'], npm: ['@superwall/react-native-superwall', 'expo-superwall'], pub: ['superwallkit_flutter'] } }, + { id: 'adapty', name: 'Adapty (paywall builder)', kind: 'paywall', docs: 'https://adapty.io/docs/', + match: { cocoapods: ['Adapty', 'AdaptyUI'], spm: ['AdaptySDK-iOS'], gradle: ['io.adapty:android-sdk', 'io.adapty:android-ui'], npm: ['react-native-adapty', '@adapty/capacitor', '@adapty/react-native-ui'], pub: ['adapty_flutter', 'adapty_ui_flutter'], unity: ['com.adapty.unity', 'AdaptySDK'] } }, + { id: 'qonversion', name: 'Qonversion', kind: 'paywall', docs: 'https://documentation.qonversion.io/', + match: { cocoapods: ['Qonversion'], spm: ['qonversion-ios-sdk'], gradle: ['io.qonversion.android.sdk:sdk', 'io.qonversion:sdk'], npm: ['react-native-qonversion', '@qonversion/capacitor-plugin'], pub: ['qonversion_flutter'] } }, + { id: 'purchasely', name: 'Purchasely', kind: 'paywall', docs: 'https://docs.purchasely.com/', + match: { cocoapods: ['Purchasely'], spm: ['Purchasely-iOS'], gradle: ['io.purchasely:core'], npm: ['react-native-purchasely', '@purchasely/cordova-plugin-purchasely'], pub: ['purchasely_flutter'] } }, + { id: 'apphud', name: 'Apphud', kind: 'paywall', docs: 'https://docs.apphud.com/', + match: { cocoapods: ['ApphudSDK'], spm: ['ApphudSDK'], gradle: ['com.apphud:ApphudSDK-Android'], npm: ['@apphud/react-native-apphud-sdk', 'react-native-apphud-sdk'], pub: ['apphud'] } }, +]; + +/** Remote config / paywall use in the own sources without a listed dependency (the web Firebase SDK, a RevenueCat + * paywall presented from the core package). Line-anchored code, never an import line. */ +export const REMOTE_CODE: { id: string; name: string; kind: RemoteSdkDef['kind']; re: RegExp }[] = [ + { id: 'firebase-remote-config', name: 'Firebase Remote Config', kind: 'remote-config', re: /\bgetRemoteConfig\(|\bfetchAndActivate\(|\bremoteConfig\(\)\.|RemoteConfig\.remoteConfig\(\)|FirebaseRemoteConfig\.(getInstance|instance)\b|\bFirebase\.RemoteConfig\b/ }, + { id: 'revenuecat-paywalls', name: 'RevenueCat Paywalls', kind: 'paywall', re: /\bpresentPaywall(IfNeeded)?\b|\bRevenueCatUI\b|\bpaywallFooter\(|\bPaywallView\(/ }, +]; + +/** Code obfuscators that hide what the app does (not plain minify: ProGuard / R8 shrinking is normal on Android). */ +export const OBFUSCATORS: { name: string; match: Partial> }[] = [ + { name: 'DexGuard', match: { gradle: ['com.guardsquare.dexguard', 'com.guardsquare:dexguard-gradle-plugin', 'dexguard'] } }, + { name: 'iXGuard', match: { cocoapods: ['iXGuard'] } }, + { name: 'JavaScript obfuscator', match: { npm: ['javascript-obfuscator', 'react-native-obfuscating-transformer', 'obfuscator-io-metro-plugin', 'webpack-obfuscator', 'vite-plugin-javascript-obfuscator', 'rollup-plugin-obfuscator'] } }, + { name: 'Beebyte Obfuscator', match: { unity: ['Beebyte'] } }, + { name: 'SwiftShield', match: { cocoapods: ['SwiftShield'], spm: ['swiftshield'] } }, +]; + export interface DepRef { eco: Eco; name: string; version: string | null; file: string; line: number } /** Does a dependency match an SDK? Pods match by name or "Name/Sub"; Gradle by "group:artifact" or a "group:" prefix; * SPM by URL fragment (or "url#Product" for one product of a multi-product repository, matched on the product). */ -export function matchesSdk(d: DepRef, s: SdkDef): boolean { +export function matchesSdk(d: DepRef, s: Pick): boolean { const list = s.match[d.eco] ?? []; const n = d.name; return list.some(m => { diff --git a/docs/pitfalls.md b/docs/pitfalls.md index 638eba3..85d33d1 100644 --- a/docs/pitfalls.md +++ b/docs/pitfalls.md @@ -9,6 +9,7 @@ fails without the fix. | # | date | lesson | guard | |---|---|---|---| +| 74 | 2026-10 | Apple sharpened Guideline 2.3.1 (hidden, dormant or undocumented features; obfuscation that hides features is grounds for removal). Apps with remote config / feature flags or remote paywalls whose review notes said nothing risk a rejection or removal when a feature or a hard paywall is switched on after review; Play's Deceptive behavior policy covers the same. Paywall tests and designs are fine once review knows; a business-model change needs a new review and a description update. | `remoteFeatureFindings` (`cli/lib/scan/rules.ts`, SDK table `REMOTE_SDKS` in `cli/lib/scan/sdks.ts`): scan / validate report `remote-features` for Apple (2.3.1) and Play (Deceptive behavior), medium, unless the review notes (apple.info.reviewNotes, reviewAccess.instructions, accounts.inApp) mention remote config, flags, A/B, a paywall test, an experiment or "remotely"; check prints it as a warning. Warn only: storebound never writes the note; the templates carry a commented example line. Code obfuscators are a low note, minify alone nothing. `tests/remote-features.test.ts`. | | 73 | 2026-10 | A game with guest play (no sign-in; `reviewAccess.signInRequired: false`, Play Sign in details "No restrictions") was rejected by Play: "Play Console Requirements: provide valid login credentials". The first screen had an empty player-name field with Continue disabled until a name was typed and an "I Have a Code" link to a transfer / recovery code dialog; the reviewer read it as a login wall. | `profileIssues` (`cli/lib/profile.ts`, called by `check` with `SIGNALS.firstRunGate` hits from `cli/lib/scan/rules.ts`): warns "Play may reject as a login wall; add guest steps" for a Play app with a first-run gate or IAP and no `reviewAccess.instructions`, and when the steps exceed 500 characters. The `play-sign-in-details` plan (`cli/lib/console-play-plans.ts`): with guest steps "restricted" and one entry "Guest play (no account needed)" without credentials, the steps in "Any other information", the dialog's required full-access box as an owner step; Add and Save the agent's. `tests/guest-login-wall.test.ts`. | | 72 | 2026-10 | A game: after Play production 1.0.0 (3) was rejected (Broken Functionality), the fix 1.0.1 (5) went through upload and track updates, then edits.validate answered 400 "Changes cannot be sent for review automatically. Please set the query parameter changesNotSentForReview to true". Play refuses the automatic send after a rejection, with other pending changes or managed publishing. | `cli/play/client.ts` (edit flow) with `cli/play/review-pending.ts`: on exactly that 400 the same edit is validated and committed again with changesNotSentForReview=true (a dry run validates that way and says so), the Publishing overview deep link is printed (the owner's button), the commit is recorded in .storebound/ and `play status` shows it; `--not-sent-for-review` on play release / upload / rollout / listing / images (MCP `not_sent_for_review`). `tests/play-not-sent-for-review.test.ts`. Only edits.commit takes changesNotSentForReview: validate answers 400 "Unknown name ... Cannot bind query parameter" (the fake store does too). | | 71 | 2026-10 | Messages sent the owner to console pages as plain text paths ("App Store Connect > App Information > Age Rating", "Play Console > App content") without a link; the owner had to find the app and the page by hand. | `cli/lib/console-links.ts`: every message carries the absolute deep link (app list / developer chooser when ids are unknown), `url` in finding JSON, an Open button in the desktop; `tests/console-links.test.ts` fails on a console path in cli/ or templates/ without an https URL; agent rule 11 in AGENTS.md. | diff --git a/skills/review-rejections/SKILL.md b/skills/review-rejections/SKILL.md index bf928e0..2648094 100644 --- a/skills/review-rejections/SKILL.md +++ b/skills/review-rejections/SKILL.md @@ -87,6 +87,9 @@ Plain, polite, specific; one guideline per paragraph; no blame, no threats, no " - **2.3 Accurate metadata**: screenshots must show the real app (for a game: real gameplay); no prices, no "free" claims for paid items, no other platforms' UI; keywords without competitor names; age rating answers that match the content. +- **2.3.1 Hidden or undocumented features** (Play: Deceptive behavior): remote config, feature flags or a remote + paywall the review notes did not mention (`storebound scan` rule `remote-features`, store-pitfalls 74). Fix: say in + the notes which SDK changes what remotely; a business-model change needs a new review and a description update. - **3.1.1 In-app purchase**: digital goods only through IAP; a visible **Restore Purchases** for non-consumables; no links to outside payment; loot boxes must show odds. - **3.1.2 Subscriptions**: the purchase screen shows title, length, price per period and what the user gets; links to diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 28a176b..8458b2d 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -877,3 +877,25 @@ that fails without the fix (see CONTRIBUTING.md). in-app purchases and no `reviewAccess.instructions`, and when the steps are longer than 500 characters (`cli/lib/profile.ts`). The plan's guest path is in `cli/lib/console-play-plans.ts` (`signInDetails`); `tests/guest-login-wall.test.ts`. + +## 74. Remote config and remote paywalls read as hidden features (2.3.1) +- **Symptom:** App Review rejects or removes an app under Guideline 2.3.1 (hidden, dormant or undocumented features), + or Play flags Deceptive behavior, after a feature or a hard paywall was switched on remotely, or the reviewer saw a + different paywall than the one users get. +- **Cause:** remote config / feature flag SDKs (Firebase Remote Config, Statsig, LaunchDarkly, GrowthBook, Optimizely, + PostHog feature flags, Unleash, ConfigCat, Amplitude Experiment, Split) and remote paywalls (RevenueCat Paywalls, + Superwall, Adapty, Qonversion, Purchasely, Apphud) change what the app does after review, and the review notes said + nothing. Paywall tests and designs are not features and are fine once App Review knows; a business-model change + (soft -> hard paywall, freemium -> premium, features moved behind a subscription) or functionality enabled after + review is a feature change. +- **Do:** this is the developer's call; storebound only warns. Suggest a line in `apple.info.reviewNotes` (and + `reviewAccess.instructions`, which also go to Play App access) that names the SDK and what changes remotely + (paywall designs, prices shown, which flags), document every feature that can be switched on or off, and send a + business-model change as a new review with a description that discloses what needs a paid subscription. Never + write the note into the developer's config or code yourself. +- **Guard:** `storebound scan` (and `validate`, which runs it; `check` prints it as a warning) reports `remote-features` + for Apple (2.3.1) and Play (Deceptive behavior), medium, with the deep links, unless the review notes mention remote + config, a feature flag, A/B, a paywall test, an experiment or "remotely" (`remoteFeatureFindings` in + `cli/lib/scan/rules.ts`, the SDK table `REMOTE_SDKS` in `cli/lib/scan/sdks.ts`). A code obfuscator (DexGuard, + iXGuard, a JavaScript obfuscator) is a low `obfuscation` note; ProGuard / R8 minify alone is never reported. + `tests/remote-features.test.ts`. diff --git a/skills/store-subscriptions/SKILL.md b/skills/store-subscriptions/SKILL.md index 88c223c..ca2179e 100644 --- a/skills/store-subscriptions/SKILL.md +++ b/skills/store-subscriptions/SKILL.md @@ -59,6 +59,9 @@ offers, offerCodes, reviewScreenshot, basePlanId, gracePeriod, platforms }] }]`, Agreement; the privacy policy URL field (`storebound apple listing`). `validate` warns when a description has no Terms link. 3.1.2(a): a subscription must give ongoing value and last at least 7 days. - Review notes: where the paywall is, that the demo account can buy in the sandbox (`review-access`). +- Remote paywalls (RevenueCat Paywalls, Superwall, Adapty, Qonversion, Purchasely, Apphud) or flags: say in the review + notes that paywall designs / prices shown change remotely (2.3.1, `scan` warns; store-pitfalls 74); moving features + behind the subscription after review needs a new review and a description that discloses it. ## Gotchas - A product id, a billing period or a subscription's group cannot change; make a new id. diff --git a/templates/profiles/app/storebound.config.ts b/templates/profiles/app/storebound.config.ts index 8286c34..f5db7e0 100644 --- a/templates/profiles/app/storebound.config.ts +++ b/templates/profiles/app/storebound.config.ts @@ -70,6 +70,8 @@ const config: ShipConfig = { reviewNotes: [ 'Example App keeps lists and notes in sync across devices. An account is optional on the first screen.', 'Privacy policy and Terms: Settings > About.', + // With remote config or feature flags (storebound scan warns, 2.3.1) you may add a line like: + // 'Some features are configured remotely with : ; none is switched on after review without a new submission.', ].join('\n\n'), }, }, diff --git a/templates/profiles/subscription-app/storebound.config.ts b/templates/profiles/subscription-app/storebound.config.ts index 8af8a0f..4277289 100644 --- a/templates/profiles/subscription-app/storebound.config.ts +++ b/templates/profiles/subscription-app/storebound.config.ts @@ -71,6 +71,8 @@ const config: ShipConfig = { 'Example App keeps lists and notes in sync across devices. Pro (yearly with a 1-week free trial, or monthly) unlocks unlimited lists, sharing and themes.', 'Subscriptions: Settings > Pro (or the paywall after the third list). Restore Purchases is on the paywall and in Settings > Pro.', 'Privacy policy and Terms of Use: on the paywall and in Settings > About.', + // With a remote paywall or feature flags (storebound scan warns, 2.3.1) you may add a line like: + // 'Paywall designs and the prices shown are tested remotely with ; what Pro unlocks does not change after review.', ].join('\n\n'), }, }, diff --git a/templates/storebound.config.ts b/templates/storebound.config.ts index 839589a..aceb998 100644 --- a/templates/storebound.config.ts +++ b/templates/storebound.config.ts @@ -70,6 +70,8 @@ const config: ShipConfig = { 'In-app purchases: Home > Shop. Restore Purchases is in Settings.', 'Ads: optional rewarded videos and interstitials between rounds. The App Tracking Transparency prompt is shown before the ad SDK starts.', 'Privacy policy: Settings > Privacy.', + // With remote config, feature flags or a remotely changed paywall (storebound scan warns, 2.3.1) you may add: + // 'Shop offers and prices shown come from and change remotely; no feature is switched on or off after review.', ].join('\n\n'), }, }, diff --git a/tests/remote-features.test.ts b/tests/remote-features.test.ts new file mode 100644 index 0000000..7c14b33 --- /dev/null +++ b/tests/remote-features.test.ts @@ -0,0 +1,80 @@ +// App Review 2.3.1 / Play Deceptive behavior: remote config, feature flags and remote paywalls must be told to review. +// scan warns (Apple and Play) unless the review notes mention them; storebound never writes the note itself. Minify +// alone is never a finding; a code obfuscator is a low note. +import { afterAll, describe, expect, test } from 'bun:test'; +import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { ShipConfig } from '../cli/lib/config'; +import { runScan } from '../cli/lib/scan'; +import { detectProject } from '../cli/lib/scan/project'; +import { remoteFeatureFindings } from '../cli/lib/scan/rules'; + +const dirs: string[] = []; +afterAll(() => { for (const d of dirs) rmSync(d, { recursive: true, force: true }); }); + +/** A tiny app: Podfile.lock pods, Gradle dependencies and own sources. */ +function app(o: { pods?: string[]; gradle?: string[]; src?: string; minify?: boolean }): string { + const d = mkdtempSync(join(tmpdir(), 'sb-remote-')); + dirs.push(d); + if (o.pods) writeFileSync(join(d, 'Podfile.lock'), `PODS:\n${o.pods.map(p => ` - ${p} (11.0.0)`).join('\n')}\n\nDEPENDENCIES:\n${o.pods.map(p => ` - ${p}`).join('\n')}\n\nCOCOAPODS: 1.15.2\n`); + mkdirSync(join(d, 'android/app'), { recursive: true }); + writeFileSync(join(d, 'android/app/build.gradle.kts'), [ + 'plugins { id("com.android.application") }', + 'android {', ' namespace = "com.example.app"', ' compileSdk = 36', + ' defaultConfig { applicationId = "com.example.app"; minSdk = 24; targetSdk = 36 }', + ` buildTypes { release { isMinifyEnabled = ${o.minify ? 'true' : 'false'}; proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") } }`, + '}', + 'dependencies {', ...(o.gradle ?? []).map(g => ` implementation("${g}")`), '}', ''].join('\n')); + if (o.src) { mkdirSync(join(d, 'src'), { recursive: true }); writeFileSync(join(d, 'src/App.swift'), o.src); } + return d; +} +const cfg = (notes?: string, instructions?: string) => ({ apple: { info: { reviewNotes: notes } }, play: { packageName: 'com.example.app' }, reviewAccess: instructions ? { signInRequired: false, instructions } : undefined }) as unknown as ShipConfig; +const both = { apple: true, play: true }; +const rules = (dir: string, c: ShipConfig | null) => remoteFeatureFindings(detectProject(dir), c, both); + +describe('remote features (2.3.1)', () => { + test('Firebase Remote Config without a review note: an Apple and a Play finding with deep links', () => { + const d = app({ pods: ['FirebaseRemoteConfig'], gradle: ['com.google.firebase:firebase-config:22.0.0'] }); + const f = rules(d, cfg('Single-player game. No account needed.')); + expect(f.map(x => `${x.store} ${x.rule} ${x.guideline} ${x.severity}`).sort()).toEqual(['apple remote-features 2.3.1 medium', 'play remote-features Play: Deceptive behavior medium']); + const apple = f.find(x => x.store === 'apple')!; + expect(apple.title).toContain('Firebase Remote Config'); + expect(apple.fix).toContain('soft -> hard paywall'); + expect(apple.url).toStartWith('https://appstoreconnect.apple.com/'); + expect(f.find(x => x.store === 'play')!.fix).toContain('App access'); + expect(apple.evidence.map(e => e.file)).toContain('Podfile.lock'); + }); + test('the same app with a note that mentions remote config: no finding', () => { + const d = app({ pods: ['FirebaseRemoteConfig'], gradle: ['com.google.firebase:firebase-config:22.0.0'] }); + expect(rules(d, cfg('Shop prices and the paywall design come from Firebase Remote Config and can change remotely.'))).toEqual([]); + expect(rules(d, cfg(undefined, 'No sign-in. Feature flags: the daily event can be switched on remotely.'))).toEqual([]); + }); + test('Superwall: a remote paywall finding', () => { + const d = app({ pods: ['SuperwallKit'] }); + const f = rules(d, cfg('A photo app.')); + expect(f.filter(x => x.rule === 'remote-features').map(x => x.store).sort()).toEqual(['apple', 'play']); + expect(f[0]!.title).toStartWith('remote paywalls (Superwall)'); + }); + test('RevenueCat paywall presented from code, Firebase web Remote Config from code, PostHog only with flag calls', () => { + expect(rules(app({ src: 'func show() {\n let v = PaywallView(offering: o)\n}\n' }), cfg('x'))[0]?.title).toContain('RevenueCat Paywalls'); + expect(rules(app({ src: 'const rc = getRemoteConfig(app);\n' }), cfg('x'))[0]?.title).toContain('Firebase Remote Config'); + expect(rules(app({ pods: ['PostHog'] }), cfg('x'))).toEqual([]); + expect(rules(app({ pods: ['PostHog'], src: 'if posthog.isFeatureEnabled("new-shop") { open() }\n' }), cfg('x'))[0]?.title).toContain('PostHog feature flags'); + }); + test('no such SDK: no finding; minify alone: no finding; an obfuscator: a low note, never an error', () => { + expect(rules(app({ pods: ['GoogleSignIn'], gradle: ['androidx.core:core-ktx:1.13.1'] }), null)).toEqual([]); + expect(rules(app({ gradle: ['androidx.core:core-ktx:1.13.1'], minify: true }), cfg('x'))).toEqual([]); + const o = rules(app({ pods: ['iXGuard'] }), cfg('x')); + expect(o.map(x => `${x.rule} ${x.severity}`)).toEqual(['obfuscation low', 'obfuscation low']); + }); + test('scan and validate carry it: the clean fixture plus Firebase Remote Config', async () => { + const d = mkdtempSync(join(tmpdir(), 'sb-remote-clean-')); + dirs.push(d); + cpSync(join(import.meta.dir, 'fixtures/scan/clean'), d, { recursive: true }); + const lock = join(d, 'Podfile.lock'); + writeFileSync(lock, readFileSync(lock, 'utf8').replace(' - GoogleSignIn (7.1.0)', ' - GoogleSignIn (7.1.0)\n - FirebaseRemoteConfig (11.0.0)')); + const f = (await runScan(d)).report.findings.filter(x => x.rule === 'remote-features'); + expect(f.map(x => x.store).sort()).toEqual(['apple', 'play']); + }); +}); From 5a266b952f4a8ee7938595e7364f38dcd0b4aa06 Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 18 Oct 2026 01:29:36 +0800 Subject: [PATCH 011/344] templates: the 2.3.1 example line says where the same goes on Google Play (no review-notes field: App access 'Any other information' with a sign-in, and the full description for what needs a subscription) --- cli/lib/embedded.ts | 6 +++--- templates/profiles/app/storebound.config.ts | 3 +++ templates/profiles/subscription-app/storebound.config.ts | 3 +++ templates/storebound.config.ts | 3 +++ 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/cli/lib/embedded.ts b/cli/lib/embedded.ts index 7ef0ac0..77d5b79 100644 --- a/cli/lib/embedded.ts +++ b/cli/lib/embedded.ts @@ -17,16 +17,16 @@ export const TEMPLATE_TEXT: Record = { "profiles/app/listing.md": "# Example App · Google Play listing copy\n\nSource for `storebound play listing` (title, short + full description) and `storebound play release` (release notes).\nRules the parser follows:\n- every `## ...` section with a `` line is a listing; one section can serve several Play codes\n- under it, `### ...` headings that contain **title** (optional, defaults to `app.name`), **short**, **full** and\n **what's new**, each followed by one fenced block\n- limits (checked before anything is sent): title 30, short 80, full 4000, what's new 500 characters\nOnly claim what the app really does. No prices, no \"best / #1\", no other apps' names.\n\n---\n\n## English (en-US)\n\n\n### Play short description (max 80)\n```\nWhat the app does for people, in one plain line\n```\n\n### Play full description (max 4000)\n```\nFirst paragraph: the job the app does and why it is easier with it, in two or three sentences.\n\nFEATURES\n• Lists and notes that sync across your devices\n• Share a list with family or friends\n• Export your data or delete your account in Settings, any time\n\nFree to use. An account is optional and only needed for sync and sharing.\n```\n\n### What's new (max 500)\n```\nFirst release. Thanks for trying it!\n```\n\n## Türkçe (tr-TR)\n\n\n### Play kısa açıklama · short (max 80)\n```\nUygulamanın insanlar için ne yaptığını anlatan sade bir cümle\n```\n\n### Play tam açıklama · full (max 4000)\n```\nİlk paragraf: uygulamanın gördüğü iş ve onunla neden daha kolay olduğu, iki üç cümlede.\n\nÖZELLİKLER\n• Tüm cihazlarında eşitlenen listeler ve notlar\n• Bir listeyi ailen ya da arkadaşlarınla paylaş\n• Verilerini dışa aktar ya da hesabını Ayarlar'dan istediğin an sil\n\nÜcretsiz. Hesap isteğe bağlıdır; yalnızca eşitleme ve paylaşım için gerekir.\n```\n\n### Yenilikler · what's new (max 500)\n```\nİlk sürüm. Denediğin için teşekkürler!\n```\n", "profiles/app/privacy-policy.html": "\n\n\n\n\nPrivacy Policy · Example Studio\n\n\n\n\n
\n \n\n
\n

Privacy Policy

\n

Example Studio · applies to all our apps · last updated 2026-01-01

\n\n

We collect what an app needs to work for you, never sell personal data and show no ads. This page explains what\n each app collects, why, and what you can do about it.

\n\n

What our apps use

\n
\n \n \n \n \n \n
AppServiceWhat and whyYour choice
Example AppAccount (our servers)Email address, account id and the lists and notes you create: to sign you in and sync your content between your devices.The account is optional; export or delete it in Settings > Account
Example AppAnalytics (e.g. a privacy-friendly analytics SDK)Random install id, screens used, device model, OS version: to improve the app.Settings > Analytics off
Example AppCrash reportingCrash logs and device model: to fix crashes.-
Example AppApp storesPurchases and subscriptions are handled by Google Play / the App Store; we never see payment details.-
\n\n

Deleting your account

\n

In the app: Settings > Account > Delete account. Without the app: example.com/delete-account.\n We delete your account and its content within 30 days; backups roll over within 90 days. A store subscription is\n not cancelled by deleting the account: cancel it in your Google Play or App Store subscriptions.

\n\n

Children

\n

Our apps are not directed at children under 13. We do not knowingly collect personal data from children. If you\n believe a child sent us data, contact us and we will delete it.

\n\n

Retention and your rights

\n

We keep account data while the account exists and analytics data for up to 24 months. You can ask for a copy or\n the deletion of your data by writing to privacy@example.com; we answer\n within 30 days.

\n\n

Security

\n

All network traffic of our apps uses HTTPS; passwords are stored only as salted hashes.

\n\n

Changes

\n

When an app starts collecting something new we update this page and its date first.

\n\n

Contact

\n

Example Studio · privacy@example.com

\n
\n\n
\n

Gizlilik Politikası

\n

Example Studio · tüm uygulamalarımız için geçerlidir · son güncelleme 2026-01-01

\n

Yalnızca uygulamanın sizin için çalışması gereken verileri topluyoruz, kişisel verileri asla satmıyoruz ve reklam\n göstermiyoruz. Yukarıdaki tablo her uygulamanın neyi neden topladığını gösterir.

\n

Hesabınızı silmek

\n

Uygulamada: Ayarlar > Hesap > Hesabı sil. Uygulama olmadan: example.com/delete-account.\n Mağaza aboneliği hesap silinince iptal olmaz; Google Play veya App Store aboneliklerinizden iptal edin.

\n

Haklarınız

\n

Verilerinizin bir kopyasını veya silinmesini privacy@example.com adresine\n yazarak isteyebilirsiniz; 30 gün içinde yanıtlıyoruz.

\n
\n
\n\n\n", "profiles/app/shots-copy.json": "{\n \"en\": {\n \"home\": { \"eyebrow\": \"Example App\", \"title\": [\"Everything in order,\", \"in one calm place\"], \"sub\": \"Lists and notes, synced on all your devices.\" },\n \"detail\": { \"eyebrow\": \"Get it done\", \"title\": [\"See what is left\", \"at a glance\"], \"sub\": \"Tap to tick, swipe to reorder.\" },\n \"share\": { \"eyebrow\": \"Together\", \"title\": [\"Share a list,\", \"plan together\"], \"sub\": \"Invite people by link and edit live.\" },\n \"privacy\": { \"eyebrow\": \"Your data\", \"title\": [\"Private by default,\", \"yours to export\"], \"sub\": \"Export your data or delete your account in Settings.\" }\n },\n \"tr\": {\n \"home\": { \"eyebrow\": \"Example App\", \"title\": [\"Her şey düzenli,\", \"tek sakin bir yerde\"], \"sub\": \"Listeler ve notlar, tüm cihazlarında eşitlenir.\" },\n \"detail\": { \"eyebrow\": \"Bitir\", \"title\": [\"Kalanları\", \"bir bakışta gör\"], \"sub\": \"Dokun işaretle, sürükle sırala.\" },\n \"share\": { \"eyebrow\": \"Birlikte\", \"title\": [\"Listeyi paylaş,\", \"birlikte planla\"], \"sub\": \"Bağlantıyla davet et, canlı düzenleyin.\" },\n \"privacy\": { \"eyebrow\": \"Verilerin\", \"title\": [\"Varsayılan olarak gizli,\", \"dışa aktarması senin\"], \"sub\": \"Verilerini dışa aktar ya da hesabını Ayarlar'dan sil.\" }\n }\n}\n", - "profiles/app/storebound.config.ts": "// storebound config for one app (profile \"app\": a utility / productivity app with an optional account and an\n// analytics SDK, no ads). Every answer below is a starting point: edit it to match your app. Credentials NEVER go\n// here (env vars or .storebound/credentials.json, gitignored). Paths are relative to this file.\n// The type import is optional: it only works when storebound is installed in the project (bun add -d storebound).\nimport type { ShipConfig } from 'storebound';\n\nconst config: ShipConfig = {\n // Every compliance answer below is the TEMPLATE's, not yours. While an area is listed here, check / validate block\n // and nothing sends it to a store. Derive the answers from the code (storebound scan --write; for an app that is\n // already live: storebound onboard --declarations), answer the rest, then remove the area from this list.\n unanswered: ['dataSafety', 'appPrivacy', 'reviewNotes', 'ageRating', 'accounts', 'reviewAccess'],\n\n app: {\n name: 'Example App',\n profile: 'app',\n copyright: '2026 Example Studio',\n privacyPolicyUrl: 'https://example.com/privacy',\n // termsUrl: 'https://example.com/terms', // Terms of Use; required once you sell subscriptions\n supportUrl: 'https://example.com/support',\n marketingUrl: 'https://example.com',\n website: 'https://example.com',\n contactEmail: 'support@example.com',\n },\n\n // Accounts (account-deletion skill). Remove this block if the app has no sign-up / sign-in at all.\n // Apple 5.1.1(v): deletion must start inside the app. Google Play: in the app AND on a public web page.\n accounts: {\n enabled: true,\n deletionUrl: 'https://example.com/delete-account', // public page, no login needed to request deletion\n inApp: 'Settings > Account > Delete account', // goes into the App Review notes\n // How people sign up: 'username' (a name picked in the app, no password, no email), 'username-password',\n // 'email-password', 'email-link', 'phone', 'oauth', 'other'. `storebound scan` proposes the account data and\n // dataSafety.accountCreation from it; only the 'email-*' methods mean an email address.\n signUp: ['email-password'],\n },\n\n // Sign-in for store reviewers (review-access skill). The demo account itself lives ONLY in\n // .storebound/credentials.json (\"reviewDemoAccount\") or REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD.\n reviewAccess: {\n signInRequired: true, // false if every feature works without signing in\n instructions: 'Sign in with the demo account. Sample data is already there; nothing needs a second device.',\n },\n\n // id = your folder / copy key; play = Play language code(s); apple = App Store Connect locale\n languages: [\n { id: 'en', play: 'en-US', apple: 'en-US' },\n { id: 'tr', play: 'tr-TR', apple: 'tr' },\n ],\n\n play: {\n packageName: 'com.example.app',\n defaultLanguage: 'en-US',\n listing: 'store/listing.md',\n icon: 'store/icons/play-512.png',\n },\n\n apple: {\n bundleId: 'com.example.app',\n // name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there (\"already being used\"); default app.name\n listing: 'store/appstore.md',\n // Export compliance (export-compliance skill): decide it, then uncomment. false ONLY if the app uses no encryption\n // beyond the OS (HTTPS through the system, standard sign-in).\n // usesNonExemptEncryption: false,\n // ipad: true,\n info: {\n categories: { primary: 'PRODUCTIVITY', secondary: 'UTILITIES' },\n ageRating: {}, // every content question NONE / false; change what applies (user-generated content, web access ...)\n contentRights: 'DOES_NOT_USE_THIRD_PARTY_CONTENT',\n free: true,\n reviewNotes: [\n 'Example App keeps lists and notes in sync across devices. An account is optional on the first screen.',\n 'Privacy policy and Terms: Settings > About.',\n // With remote config or feature flags (storebound scan warns, 2.3.1) you may add a line like:\n // 'Some features are configured remotely with : ; none is switched on after review without a new submission.',\n ].join('\\n\\n'),\n },\n },\n\n // In-app purchases (optional): a one-time \"Pro\" unlock, for example. Subscriptions: see the subscription-app profile\n // (storebound init --profile subscription-app) or the store-subscriptions skill.\n // products: [{ id: 'com.example.app.pro', type: 'non_consumable', usd: 4.99,\n // listings: { en: { title: 'Pro', description: 'Unlimited lists and themes.' } }, reviewScreenshot: 'store/iap-review/pro.png' }],\n\n // Google Play Data safety. Types not listed = not collected. Typical app with accounts + an analytics SDK acting as\n // your processor (collected, not shared). Edit to match what your app and its SDKs really do.\n dataSafety: {\n collectsData: true,\n encryptedInTransit: true,\n // Sign-up methods. Google does not publish these ids: compare with Play Console > App content > Data safety >\n // Export to CSV before the first import. The delete-account URL (PSL_ACCOUNT_DELETION_URL) comes from\n // accounts.deletionUrl; `storebound check` names any other row Play requires.\n accountCreation: ['PSL_ACM_USER_ID_PASSWORD'],\n // Can people delete their data without deleting the account (a data-only page)? true needs partialDeletionUrl.\n // Play's \"can users request deletion?\" is answered yes by accounts.deletionUrl. Ask the owner.\n partialDeletion: false,\n data: {\n PSL_EMAIL: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_ACCOUNT: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_GENERATED_CONTENT: { shared: false, collect: ['functionality'] },\n PSL_USER_INTERACTION: { shared: false, collect: ['analytics'] },\n PSL_CRASH_LOGS: { shared: false, collect: ['analytics'] },\n PSL_PERFORMANCE_DIAGNOSTICS: { shared: false, collect: ['analytics'] },\n PSL_DEVICE_ID: { shared: false, collect: ['analytics'] },\n },\n },\n\n renders: 'store/renders',\n\n shots: {\n style: 'app', // calm gradient, device frame, headline + subline (game: sparkles and badges)\n copy: 'store/shots/copy.json',\n frames: 'store/shots/frames', // /phone/.png, /tablet/.png\n out: 'store/renders',\n // fonts: { title: 'Inter', body: 'Inter' }, // the app style default\n scenes: [\n { id: 'home', palette: 'mist', frames: [{ src: 'home.png' }] },\n { id: 'detail', palette: 'mint', frames: [{ src: 'detail.png' }] },\n { id: 'share', palette: 'sky', frames: [{ src: 'share.png' }] },\n { id: 'privacy', palette: 'slate', frames: [{ src: 'settings.png' }] },\n ],\n feature: { frame: 'home.png', palette: 'mist' },\n // Raw frames from a web build, the iOS Simulator (ios-sim) or an Android emulator (android-emu): sign in to a demo\n // account with realistic sample data, never real user data (store-screenshots skill).\n capture: {\n baseUrl: 'http://127.0.0.1:5173',\n query: 'lang={lang}&demo=1',\n shots: {\n 'home': { path: '/', delayMs: 1000, device: 'both' },\n 'detail': { path: '/lists/1', delayMs: 1000, device: 'both' },\n 'share': { path: '/lists/1/share', delayMs: 1000, device: 'both' },\n 'settings': { path: '/settings', delayMs: 1000, device: 'both' },\n },\n },\n },\n\n icons: {\n composite: 'store/icon/icon.png',\n foreground: 'store/icon/foreground.png',\n background: 'store/icon/background.png',\n out: 'store/icons',\n },\n};\n\nexport default config;\n", + "profiles/app/storebound.config.ts": "// storebound config for one app (profile \"app\": a utility / productivity app with an optional account and an\n// analytics SDK, no ads). Every answer below is a starting point: edit it to match your app. Credentials NEVER go\n// here (env vars or .storebound/credentials.json, gitignored). Paths are relative to this file.\n// The type import is optional: it only works when storebound is installed in the project (bun add -d storebound).\nimport type { ShipConfig } from 'storebound';\n\nconst config: ShipConfig = {\n // Every compliance answer below is the TEMPLATE's, not yours. While an area is listed here, check / validate block\n // and nothing sends it to a store. Derive the answers from the code (storebound scan --write; for an app that is\n // already live: storebound onboard --declarations), answer the rest, then remove the area from this list.\n unanswered: ['dataSafety', 'appPrivacy', 'reviewNotes', 'ageRating', 'accounts', 'reviewAccess'],\n\n app: {\n name: 'Example App',\n profile: 'app',\n copyright: '2026 Example Studio',\n privacyPolicyUrl: 'https://example.com/privacy',\n // termsUrl: 'https://example.com/terms', // Terms of Use; required once you sell subscriptions\n supportUrl: 'https://example.com/support',\n marketingUrl: 'https://example.com',\n website: 'https://example.com',\n contactEmail: 'support@example.com',\n },\n\n // Accounts (account-deletion skill). Remove this block if the app has no sign-up / sign-in at all.\n // Apple 5.1.1(v): deletion must start inside the app. Google Play: in the app AND on a public web page.\n accounts: {\n enabled: true,\n deletionUrl: 'https://example.com/delete-account', // public page, no login needed to request deletion\n inApp: 'Settings > Account > Delete account', // goes into the App Review notes\n // How people sign up: 'username' (a name picked in the app, no password, no email), 'username-password',\n // 'email-password', 'email-link', 'phone', 'oauth', 'other'. `storebound scan` proposes the account data and\n // dataSafety.accountCreation from it; only the 'email-*' methods mean an email address.\n signUp: ['email-password'],\n },\n\n // Sign-in for store reviewers (review-access skill). The demo account itself lives ONLY in\n // .storebound/credentials.json (\"reviewDemoAccount\") or REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD.\n reviewAccess: {\n signInRequired: true, // false if every feature works without signing in\n instructions: 'Sign in with the demo account. Sample data is already there; nothing needs a second device.',\n },\n\n // id = your folder / copy key; play = Play language code(s); apple = App Store Connect locale\n languages: [\n { id: 'en', play: 'en-US', apple: 'en-US' },\n { id: 'tr', play: 'tr-TR', apple: 'tr' },\n ],\n\n play: {\n packageName: 'com.example.app',\n defaultLanguage: 'en-US',\n listing: 'store/listing.md',\n icon: 'store/icons/play-512.png',\n },\n\n apple: {\n bundleId: 'com.example.app',\n // name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there (\"already being used\"); default app.name\n listing: 'store/appstore.md',\n // Export compliance (export-compliance skill): decide it, then uncomment. false ONLY if the app uses no encryption\n // beyond the OS (HTTPS through the system, standard sign-in).\n // usesNonExemptEncryption: false,\n // ipad: true,\n info: {\n categories: { primary: 'PRODUCTIVITY', secondary: 'UTILITIES' },\n ageRating: {}, // every content question NONE / false; change what applies (user-generated content, web access ...)\n contentRights: 'DOES_NOT_USE_THIRD_PARTY_CONTENT',\n free: true,\n reviewNotes: [\n 'Example App keeps lists and notes in sync across devices. An account is optional on the first screen.',\n 'Privacy policy and Terms: Settings > About.',\n // With remote config or feature flags (storebound scan warns, 2.3.1) you may add a line like:\n // 'Some features are configured remotely with : ; none is switched on after review without a new submission.',\n // Google Play has no review-notes field: put the same line in reviewAccess.instructions (Play App content >\n // App access, 'Any other information') when the app has a sign-in, and say in the full description what needs\n // a paid subscription (Play: Deceptive behavior, Payments).\n ].join('\\n\\n'),\n },\n },\n\n // In-app purchases (optional): a one-time \"Pro\" unlock, for example. Subscriptions: see the subscription-app profile\n // (storebound init --profile subscription-app) or the store-subscriptions skill.\n // products: [{ id: 'com.example.app.pro', type: 'non_consumable', usd: 4.99,\n // listings: { en: { title: 'Pro', description: 'Unlimited lists and themes.' } }, reviewScreenshot: 'store/iap-review/pro.png' }],\n\n // Google Play Data safety. Types not listed = not collected. Typical app with accounts + an analytics SDK acting as\n // your processor (collected, not shared). Edit to match what your app and its SDKs really do.\n dataSafety: {\n collectsData: true,\n encryptedInTransit: true,\n // Sign-up methods. Google does not publish these ids: compare with Play Console > App content > Data safety >\n // Export to CSV before the first import. The delete-account URL (PSL_ACCOUNT_DELETION_URL) comes from\n // accounts.deletionUrl; `storebound check` names any other row Play requires.\n accountCreation: ['PSL_ACM_USER_ID_PASSWORD'],\n // Can people delete their data without deleting the account (a data-only page)? true needs partialDeletionUrl.\n // Play's \"can users request deletion?\" is answered yes by accounts.deletionUrl. Ask the owner.\n partialDeletion: false,\n data: {\n PSL_EMAIL: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_ACCOUNT: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_GENERATED_CONTENT: { shared: false, collect: ['functionality'] },\n PSL_USER_INTERACTION: { shared: false, collect: ['analytics'] },\n PSL_CRASH_LOGS: { shared: false, collect: ['analytics'] },\n PSL_PERFORMANCE_DIAGNOSTICS: { shared: false, collect: ['analytics'] },\n PSL_DEVICE_ID: { shared: false, collect: ['analytics'] },\n },\n },\n\n renders: 'store/renders',\n\n shots: {\n style: 'app', // calm gradient, device frame, headline + subline (game: sparkles and badges)\n copy: 'store/shots/copy.json',\n frames: 'store/shots/frames', // /phone/.png, /tablet/.png\n out: 'store/renders',\n // fonts: { title: 'Inter', body: 'Inter' }, // the app style default\n scenes: [\n { id: 'home', palette: 'mist', frames: [{ src: 'home.png' }] },\n { id: 'detail', palette: 'mint', frames: [{ src: 'detail.png' }] },\n { id: 'share', palette: 'sky', frames: [{ src: 'share.png' }] },\n { id: 'privacy', palette: 'slate', frames: [{ src: 'settings.png' }] },\n ],\n feature: { frame: 'home.png', palette: 'mist' },\n // Raw frames from a web build, the iOS Simulator (ios-sim) or an Android emulator (android-emu): sign in to a demo\n // account with realistic sample data, never real user data (store-screenshots skill).\n capture: {\n baseUrl: 'http://127.0.0.1:5173',\n query: 'lang={lang}&demo=1',\n shots: {\n 'home': { path: '/', delayMs: 1000, device: 'both' },\n 'detail': { path: '/lists/1', delayMs: 1000, device: 'both' },\n 'share': { path: '/lists/1/share', delayMs: 1000, device: 'both' },\n 'settings': { path: '/settings', delayMs: 1000, device: 'both' },\n },\n },\n },\n\n icons: {\n composite: 'store/icon/icon.png',\n foreground: 'store/icon/foreground.png',\n background: 'store/icon/background.png',\n out: 'store/icons',\n },\n};\n\nexport default config;\n", "profiles/app/workflows/beta.yml": "# storebound flow \"beta\": a TestFlight / internal testing build for your testers.\n# storebound flow run beta VERSION=1.2.0 [--apply]\ndescription: Next build to TestFlight and Play internal testing\nparams:\n VERSION: \"1.0.0\"\n GROUP: \"Internal\"\nsteps:\n - id: check\n run: check\n - id: next-build\n if: apple\n run: apple next-build\n capture: BUILD\n - id: build\n if: apple\n run: apple build --version ${VERSION} --build-number ${BUILD}\n - id: upload\n if: apple\n run: apple upload --no-wait --build ${BUILD} --allow-existing\n - id: wait\n if: apple\n run: apple testflight wait --build ${BUILD} --version ${VERSION}\n - id: what-to-test\n if: apple\n run: apple testflight what-to-test --build ${BUILD}\n - id: distribute\n if: apple\n run: apple testflight distribute --build ${BUILD} --group ${GROUP}\n - id: play-build\n if: play\n run: play build --version-name ${VERSION}\n - id: play-upload\n if: play\n run: play upload --track internal\n - id: external\n owner: \"External testers: storebound apple testflight distribute --build ${BUILD} --group --submit-review (Beta App Review is your call)\"\n", "profiles/app/workflows/release.yml": "# storebound flow \"release\": one version of the app on both stores, up to your Submit click.\n# storebound flow run release VERSION=1.2.0 reads run, writes run as dry runs (nothing changes)\n# storebound flow run release VERSION=1.2.0 --apply writes run for real; each command still asks you first\n# storebound flow run release --resume --apply continue after fixing a failed step\n# Steps are storebound commands (no \"storebound\" prefix). `if: apple` / `if: play` skip a store the config does not\n# have; `owner:` steps are never run, they list what you click. Edit freely: this file is yours.\ndescription: Build, upload and check one version on both stores, then your Submit click\nparams:\n VERSION: \"1.0.0\"\nsteps:\n - id: next-build\n if: apple\n run: apple next-build\n capture: BUILD\n - id: build\n if: apple\n run: apple build --version ${VERSION} --build-number ${BUILD}\n - id: upload\n if: apple\n run: apple upload --no-wait --build ${BUILD} --allow-existing\n - id: wait\n if: apple\n run: apple testflight wait --build ${BUILD} --version ${VERSION}\n - id: play-build\n if: play\n run: play build --version-name ${VERSION}\n - id: play-upload\n if: play\n run: play upload --track internal\n - id: whats-new\n if: exists store/whats-new\n run: whats-new apply\n - id: listing\n if: apple\n run: apple listing --version ${VERSION} --build ${BUILD}\n - id: validate\n run: validate\n - id: scan\n run: scan\n - id: plan\n run: release plan ${VERSION}\n - id: submit\n owner: \"App Store Connect: Submit for Review (version ${VERSION}, build ${BUILD}). Play Console: promote the internal release and Send changes for review\"\n", "profiles/subscription-app/app-privacy.md": "# Example App · App Store \"App Privacy\" answers\n\nApp Store Connect > your app > App Privacy (https://appstoreconnect.apple.com/apps, then the app; `storebound console plan apple-app-privacy` gives the deep link). **Web UI only, there is no API.** Fill it from this table, then press\n**Publish** (saving alone does not publish it). Keep it consistent with the privacy policy and the Play Data safety\nanswers (`dataSafety` in `storebound.config.ts`). **Edit to match your app.**\n\nTypical subscription app: account (email), content synced to your backend, auto-renewable subscriptions checked by\nyour server, an analytics SDK acting as your processor, no ads, no tracking.\n\n**Do you or your third-party partners collect data from this app?** Yes\n\n**Tracking**: No (no ad SDK, no data broker, nothing combined with other companies' data for advertising). If that\nchanges, add the App Tracking Transparency prompt first.\n\n| data type | collected | used to track | linked to the user | purposes |\n|---|---|---|---|---|\n| Contact Info > Email Address | yes (account) | no | yes | App Functionality |\n| Identifiers > User ID | yes (account id) | no | yes | App Functionality, Analytics |\n| User Content > Other User Content (lists, notes) | yes (synced) | no | yes | App Functionality |\n| Usage Data > Product Interaction | yes (analytics) | no | yes if tied to the account, else no | Analytics |\n| Purchases > Purchase History (subscription status) | yes | no | yes | App Functionality |\n| Diagnostics > Crash Data | yes | no | no | App Functionality, Analytics |\n| Diagnostics > Performance Data | yes | no | no | Analytics |\n\n\"Linked to you\" is **Yes** for what you store under the account. Not collected (typical): Location, Health and\nFitness, Financial Info, Contacts, Photos or Videos (unless people attach them), Browsing and Search History,\nSensitive Info.\n\nPer data type the UI asks, in order: purposes > \"Is this data linked to the user's identity?\" > \"Do you or your\nthird-party partners use this data for tracking purposes?\".\n", "profiles/subscription-app/appstore.md": "# Example App · App Store listing copy\n\nSource for `storebound apple listing`. One `## ` section per locale (the first word is the locale code:\n`en-US`, `tr`, `de-DE`, `ja`, `zh-Hans`, `ar-SA`, ...), one fenced block per `### `, field names exactly:\n`name` (optional, defaults to `apple.name`, else `app.name`), `subtitle` (30), `promotionalText` (170), `keywords` (100 characters, comma\nseparated, no spaces after commas, do not repeat the app name), `description` (4000), `whatsNew` (optional; not allowed\non the first version). Shared values (privacy policy, support and marketing URL) come from `storebound.config.ts`.\n\n---\n\n## en-US · English (U.S.)\n\n### subtitle\n```\nLists and notes, in sync\n```\n\n### promotionalText\n```\nOne or two sentences you can change any time without a new version.\n```\n\n### keywords\n```\ntodo,checklist,groceries,planner,notes,shared,family,organizer,tasks,sync\n```\n\n### description\n```\nFirst paragraph: the job the app does and why it is easier with it.\n\nFEATURES\n• Lists and notes that sync across your devices\n• Share a list with family or friends\n• Export your data or delete your account in Settings, any time\n\nFree to use with up to 3 lists. Example Pro unlocks unlimited lists, sharing and themes: yearly with a 1-week free trial, or monthly. Payment is charged to your store account; the subscription renews automatically unless cancelled at least 24 hours before the end of the period, and you can manage or cancel it in your account settings.\n\nTerms of Use: https://example.com/terms\nPrivacy Policy: https://example.com/privacy\n```\n\n## tr · Türkçe\n\n### subtitle\n```\nListeler ve notlar, eşitli\n```\n\n### promotionalText\n```\nYeni sürüm göndermeden istediğin zaman değiştirebileceğin bir iki cümle.\n```\n\n### keywords\n```\nyapılacaklar,kontrol,market,planlayıcı,not,paylaşım,aile,düzen,görev\n```\n\n### description\n```\nİlk paragraf: uygulamanın gördüğü iş ve onunla neden daha kolay olduğu.\n\nÖZELLİKLER\n• Tüm cihazlarında eşitlenen listeler ve notlar\n• Bir listeyi ailen ya da arkadaşlarınla paylaş\n• Verilerini dışa aktar ya da hesabını Ayarlar'dan istediğin an sil\n\n3 listeye kadar ücretsiz. Example Pro sınırsız liste, paylaşım ve tema açar: 1 hafta ücretsiz denemeli yıllık ya da aylık. Ödeme mağaza hesabınızdan alınır; abonelik, dönem bitmeden en az 24 saat önce iptal edilmezse otomatik yenilenir; hesap ayarlarınızdan yönetebilir ya da iptal edebilirsiniz.\n\nKullanım Koşulları: https://example.com/terms\nGizlilik Politikası: https://example.com/privacy\n```\n", "profiles/subscription-app/declarations.md": "# Example App · store declarations (answers to copy into the consoles)\n\nStarting answers for a typical **subscription app**: auto-renewable subscriptions (free trial on the yearly plan), an account (email + password, or sign in\nwith a provider), an analytics SDK acting as your processor, data synced to your own backend, no ads, no chat with\nstrangers, general audience. **Edit every line to match your app**: these are your statements to the stores. Everything\nmarked **UI** has no API: Play Console > your app > Policy and programs > **App content** (https://play.google.com/console), and App Store Connect for\nApple. Data safety (Play) has an API: `storebound play data-safety`.\n\n## Google Play · App content (UI)\n\n| declaration | answer |\n|---|---|\n| Privacy policy | your policy URL (same one in the listing and inside the app) |\n| App access | \"All or some functionality is restricted\": add the demo account (username, password) and the steps from `reviewAccess.instructions`; credentials must work at all times, no 2FA / OTP (review-access skill) |\n| Ads | No, my app does not contain ads |\n| Content rating | IARC questionnaire, below |\n| Target audience and content | 18 and over (or 13+ if teens use it); \"Could your app unintentionally appeal to children?\" No (only if true) |\n| News app | No |\n| Data safety | `storebound play data-safety`, then check the summary; with accounts: the delete-account URL (`accounts.deletionUrl`) |\n| Government apps | No |\n| Financial features | My app doesn't provide any financial features |\n| Health apps | No health features |\n| Advertising ID | No (unless an SDK in your app reads it: check the SDK docs and your merged manifest) |\n| Store settings | App, category (Productivity, Tools, ...); contact email + website |\n\n## Account deletion (account-deletion skill)\n\n- In the app: Settings > Account > Delete account deletes the account and its data (not only \"deactivate\").\n- On the web: `accounts.deletionUrl` lets people request deletion without the app; Play asks for it in Data safety.\n- With subscriptions: say that deleting the account does not cancel the store subscription, and how to cancel.\n\n## IARC content rating (Play UI; Apple has its own form, `storebound apple appinfo`)\n\nCategory: not a game (e.g. Utility, Productivity, Communication, or Social Networking if people share content with\nothers). Typical answers for a lists / notes app:\n\n| topic | answer |\n|---|---|\n| Violence, sexuality, language, controlled substances | No |\n| Gambling (simulated / real money) | No |\n| Users interact or exchange content | Yes only if people can share with others outside their own invitations; then also moderation and reporting |\n| Shares location with other users | No |\n| Digital purchases | Yes (subscriptions) |\n| Unrestricted internet / browser | No |\n\nExpected: PEGI 3, ESRB Everyone, IARC 3+. Apple age rating 4+ (all content questions None) unless users share\ncontent publicly.\n\n## App Store (UI-only parts)\n\n- App record: App Store Connect > Apps > + > New App (https://appstoreconnect.apple.com/apps). No API.\n- App Privacy: `app-privacy.md`, then **Publish**.\n- App Review information: `storebound apple review-details` sends the contact, the demo account (from\n `.storebound/credentials.json`, masked in the log) and the notes.\n- Export compliance (export-compliance skill): `ITSAppUsesNonExemptEncryption = NO` only if true.\n- Guideline 5.1.1: the privacy policy link must also be reachable **inside the app**; 5.1.1(v): account deletion\n inside the app.\n\n## Subscriptions (store-subscriptions skill)\n\n- Purchase screen (both stores): plan name, length, the full renewal price per period (most prominent), what is\n included, free trial length and what is charged after it, how to cancel, Restore Purchases, links to the Terms of Use\n and the Privacy Policy. Apple 3.1.2; Google Play subscriptions policy.\n- Metadata: the App Store description (or a custom EULA in App Information > License Agreement) links the Terms of\n Use; the Privacy Policy URL field is set by `storebound apple listing`.\n- First subscriptions are submitted together with an app version (App Store Connect: add them to the version on its\n page before Submit for Review), like first in-app purchases.\n- App Review notes say where the paywall is and that sandbox purchases work with the demo account.\n- Play: base plans and offers must be active before people can buy; new subscribers see the converted regional prices.\n", "profiles/subscription-app/listing.md": "# Example App · Google Play listing copy\n\nSource for `storebound play listing` (title, short + full description) and `storebound play release` (release notes).\nRules the parser follows:\n- every `## ...` section with a `` line is a listing; one section can serve several Play codes\n- under it, `### ...` headings that contain **title** (optional, defaults to `app.name`), **short**, **full** and\n **what's new**, each followed by one fenced block\n- limits (checked before anything is sent): title 30, short 80, full 4000, what's new 500 characters\nOnly claim what the app really does. No prices, no \"best / #1\", no other apps' names.\n\n---\n\n## English (en-US)\n\n\n### Play short description (max 80)\n```\nWhat the app does for people, in one plain line\n```\n\n### Play full description (max 4000)\n```\nFirst paragraph: the job the app does and why it is easier with it, in two or three sentences.\n\nFEATURES\n• Lists and notes that sync across your devices\n• Share a list with family or friends\n• Export your data or delete your account in Settings, any time\n\nFree to use with up to 3 lists. Example Pro unlocks unlimited lists, sharing and themes: yearly with a 1-week free trial, or monthly. Payment is charged to your store account; the subscription renews automatically unless cancelled at least 24 hours before the end of the period, and you can manage or cancel it in your account settings.\n\nTerms of Use: https://example.com/terms\nPrivacy Policy: https://example.com/privacy\n```\n\n### What's new (max 500)\n```\nFirst release. Thanks for trying it!\n```\n\n## Türkçe (tr-TR)\n\n\n### Play kısa açıklama · short (max 80)\n```\nUygulamanın insanlar için ne yaptığını anlatan sade bir cümle\n```\n\n### Play tam açıklama · full (max 4000)\n```\nİlk paragraf: uygulamanın gördüğü iş ve onunla neden daha kolay olduğu, iki üç cümlede.\n\nÖZELLİKLER\n• Tüm cihazlarında eşitlenen listeler ve notlar\n• Bir listeyi ailen ya da arkadaşlarınla paylaş\n• Verilerini dışa aktar ya da hesabını Ayarlar'dan istediğin an sil\n\n3 listeye kadar ücretsiz. Example Pro sınırsız liste, paylaşım ve tema açar: 1 hafta ücretsiz denemeli yıllık ya da aylık. Ödeme mağaza hesabınızdan alınır; abonelik, dönem bitmeden en az 24 saat önce iptal edilmezse otomatik yenilenir; hesap ayarlarınızdan yönetebilir ya da iptal edebilirsiniz.\n\nKullanım Koşulları: https://example.com/terms\nGizlilik Politikası: https://example.com/privacy\n```\n\n### Yenilikler · what's new (max 500)\n```\nİlk sürüm. Denediğin için teşekkürler!\n```\n", - "profiles/subscription-app/storebound.config.ts": "// storebound config for one app (profile \"subscription-app\": accounts plus auto-renewable subscriptions, an\n// analytics SDK, no ads). Every answer below is a starting point: edit it to match your app. Credentials NEVER go\n// here (env vars or .storebound/credentials.json, gitignored). Paths are relative to this file.\n// The type import is optional: it only works when storebound is installed in the project (bun add -d storebound).\nimport type { ShipConfig } from 'storebound';\n\nconst config: ShipConfig = {\n // Every compliance answer below is the TEMPLATE's, not yours. While an area is listed here, check / validate block\n // and nothing sends it to a store. Derive the answers from the code (storebound scan --write; for an app that is\n // already live: storebound onboard --declarations), answer the rest, then remove the area from this list.\n unanswered: ['dataSafety', 'appPrivacy', 'reviewNotes', 'ageRating', 'accounts', 'reviewAccess'],\n\n app: {\n name: 'Example App',\n profile: 'subscription-app',\n copyright: '2026 Example Studio',\n privacyPolicyUrl: 'https://example.com/privacy',\n termsUrl: 'https://example.com/terms', // Terms of Use (EULA): in the app and the metadata (Apple 3.1.2)\n supportUrl: 'https://example.com/support',\n marketingUrl: 'https://example.com',\n website: 'https://example.com',\n contactEmail: 'support@example.com',\n },\n\n // Accounts (account-deletion skill). Remove this block if the app has no sign-up / sign-in at all.\n // Apple 5.1.1(v): deletion must start inside the app. Google Play: in the app AND on a public web page.\n accounts: {\n enabled: true,\n deletionUrl: 'https://example.com/delete-account', // public page, no login needed to request deletion\n inApp: 'Settings > Account > Delete account', // goes into the App Review notes\n // How people sign up: 'username' (a name picked in the app, no password, no email), 'username-password',\n // 'email-password', 'email-link', 'phone', 'oauth', 'other'. `storebound scan` proposes the account data and\n // dataSafety.accountCreation from it; only the 'email-*' methods mean an email address.\n signUp: ['email-password'],\n },\n\n // Sign-in for store reviewers (review-access skill). The demo account itself lives ONLY in\n // .storebound/credentials.json (\"reviewDemoAccount\") or REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD.\n reviewAccess: {\n signInRequired: true, // false if every feature works without signing in\n instructions: 'Sign in with the demo account. Sample data is already there; nothing needs a second device.',\n },\n\n // id = your folder / copy key; play = Play language code(s); apple = App Store Connect locale\n languages: [\n { id: 'en', play: 'en-US', apple: 'en-US' },\n { id: 'tr', play: 'tr-TR', apple: 'tr' },\n ],\n\n play: {\n packageName: 'com.example.app',\n defaultLanguage: 'en-US',\n listing: 'store/listing.md',\n icon: 'store/icons/play-512.png',\n },\n\n apple: {\n bundleId: 'com.example.app',\n // name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there (\"already being used\"); default app.name\n listing: 'store/appstore.md',\n // Export compliance (export-compliance skill): decide it, then uncomment. false ONLY if the app uses no encryption\n // beyond the OS (HTTPS through the system, standard sign-in).\n // usesNonExemptEncryption: false,\n // ipad: true,\n info: {\n categories: { primary: 'PRODUCTIVITY', secondary: 'UTILITIES' },\n ageRating: {}, // every content question NONE / false; change what applies (user-generated content, web access ...)\n contentRights: 'DOES_NOT_USE_THIRD_PARTY_CONTENT',\n free: true,\n reviewNotes: [\n 'Example App keeps lists and notes in sync across devices. Pro (yearly with a 1-week free trial, or monthly) unlocks unlimited lists, sharing and themes.',\n 'Subscriptions: Settings > Pro (or the paywall after the third list). Restore Purchases is on the paywall and in Settings > Pro.',\n 'Privacy policy and Terms of Use: on the paywall and in Settings > About.',\n // With a remote paywall or feature flags (storebound scan warns, 2.3.1) you may add a line like:\n // 'Paywall designs and the prices shown are tested remotely with ; what Pro unlocks does not change after review.',\n ].join('\\n\\n'),\n },\n },\n\n // Auto-renewable subscriptions (store-subscriptions skill): `storebound apple subscriptions`, `storebound play\n // subscriptions`. Apple: one group, levels rank the plans (1 = highest). Play: one subscription per entry with one\n // auto-renewing base plan. Prices: USD base, Apple equalizes from the USA, Play converts per region; overrides set a\n // region by hand. The disclosure (price per period, renewal, how to cancel, Terms + Privacy links) belongs on the\n // purchase screen and in the descriptions.\n subscriptions: [\n {\n name: 'Example Pro',\n listings: { en: { name: 'Example Pro' }, tr: { name: 'Example Pro' } },\n subscriptions: [\n {\n id: 'com.example.app.pro_yearly', period: 'P1Y', level: 1, usd: 29.99,\n listings: {\n en: { title: 'Pro yearly', description: 'Unlimited lists, sharing and themes.', benefits: ['Unlimited lists', 'Shared lists', 'All themes'] },\n tr: { title: 'Pro yıllık', description: 'Sınırsız liste, paylaşım ve tema.', benefits: ['Sınırsız liste', 'Paylaşılan listeler', 'Tüm temalar'] },\n },\n intro: { type: 'free', duration: 'P1W' }, // 1 week free trial for new subscribers\n reviewScreenshot: 'store/iap-review/paywall.png',\n },\n {\n id: 'com.example.app.pro_monthly', period: 'P1M', level: 2, usd: 3.99,\n overrides: [{ region: 'TR', currency: 'TRY', price: 99.99 }],\n listings: {\n en: { title: 'Pro monthly', description: 'Unlimited lists, sharing and themes.', benefits: ['Unlimited lists', 'Shared lists', 'All themes'] },\n tr: { title: 'Pro aylık', description: 'Sınırsız liste, paylaşım ve tema.', benefits: ['Sınırsız liste', 'Paylaşılan listeler', 'Tüm temalar'] },\n },\n reviewScreenshot: 'store/iap-review/paywall.png',\n },\n ],\n },\n ],\n\n // Google Play Data safety. Types not listed = not collected. Typical app with accounts + an analytics SDK acting as\n // your processor (collected, not shared). Edit to match what your app and its SDKs really do.\n dataSafety: {\n collectsData: true,\n encryptedInTransit: true,\n // Sign-up methods. Google does not publish these ids: compare with Play Console > App content > Data safety >\n // Export to CSV before the first import. The delete-account URL (PSL_ACCOUNT_DELETION_URL) comes from\n // accounts.deletionUrl; `storebound check` names any other row Play requires.\n accountCreation: ['PSL_ACM_USER_ID_PASSWORD'],\n // Can people delete their data without deleting the account (a data-only page)? true needs partialDeletionUrl.\n // Play's \"can users request deletion?\" is answered yes by accounts.deletionUrl. Ask the owner.\n partialDeletion: false,\n data: {\n PSL_EMAIL: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_ACCOUNT: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_GENERATED_CONTENT: { shared: false, collect: ['functionality'] },\n PSL_USER_INTERACTION: { shared: false, collect: ['analytics'] },\n PSL_CRASH_LOGS: { shared: false, collect: ['analytics'] },\n PSL_PERFORMANCE_DIAGNOSTICS: { shared: false, collect: ['analytics'] },\n PSL_DEVICE_ID: { shared: false, collect: ['analytics'] },\n PSL_PURCHASE_HISTORY: { shared: false, collect: ['functionality'] }, // subscription status tied to the account\n },\n },\n\n renders: 'store/renders',\n\n shots: {\n style: 'app', // calm gradient, device frame, headline + subline (game: sparkles and badges)\n copy: 'store/shots/copy.json',\n frames: 'store/shots/frames', // /phone/.png, /tablet/.png\n out: 'store/renders',\n // fonts: { title: 'Inter', body: 'Inter' }, // the app style default\n scenes: [\n { id: 'home', palette: 'mist', frames: [{ src: 'home.png' }] },\n { id: 'detail', palette: 'mint', frames: [{ src: 'detail.png' }] },\n { id: 'share', palette: 'sky', frames: [{ src: 'share.png' }] },\n { id: 'privacy', palette: 'slate', frames: [{ src: 'settings.png' }] },\n ],\n feature: { frame: 'home.png', palette: 'mist' },\n // Raw frames from a web build, the iOS Simulator (ios-sim) or an Android emulator (android-emu): sign in to a demo\n // account with realistic sample data, never real user data (store-screenshots skill).\n capture: {\n baseUrl: 'http://127.0.0.1:5173',\n query: 'lang={lang}&demo=1',\n shots: {\n 'home': { path: '/', delayMs: 1000, device: 'both' },\n 'detail': { path: '/lists/1', delayMs: 1000, device: 'both' },\n 'share': { path: '/lists/1/share', delayMs: 1000, device: 'both' },\n 'settings': { path: '/settings', delayMs: 1000, device: 'both' },\n },\n },\n },\n\n icons: {\n composite: 'store/icon/icon.png',\n foreground: 'store/icon/foreground.png',\n background: 'store/icon/background.png',\n out: 'store/icons',\n },\n};\n\nexport default config;\n", + "profiles/subscription-app/storebound.config.ts": "// storebound config for one app (profile \"subscription-app\": accounts plus auto-renewable subscriptions, an\n// analytics SDK, no ads). Every answer below is a starting point: edit it to match your app. Credentials NEVER go\n// here (env vars or .storebound/credentials.json, gitignored). Paths are relative to this file.\n// The type import is optional: it only works when storebound is installed in the project (bun add -d storebound).\nimport type { ShipConfig } from 'storebound';\n\nconst config: ShipConfig = {\n // Every compliance answer below is the TEMPLATE's, not yours. While an area is listed here, check / validate block\n // and nothing sends it to a store. Derive the answers from the code (storebound scan --write; for an app that is\n // already live: storebound onboard --declarations), answer the rest, then remove the area from this list.\n unanswered: ['dataSafety', 'appPrivacy', 'reviewNotes', 'ageRating', 'accounts', 'reviewAccess'],\n\n app: {\n name: 'Example App',\n profile: 'subscription-app',\n copyright: '2026 Example Studio',\n privacyPolicyUrl: 'https://example.com/privacy',\n termsUrl: 'https://example.com/terms', // Terms of Use (EULA): in the app and the metadata (Apple 3.1.2)\n supportUrl: 'https://example.com/support',\n marketingUrl: 'https://example.com',\n website: 'https://example.com',\n contactEmail: 'support@example.com',\n },\n\n // Accounts (account-deletion skill). Remove this block if the app has no sign-up / sign-in at all.\n // Apple 5.1.1(v): deletion must start inside the app. Google Play: in the app AND on a public web page.\n accounts: {\n enabled: true,\n deletionUrl: 'https://example.com/delete-account', // public page, no login needed to request deletion\n inApp: 'Settings > Account > Delete account', // goes into the App Review notes\n // How people sign up: 'username' (a name picked in the app, no password, no email), 'username-password',\n // 'email-password', 'email-link', 'phone', 'oauth', 'other'. `storebound scan` proposes the account data and\n // dataSafety.accountCreation from it; only the 'email-*' methods mean an email address.\n signUp: ['email-password'],\n },\n\n // Sign-in for store reviewers (review-access skill). The demo account itself lives ONLY in\n // .storebound/credentials.json (\"reviewDemoAccount\") or REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD.\n reviewAccess: {\n signInRequired: true, // false if every feature works without signing in\n instructions: 'Sign in with the demo account. Sample data is already there; nothing needs a second device.',\n },\n\n // id = your folder / copy key; play = Play language code(s); apple = App Store Connect locale\n languages: [\n { id: 'en', play: 'en-US', apple: 'en-US' },\n { id: 'tr', play: 'tr-TR', apple: 'tr' },\n ],\n\n play: {\n packageName: 'com.example.app',\n defaultLanguage: 'en-US',\n listing: 'store/listing.md',\n icon: 'store/icons/play-512.png',\n },\n\n apple: {\n bundleId: 'com.example.app',\n // name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there (\"already being used\"); default app.name\n listing: 'store/appstore.md',\n // Export compliance (export-compliance skill): decide it, then uncomment. false ONLY if the app uses no encryption\n // beyond the OS (HTTPS through the system, standard sign-in).\n // usesNonExemptEncryption: false,\n // ipad: true,\n info: {\n categories: { primary: 'PRODUCTIVITY', secondary: 'UTILITIES' },\n ageRating: {}, // every content question NONE / false; change what applies (user-generated content, web access ...)\n contentRights: 'DOES_NOT_USE_THIRD_PARTY_CONTENT',\n free: true,\n reviewNotes: [\n 'Example App keeps lists and notes in sync across devices. Pro (yearly with a 1-week free trial, or monthly) unlocks unlimited lists, sharing and themes.',\n 'Subscriptions: Settings > Pro (or the paywall after the third list). Restore Purchases is on the paywall and in Settings > Pro.',\n 'Privacy policy and Terms of Use: on the paywall and in Settings > About.',\n // With a remote paywall or feature flags (storebound scan warns, 2.3.1) you may add a line like:\n // 'Paywall designs and the prices shown are tested remotely with ; what Pro unlocks does not change after review.',\n // Google Play has no review-notes field: put the same line in reviewAccess.instructions (Play App content >\n // App access, 'Any other information') when the app has a sign-in, and say in the full description what needs\n // a paid subscription (Play: Deceptive behavior, Payments).\n ].join('\\n\\n'),\n },\n },\n\n // Auto-renewable subscriptions (store-subscriptions skill): `storebound apple subscriptions`, `storebound play\n // subscriptions`. Apple: one group, levels rank the plans (1 = highest). Play: one subscription per entry with one\n // auto-renewing base plan. Prices: USD base, Apple equalizes from the USA, Play converts per region; overrides set a\n // region by hand. The disclosure (price per period, renewal, how to cancel, Terms + Privacy links) belongs on the\n // purchase screen and in the descriptions.\n subscriptions: [\n {\n name: 'Example Pro',\n listings: { en: { name: 'Example Pro' }, tr: { name: 'Example Pro' } },\n subscriptions: [\n {\n id: 'com.example.app.pro_yearly', period: 'P1Y', level: 1, usd: 29.99,\n listings: {\n en: { title: 'Pro yearly', description: 'Unlimited lists, sharing and themes.', benefits: ['Unlimited lists', 'Shared lists', 'All themes'] },\n tr: { title: 'Pro yıllık', description: 'Sınırsız liste, paylaşım ve tema.', benefits: ['Sınırsız liste', 'Paylaşılan listeler', 'Tüm temalar'] },\n },\n intro: { type: 'free', duration: 'P1W' }, // 1 week free trial for new subscribers\n reviewScreenshot: 'store/iap-review/paywall.png',\n },\n {\n id: 'com.example.app.pro_monthly', period: 'P1M', level: 2, usd: 3.99,\n overrides: [{ region: 'TR', currency: 'TRY', price: 99.99 }],\n listings: {\n en: { title: 'Pro monthly', description: 'Unlimited lists, sharing and themes.', benefits: ['Unlimited lists', 'Shared lists', 'All themes'] },\n tr: { title: 'Pro aylık', description: 'Sınırsız liste, paylaşım ve tema.', benefits: ['Sınırsız liste', 'Paylaşılan listeler', 'Tüm temalar'] },\n },\n reviewScreenshot: 'store/iap-review/paywall.png',\n },\n ],\n },\n ],\n\n // Google Play Data safety. Types not listed = not collected. Typical app with accounts + an analytics SDK acting as\n // your processor (collected, not shared). Edit to match what your app and its SDKs really do.\n dataSafety: {\n collectsData: true,\n encryptedInTransit: true,\n // Sign-up methods. Google does not publish these ids: compare with Play Console > App content > Data safety >\n // Export to CSV before the first import. The delete-account URL (PSL_ACCOUNT_DELETION_URL) comes from\n // accounts.deletionUrl; `storebound check` names any other row Play requires.\n accountCreation: ['PSL_ACM_USER_ID_PASSWORD'],\n // Can people delete their data without deleting the account (a data-only page)? true needs partialDeletionUrl.\n // Play's \"can users request deletion?\" is answered yes by accounts.deletionUrl. Ask the owner.\n partialDeletion: false,\n data: {\n PSL_EMAIL: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_ACCOUNT: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_GENERATED_CONTENT: { shared: false, collect: ['functionality'] },\n PSL_USER_INTERACTION: { shared: false, collect: ['analytics'] },\n PSL_CRASH_LOGS: { shared: false, collect: ['analytics'] },\n PSL_PERFORMANCE_DIAGNOSTICS: { shared: false, collect: ['analytics'] },\n PSL_DEVICE_ID: { shared: false, collect: ['analytics'] },\n PSL_PURCHASE_HISTORY: { shared: false, collect: ['functionality'] }, // subscription status tied to the account\n },\n },\n\n renders: 'store/renders',\n\n shots: {\n style: 'app', // calm gradient, device frame, headline + subline (game: sparkles and badges)\n copy: 'store/shots/copy.json',\n frames: 'store/shots/frames', // /phone/.png, /tablet/.png\n out: 'store/renders',\n // fonts: { title: 'Inter', body: 'Inter' }, // the app style default\n scenes: [\n { id: 'home', palette: 'mist', frames: [{ src: 'home.png' }] },\n { id: 'detail', palette: 'mint', frames: [{ src: 'detail.png' }] },\n { id: 'share', palette: 'sky', frames: [{ src: 'share.png' }] },\n { id: 'privacy', palette: 'slate', frames: [{ src: 'settings.png' }] },\n ],\n feature: { frame: 'home.png', palette: 'mist' },\n // Raw frames from a web build, the iOS Simulator (ios-sim) or an Android emulator (android-emu): sign in to a demo\n // account with realistic sample data, never real user data (store-screenshots skill).\n capture: {\n baseUrl: 'http://127.0.0.1:5173',\n query: 'lang={lang}&demo=1',\n shots: {\n 'home': { path: '/', delayMs: 1000, device: 'both' },\n 'detail': { path: '/lists/1', delayMs: 1000, device: 'both' },\n 'share': { path: '/lists/1/share', delayMs: 1000, device: 'both' },\n 'settings': { path: '/settings', delayMs: 1000, device: 'both' },\n },\n },\n },\n\n icons: {\n composite: 'store/icon/icon.png',\n foreground: 'store/icon/foreground.png',\n background: 'store/icon/background.png',\n out: 'store/icons',\n },\n};\n\nexport default config;\n", "shots-copy.json": "{\n \"en\": {\n \"hero\": { \"title\": [\"Tap. Match.\", \"Repeat!\"], \"badges\": [[\"100+ levels\", \"and more every update\"], [\"Play offline\", \"No account needed\"]] },\n \"play\": { \"eyebrow\": \"Play\", \"title\": [\"Easy to learn,\", \"hard to put down\"], \"sub\": \"One thumb, short rounds, big satisfying moments.\", \"badges\": [[\"Quick rounds\", \"Two minutes each\"], [\"Great!\"]] },\n \"levels\": { \"eyebrow\": \"Worlds\", \"title\": [\"Explore new\", \"worlds\"], \"sub\": \"A fresh look and new rules every ten levels.\", \"badges\": [[\"10 worlds\", \"A new one every 10 levels\"]] },\n \"stars\": { \"eyebrow\": \"Stars\", \"title\": [\"Play smart,\", \"grab 3 stars\"], \"sub\": \"Finish with moves to spare and collect every star.\", \"badges\": [[\"3 stars\"]] }\n },\n \"tr\": {\n \"hero\": { \"title\": [\"Dokun. Eşleştir.\", \"Tekrarla!\"], \"badges\": [[\"100+ bölüm\", \"her güncellemede yenileri\"], [\"İnternetsiz\", \"hesap gerekmez\"]] },\n \"play\": { \"eyebrow\": \"Oyna\", \"title\": [\"Öğrenmesi kolay,\", \"bırakması zor\"], \"sub\": \"Tek parmak, kısa turlar, büyük keyifli anlar.\", \"badges\": [[\"Kısa turlar\", \"Her biri iki dakika\"], [\"Harika!\"]] },\n \"levels\": { \"eyebrow\": \"Dünyalar\", \"title\": [\"Yeni dünyaları\", \"keşfet\"], \"sub\": \"Her on bölümde yeni bir görünüm ve yeni kurallar.\", \"badges\": [[\"10 dünya\", \"Her 10 bölümde yeni biri\"]] },\n \"stars\": { \"eyebrow\": \"Yıldızlar\", \"title\": [\"Akıllı oyna,\", \"3 yıldızı kap\"], \"sub\": \"Hamle artırarak bitir, tüm yıldızları topla.\", \"badges\": [[\"3 yıldız\"]] }\n },\n \"es\": {\n \"hero\": { \"title\": [\"Toca. Combina.\", \"¡Repite!\"], \"badges\": [[\"100+ niveles\", \"y más en cada versión\"], [\"Sin conexión\", \"Sin cuenta\"]] },\n \"play\": { \"eyebrow\": \"Juega\", \"title\": [\"Fácil de aprender,\", \"difícil de soltar\"], \"sub\": \"Un pulgar, rondas cortas, grandes momentos.\", \"badges\": [[\"Rondas cortas\", \"Dos minutos cada una\"], [\"¡Genial!\"]] },\n \"levels\": { \"eyebrow\": \"Mundos\", \"title\": [\"Explora\", \"nuevos mundos\"], \"sub\": \"Un aspecto nuevo y nuevas reglas cada diez niveles.\", \"badges\": [[\"10 mundos\", \"Uno nuevo cada 10 niveles\"]] },\n \"stars\": { \"eyebrow\": \"Estrellas\", \"title\": [\"Juega con cabeza,\", \"logra 3 estrellas\"], \"sub\": \"Termina con movimientos de sobra y consigue todas las estrellas.\", \"badges\": [[\"3 estrellas\"]] }\n },\n \"ja\": {\n \"hero\": { \"title\": [\"タップして、そろえて、\", \"もう一回!\"], \"badges\": [[\"100以上のステージ\", \"アップデートで追加\"], [\"オフラインで遊べる\", \"アカウント不要\"]] },\n \"play\": { \"eyebrow\": \"プレイ\", \"title\": [\"かんたんなのに\", \"やめられない\"], \"sub\": \"片手で遊べる短いラウンド、気持ちいい瞬間がたくさん。\", \"badges\": [[\"短いラウンド\", \"1回2分\"], [\"すごい!\"]] },\n \"levels\": { \"eyebrow\": \"ワールド\", \"title\": [\"新しいワールドを\", \"冒険しよう\"], \"sub\": \"10ステージごとに新しい見た目と新しいルール。\", \"badges\": [[\"10のワールド\", \"10ステージごとに追加\"]] },\n \"stars\": { \"eyebrow\": \"スター\", \"title\": [\"かしこく遊んで\", \"星を3つゲット\"], \"sub\": \"手数を残してクリアし、すべての星を集めよう。\", \"badges\": [[\"星3つ\"]] }\n },\n \"ar\": {\n \"hero\": { \"title\": [\"انقر. طابق.\", \"كرّر!\"], \"badges\": [[\"أكثر من 100 مرحلة\", \"والمزيد مع كل تحديث\"], [\"العب دون اتصال\", \"دون حساب\"]] },\n \"play\": { \"eyebrow\": \"العب\", \"title\": [\"سهلة التعلّم،\", \"صعبة التوقف\"], \"sub\": \"إبهام واحد، جولات قصيرة، ولحظات ممتعة.\", \"badges\": [[\"جولات قصيرة\", \"دقيقتان لكل جولة\"], [\"رائع!\"]] },\n \"levels\": { \"eyebrow\": \"العوالم\", \"title\": [\"استكشف\", \"عوالم جديدة\"], \"sub\": \"شكل جديد وقواعد جديدة كل عشر مراحل.\", \"badges\": [[\"10 عوالم\", \"عالم جديد كل 10 مراحل\"]] },\n \"stars\": { \"eyebrow\": \"النجوم\", \"title\": [\"العب بذكاء،\", \"واجمع 3 نجوم\"], \"sub\": \"أنهِ المرحلة بحركات متبقية واجمع كل النجوم.\", \"badges\": [[\"3 نجوم\"]] }\n }\n}\n", - "storebound.config.ts": "// storebound config for one game. Everything game-specific lives here; credentials NEVER do (they go in env vars or\n// .storebound/credentials.json, which must stay gitignored). Paths are relative to this file.\n// The type import is optional: it only works when storebound is installed in the project (bun add -d ).\nimport type { ShipConfig } from 'storebound';\n\nconst config: ShipConfig = {\n // Every compliance answer below is the TEMPLATE's, not yours. While an area is listed here, check / validate block\n // and nothing sends it to a store. Derive the answers from the code (storebound scan --write; for an app that is\n // already live: storebound onboard --declarations), answer the rest, then remove the area from this list.\n unanswered: ['dataSafety', 'appPrivacy', 'reviewNotes', 'ageRating'],\n\n app: {\n name: 'Example Game',\n profile: 'game',\n copyright: '2026 Example Studio',\n privacyPolicyUrl: 'https://example.com/privacy',\n supportUrl: 'https://example.com',\n marketingUrl: 'https://example.com',\n // Developer website on Play: the same domain must serve /app-ads.txt if the game shows ads\n website: 'https://example.com',\n contactEmail: 'support@example.com',\n },\n\n // id = your folder / copy key; play = Play language code(s); apple = App Store Connect locale\n languages: [\n { id: 'en', play: 'en-US', apple: 'en-US' },\n { id: 'tr', play: 'tr-TR', apple: 'tr' },\n { id: 'es', play: ['es-ES', 'es-419'], apple: 'es-ES' },\n { id: 'ja', play: 'ja-JP', apple: 'ja' },\n { id: 'ar', play: 'ar', apple: 'ar-SA', rtl: true },\n ],\n\n play: {\n packageName: 'com.example.game',\n defaultLanguage: 'en-US',\n listing: 'store/listing.md',\n icon: 'store/icons/play-512.png',\n // read by `storebound scan` (fill in what is true for your account and app):\n // accountType: 'personal', accountCreated: 'YYYY-MM-DD', // new personal accounts: 12 testers x 14 days closed test\n // targetAges: ['13-15', '16-17', '18+'], // App content > Target audience; under 13 = Families policy\n },\n\n apple: {\n bundleId: 'com.example.game',\n // name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there (\"already being used\"); default app.name\n // appId: '1234567890', // Apple ID of the app record; looked up by bundle id when left out\n listing: 'store/appstore.md',\n reviewShots: 'store/iap-review',\n // Export compliance (export-compliance skill). false ONLY if the game uses no encryption beyond the OS (HTTPS through\n // the system). Left unset on purpose: decide it, then uncomment. Same answer as ITSAppUsesNonExemptEncryption.\n // usesNonExemptEncryption: false,\n // ipad: true, // the app runs on iPad: 13\" iPad screenshots (2064 x 2752, ipad13) are rendered, checked and uploaded\n // iphoneMedium: true, // optional 6.3\" iPhone set (1206 x 2622, iphone-medium); off: Apple scales the 6.5\" set down\n // screenshotTypes: ['APP_IPHONE_67'], // what `storebound validate` requires per locale (default; + APP_IPAD_PRO_3GEN_129 with ipad)\n // TestFlight (`storebound apple testflight`, testflight skill). Tester emails live in .storebound/testers.csv only.\n testflight: {\n groups: [\n { name: 'Team', internal: true, allBuilds: true },\n { name: 'Friends' },\n ],\n description: { en: 'Example Game beta: try the new levels and tell us what feels too hard.' },\n },\n info: {\n categories: { primary: 'GAMES', primarySubOne: 'GAMES_CASUAL', primarySubTwo: 'GAMES_PUZZLE', secondary: 'ENTERTAINMENT' },\n ageRating: { advertising: true }, // everything else NONE / false\n contentRights: 'DOES_NOT_USE_THIRD_PARTY_CONTENT',\n free: true,\n reviewNotes: [\n 'Single-player game. No account or login is needed; there is no user-generated content or chat.',\n 'In-app purchases: Home > Shop. Restore Purchases is in Settings.',\n 'Ads: optional rewarded videos and interstitials between rounds. The App Tracking Transparency prompt is shown before the ad SDK starts.',\n 'Privacy policy: Settings > Privacy.',\n // With remote config, feature flags or a remotely changed paywall (storebound scan warns, 2.3.1) you may add:\n // 'Shop offers and prices shown come from and change remotely; no feature is switched on or off after review.',\n ].join('\\n\\n'),\n },\n },\n\n // Price changes later for many products / regions: storebound prices export, edit store/prices.csv, prices import --dry.\n // prices: { csv: 'store/prices.csv', baseTerritory: 'USA' },\n\n // Same ids on both stores. Prices: USD base; Play converts per region, Apple equalizes from the USA. Overrides set a\n // region by hand (Apple needs an existing price point with exactly that value).\n products: [\n {\n id: 'com.example.game.remove_ads', type: 'non_consumable', usd: 2.99,\n overrides: [{ region: 'TR', currency: 'TRY', price: 99.99 }],\n listings: {\n en: { title: 'Remove Ads', description: 'Removes interstitial ads for good.' },\n tr: { title: 'Reklamları Kaldır', description: 'Ara reklamları kalıcı olarak kaldırır.' },\n },\n reviewScreenshot: 'store/iap-review/shop.png',\n },\n {\n id: 'com.example.game.coins_small', type: 'consumable', usd: 0.99,\n listings: {\n en: { title: '500 Coins', description: 'A small bag of coins.' },\n tr: { title: '500 Altın', description: 'Küçük bir kese altın.' },\n },\n reviewScreenshot: 'store/iap-review/shop.png',\n },\n ],\n\n // Google Play Data safety. Types not listed = not collected. Purposes: functionality, analytics, communications,\n // fraud, advertising, personalization, account. Typical F2P game with an analytics SDK + ad mediation:\n dataSafety: {\n collectsData: true,\n encryptedInTransit: true,\n // No accounts: PSL_ACM_NONE. A guest account with a name picked on the device and a server token (no password, no\n // email): accounts { enabled: true, signUp: ['username'], ... } and ['PSL_ACM_USER_ID_OTHER_AUTH'] here (Play's\n // \"Username and other authentication\"; `storebound scan` proposes it). With accounts Play also requires the\n // delete-account URL (from accounts.deletionUrl). That page also answers \"can users request that their data is\n // deleted?\" with yes (dataDeletion: 'yes' | 'no' | 'auto90' only for apps without one). partialDeletion: true +\n // partialDeletionUrl when a page deletes data without deleting the account. `storebound check` compares every row with Play's\n // current form (cli/data/play-data-safety-form.csv).\n accountCreation: ['PSL_ACM_NONE'],\n data: {\n PSL_APPROX_LOCATION: { shared: true, collect: ['analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_USER_INTERACTION: { shared: true, collect: ['analytics', 'advertising'], share: ['analytics', 'advertising'] },\n PSL_OTHER_APP_ACTIVITY: { shared: false, collect: ['functionality'] },\n PSL_PERFORMANCE_DIAGNOSTICS: { shared: true, collect: ['analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_DEVICE_ID: { shared: true, collect: ['functionality', 'analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_PURCHASE_HISTORY: { shared: false, collect: ['functionality', 'fraud'] },\n },\n },\n\n // Ads: `storebound validate --play` checks /app-ads.txt for these lines (copy them from your mediation\n // dashboard's app-ads.txt page). Placeholder line below; replace it.\n // ads: { appAdsTxt: ['example-network.com, pub-0000000000000000, DIRECT, 0000000000000000'] },\n\n renders: 'store/renders',\n\n shots: {\n copy: 'store/shots/copy.json',\n frames: 'store/shots/frames', // /phone/.png, /tablet/.png\n out: 'store/renders',\n logo: 'store/shots/logo.png', // optional: hero scene + feature graphic\n // Google Fonts; both cover Latin Extended (tr, pl, cs, ro ...) and Vietnamese. `shots fonts` checks every glyph of the\n // copy; a character the font lacks needs a font that has it or fallback: ['Noto Sans Display'] (else shots check fails).\n fonts: { title: 'Paytone One', body: 'Montserrat' },\n // phone: { w: 440, h: 902, dpr: 3 }, // raw frame size in CSS px (screen below a 54 px status bar)\n // tablet: { w: 1032, h: 1352, dpr: 2 }, // default with apple.ipad (13\" iPad below its 24 px bar), else 800 x 1240\n scenes: [\n { id: 'hero', palette: 'fire', hero: true, over: 34, frames: [{ src: 'hero.png', rotate: -4 }],\n badges: [{ y: 0.42, side: 'l', icon: 'flag', iconBg: 'red', rot: -4 }, { y: 0.66, side: 'r', icon: 'offline', iconBg: 'red', rot: 3 }] },\n { id: 'play', palette: 'violet', frames: [{ src: 'gameplay.png', rotate: 3 }],\n badges: [{ y: 0.3, side: 'l', icon: 'bolt', iconBg: 'gold', rot: -3 }, { y: 0.7, side: 'r', hot: true, rot: 4 }] },\n { id: 'levels', palette: 'sky', frames: [{ src: 'level-b.png', scale: 0.82 }, { src: 'level-a.png', x: -31, dy: 10, scale: 0.7, rotate: -8 }, { src: 'level-c.png', x: 31, dy: 10, scale: 0.7, rotate: 8 }],\n badges: [{ y: 0.66, side: 'r', icon: 'map', iconBg: 'blue', rot: 3 }] },\n { id: 'stars', palette: 'gold', frames: [{ src: 'results.png', rotate: -3 }],\n badges: [{ y: 0.42, side: 'l', stars: true, rot: -3 }] },\n ],\n feature: { frame: 'hero.png', palette: 'fire' },\n capture: {\n baseUrl: 'http://127.0.0.1:5173',\n query: 'lang={lang}&noads=1&seed=1',\n shots: {\n 'hero': { path: '/?level=12', waitFor: \"window.game && game.state === 'playing'\", delayMs: 1500, device: 'both' },\n 'gameplay': { path: '/?level=3', delayMs: 2500, device: 'both' },\n 'level-a': { path: '/?level=20', delayMs: 2000 },\n 'level-b': { path: '/?level=40', delayMs: 2000 },\n 'level-c': { path: '/?level=60', delayMs: 2000 },\n 'results': { path: '/?level=5&result=3', delayMs: 2000, device: 'both' },\n },\n },\n },\n\n icons: {\n composite: 'store/icon/icon.png', // 1024 opaque\n foreground: 'store/icon/foreground.png', // 1024 RGBA, subject on transparent\n background: 'store/icon/background.png', // 1024 opaque\n out: 'store/icons',\n web: 'public/icons',\n // capacitorAssets: 'native/assets',\n // capacitorCommand: 'bunx @capacitor/assets generate --assetPath native/assets',\n // androidRes: 'native/android/app/src/main/res',\n },\n};\n\nexport default config;\n", + "storebound.config.ts": "// storebound config for one game. Everything game-specific lives here; credentials NEVER do (they go in env vars or\n// .storebound/credentials.json, which must stay gitignored). Paths are relative to this file.\n// The type import is optional: it only works when storebound is installed in the project (bun add -d ).\nimport type { ShipConfig } from 'storebound';\n\nconst config: ShipConfig = {\n // Every compliance answer below is the TEMPLATE's, not yours. While an area is listed here, check / validate block\n // and nothing sends it to a store. Derive the answers from the code (storebound scan --write; for an app that is\n // already live: storebound onboard --declarations), answer the rest, then remove the area from this list.\n unanswered: ['dataSafety', 'appPrivacy', 'reviewNotes', 'ageRating'],\n\n app: {\n name: 'Example Game',\n profile: 'game',\n copyright: '2026 Example Studio',\n privacyPolicyUrl: 'https://example.com/privacy',\n supportUrl: 'https://example.com',\n marketingUrl: 'https://example.com',\n // Developer website on Play: the same domain must serve /app-ads.txt if the game shows ads\n website: 'https://example.com',\n contactEmail: 'support@example.com',\n },\n\n // id = your folder / copy key; play = Play language code(s); apple = App Store Connect locale\n languages: [\n { id: 'en', play: 'en-US', apple: 'en-US' },\n { id: 'tr', play: 'tr-TR', apple: 'tr' },\n { id: 'es', play: ['es-ES', 'es-419'], apple: 'es-ES' },\n { id: 'ja', play: 'ja-JP', apple: 'ja' },\n { id: 'ar', play: 'ar', apple: 'ar-SA', rtl: true },\n ],\n\n play: {\n packageName: 'com.example.game',\n defaultLanguage: 'en-US',\n listing: 'store/listing.md',\n icon: 'store/icons/play-512.png',\n // read by `storebound scan` (fill in what is true for your account and app):\n // accountType: 'personal', accountCreated: 'YYYY-MM-DD', // new personal accounts: 12 testers x 14 days closed test\n // targetAges: ['13-15', '16-17', '18+'], // App content > Target audience; under 13 = Families policy\n },\n\n apple: {\n bundleId: 'com.example.game',\n // name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there (\"already being used\"); default app.name\n // appId: '1234567890', // Apple ID of the app record; looked up by bundle id when left out\n listing: 'store/appstore.md',\n reviewShots: 'store/iap-review',\n // Export compliance (export-compliance skill). false ONLY if the game uses no encryption beyond the OS (HTTPS through\n // the system). Left unset on purpose: decide it, then uncomment. Same answer as ITSAppUsesNonExemptEncryption.\n // usesNonExemptEncryption: false,\n // ipad: true, // the app runs on iPad: 13\" iPad screenshots (2064 x 2752, ipad13) are rendered, checked and uploaded\n // iphoneMedium: true, // optional 6.3\" iPhone set (1206 x 2622, iphone-medium); off: Apple scales the 6.5\" set down\n // screenshotTypes: ['APP_IPHONE_67'], // what `storebound validate` requires per locale (default; + APP_IPAD_PRO_3GEN_129 with ipad)\n // TestFlight (`storebound apple testflight`, testflight skill). Tester emails live in .storebound/testers.csv only.\n testflight: {\n groups: [\n { name: 'Team', internal: true, allBuilds: true },\n { name: 'Friends' },\n ],\n description: { en: 'Example Game beta: try the new levels and tell us what feels too hard.' },\n },\n info: {\n categories: { primary: 'GAMES', primarySubOne: 'GAMES_CASUAL', primarySubTwo: 'GAMES_PUZZLE', secondary: 'ENTERTAINMENT' },\n ageRating: { advertising: true }, // everything else NONE / false\n contentRights: 'DOES_NOT_USE_THIRD_PARTY_CONTENT',\n free: true,\n reviewNotes: [\n 'Single-player game. No account or login is needed; there is no user-generated content or chat.',\n 'In-app purchases: Home > Shop. Restore Purchases is in Settings.',\n 'Ads: optional rewarded videos and interstitials between rounds. The App Tracking Transparency prompt is shown before the ad SDK starts.',\n 'Privacy policy: Settings > Privacy.',\n // With remote config, feature flags or a remotely changed paywall (storebound scan warns, 2.3.1) you may add:\n // 'Shop offers and prices shown come from and change remotely; no feature is switched on or off after review.',\n // Google Play has no review-notes field: put the same line in reviewAccess.instructions (Play App content >\n // App access, 'Any other information') when the app has a sign-in, and say in the full description what needs\n // a paid subscription (Play: Deceptive behavior, Payments).\n ].join('\\n\\n'),\n },\n },\n\n // Price changes later for many products / regions: storebound prices export, edit store/prices.csv, prices import --dry.\n // prices: { csv: 'store/prices.csv', baseTerritory: 'USA' },\n\n // Same ids on both stores. Prices: USD base; Play converts per region, Apple equalizes from the USA. Overrides set a\n // region by hand (Apple needs an existing price point with exactly that value).\n products: [\n {\n id: 'com.example.game.remove_ads', type: 'non_consumable', usd: 2.99,\n overrides: [{ region: 'TR', currency: 'TRY', price: 99.99 }],\n listings: {\n en: { title: 'Remove Ads', description: 'Removes interstitial ads for good.' },\n tr: { title: 'Reklamları Kaldır', description: 'Ara reklamları kalıcı olarak kaldırır.' },\n },\n reviewScreenshot: 'store/iap-review/shop.png',\n },\n {\n id: 'com.example.game.coins_small', type: 'consumable', usd: 0.99,\n listings: {\n en: { title: '500 Coins', description: 'A small bag of coins.' },\n tr: { title: '500 Altın', description: 'Küçük bir kese altın.' },\n },\n reviewScreenshot: 'store/iap-review/shop.png',\n },\n ],\n\n // Google Play Data safety. Types not listed = not collected. Purposes: functionality, analytics, communications,\n // fraud, advertising, personalization, account. Typical F2P game with an analytics SDK + ad mediation:\n dataSafety: {\n collectsData: true,\n encryptedInTransit: true,\n // No accounts: PSL_ACM_NONE. A guest account with a name picked on the device and a server token (no password, no\n // email): accounts { enabled: true, signUp: ['username'], ... } and ['PSL_ACM_USER_ID_OTHER_AUTH'] here (Play's\n // \"Username and other authentication\"; `storebound scan` proposes it). With accounts Play also requires the\n // delete-account URL (from accounts.deletionUrl). That page also answers \"can users request that their data is\n // deleted?\" with yes (dataDeletion: 'yes' | 'no' | 'auto90' only for apps without one). partialDeletion: true +\n // partialDeletionUrl when a page deletes data without deleting the account. `storebound check` compares every row with Play's\n // current form (cli/data/play-data-safety-form.csv).\n accountCreation: ['PSL_ACM_NONE'],\n data: {\n PSL_APPROX_LOCATION: { shared: true, collect: ['analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_USER_INTERACTION: { shared: true, collect: ['analytics', 'advertising'], share: ['analytics', 'advertising'] },\n PSL_OTHER_APP_ACTIVITY: { shared: false, collect: ['functionality'] },\n PSL_PERFORMANCE_DIAGNOSTICS: { shared: true, collect: ['analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_DEVICE_ID: { shared: true, collect: ['functionality', 'analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_PURCHASE_HISTORY: { shared: false, collect: ['functionality', 'fraud'] },\n },\n },\n\n // Ads: `storebound validate --play` checks /app-ads.txt for these lines (copy them from your mediation\n // dashboard's app-ads.txt page). Placeholder line below; replace it.\n // ads: { appAdsTxt: ['example-network.com, pub-0000000000000000, DIRECT, 0000000000000000'] },\n\n renders: 'store/renders',\n\n shots: {\n copy: 'store/shots/copy.json',\n frames: 'store/shots/frames', // /phone/.png, /tablet/.png\n out: 'store/renders',\n logo: 'store/shots/logo.png', // optional: hero scene + feature graphic\n // Google Fonts; both cover Latin Extended (tr, pl, cs, ro ...) and Vietnamese. `shots fonts` checks every glyph of the\n // copy; a character the font lacks needs a font that has it or fallback: ['Noto Sans Display'] (else shots check fails).\n fonts: { title: 'Paytone One', body: 'Montserrat' },\n // phone: { w: 440, h: 902, dpr: 3 }, // raw frame size in CSS px (screen below a 54 px status bar)\n // tablet: { w: 1032, h: 1352, dpr: 2 }, // default with apple.ipad (13\" iPad below its 24 px bar), else 800 x 1240\n scenes: [\n { id: 'hero', palette: 'fire', hero: true, over: 34, frames: [{ src: 'hero.png', rotate: -4 }],\n badges: [{ y: 0.42, side: 'l', icon: 'flag', iconBg: 'red', rot: -4 }, { y: 0.66, side: 'r', icon: 'offline', iconBg: 'red', rot: 3 }] },\n { id: 'play', palette: 'violet', frames: [{ src: 'gameplay.png', rotate: 3 }],\n badges: [{ y: 0.3, side: 'l', icon: 'bolt', iconBg: 'gold', rot: -3 }, { y: 0.7, side: 'r', hot: true, rot: 4 }] },\n { id: 'levels', palette: 'sky', frames: [{ src: 'level-b.png', scale: 0.82 }, { src: 'level-a.png', x: -31, dy: 10, scale: 0.7, rotate: -8 }, { src: 'level-c.png', x: 31, dy: 10, scale: 0.7, rotate: 8 }],\n badges: [{ y: 0.66, side: 'r', icon: 'map', iconBg: 'blue', rot: 3 }] },\n { id: 'stars', palette: 'gold', frames: [{ src: 'results.png', rotate: -3 }],\n badges: [{ y: 0.42, side: 'l', stars: true, rot: -3 }] },\n ],\n feature: { frame: 'hero.png', palette: 'fire' },\n capture: {\n baseUrl: 'http://127.0.0.1:5173',\n query: 'lang={lang}&noads=1&seed=1',\n shots: {\n 'hero': { path: '/?level=12', waitFor: \"window.game && game.state === 'playing'\", delayMs: 1500, device: 'both' },\n 'gameplay': { path: '/?level=3', delayMs: 2500, device: 'both' },\n 'level-a': { path: '/?level=20', delayMs: 2000 },\n 'level-b': { path: '/?level=40', delayMs: 2000 },\n 'level-c': { path: '/?level=60', delayMs: 2000 },\n 'results': { path: '/?level=5&result=3', delayMs: 2000, device: 'both' },\n },\n },\n },\n\n icons: {\n composite: 'store/icon/icon.png', // 1024 opaque\n foreground: 'store/icon/foreground.png', // 1024 RGBA, subject on transparent\n background: 'store/icon/background.png', // 1024 opaque\n out: 'store/icons',\n web: 'public/icons',\n // capacitorAssets: 'native/assets',\n // capacitorCommand: 'bunx @capacitor/assets generate --assetPath native/assets',\n // androidRes: 'native/android/app/src/main/res',\n },\n};\n\nexport default config;\n", "testers.csv": "email,first_name,last_name,groups\n", "web/appstore.svg": "App Store", "web/googleplay.svg": "Google Play", diff --git a/templates/profiles/app/storebound.config.ts b/templates/profiles/app/storebound.config.ts index f5db7e0..52bb056 100644 --- a/templates/profiles/app/storebound.config.ts +++ b/templates/profiles/app/storebound.config.ts @@ -72,6 +72,9 @@ const config: ShipConfig = { 'Privacy policy and Terms: Settings > About.', // With remote config or feature flags (storebound scan warns, 2.3.1) you may add a line like: // 'Some features are configured remotely with : ; none is switched on after review without a new submission.', + // Google Play has no review-notes field: put the same line in reviewAccess.instructions (Play App content > + // App access, 'Any other information') when the app has a sign-in, and say in the full description what needs + // a paid subscription (Play: Deceptive behavior, Payments). ].join('\n\n'), }, }, diff --git a/templates/profiles/subscription-app/storebound.config.ts b/templates/profiles/subscription-app/storebound.config.ts index 4277289..ff0b692 100644 --- a/templates/profiles/subscription-app/storebound.config.ts +++ b/templates/profiles/subscription-app/storebound.config.ts @@ -73,6 +73,9 @@ const config: ShipConfig = { 'Privacy policy and Terms of Use: on the paywall and in Settings > About.', // With a remote paywall or feature flags (storebound scan warns, 2.3.1) you may add a line like: // 'Paywall designs and the prices shown are tested remotely with ; what Pro unlocks does not change after review.', + // Google Play has no review-notes field: put the same line in reviewAccess.instructions (Play App content > + // App access, 'Any other information') when the app has a sign-in, and say in the full description what needs + // a paid subscription (Play: Deceptive behavior, Payments). ].join('\n\n'), }, }, diff --git a/templates/storebound.config.ts b/templates/storebound.config.ts index aceb998..38d6827 100644 --- a/templates/storebound.config.ts +++ b/templates/storebound.config.ts @@ -72,6 +72,9 @@ const config: ShipConfig = { 'Privacy policy: Settings > Privacy.', // With remote config, feature flags or a remotely changed paywall (storebound scan warns, 2.3.1) you may add: // 'Shop offers and prices shown come from and change remotely; no feature is switched on or off after review.', + // Google Play has no review-notes field: put the same line in reviewAccess.instructions (Play App content > + // App access, 'Any other information') when the app has a sign-in, and say in the full description what needs + // a paid subscription (Play: Deceptive behavior, Payments). ].join('\n\n'), }, }, From 6d95ea00f53de8c9e6916bdbdb0625d201be04b4 Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 18 Oct 2026 01:31:17 +0800 Subject: [PATCH 012/344] agent rules: every check, rule, template line, message and desktop view covers both stores and every surface --- AGENTS.md | 2 ++ tools/gen-adapters.ts | 2 ++ 2 files changed, 4 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 4920362..437ef2a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -127,4 +127,6 @@ need to ...", do it instead, unless it is one of the owner steps in point 2. - Inner loop: `bun run ci:quick` (typecheck, the tests related to your change against origin/main, scrub; seconds). Before every push: the full `bun run ci` (every check and test, in parallel shards), and check its exit code. - Skills are the single source: edit `skills/*/SKILL.md` or `docs/agents-core.md`, then `bun tools/gen-adapters.ts`. +- Every check, rule, template line, message and desktop view covers both stores (App Store and Google Play) and every + surface (CLI, MCP, desktop, skills); when a store has no equivalent field, say where the same thing goes there. - Never commit credentials, account / team / issuer / key / app ids or personal data; placeholders use example.com. diff --git a/tools/gen-adapters.ts b/tools/gen-adapters.ts index 875b692..cba4d50 100644 --- a/tools/gen-adapters.ts +++ b/tools/gen-adapters.ts @@ -87,6 +87,8 @@ export function generate(root: string): Map { '- Inner loop: `bun run ci:quick` (typecheck, the tests related to your change against origin/main, scrub; seconds).', ' Before every push: the full `bun run ci` (every check and test, in parallel shards), and check its exit code.', '- Skills are the single source: edit `skills/*/SKILL.md` or `docs/agents-core.md`, then `bun tools/gen-adapters.ts`.', + '- Every check, rule, template line, message and desktop view covers both stores (App Store and Google Play) and every', + ' surface (CLI, MCP, desktop, skills); when a store has no equivalent field, say where the same thing goes there.', '- Never commit credentials, account / team / issuer / key / app ids or personal data; placeholders use example.com.', ''].join('\n')); From af349b3db1a3a0a2dc9092b9ce6e09cfc8076299 Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 18 Oct 2026 01:42:03 +0800 Subject: [PATCH 013/344] report: storebound report writes one shareable, self-contained readiness page (.storebound/reports/readiness-.html; --md, --json, --no-open, --offline, --out) from scan, check and validate: a verdict per store (Ready to submit / N blockers / Not checked with the reason), findings per store by severity with guideline, evidence, fix and console button, the owner's compliance questions as a checklist, secrets masked; storebound.dev look, light / dark, print; desktop Checks > Report (same code path, opens through project_reveal) and its Markdown export on the same renderer; read-only MCP tool report --- CHANGELOG.md | 8 + apps/desktop/src-tauri/src/policy.rs | 9 +- apps/desktop/src-tauri/tests/complete.rs | 4 + apps/desktop/src/dev/fixtures.ts | 9 +- apps/desktop/src/i18n/en.ts | 8 + apps/desktop/src/i18n/tr.ts | 8 + apps/desktop/src/lib/exports.ts | 12 +- apps/desktop/src/screens/tabs/Checks.tsx | 45 +++- cli/commands.ts | 1 + cli/data/flags.json | 21 ++ cli/lib/report.ts | 330 +++++++++++++++++++++++ cli/mcp-tools.ts | 4 + cli/report.ts | 182 +++++++++++++ cli/serve.ts | 2 +- docs/commands.md | 1 + docs/mcp.md | 2 +- skills/store-preflight/SKILL.md | 8 + tests/report.test.ts | 150 +++++++++++ 18 files changed, 792 insertions(+), 12 deletions(-) create mode 100644 cli/lib/report.ts create mode 100644 cli/report.ts create mode 100644 tests/report.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 128d4c5..4642fa6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ ## Unreleased +- **Shareable readiness report.** `storebound report` puts `scan`, `check` and `validate` into one self-contained HTML + page (`.storebound/reports/readiness-.html`, inline CSS, no scripts, light / dark, print-friendly) and opens it + in the browser: a verdict per store ("Ready to submit", "N blockers", "Not checked" with the reason when a store key + is missing), findings per store by severity with guideline, evidence, fix and an Open in App Store Connect / Play + Console button, and the questions only the owner can answer as a checklist. Credentials, key ids, emails and the + review demo account are masked. `--md`, `--json`, `--no-open`, `--offline`, `--out`. The desktop's Checks tab has a + Report button (same code path) and its Markdown export uses the same renderer; MCP gets a read-only `report` tool. + - **Remote config and remote paywalls (App Review 2.3.1, Play Deceptive behavior).** `storebound scan` (and `validate`; `check` as a warning) reports `remote-features` for both stores when the app ships a remote config / feature flag SDK (Firebase Remote Config, Statsig, LaunchDarkly, GrowthBook, Optimizely, PostHog feature flags, diff --git a/apps/desktop/src-tauri/src/policy.rs b/apps/desktop/src-tauri/src/policy.rs index d8c608a..a03dc88 100644 --- a/apps/desktop/src-tauri/src/policy.rs +++ b/apps/desktop/src-tauri/src/policy.rs @@ -174,9 +174,14 @@ pub fn project_relative(rel: &str) -> Option { Some(p.to_path_buf()) } -/// What `project_reveal` may open (not only show in the file manager): a folder, or the gallery page storebound writes. +/// What `project_reveal` may open (not only show in the file manager): a folder, the gallery page storebound writes, +/// or a readiness report page of `storebound report` (.storebound/reports/readiness-*.html, no scripts in it). pub fn openable(rel: &std::path::Path, is_dir: bool) -> bool { - is_dir || rel.file_name().and_then(|n| n.to_str()) == Some("index.html") + if is_dir || rel.file_name().and_then(|n| n.to_str()) == Some("index.html") { + return true; + } + let parts: Vec<&str> = rel.components().filter_map(|c| c.as_os_str().to_str()).collect(); + matches!(parts.as_slice(), [".storebound", "reports", name] if name.starts_with("readiness-") && name.ends_with(".html") && name.len() <= 80) } /// Hosts `open_external` may open in the browser: the two store consoles and storebound's own site. diff --git a/apps/desktop/src-tauri/tests/complete.rs b/apps/desktop/src-tauri/tests/complete.rs index 798002e..e894dbf 100644 --- a/apps/desktop/src-tauri/tests/complete.rs +++ b/apps/desktop/src-tauri/tests/complete.rs @@ -32,6 +32,10 @@ fn app_folder_paths() { assert!(openable(Path::new("store/renders/index.html"), false)); assert!(openable(Path::new("store/renders"), true)); assert!(!openable(Path::new("store/renders/run.sh"), false)); + assert!(openable(Path::new(".storebound/reports/readiness-2026-10-18.html"), false)); + assert!(!openable(Path::new(".storebound/reports/readiness-2026-10-18.sh"), false)); + assert!(!openable(Path::new(".storebound/credentials.json"), false)); + assert!(!openable(Path::new("other/reports/readiness-2026-10-18.html"), false)); assert!(!openable(Path::new("store/prices.csv"), false)); } diff --git a/apps/desktop/src/dev/fixtures.ts b/apps/desktop/src/dev/fixtures.ts index ecf2f05..1189868 100644 --- a/apps/desktop/src/dev/fixtures.ts +++ b/apps/desktop/src/dev/fixtures.ts @@ -5,6 +5,7 @@ // not contain it (tests/webview.test.ts checks the built files for FIXTURE_MARKER). import { type Account, type AccountCheck, type ConsoleFillResult, type ConsoleForm, type AppsListResult, type AppStatus, type CacheEntry, DEFAULT_SETTINGS, type DownloadEvent, type DraftsResult, type ListingField, type ListingsResult, type PortfolioResult, type Project, type ProjectSummary, type Settings, type StoreApp, type StoreRelease, type Studio, type ToolResult } from '../api'; +import { buildReport } from '../../../../cli/lib/report'; import { buildApps, type Overrides } from '../lib/identity'; import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult, ScanResult } from '../lib/model'; import { editableFixture, liveFixture } from './editor-fixtures'; @@ -461,6 +462,12 @@ function read(method: string, id: string, args: Record = {}): T case 'apple.testflight_status': return ok(method, TF[id]); case 'catalog.diff': return ok(method, CATALOG[id]); case 'validate': return ok(method, VALIDATE[id]); + case 'report': { + const sum = SUMMARY[id]; + const r = buildReport({ app: { name: sum?.name ?? id }, stores: (['apple', 'play'] as const).filter(x => !!sum?.[x]), storeRead: { apple: true, play: 'no Play service account' }, + generatedAt: new Date().toISOString(), storebound: 'fixture', validate: VALIDATE[id] as never, scan: (SCAN[id] ?? SCAN_EMPTY) as never }); + return ok(method, { file: `/fixture/${id}/.storebound/reports/readiness.html`, path: '.storebound/reports/readiness.html', ...r }); + } case 'scan': return ok(method, SCAN[id] ?? SCAN_EMPTY); case 'project.declarations': return ok(method, DECLARATIONS[id]); case 'project.listing_text': return ok(method, LISTING_TEXT[id]); @@ -505,7 +512,7 @@ const CONSOLE_FILL: Record = { }; const CACHED_AGO: Record = { health: 60 * 3, 'reviews.list': 45, 'apple.testflight_status': 60 * 5, 'catalog.diff': 60 * 26, validate: 60 * 2, 'prices.current': 60 * 4, 'apple.ppo_status': 60 * 6 }; -const NETWORK = new Set(['health', 'health.issue', 'reviews.list', 'apple.testflight_status', 'catalog.diff', 'validate', 'prices.current', 'prices.diff', 'apple.ppo_status', 'apple.status', 'play.status', 'console.verify']); +const NETWORK = new Set(['health', 'health.issue', 'reviews.list', 'apple.testflight_status', 'catalog.diff', 'validate', 'report', 'prices.current', 'prices.diff', 'apple.ppo_status', 'apple.status', 'play.status', 'console.verify']); async function progressLines(job: string | null, lines: string[]) { for (const line of lines) { await sleep(260); if (job) emit('sidecar-progress', { params: { requestId: 1, line, stream: 'stderr' }, job }); } diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 730adf0..58c20e5 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -422,6 +422,14 @@ export const en = { 'checks.problem': 'Problem', 'checks.warning': 'Warning', 'checks.validate': 'Store readiness', + 'checks.report': 'Shareable report', + 'checks.reportSub': 'One page for both stores with every finding, fix and console link, and the questions only you can answer. Opens in your browser; nothing is sent to a store.', + 'checks.reportOpen': 'Report', + 'checks.reportFailed': 'The report was not written', + 'checks.reportBlockers': '{count} blocker(s)', + 'checks.reportNotChecked': 'not checked (no store key)', + 'checks.reportNotSetUp': 'not set up', + 'checks.reportReady': 'ready to submit', 'checks.validateSub': 'Read-only report from both stores, blockers in order', 'checks.run': 'Run the report', 'checks.validateEmpty': 'Readiness not checked yet', diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index aca173a..a660602 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -424,6 +424,14 @@ export const tr: Record = { 'checks.problem': 'Sorun', 'checks.warning': 'Uyarı', 'checks.validate': 'Mağaza hazırlığı', + 'checks.report': 'Paylaşılabilir rapor', + 'checks.reportSub': 'İki mağaza için tek sayfa: her bulgu, düzeltme ve konsol bağlantısı, yalnızca senin yanıtlayabileceğin sorular. Tarayıcında açılır; mağazaya hiçbir şey gönderilmez.', + 'checks.reportOpen': 'Rapor', + 'checks.reportFailed': 'Rapor yazılamadı', + 'checks.reportBlockers': '{count} engel', + 'checks.reportNotChecked': 'kontrol edilmedi (mağaza anahtarı yok)', + 'checks.reportNotSetUp': 'kurulmamış', + 'checks.reportReady': 'gönderime hazır', 'checks.validateSub': 'İki mağazadan salt okunur rapor, engeller sırayla', 'checks.run': 'Raporu çalıştır', 'checks.validateEmpty': 'Hazırlık henüz kontrol edilmedi', diff --git a/apps/desktop/src/lib/exports.ts b/apps/desktop/src/lib/exports.ts index d918dfb..e4a7430 100644 --- a/apps/desktop/src/lib/exports.ts +++ b/apps/desktop/src/lib/exports.ts @@ -4,6 +4,7 @@ import type { AnalyticsCompare, AppStatus, DeclarationsResult, ListingText, PricesCurrent } from '../api'; import type { CatalogDiff, HealthSnapshot, Review, ValidateResult } from './model'; import { isError } from './model'; +import { buildReport, renderMarkdown } from '../../../../cli/lib/report'; type Cell = string | number | boolean | null | undefined; @@ -62,11 +63,12 @@ export function healthMd(app: string, h: HealthSnapshot): string { return out.join('\n'); } -export function validateMd(app: string, v: ValidateResult, at: string | null): string { - const lvl = (l: string) => (l === 'blocker' ? 'Blocker' : l === 'warn' ? 'Warning' : 'OK'); - return [`# ${app}: store readiness`, '', `Read ${at ?? 'now'} · ${v.blockers} blocker(s), ${v.findings.filter(f => f.level === 'warn').length} warning(s)`, '', - mdTable(['store', 'level', 'check', 'finding', 'fix'], v.findings.map(f => [f.store === 'apple' ? 'App Store' : 'Google Play', lvl(f.level), f.code, f.msg, f.fix ?? ''])), - ].join('\n'); +/** The store readiness export: the same report and Markdown renderer as `storebound report --md` (cli/lib/report.ts), + * from what the Checks tab read (validate, the offline check, the scan when it ran). */ +export function validateMd(app: string, v: ValidateResult, at: string | null, more: { check?: { problems: string[]; warnings: string[] } | null; scan?: unknown; version?: string; stores?: ('apple' | 'play')[] } = {}): string { + const r = buildReport({ app: { name: app }, ...(more.stores ? { stores: more.stores } : {}), generatedAt: at ?? new Date().toISOString(), storebound: more.version ?? 'desktop', + validate: v as never, check: more.check ?? null, scan: (more.scan ?? null) as never, storeRead: { apple: true, play: true } }); + return renderMarkdown(r); } export function catalogMd(app: string, c: CatalogDiff): string { diff --git a/apps/desktop/src/screens/tabs/Checks.tsx b/apps/desktop/src/screens/tabs/Checks.tsx index 903880d..1752997 100644 --- a/apps/desktop/src/screens/tabs/Checks.tsx +++ b/apps/desktop/src/screens/tabs/Checks.tsx @@ -7,7 +7,9 @@ import type { Finding, FixAction, ScanFinding, ScanResult, ScanSeverity, Validat import { useData, useRead, useWrite } from '../../store'; import { WriteButton } from '../../ui/WriteButton'; import { AiFix, aiFinding } from '../../ui/AiFix'; -import { api } from '../../api'; +import { api, errorText, newJob } from '../../api'; +import type { ToolResult } from '../../api'; +import type { ReportData } from '../../../../../cli/lib/report'; import { useEffect, useState } from 'react'; import { Icon } from '../../ui/icons'; import { OpenLink } from '../../ui/OpenLink'; @@ -15,6 +17,8 @@ import { Card, Chip, Empty, ErrorNotice, ReadControl, Skeleton } from '../../ui/ import { exportName, validateMd } from '../../lib/exports'; import { useExports } from '../../ui/Exports'; +type ReportResult = ReportData & { file: string; path: string }; + const LEVEL: Record = { blocker: ['bad', 'alertCircle'], warn: ['warn', 'alert'], ok: ['ok', 'check'] }; /** Fix methods the window runs from a finding (cli/lib/fix-actions.ts FIX_METHODS): local config writes and store @@ -93,18 +97,55 @@ function ScanCard({ project }: { project: Project }) { ); } +/** The shareable readiness report (`storebound report`, the same code path as the CLI): one HTML page in + * .storebound/reports/, opened in the default browser through project_reveal (the host only opens that page). */ +function ReportBar({ project }: { project: Project }) { + const d = useData(); + const [busy, setBusy] = useState(false); + const [last, setLast] = useState(null); + const run = async () => { + setBusy(true); + try { + const r = await api.call('report', project.id, {}, newJob('report')); + if (!r.ok || !r.data?.path) throw new Error(r.output || t('checks.reportFailed')); + setLast(r.data); + await api.reveal(project.id, r.data.path, true); + } catch (e) { d.toast({ kind: 'bad', title: t('checks.reportFailed'), detail: errorText(e) }); } + finally { setBusy(false); } + }; + return ( + {t('checks.reportOpen')}}> + {null} + + ); +} + +/** One line, both stores: "App Store: 2 blockers · Google Play: not checked". */ +export function reportSummary(r: ReportResult): string { + const one = (s: 'apple' | 'play') => { + const x = r.summary[s], read = r.read[s]; + const v = x.blockers ? t('checks.reportBlockers', { count: x.blockers }) : !r.stores.includes(s) ? t('checks.reportNotSetUp') : !read.checked ? t('checks.reportNotChecked') : t('checks.reportReady'); + return `${s === 'apple' ? 'App Store' : 'Google Play'}: ${v}`; + }; + return `${one('apple')} · ${one('play')}`; +} + export function ChecksTab({ project }: { project: Project }) { const d = useData(); const e = d.statusOf(project); const v = useRead(project.id, 'validate', { network: true, title: t('checks.validate') }); const w = useWrite(project.id); const name = e?.summary?.name ?? project.name; - useExports('checks', [{ id: 'validate-md', label: t('export.validate'), icon: 'shield', kind: 'md', file: exportName(name, 'store readiness'), disabled: v.data ? false : t('export.readFirst'), build: () => validateMd(name, v.data!, v.at) }]); + const stores = (['apple', 'play'] as const).filter(x => !!e?.summary?.[x]); + useExports('checks', [{ id: 'validate-md', label: t('export.validate'), icon: 'shield', kind: 'md', file: exportName(name, 'store readiness'), disabled: v.data ? false : t('export.readFirst'), + build: () => validateMd(name, v.data!, v.at, { check: e?.check ?? null, version: d.info?.version, ...(stores.length ? { stores } : {}) }) }]); const problems = [...(e?.errors ?? []), ...(e?.check?.problems ?? [])]; const warnings = e?.check?.warnings ?? []; const findings = [...(v.data?.findings ?? [])].sort((a, b) => ['blocker', 'warn', 'ok'].indexOf(a.level) - ['blocker', 'warn', 'ok'].indexOf(b.level)); return (
+
d.refreshPortfolio(false)} disabled={!!d.portfolioBusy}>{t('checks.again')}}> diff --git a/cli/commands.ts b/cli/commands.ts index 9918485..151c217 100644 --- a/cli/commands.ts +++ b/cli/commands.ts @@ -29,6 +29,7 @@ export const COMMANDS: Record Promise, string]> = { 'inspect': [() => import('./inspect'), 'offline summary of the config (name, store ids, languages, products, subscriptions); --json'], 'check': [() => import('./check'), 'validate config, copy files, data safety answers, products, subscriptions and the app profile (offline); --aso keyword audit'], 'validate': [() => import('./validate'), 'read-only store readiness report with ordered blockers (--apple / --play), plus local renders checks (--no-local skips); exit 1 on blockers'], + 'report': [() => import('./report'), 'shareable store readiness report: scan + check + validate (read-only; only the stores with credentials, else it says why) in one self-contained HTML page .storebound/reports/readiness-.html, opened in the browser; --out , --md, --json, --no-open, --offline'], 'analytics': [() => import('./analytics'), 'setup (App Store report request) | snapshot (impressions, page views, installs, conversion -> .storebound/analytics) | compare (vs listing changes in git)'], 'health': [() => import('./health'), 'crash / ANR vitals (Play) and diagnostics (App Store), read-only; --weekly writes a markdown report; exit 1 over a threshold'], 'art': [() => import('./art'), 'pull [--store apple|play] [--write] [--force]: the live store art (App Store screenshot sets, previews, icon; Play icon, feature graphic, screenshots per language) into store/renders + pulled.json, so checks and uploads treat it like rendered art (upsert; differing local files kept without --force; read-only on the stores) | live [--json]: the live art with thumbnails | replace --from --to : one image of the app folder'], diff --git a/cli/data/flags.json b/cli/data/flags.json index b9cf5c7..467de14 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -699,6 +699,23 @@ "versions", "workspace" ], + "report": [ + "capacitor", + "cordova", + "cordova-android", + "cordova-ios", + "expo", + "flutter", + "godot", + "md", + "name", + "no-open", + "offline", + "out", + "react-native", + "sku", + "unity" + ], "reports": [ "csv", "date", @@ -996,6 +1013,7 @@ "no-local", "no-mcp", "no-only-decreases", + "no-open", "no-prebuild", "no-save", "no-scan", @@ -1394,6 +1412,9 @@ "storebound privacy-manifest --ios ios/App [--sdk-dirs node_modules/@capacitor,node_modules/some-plugin] [--json]", "storebound privacy-manifest --ios ios/App --propose [--tracking-domains a.example.com,b.example.com]" ], + "report": [ + "storebound report [--out ] [--md] [--json] [--no-open] [--offline]" + ], "reports": [ "storebound reports apple-sales [--type SALES] [--frequency DAILY|WEEKLY|MONTHLY|YEARLY] [--date ...] [--vendor N]", "storebound reports apple-finance --month YYYY-MM [--detail] [--region ZZ] [--vendor N]", diff --git a/cli/lib/report.ts b/cli/lib/report.ts new file mode 100644 index 0000000..d713dd6 --- /dev/null +++ b/cli/lib/report.ts @@ -0,0 +1,330 @@ +// The shareable store readiness report (`storebound report`, the desktop's Report button and its Markdown export, the +// MCP `report` tool): one data shape built from `scan`, `check` and `validate`, rendered as a self-contained HTML page +// (inline CSS, no scripts, no external requests, light and dark), as Markdown or as JSON. Pure: no file system, no +// network, so the desktop window imports it too. Every text goes through maskSecrets: credentials, key ids, emails, +// tokens and the review demo account never reach the page (the command also passes the literal values it knows). + +export type ReportStore = 'apple' | 'play' | 'both'; +export type ReportLevel = 'blocker' | 'warn' | 'ok' | 'info'; +export type ReportSource = 'scan' | 'check' | 'validate'; + +export interface ReportFinding { + store: ReportStore; + level: ReportLevel; + source: ReportSource; + /** Rule / check id (scan rule, validate code, "check"). */ + rule: string; + guideline?: string; + title: string; + /** file:line evidence. */ + evidence: string[]; + fix?: string; + /** Absolute console deep link. */ + url?: string; +} + +export interface ReportQuestion { store: ReportStore; text: string; source: string; /** Console page where it is answered. */ url?: string } +export interface SourceState { ran: boolean; note?: string } +export interface StoreSummary { blockers: number; warnings: number; ok: number } + +export interface ReportData { + app: { name: string; version?: string; build?: string }; + /** The stores the config has (the summary shows these and "both"). */ + stores: ('apple' | 'play')[]; + /** Per store: was the store itself read (validate), and if not, why. */ + read: Record<'apple' | 'play', { checked: boolean; why?: string }>; + generatedAt: string; + storebound: string; + sources: Record; + summary: Record; + findings: ReportFinding[]; + questions: ReportQuestion[]; +} + +// ---- inputs (the --json shapes of the three commands) ---- + +export interface ScanInput { + findings?: { rule: string; guideline: string; store: 'apple' | 'play'; severity: 'blocker' | 'high' | 'medium' | 'low'; title: string; evidence?: { file: string; line: number }[]; url?: string; fix: string; skill?: string; accepted?: string }[]; + declarations?: { items?: { area: string; what: string; value: string; status: 'detected' | 'ask'; note?: string }[] }; +} +export interface CheckInput { ok?: boolean; items?: { what: string; detail: string }[]; warnings?: string[]; hints?: string[]; problems?: string[] } +export interface ValidateInput { blockers?: number; findings?: { store: 'apple' | 'play'; level: 'blocker' | 'warn' | 'ok'; code: string; msg: string; fix?: string; url?: string }[] } + +export interface BuildInput { + app: ReportData['app']; + stores?: ('apple' | 'play')[]; + /** Per store: true when validate read it, else the reason it did not. */ + storeRead?: Partial>; + generatedAt: string; + storebound: string; + /** Console deep link for a finding that carries none (cli/lib/console-links.ts, chosen by the command). */ + linkFor?: (f: ReportFinding) => string | undefined; + scan?: ScanInput | null; + check?: CheckInput | null; + validate?: ValidateInput | null; + /** Why a source did not run (e.g. no credentials). */ + notes?: Partial>; + /** Questions from elsewhere (console plans' ask-owner answers). */ + questions?: ReportQuestion[]; + /** Literal secret values to mask wherever they appear. */ + secrets?: string[]; +} + +const ORDER: ReportLevel[] = ['blocker', 'warn', 'info', 'ok']; +const STORES: ReportStore[] = ['apple', 'play', 'both']; +export const STORE_LABEL: Record = { apple: 'App Store', play: 'Google Play', both: 'Both stores' }; +const LEVEL_LABEL: Record = { blocker: 'Blocker', warn: 'Warning', info: 'Note', ok: 'OK' }; +/** A message that asks the owner for an answer only they know (compliance). */ +const ASK_RE = /ask the owner|still to answer|still holds template answers|answers? (?:is|are) not in the config/i; + +/** The store a free-text check line is about, from its prefix. */ +function storeOf(msg: string): ReportStore { + if (/^(play|google play|android)\b/i.test(msg)) return 'play'; + if (/^(apple|app store|appstore|ios|testflight)\b/i.test(msg)) return 'apple'; + return 'both'; +} + +/** Masks anything that looks like a secret: PEM blocks, private key JSON, JWTs, emails, UUIDs (issuer ids), App Store + * Connect key ids, long tokens, plus every literal value in `known`. */ +export function maskSecrets(text: string, known: string[] = []): string { + let s = text; + for (const k of [...new Set(known)].filter(k => k && k.length >= 4).sort((a, b) => b.length - a.length)) s = s.split(k).join('[hidden]'); + return s + .replace(/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(-----END [A-Z ]*PRIVATE KEY-----|$)/g, '[private key hidden]') + .replace(/"private_key(_id)?"\s*:\s*"[^"]*"/g, '"private_key$1": "[hidden]"') + .replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g, '[token hidden]') + .replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, m => (/@example\.(com|org|net)$/i.test(m) ? m : '[email hidden]')) + .replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, '[id hidden]') + .replace(/\b(?=[A-Z0-9]*\d)(?=[A-Z0-9]*[A-Z])[A-Z0-9]{10}\b/g, '[key id hidden]') + .replace(/\b(?:sk|pk|rk|ghp|gho|xox[abp]|AIza)[_-]?[A-Za-z0-9_-]{16,}\b/g, '[token hidden]') + .replace(/\b[A-Za-z0-9+/_-]{40,}={0,2}/g, m => (/\d/.test(m) && /[A-Za-z]/.test(m) && !(m.includes('/') && !/[+=]/.test(m)) ? '[token hidden]' : m)); +} + +const severityLevel = (s: string): ReportLevel => (s === 'blocker' ? 'blocker' : s === 'low' ? 'info' : 'warn'); + +/** One report from the three command outputs: findings deduplicated, findings shown on both stores merged into + * "both", sorted by severity, the owner's open questions collected. */ +export function buildReport(i: BuildInput): ReportData { + const raw: ReportFinding[] = []; + for (const f of i.scan?.findings ?? []) { + if (f.accepted) continue; + raw.push({ store: f.store, level: severityLevel(f.severity), source: 'scan', rule: f.rule, guideline: f.guideline, title: f.title, + evidence: (f.evidence ?? []).slice(0, 5).map(e => `${e.file}:${e.line}`), fix: f.skill ? `${f.fix} (skill: ${f.skill})` : f.fix, ...(f.url ? { url: f.url } : {}) }); + } + const c = i.check; + for (const p of c?.problems ?? []) raw.push({ store: storeOf(p), level: 'blocker', source: 'check', rule: 'check', title: p, evidence: [] }); + for (const w of c?.warnings ?? []) raw.push({ store: storeOf(w), level: 'warn', source: 'check', rule: 'check', title: w, evidence: [] }); + for (const h of c?.hints ?? []) raw.push({ store: storeOf(h), level: 'info', source: 'check', rule: 'check', title: h, evidence: [] }); + for (const it of c?.items ?? []) raw.push({ store: storeOf(it.what), level: 'ok', source: 'check', rule: 'check', title: `${it.what}: ${it.detail}`, evidence: [] }); + for (const f of i.validate?.findings ?? []) { + const ev = /\(([^()\s]+:\d+)\)\s*$/.exec(f.msg)?.[1]; + raw.push({ store: f.store, level: f.level, source: 'validate', rule: f.code, title: f.msg, evidence: ev ? [ev] : [], ...(f.fix ? { fix: f.fix } : {}), ...(f.url ? { url: f.url } : {}) }); + } + // same text on both stores -> one "both" finding; exact duplicates (validate repeats check's template lines) dropped + const key = (f: ReportFinding) => `${f.level}|${f.rule}|${f.title}`; + const seen = new Map(); + for (const f of raw) { + const k = key(f); + const had = seen.get(k) ?? [...seen.values()].find(x => x.title === f.title && x.level === f.level); + if (!had) { seen.set(k, { ...f }); continue; } + if (had.store !== f.store) had.store = 'both'; + if (!had.url && f.url) had.url = f.url; + if (!had.fix && f.fix) had.fix = f.fix; + } + if (i.linkFor) for (const f of seen.values()) if (!f.url && f.level !== 'ok') { const u = i.linkFor(f); if (u) f.url = u; } + const findings = [...seen.values()].sort((a, b) => ORDER.indexOf(a.level) - ORDER.indexOf(b.level) || STORES.indexOf(a.store) - STORES.indexOf(b.store)); + + const questions: ReportQuestion[] = []; + const ask = (q: ReportQuestion) => { if (!questions.some(x => x.text === q.text)) questions.push(q); }; + for (const d of i.scan?.declarations?.items ?? []) if (d.status === 'ask' && d.area !== 'privacyManifest') ask({ store: d.area === 'appPrivacy' || d.area === 'att' ? 'apple' : d.area === 'dataSafety' ? 'play' : 'both', text: `${d.what}: ${d.value}${d.note ? ` (${d.note})` : ''}`, source: 'scan' }); + for (const f of findings) if (f.level !== 'ok' && ASK_RE.test(f.title)) ask({ store: f.store, text: f.title, source: f.source }); + for (const q of i.questions ?? []) ask(q); + + const summary = Object.fromEntries(STORES.map(s => [s, { blockers: 0, warnings: 0, ok: 0 }])) as Record; + for (const f of findings) { + const s = summary[f.store]; + if (f.level === 'blocker') s.blockers++; else if (f.level === 'warn') s.warnings++; else if (f.level === 'ok') s.ok++; + } + const sources: Record = { + scan: { ran: !!i.scan, ...(i.notes?.scan ? { note: i.notes.scan } : {}) }, + check: { ran: !!i.check, ...(i.notes?.check ? { note: i.notes.check } : {}) }, + validate: { ran: !!i.validate, ...(i.notes?.validate ? { note: i.notes.validate } : {}) }, + }; + const stores = i.stores ?? (['apple', 'play'] as const).filter(s => raw.some(f => f.store === s)); + const readOf = (st: 'apple' | 'play') => { const v = i.storeRead?.[st]; return v === true ? { checked: true } : { checked: false, ...(v ? { why: v } : {}) }; }; + return maskReport({ app: i.app, stores, read: { apple: readOf('apple'), play: readOf('play') }, generatedAt: i.generatedAt, storebound: i.storebound, sources, summary, findings, questions }, i.secrets ?? []); +} + +/** The report with every string masked (maskSecrets); urls only when they are https. */ +export function maskReport(r: ReportData, known: string[] = []): ReportData { + const m = (s: string) => maskSecrets(s, known); + const mo = (s: T): T => (s === undefined ? s : m(s) as T); + const safeUrl = (u?: string) => (u && /^https:\/\/[^\s"'<>]+$/.test(u) ? u : undefined); + return { + ...r, + app: { name: m(r.app.name), ...(r.app.version ? { version: m(r.app.version) } : {}), ...(r.app.build ? { build: m(r.app.build) } : {}) }, + read: { apple: { ...r.read.apple, ...(r.read.apple.why ? { why: m(r.read.apple.why) } : {}) }, play: { ...r.read.play, ...(r.read.play.why ? { why: m(r.read.play.why) } : {}) } }, + sources: Object.fromEntries(Object.entries(r.sources).map(([k, v]) => [k, { ran: v.ran, ...(v.note ? { note: m(v.note) } : {}) }])) as ReportData['sources'], + findings: r.findings.map(f => { + const url = safeUrl(f.url); + const { url: _drop, ...rest } = f; + return { ...rest, title: m(f.title), guideline: mo(f.guideline), fix: mo(f.fix), evidence: f.evidence.map(m), ...(url ? { url } : {}) }; + }), + questions: r.questions.map(q => { const url = safeUrl(q.url); const { url: _u, ...rest } = q; return { ...rest, text: m(q.text), ...(url ? { url } : {}) }; }), + }; +} + +// ---- renderers ---- + +export const escapeHtml = (s: string): string => s.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); + +/** The summary columns: both stores always (a store the config lacks shows "Not set up"), plus "both" when anything is on both. */ +const shown = (r: ReportData): ReportStore[] => ['apple', 'play', ...(r.findings.some(f => f.store === 'both') ? ['both' as const] : [])]; +const appLine = (r: ReportData) => [r.app.version && `version ${r.app.version}`, r.app.build && `build ${r.app.build}`].filter(Boolean).join(' · '); +const sourceLine = (name: ReportSource, s: SourceState) => `${name}: ${s.ran ? 'ran' : 'skipped'}${s.note ? ` (${s.note})` : ''}`; + +// storebound.dev's look (site/style.css tokens): slate ink, the indigo accent, the system font stack, 14px radius. +const CSS = `:root{color-scheme:light dark;--bg:#f8fafc;--surface:#fff;--ink:#0f172a;--ink-2:#334155;--muted:#64748b;--line:#e2e8f0;--accent:#4f46e5;--accent-ink:#fff;--accent-soft:#eef2ff; +--bad-bg:#fee2e2;--bad:#991b1b;--warn-bg:#fef3c7;--warn:#92400e;--note-bg:#eef2ff;--note:#3730a3;--ok-bg:#dcfce7;--ok:#166534;--radius:14px; +--shadow:0 1px 2px rgba(15,23,42,.06),0 8px 24px -12px rgba(15,23,42,.18);--font:ui-sans-serif,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;--mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,"Liberation Mono",monospace} +@media (prefers-color-scheme:dark){:root{--bg:#0b1120;--surface:#131c2f;--ink:#f1f5f9;--ink-2:#cbd5e1;--muted:#94a3b8;--line:#1e293b;--accent:#818cf8;--accent-ink:#0b1120;--accent-soft:#1e1b4b; +--bad-bg:#450a0a;--bad:#fca5a5;--warn-bg:#451a03;--warn:#fcd34d;--note-bg:#1e1b4b;--note:#c7d2fe;--ok-bg:#14532d;--ok:#86efac;--shadow:0 1px 2px rgba(0,0,0,.4),0 12px 32px -16px rgba(0,0,0,.7)}} +*{box-sizing:border-box}html{-webkit-text-size-adjust:100%} +body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.6 var(--font);font-variant-numeric:tabular-nums} +main{max-width:1180px;margin:0 auto;padding:40px 16px 56px} +.small,.muted,dl,.tag,.pill,footer,summary{font-size:13px}.muted{color:var(--muted)} +header.top{display:flex;gap:16px;align-items:center;margin-bottom:28px} +header.top img{width:64px;height:64px;border-radius:15px;box-shadow:var(--shadow);flex:none} +h1{font-size:28px;line-height:1.2;margin:0 0 4px;letter-spacing:-.01em}h2{font-size:20px;line-height:1.3;margin:0 0 4px}h3{font-size:15px;margin:0} +.verdicts{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:16px;margin:0 0 40px} +.verdict{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:20px;box-shadow:var(--shadow)} +.verdict .big{font-size:26px;font-weight:700;line-height:1.25;margin:6px 0 8px} +.verdict.bad .big{color:var(--bad)}.verdict.ok .big{color:var(--ok)}.verdict.none .big{color:var(--muted)} +.counts{display:flex;gap:16px;flex-wrap:wrap;color:var(--ink-2);font-size:13px}.counts b{font-weight:600} +.cols{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,420px),1fr));gap:32px;align-items:start} +section.store{min-width:0;margin-bottom:40px}section.store>.head{margin-bottom:16px} +.card{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:16px 18px;margin:0 0 12px;overflow-wrap:anywhere} +.card .row{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:6px} +.pill{display:inline-block;font-weight:600;padding:2px 10px;border-radius:999px;line-height:1.5} +.pill.blocker{background:var(--bad-bg);color:var(--bad)}.pill.warn{background:var(--warn-bg);color:var(--warn)}.pill.info{background:var(--note-bg);color:var(--note)}.pill.ok{background:var(--ok-bg);color:var(--ok)} +.tag{color:var(--muted);border:1px solid var(--line);border-radius:999px;padding:1px 9px} +.title{font-weight:600;margin:0 0 6px}.fix{color:var(--ink-2);margin:6px 0 0} +.ev{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0 0}code{font:13px/1.5 var(--mono);background:var(--bg);border:1px solid var(--line);border-radius:6px;padding:1px 6px} +.btn{display:inline-block;margin-top:12px;background:var(--accent);color:var(--accent-ink);text-decoration:none;font-weight:600;font-size:13px;padding:7px 14px;border-radius:10px} +.btn:hover{filter:brightness(1.08)}.btn:focus-visible{outline:2px solid var(--accent);outline-offset:2px} +.clean{background:var(--surface);border:1px dashed var(--line);border-radius:var(--radius);padding:20px;color:var(--muted)} +details{margin:8px 0 12px}summary{cursor:pointer;color:var(--ink-2);font-weight:600;padding:6px 0}details .card{margin-top:8px} +.q{list-style:none;padding:0;margin:12px 0 0;display:grid;gap:10px} +.q li{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:12px 16px} +.q label{display:flex;gap:12px;align-items:flex-start;cursor:pointer}.q input{width:18px;height:18px;margin:3px 0 0;accent-color:var(--accent);flex:none} +.q a{color:var(--accent);font-size:13px;font-weight:600} +.questions{margin-top:8px}.qcols{margin-top:20px}.qcol h3{margin-bottom:4px}footer{margin-top:48px;color:var(--muted);border-top:1px solid var(--line);padding-top:16px} +@media (max-width:560px){main{padding-top:24px}h1{font-size:24px}header.top img{width:48px;height:48px;border-radius:11px}} +@media print{:root{color-scheme:light}body{background:#fff}.btn,.q a{display:none}.card,.verdict,.q li{box-shadow:none;break-inside:avoid} +.cols{display:block}section.store+section.store,.questions{break-before:page}details>*{display:block}main{padding:0}}`; + +const PILL: Record = { blocker: 'Blocker', warn: 'Warning', info: 'Note', ok: 'Passed' }; +const consoleName = (url: string) => (/appstoreconnect\.apple\.com|developer\.apple\.com/.test(url) ? 'App Store Connect' : /play\.google\.com/.test(url) ? 'Play Console' : 'the console'); + +function findingHtml(f: ReportFinding): string { + const e = escapeHtml; + const tags = [f.guideline && `${e(f.guideline)}`, `${e(f.rule)}`].filter(Boolean).join(''); + return `
${PILL[f.level]}${tags}
` + + `

${e(f.title)}

` + + (f.evidence.length ? `
${f.evidence.map(x => `${e(x)}`).join('')}
` : '') + + (f.fix ? `

${e(f.fix)}

` : '') + + (f.url ? `Open in ${consoleName(f.url)}` : '') + + '
'; +} + +/** The verdict of one store: blockers first, then whether the store itself was read. */ +function verdictOf(r: ReportData, s: ReportStore): { cls: string; big: string; sub: string } { + const x = r.summary[s]; + const read = s === 'both' ? undefined : r.read[s]; + const notRead = read && !read.checked ? `Store not read${read.why ? `: ${read.why}` : ''}` : ''; + if (x.blockers) return { cls: 'bad', big: `${x.blockers} blocker${x.blockers === 1 ? '' : 's'}`, sub: notRead }; + if (read && !read.checked && /section in the config/.test(read.why ?? '')) return { cls: 'none', big: 'Not set up', sub: `Not checked: ${read.why} (storebound init adds it)` }; + if (notRead) return { cls: 'none', big: `Not checked (${read?.why && /credential|key|service account/i.test(read.why) ? 'no credentials' : read?.why ?? 'not read'})`, sub: `Store not read: ${read?.why ?? 'unknown'}. Offline checks found no blockers.` }; + return { cls: 'ok', big: s === 'both' ? 'No shared blockers' : 'Ready to submit', sub: '' }; +} + +export interface HtmlOptions { /** The app icon as a data: URL (PNG / JPEG / WebP only). */ icon?: string | null } +const ICON_RE = /^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/; + +/** The self-contained HTML page: inline CSS, no script, no external request. */ +export function renderHtml(r: ReportData, o: HtmlOptions = {}): string { + const e = escapeHtml; + const cols = shown(r); + const verdict = (s: ReportStore) => { + const v = verdictOf(r, s), x = r.summary[s]; + return `

${STORE_LABEL[s]}

${e(v.big)}
` + + `
${x.blockers} blockers${x.warnings} warnings${x.ok} passed
` + + (v.sub ? `
${e(v.sub)}
` : '') + '
'; + }; + const section = (s: ReportStore) => { + const open = r.findings.filter(f => f.store === s && (f.level === 'blocker' || f.level === 'warn')); + const notes = r.findings.filter(f => f.store === s && f.level === 'info'); + const ok = r.findings.filter(f => f.store === s && f.level === 'ok'); + if (s === 'both' && !open.length && !notes.length && !ok.length) return ''; + const head = `

${STORE_LABEL[s]}

${open.length ? `${open.length} to fix, most severe first` : 'Nothing to fix'}
`; + const fold = (label: string, list: ReportFinding[]) => (list.length ? `
${list.length} ${label}${list.map(findingHtml).join('')}
` : ''); + const empty = s !== 'both' && !r.stores.includes(s) ? `Not set up: ${r.read[s].why ?? 'not in the config'}.` : 'No blockers or warnings.'; + return `
${head}${open.map(findingHtml).join('') || `
${e(empty)}
`}${fold(notes.length === 1 ? 'note' : 'notes', notes)}${fold('passed', ok)}
`; + }; + const both = cols.includes('both') ? section('both') : ''; + const stores = cols.filter(s => s !== 'both'); + const meta = [r.app.version && `Version ${r.app.version}`, r.app.build && `build ${r.app.build}`, `checked ${r.generatedAt.slice(0, 10)}`].filter(Boolean).join(' · '); + const icon = o.icon && ICON_RE.test(o.icon) ? `` : ''; + const qList = (st: ReportStore) => { + const list = r.questions.filter(x => x.store === st); + if (st === 'both' && !list.length) return ''; + const none = st !== 'both' && !r.stores.includes(st) ? 'Not set up in this config.' : 'Nothing open: every answer is in the config.'; + return `

${STORE_LABEL[st]}

${list.length + ? `` + : `
${none}
`}
`; + }; + const q = `
${(['apple', 'play', 'both'] as const).map(qList).join('')}
`; + return ` + + +${e(r.app.name)}: store readiness +
+
${icon}

${e(r.app.name)}

${e(meta)}
+
${cols.map(verdict).join('')}
+${both} +
${stores.map(section).join('')}
+

Questions only you can answer

Compliance facts no code or config can prove. Answer them once; storebound writes them into the config.
${q}
+
storebound ${e(r.storebound)} · ${e(r.generatedAt)} · ${(Object.keys(r.sources) as ReportSource[]).map(k => e(sourceLine(k, r.sources[k]))).join(' · ')} · Read-only: nothing was sent to a store.
+
+`; +} + +const mdCell = (s: string) => s.replace(/\|/g, '\\|').replace(/\r?\n/g, ' '); + +/** The same report as Markdown (desktop export, `--md`). */ +export function renderMarkdown(r: ReportData): string { + const out: string[] = [`# ${r.app.name}: store readiness`, '']; + const meta = appLine(r); + if (meta) out.push(meta, ''); + out.push('| store | verdict | blockers | warnings | passed |', '|---|---|---|---|---|', ...shown(r).map(s => `| ${STORE_LABEL[s]} | ${mdCell(verdictOf(r, s).big)} | ${r.summary[s].blockers} | ${r.summary[s].warnings} | ${r.summary[s].ok} |`), ''); + out.push((Object.keys(r.sources) as ReportSource[]).map(k => sourceLine(k, r.sources[k])).join(' · '), ''); + for (const s of STORES) { + const list = r.findings.filter(f => f.store === s && f.level !== 'ok'); + if (!list.length) continue; + out.push(`## ${STORE_LABEL[s]}`, '', '| level | rule | guideline | finding | evidence | fix | console |', '|---|---|---|---|---|---|---|'); + for (const f of list) out.push(`| ${LEVEL_LABEL[f.level]} | ${mdCell(f.rule)} | ${mdCell(f.guideline ?? '')} | ${mdCell(f.title)} | ${mdCell(f.evidence.join(', '))} | ${mdCell(f.fix ?? '')} | ${f.url ? `[open](${f.url})` : ''} |`); + out.push(''); + } + out.push('## Questions only you can answer', '', ...(r.questions.length ? r.questions.map(q => `- [ ] **${STORE_LABEL[q.store]}:** ${q.text}${q.url ? ` ([open](${q.url}))` : ''}`) : ['None open.']), ''); + out.push(`storebound ${r.storebound} · ${r.generatedAt}`); + return out.join('\n') + '\n'; +} + +/** Short summary line for logs and the MCP result. */ +export function summaryText(r: ReportData): string { + return shown(r).map(s => { + const v = verdictOf(r, s), x = r.summary[s], read = s === 'both' ? undefined : r.read[s]; + const extra = [x.warnings ? `${x.warnings} warning(s)` : '', x.blockers && read && !read.checked ? `store not read: ${read.why ?? 'unknown'}` : ''].filter(Boolean).join(', '); + return `${STORE_LABEL[s]}: ${v.big}${extra ? ` (${extra})` : ''}`; + }).join(' · '); +} diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index 8d42d58..318c5eb 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -57,6 +57,10 @@ export const TOOLS: ToolDef[] = [ description: 'Read-only readiness report for App Store Connect and/or Google Play with ordered blockers (build, encryption, metadata, screenshots, review details and demo account, age rating, prices, IAPs, subscriptions, privacy, delete-account and terms URLs, app-ads.txt, tracks, products, base plans).', props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' } }, args: i => (i.store === 'apple' ? ['--apple'] : i.store === 'play' ? ['--play'] : []) }, + { name: 'report', title: 'Shareable readiness report', command: ['report'], write: false, network: true, + description: 'One self-contained HTML page with the scan, check and validate results (read-only; validate only for the stores whose credentials are there, else the page says why): summary per store, findings by store and severity with guideline, evidence, fix and console link, the compliance questions only the owner can answer. Writes only .storebound/reports/readiness-.html (masked: no credentials, key ids, emails or demo account) and returns its path and the summary; never opens a browser.', + props: { format: { type: 'string', enum: ['html', 'md'], default: 'html' }, offline: { type: 'boolean', default: false, description: 'Skip validate (no store reads)' } }, + args: i => ['--no-open', ...(i.format === 'md' ? ['--md'] : []), ...(i.offline === true ? ['--offline'] : [])] }, { name: 'health', title: 'Crash and vitals health', command: ['health'], write: false, network: true, description: 'Read-only crash / ANR vitals from the Play Developer Reporting API (user-perceived rates vs the bad behavior thresholds 1.09 % / 0.47 %, worst device models, top issues) and App Store power and performance metrics, diagnostic signatures and TestFlight crash reports. Exit 1 when a metric is over a store threshold.', props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' }, days: { type: 'integer', minimum: 1, maximum: 90, default: 7 } }, diff --git a/cli/report.ts b/cli/report.ts new file mode 100644 index 0000000..7a4b6e0 --- /dev/null +++ b/cli/report.ts @@ -0,0 +1,182 @@ +// A shareable store readiness report: one self-contained HTML page (or Markdown / JSON) anyone can open, no terminal +// skills and no AI agent needed. +// storebound report [--out ] [--md] [--json] [--no-open] [--offline] +// Gathers `scan` (offline), `check` (offline) and `validate` (read-only, both stores; only for the stores whose +// credentials are there, otherwise the report says it was skipped and why; --offline skips it) and writes +// .storebound/reports/readiness-.html (--md: .md). Then opens it in the default browser unless --no-open, --json, +// not a terminal, CI or the desktop sidecar. --json prints { file, ...report } on stdout. The only write is the report +// file. Credentials, key ids, emails, tokens and the review demo account are masked (cli/lib/report.ts). +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join, relative, resolve } from 'node:path'; +import pkg from '../package.json' with { type: 'json' }; +import { consolePlan } from './lib/console-plan'; +import { type ConsolePage, consoleUrl } from './lib/console-links'; +import type { PlanFormId } from './lib/console-answers'; +import type { ShipConfig } from './lib/config'; +import { CREDENTIAL_KEYS, credentialStatus, credentialValue, reviewContact, reviewDemoAccount } from './lib/credentials'; +import type { Ctx } from './lib/ctx'; +import { log, printJson, warn } from './lib/log'; +import { buildReport, type CheckInput, type ReportData, type ReportFinding, type ReportQuestion, renderHtml, renderMarkdown, type ScanInput, summaryText, type ValidateInput } from './lib/report'; +import { findIcon, iconDataUrl } from './lib/project-files'; +import { runCommand } from './lib/runner'; +import * as rt from './lib/rt'; + +const TAG = 'report'; +/** Console plans whose ask-owner answers are compliance questions. */ +const QUESTION_FORMS: { form: PlanFormId; store: 'apple' | 'play'; all?: boolean }[] = [ + { form: 'apple-app-privacy', store: 'apple' }, { form: 'apple-age-rating', store: 'apple' }, + { form: 'play-content-rating', store: 'play' }, { form: 'play-target-audience', store: 'play' }, { form: 'play-app-content', store: 'play', all: true }, +]; + +/** Version and build of the project, when a project file says them (package.json, pubspec.yaml, the Android app module). */ +export function projectVersion(root: string): { version?: string; build?: string } { + const read = (p: string) => { try { return readFileSync(join(root, p), 'utf8'); } catch { return null; } }; + const pub = read('pubspec.yaml'); + const pm = pub && /^version:\s*([0-9][^\s+]*)(?:\+(\d+))?/m.exec(pub); + if (pm) return { version: pm[1], ...(pm[2] ? { build: pm[2] } : {}) }; + for (const g of ['android/app/build.gradle', 'android/app/build.gradle.kts', 'app/build.gradle', 'app/build.gradle.kts']) { + const t = read(g); + const name = t && /versionName\s*=?\s*["']([^"']+)["']/.exec(t)?.[1]; + if (name) { const code = /versionCode\s*=?\s*(\d+)/.exec(t!)?.[1]; return { version: name, ...(code ? { build: code } : {}) }; } + } + const pj = read('package.json'); + if (pj) { try { const v = (JSON.parse(pj) as { version?: unknown }).version; if (typeof v === 'string' && v && v !== '0.0.0') return { version: v }; } catch { /* not JSON */ } } + return {}; +} + +/** Every secret value this project can see (to mask literally): credentials, the review contact and demo account. */ +export function knownSecrets(root: string): string[] { + const out: string[] = []; + for (const k of CREDENTIAL_KEYS) { try { const v = credentialValue(root, k); if (v) out.push(v); } catch { /* unreadable */ } } + try { const d = reviewDemoAccount(root); if (d) out.push(d.username, d.password); } catch { /* none */ } + try { const c = reviewContact(root); if (c) out.push(c.email, c.phone, c.firstName, c.lastName); } catch { /* none */ } + return out.filter(v => typeof v === 'string' && v.length >= 4); +} + +/** Which stores `validate` can read with the credentials here, and why the others are skipped. */ +export function validateStores(root: string, config: ShipConfig): { apple: boolean; play: boolean; skipped: string[] } { + const st = new Map(credentialStatus(root).map(c => [c.key, c.status])); + const set = (k: string) => st.get(k) === 'set'; + const skipped: string[] = []; + const apple = !!config.apple && set('ASC_KEY_ID') && set('ASC_ISSUER_ID'); + const play = !!config.play && set('PLAY_SERVICE_ACCOUNT'); + if (config.apple && !apple) skipped.push('App Store: no App Store Connect API key (ASC_KEY_ID, ASC_ISSUER_ID, ASC_P8 in env, .storebound/credentials.json or a credential profile)'); + if (config.play && !play) skipped.push('Google Play: no service account (PLAY_SERVICE_ACCOUNT in env, .storebound/credentials.json or a credential profile)'); + return { apple, play, skipped }; +} + +/** The compliance answers the console plans still need from the owner. */ +function planQuestions(config: ShipConfig, root: string): ReportQuestion[] { + const out: ReportQuestion[] = []; + let demo = false; + try { demo = !!reviewDemoAccount(root); } catch { /* none */ } + for (const q of QUESTION_FORMS) { + if (!config[q.store]) continue; + try { + const pl = consolePlan(q.form, config, { demoAccount: demo }, { all: !!q.all }); + const url = pl.start.url; + // many confirmations of one form (age rating answers left at the default): one line with their names + if (pl.askOwner.length > 3) { + const names = pl.askOwner.map(x => x.split(': ask the owner')[0]!.split(':').pop()!.trim()).filter(Boolean); + out.push({ store: q.store, text: `${pl.title}: ${pl.askOwner.length} answers to give or confirm (${names.join(', ')})`, source: 'console plan', url }); + } else for (const x of pl.askOwner) out.push({ store: q.store, text: `${pl.title}: ${x}`, source: 'console plan', url }); + } catch { /* template answers: check reports them */ } + } + return out; +} + +/** The --json result of one storebound command run as a child (same binary), or the reason it gave none. */ +async function child(argv: string[], cwd: string): Promise<{ data: unknown; error?: string }> { + const r = await runCommand(argv, { cwd, machine: true }).result; + if (r.data !== undefined) return { data: r.data }; + return { data: null, error: (r.err || r.out).split('\n').filter(Boolean).pop()?.replace(/^error:\s*/, '').slice(0, 300) || `exit ${r.code}` }; +} + +/** A console page for a finding without a link of its own, by what its rule is about. */ +export function linkFor(f: ReportFinding): string | undefined { + if (f.store === 'both') return undefined; + const t = `${f.rule} ${f.title}`.toLowerCase(); + const pick = (apple: ConsolePage, play: ConsolePage) => consoleUrl(f.store === 'apple' ? apple : play); + if (/privacy|tracking|\batt\b|data safety|data-safety|label/.test(t)) return pick('asc.app-privacy', 'play.data-safety'); + if (/demo|sign-in|login|review access|app access/.test(t)) return pick('asc.app-review', 'play.app-access'); + if (/subscription/.test(t)) return pick('asc.subscriptions', 'play.subscriptions'); + if (/purchase|iap|product|restore/.test(t)) return pick('asc.iaps', 'play.products'); + if (/age rating|content rating|target audience|families|kids/.test(t)) return pick('asc.age-rating', 'play.target-audience'); + if (/encryption/.test(t)) return pick('asc.encryption', 'play.app-content'); + if (/listing|keyword|subtitle|description|screenshot|metadata/.test(t)) return pick('asc.version', 'play.store-listing'); + if (/target ?sdk|16 ?kb|bundle|manifest|permission/.test(t) && f.store === 'play') return consoleUrl('play.bundle-explorer'); + return pick('asc.version', 'play.app-content'); +} + +const localDate = (d = new Date()): string => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; + +export interface ReportRun { file: string; report: ReportData } + +/** Gathers the three sources and writes the report file. Shared by the command, the desktop (serve) and MCP. */ +export async function makeReport(ctx: Ctx): Promise { + const { config, root, path } = ctx.loaded; + const a = ctx.args; + const notes: Partial> = {}; + const cfg = ['--config', path]; + log(TAG, 'project scan (offline)'); + let scan: ScanInput | null = null; + try { scan = (await (await import('./lib/scan')).runScan(root, { config: path })).report as unknown as ScanInput; } catch (e) { notes.scan = `failed: ${(e as Error).message.slice(0, 200)}`; } + log(TAG, 'config check (offline)'); + const c = await child(['check', '--json', ...cfg], root); + const check = c.data as CheckInput | null; + if (!check) notes.check = `failed: ${c.error}`; + let validate: ValidateInput | null = null; + const storeRead: Partial> = {}; + if (a.has('offline')) { notes.validate = '--offline'; storeRead.apple = config.apple ? 'skipped with --offline' : 'no apple section in the config'; storeRead.play = config.play ? 'skipped with --offline' : 'no play section in the config'; } + else { + const v = validateStores(root, config); + if (!v.apple) storeRead.apple = config.apple ? 'no App Store Connect API key' : 'no apple section in the config'; + if (!v.play) storeRead.play = config.play ? 'no Play service account' : 'no play section in the config'; + if (!v.apple && !v.play) notes.validate = v.skipped.join('; ') || 'no store in the config'; + else { + log(TAG, `store readiness (read-only): ${[v.apple && 'App Store', v.play && 'Google Play'].filter(Boolean).join(' + ')}`); + const r = await child(['validate', '--json', '--no-scan', ...(v.apple && v.play ? [] : v.apple ? ['--apple'] : ['--play']), ...cfg], root); + validate = r.data as ValidateInput | null; + if (!validate) { notes.validate = `failed: ${r.error}`; if (v.apple) storeRead.apple = 'the store read failed'; if (v.play) storeRead.play = 'the store read failed'; } + else { + if (v.apple) storeRead.apple = true; + if (v.play) storeRead.play = true; + if (v.skipped.length) notes.validate = `skipped ${v.skipped.join('; ')}`; + } + } + } + const report = buildReport({ + app: { name: config.app.name, ...projectVersion(root) }, stores: (['apple', 'play'] as const).filter(s => !!config[s]), linkFor, storeRead, generatedAt: new Date().toISOString().replace(/\.\d+Z$/, 'Z'), storebound: pkg.version, + scan, check, validate, notes, questions: planQuestions(config, root), secrets: knownSecrets(root), + }); + const md = a.has('md'); + const file = resolve(root, a.get('out') ?? join('.storebound', 'reports', `readiness-${localDate()}.${md ? 'md' : 'html'}`)); + mkdirSync(dirname(file), { recursive: true }); + let icon: string | null = null; + try { icon = iconDataUrl(findIcon(config, root)).dataUrl; } catch { /* no icon */ } + writeFileSync(file, md ? renderMarkdown(report) : renderHtml(report, { icon })); + return { file, report }; +} + +/** Opens a file in the default browser / viewer (macOS open, Windows start, Linux xdg-open). */ +export function openFile(file: string): boolean { + const argv = process.platform === 'darwin' ? ['open', file] : process.platform === 'win32' ? ['cmd', '/c', 'start', '""', file] : ['xdg-open', file]; + try { const p = rt.spawn(argv, { stdin: 'ignore', stdout: 'ignore', stderr: 'ignore' }); void p.exited.catch(() => {}); return true; } catch { return false; } +} + +/** Open the report: not with --no-open / --json, not without a terminal, not in CI or under the desktop sidecar. */ +export function shouldOpen(args: { has(k: string): boolean }, env: Record = process.env, tty = !!process.stdout.isTTY): boolean { + return !args.has('no-open') && !args.has('json') && tty && !env.CI && env.STOREBOUND_SERVE !== '1'; +} + +export async function run(ctx: Ctx): Promise { + const { file, report } = await makeReport(ctx); + const shown = relative(process.cwd(), file) || file; + if (ctx.args.has('json')) { printJson({ file, path: relative(ctx.loaded.root, file).split('\\').join('/'), ...report }); return; } + log(TAG, summaryText(report)); + if (report.questions.length) log(TAG, `${report.questions.length} question(s) only you can answer are listed in the report`); + if (report.sources.validate.note) warn(TAG, `validate: ${report.sources.validate.note}`); + log(TAG, `wrote ${file}`); + if (shouldOpen(ctx.args)) { if (!openFile(file)) warn(TAG, `could not open ${shown}: open it in a browser`); } + if (!existsSync(file)) throw new Error(`${shown} was not written`); +} diff --git a/cli/serve.ts b/cli/serve.ts index d262a97..ee05729 100644 --- a/cli/serve.ts +++ b/cli/serve.ts @@ -54,7 +54,7 @@ export const DESKTOP_EXCLUDED = new Set(['play_release_testing', 'apple_phased_r export const FORBIDDEN_METHOD_WORDS = /submit|release|publish|rollout|resume|complete|send|start|stop|cancel|delete|remove|invite/i; /** Read tools whose command prints a structured result with --json. */ -export const JSON_TOOLS = new Set(['check', 'check_aso', 'aso_audit', 'aso_suggest', 'aso_competitors', 'scan', 'validate', 'health', 'health_issue', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status', +export const JSON_TOOLS = new Set(['check', 'report', 'check_aso', 'aso_audit', 'aso_suggest', 'aso_competitors', 'scan', 'validate', 'health', 'health_issue', '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', 'project_icon', 'project_listings', 'reviews_drafts', 'project_declarations', 'project_listing_text', 'project_renders', 'project_render', 'prices_current', 'project_editable', 'listing_live', 'art_live', 'art_thumb']); diff --git a/docs/commands.md b/docs/commands.md index 8dc72c1..4c00820 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -20,6 +20,7 @@ run in the background with a log (`storebound shots render > .storebound/render. | `check --aso` | local | keyword audit: App Store keyword field rules, Play stuffing / claims | | `scan [--store apple\|play] [--json] [--write] [--originality --against ]` | local, read-only | rejection risks in the project itself (stack, SDKs, Info.plist, manifest, listings) with guideline, evidence file:line, fix and skill; Data safety / App Privacy / ATT / privacy manifest proposal as a diff (`--write` adds the detected answers to the config); exit 1 on blockers | | `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 | +| `report [--out ] [--md] [--json] [--no-open] [--offline]` | local + API, read-only | shareable store readiness report: `scan`, `check` and `validate` (only the stores whose credentials are there; otherwise each store says "Not checked" and why) in one self-contained HTML page `.storebound/reports/readiness-.html` (inline CSS, no scripts, light / dark, print-friendly): a verdict per store, findings by store and severity with guideline, evidence, fix and console link, the questions only you can answer. Opens in the browser unless `--no-open`, `--json`, CI or no terminal; credentials, key ids, emails and the demo account are masked. `--md` writes Markdown, `--json` prints the data with the file path. Desktop: Checks > Report; MCP: `report` | | `originality --against [--json]` | local, read-only | Guideline 4.3 check vs your other apps: name, listing text, icon and screenshot perceptual hashes, project structure; scores, near-duplicate flags, suggestions; exit 1 when flagged | | `whats-new [--since ]` | local | draft player-facing release notes from git log into both listing files | | `whats-new --languages en,de,tr` / `check` / `apply` | local | one file per language (`store/whats-new/`) for your agent (or a `--translate` hook of yours) to translate, per-store limits (Play 500, App Store 4000), then into both listing files | diff --git a/docs/mcp.md b/docs/mcp.md index a54246f..0e8b66c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5,7 +5,7 @@ per-request `_meta`, `resultType`, cacheable `tools/list`) and, on the same proc `initialize` (2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05). It runs each tool as a CLI call in the project directory (the server's working directory, or `STOREBOUND_PROJECT`) and returns the output. -- One tool per command. Read-only: `scan`, `check`, `check_aso`, `aso_competitors` (no snapshot saved), `aso_suggest` (never writes), `aso_audit`, `validate`, `catalog_diff`, `health`, `reviews_list`, `prices_diff`, +- One tool per command. Read-only: `scan`, `check`, `check_aso`, `aso_competitors` (no snapshot saved), `aso_suggest` (never writes), `aso_audit`, `validate`, `report` (writes only the report page in .storebound/reports/ and returns its path and both stores' verdicts), `catalog_diff`, `health`, `reviews_list`, `prices_diff`, `analytics_compare`, `apple_status`, `apple_next_build`, `apple_testflight_status`, `apple_ppo_status`, `play_status`, `play_next_version_code`, `privacy_manifest`, `shots_check`, `workspace_list`, `workspace_status`, `release_status`, `release_plan`, `flow_list`, `flow_run` (dry mode only), `listing_check`, `api_get` (any App Store diff --git a/skills/store-preflight/SKILL.md b/skills/store-preflight/SKILL.md index 95d6ba3..8d043d4 100644 --- a/skills/store-preflight/SKILL.md +++ b/skills/store-preflight/SKILL.md @@ -40,6 +40,14 @@ Many apps (a `storebound.workspace.json` above the app folders, `storebound ws i and `storebound ws validate [--apps a,b]` run the same checks over every app, a few at a time, each with its studio's credential profile; `storebound ws run --apps a,b` runs any other read command (writes only as dry runs). +## Share the report: `storebound report` + +For the owner, a teammate or a client who should not need a terminal: `storebound report` runs `scan`, `check` and +`validate` (read-only; a store without credentials shows "Not checked" with the reason) and writes one self-contained +page, `.storebound/reports/readiness-.html`, then opens it in the browser. A verdict per store, every finding +with its fix and console link, and the questions only the owner can answer. Secrets are masked. `--md` for Markdown, +`--json` for the data, `--no-open` in scripts. MCP: `report`; desktop: Checks > Report. + ## Reading `scan` | finding | fix | skill | |---|---|---| diff --git a/tests/report.test.ts b/tests/report.test.ts new file mode 100644 index 0000000..70f8579 --- /dev/null +++ b/tests/report.test.ts @@ -0,0 +1,150 @@ +// storebound report: the shared renderer (grouping, order, links, escaping, masking) and the command (file written, +// --no-open, --md, --json, validate skipped without credentials, no fixture secret in any output). +import { describe, expect, test } from 'bun:test'; +import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { buildReport, maskSecrets, renderHtml, renderMarkdown, summaryText } from '../cli/lib/report'; +import { shouldOpen } from '../cli/report'; + +const ROOT = join(import.meta.dir, '..'); +const PEM = '-----BEGIN PRIVATE KEY-----\nMIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgFIXTURE000000000000\n-----END PRIVATE KEY-----'; +const SECRETS = { keyId: 'K2X9Q7W4Z1', issuer: '6f1c2a3b-4d5e-4f60-8a9b-0c1d2e3f4a5b', demoUser: 'reviewer.fixture@corp.invalid', demoPass: 'Fixture-Pass-9931', contact: 'owner.fixture@corp.invalid' }; + +const fixture = () => buildReport({ + app: { name: 'Fixture ', version: '1.2.0', build: '42' }, stores: ['apple', 'play'], storeRead: { apple: true, play: 'no Play service account' }, + generatedAt: '2026-10-18T10:00:00Z', storebound: '0.0.0-test', secrets: [SECRETS.demoPass], + scan: { + findings: [ + { rule: 'att', guideline: '5.1.2', store: 'apple', severity: 'medium', title: 'Tracking without ATT', evidence: [{ file: 'ios/App/Info.plist', line: 12 }], fix: 'Add the ATT prompt', skill: 'privacy-manifest' }, + { rule: 'demo-account', guideline: '2.1', store: 'apple', severity: 'blocker', title: 'No demo account ', evidence: [], fix: `Use ${SECRETS.demoUser} / ${SECRETS.demoPass}`, url: 'https://appstoreconnect.apple.com/apps/123/distribution/reviewsubmissions' }, + { rule: 'privacy-labels', guideline: 'Data safety', store: 'play', severity: 'high', title: 'Labels miss DEVICE_ID', evidence: [{ file: 'android/app/build.gradle', line: 30 }], fix: 'Declare it', url: 'javascript:alert(1)' }, + { rule: 'privacy-labels', guideline: 'Data safety', store: 'apple', severity: 'high', title: 'Labels miss DEVICE_ID', evidence: [{ file: 'android/app/build.gradle', line: 30 }], fix: 'Declare it' }, + { rule: 'accepted-one', guideline: 'x', store: 'play', severity: 'blocker', title: 'Accepted by the owner', evidence: [], fix: 'none', accepted: 'fine' }, + { rule: 'obfuscator', guideline: '2.3.1', store: 'play', severity: 'low', title: 'Obfuscator found', evidence: [], fix: 'Mention it' }, + ], + declarations: { items: [{ area: 'dataSafety', what: 'encryptedInTransit', value: '?', status: 'ask' }, { area: 'dataSafety', what: 'PSL_NAME', value: 'yes', status: 'detected' }] }, + }, + check: { ok: false, problems: [`key ${SECRETS.keyId} issuer ${SECRETS.issuer} in ${SECRETS.contact}`], warnings: ['play listing has no section for de-DE'], hints: [], items: [{ what: 'appstore listing', detail: '1 locales' }] }, + validate: { blockers: 1, findings: [{ store: 'apple', level: 'blocker', code: 'build', msg: 'No build attached', fix: 'storebound apple upload' }, { store: 'apple', level: 'ok', code: 'name', msg: 'Name set' }] }, +}); + +describe('report renderer', () => { + test('groups by store, merges both stores, orders by severity, drops accepted findings', () => { + const r = fixture(); + const both = r.findings.filter(f => f.store === 'both'); + expect(both.map(f => f.title)).toContain('Labels miss DEVICE_ID'); + expect(r.findings.some(f => f.title === 'Accepted by the owner')).toBe(false); + const apple = r.findings.filter(f => f.store === 'apple').map(f => f.level); + expect(apple).toEqual([...apple].sort((a, b) => ['blocker', 'warn', 'info', 'ok'].indexOf(a) - ['blocker', 'warn', 'info', 'ok'].indexOf(b))); + expect(r.findings[0]!.level).toBe('blocker'); + expect(r.summary.apple.blockers).toBe(2); + expect(r.summary.play.warnings).toBe(1); + expect(r.questions.map(q => q.text)).toContain('encryptedInTransit: ?'); + expect(summaryText(r)).toContain('App Store: 2 blockers'); + expect(summaryText(r)).toContain('Google Play: Not checked (no credentials)'); + }); + + test('html: both store columns, console links, evidence, no script, escaped text, unsafe urls dropped', () => { + const html = renderHtml(fixture()); + expect(html).toContain('

App Store

'); + expect(html).toContain('

Google Play

'); + expect(html).toContain('href="https://appstoreconnect.apple.com/apps/123/distribution/reviewsubmissions"'); + expect(html).toContain('Open in App Store Connect'); + expect(html).toContain('ios/App/Info.plist:12'); + expect(html).toContain('5.1.2'); + expect(html).toContain('Questions only you can answer'); + expect(html).toContain('prefers-color-scheme:dark'); + expect(html).toContain('@media print'); + expect(html).not.toContain('.html`, inline CSS, no scripts, light / dark, print-friendly) and opens it in the browser: a verdict per store ("Ready to submit", "N blockers", "Not checked" with the reason when a store key diff --git a/apps/desktop/package.json b/apps/desktop/package.json index e80441c..4aed85e 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.11", + "version": "0.8.12", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 278a311..e5b3c59 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4010,7 +4010,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.11" +version = "0.8.12" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 1087058..46955c1 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.11" +version = "0.8.12" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 7728afe..7e01bff 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.11", + "version": "0.8.12", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index 7ce7b1f..af290f3 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.11", + "version": "0.8.12", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index 4aafe9e..76f0df0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.11", + "version": "0.8.12", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From 9bfc107415b05cc287aabf7b4e3b54c912fe34e4 Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 18 Oct 2026 01:45:37 +0800 Subject: [PATCH 015/344] release-candidate: the background test jobs (ci, acceptance) never gate a candidate; only the installer builds and the record count (0.8.12 stopped on a red ci job) --- tests/release-pipeline.test.ts | 8 +++++--- tools/release-candidate.ts | 4 +++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/tests/release-pipeline.test.ts b/tests/release-pipeline.test.ts index 9022051..89991db 100644 --- a/tests/release-pipeline.test.ts +++ b/tests/release-pipeline.test.ts @@ -36,13 +36,15 @@ describe('candidate state from the ci.yml jobs', () => { const t = (name: string, status: string, run = 5, sha = SHA, wf = 'ci.yml'): Task => ({ id: 1, name, run_number: run, workflow_id: wf, head_sha: sha, status }); const url = (n: number) => `run/${n}`; test('none, pending, red; the newest run counts', () => { - expect(taskState([t('ci', 'success', 5, 'b'.repeat(40))], SHA, url)).toEqual({ state: 'none' }); + expect(taskState([t('linux', 'success', 5, 'b'.repeat(40))], SHA, url)).toEqual({ state: 'none' }); expect(taskState([t('ci', 'success'), t('windows', 'running')], SHA, url)).toEqual({ state: 'pending', run: 'run/5', running: ['windows (running)'] }); - expect(taskState([t('ci', 'success'), t('acceptance (bun)', 'failure')], SHA, url)).toEqual({ state: 'red', run: 'run/5', failed: ['acceptance (bun)'], cancelledOnly: false }); + expect(taskState([t('linux', 'success'), t('windows', 'failure')], SHA, url)).toEqual({ state: 'red', run: 'run/5', failed: ['windows'], cancelledOnly: false }); // a cancelled run (old-tag runs freed, superseded) is not a failure: a version-only child runs everything expect(taskState([t('ci', 'success'), t('linux', 'cancelled')], SHA, url)).toEqual({ state: 'red', run: 'run/5', failed: ['linux'], cancelledOnly: true }); - expect(taskState([t('ci', 'failure', 4), t('ci', 'running', 6)], SHA, url).state).toBe('pending'); + expect(taskState([t('linux', 'failure', 4), t('linux', 'running', 6)], SHA, url).state).toBe('pending'); expect(taskState([t('promote', 'failure', 9, SHA, 'release.yml')], SHA, url)).toEqual({ state: 'none' }); + // background tests never gate: a red ci / acceptance job leaves the candidate pending on its installers + expect(taskState([t('ci', 'failure'), t('acceptance (bun)', 'failure'), t('linux', 'success'), t('windows', 'running')], SHA, url)).toEqual({ state: 'pending', run: 'run/5', running: ['windows (running)'] }); }); test('tags and prereleases', () => { expect(tagVersion('v0.8.5')).toBe('0.8.5'); diff --git a/tools/release-candidate.ts b/tools/release-candidate.ts index 414c181..bb0ff92 100644 --- a/tools/release-candidate.ts +++ b/tools/release-candidate.ts @@ -94,7 +94,9 @@ export interface Task { id: number; name: string; run_number: number; workflow_i /** The state of a commit from its ci.yml jobs (the newest run of that commit) and whether its record exists. Pure. */ export function taskState(tasks: Task[], sha: string, runUrl: (n: number) => string): Exclude { - const mine = tasks.filter(t => t.head_sha === sha && t.workflow_id === 'ci.yml'); + // the background test jobs (ci, acceptance) never gate a release (the owner's decision 2026-10-16): only the + // installer builds and the record count; tools/ci-status.ts reports the tests + const mine = tasks.filter(t => t.head_sha === sha && t.workflow_id === 'ci.yml' && !/^(ci|acceptance\b)/.test(t.name)); if (!mine.length) return { state: 'none' }; const latest = Math.max(...mine.map(t => t.run_number)); const jobs = mine.filter(t => t.run_number === latest); From 45b705ba85c1c6243fc3790e0614654b98180ca8 Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 18 Oct 2026 01:46:36 +0800 Subject: [PATCH 016/344] tests: report fixtures use example.com subdomains and the zero uuid (the repo scrub flagged corp.invalid emails and a real-looking issuer id) --- tests/report.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/report.test.ts b/tests/report.test.ts index 70f8579..a98d9bc 100644 --- a/tests/report.test.ts +++ b/tests/report.test.ts @@ -9,7 +9,7 @@ import { shouldOpen } from '../cli/report'; const ROOT = join(import.meta.dir, '..'); const PEM = '-----BEGIN PRIVATE KEY-----\nMIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgFIXTURE000000000000\n-----END PRIVATE KEY-----'; -const SECRETS = { keyId: 'K2X9Q7W4Z1', issuer: '6f1c2a3b-4d5e-4f60-8a9b-0c1d2e3f4a5b', demoUser: 'reviewer.fixture@corp.invalid', demoPass: 'Fixture-Pass-9931', contact: 'owner.fixture@corp.invalid' }; +const SECRETS = { keyId: 'K2X9Q7W4Z1', issuer: '00000000-0000-0000-0000-000000000000', demoUser: 'reviewer.fixture@mail.example.com', demoPass: 'Fixture-Pass-9931', contact: 'owner.fixture@mail.example.com' }; const fixture = () => buildReport({ app: { name: 'Fixture ', version: '1.2.0', build: '42' }, stores: ['apple', 'play'], storeRead: { apple: true, play: 'no Play service account' }, @@ -70,12 +70,12 @@ describe('report renderer', () => { }); test('maskSecrets: keys, tokens, emails; example.com and plain words kept', () => { - const m = maskSecrets(`${PEM} eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJmaXh0dXJlIn0.c2lnbmF0dXJlZml4dHVyZQ ${SECRETS.keyId} ${SECRETS.issuer} a@corp.invalid support@example.com ageRating NSPrivacyAccessedAPICategoryUserDefaults ITMS-91053`); + const m = maskSecrets(`${PEM} eyJhbGciOiJFUzI1NiJ9.eyJpc3MiOiJmaXh0dXJlIn0.c2lnbmF0dXJlZml4dHVyZQ ${SECRETS.keyId} ${SECRETS.issuer} a@mail.example.com support@example.com ageRating NSPrivacyAccessedAPICategoryUserDefaults ITMS-91053`); expect(m).not.toContain('BEGIN PRIVATE KEY'); expect(m).not.toContain('eyJhbGci'); expect(m).not.toContain(SECRETS.keyId); expect(m).not.toContain(SECRETS.issuer); - expect(m).not.toContain('a@corp.invalid'); + expect(m).not.toContain('a@mail.example.com'); expect(m).toContain('support@example.com'); expect(m).toContain('NSPrivacyAccessedAPICategoryUserDefaults'); expect(m).toContain('ITMS-91053'); From 88078f1d7eacec356b0c408ffacaf059799477e5 Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 18 Oct 2026 02:11:54 +0800 Subject: [PATCH 017/344] desktop-release: a DMG notarization upload cut off before Apple had it (abortedUpload) is submitted once more --- tools/desktop-release.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tools/desktop-release.ts b/tools/desktop-release.ts index 54cf8e7..0195f7a 100644 --- a/tools/desktop-release.ts +++ b/tools/desktop-release.ts @@ -517,7 +517,12 @@ async function mac(argv: string[]): Promise { const updaterSig = signFile(updater); if (dmgNotary) { - const n = await dmgNotary; + let n = await dmgNotary; + // an upload cut off on the way to Apple (abortedUpload, a reset connection) submitted nothing: send it once more + if (n.code !== 0 && /abortedUpload|connection (was )?reset|timed out|network connection was lost/i.test(n.err + n.out)) { + say('notarytool: the DMG upload was cut off before Apple had it; submitting once more'); + n = await runAsync(['xcrun', 'notarytool', 'submit', dmg, '--key', notary!.APPLE_API_KEY_PATH!, '--key-id', notary!.APPLE_API_KEY!, '--issuer', notary!.APPLE_API_ISSUER!, '--wait', '--output-format', 'json'], { timeoutMs: 3_600_000 }); + } const status = (() => { try { return (JSON.parse(n.out) as { status?: string }).status; } catch { return undefined; } })(); if (status !== 'Accepted') fail(`notarization of the DMG: ${status ?? (n.err.trim() || n.out.trim() || `notarytool exited ${n.code} without an answer (killed or timed out): run again; xcrun notarytool history shows the submission`)}`); say(`DMG notarized in ${(n.ms / 1000).toFixed(0)} s`); From ddb813576e88d895557a9bd127e4cc648b1ed737 Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 18 Oct 2026 02:24:34 +0800 Subject: [PATCH 018/344] desktop-release: notarization retries go by notarytool's status, not its exit code (0.8.12's aborted upload exited without an error), up to 3 tries, the later ones with --no-s3-acceleration --- tools/desktop-release.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tools/desktop-release.ts b/tools/desktop-release.ts index 0195f7a..73ac7ab 100644 --- a/tools/desktop-release.ts +++ b/tools/desktop-release.ts @@ -518,10 +518,13 @@ async function mac(argv: string[]): Promise { if (dmgNotary) { let n = await dmgNotary; - // an upload cut off on the way to Apple (abortedUpload, a reset connection) submitted nothing: send it once more - if (n.code !== 0 && /abortedUpload|connection (was )?reset|timed out|network connection was lost/i.test(n.err + n.out)) { - say('notarytool: the DMG upload was cut off before Apple had it; submitting once more'); - n = await runAsync(['xcrun', 'notarytool', 'submit', dmg, '--key', notary!.APPLE_API_KEY_PATH!, '--key-id', notary!.APPLE_API_KEY!, '--issuer', notary!.APPLE_API_ISSUER!, '--wait', '--output-format', 'json'], { timeoutMs: 3_600_000 }); + // an upload cut off on the way to Apple (abortedUpload, a reset connection) submitted nothing: send it again, up + // to 3 tries, the later ones without S3 transfer acceleration (the path that broke twice for 0.8.12); the exit + // code is not trusted, only notarytool's own status + const accepted = (o: string) => { try { return (JSON.parse(o) as { status?: string }).status === 'Accepted'; } catch { return false; } }; + for (let tries = 1; tries < 3 && !accepted(n.out) && /abortedUpload|connection (was )?reset|timed out|network connection was lost|NSURLErrorDomain/i.test(n.err + n.out); tries++) { + say(`notarytool: the DMG upload was cut off before Apple had it (try ${tries}); submitting again without S3 acceleration`); + n = await runAsync(['xcrun', 'notarytool', 'submit', dmg, '--key', notary!.APPLE_API_KEY_PATH!, '--key-id', notary!.APPLE_API_KEY!, '--issuer', notary!.APPLE_API_ISSUER!, '--no-s3-acceleration', '--wait', '--output-format', 'json'], { timeoutMs: 3_600_000 }); } const status = (() => { try { return (JSON.parse(n.out) as { status?: string }).status; } catch { return undefined; } })(); if (status !== 'Accepted') fail(`notarization of the DMG: ${status ?? (n.err.trim() || n.out.trim() || `notarytool exited ${n.code} without an answer (killed or timed out): run again; xcrun notarytool history shows the submission`)}`); From d2ae0fa765e55f0a63b79b70653f787d7ec6d4a3 Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 18 Oct 2026 02:32:44 +0800 Subject: [PATCH 019/344] release: one release at a time (a lock with the pid in ~/.storebound-releases/release.lock): two runs once built into the same target folder and both failed --- tools/release.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tools/release.ts b/tools/release.ts index f32af01..c96807a 100644 --- a/tools/release.ts +++ b/tools/release.ts @@ -247,6 +247,16 @@ async function main(): Promise { const out = join(RELEASES, 'desktop', version); const logDir = join(RELEASES, 'logs', version); const host = publishHost(); + // one release at a time on this Mac: two runs once built into the same target folder and the signing failed + if (yes) { + const lock = join(RELEASES, 'release.lock'); + const held = existsSync(lock) ? Number(readFileSync(lock, 'utf8').trim()) : 0; + const alive = held > 0 && (() => { try { process.kill(held, 0); return true; } catch { return false; } })(); + if (alive && held !== process.pid) fail(`another release runs (pid ${held}, ${lock.replace(HOME, '~')}): wait for it, or end it first`); + mkdirSync(RELEASES, { recursive: true }); + writeFileSync(lock, `${process.pid}\n`); + process.on('exit', () => { try { if (readFileSync(lock, 'utf8').trim() === String(process.pid)) rmSync(lock, { force: true }); } catch { /* gone */ } }); + } // ---------------------------------------------------------------- 1. preflight const remote = remoteSessionReason(process.env, sh(['launchctl', 'managername'], { allowFail: true }).trim()); From 0b32df57f0a5e2c939fb52e62dc1b3a9274e88fc Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 18 Oct 2026 02:43:59 +0800 Subject: [PATCH 020/344] desktop-release: tauri only signs; the app is notarized with notarytool directly (up to 3 tries, later ones without S3 acceleration) and stapled, because the upload inside tauri bundle was cut off twice for 0.8.12 with no retry --- tools/desktop-release.ts | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/tools/desktop-release.ts b/tools/desktop-release.ts index 73ac7ab..e7cc300 100644 --- a/tools/desktop-release.ts +++ b/tools/desktop-release.ts @@ -38,7 +38,7 @@ import { spawnSync, type SpawnSyncOptions } from 'node:child_process'; import { createHash } from 'node:crypto'; import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'; import { homedir, release as osRelease, tmpdir } from 'node:os'; -import { basename, join, resolve } from 'node:path'; +import { basename, dirname, join, resolve } from 'node:path'; import { type Download, type DownloadKey, type Manifest, manifestProblems } from '../cli/lib/desktop-dist'; import { verify as verifySig } from '../cli/lib/minisign'; import { buildOne, OUT_DIR as SIDECAR_DIR } from './build-sidecars'; @@ -170,6 +170,22 @@ function run(cmd: string[], opts: SpawnSyncOptions & { quiet?: boolean; allowFai /** A command in the background (notarytool waiting for Apple, the boot check) while this process checks other * artifacts. Output is collected; the caller decides what a failure means. */ +/** notarytool submit --wait with up to 3 tries when the upload is cut off before Apple has it (abortedUpload, a reset + * connection); the later tries without S3 transfer acceleration. Returns notarytool's status or the last error. */ +async function notarizeWithRetry(file: string, n: Record, what: string): Promise { + let last = ''; + for (let tries = 1; tries <= 3; tries++) { + const args = ['xcrun', 'notarytool', 'submit', file, '--key', n.APPLE_API_KEY_PATH!, '--key-id', n.APPLE_API_KEY!, '--issuer', n.APPLE_API_ISSUER!, ...(tries > 1 ? ['--no-s3-acceleration'] : []), '--wait', '--output-format', 'json']; + const r = await runAsync(args, { timeoutMs: 3_600_000 }); + const status = (() => { try { return (JSON.parse(r.out) as { status?: string }).status; } catch { return undefined; } })(); + if (status) return status; + last = (r.err.trim() || r.out.trim() || `notarytool exited ${r.code}`).slice(0, 300); + if (!/abortedUpload|connection (was )?reset|timed out|network connection was lost|NSURLErrorDomain/i.test(last)) return last; + say(`notarytool (${what}): the upload was cut off before Apple had it (try ${tries}); ${tries < 3 ? 'again without S3 acceleration' : 'giving up'}`); + } + return last; +} + function runAsync(cmd: string[], opts: { cwd?: string; env?: Record; timeoutMs?: number; inherit?: boolean } = {}): Promise<{ code: number; out: string; err: string; ms: number }> { const start = Date.now(); const p = Bun.spawn(cmd, { cwd: opts.cwd, env: (opts.env ?? process.env) as Record, stdin: 'ignore', stdout: opts.inherit ? 'inherit' : 'pipe', stderr: opts.inherit ? 'inherit' : 'pipe' }); @@ -463,11 +479,27 @@ async function mac(argv: string[]): Promise { // Object.prototype with old saved states (tools/desktop-boot-check.ts); a blank window never ships again say(`tauri bundle --target universal-apple-darwin --bundles app (${signed ? `sign${notarized ? ', notarize, staple' : ''}` : 'ad-hoc sign'}), boot check of the built window at the same time`); const bootP = runAsync(['bun', join(ROOT, 'tools/desktop-boot-check.ts')], { cwd: ROOT, timeoutMs: 600_000 }); - const tbs = await runAsync(['bunx', 'tauri', 'bundle', '--target', 'universal-apple-darwin', '--bundles', 'app', '--ci', '--config', overrideFile], { cwd: APP_DIR, env, inherit: true, timeoutMs: 3_600_000 }); + // tauri signs only: notarization runs below with notarytool directly (retries, no S3 acceleration), because the + // upload inside tauri bundle was cut off twice (abortedUpload) for 0.8.12 and tauri gives no retry + const signEnv: Record = { ...env }; + delete signEnv.APPLE_API_KEY; delete signEnv.APPLE_API_ISSUER; delete signEnv.APPLE_API_KEY_PATH; + const tbs = await runAsync(['bunx', 'tauri', 'bundle', '--target', 'universal-apple-darwin', '--bundles', 'app', '--ci', '--config', overrideFile], { cwd: APP_DIR, env: signEnv, inherit: true, timeoutMs: 3_600_000 }); say(`tauri bundle done in ${(tbs.ms / 1000).toFixed(0)} s`); const boot = await bootP; process.stdout.write(boot.out); if (tbs.code !== 0) fail(`tauri bundle (signing) failed (exit ${tbs.code})`); + if (notarized) { + const appPath = join(targetDir, 'universal-apple-darwin/release/bundle/macos', APP_NAME); + const zip = join(mkdtempSync(join(tmpdir(), 'sb-notary-')), 'storebound.zip'); + const z = spawnSync('ditto', ['-c', '-k', '--keepParent', appPath, zip]); + if (z.status !== 0) fail('ditto: could not zip the app for notarization'); + const n = await notarizeWithRetry(zip, notary!, 'app'); + rmSync(dirname(zip), { recursive: true, force: true }); + if (n !== 'Accepted') fail(`notarization of the app: ${n}`); + const st = spawnSync('xcrun', ['stapler', 'staple', appPath], { encoding: 'utf8' }); + if (st.status !== 0) fail(`stapler staple (app): ${(st.stderr || st.stdout).trim().slice(-300)}`); + say('app notarized and stapled'); + } if (boot.code !== 0) fail(`the built window does not boot cleanly (tools/desktop-boot-check.ts): ${boot.err.trim().split('\n').slice(-3).join(' / ')}`); say(`boot check passed in ${(boot.ms / 1000).toFixed(0)} s`); const bootCheck = boot.out.trim().split('\n').at(-1) ?? 'ok'; From 3381673ae6387580eddcfd539da00eecb7c05fd3 Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 18 Oct 2026 13:07:15 +0700 Subject: [PATCH 021/344] iPhone Duo screenshots (render, check, upload skip with console link while the API has no display type) and the medium display class as the required iPhone set, labels as in the console --- CHANGELOG.md | 10 +++++++ cli/apple/screenshots.ts | 22 +++++++++++--- cli/art.ts | 2 +- cli/check.ts | 3 ++ cli/lib/config.ts | 4 +++ cli/lib/embedded.ts | 2 +- cli/lib/validate-rules.ts | 16 +++++++++- cli/mcp-tools.ts | 2 +- cli/shots/lib.ts | 6 +++- cli/shots/spec.ts | 25 ++++++++++++++-- cli/validate.ts | 1 + docs/store-art.md | 4 +++ skills/store-pitfalls/SKILL.md | 12 ++++++++ skills/store-screenshots/SKILL.md | 14 +++++++++ templates/storebound.config.ts | 3 +- tests/ppo.test.ts | 49 +++++++++++++++++++++++++++++-- tests/specs.test.ts | 4 +-- 17 files changed, 163 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f2cb69..548a917 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## Unreleased +- **iPhone Duo screenshots.** `apple.iphoneDuo: true` adds the foldable's outer (1398 x 2034) and inner (2007 x 2853) + sets, portrait or landscape, to `shots render`, `shots check` (exact sizes, no alpha) and the gallery. App Store + Connect API 4.5.1 has no Duo `ScreenshotDisplayType`, so `apple screenshots` skips them with a message and the deep + link to the version page's App Previews and Screenshots tab (one constant, `IPHONE_DUO_DISPLAY`, takes the enum + names once Apple adds them). `check` / `validate` note a missing Duo set: optional now, required from April 2027 for + iOS 27.1 SDK builds (a warning after that date, never a blocker), and point Play to the tablet sets (no foldable slot). +- **Required iPhone class follows the console.** `validate` now requires "iPhone with Dynamic Island (medium display)" + (`APP_IPHONE_61`) per locale, met by a 6.9" or 6.5" set that App Store Connect scales down (an ok row, not a + warning). Labels match the console: "iPhone with Dynamic Island (medium display)", "iPhone Duo", "iPad 13" display". + ## 0.8.12 · 2026-10-17 - **Shareable readiness report.** `storebound report` puts `scan`, `check` and `validate` into one self-contained HTML diff --git a/cli/apple/screenshots.ts b/cli/apple/screenshots.ts index 9565c4c..2e7df65 100644 --- a/cli/apple/screenshots.ts +++ b/cli/apple/screenshots.ts @@ -16,6 +16,8 @@ import { numberedImages } from '../play/images'; import { variantRoot } from '../shots/lib'; import { findOrCreate } from '../lib/upsert'; import { pulledChecksum } from '../lib/art-pull'; +import { consoleLink } from '../lib/console-links'; +import { IPHONE_DUO_DISPLAY, IPHONE_DUO_NOT_IN_API } from '../shots/spec'; import { type Asc, ascClient, keptPrefix, md5, setUpToDate, type J } from './asc'; /** Render size key -> ASC screenshotDisplayType (iPhone sets). */ @@ -28,12 +30,22 @@ export const MEDIUM_DISPLAY: Record = { 'iphone-medium': 'APP_IP /** Display sets this project uploads: the iPhone sets, plus the 6.3" set with apple.iphoneMedium and the 13" iPad set * with apple.ipad. */ -export const displaySets = (apple: { ipad?: boolean; iphoneMedium?: boolean } | undefined): Record => - ({ ...DISPLAY, ...(apple?.iphoneMedium ? MEDIUM_DISPLAY : {}), ...(apple?.ipad ? IPAD_DISPLAY : {}) }); +export const displaySets = (apple: { ipad?: boolean; iphoneMedium?: boolean; iphoneDuo?: boolean } | undefined): Record => + ({ ...DISPLAY, ...(apple?.iphoneMedium ? MEDIUM_DISPLAY : {}), ...(apple?.ipad ? IPAD_DISPLAY : {}), + ...(apple?.iphoneDuo ? Object.fromEntries(Object.entries(IPHONE_DUO_DISPLAY).filter((e): e is [string, string] => !!e[1])) : {}) }); -/** Display types `validate` requires on every locale: apple.screenshotTypes, else 6.9" iPhone (+ 13" iPad with ipad). */ +/** iPhone Duo size keys `apple screenshots` skips (apple.iphoneDuo on, no API display type yet), with the message. */ +export function skippedDuoSets(apple: { iphoneDuo?: boolean; appId?: string } | undefined): { dirs: string[]; msg: string } | null { + const dirs = apple?.iphoneDuo ? Object.entries(IPHONE_DUO_DISPLAY).filter(([, t]) => !t).map(([k]) => k) : []; + // the console takes them (its own "iPhone Duo" tab): send the owner straight to the version page + return dirs.length ? { dirs, msg: `${dirs.join(', ')}: ${IPHONE_DUO_NOT_IN_API}. Add them in ${consoleLink('asc.version', '> App Previews and Screenshots > iPhone Duo', { appleAppId: apple?.appId })}` } : null; +} + +/** Display types `validate` requires on every locale: apple.screenshotTypes, else the classes App Store Connect's + * "App Previews and Screenshots" tab lists (October 2026): iPhone with Dynamic Island (medium display), filled by + * scaling a 6.9" or 6.5" set down (ACCEPTED_INSTEAD), plus iPad 13" display with ipad. iPhone Duo is optional. */ export const requiredDisplayTypes = (apple: { ipad?: boolean; screenshotTypes?: string[] } | undefined): string[] => - apple?.screenshotTypes ?? ['APP_IPHONE_67', ...(apple?.ipad ? ['APP_IPAD_PRO_3GEN_129'] : [])]; + apple?.screenshotTypes ?? ['APP_IPHONE_61', ...(apple?.ipad ? ['APP_IPAD_PRO_3GEN_129'] : [])]; /** Makes one screenshot set (of a version localization, a custom product page localization or a Product Page * Optimization treatment localization) hold exactly `files`, in order: left alone when the MD5s match, else the @@ -73,6 +85,8 @@ export async function run(ctx: Ctx): Promise { const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId); const version = await c.editableVersion(); if (!version) throw new Error('no editable App Store version (run apple listing --version x.y.z first)'); + const duoSkip = skippedDuoSets(config.apple); + if (duoSkip) warn('apple', duoSkip.msg); const langOf = byAppleLocale(config.languages); const locs = await c.all(`/v1/appStoreVersions/${version.id}/appStoreVersionLocalizations?limit=50`); diff --git a/cli/art.ts b/cli/art.ts index f1d7eac..87dc882 100644 --- a/cli/art.ts +++ b/cli/art.ts @@ -408,7 +408,7 @@ type LiveSet = LiveArtSet; type LiveResult = LiveArtResult; const LABELS: Record = { - APP_IPHONE_67: 'App Store iPhone 6.9"', APP_IPHONE_65: 'App Store iPhone 6.5"', APP_IPHONE_61: 'App Store iPhone 6.3"', APP_IPHONE_55: 'App Store iPhone 5.5"', APP_IPAD_PRO_3GEN_129: 'App Store iPad 13"', APP_IPAD_PRO_129: 'App Store iPad 12.9" (2nd gen)', + APP_IPHONE_67: 'App Store iPhone 6.9"', APP_IPHONE_65: 'App Store iPhone 6.5"', APP_IPHONE_61: 'iPhone with Dynamic Island (medium display)', APP_IPHONE_55: 'App Store iPhone 5.5"', APP_IPAD_PRO_3GEN_129: 'iPad 13" display', APP_IPAD_PRO_129: 'App Store iPad 12.9" (2nd gen)', IPHONE_67: 'App Store iPhone app preview', IPAD_PRO_3GEN_129: 'App Store iPad app preview', featureGraphic: 'Play feature graphic', phoneScreenshots: 'Play phone', sevenInchScreenshots: 'Play 7" tablet', tenInchScreenshots: 'Play 10" tablet', tvScreenshots: 'Play TV', wearScreenshots: 'Play Wear OS', }; diff --git a/cli/check.ts b/cli/check.ts index 3f1e5d4..3aa9f70 100644 --- a/cli/check.ts +++ b/cli/check.ts @@ -30,6 +30,7 @@ import { allSubscriptions } from './lib/subscriptions'; import { type CopyFile, validateCopy } from './shots/lib'; import { posix, readPulled } from './lib/art-pull'; import { type CapProject, capacitorProject, prebuildFor, staleMessage, webState } from './lib/web-assets'; +import { iphoneDuoNote } from './shots/spec'; /** The newest .ipa in a folder (apple build's export), or null. */ function newestIpa(dir: string): string | null { @@ -146,6 +147,8 @@ export async function run(ctx: Ctx): Promise { try { for (const n of (await runScan(ctx.loaded.root, { config: ctx.loaded.path })).report.notes) if (n.startsWith('scan.ignore[')) note(n); } catch (e) { note(`scan.ignore not checked: ${(e as Error).message}`); } } if (config.apple && !config.app.copyright?.trim()) problems.push(COPYRIGHT_MISSING); + const duo = iphoneDuoNote({ apple: !!config.apple, duo: !!config.apple?.iphoneDuo, play: !!config.play }); + if (duo?.level === 'info') { hints.push(duo.msg); log('check', `hint: ${duo.msg}`); } else if (duo) note(duo.msg); // the scaffolder's own placeholders would reach the stores as the app's copyright, contact and legal pages const tph = templatePlaceholders(config as never); if (tph.length) problems.push(`template placeholders still in the config: ${tph.join(', ')} ("Example Studio", example.com): the stores would show them as your copyright, contact address and legal pages; put the real values in`); diff --git a/cli/lib/config.ts b/cli/lib/config.ts index 5c5536f..f64bb93 100644 --- a/cli/lib/config.ts +++ b/cli/lib/config.ts @@ -622,6 +622,10 @@ export interface ShipConfig { * pixel-exact art on 6.3" phones, or if Apple stops scaling. (Screenshot specifications, App Store Connect Help.) */ iphoneMedium?: boolean; + /** Also render and check iPhone Duo (foldable) screenshots: outer 1398 x 2034 and inner 2007 x 2853 (landscape too). + * Optional now, reportedly required from April 2027 for iOS 27.1 SDK builds. Not uploaded while the API has no + * display type for them (cli/shots/spec.ts IPHONE_DUO_DISPLAY). */ + iphoneDuo?: boolean; /** TestFlight beta groups, the tester CSV (in .storebound/) and Test Information (`storebound apple testflight`). */ testflight?: TfConfig; /** Certificates, profiles and capabilities through the API (`storebound apple signing`), signing style of `apple build`. */ diff --git a/cli/lib/embedded.ts b/cli/lib/embedded.ts index 77d5b79..ddf1d2f 100644 --- a/cli/lib/embedded.ts +++ b/cli/lib/embedded.ts @@ -26,7 +26,7 @@ export const TEMPLATE_TEXT: Record = { "profiles/subscription-app/listing.md": "# Example App · Google Play listing copy\n\nSource for `storebound play listing` (title, short + full description) and `storebound play release` (release notes).\nRules the parser follows:\n- every `## ...` section with a `` line is a listing; one section can serve several Play codes\n- under it, `### ...` headings that contain **title** (optional, defaults to `app.name`), **short**, **full** and\n **what's new**, each followed by one fenced block\n- limits (checked before anything is sent): title 30, short 80, full 4000, what's new 500 characters\nOnly claim what the app really does. No prices, no \"best / #1\", no other apps' names.\n\n---\n\n## English (en-US)\n\n\n### Play short description (max 80)\n```\nWhat the app does for people, in one plain line\n```\n\n### Play full description (max 4000)\n```\nFirst paragraph: the job the app does and why it is easier with it, in two or three sentences.\n\nFEATURES\n• Lists and notes that sync across your devices\n• Share a list with family or friends\n• Export your data or delete your account in Settings, any time\n\nFree to use with up to 3 lists. Example Pro unlocks unlimited lists, sharing and themes: yearly with a 1-week free trial, or monthly. Payment is charged to your store account; the subscription renews automatically unless cancelled at least 24 hours before the end of the period, and you can manage or cancel it in your account settings.\n\nTerms of Use: https://example.com/terms\nPrivacy Policy: https://example.com/privacy\n```\n\n### What's new (max 500)\n```\nFirst release. Thanks for trying it!\n```\n\n## Türkçe (tr-TR)\n\n\n### Play kısa açıklama · short (max 80)\n```\nUygulamanın insanlar için ne yaptığını anlatan sade bir cümle\n```\n\n### Play tam açıklama · full (max 4000)\n```\nİlk paragraf: uygulamanın gördüğü iş ve onunla neden daha kolay olduğu, iki üç cümlede.\n\nÖZELLİKLER\n• Tüm cihazlarında eşitlenen listeler ve notlar\n• Bir listeyi ailen ya da arkadaşlarınla paylaş\n• Verilerini dışa aktar ya da hesabını Ayarlar'dan istediğin an sil\n\n3 listeye kadar ücretsiz. Example Pro sınırsız liste, paylaşım ve tema açar: 1 hafta ücretsiz denemeli yıllık ya da aylık. Ödeme mağaza hesabınızdan alınır; abonelik, dönem bitmeden en az 24 saat önce iptal edilmezse otomatik yenilenir; hesap ayarlarınızdan yönetebilir ya da iptal edebilirsiniz.\n\nKullanım Koşulları: https://example.com/terms\nGizlilik Politikası: https://example.com/privacy\n```\n\n### Yenilikler · what's new (max 500)\n```\nİlk sürüm. Denediğin için teşekkürler!\n```\n", "profiles/subscription-app/storebound.config.ts": "// storebound config for one app (profile \"subscription-app\": accounts plus auto-renewable subscriptions, an\n// analytics SDK, no ads). Every answer below is a starting point: edit it to match your app. Credentials NEVER go\n// here (env vars or .storebound/credentials.json, gitignored). Paths are relative to this file.\n// The type import is optional: it only works when storebound is installed in the project (bun add -d storebound).\nimport type { ShipConfig } from 'storebound';\n\nconst config: ShipConfig = {\n // Every compliance answer below is the TEMPLATE's, not yours. While an area is listed here, check / validate block\n // and nothing sends it to a store. Derive the answers from the code (storebound scan --write; for an app that is\n // already live: storebound onboard --declarations), answer the rest, then remove the area from this list.\n unanswered: ['dataSafety', 'appPrivacy', 'reviewNotes', 'ageRating', 'accounts', 'reviewAccess'],\n\n app: {\n name: 'Example App',\n profile: 'subscription-app',\n copyright: '2026 Example Studio',\n privacyPolicyUrl: 'https://example.com/privacy',\n termsUrl: 'https://example.com/terms', // Terms of Use (EULA): in the app and the metadata (Apple 3.1.2)\n supportUrl: 'https://example.com/support',\n marketingUrl: 'https://example.com',\n website: 'https://example.com',\n contactEmail: 'support@example.com',\n },\n\n // Accounts (account-deletion skill). Remove this block if the app has no sign-up / sign-in at all.\n // Apple 5.1.1(v): deletion must start inside the app. Google Play: in the app AND on a public web page.\n accounts: {\n enabled: true,\n deletionUrl: 'https://example.com/delete-account', // public page, no login needed to request deletion\n inApp: 'Settings > Account > Delete account', // goes into the App Review notes\n // How people sign up: 'username' (a name picked in the app, no password, no email), 'username-password',\n // 'email-password', 'email-link', 'phone', 'oauth', 'other'. `storebound scan` proposes the account data and\n // dataSafety.accountCreation from it; only the 'email-*' methods mean an email address.\n signUp: ['email-password'],\n },\n\n // Sign-in for store reviewers (review-access skill). The demo account itself lives ONLY in\n // .storebound/credentials.json (\"reviewDemoAccount\") or REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD.\n reviewAccess: {\n signInRequired: true, // false if every feature works without signing in\n instructions: 'Sign in with the demo account. Sample data is already there; nothing needs a second device.',\n },\n\n // id = your folder / copy key; play = Play language code(s); apple = App Store Connect locale\n languages: [\n { id: 'en', play: 'en-US', apple: 'en-US' },\n { id: 'tr', play: 'tr-TR', apple: 'tr' },\n ],\n\n play: {\n packageName: 'com.example.app',\n defaultLanguage: 'en-US',\n listing: 'store/listing.md',\n icon: 'store/icons/play-512.png',\n },\n\n apple: {\n bundleId: 'com.example.app',\n // name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there (\"already being used\"); default app.name\n listing: 'store/appstore.md',\n // Export compliance (export-compliance skill): decide it, then uncomment. false ONLY if the app uses no encryption\n // beyond the OS (HTTPS through the system, standard sign-in).\n // usesNonExemptEncryption: false,\n // ipad: true,\n info: {\n categories: { primary: 'PRODUCTIVITY', secondary: 'UTILITIES' },\n ageRating: {}, // every content question NONE / false; change what applies (user-generated content, web access ...)\n contentRights: 'DOES_NOT_USE_THIRD_PARTY_CONTENT',\n free: true,\n reviewNotes: [\n 'Example App keeps lists and notes in sync across devices. Pro (yearly with a 1-week free trial, or monthly) unlocks unlimited lists, sharing and themes.',\n 'Subscriptions: Settings > Pro (or the paywall after the third list). Restore Purchases is on the paywall and in Settings > Pro.',\n 'Privacy policy and Terms of Use: on the paywall and in Settings > About.',\n // With a remote paywall or feature flags (storebound scan warns, 2.3.1) you may add a line like:\n // 'Paywall designs and the prices shown are tested remotely with ; what Pro unlocks does not change after review.',\n // Google Play has no review-notes field: put the same line in reviewAccess.instructions (Play App content >\n // App access, 'Any other information') when the app has a sign-in, and say in the full description what needs\n // a paid subscription (Play: Deceptive behavior, Payments).\n ].join('\\n\\n'),\n },\n },\n\n // Auto-renewable subscriptions (store-subscriptions skill): `storebound apple subscriptions`, `storebound play\n // subscriptions`. Apple: one group, levels rank the plans (1 = highest). Play: one subscription per entry with one\n // auto-renewing base plan. Prices: USD base, Apple equalizes from the USA, Play converts per region; overrides set a\n // region by hand. The disclosure (price per period, renewal, how to cancel, Terms + Privacy links) belongs on the\n // purchase screen and in the descriptions.\n subscriptions: [\n {\n name: 'Example Pro',\n listings: { en: { name: 'Example Pro' }, tr: { name: 'Example Pro' } },\n subscriptions: [\n {\n id: 'com.example.app.pro_yearly', period: 'P1Y', level: 1, usd: 29.99,\n listings: {\n en: { title: 'Pro yearly', description: 'Unlimited lists, sharing and themes.', benefits: ['Unlimited lists', 'Shared lists', 'All themes'] },\n tr: { title: 'Pro yıllık', description: 'Sınırsız liste, paylaşım ve tema.', benefits: ['Sınırsız liste', 'Paylaşılan listeler', 'Tüm temalar'] },\n },\n intro: { type: 'free', duration: 'P1W' }, // 1 week free trial for new subscribers\n reviewScreenshot: 'store/iap-review/paywall.png',\n },\n {\n id: 'com.example.app.pro_monthly', period: 'P1M', level: 2, usd: 3.99,\n overrides: [{ region: 'TR', currency: 'TRY', price: 99.99 }],\n listings: {\n en: { title: 'Pro monthly', description: 'Unlimited lists, sharing and themes.', benefits: ['Unlimited lists', 'Shared lists', 'All themes'] },\n tr: { title: 'Pro aylık', description: 'Sınırsız liste, paylaşım ve tema.', benefits: ['Sınırsız liste', 'Paylaşılan listeler', 'Tüm temalar'] },\n },\n reviewScreenshot: 'store/iap-review/paywall.png',\n },\n ],\n },\n ],\n\n // Google Play Data safety. Types not listed = not collected. Typical app with accounts + an analytics SDK acting as\n // your processor (collected, not shared). Edit to match what your app and its SDKs really do.\n dataSafety: {\n collectsData: true,\n encryptedInTransit: true,\n // Sign-up methods. Google does not publish these ids: compare with Play Console > App content > Data safety >\n // Export to CSV before the first import. The delete-account URL (PSL_ACCOUNT_DELETION_URL) comes from\n // accounts.deletionUrl; `storebound check` names any other row Play requires.\n accountCreation: ['PSL_ACM_USER_ID_PASSWORD'],\n // Can people delete their data without deleting the account (a data-only page)? true needs partialDeletionUrl.\n // Play's \"can users request deletion?\" is answered yes by accounts.deletionUrl. Ask the owner.\n partialDeletion: false,\n data: {\n PSL_EMAIL: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_ACCOUNT: { shared: false, collect: ['functionality', 'account'] },\n PSL_USER_GENERATED_CONTENT: { shared: false, collect: ['functionality'] },\n PSL_USER_INTERACTION: { shared: false, collect: ['analytics'] },\n PSL_CRASH_LOGS: { shared: false, collect: ['analytics'] },\n PSL_PERFORMANCE_DIAGNOSTICS: { shared: false, collect: ['analytics'] },\n PSL_DEVICE_ID: { shared: false, collect: ['analytics'] },\n PSL_PURCHASE_HISTORY: { shared: false, collect: ['functionality'] }, // subscription status tied to the account\n },\n },\n\n renders: 'store/renders',\n\n shots: {\n style: 'app', // calm gradient, device frame, headline + subline (game: sparkles and badges)\n copy: 'store/shots/copy.json',\n frames: 'store/shots/frames', // /phone/.png, /tablet/.png\n out: 'store/renders',\n // fonts: { title: 'Inter', body: 'Inter' }, // the app style default\n scenes: [\n { id: 'home', palette: 'mist', frames: [{ src: 'home.png' }] },\n { id: 'detail', palette: 'mint', frames: [{ src: 'detail.png' }] },\n { id: 'share', palette: 'sky', frames: [{ src: 'share.png' }] },\n { id: 'privacy', palette: 'slate', frames: [{ src: 'settings.png' }] },\n ],\n feature: { frame: 'home.png', palette: 'mist' },\n // Raw frames from a web build, the iOS Simulator (ios-sim) or an Android emulator (android-emu): sign in to a demo\n // account with realistic sample data, never real user data (store-screenshots skill).\n capture: {\n baseUrl: 'http://127.0.0.1:5173',\n query: 'lang={lang}&demo=1',\n shots: {\n 'home': { path: '/', delayMs: 1000, device: 'both' },\n 'detail': { path: '/lists/1', delayMs: 1000, device: 'both' },\n 'share': { path: '/lists/1/share', delayMs: 1000, device: 'both' },\n 'settings': { path: '/settings', delayMs: 1000, device: 'both' },\n },\n },\n },\n\n icons: {\n composite: 'store/icon/icon.png',\n foreground: 'store/icon/foreground.png',\n background: 'store/icon/background.png',\n out: 'store/icons',\n },\n};\n\nexport default config;\n", "shots-copy.json": "{\n \"en\": {\n \"hero\": { \"title\": [\"Tap. Match.\", \"Repeat!\"], \"badges\": [[\"100+ levels\", \"and more every update\"], [\"Play offline\", \"No account needed\"]] },\n \"play\": { \"eyebrow\": \"Play\", \"title\": [\"Easy to learn,\", \"hard to put down\"], \"sub\": \"One thumb, short rounds, big satisfying moments.\", \"badges\": [[\"Quick rounds\", \"Two minutes each\"], [\"Great!\"]] },\n \"levels\": { \"eyebrow\": \"Worlds\", \"title\": [\"Explore new\", \"worlds\"], \"sub\": \"A fresh look and new rules every ten levels.\", \"badges\": [[\"10 worlds\", \"A new one every 10 levels\"]] },\n \"stars\": { \"eyebrow\": \"Stars\", \"title\": [\"Play smart,\", \"grab 3 stars\"], \"sub\": \"Finish with moves to spare and collect every star.\", \"badges\": [[\"3 stars\"]] }\n },\n \"tr\": {\n \"hero\": { \"title\": [\"Dokun. Eşleştir.\", \"Tekrarla!\"], \"badges\": [[\"100+ bölüm\", \"her güncellemede yenileri\"], [\"İnternetsiz\", \"hesap gerekmez\"]] },\n \"play\": { \"eyebrow\": \"Oyna\", \"title\": [\"Öğrenmesi kolay,\", \"bırakması zor\"], \"sub\": \"Tek parmak, kısa turlar, büyük keyifli anlar.\", \"badges\": [[\"Kısa turlar\", \"Her biri iki dakika\"], [\"Harika!\"]] },\n \"levels\": { \"eyebrow\": \"Dünyalar\", \"title\": [\"Yeni dünyaları\", \"keşfet\"], \"sub\": \"Her on bölümde yeni bir görünüm ve yeni kurallar.\", \"badges\": [[\"10 dünya\", \"Her 10 bölümde yeni biri\"]] },\n \"stars\": { \"eyebrow\": \"Yıldızlar\", \"title\": [\"Akıllı oyna,\", \"3 yıldızı kap\"], \"sub\": \"Hamle artırarak bitir, tüm yıldızları topla.\", \"badges\": [[\"3 yıldız\"]] }\n },\n \"es\": {\n \"hero\": { \"title\": [\"Toca. Combina.\", \"¡Repite!\"], \"badges\": [[\"100+ niveles\", \"y más en cada versión\"], [\"Sin conexión\", \"Sin cuenta\"]] },\n \"play\": { \"eyebrow\": \"Juega\", \"title\": [\"Fácil de aprender,\", \"difícil de soltar\"], \"sub\": \"Un pulgar, rondas cortas, grandes momentos.\", \"badges\": [[\"Rondas cortas\", \"Dos minutos cada una\"], [\"¡Genial!\"]] },\n \"levels\": { \"eyebrow\": \"Mundos\", \"title\": [\"Explora\", \"nuevos mundos\"], \"sub\": \"Un aspecto nuevo y nuevas reglas cada diez niveles.\", \"badges\": [[\"10 mundos\", \"Uno nuevo cada 10 niveles\"]] },\n \"stars\": { \"eyebrow\": \"Estrellas\", \"title\": [\"Juega con cabeza,\", \"logra 3 estrellas\"], \"sub\": \"Termina con movimientos de sobra y consigue todas las estrellas.\", \"badges\": [[\"3 estrellas\"]] }\n },\n \"ja\": {\n \"hero\": { \"title\": [\"タップして、そろえて、\", \"もう一回!\"], \"badges\": [[\"100以上のステージ\", \"アップデートで追加\"], [\"オフラインで遊べる\", \"アカウント不要\"]] },\n \"play\": { \"eyebrow\": \"プレイ\", \"title\": [\"かんたんなのに\", \"やめられない\"], \"sub\": \"片手で遊べる短いラウンド、気持ちいい瞬間がたくさん。\", \"badges\": [[\"短いラウンド\", \"1回2分\"], [\"すごい!\"]] },\n \"levels\": { \"eyebrow\": \"ワールド\", \"title\": [\"新しいワールドを\", \"冒険しよう\"], \"sub\": \"10ステージごとに新しい見た目と新しいルール。\", \"badges\": [[\"10のワールド\", \"10ステージごとに追加\"]] },\n \"stars\": { \"eyebrow\": \"スター\", \"title\": [\"かしこく遊んで\", \"星を3つゲット\"], \"sub\": \"手数を残してクリアし、すべての星を集めよう。\", \"badges\": [[\"星3つ\"]] }\n },\n \"ar\": {\n \"hero\": { \"title\": [\"انقر. طابق.\", \"كرّر!\"], \"badges\": [[\"أكثر من 100 مرحلة\", \"والمزيد مع كل تحديث\"], [\"العب دون اتصال\", \"دون حساب\"]] },\n \"play\": { \"eyebrow\": \"العب\", \"title\": [\"سهلة التعلّم،\", \"صعبة التوقف\"], \"sub\": \"إبهام واحد، جولات قصيرة، ولحظات ممتعة.\", \"badges\": [[\"جولات قصيرة\", \"دقيقتان لكل جولة\"], [\"رائع!\"]] },\n \"levels\": { \"eyebrow\": \"العوالم\", \"title\": [\"استكشف\", \"عوالم جديدة\"], \"sub\": \"شكل جديد وقواعد جديدة كل عشر مراحل.\", \"badges\": [[\"10 عوالم\", \"عالم جديد كل 10 مراحل\"]] },\n \"stars\": { \"eyebrow\": \"النجوم\", \"title\": [\"العب بذكاء،\", \"واجمع 3 نجوم\"], \"sub\": \"أنهِ المرحلة بحركات متبقية واجمع كل النجوم.\", \"badges\": [[\"3 نجوم\"]] }\n }\n}\n", - "storebound.config.ts": "// storebound config for one game. Everything game-specific lives here; credentials NEVER do (they go in env vars or\n// .storebound/credentials.json, which must stay gitignored). Paths are relative to this file.\n// The type import is optional: it only works when storebound is installed in the project (bun add -d ).\nimport type { ShipConfig } from 'storebound';\n\nconst config: ShipConfig = {\n // Every compliance answer below is the TEMPLATE's, not yours. While an area is listed here, check / validate block\n // and nothing sends it to a store. Derive the answers from the code (storebound scan --write; for an app that is\n // already live: storebound onboard --declarations), answer the rest, then remove the area from this list.\n unanswered: ['dataSafety', 'appPrivacy', 'reviewNotes', 'ageRating'],\n\n app: {\n name: 'Example Game',\n profile: 'game',\n copyright: '2026 Example Studio',\n privacyPolicyUrl: 'https://example.com/privacy',\n supportUrl: 'https://example.com',\n marketingUrl: 'https://example.com',\n // Developer website on Play: the same domain must serve /app-ads.txt if the game shows ads\n website: 'https://example.com',\n contactEmail: 'support@example.com',\n },\n\n // id = your folder / copy key; play = Play language code(s); apple = App Store Connect locale\n languages: [\n { id: 'en', play: 'en-US', apple: 'en-US' },\n { id: 'tr', play: 'tr-TR', apple: 'tr' },\n { id: 'es', play: ['es-ES', 'es-419'], apple: 'es-ES' },\n { id: 'ja', play: 'ja-JP', apple: 'ja' },\n { id: 'ar', play: 'ar', apple: 'ar-SA', rtl: true },\n ],\n\n play: {\n packageName: 'com.example.game',\n defaultLanguage: 'en-US',\n listing: 'store/listing.md',\n icon: 'store/icons/play-512.png',\n // read by `storebound scan` (fill in what is true for your account and app):\n // accountType: 'personal', accountCreated: 'YYYY-MM-DD', // new personal accounts: 12 testers x 14 days closed test\n // targetAges: ['13-15', '16-17', '18+'], // App content > Target audience; under 13 = Families policy\n },\n\n apple: {\n bundleId: 'com.example.game',\n // name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there (\"already being used\"); default app.name\n // appId: '1234567890', // Apple ID of the app record; looked up by bundle id when left out\n listing: 'store/appstore.md',\n reviewShots: 'store/iap-review',\n // Export compliance (export-compliance skill). false ONLY if the game uses no encryption beyond the OS (HTTPS through\n // the system). Left unset on purpose: decide it, then uncomment. Same answer as ITSAppUsesNonExemptEncryption.\n // usesNonExemptEncryption: false,\n // ipad: true, // the app runs on iPad: 13\" iPad screenshots (2064 x 2752, ipad13) are rendered, checked and uploaded\n // iphoneMedium: true, // optional 6.3\" iPhone set (1206 x 2622, iphone-medium); off: Apple scales the 6.5\" set down\n // screenshotTypes: ['APP_IPHONE_67'], // what `storebound validate` requires per locale (default; + APP_IPAD_PRO_3GEN_129 with ipad)\n // TestFlight (`storebound apple testflight`, testflight skill). Tester emails live in .storebound/testers.csv only.\n testflight: {\n groups: [\n { name: 'Team', internal: true, allBuilds: true },\n { name: 'Friends' },\n ],\n description: { en: 'Example Game beta: try the new levels and tell us what feels too hard.' },\n },\n info: {\n categories: { primary: 'GAMES', primarySubOne: 'GAMES_CASUAL', primarySubTwo: 'GAMES_PUZZLE', secondary: 'ENTERTAINMENT' },\n ageRating: { advertising: true }, // everything else NONE / false\n contentRights: 'DOES_NOT_USE_THIRD_PARTY_CONTENT',\n free: true,\n reviewNotes: [\n 'Single-player game. No account or login is needed; there is no user-generated content or chat.',\n 'In-app purchases: Home > Shop. Restore Purchases is in Settings.',\n 'Ads: optional rewarded videos and interstitials between rounds. The App Tracking Transparency prompt is shown before the ad SDK starts.',\n 'Privacy policy: Settings > Privacy.',\n // With remote config, feature flags or a remotely changed paywall (storebound scan warns, 2.3.1) you may add:\n // 'Shop offers and prices shown come from and change remotely; no feature is switched on or off after review.',\n // Google Play has no review-notes field: put the same line in reviewAccess.instructions (Play App content >\n // App access, 'Any other information') when the app has a sign-in, and say in the full description what needs\n // a paid subscription (Play: Deceptive behavior, Payments).\n ].join('\\n\\n'),\n },\n },\n\n // Price changes later for many products / regions: storebound prices export, edit store/prices.csv, prices import --dry.\n // prices: { csv: 'store/prices.csv', baseTerritory: 'USA' },\n\n // Same ids on both stores. Prices: USD base; Play converts per region, Apple equalizes from the USA. Overrides set a\n // region by hand (Apple needs an existing price point with exactly that value).\n products: [\n {\n id: 'com.example.game.remove_ads', type: 'non_consumable', usd: 2.99,\n overrides: [{ region: 'TR', currency: 'TRY', price: 99.99 }],\n listings: {\n en: { title: 'Remove Ads', description: 'Removes interstitial ads for good.' },\n tr: { title: 'Reklamları Kaldır', description: 'Ara reklamları kalıcı olarak kaldırır.' },\n },\n reviewScreenshot: 'store/iap-review/shop.png',\n },\n {\n id: 'com.example.game.coins_small', type: 'consumable', usd: 0.99,\n listings: {\n en: { title: '500 Coins', description: 'A small bag of coins.' },\n tr: { title: '500 Altın', description: 'Küçük bir kese altın.' },\n },\n reviewScreenshot: 'store/iap-review/shop.png',\n },\n ],\n\n // Google Play Data safety. Types not listed = not collected. Purposes: functionality, analytics, communications,\n // fraud, advertising, personalization, account. Typical F2P game with an analytics SDK + ad mediation:\n dataSafety: {\n collectsData: true,\n encryptedInTransit: true,\n // No accounts: PSL_ACM_NONE. A guest account with a name picked on the device and a server token (no password, no\n // email): accounts { enabled: true, signUp: ['username'], ... } and ['PSL_ACM_USER_ID_OTHER_AUTH'] here (Play's\n // \"Username and other authentication\"; `storebound scan` proposes it). With accounts Play also requires the\n // delete-account URL (from accounts.deletionUrl). That page also answers \"can users request that their data is\n // deleted?\" with yes (dataDeletion: 'yes' | 'no' | 'auto90' only for apps without one). partialDeletion: true +\n // partialDeletionUrl when a page deletes data without deleting the account. `storebound check` compares every row with Play's\n // current form (cli/data/play-data-safety-form.csv).\n accountCreation: ['PSL_ACM_NONE'],\n data: {\n PSL_APPROX_LOCATION: { shared: true, collect: ['analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_USER_INTERACTION: { shared: true, collect: ['analytics', 'advertising'], share: ['analytics', 'advertising'] },\n PSL_OTHER_APP_ACTIVITY: { shared: false, collect: ['functionality'] },\n PSL_PERFORMANCE_DIAGNOSTICS: { shared: true, collect: ['analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_DEVICE_ID: { shared: true, collect: ['functionality', 'analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_PURCHASE_HISTORY: { shared: false, collect: ['functionality', 'fraud'] },\n },\n },\n\n // Ads: `storebound validate --play` checks /app-ads.txt for these lines (copy them from your mediation\n // dashboard's app-ads.txt page). Placeholder line below; replace it.\n // ads: { appAdsTxt: ['example-network.com, pub-0000000000000000, DIRECT, 0000000000000000'] },\n\n renders: 'store/renders',\n\n shots: {\n copy: 'store/shots/copy.json',\n frames: 'store/shots/frames', // /phone/.png, /tablet/.png\n out: 'store/renders',\n logo: 'store/shots/logo.png', // optional: hero scene + feature graphic\n // Google Fonts; both cover Latin Extended (tr, pl, cs, ro ...) and Vietnamese. `shots fonts` checks every glyph of the\n // copy; a character the font lacks needs a font that has it or fallback: ['Noto Sans Display'] (else shots check fails).\n fonts: { title: 'Paytone One', body: 'Montserrat' },\n // phone: { w: 440, h: 902, dpr: 3 }, // raw frame size in CSS px (screen below a 54 px status bar)\n // tablet: { w: 1032, h: 1352, dpr: 2 }, // default with apple.ipad (13\" iPad below its 24 px bar), else 800 x 1240\n scenes: [\n { id: 'hero', palette: 'fire', hero: true, over: 34, frames: [{ src: 'hero.png', rotate: -4 }],\n badges: [{ y: 0.42, side: 'l', icon: 'flag', iconBg: 'red', rot: -4 }, { y: 0.66, side: 'r', icon: 'offline', iconBg: 'red', rot: 3 }] },\n { id: 'play', palette: 'violet', frames: [{ src: 'gameplay.png', rotate: 3 }],\n badges: [{ y: 0.3, side: 'l', icon: 'bolt', iconBg: 'gold', rot: -3 }, { y: 0.7, side: 'r', hot: true, rot: 4 }] },\n { id: 'levels', palette: 'sky', frames: [{ src: 'level-b.png', scale: 0.82 }, { src: 'level-a.png', x: -31, dy: 10, scale: 0.7, rotate: -8 }, { src: 'level-c.png', x: 31, dy: 10, scale: 0.7, rotate: 8 }],\n badges: [{ y: 0.66, side: 'r', icon: 'map', iconBg: 'blue', rot: 3 }] },\n { id: 'stars', palette: 'gold', frames: [{ src: 'results.png', rotate: -3 }],\n badges: [{ y: 0.42, side: 'l', stars: true, rot: -3 }] },\n ],\n feature: { frame: 'hero.png', palette: 'fire' },\n capture: {\n baseUrl: 'http://127.0.0.1:5173',\n query: 'lang={lang}&noads=1&seed=1',\n shots: {\n 'hero': { path: '/?level=12', waitFor: \"window.game && game.state === 'playing'\", delayMs: 1500, device: 'both' },\n 'gameplay': { path: '/?level=3', delayMs: 2500, device: 'both' },\n 'level-a': { path: '/?level=20', delayMs: 2000 },\n 'level-b': { path: '/?level=40', delayMs: 2000 },\n 'level-c': { path: '/?level=60', delayMs: 2000 },\n 'results': { path: '/?level=5&result=3', delayMs: 2000, device: 'both' },\n },\n },\n },\n\n icons: {\n composite: 'store/icon/icon.png', // 1024 opaque\n foreground: 'store/icon/foreground.png', // 1024 RGBA, subject on transparent\n background: 'store/icon/background.png', // 1024 opaque\n out: 'store/icons',\n web: 'public/icons',\n // capacitorAssets: 'native/assets',\n // capacitorCommand: 'bunx @capacitor/assets generate --assetPath native/assets',\n // androidRes: 'native/android/app/src/main/res',\n },\n};\n\nexport default config;\n", + "storebound.config.ts": "// storebound config for one game. Everything game-specific lives here; credentials NEVER do (they go in env vars or\n// .storebound/credentials.json, which must stay gitignored). Paths are relative to this file.\n// The type import is optional: it only works when storebound is installed in the project (bun add -d ).\nimport type { ShipConfig } from 'storebound';\n\nconst config: ShipConfig = {\n // Every compliance answer below is the TEMPLATE's, not yours. While an area is listed here, check / validate block\n // and nothing sends it to a store. Derive the answers from the code (storebound scan --write; for an app that is\n // already live: storebound onboard --declarations), answer the rest, then remove the area from this list.\n unanswered: ['dataSafety', 'appPrivacy', 'reviewNotes', 'ageRating'],\n\n app: {\n name: 'Example Game',\n profile: 'game',\n copyright: '2026 Example Studio',\n privacyPolicyUrl: 'https://example.com/privacy',\n supportUrl: 'https://example.com',\n marketingUrl: 'https://example.com',\n // Developer website on Play: the same domain must serve /app-ads.txt if the game shows ads\n website: 'https://example.com',\n contactEmail: 'support@example.com',\n },\n\n // id = your folder / copy key; play = Play language code(s); apple = App Store Connect locale\n languages: [\n { id: 'en', play: 'en-US', apple: 'en-US' },\n { id: 'tr', play: 'tr-TR', apple: 'tr' },\n { id: 'es', play: ['es-ES', 'es-419'], apple: 'es-ES' },\n { id: 'ja', play: 'ja-JP', apple: 'ja' },\n { id: 'ar', play: 'ar', apple: 'ar-SA', rtl: true },\n ],\n\n play: {\n packageName: 'com.example.game',\n defaultLanguage: 'en-US',\n listing: 'store/listing.md',\n icon: 'store/icons/play-512.png',\n // read by `storebound scan` (fill in what is true for your account and app):\n // accountType: 'personal', accountCreated: 'YYYY-MM-DD', // new personal accounts: 12 testers x 14 days closed test\n // targetAges: ['13-15', '16-17', '18+'], // App content > Target audience; under 13 = Families policy\n },\n\n apple: {\n bundleId: 'com.example.game',\n // name: 'Example: Short Tagline', // App Store name (max 30) when app.name is taken there (\"already being used\"); default app.name\n // appId: '1234567890', // Apple ID of the app record; looked up by bundle id when left out\n listing: 'store/appstore.md',\n reviewShots: 'store/iap-review',\n // Export compliance (export-compliance skill). false ONLY if the game uses no encryption beyond the OS (HTTPS through\n // the system). Left unset on purpose: decide it, then uncomment. Same answer as ITSAppUsesNonExemptEncryption.\n // usesNonExemptEncryption: false,\n // ipad: true, // the app runs on iPad: 13\" iPad screenshots (2064 x 2752, ipad13) are rendered, checked and uploaded\n // iphoneMedium: true, // optional 6.3\" iPhone set (1206 x 2622, iphone-medium); off: Apple scales the 6.5\" set down\n // iphoneDuo: true, // optional iPhone Duo (foldable) sets, outer 1398 x 2034 + inner 2007 x 2853; rendered and checked, not uploaded until the API takes them\n // screenshotTypes: ['APP_IPHONE_61'], // what `storebound validate` requires per locale (default: medium display, met by a 6.9\" or 6.5\" set; + APP_IPAD_PRO_3GEN_129 with ipad)\n // TestFlight (`storebound apple testflight`, testflight skill). Tester emails live in .storebound/testers.csv only.\n testflight: {\n groups: [\n { name: 'Team', internal: true, allBuilds: true },\n { name: 'Friends' },\n ],\n description: { en: 'Example Game beta: try the new levels and tell us what feels too hard.' },\n },\n info: {\n categories: { primary: 'GAMES', primarySubOne: 'GAMES_CASUAL', primarySubTwo: 'GAMES_PUZZLE', secondary: 'ENTERTAINMENT' },\n ageRating: { advertising: true }, // everything else NONE / false\n contentRights: 'DOES_NOT_USE_THIRD_PARTY_CONTENT',\n free: true,\n reviewNotes: [\n 'Single-player game. No account or login is needed; there is no user-generated content or chat.',\n 'In-app purchases: Home > Shop. Restore Purchases is in Settings.',\n 'Ads: optional rewarded videos and interstitials between rounds. The App Tracking Transparency prompt is shown before the ad SDK starts.',\n 'Privacy policy: Settings > Privacy.',\n // With remote config, feature flags or a remotely changed paywall (storebound scan warns, 2.3.1) you may add:\n // 'Shop offers and prices shown come from and change remotely; no feature is switched on or off after review.',\n // Google Play has no review-notes field: put the same line in reviewAccess.instructions (Play App content >\n // App access, 'Any other information') when the app has a sign-in, and say in the full description what needs\n // a paid subscription (Play: Deceptive behavior, Payments).\n ].join('\\n\\n'),\n },\n },\n\n // Price changes later for many products / regions: storebound prices export, edit store/prices.csv, prices import --dry.\n // prices: { csv: 'store/prices.csv', baseTerritory: 'USA' },\n\n // Same ids on both stores. Prices: USD base; Play converts per region, Apple equalizes from the USA. Overrides set a\n // region by hand (Apple needs an existing price point with exactly that value).\n products: [\n {\n id: 'com.example.game.remove_ads', type: 'non_consumable', usd: 2.99,\n overrides: [{ region: 'TR', currency: 'TRY', price: 99.99 }],\n listings: {\n en: { title: 'Remove Ads', description: 'Removes interstitial ads for good.' },\n tr: { title: 'Reklamları Kaldır', description: 'Ara reklamları kalıcı olarak kaldırır.' },\n },\n reviewScreenshot: 'store/iap-review/shop.png',\n },\n {\n id: 'com.example.game.coins_small', type: 'consumable', usd: 0.99,\n listings: {\n en: { title: '500 Coins', description: 'A small bag of coins.' },\n tr: { title: '500 Altın', description: 'Küçük bir kese altın.' },\n },\n reviewScreenshot: 'store/iap-review/shop.png',\n },\n ],\n\n // Google Play Data safety. Types not listed = not collected. Purposes: functionality, analytics, communications,\n // fraud, advertising, personalization, account. Typical F2P game with an analytics SDK + ad mediation:\n dataSafety: {\n collectsData: true,\n encryptedInTransit: true,\n // No accounts: PSL_ACM_NONE. A guest account with a name picked on the device and a server token (no password, no\n // email): accounts { enabled: true, signUp: ['username'], ... } and ['PSL_ACM_USER_ID_OTHER_AUTH'] here (Play's\n // \"Username and other authentication\"; `storebound scan` proposes it). With accounts Play also requires the\n // delete-account URL (from accounts.deletionUrl). That page also answers \"can users request that their data is\n // deleted?\" with yes (dataDeletion: 'yes' | 'no' | 'auto90' only for apps without one). partialDeletion: true +\n // partialDeletionUrl when a page deletes data without deleting the account. `storebound check` compares every row with Play's\n // current form (cli/data/play-data-safety-form.csv).\n accountCreation: ['PSL_ACM_NONE'],\n data: {\n PSL_APPROX_LOCATION: { shared: true, collect: ['analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_USER_INTERACTION: { shared: true, collect: ['analytics', 'advertising'], share: ['analytics', 'advertising'] },\n PSL_OTHER_APP_ACTIVITY: { shared: false, collect: ['functionality'] },\n PSL_PERFORMANCE_DIAGNOSTICS: { shared: true, collect: ['analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_DEVICE_ID: { shared: true, collect: ['functionality', 'analytics', 'advertising', 'fraud'], share: ['analytics', 'advertising', 'fraud'] },\n PSL_PURCHASE_HISTORY: { shared: false, collect: ['functionality', 'fraud'] },\n },\n },\n\n // Ads: `storebound validate --play` checks /app-ads.txt for these lines (copy them from your mediation\n // dashboard's app-ads.txt page). Placeholder line below; replace it.\n // ads: { appAdsTxt: ['example-network.com, pub-0000000000000000, DIRECT, 0000000000000000'] },\n\n renders: 'store/renders',\n\n shots: {\n copy: 'store/shots/copy.json',\n frames: 'store/shots/frames', // /phone/.png, /tablet/.png\n out: 'store/renders',\n logo: 'store/shots/logo.png', // optional: hero scene + feature graphic\n // Google Fonts; both cover Latin Extended (tr, pl, cs, ro ...) and Vietnamese. `shots fonts` checks every glyph of the\n // copy; a character the font lacks needs a font that has it or fallback: ['Noto Sans Display'] (else shots check fails).\n fonts: { title: 'Paytone One', body: 'Montserrat' },\n // phone: { w: 440, h: 902, dpr: 3 }, // raw frame size in CSS px (screen below a 54 px status bar)\n // tablet: { w: 1032, h: 1352, dpr: 2 }, // default with apple.ipad (13\" iPad below its 24 px bar), else 800 x 1240\n scenes: [\n { id: 'hero', palette: 'fire', hero: true, over: 34, frames: [{ src: 'hero.png', rotate: -4 }],\n badges: [{ y: 0.42, side: 'l', icon: 'flag', iconBg: 'red', rot: -4 }, { y: 0.66, side: 'r', icon: 'offline', iconBg: 'red', rot: 3 }] },\n { id: 'play', palette: 'violet', frames: [{ src: 'gameplay.png', rotate: 3 }],\n badges: [{ y: 0.3, side: 'l', icon: 'bolt', iconBg: 'gold', rot: -3 }, { y: 0.7, side: 'r', hot: true, rot: 4 }] },\n { id: 'levels', palette: 'sky', frames: [{ src: 'level-b.png', scale: 0.82 }, { src: 'level-a.png', x: -31, dy: 10, scale: 0.7, rotate: -8 }, { src: 'level-c.png', x: 31, dy: 10, scale: 0.7, rotate: 8 }],\n badges: [{ y: 0.66, side: 'r', icon: 'map', iconBg: 'blue', rot: 3 }] },\n { id: 'stars', palette: 'gold', frames: [{ src: 'results.png', rotate: -3 }],\n badges: [{ y: 0.42, side: 'l', stars: true, rot: -3 }] },\n ],\n feature: { frame: 'hero.png', palette: 'fire' },\n capture: {\n baseUrl: 'http://127.0.0.1:5173',\n query: 'lang={lang}&noads=1&seed=1',\n shots: {\n 'hero': { path: '/?level=12', waitFor: \"window.game && game.state === 'playing'\", delayMs: 1500, device: 'both' },\n 'gameplay': { path: '/?level=3', delayMs: 2500, device: 'both' },\n 'level-a': { path: '/?level=20', delayMs: 2000 },\n 'level-b': { path: '/?level=40', delayMs: 2000 },\n 'level-c': { path: '/?level=60', delayMs: 2000 },\n 'results': { path: '/?level=5&result=3', delayMs: 2000, device: 'both' },\n },\n },\n },\n\n icons: {\n composite: 'store/icon/icon.png', // 1024 opaque\n foreground: 'store/icon/foreground.png', // 1024 RGBA, subject on transparent\n background: 'store/icon/background.png', // 1024 opaque\n out: 'store/icons',\n web: 'public/icons',\n // capacitorAssets: 'native/assets',\n // capacitorCommand: 'bunx @capacitor/assets generate --assetPath native/assets',\n // androidRes: 'native/android/app/src/main/res',\n },\n};\n\nexport default config;\n", "testers.csv": "email,first_name,last_name,groups\n", "web/appstore.svg": "App Store", "web/googleplay.svg": "Google Play", diff --git a/cli/lib/validate-rules.ts b/cli/lib/validate-rules.ts index 4c3b14b..3fd8938 100644 --- a/cli/lib/validate-rules.ts +++ b/cli/lib/validate-rules.ts @@ -3,6 +3,7 @@ import { consoleLink, consoleUrl } from './console-links'; import { type FixAction, fixAppleListing, fixPlayListing, fixReviewDetails } from './fix-actions'; +import { iphoneDuoNote } from '../shots/spec'; export type Level = 'blocker' | 'warn' | 'ok'; @@ -11,11 +12,16 @@ export type Level = 'blocker' | 'warn' | 'ok'; * (either 13" display type). The smaller sizes are scaled down from these. A live app with only the 6.5" set is fine * (store-pitfalls 44). */ export const ACCEPTED_INSTEAD: Record = { + // the console's required iPhone class (medium display): smaller sizes scale down from a larger set automatically + APP_IPHONE_61: ['APP_IPHONE_67', 'APP_IPHONE_65'], APP_IPHONE_67: ['APP_IPHONE_65'], APP_IPHONE_65: ['APP_IPHONE_67'], APP_IPAD_PRO_3GEN_129: ['APP_IPAD_PRO_129'], APP_IPAD_PRO_129: ['APP_IPAD_PRO_3GEN_129'], }; +/** Required class -> larger sets App Store Connect scales down into it ("View All Sizes in Media Manager"). */ +const SCALES_DOWN: Record = { APP_IPHONE_61: ['APP_IPHONE_67', 'APP_IPHONE_65'] }; +const LABEL: Record = { APP_IPHONE_61: 'iPhone with Dynamic Island (medium display)', APP_IPAD_PRO_3GEN_129: 'iPad 13" display' }; export interface Finding { store: 'apple' | 'play'; level: Level; code: string; msg: string; fix?: string; /** Absolute deep link to the console page the message points to (desktop / MCP render it as an Open link). */ url?: string; @@ -58,6 +64,10 @@ export interface AppleSnapshot { expectedLocales: string[]; locales: { locale: string; name?: string; subtitle?: string; description?: string; keywords?: string; screenshots: Record }[]; requiredDisplayTypes: string[]; + /** apple.iphoneDuo (iPhone Duo renders on) and whether the project has a play section, for the Duo note. */ + iphoneDuo?: boolean; + play?: boolean; + today?: Date; reviewDetail: { contactEmail?: string | null; contactPhone?: string | null; contactFirstName?: string | null; contactLastName?: string | null; demoAccountRequired?: boolean; demoAccountName?: string | null; notes?: string | null } | null; /** Age rating declaration attributes (null = not readable). */ ageRating: Record | null; @@ -212,7 +222,8 @@ export function appleRules(s: AppleSnapshot): Finding[] { for (const t of s.requiredDisplayTypes) { if (l.screenshots[t]) continue; const alt = (ACCEPTED_INSTEAD[t] ?? []).find(x => l.screenshots[x]); - if (alt) add('warn', 'screenshots-size', `${l.locale}: no ${t} set; Apple accepts the ${alt} set (${l.screenshots[alt]} screenshots) and scales it for the other sizes. Recommended, not required: add ${t}`, 'storebound apple screenshots'); + if (alt && SCALES_DOWN[t]?.includes(alt)) add('ok', 'screenshots-size', `${l.locale}: ${LABEL[t] ?? t} filled by scaling the ${alt} set down (${l.screenshots[alt]} screenshots)`); + else if (alt) add('warn', 'screenshots-size', `${l.locale}: no ${t} set; Apple accepts the ${alt} set (${l.screenshots[alt]} screenshots) and scales it for the other sizes. Recommended, not required: add ${t}`, 'storebound apple screenshots'); else add('blocker', 'screenshots', `${l.locale}: no ${t} screenshots${ACCEPTED_INSTEAD[t] ? ` (or ${ACCEPTED_INSTEAD[t]!.join(' / ')})` : ''}`, 'storebound apple screenshots'); } } @@ -254,6 +265,9 @@ export function appleRules(s: AppleSnapshot): Finding[] { add(urlOk(s.privacyUrl) ? 'ok' : 'blocker', 'privacy-url', `privacy policy ${s.privacyUrl.url}: ${urlMsg(s.privacyUrl)}`, 'privacy-policy skill'); if (s.profile) f.push(...profileRules('apple', s.profile, { reviewDetail: s.reviewDetail, descriptions: s.locales.map(l => ({ locale: l.locale, text: l.description ?? '' })) })); f.push(...rendersFindings('apple', s.renders)); + // iPhone Duo: optional until April 2027, so a passing note (never a blocker); a warning after that date + const duo = iphoneDuoNote({ apple: true, duo: !!s.iphoneDuo, play: s.play, today: s.today }); + if (duo) add(duo.level === 'info' ? 'ok' : 'warn', 'screenshots-duo', duo.msg, 'apple.iphoneDuo: true, then storebound shots render'); return sortFindings(f); } diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index 318c5eb..67c90f4 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -228,7 +228,7 @@ export const TOOLS: ToolDef[] = [ ...(i.concurrency ? ['--concurrency', String(i.concurrency)] : []), ...(i.mode === 'force' ? ['--force'] : i.mode === 'only-missing' ? ['--only-missing'] : [])] }, { name: 'shots_render', title: 'Render store screenshots', command: ['shots', 'render'], write: true, network: false, idempotent: true, description: 'Store screenshots + Play feature graphic in every size and language from the frames and the copy file (local PNGs, needs Playwright + ffmpeg; slow for many languages). dry_run lists what would be rendered.', - props: { lang, size: { type: 'string', description: 'Comma-separated size keys: ios69, ios65, iphone-medium, ipad13, play, tab7, tab10, feature' }, + props: { lang, size: { type: 'string', description: 'Comma-separated size keys: ios69, ios65, iphone-medium, iphone-duo-outer, iphone-duo-inner, ipad13, play, tab7, tab10, feature' }, scenes: { type: 'string', description: 'Comma-separated scene ids' }, variant, all_variants: { type: 'boolean', default: false, description: 'Base + every variant' }, concurrency: { type: 'integer', minimum: 1, maximum: 32, description: 'Parallel pages (default min(4, CPU cores / 2))' } }, args: i => [...opt('lang', i.lang), ...opt('size', i.size), ...opt('scenes', i.scenes), ...(i.all_variants === true ? ['--variants'] : opt('variant', i.variant)), diff --git a/cli/shots/lib.ts b/cli/shots/lib.ts index 3346f06..a173e0c 100644 --- a/cli/shots/lib.ts +++ b/cli/shots/lib.ts @@ -11,6 +11,9 @@ export const SIZES: Record): Record<' export const PLAY_TABLET_SIZES: readonly string[] = ['tab7', 'tab10']; /** Size keys this project renders by default: Apple sizes only with an apple section (iPad only with apple.ipad, the - * 6.3" iPhone only with apple.iphoneMedium), + * 6.3" iPhone only with apple.iphoneMedium, the iPhone Duo sizes only with apple.iphoneDuo), * Play sizes only with a play section (both when neither is configured); the Play tablet sizes only when `tablets` * (resolved play.tablets, see resolvedTablets in report.ts; unset here = play.tablets ?? true). */ export function defaultSizes(config: Pick, tablets?: boolean): string[] { const apple = !!config.apple || !config.play, play = !!config.play || !config.apple; const tabs = tablets ?? config.play?.tablets ?? true; return Object.keys(SIZES).filter(k => (k === 'ipad13' ? apple && !!config.apple?.ipad : k === 'iphone-medium' ? apple && !!config.apple?.iphoneMedium + : k.startsWith('iphone-duo') ? apple && !!config.apple?.iphoneDuo : k.startsWith('ios') ? apple : PLAY_TABLET_SIZES.includes(k) ? play && tabs : play)); } diff --git a/cli/shots/spec.ts b/cli/shots/spec.ts index 8c8074b..e0663ec 100644 --- a/cli/shots/spec.ts +++ b/cli/shots/spec.ts @@ -40,10 +40,14 @@ export const IMAGE_SPECS: Record = { // 6.3" iPhone with Dynamic Island, medium display (iPhone 14 Pro .. 18 Pro): optional here (apple.iphoneMedium). Apple // scales the 6.5" (Face ID large) set down for it when it is missing. APP_IPHONE_61 is inferred: the enum has no // descriptions and 61 is the only medium iPhone bucket (NOT VERIFIED against an upload). - 'iphone-medium': { store: 'apple', type: 'APP_IPHONE_61', label: 'App Store iPhone 6.3"', sizes: [[1206, 2622], [1179, 2556]], min: 1, max: 10, maxBytes: null, alpha: false }, + 'iphone-medium': { store: 'apple', type: 'APP_IPHONE_61', label: 'iPhone with Dynamic Island (medium display)', sizes: [[1206, 2622], [1179, 2556]], min: 1, max: 10, maxBytes: null, alpha: false }, ios65: { store: 'apple', type: 'APP_IPHONE_65', label: 'App Store iPhone 6.5"', sizes: [[1284, 2778], [1242, 2688]], min: 1, max: 10, maxBytes: null, alpha: false }, // 13" iPad display (iPad Pro M4/M5, iPad Air M2+): required when the app runs on iPad. API display type keeps the old name. - ipad13: { store: 'apple', type: 'APP_IPAD_PRO_3GEN_129', label: 'App Store iPad 13"', sizes: [[2064, 2752], [2048, 2732]], min: 1, max: 10, maxBytes: null, alpha: false }, + ipad13: { store: 'apple', type: 'APP_IPAD_PRO_3GEN_129', label: 'iPad 13" display', sizes: [[2064, 2752], [2048, 2732]], min: 1, max: 10, maxBytes: null, alpha: false }, + // iPhone Duo (foldable, Screenshot specifications, October 2026): outer and inner display, portrait or landscape, + // optional (apple.iphoneDuo). `type` is not an ASC display type: see IPHONE_DUO_DISPLAY. No app preview sizes yet. + 'iphone-duo-outer': { store: 'apple', type: 'IPHONE_DUO_OUTER', label: 'iPhone Duo (outer display)', sizes: [[1398, 2034]], min: 1, max: 10, maxBytes: null, alpha: false }, + 'iphone-duo-inner': { store: 'apple', type: 'IPHONE_DUO_INNER', label: 'iPhone Duo (inner display)', sizes: [[2007, 2853]], min: 1, max: 10, maxBytes: null, alpha: false }, play: { store: 'play', type: 'phoneScreenshots', label: 'Play phone', sizes: [[1080, 1920]], min: 2, max: 8, maxBytes: 8 * MB, alpha: false }, tab7: { store: 'play', type: 'sevenInchScreenshots', label: 'Play 7" tablet', sizes: [[1080, 1920]], min: 0, max: 8, maxBytes: 8 * MB, alpha: false }, tab10: { store: 'play', type: 'tenInchScreenshots', label: 'Play 10" tablet', sizes: [[1440, 2560]], min: 0, max: 8, maxBytes: 8 * MB, alpha: false }, @@ -51,6 +55,23 @@ export const IMAGE_SPECS: Record = { feature: { store: 'play', type: 'featureGraphic', label: 'Play feature graphic', sizes: [[1024, 500]], min: 1, max: 1, maxBytes: 15 * MB, alpha: false }, }; +/** ASC screenshotDisplayType per iPhone Duo size key. null = NOT IN THE API YET: ScreenshotDisplayType in App Store + * Connect API 4.5.1 (spec checked 2026-10-18) has no Duo value (only AppAssetLibraryDisplayClass lists IPHONE_DUO). + * When Apple adds it: regenerate (bun tools/gen-api.ts) and put the exact enum names here; uploads then include them. */ +export const IPHONE_DUO_DISPLAY: Record = { 'iphone-duo-outer': null, 'iphone-duo-inner': null }; +export const IPHONE_DUO_NOT_IN_API = 'App Store Connect does not take iPhone Duo screenshots through the API yet; storebound keeps them in store/renders'; +/** Reportedly required from this date for apps built with the iOS 27.1 SDK or later. */ +export const IPHONE_DUO_REQUIRED_FROM = '2027-04-01'; +const PLAY_FOLDABLE = 'Google Play has no foldable slot: foldables show the 7" / 10" tablet screenshots (tab7, tab10, play.tablets)'; + +/** check / validate note for an iPhone app without iPhone Duo screenshots: info before IPHONE_DUO_REQUIRED_FROM, a + * warning after (never an error: the rule depends on the SDK the build uses). null when Duo renders exist or no iPhone app. */ +export function iphoneDuoNote(o: { apple: boolean; duo: boolean; play?: boolean; today?: Date }): { level: 'info' | 'warn'; msg: string } | null { + if (!o.apple || o.duo) return null; + const late = (o.today ?? new Date()).toISOString().slice(0, 10) >= IPHONE_DUO_REQUIRED_FROM; + return { level: late ? 'warn' : 'info', msg: `no iPhone Duo screenshots (outer 1398x2034, inner 2007x2853; apple.iphoneDuo): optional now, required from April 2027 for iOS 27.1 SDK builds${o.play ? `. ${PLAY_FOLDABLE}` : ''}` }; +} + /** Play screenshots in general (any size the store accepts): 320..3840 px per side, long side at most 2x the short. */ export function playScreenshotOk(w: number, h: number): boolean { const lo = Math.min(w, h), hi = Math.max(w, h); diff --git a/cli/validate.ts b/cli/validate.ts index 65e6fe3..b3843c3 100644 --- a/cli/validate.ts +++ b/cli/validate.ts @@ -113,6 +113,7 @@ export async function collectApple(ctx: Ctx): Promise { build, locales, reviewDetail, ageRating, expectedLocales: config.languages.map(l => l.apple).filter((x): x is string => !!x), requiredDisplayTypes: requiredDisplayTypes(config.apple), + iphoneDuo: !!config.apple?.iphoneDuo, play: !!config.play, priceSchedule: !!sched?.included?.some((x: J) => x.type === 'appPrices'), availability: !!avail?.data, firstProductGaps, diff --git a/docs/store-art.md b/docs/store-art.md index 5eba830..a9b2567 100644 --- a/docs/store-art.md +++ b/docs/store-art.md @@ -76,6 +76,10 @@ languages, every store size, a review gallery and an app preview video. No store 6. **Video.** `shots record` films the autoplay mode, `shots video` cuts 15-30 s App Store previews (886 x 1920, 1200 x 1600) and a 9:16 / 16:9 promo for YouTube with captions in every language, `apple previews` uploads them. Play takes a YouTube URL in `play.video`. +7. **iPhone Duo (foldable).** `apple.iphoneDuo: true` renders and checks the outer (1398 x 2034) and inner + (2007 x 2853) sets. Optional now, reportedly required from April 2027 for iOS 27.1 SDK builds (`check` / `validate` + note it). The API has no Duo display type yet, so `apple screenshots` skips them with a link to the console's + iPhone Duo tab. Play has no foldable slot: foldables use the 7" / 10" tablet sets. Details: the [store-screenshots](../skills/store-screenshots/SKILL.md) and [app-previews](../skills/app-previews/SKILL.md) skills. diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 8458b2d..236b1a8 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -899,3 +899,15 @@ that fails without the fix (see CONTRIBUTING.md). `cli/lib/scan/rules.ts`, the SDK table `REMOTE_SDKS` in `cli/lib/scan/sdks.ts`). A code obfuscator (DexGuard, iXGuard, a JavaScript obfuscator) is a low `obfuscation` note; ProGuard / R8 minify alone is never reported. `tests/remote-features.test.ts`. + +## 75. iPhone Duo screenshots: in the console, not in the API + +- **Symptom:** App Store Connect shows an "iPhone Duo" tab next to "iPhone with Dynamic Island (medium display)" and + "iPad 13" display", but an upload for it through the API has no display type to use (a guessed one answers 400). +- **Cause:** the API's `ScreenshotDisplayType` (4.5.1) has no Duo value yet; only the asset library enum lists + `IPHONE_DUO`. Duo is optional now, reportedly required from April 2027 for iOS 27.1 SDK builds. +- **Do:** render and check the sets (`apple.iphoneDuo: true`), add them in the console's iPhone Duo tab (the skip + message has the deep link), never guess an enum name. For Play point foldables to the tablet sets; there is no Duo slot. +- **Guard:** `IPHONE_DUO_DISPLAY` in `cli/shots/spec.ts` (null = not in the API; regenerate with + `bun tools/gen-api.ts` and fill in the exact names), `skippedDuoSets` in `cli/apple/screenshots.ts`, the + `screenshots-duo` note in check / validate. `tests/ppo.test.ts`. diff --git a/skills/store-screenshots/SKILL.md b/skills/store-screenshots/SKILL.md index b6d37ba..b16019a 100644 --- a/skills/store-screenshots/SKILL.md +++ b/skills/store-screenshots/SKILL.md @@ -33,6 +33,8 @@ or uploaded as another size. `store/renders` can be large (hundreds of MB) and n |---|---|---| | ios69 | 1320 x 2868 | App Store 6.9" (`APP_IPHONE_67`, "Dynamic Island (large display)"); the set storebound requires | | ios65 | 1284 x 2778 | App Store 6.5" (`APP_IPHONE_65`) | +| iphone-duo-outer | 1398 x 2034 (or 2034 x 1398) | App Store "iPhone Duo" outer display; optional, only with `apple.iphoneDuo: true` (tablet frames) | +| iphone-duo-inner | 2007 x 2853 (or 2853 x 2007) | App Store "iPhone Duo" inner display; same switch | | ipad13 | 2064 x 2752 | App Store 13" iPad (`APP_IPAD_PRO_3GEN_129`), required when the app runs on iPad; only with `apple.ipad: true` | | play | 1080 x 1920 | Play phone (2-8, ratio at most 2:1) | | tab7 | 1080 x 1920 | Play 7" tablet (tablet frames, Android tablet body); optional, see `play.tablets` | @@ -61,6 +63,18 @@ to the 13" iPad screen (1032 x 1352 CSS px @2x below a 24 px bar), so an `iPad P simulator screenshot fits after the bar is cropped. Play tablet sizes (tab7 / tab10) reuse the same tablet frames, drawn in a plain Android tablet body instead of the iPad one. +**iPhone Duo (foldable).** App Store Connect's "App Previews and Screenshots" tab now lists three classes: +"iPhone with Dynamic Island (medium display)" (required for iPhone; a 6.9" or 6.5" set scales down into it, so +`validate` passes with the `ios69` set), "iPhone Duo" and "iPad 13" display" (required with `apple.ipad`). Duo takes an +outer (1398 x 2034) and an inner (2007 x 2853) set, portrait or landscape, PNG / JPEG without alpha, 1-10 each. It is +optional now and reportedly required from April 2027 for builds with the iOS 27.1 SDK or later; `check` / `validate` +print an info note until then (a warning after, never a blocker). `apple.iphoneDuo: true` adds both sizes to +`shots render` / `shots check` / the gallery. The API (4.5.1) has no Duo `ScreenshotDisplayType` yet, so +`apple screenshots` skips the Duo folders with a message and the deep link to the version page; add them in the +console's iPhone Duo tab until then (one constant, `IPHONE_DUO_DISPLAY` in `cli/shots/spec.ts`, takes the names once +the enum has them). No Duo app preview sizes are published. Google Play has no foldable slot: foldables show the +7" / 10" tablet sets below. + **Play tablets are optional.** Play requires the 512 x 512 icon, the 1024 x 500 feature graphic and at least 2 screenshots (answer 9866151 above); 7" / 10" tablet screenshots are optional, but without them the app is not eligible for tablet featuring. `play.tablets` decides: unset = true when tablet renders (tab7/ or tab10/) already exist, else diff --git a/templates/storebound.config.ts b/templates/storebound.config.ts index 38d6827..91a5bab 100644 --- a/templates/storebound.config.ts +++ b/templates/storebound.config.ts @@ -51,7 +51,8 @@ const config: ShipConfig = { // usesNonExemptEncryption: false, // ipad: true, // the app runs on iPad: 13" iPad screenshots (2064 x 2752, ipad13) are rendered, checked and uploaded // iphoneMedium: true, // optional 6.3" iPhone set (1206 x 2622, iphone-medium); off: Apple scales the 6.5" set down - // screenshotTypes: ['APP_IPHONE_67'], // what `storebound validate` requires per locale (default; + APP_IPAD_PRO_3GEN_129 with ipad) + // iphoneDuo: true, // optional iPhone Duo (foldable) sets, outer 1398 x 2034 + inner 2007 x 2853; rendered and checked, not uploaded until the API takes them + // screenshotTypes: ['APP_IPHONE_61'], // what `storebound validate` requires per locale (default: medium display, met by a 6.9" or 6.5" set; + APP_IPAD_PRO_3GEN_129 with ipad) // TestFlight (`storebound apple testflight`, testflight skill). Tester emails live in .storebound/testers.csv only. testflight: { groups: [ diff --git a/tests/ppo.test.ts b/tests/ppo.test.ts index fce61e6..f130eab 100644 --- a/tests/ppo.test.ts +++ b/tests/ppo.test.ts @@ -1,11 +1,12 @@ import { describe, expect, test } from 'bun:test'; -import { displaySets } from '../cli/apple/screenshots'; +import { displaySets, skippedDuoSets } from '../cli/apple/screenshots'; +import { appleRules } from '../cli/lib/validate-rules'; import { checkCreate, createExperimentReq, defaultName, experimentFromApi, pickExperiment, planTreatmentLocales, planTreatments, startStopReq } from '../cli/lib/ppo'; import { validateConfig } from '../cli/lib/config'; import { FORBIDDEN_ARGS, TOOLS, toArgv, validateInput } from '../cli/mcp-tools'; import { requiredSets } from '../cli/shots/report'; import { defaultSizes, SIZES } from '../cli/shots/lib'; -import { checkImage, IMAGE_SPECS, imageInfo } from '../cli/shots/spec'; +import { checkImage, IMAGE_SPECS, imageInfo, IPHONE_DUO_DISPLAY, IPHONE_DUO_NOT_IN_API, iphoneDuoNote } from '../cli/shots/spec'; import { png } from './fixtures'; describe('product page optimization', () => { @@ -74,3 +75,47 @@ describe('optional 6.3" iPhone size (iphone-medium)', () => { expect(checkImage(imageInfo(png(1320, 2868)), 'iphone-medium').map(i => i.code)).toEqual(['size']); }); }); + +describe('iPhone Duo (foldable) sizes', () => { + test('device table: outer and inner, portrait and landscape; opt-in with apple.iphoneDuo', () => { + expect(SIZES['iphone-duo-outer']).toMatchObject({ w: 1398, h: 2034 }); + expect(SIZES['iphone-duo-inner']).toMatchObject({ w: 2007, h: 2853 }); + expect(defaultSizes({ apple: { bundleId: 'x' } })).not.toContain('iphone-duo-outer'); + expect(defaultSizes({ apple: { bundleId: 'x', iphoneDuo: true } })).toEqual(expect.arrayContaining(['iphone-duo-outer', 'iphone-duo-inner'])); + expect(defaultSizes({ play: { packageName: 'x' }, apple: undefined })).not.toContain('iphone-duo-inner'); + }); + test('shots check: the 4 exact sizes pass, others and alpha fail', () => { + for (const [k, w, h] of [['iphone-duo-outer', 1398, 2034], ['iphone-duo-outer', 2034, 1398], ['iphone-duo-inner', 2007, 2853], ['iphone-duo-inner', 2853, 2007]] as const) + expect(checkImage(imageInfo(png(w, h)), k)).toEqual([]); + expect(checkImage(imageInfo(png(1398, 2035)), 'iphone-duo-outer').map(i => i.code)).toEqual(['size']); + expect(checkImage(imageInfo(png(2007, 2853)), 'iphone-duo-outer').map(i => i.code)).toEqual(['size']); + expect(checkImage(imageInfo(png(2007, 2853, { colorType: 6 })), 'iphone-duo-inner').map(i => i.code)).toEqual(['alpha']); + }); + test('upload: no API display type yet, so the sets are skipped with the message', () => { + expect(Object.values(IPHONE_DUO_DISPLAY).every(t => t === null)).toBe(true); + expect(Object.keys(displaySets({ iphoneDuo: true }))).not.toContain('iphone-duo-outer'); + expect(skippedDuoSets({})).toBeNull(); + expect(skippedDuoSets({ iphoneDuo: true })).toEqual({ dirs: ['iphone-duo-outer', 'iphone-duo-inner'], msg: expect.stringContaining(`iphone-duo-outer, iphone-duo-inner: ${IPHONE_DUO_NOT_IN_API}. Add them in App Store Connect > the iOS version page > App Previews and Screenshots > iPhone Duo: https://`) }); + expect(skippedDuoSets({ iphoneDuo: true, appId: '1234567890' })!.msg).toContain('/apps/1234567890/distribution/ios/version/inflight'); + }); + test('check / validate note: info before April 2027, never a blocker; points Play to the tablet sets', () => { + const before = new Date('2026-10-18'), after = new Date('2027-04-02'); + expect(iphoneDuoNote({ apple: true, duo: true })).toBeNull(); + expect(iphoneDuoNote({ apple: false, duo: false })).toBeNull(); + const n = iphoneDuoNote({ apple: true, duo: false, play: true, today: before })!; + expect(n.level).toBe('info'); + expect(n.msg).toContain('optional now, required from April 2027 for iOS 27.1 SDK builds'); + expect(n.msg).toContain('tablet screenshots'); + expect(iphoneDuoNote({ apple: true, duo: false, today: after })!.level).toBe('warn'); + const base = { version: null, build: null, locales: [], expectedLocales: [], requiredDisplayTypes: [], reviewDetail: null, ageRating: null, priceSchedule: true, availability: true, iaps: [], expectedProducts: [], privacyUrl: { url: 'https://example.com/privacy', status: 200 } }; + const f = appleRules({ ...base, today: before } as unknown as Parameters[0]).find(x => x.code === 'screenshots-duo')!; + expect(f.level).toBe('ok'); + expect(appleRules({ ...base, iphoneDuo: true, today: before } as unknown as Parameters[0]).some(x => x.code === 'screenshots-duo')).toBe(false); + }); + test('validate: the medium display class is required; a 6.9" set fills it (scaled down), none is a blocker', () => { + const base = { version: null, build: null, expectedLocales: [], requiredDisplayTypes: ['APP_IPHONE_61'], reviewDetail: null, ageRating: null, priceSchedule: true, availability: true, iaps: [], expectedProducts: [], privacyUrl: { url: 'https://example.com/privacy', status: 200 } }; + const run = (screenshots: Record) => appleRules({ ...base, locales: [{ locale: 'en-US', description: 'd', keywords: 'k', subtitle: 's', screenshots }] } as unknown as Parameters[0]); + expect(run({ APP_IPHONE_67: 5 }).find(x => x.code === 'screenshots-size')!.level).toBe('ok'); + expect(run({}).find(x => x.code === 'screenshots')!.level).toBe('blocker'); + }); +}); diff --git a/tests/specs.test.ts b/tests/specs.test.ts index ad39819..79db3b4 100644 --- a/tests/specs.test.ts +++ b/tests/specs.test.ts @@ -105,8 +105,8 @@ describe('13" iPad', () => { expect(displaySets({})).toEqual(DISPLAY); expect(displaySets(undefined)).toEqual(DISPLAY); expect(Object.keys(displaySets({ ipad: true }))).toEqual(['ios69', 'ios65', 'ipad13']); - expect(requiredDisplayTypes({})).toEqual(['APP_IPHONE_67']); - expect(requiredDisplayTypes({ ipad: true })).toEqual(['APP_IPHONE_67', 'APP_IPAD_PRO_3GEN_129']); + expect(requiredDisplayTypes({})).toEqual(['APP_IPHONE_61']); + expect(requiredDisplayTypes({ ipad: true })).toEqual(['APP_IPHONE_61', 'APP_IPAD_PRO_3GEN_129']); expect(requiredDisplayTypes({ ipad: true, screenshotTypes: ['APP_IPHONE_65'] })).toEqual(['APP_IPHONE_65']); expect(defaultSizes({ apple: { bundleId: 'x' } })).not.toContain('ipad13'); expect(defaultSizes({ apple: { bundleId: 'x', ipad: true } })).toContain('ipad13'); From 14ffe3545ac23f9616f815fd906a96ea49b222be Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 18 Oct 2026 13:07:45 +0700 Subject: [PATCH 022/344] npx / bunx storebound always run the newest version: a copy started from the npx or bunx cache re-runs the command as storebound@ when npm has a newer one (registry asked at most every 10 minutes, 1.5 s timeout; off with STOREBOUND_NO_UPDATE=1, in CI and offline); a project install gets a one-line note instead --- cli/index.ts | 2 ++ cli/lib/self-update.ts | 69 +++++++++++++++++++++++++++++++++++++++ tests/self-update.test.ts | 15 +++++++++ 3 files changed, 86 insertions(+) create mode 100644 cli/lib/self-update.ts create mode 100644 tests/self-update.test.ts diff --git a/cli/index.ts b/cli/index.ts index e5bd789..b6346f4 100755 --- a/cli/index.ts +++ b/cli/index.ts @@ -61,6 +61,8 @@ async function main(): Promise { argv.splice(i, argv[i]!.includes('=') ? 1 : 2); } } + // npx / bunx run a cached copy: start the newest storebound instead (cli/lib/self-update.ts) + { const { runNewest } = await import('./lib/self-update'); await runNewest((await import('../package.json')).version, process.argv.slice(2)); } const [a, b] = argv; if (!a || a === 'help' || a === '--help' || a === '-h') return help(); if (a === 'version' || a === '--version') return console.log((await import('../package.json')).version); diff --git a/cli/lib/self-update.ts b/cli/lib/self-update.ts new file mode 100644 index 0000000..c3e91f9 --- /dev/null +++ b/cli/lib/self-update.ts @@ -0,0 +1,69 @@ +// `npx storebound` / `bunx storebound` always run the newest version: npx and bunx reuse a cached copy without +// asking the registry, so an old storebound kept running after a release. When this copy runs from such a cache and +// npm has a newer version, the same command is started again as `npx -y storebound@` (or bunx) and this one +// exits with its code. A project's own install (node_modules) is never swapped: it gets a one-line note instead. +// Off with STOREBOUND_NO_UPDATE=1, in CI, offline and in tests; the registry is asked at most every 10 minutes. +import { spawn } from 'node:child_process'; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { join } from 'node:path'; + +const CACHE = join(homedir(), '.storebound', 'update-check.json'); +const TTL_MS = 10 * 60_000; + +/** a > b for x.y.z versions (pre-releases are never newer than their release). Pure. */ +export function newer(a: string, b: string): boolean { + const p = (v: string) => v.split('-')[0]!.split('.').map(n => Number(n) || 0); + const [x, y] = [p(a), p(b)]; + for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0); + return !a.includes('-') && b.includes('-'); +} + +/** How this copy was started: an npx / bunx cache (swappable), a project install, or anything else. Pure. */ +export function runner(scriptPath: string): 'npx' | 'bunx' | 'project' | 'other' { + const s = scriptPath.replace(/\\/g, '/'); + if (s.includes('/_npx/')) return 'npx'; + if (s.includes('/.bun/install/cache/') || /\/bunx-[^/]*\//.test(s)) return 'bunx'; + if (s.includes('/node_modules/storebound/')) return 'project'; + return 'other'; +} + +async function latest(): Promise { + try { + const c = JSON.parse(readFileSync(CACHE, 'utf8')) as { at: number; version: string }; + if (Date.now() - c.at < TTL_MS && c.version) return c.version; + } catch { /* no cache */ } + try { + const r = await fetch('https://registry.npmjs.org/storebound/latest', { signal: AbortSignal.timeout(1500), headers: { accept: 'application/json' } }); + if (!r.ok) return null; + const v = ((await r.json()) as { version?: string }).version ?? null; + if (v) { try { mkdirSync(join(homedir(), '.storebound'), { recursive: true }); writeFileSync(CACHE, JSON.stringify({ at: Date.now(), version: v })); } catch { /* read-only home */ } } + return v; + } catch { return null; } +} + +/** Re-runs the command with the newest storebound when this copy is an outdated npx / bunx cache; returns false to + * go on with this copy. Never throws. */ +export async function runNewest(current: string, argv: string[], scriptPath = process.argv[1] ?? ''): Promise { + const env = process.env; + if (env.STOREBOUND_NO_UPDATE === '1' || env.CI || env.STOREBOUND_NO_NETWORK === '1' || env.STOREBOUND_STORE_MOCK) return false; + const how = runner(scriptPath); + if (how === 'other') return false; + const v = await latest(); + if (!v || !newer(v, current)) return false; + if (how === 'project') { + process.stderr.write(`storebound ${v} is out (this project has ${current}): bun add -d storebound@latest, or npx storebound@latest\n`); + return false; + } + process.stderr.write(`storebound ${current} -> ${v} (newest)\n`); + const cmd = how === 'npx' ? ['npx', '-y', `storebound@${v}`] : ['bunx', `storebound@${v}`]; + const code = await new Promise(res => { + const p = spawn(cmd[0]!, [...cmd.slice(1), ...argv], { stdio: 'inherit', env: { ...env, STOREBOUND_NO_UPDATE: '1' }, shell: process.platform === 'win32' }); + p.on('exit', c => res(c ?? 1)); + p.on('error', () => res(-1)); + }); + if (code === -1) return false; // npx / bunx missing: go on with this copy + process.exit(code); +} + +export const cacheFile = (): string | null => (existsSync(CACHE) ? CACHE : null); diff --git a/tests/self-update.test.ts b/tests/self-update.test.ts new file mode 100644 index 0000000..845d40c --- /dev/null +++ b/tests/self-update.test.ts @@ -0,0 +1,15 @@ +import { expect, test } from 'bun:test'; +import { newer, runner } from '../cli/lib/self-update'; + +test('npx / bunx caches are swapped for the newest version, a project install only gets a note', () => { + expect(runner('/Users/you/.npm/_npx/1a2b/node_modules/storebound/dist/storebound.mjs')).toBe('npx'); + expect(runner('C:\\Users\\x\\AppData\\Local\\npm-cache\\_npx\\1a2b\\node_modules\\storebound\\dist\\storebound.mjs')).toBe('npx'); + expect(runner('/Users/you/.bun/install/cache/storebound@0.8.12@@@1/dist/storebound.mjs')).toBe('bunx'); + expect(runner('/Users/you/app/node_modules/storebound/dist/storebound.mjs')).toBe('project'); + expect(runner('/Users/you/storebound/cli/index.ts')).toBe('other'); + expect(newer('0.8.13', '0.8.12')).toBe(true); + expect(newer('0.8.12', '0.8.12')).toBe(false); + expect(newer('0.9.0', '0.8.99')).toBe(true); + expect(newer('0.8.12', '0.8.13')).toBe(false); + expect(newer('0.8.12', '0.8.12-rc.1')).toBe(true); +}); From e5369090fa2afd29a85b2d6948909c33717f337d Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 18 Oct 2026 13:09:38 +0700 Subject: [PATCH 023/344] apple creative-assets: App Store Header and Search Results (PRODUCT_PAGE_HEADER_ASSET, APP_STORE_SEARCH_RESULTS_ASSET) through the App Asset Library: local size / alpha / video checks, upload once by MD5, select only approved assets, replace on a changed file; check / validate note, MCP tool, gallery and desktop Art row, docs, pitfall 75 --- CHANGELOG.md | 9 +- cli/api/wrapped.gen.ts | 8 +- cli/apple/creative-assets.ts | 134 ++++++++++++++++++++++++++++++ cli/check.ts | 3 + cli/commands.ts | 1 + cli/data/flags.json | 6 ++ cli/lib/config.ts | 6 ++ cli/mcp-tools.ts | 3 + cli/shots/creative.ts | 108 ++++++++++++++++++++++++ cli/shots/gallery.ts | 14 +++- cli/validate.ts | 3 + docs/api-coverage.md | 16 ++-- docs/store-art.md | 19 +++++ skills/store-pitfalls/SKILL.md | 14 ++++ skills/store-screenshots/SKILL.md | 19 +++++ tests/creative-assets.test.ts | 126 ++++++++++++++++++++++++++++ tests/helpers/fake-stores.ts | 13 ++- 17 files changed, 486 insertions(+), 16 deletions(-) create mode 100644 cli/apple/creative-assets.ts create mode 100644 cli/shots/creative.ts create mode 100644 tests/creative-assets.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 548a917..db8a60a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,14 @@ (`APP_IPHONE_61`) per locale, met by a 6.9" or 6.5" set that App Store Connect scales down (an ok row, not a warning). Labels match the console: "iPhone with Dynamic Island (medium display)", "iPhone Duo", "iPad 13" display". +- **App Store Header and Search Results.** `storebound apple creative-assets [--dry]` puts a product page header + (3840 x 1646, 21:9) and a search results asset (3:2, 1920 x 1280 to 3840 x 2560), image or video (5-30 s, 30/60 + fps), per locale from `//creative/`, or one universal 5244 x 2950 PNG, into the App Asset Library and + selects them (`PRODUCT_PAGE_HEADER_ASSET`, `APP_STORE_SEARCH_RESULTS_ASSET`) once Apple approved them; MD5 upsert, + read back. Local checks: size, no alpha, video length / fps / container (ffprobe, else skipped with a note). + `check` and `validate` note when there is none (Play: the feature graphic and promo video are the counterparts). + MCP `apple_creative_assets`; config `apple.creativeAssets`; pitfall 76. + ## 0.8.12 · 2026-10-17 - **Shareable readiness report.** `storebound report` puts `scan`, `check` and `validate` into one self-contained HTML @@ -259,7 +267,6 @@ errors are clear messages instead of raw API text. - **One row per release across the stores.** Versions are matched without trailing .0 parts (App Store "1.0" and Play "1.0.0" are one row and one timeline); each side still shows the store's own string. - ## 0.8.1 · 2026-10-13 `apple build` exports each build into its own folder and fails loudly on any export error; `apple upload` refuses a diff --git a/cli/api/wrapped.gen.ts b/cli/api/wrapped.gen.ts index 8668a6f..0a075f2 100644 --- a/cli/api/wrapped.gen.ts +++ b/cli/api/wrapped.gen.ts @@ -7,6 +7,10 @@ export const WRAPPED: { apple: Record; play: Record; play: Record; play: Record//creative/header.{png,jpg,mov,m4v,mp4} (3840x1646, 21:9), +// search.{...} (3:2, 1920x1280 to 3840x2560), or one universal.png (5244x2950) for both slots. apple.creativeAssets +// can turn a placement off (header: false / search: false) or point at another universal file. +// Flow, as App Store Connect works (Header and Search Results tab > Header / Search Results > Browse Assets): a file is +// uploaded once into the app's Asset Library (POST appAssetLibraryImages / Videos, category CREATIVE_ASSETS, its MD5 +// in referenceName "storebound " because library assets carry no checksum), Apple reviews it, and only an +// APPROVED asset is selected for a slot (POST appAssetLibraryPlacements with placementType PRODUCT_PAGE_HEADER_ASSET or +// APP_STORE_SEARCH_RESULTS_ASSET and the version localization). Upsert: a slot that already shows the same MD5 is left +// alone; a new file replaces the slot only once it is approved (the old placement is removed, then the new one is +// created); an asset with the same MD5 already in the library is reused, never uploaded twice. Read back at the end. +// Play has no such slot: the feature graphic (play images) and the promo video URL are its closest equivalents. +import { readFileSync } from 'node:fs'; +import { basename } from 'node:path'; +import type { Ctx } from '../lib/ctx'; +import { need } from '../lib/ctx'; +import { done, log, warn } from '../lib/log'; +import { ffprobe } from '../shots/report'; +import { imageInfo } from '../shots/spec'; +import { checkCreativeImage, checkCreativeVideo, type CreativeFile, creativeFiles, PLACEMENT_TYPE, type Placement } from '../shots/creative'; +import { ascClient, md5, type J } from './asc'; + +export const REF = (sum: string): string => `storebound ${sum}`; +const sumOf = (a: J): string | undefined => /^storebound ([0-9a-f]{32})$/.exec(String(a?.attributes?.referenceName ?? ''))?.[1]; + +export interface Row { locale: string; placement: Placement; file: string; action: 'keep' | 'upload' | 'wait' | 'select' | 'replace'; state?: string } + +/** Local files per App Store locale, checked; throws on any error before a network call. */ +export function localCreative(ctx: Ctx): { src: string; local: Map } { + const { config, resolve } = ctx.loaded; + const a = ctx.args; + const src = resolve(a.get('src') ?? config.renders ?? config.shots?.out ?? 'store/renders'); + const only = a.list('only'); + const ca = config.apple?.creativeAssets ?? {}; + const local = new Map(); + let bad = 0; + for (const l of config.languages) { + if (!l.apple || (only.length && !only.includes(l.apple))) continue; + let fs = creativeFiles(src, l.id); + if (ca.universal && !fs.length) fs = (['header', 'search'] as Placement[]).map(p => ({ placement: p, file: resolve(ca.universal!), kind: 'image' as const, universal: true })); + fs = fs.filter(f => ca[f.placement] !== false); + for (const f of fs) { + const issues = f.kind === 'image' ? checkCreativeImage(imageInfo(readFileSync(f.file)), f.placement, f.universal) : checkCreativeVideo(f.file, ffprobe(f.file), f.placement); + for (const i of issues) (i.level === 'error' ? warn : log)('apple', `${l.apple} ${f.placement} ${basename(f.file)}: ${i.msg}`); + if (issues.some(i => i.level === 'error')) bad++; + } + if (fs.length) local.set(l.apple, fs); + } + if (bad) throw new Error(`${bad} creative asset problems: fix them first (sizes in docs/store-art.md)`); + return { src, local }; +} + +export async function run(ctx: Ctx): Promise { + const { config, root } = ctx.loaded; + const dry = ctx.args.has('dry'); + const bundleId = need(config.apple?.bundleId, 'apple.bundleId'); + const { src, local } = localCreative(ctx); + if (!local.size) { warn('apple', `no creative assets in ${src}//creative/ (header.png 3840x1646, search.png 3:2, or universal.png 5244x2950): optional; without them the App Store uses events, previews and screenshots`); return; } + log('apple', `${[...local.values()].flat().length} creative assets for ${local.size} locales pass the checks`); + + let c: Awaited>; + try { c = await ascClient(root, bundleId, config.apple?.appId); } + catch (e) { + if (!dry) throw e; + for (const [loc, fs] of local) for (const f of fs) log('apple', `${loc} ${PLACEMENT_TYPE[f.placement]}: would upload ${basename(f.file)} to the Asset Library and select it once approved`); + return done('apple', `creative assets planned (dry run, no App Store Connect comparison: ${(e as Error).message.split('\n')[0]})`); + } + const lib = (await c.asc('GET', `/v1/apps/${await c.app()}/assetLibrary`)).data as J; + const version = await c.editableVersion(); + if (!version) throw new Error('no editable App Store version (run apple listing --version x.y.z first)'); + const locs = await c.all(`/v1/appStoreVersions/${version.id}/appStoreVersionLocalizations?limit=50`); + const library = async (): Promise => [ + ...(await c.all(`/v1/appAssetLibraries/${lib.id}/images?filter[category]=CREATIVE_ASSETS&limit=200`)), + ...(await c.all(`/v1/appAssetLibraries/${lib.id}/videos?filter[category]=CREATIVE_ASSETS&limit=200`)), + ]; + let assets = await library(); + const bySum = (s: string) => assets.filter(x => sumOf(x) === s && x.attributes?.state !== 'ARCHIVED' && x.attributes?.state !== 'FAILED' && x.attributes?.state !== 'REJECTED')[0]; + const rows: Row[] = []; + + async function upload(f: CreativeFile, sum: string): Promise { + const buf = readFileSync(f.file); + const type = f.kind === 'image' ? 'appAssetLibraryImages' : 'appAssetLibraryVideos'; + const res = (await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { fileName: basename(f.file), fileSize: buf.length, category: 'CREATIVE_ASSETS', referenceName: REF(sum) }, + relationships: { assetLibrary: { data: { type: 'appAssetLibraries', id: lib.id } } } } })).data as J; + for (const op of (res.attributes.uploadOperations ?? []) as J[]) { + const headers: Record = {}; + for (const h of op.requestHeaders ?? []) headers[h.name] = h.value; + const r = await fetch(op.url, { method: op.method, headers, body: buf.subarray(op.offset, op.offset + op.length) }); + if (!r.ok) throw new Error(`upload ${basename(f.file)} part ${op.offset} -> ${r.status}`); + } + return (await c.asc('PATCH', `/v1/${type}/${res.id}`, { data: { type, id: res.id, attributes: { uploaded: true } } })).data as J; + } + + for (const loc of locs) { + const locale: string = loc.attributes.locale; + for (const f of local.get(locale) ?? []) { + const ptype = PLACEMENT_TYPE[f.placement]; + const tag = `${locale} ${ptype}`; + const sum = md5(readFileSync(f.file)); + const placed = await c.all(`/v1/appStoreVersionLocalizations/${loc.id}/placements?filter[placementType]=${ptype}&include=image,video`); + const shownIds = placed.map(p => p.relationships?.image?.data?.id ?? p.relationships?.video?.data?.id).filter(Boolean); + if (placed.length === 1 && assets.some(x => shownIds.includes(x.id) && sumOf(x) === sum)) { log('apple', `${tag}: ${basename(f.file)} already selected`); rows.push({ locale, placement: f.placement, file: f.file, action: 'keep' }); continue; } + let asset = bySum(sum); + if (!asset) { + if (dry) { log('apple', `${tag}: would upload ${basename(f.file)} to the Asset Library (Apple approves it, then it is selected)`); rows.push({ locale, placement: f.placement, file: f.file, action: 'upload' }); continue; } + log('apple', `${tag}: uploading ${basename(f.file)} to the Asset Library`); + asset = await upload(f, sum); + assets = await library(); + asset = bySum(sum) ?? asset; + } + const state = String(asset.attributes?.state ?? ''); + if (state !== 'APPROVED') { log('apple', `${tag}: ${basename(f.file)} waiting for Apple's approval (${state || 'processing'}); re-run once it is approved to select it`); rows.push({ locale, placement: f.placement, file: f.file, action: 'wait', state }); continue; } + const action = placed.length ? 'replace' : 'select'; + if (dry) { log('apple', `${tag}: would ${action === 'replace' ? `replace ${placed.length} selected asset(s) with` : 'select'} ${basename(f.file)}`); rows.push({ locale, placement: f.placement, file: f.file, action }); continue; } + for (const p of placed) await c.asc('DELETE', `/v1/appAssetLibraryPlacements/${p.id}`); + const media = f.kind === 'image' ? 'image' : 'video'; + await c.asc('POST', '/v1/appAssetLibraryPlacements', { data: { type: 'appAssetLibraryPlacements', attributes: { placementType: ptype }, + relationships: { [media]: { data: { type: asset.type, id: asset.id } }, appStoreVersionLocalization: { data: { type: 'appStoreVersionLocalizations', id: loc.id } } } } }); + log('apple', `${tag}: selected ${basename(f.file)}`); + rows.push({ locale, placement: f.placement, file: f.file, action }); + } + } + if (dry) return done('apple', 'creative assets checked (dry run, nothing sent)'); + // read back + let off = 0; + for (const r of rows.filter(r => r.action === 'select' || r.action === 'replace')) { + const loc = locs.find(l => l.attributes.locale === r.locale)!; + const now = await c.all(`/v1/appStoreVersionLocalizations/${loc.id}/placements?filter[placementType]=${PLACEMENT_TYPE[r.placement]}`); + if (now.length !== 1) { off++; warn('apple', `${r.locale} ${PLACEMENT_TYPE[r.placement]}: read back ${now.length} selected assets, wanted 1`); } + } + const waiting = rows.filter(r => r.action === 'wait').length; + done('apple', `creative assets: ${rows.filter(r => r.action === 'keep').length} up to date, ${rows.filter(r => r.action === 'select' || r.action === 'replace').length} selected, ${waiting} waiting for approval${off ? `, ${off} did not read back` : ''}`); +} diff --git a/cli/check.ts b/cli/check.ts index 3aa9f70..288b830 100644 --- a/cli/check.ts +++ b/cli/check.ts @@ -29,6 +29,7 @@ import { reviewShotProblem } from './apple/iap-review'; import { allSubscriptions } from './lib/subscriptions'; import { type CopyFile, validateCopy } from './shots/lib'; import { posix, readPulled } from './lib/art-pull'; +import { creativeNote } from './shots/creative'; import { type CapProject, capacitorProject, prebuildFor, staleMessage, webState } from './lib/web-assets'; import { iphoneDuoNote } from './shots/spec'; @@ -149,6 +150,8 @@ export async function run(ctx: Ctx): Promise { if (config.apple && !config.app.copyright?.trim()) problems.push(COPYRIGHT_MISSING); const duo = iphoneDuoNote({ apple: !!config.apple, duo: !!config.apple?.iphoneDuo, play: !!config.play }); if (duo?.level === 'info') { hints.push(duo.msg); log('check', `hint: ${duo.msg}`); } else if (duo) note(duo.msg); + const creative = creativeNote(config, ctx.loaded.resolve(config.renders ?? config.shots?.out ?? 'store/renders')); + if (creative) { hints.push(creative); log('check', `hint: ${creative}`); } // the scaffolder's own placeholders would reach the stores as the app's copyright, contact and legal pages const tph = templatePlaceholders(config as never); if (tph.length) problems.push(`template placeholders still in the config: ${tph.join(', ')} ("Example Studio", example.com): the stores would show them as your copyright, contact address and legal pages; put the real values in`); diff --git a/cli/commands.ts b/cli/commands.ts index 151c217..fd850b1 100644 --- a/cli/commands.ts +++ b/cli/commands.ts @@ -80,6 +80,7 @@ export const COMMANDS: Record Promise, string]> = { 'apple appinfo': [() => import('./apple/appinfo'), 'categories, age rating, content rights, Free price, territories'], 'apple review-details': [() => import('./apple/review-details'), 'App Review contact, demo account (from .storebound/, masked) + notes'], 'apple status': [() => import('./apple/status'), 'versions, builds, IAPs, review submissions (--wait-review, --cancel-submission )'], + 'apple creative-assets': [() => import('./apple/creative-assets'), 'Header and Search Results: product page header (21:9) and search results asset (3:2) per locale, or one universal 5244x2950 PNG; uploads to the Asset Library, selects once Apple approved it (MD5 upsert); --dry'], 'apple previews': [() => import('./apple/previews'), 'app preview videos per locale (MD5-idempotent, poster frame time code); --dry'], 'apple release': [() => import('./apple/release'), 'phased release on|pause|resume|complete, --manual-release (asks first)'], 'apple signing': [() => import('./apple/signing'), 'status | ensure: bundle id capabilities, distribution certificate (key kept in .storebound/signing), App Store profiles installed for Xcode; --dry, asks first'], diff --git a/cli/data/flags.json b/cli/data/flags.json index 467de14..370e4cf 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -87,6 +87,9 @@ "variant", "write" ], + "apple creative-assets": [ + "src" + ], "apple encryption": [ "build" ], @@ -1175,6 +1178,9 @@ "storebound apple cpp submit --name \"...\" [--dry] [--yes] into a review submission (the owner's step; asks)", "storebound apple cpp visible --name \"...\" [--off] [--dry] [--yes] show / hide an approved page (asks)" ], + "apple creative-assets": [ + "storebound apple creative-assets [--src store/renders] [--only en-US,tr] [--dry]" + ], "apple encryption": [ "storebound apple encryption [--build 42] [--dry]" ], diff --git a/cli/lib/config.ts b/cli/lib/config.ts index f64bb93..152d025 100644 --- a/cli/lib/config.ts +++ b/cli/lib/config.ts @@ -626,6 +626,12 @@ export interface ShipConfig { * Optional now, reportedly required from April 2027 for iOS 27.1 SDK builds. Not uploaded while the API has no * display type for them (cli/shots/spec.ts IPHONE_DUO_DISPLAY). */ iphoneDuo?: boolean; + /** "Header and Search Results" creative assets (`storebound apple creative-assets`, iOS / iPadOS 27+). Files under + * //creative/: header.{png,jpg,mov,m4v,mp4} (3840x1646, 21:9), search.{...} (3:2, 1920x1280 to + * 3840x2560) or universal.png (5244x2950) for both. `header` / `search` false skip that slot; `universal` is a + * universal PNG for every locale without own files. Optional: without them the App Store uses events, previews and + * screenshots. Play: the feature graphic and the promo video are the closest equivalents. */ + creativeAssets?: { header?: boolean; search?: boolean; universal?: string }; /** TestFlight beta groups, the tester CSV (in .storebound/) and Test Information (`storebound apple testflight`). */ testflight?: TfConfig; /** Certificates, profiles and capabilities through the API (`storebound apple signing`), signing style of `apple build`. */ diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index 67c90f4..4d6606f 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -245,6 +245,9 @@ export const TOOLS: ToolDef[] = [ props: { lang, target: { type: 'string', description: 'Comma-separated: iphone, ipad, youtube, youtube-landscape' }, seconds: { type: 'integer', minimum: 15, maximum: 30 }, captions: { type: 'boolean', default: true } }, args: i => [...opt('lang', i.lang), ...opt('target', i.target), ...opt('seconds', i.seconds), ...(i.captions === false ? ['--no-captions'] : [])] }, + { name: 'apple_creative_assets', title: 'App Store header and search results assets', command: ['apple', 'creative-assets'], write: true, destructive: true, network: true, idempotent: true, + description: 'Header and Search Results (iOS / iPadOS 27+): checks //creative/ (header 3840x1646, search 3:2, universal 5244x2950 PNG; no alpha; videos 5-30 s, 30/60 fps), uploads new files to the App Asset Library, and selects an asset for PRODUCT_PAGE_HEADER_ASSET / APP_STORE_SEARCH_RESULTS_ASSET only once Apple approved it (MD5 upsert, same file = nothing sent). Play counterpart: feature graphic + promo video.', + props: { only }, args: i => opt('only', i.only) }, { name: 'apple_previews', title: 'Upload App Store app previews', command: ['apple', 'previews'], write: true, destructive: true, network: true, idempotent: true, description: 'Sync app preview videos per locale to the editable App Store version (checked locally first; MD5-idempotent, changed sets are replaced; poster frame time code). Not public until the version is submitted and released. Slow: prefer the terminal with a log.', props: { only, poster: { type: 'integer', minimum: 0, maximum: 29, description: 'Poster frame second (default shots.video.poster or 5)' } }, diff --git a/cli/shots/creative.ts b/cli/shots/creative.ts new file mode 100644 index 0000000..d5828d6 --- /dev/null +++ b/cli/shots/creative.ts @@ -0,0 +1,108 @@ +// App Store creative assets for "Header and Search Results" (App Store Connect, since 5 Oct 2026, shown on iOS / iPadOS +// 27+): the product page header (21:9) and the search results asset (3:2), image or video, per locale, with one +// universal 16:9 image (5244 x 2950) that can fill either slot. Apple's Creative assets specifications: +// https://developer.apple.com/help/app-store-connect/reference/app-information/creative-assets-specifications/ +// Files: //creative/{header,search}.{png,jpg,jpeg,mov,m4v,mp4}; universal fallback +// //creative/universal.png or /creative/universal.png (every locale). +// API: App Asset Library (placement types PRODUCT_PAGE_HEADER_ASSET and APP_STORE_SEARCH_RESULTS_ASSET); see +// cli/apple/creative-assets.ts. Play has no such slot: the feature graphic (1024 x 500) and the promo video are its +// closest equivalents. +import { existsSync, readdirSync } from 'node:fs'; +import { join } from 'node:path'; +import type { ImageInfo, Issue, ProbeInfo } from './spec'; + +export type Placement = 'header' | 'search'; +export const PLACEMENT_TYPE: Record = { header: 'PRODUCT_PAGE_HEADER_ASSET', search: 'APP_STORE_SEARCH_RESULTS_ASSET' }; +export const PLACEMENT_LABEL: Record = { header: 'product page header (21:9)', search: 'search results asset (3:2)' }; + +export const CREATIVE_RULES = { + header: { w: 3840, h: 1646, ratio: 21 / 9 }, + search: { minW: 1920, minH: 1280, maxW: 3840, maxH: 2560, ratio: 3 / 2 }, + universal: { w: 5244, h: 2950 }, + video: { minSec: 5, maxSec: 30, fps: [30, 60], ext: /\.(mov|m4v|mp4)$/i }, +} as const; + +export const CREATIVE_NOTE = 'App Store "Header and Search Results" (iOS / iPadOS 27+) has no header or search results asset: optional; without it the App Store uses in-app events, app previews and screenshots (storebound apple creative-assets; Play: the feature graphic 1024x500 and the promo video are the closest equivalents)'; + +export interface CreativeFile { placement: Placement; file: string; kind: 'image' | 'video'; universal: boolean } + +const EXT = /\.(png|jpe?g|mov|m4v|mp4)$/i; +const kindOf = (f: string): 'image' | 'video' => (CREATIVE_RULES.video.ext.test(f) ? 'video' : 'image'); + +/** The file for each placement of one language: own header / search file first, else the universal image. */ +export function creativeFiles(renders: string, lang: string, list: (d: string) => string[] = d => (existsSync(d) ? readdirSync(d) : [])): CreativeFile[] { + const dir = join(renders, lang, 'creative'); + const own = list(dir).filter(f => EXT.test(f)).sort(); + const uni = own.find(f => /^universal\.png$/i.test(f)) ? join(dir, own.find(f => /^universal\.png$/i.test(f))!) + : list(join(renders, 'creative')).some(f => f === 'universal.png') ? join(renders, 'creative', 'universal.png') : undefined; + const out: CreativeFile[] = []; + for (const p of ['header', 'search'] as Placement[]) { + const f = own.find(x => x.toLowerCase().startsWith(`${p}.`)); + if (f) out.push({ placement: p, file: join(dir, f), kind: kindOf(f), universal: false }); + else if (uni) out.push({ placement: p, file: uni, kind: 'image', universal: true }); + } + return out; +} + +const close = (a: number, b: number) => Math.abs(a - b) / b < 0.01; + +/** Problems with a creative image (JPEG / PNG, no alpha, size per placement or the universal 5244 x 2950). */ +export function checkCreativeImage(info: ImageInfo, placement: Placement, universal = false): Issue[] { + const out: Issue[] = []; + if (info.format === 'unknown') return [{ level: 'error', code: 'format', msg: 'not a PNG or JPEG' }]; + if (info.alpha) out.push({ level: 'error', code: 'alpha', msg: 'has an alpha channel / transparency (Apple rejects it): flatten to RGB' }); + const { w, h } = info; + if (universal) { + if (info.format !== 'png') out.push({ level: 'error', code: 'format', msg: 'the universal asset is a PNG' }); + if (w !== CREATIVE_RULES.universal.w || h !== CREATIVE_RULES.universal.h) out.push({ level: 'error', code: 'size', msg: `${w}x${h}, the universal asset is 5244x2950 (16:9)` }); + } else if (placement === 'header') { + if (w !== CREATIVE_RULES.header.w || h !== CREATIVE_RULES.header.h) out.push({ level: 'error', code: 'size', msg: `${w}x${h}, the product page header is 3840x1646 (21:9)` }); + } else { + const s = CREATIVE_RULES.search; + if (w < s.minW || h < s.minH || w > s.maxW || h > s.maxH || w * 2 !== h * 3) out.push({ level: 'error', code: 'size', msg: `${w}x${h}, the search results asset is 3:2 from 1920x1280 to 3840x2560` }); + } + return out; +} + +/** Problems with a creative video (5-30 s, 30 or 60 fps, .mov / .m4v / .mp4, the placement's aspect ratio). */ +export function checkCreativeVideo(file: string, p: ProbeInfo | null, placement: Placement): Issue[] { + const out: Issue[] = []; + const err = (msg: string) => out.push({ level: 'error', code: 'video', msg }); + if (!CREATIVE_RULES.video.ext.test(file)) err('container: .mov, .m4v or .mp4'); + if (!p) return [...out, { level: 'warn', code: 'video', msg: 'length, frame rate and size not checked (ffprobe missing: brew install ffmpeg)' }]; + if (!p.video) { err('no video stream'); return out; } + const ratio = placement === 'header' ? CREATIVE_RULES.header.ratio : CREATIVE_RULES.search.ratio; + if (!close(p.video.w / p.video.h, ratio)) err(`${p.video.w}x${p.video.h}, the ${PLACEMENT_LABEL[placement]} video has the same aspect ratio as the image`); + if (p.duration < CREATIVE_RULES.video.minSec - 0.05 || p.duration > CREATIVE_RULES.video.maxSec + 0.05) err(`${p.duration.toFixed(1)} s, creative videos are 5-30 s`); + if (!CREATIVE_RULES.video.fps.some(f => Math.abs(p.video!.fps - f) < 0.05)) err(`${p.video.fps.toFixed(2)} fps, creative videos are 30 or 60 fps`); + if (placement === 'search' && p.audio) out.push({ level: 'warn', code: 'video', msg: 'has an audio track: search results videos play muted' }); + return out; +} + +/** check / validate: the info note when an App Store app has no header or search results asset in any locale. */ +export function creativeNote(config: { apple?: { creativeAssets?: { header?: boolean; search?: boolean; universal?: string } }; languages: { id: string; apple?: string }[] }, renders: string, + list?: (d: string) => string[]): string | null { + if (!config.apple) return null; + const ca = config.apple.creativeAssets ?? {}; + if (ca.header === false && ca.search === false) return null; + if (ca.universal) return null; + const has = config.languages.filter(l => l.apple).some(l => creativeFiles(renders, l.id, list).length); + return has ? null : CREATIVE_NOTE; +} + +/** Gallery / desktop Art rows: one "creative" row per language with its header / search files and their issues. */ +export function creativeRows(renders: string, langs: string[], rel: (f: string) => string, probe: (f: string) => ProbeInfo | null, + read: (f: string) => Uint8Array, info: (b: Uint8Array) => ImageInfo): Map { + const out = new Map extends Map ? V : never>(); + for (const lang of langs) { + const fs = creativeFiles(renders, lang); + if (!fs.length) continue; + const tiles = fs.map(f => { + if (f.kind === 'image') { const i = info(read(f.file)); return { src: rel(f.file), kind: 'image' as const, name: `${f.placement}: ${f.file.split(/[\\/]/).pop()}`, w: i.w, h: i.h, bytes: i.bytes, issues: checkCreativeImage(i, f.placement, f.universal) }; } + const p = probe(f.file); + return { src: rel(f.file), kind: 'video' as const, name: `${f.placement}: ${f.file.split(/[\\/]/).pop()}`, w: p?.video?.w ?? 0, h: p?.video?.h ?? 0, bytes: p?.bytes ?? 0, issues: checkCreativeVideo(f.file, p, f.placement) }; + }); + out.set(lang, { size: 'creative', label: 'App Store header and search results', store: 'apple', tiles, issues: [] }); + } + return out; +} diff --git a/cli/shots/gallery.ts b/cli/shots/gallery.ts index b476179..d94044f 100644 --- a/cli/shots/gallery.ts +++ b/cli/shots/gallery.ts @@ -6,13 +6,14 @@ // `shots check`: size, alpha, bytes, counts, text overflow from report.json, video rules) are outlined in red (error) // or amber (warning) with the message under the tile. Images are linked by relative path, so the page stays small and // always shows the current files; move it together with the renders folder. -import { existsSync, writeFileSync } from 'node:fs'; +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; import { join, relative } from 'node:path'; import type { Ctx } from '../lib/ctx'; import { done, log, printJson, warn } from '../lib/log'; import { SIZES } from './lib'; -import { allIssues, requiredSets, type RendersScan, resolvedTablets, scanRenders } from './report'; -import { type Issue, IMAGE_SPECS, VIDEO_TARGETS } from './spec'; +import { allIssues, ffprobe, requiredSets, type RendersScan, resolvedTablets, scanRenders } from './report'; +import { type Issue, IMAGE_SPECS, imageInfo, VIDEO_TARGETS } from './spec'; +import { creativeRows } from './creative'; export interface GalleryTile { /** Path relative to the gallery file. */ @@ -245,6 +246,13 @@ export async function run(ctx: Ctx): Promise { const scan = scanRenders(dir, { langs, variants, required: lang => requiredSets(config, lang, tablets) }); if (!scan.images.length && !scan.videos.length) warn('shots', `no renders in ${dir} (storebound shots render)`); const data = galleryData(scan, { at: join(out, '..'), title: `${config.app.name} · store renders`, exists: existsSync }); + // App Store Header and Search Results assets (/creative/), base variant only + if (config.apple) for (const [lang, row] of creativeRows(dir, langs, f => relative(join(out, '..'), f).split('\\').join('/'), ffprobe, f => readFileSync(f), imageInfo)) { + const base = data.variants[0]!; + let l = base.langs.find(x => x.lang === lang); + if (!l) base.langs.push(l = { lang, rows: [] }); + l.rows.push(row); + } // --json: the data only (the desktop gallery), with the renders folder relative to the app folder; writes nothing if (a.has('json')) { printJson({ ...data, dir: relative(ctx.loaded.root, dir).split('\\').join('/') || '.' }); return; } if (a.has('dry')) { log('shots', `would write ${out}: ${data.totals.images} images, ${data.totals.videos} videos, ${data.totals.errors} errors`); return; } diff --git a/cli/validate.ts b/cli/validate.ts index b3843c3..72aa93c 100644 --- a/cli/validate.ts +++ b/cli/validate.ts @@ -33,6 +33,7 @@ import { runScan } from './lib/scan'; import type { ScanFinding } from './lib/scan/rules'; import { playClient } from './play/client'; import { listOneTimeProducts } from './play/products'; +import { creativeNote } from './shots/creative'; /** Profile facts for the checks: config + local credentials + public URL checks (no store API). */ export async function collectProfile(loaded: Loaded): Promise { @@ -196,6 +197,8 @@ export async function run(ctx: Ctx): Promise { if ((both || a.has('apple')) && config.apple) { try { findings.push(...appleRules({ ...(await collectApple(ctx)), renders: local?.apple })); } catch (e) { findings.push({ store: 'apple', level: 'blocker', code: 'api', msg: (e as Error).message.slice(0, 400) }, ...rendersFindings('apple', local?.apple)); } + const creative = creativeNote(config, dir); + if (creative) findings.push({ store: 'apple', level: 'ok', code: 'creative-assets', msg: creative, fix: 'storebound apple creative-assets --dry' }); } else if (a.has('apple')) warn('validate', 'no apple section in the config'); if ((both || a.has('play')) && config.play) { try { findings.push(...playRules({ ...(await collectPlay(ctx)), renders: local?.play })); } diff --git a/docs/api-coverage.md b/docs/api-coverage.md index ca7c1b5..664f363 100644 --- a/docs/api-coverage.md +++ b/docs/api-coverage.md @@ -12,7 +12,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | API | operations | GET | other | wrapped by a command | owner only | |---|---:|---:|---:|---:|---:| -| App Store Connect API 4.5.1 | 1303 | 826 | 477 | 204 | 166 | +| App Store Connect API 4.5.1 | 1303 | 826 | 477 | 210 | 166 | | Google Play Android Developer API v3 (revision 20261008) | 145 | 45 | 100 | 35 | 49 | | Google Play Developer Reporting API v1beta1 (revision 20261008) | 25 | 15 | 10 | 6 | 0 | @@ -80,9 +80,9 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | `androidToIosAppMappingDetails_updateInstance` | PATCH | `/v1/androidToIosAppMappingDetails/{id}` | write (dry by default) | | | **appAssetLibraries** (5) | | | | | | `appAssetLibraries_getInstance` | GET | `/v1/appAssetLibraries/{id}` | read | | -| `appAssetLibraries_images_getToManyRelated` | GET | `/v1/appAssetLibraries/{id}/images` | read | | +| `appAssetLibraries_images_getToManyRelated` | GET | `/v1/appAssetLibraries/{id}/images` | read | apple/creative-assets | | `appAssetLibraries_images_getToManyRelationship` | GET | `/v1/appAssetLibraries/{id}/relationships/images` | read | | -| `appAssetLibraries_videos_getToManyRelated` | GET | `/v1/appAssetLibraries/{id}/videos` | read | | +| `appAssetLibraries_videos_getToManyRelated` | GET | `/v1/appAssetLibraries/{id}/videos` | read | apple/creative-assets | | `appAssetLibraries_videos_getToManyRelationship` | GET | `/v1/appAssetLibraries/{id}/relationships/videos` | read | | | **appAssetLibraryImages** (6) | | | | | | `appAssetLibraryImages_createInstance` | POST | `/v1/appAssetLibraryImages` | write (dry by default) | | @@ -94,8 +94,8 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | **appAssetLibraryPlacementOrderingRequests** (1) | | | | | | `appAssetLibraryPlacementOrderingRequests_createInstance` | POST | `/v1/appAssetLibraryPlacementOrderingRequests` | write (dry by default) | | | **appAssetLibraryPlacements** (3) | | | | | -| `appAssetLibraryPlacements_createInstance` | POST | `/v1/appAssetLibraryPlacements` | write (dry by default) | | -| `appAssetLibraryPlacements_deleteInstance` | DELETE | `/v1/appAssetLibraryPlacements/{id}` | owner only (typed confirm) | | +| `appAssetLibraryPlacements_createInstance` | POST | `/v1/appAssetLibraryPlacements` | write (dry by default) | apple/creative-assets | +| `appAssetLibraryPlacements_deleteInstance` | DELETE | `/v1/appAssetLibraryPlacements/{id}` | owner only (typed confirm) | apple/creative-assets | | `appAssetLibraryPlacements_getInstance` | GET | `/v1/appAssetLibraryPlacements/{id}` | read | | | **appAssetLibraryRefData** (2) | | | | | | `appAssetLibraryRefData_getCollection` | GET | `/v1/appAssetLibraryRefData` | read | | @@ -342,7 +342,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | `appStoreVersionLocalizations_createInstance` | POST | `/v1/appStoreVersionLocalizations` | write (dry by default) | listing-store | | `appStoreVersionLocalizations_deleteInstance` | DELETE | `/v1/appStoreVersionLocalizations/{id}` | owner only (typed confirm) | | | `appStoreVersionLocalizations_getInstance` | GET | `/v1/appStoreVersionLocalizations/{id}` | read | | -| `appStoreVersionLocalizations_placements_getToManyRelated` | GET | `/v1/appStoreVersionLocalizations/{id}/placements` | read | | +| `appStoreVersionLocalizations_placements_getToManyRelated` | GET | `/v1/appStoreVersionLocalizations/{id}/placements` | read | apple/creative-assets | | `appStoreVersionLocalizations_placements_getToManyRelationship` | GET | `/v1/appStoreVersionLocalizations/{id}/relationships/placements` | read | | | `appStoreVersionLocalizations_searchKeywords_createToManyRelationship` | POST | `/v1/appStoreVersionLocalizations/{id}/relationships/searchKeywords` | write (dry by default) | | | `appStoreVersionLocalizations_searchKeywords_deleteToManyRelationship` | DELETE | `/v1/appStoreVersionLocalizations/{id}/relationships/searchKeywords` | owner only (typed confirm) | | @@ -371,7 +371,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | `appStoreVersions_appStoreVersionExperimentsV2_getToManyRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/appStoreVersionExperimentsV2` | read | | | `appStoreVersions_appStoreVersionExperiments_getToManyRelated` | GET | `/v1/appStoreVersions/{id}/appStoreVersionExperiments` | read | | | `appStoreVersions_appStoreVersionExperiments_getToManyRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/appStoreVersionExperiments` | read | | -| `appStoreVersions_appStoreVersionLocalizations_getToManyRelated` | GET | `/v1/appStoreVersions/{id}/appStoreVersionLocalizations` | read | apple/listing, apple/previews, apple/screenshots, art, listing-store, onboard, validate | +| `appStoreVersions_appStoreVersionLocalizations_getToManyRelated` | GET | `/v1/appStoreVersions/{id}/appStoreVersionLocalizations` | read | apple/creative-assets, apple/listing, apple/previews, apple/screenshots, art, listing-store, onboard, validate | | `appStoreVersions_appStoreVersionLocalizations_getToManyRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/appStoreVersionLocalizations` | read | | | `appStoreVersions_appStoreVersionPhasedRelease_getToOneRelated` | GET | `/v1/appStoreVersions/{id}/appStoreVersionPhasedRelease` | read | apple/release, apple/status | | `appStoreVersions_appStoreVersionPhasedRelease_getToOneRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/appStoreVersionPhasedRelease` | read | | @@ -425,7 +425,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | `apps_appStoreVersions_getToManyRelationship` | GET | `/v1/apps/{id}/relationships/appStoreVersions` | read | | | `apps_appTags_getToManyRelated` | GET | `/v1/apps/{id}/appTags` | read | | | `apps_appTags_getToManyRelationship` | GET | `/v1/apps/{id}/relationships/appTags` | read | | -| `apps_assetLibrary_getToOneRelated` | GET | `/v1/apps/{id}/assetLibrary` | read | | +| `apps_assetLibrary_getToOneRelated` | GET | `/v1/apps/{id}/assetLibrary` | read | apple/creative-assets | | `apps_assetLibrary_getToOneRelationship` | GET | `/v1/apps/{id}/relationships/assetLibrary` | read | | | `apps_backgroundAssets_getToManyRelated` | GET | `/v1/apps/{id}/backgroundAssets` | read | | | `apps_backgroundAssets_getToManyRelationship` | GET | `/v1/apps/{id}/relationships/backgroundAssets` | read | | diff --git a/docs/store-art.md b/docs/store-art.md index a9b2567..bafe71d 100644 --- a/docs/store-art.md +++ b/docs/store-art.md @@ -87,3 +87,22 @@ skills. --- [All docs](README.md) · [README](../README.md) + +## Header and Search Results (App Store creative assets, iOS / iPadOS 27+) +Since 5 Oct 2026 the App Store version page has a "Header and Search Results" tab next to "App Previews and +Screenshots". Optional: without these assets the App Store uses in-app events, app previews and screenshots. +- **Files** under the renders folder, per language: `//creative/header.png` (3840 x 1646, 21:9), + `search.png` (3:2, 1920 x 1280 up to 3840 x 2560), or one `universal.png` (5244 x 2950, 16:9) that fills either slot + (also `/creative/universal.png` for every locale, or `apple.creativeAssets.universal`). JPEG / PNG without + alpha. Videos instead: `header.mov|m4v|mp4` / `search.*`, 5-30 s, 30 or 60 fps, the same aspect ratio; search videos + play muted. `apple.creativeAssets.header: false` / `search: false` skips a slot. +- **Not rendered by `shots render`**: the scene templates are portrait device shots; make the wide art yourself (or from + the feature graphic artwork at the larger size) and drop it in. +- **Upload:** `storebound apple creative-assets --dry`, then without `--dry`. Files go into the app's Asset Library + (API: `appAssetLibraryImages` / `appAssetLibraryVideos`, category `CREATIVE_ASSETS`); Apple reviews each asset, and + only an approved one is selected for the slot (`appAssetLibraryPlacements`, `PRODUCT_PAGE_HEADER_ASSET` / + `APP_STORE_SEARCH_RESULTS_ASSET`). Until then the run says "waiting for Apple's approval": re-run later. Same file + (MD5) = nothing sent. MCP: `apple_creative_assets` (dry by default). +- **Checks:** `storebound check` and `validate` print an info note when no locale has one. +- **Play:** no such slot. The feature graphic (1024 x 500, `play images`) and the promo video (YouTube URL) are the + closest equivalents. diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 236b1a8..0479986 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -911,3 +911,17 @@ that fails without the fix (see CONTRIBUTING.md). - **Guard:** `IPHONE_DUO_DISPLAY` in `cli/shots/spec.ts` (null = not in the API; regenerate with `bun tools/gen-api.ts` and fill in the exact names), `skippedDuoSets` in `cli/apple/screenshots.ts`, the `screenshots-duo` note in check / validate. `tests/ppo.test.ts`. + +## 76. Header and Search Results assets are not uploaded like screenshots +- **Symptom:** a header or search results image was "uploaded" but the version page still says "Browse approved + assets to select a header asset", or a re-run uploaded the same file again. +- **Cause:** these slots take assets from the app's Asset Library (`GET /v1/apps/{id}/assetLibrary`), not a set of + their own. Each asset is reviewed by Apple first; only an APPROVED asset can be selected (an + `appAssetLibraryPlacements` row with `PRODUCT_PAGE_HEADER_ASSET` or `APP_STORE_SEARCH_RESULTS_ASSET` and the version + localization). Library assets carry no `sourceFileChecksum`, and the write-ups' name for the search slot is the + API's `APP_STORE_SEARCH_RESULTS_ASSET` (`SEARCH_RESULTS_ADS_ASSET` is the Apple Ads one). +- **Do:** `storebound apple creative-assets`: it keeps the file's MD5 in `referenceName` ("storebound "), reuses + a library asset with the same MD5, selects only approved ones and says "waiting for Apple's approval" otherwise. + Uploading and selecting are normal steps, not owner buttons; the version's Submit for Review stays the owner's. +- **Guard:** `cli/apple/creative-assets.ts`, `tests/creative-assets.test.ts` (fake App Store Connect: dry run, upload, + waiting, select, replace on a changed file, nothing on the same file). diff --git a/skills/store-screenshots/SKILL.md b/skills/store-screenshots/SKILL.md index b16019a..5a223c7 100644 --- a/skills/store-screenshots/SKILL.md +++ b/skills/store-screenshots/SKILL.md @@ -197,6 +197,25 @@ images there), so only do that after a test has a winner. What the stores offer, - Test one thing per experiment (usually the first screenshot or the order), give it real traffic, and do not read results early. +## Header and Search Results (App Store creative assets, iOS / iPadOS 27+) +Since 5 Oct 2026 the App Store version page has a "Header and Search Results" tab next to "App Previews and +Screenshots". Optional: without these assets the App Store uses in-app events, app previews and screenshots. +- **Files** under the renders folder, per language: `//creative/header.png` (3840 x 1646, 21:9), + `search.png` (3:2, 1920 x 1280 up to 3840 x 2560), or one `universal.png` (5244 x 2950, 16:9) that fills either slot + (also `/creative/universal.png` for every locale, or `apple.creativeAssets.universal`). JPEG / PNG without + alpha. Videos instead: `header.mov|m4v|mp4` / `search.*`, 5-30 s, 30 or 60 fps, the same aspect ratio; search videos + play muted. `apple.creativeAssets.header: false` / `search: false` skips a slot. +- **Not rendered by `shots render`**: the scene templates are portrait device shots; make the wide art yourself (or from + the feature graphic artwork at the larger size) and drop it in. +- **Upload:** `storebound apple creative-assets --dry`, then without `--dry`. Files go into the app's Asset Library + (API: `appAssetLibraryImages` / `appAssetLibraryVideos`, category `CREATIVE_ASSETS`); Apple reviews each asset, and + only an approved one is selected for the slot (`appAssetLibraryPlacements`, `PRODUCT_PAGE_HEADER_ASSET` / + `APP_STORE_SEARCH_RESULTS_ASSET`). Until then the run says "waiting for Apple's approval": re-run later. Same file + (MD5) = nothing sent. MCP: `apple_creative_assets` (dry by default). +- **Checks:** `storebound check` and `validate` print an info note when no locale has one. +- **Play:** no such slot. The feature graphic (1024 x 500, `play images`) and the promo video (YouTube URL) are the + closest equivalents. + ## From an AI tool (MCP) `storebound mcp` exposes `shots_check` (read-only) and `shots_capture`, `shots_render`, `shots_gallery` (local files, `dry_run: true` by default: run it once dry, show the plan, then with `dry_run: false`). Uploads (`apple_screenshots`, diff --git a/tests/creative-assets.test.ts b/tests/creative-assets.test.ts new file mode 100644 index 0000000..1239a96 --- /dev/null +++ b/tests/creative-assets.test.ts @@ -0,0 +1,126 @@ +// App Store "Header and Search Results" creative assets: local size / alpha / video checks, the check / validate note, +// and `apple creative-assets` against the fake App Store Connect (Asset Library upload, approval wait, select, replace +// on a changed file, nothing on the same file). +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test'; +import { md5 } from '../cli/apple/asc'; +import { REF, run } from '../cli/apple/creative-assets'; +import { checkCreativeImage, checkCreativeVideo, CREATIVE_NOTE, creativeFiles, creativeNote } from '../cli/shots/creative'; +import { imageInfo } from '../cli/shots/spec'; +import { upsertTiming } from '../cli/lib/upsert'; +import { ascEnv, BASE, capture, project, restore } from './helpers/store-mock'; +import { installStores, type Stores, uninstallStores, writes } from './helpers/fake-stores'; + +/** A PNG header (IHDR only: imageInfo reads no more), RGB or RGBA, plus `salt` bytes so files differ. */ +function png(w: number, h: number, alpha = false, salt = 0): Uint8Array { + const b = new Uint8Array(33 + 1); + b.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52]); + const dv = new DataView(b.buffer); + dv.setUint32(16, w); dv.setUint32(20, h); b[24] = 8; b[25] = alpha ? 6 : 2; + b[33] = salt; + return b; +} + +describe('creative asset checks', () => { + test('header: exactly 3840x1646, no alpha', () => { + expect(checkCreativeImage(imageInfo(png(3840, 1646)), 'header')).toEqual([]); + expect(checkCreativeImage(imageInfo(png(3840, 1645)), 'header')[0]!.code).toBe('size'); + expect(checkCreativeImage(imageInfo(png(3840, 1646, true)), 'header').map(i => i.code)).toEqual(['alpha']); + }); + test('search: 3:2 from 1920x1280 to 3840x2560', () => { + for (const [w, h] of [[1920, 1280], [3000, 2000], [3840, 2560]]) expect(checkCreativeImage(imageInfo(png(w!, h!)), 'search')).toEqual([]); + for (const [w, h] of [[1800, 1200], [3900, 2600], [2000, 1280]]) expect(checkCreativeImage(imageInfo(png(w!, h!)), 'search')[0]!.code).toBe('size'); + }); + test('universal: one 5244x2950 PNG for either slot', () => { + expect(checkCreativeImage(imageInfo(png(5244, 2950)), 'header', true)).toEqual([]); + expect(checkCreativeImage(imageInfo(png(5244, 2950)), 'search', true)).toEqual([]); + expect(checkCreativeImage(imageInfo(png(3840, 2160)), 'search', true)[0]!.code).toBe('size'); + }); + test('video: length, fps, container, aspect; ffprobe missing is a skipped-check warning', () => { + const v = (w: number, h: number, fps: number, duration: number, audio = false) => ({ bytes: 1, duration, video: { codec: 'h264', w, h, fps }, ...(audio ? { audio: { codec: 'aac', channels: 2, sampleRate: 48000 } } : {}) }); + expect(checkCreativeVideo('header.mov', v(3840, 1646, 30, 10), 'header')).toEqual([]); + expect(checkCreativeVideo('search.mp4', v(1920, 1280, 60, 30), 'search')).toEqual([]); + expect(checkCreativeVideo('search.mp4', v(1920, 1280, 25, 4), 'search').map(i => i.msg).join()).toMatch(/5-30 s.*30 or 60 fps/); + expect(checkCreativeVideo('header.webm', v(3840, 1646, 30, 10), 'header')[0]!.msg).toContain('.mov'); + expect(checkCreativeVideo('header.mov', v(1920, 1080, 30, 10), 'header')[0]!.msg).toContain('aspect'); + expect(checkCreativeVideo('search.mp4', v(1920, 1280, 30, 10, true), 'search')[0]!.level).toBe('warn'); + const skipped = checkCreativeVideo('header.mov', null, 'header'); + expect(skipped).toHaveLength(1); + expect(skipped[0]!.msg).toContain('not checked (ffprobe missing'); + }); + test('files: own header / search first, the universal image fills the rest', () => { + const list = (d: string) => (d.endsWith('en/creative') ? ['header.png', 'notes.txt'] : d.endsWith('creative') ? ['universal.png'] : []); + const fs = creativeFiles('/r', 'en', list); + expect(fs.map(f => [f.placement, f.file, f.universal])).toEqual([['header', '/r/en/creative/header.png', false], ['search', '/r/creative/universal.png', true]]); + }); + test('info note: an App Store app without any asset; none for Play-only or with files', () => { + const langs = [{ id: 'en', apple: 'en-US' }]; + expect(creativeNote({ apple: {}, languages: langs }, '/r', () => [])).toBe(CREATIVE_NOTE); + expect(CREATIVE_NOTE).toContain('optional; without it the App Store uses in-app events, app previews and screenshots'); + expect(CREATIVE_NOTE).toContain('feature graphic'); + expect(creativeNote({ languages: langs }, '/r', () => [])).toBeNull(); + expect(creativeNote({ apple: {}, languages: langs }, '/r', d => (d.endsWith('creative') ? ['search.png'] : []))).toBeNull(); + }); +}); + +describe('apple creative-assets against the fake App Store Connect', () => { + let s: Stores; + beforeAll(ascEnv); + afterAll(restore); + beforeEach(() => { upsertTiming.waitMs = 0; s = installStores(); }); + afterEach(uninstallStores); + const APP = '6400000101'; + const CFG = { ...BASE, languages: [{ id: 'en', apple: 'en-US', play: 'en-US' }] }; + const setup = (files: Record) => { + s.asc.put({ type: 'appAssetLibraries', id: 'lib-1', attributes: {}, rels: { app: APP } }); + s.asc.put({ type: 'appStoreVersions', id: 'ver-1', attributes: { versionString: '1.0.0', appVersionState: 'PREPARE_FOR_SUBMISSION', platform: 'IOS' }, rels: { app: APP } }); + s.asc.put({ type: 'appStoreVersionLocalizations', id: 'loc-en', attributes: { locale: 'en-US' }, rels: { appStoreVersion: 'ver-1' } }); + return project(CFG, files); + }; + const go = async (p: ReturnType, argv: string[] = []) => { + const a = s.calls.length; + const r = await capture(() => run(p.ctx(argv))); + if (r.exit) throw new Error(`exit ${r.exit}: ${r.out}\n${r.err}`); + return { out: r.out, w: writes(s.calls.slice(a)).map(c => `${c.method} ${decodeURIComponent(c.path).replace(/\?.*/, '').replace(/\/v1\/(\w+)\/[^/]+$/, '/v1/$1/{id}')}`).filter(x => x.includes(' /v1/')) }; + }; + const approve = () => { for (const t of ['appAssetLibraryImages', 'appAssetLibraryVideos']) for (const x of s.asc.all(t)) x.attributes.state = 'APPROVED'; }; + + test('dry run, upload, wait for approval, select, same file = nothing, changed file = replace', async () => { + const header = png(3840, 1646, false, 1); + const p = setup({ 'store/renders/en/creative/header.png': header, 'store/renders/en/creative/search.png': png(1920, 1280, false, 2) }); + + const dry = await go(p, ['--dry']); + expect(dry.w).toEqual([]); + expect(dry.out).toContain('would upload header.png'); + + const first = await go(p); + expect(first.w).toEqual(['POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}', 'POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}']); + expect(first.out).toContain("waiting for Apple's approval"); + expect(s.asc.all('appAssetLibraryImages').map(x => x.attributes.referenceName)).toContain(REF(md5(header))); + expect(s.asc.all('appAssetLibraryPlacements')).toHaveLength(0); + + const again = await go(p); + expect(again.w).toEqual([]); // still waiting: no second upload + + approve(); + const sel = await go(p); + expect(sel.w).toEqual(['POST /v1/appAssetLibraryPlacements', 'POST /v1/appAssetLibraryPlacements']); + expect(s.asc.all('appAssetLibraryPlacements').map(x => x.attributes.placementType).sort()).toEqual(['APP_STORE_SEARCH_RESULTS_ASSET', 'PRODUCT_PAGE_HEADER_ASSET']); + + expect((await go(p)).w).toEqual([]); + + // a changed header: uploaded, selected only after approval, then the old placement is replaced + const q = project(CFG, { 'store/renders/en/creative/header.png': png(3840, 1646, false, 9), 'store/renders/en/creative/search.png': png(1920, 1280, false, 2) }); + expect((await go(q)).w).toEqual(['POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}']); + approve(); + const rep = await go(q); + expect(rep.w).toEqual(['DELETE /v1/appAssetLibraryPlacements/{id}', 'POST /v1/appAssetLibraryPlacements']); + expect(s.asc.all('appAssetLibraryPlacements')).toHaveLength(2); + }); + + test('a bad file stops the run before any call', async () => { + const p = setup({ 'store/renders/en/creative/header.png': png(3840, 1600, true) }); + const a = s.calls.length; + await expect(capture(() => run(p.ctx([])))).rejects.toThrow('creative asset problems'); + expect(s.calls.length).toBe(a); + }); +}); diff --git a/tests/helpers/fake-stores.ts b/tests/helpers/fake-stores.ts index 5fa874b..bf45d8c 100644 --- a/tests/helpers/fake-stores.ts +++ b/tests/helpers/fake-stores.ts @@ -71,6 +71,10 @@ const LISTS: Record = { 'subscriptions/winBackOffers': { type: 'winBackOffers' }, 'betaGroups/betaTesters': { type: 'betaTesters' }, 'apps/analyticsReportRequests': { type: 'analyticsReportRequests' }, + 'apps/assetLibrary': { type: 'appAssetLibraries', one: true }, + 'appAssetLibraries/images': { type: 'appAssetLibraryImages' }, + 'appAssetLibraries/videos': { type: 'appAssetLibraryVideos' }, + 'appStoreVersionLocalizations/placements': { type: 'appAssetLibraryPlacements' }, }; /** Stores refuse a second resource with the same key (409 ENTITY_ERROR ... already exists). */ const UNIQUE: Record string> = { @@ -97,7 +101,9 @@ const UNIQUE: Record string> = { winBackOffers: r => `${r.rels.subscription}|${r.attributes.offerId}`, betaTesters: r => String(r.attributes.email).toLowerCase(), }; -const ASSETS = /Screenshots$|^appPreviews$|^appScreenshots$/; +const ASSETS = /Screenshots$|^appPreviews$|^appScreenshots$|^appAssetLibrary(Images|Videos)$/; +/** App Asset Library assets: a state of their own (AWAITING_UPLOAD -> WAITING_FOR_REVIEW after the commit; a test sets APPROVED). */ +const LIBRARY = /^appAssetLibrary(Images|Videos)$/; /** Attributes a new resource of a type starts with. */ const DEFAULTS: Record> = { inAppPurchases: { state: 'MISSING_METADATA' }, subscriptions: { state: 'MISSING_METADATA' }, reviewSubmissions: { state: 'READY_FOR_REVIEW' }, @@ -178,7 +184,7 @@ export class FakeAsc { return json({ errors: [{ status: '409', code: 'ENTITY_ERROR.ATTRIBUTE.INVALID.DUPLICATE', title: 'The provided entity includes an attribute with a value that has already been used', detail: 'already exists' }] }, 409); if (ASSETS.test(d.type) && d.attributes?.fileName) { main.attributes.uploadOperations = [{ method: 'PUT', url: `${UPLOAD_HOST}${main.id}`, offset: 0, length: Number(d.attributes.fileSize ?? 0), requestHeaders: [{ name: 'Content-Type', value: 'image/png' }] }]; - main.attributes.assetDeliveryState = { state: 'AWAITING_UPLOAD' }; + if (LIBRARY.test(d.type)) main.attributes.state = 'AWAITING_UPLOAD'; else main.attributes.assetDeliveryState = { state: 'AWAITING_UPLOAD' }; } // a tester belongs to the app of its groups (GET /v1/betaTesters?filter[apps]=) if (d.type === 'betaTesters') { const g = [main.rels.betaGroups].flat()[0]; const app = g ? this.res.get(String(g))?.rels.app : undefined; if (app) main.rels.app = app; } @@ -304,7 +310,8 @@ export class FakeAsc { rels: { [singular(self.type)]: self.id, ...Object.fromEntries(Object.entries(inc.relationships ?? {}).map(([k, v]) => [k, v.data.id])) } }); if (attrs.uploaded === true && ASSETS.test(self.type)) { const { uploaded: _u, ...rest } = attrs; - Object.assign(self.attributes, rest, { assetDeliveryState: { state: this.parts.includes(self.id) ? 'COMPLETE' : 'FAILED' } }); + if (LIBRARY.test(self.type)) Object.assign(self.attributes, rest, { state: this.parts.includes(self.id) ? 'WAITING_FOR_REVIEW' : 'FAILED' }); + else Object.assign(self.attributes, rest, { assetDeliveryState: { state: this.parts.includes(self.id) ? 'COMPLETE' : 'FAILED' } }); delete self.attributes.uploadOperations; } else if (self.type === 'reviewSubmissions' && (attrs.submitted === true || attrs.canceled === true)) { // seen live (2026-10-12): a REJECTED item that is not marked resolved blocks every submit with this 409, and an From d006f8d93222937040616fa98b36550aa74bcd86 Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 18 Oct 2026 13:13:16 +0700 Subject: [PATCH 024/344] storebound 0.8.13: version in package.json and every copy, CHANGELOG 0.8.13 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index a6ec82d..a69d45b 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.12", + "version": "0.8.13", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 33921ae..590b859 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.12", + "version": "0.8.13", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index d53044f..e19c636 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.12", + "version": "0.8.13", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index db8a60a..95b8b67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.13 · 2026-10-18 + - **iPhone Duo screenshots.** `apple.iphoneDuo: true` adds the foldable's outer (1398 x 2034) and inner (2007 x 2853) sets, portrait or landscape, to `shots render`, `shots check` (exact sizes, no alpha) and the gallery. App Store Connect API 4.5.1 has no Duo `ScreenshotDisplayType`, so `apple screenshots` skips them with a message and the deep diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 4aed85e..ce46d13 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.12", + "version": "0.8.13", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index e5b3c59..2192196 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4010,7 +4010,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.12" +version = "0.8.13" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 46955c1..bdd545a 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.12" +version = "0.8.13" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 7e01bff..d766476 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.12", + "version": "0.8.13", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index af290f3..7c6a291 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.12", + "version": "0.8.13", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index 76f0df0..8d68012 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.12", + "version": "0.8.13", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From 3e4015b686438fe8e538d51e336a56b10d127c4f Mon Sep 17 00:00:00 2001 From: CRT Date: Sun, 18 Oct 2026 13:38:26 +0700 Subject: [PATCH 025/344] ci: the background acceptance jobs start after the Linux and Windows installer builds (0.8.13's Windows installer waited behind six acceptance jobs on the one Windows runner); release: an npm deprecation already set by an earlier npm-publish run (422) is not an error --- .forgejo/workflows/ci.yml | 4 +++- tools/release.ts | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml index 09f0171..286c25a 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -76,8 +76,10 @@ jobs: # npm tarball, in fresh temp folders with piped stdin and the fake stores, on Linux and Windows x Node 20 / Node 22 # (npx --package=) / Bun (bun x). One red cell and the commit is no candidate. macOS runs on the owner's Mac # (tools/release.ts, cached per CLI key). + # after the installers: the one Windows runner builds the release installer first, the background tests wait + # (0.8.13's Windows installer queued behind six acceptance jobs) acceptance: - needs: gate + needs: [gate, linux, windows] if: github.event_name != 'pull_request' || true strategy: fail-fast: false diff --git a/tools/release.ts b/tools/release.ts index c96807a..41b7dc3 100644 --- a/tools/release.ts +++ b/tools/release.ts @@ -455,7 +455,9 @@ async function npmRelease(version: string, token: string): Promise { await new Promise(res => setTimeout(res, 5_000)); } const dep = npmRun(['deprecate', `storebound@<${version}`, `storebound ${version} is out: npx storebound@${version}`], token); - if (dep.code !== 0) fail(`npm deprecate failed: ${dep.out.trim().split('\n').slice(-3).join(' ')}`); + // a deprecation that is already set (an earlier npm-publish run) answers 422: fine when the message is the same + if (dep.code !== 0 && /E422|Unprocessable/i.test(dep.out) && (spawnSync('npm', ['view', `storebound@<${version}`, 'deprecated'], { encoding: 'utf8', timeout: 30_000 }).stdout ?? '').includes(`storebound ${version} is out`)) say('npm: older versions were already deprecated'); + else if (dep.code !== 0) fail(`npm deprecate failed: ${dep.out.trim().split('\n').slice(-3).join(' ')}`); say(`npm: storebound@${version} published and older versions deprecated`); } From 183579449cc29fd487414f3491a0f20333705e9e Mon Sep 17 00:00:00 2001 From: CRT Date: Mon, 19 Oct 2026 05:42:53 +0700 Subject: [PATCH 026/344] apple creative-assets: select Header and Search Results assets once processed (Prepare for Submission), not once approved: Apple reviews an asset only in a review submission, so 0.8.13 waited forever; upload and select in one run with a bounded processing wait; --add-for-review puts unreviewed assets into the draft review submission (never submits); --verify reads every slot back read-only (MCP apple_creative_assets_verify); a rejected file or one that failed processing twice is not re-uploaded, an archived copy is unarchived; fake commits library assets to PREPARE_FOR_SUBMISSION; pitfall 76 rewritten; apple-name check test only looks at name hints --- CHANGELOG.md | 9 + cli/api/wrapped.gen.ts | 2 +- cli/apple/creative-assets.ts | 221 +++++++++++++++--- cli/commands.ts | 2 +- cli/data/flags.json | 10 +- cli/mcp-tools.ts | 6 +- docs/api-coverage.md | 2 +- .../header-search-results-announcement.md | 29 +++ docs/store-art.md | 18 +- skills/store-pitfalls/SKILL.md | 29 ++- skills/store-screenshots/SKILL.md | 18 +- tests/apple-name.test.ts | 3 +- tests/creative-assets.test.ts | 114 ++++++--- tests/helpers/fake-stores.ts | 10 +- 14 files changed, 378 insertions(+), 95 deletions(-) create mode 100644 docs/drafts/header-search-results-announcement.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 95b8b67..e62234e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +- **Header and Search Results: select once processed, then add for review.** `storebound apple creative-assets` now + selects an asset for the product page header or search results slot as soon as it is processed ("Prepare for + Submission"), as the console's Browse Assets does: Apple reviews an asset only once it is in a review submission, so + 0.8.13's "select once approved" never finished. Upload and select happen in one run (processing wait up to 2 min with + a heartbeat). `--add-for-review` adds the selected, unreviewed assets to the app's draft review submission (never + submits; Submit for Review stays the owner's); `--verify` (MCP `apple_creative_assets_verify`) reads every slot back + read-only and fails when one differs from the local file. A file App Review rejected, or one that failed processing + twice, is not uploaded again; an archived copy of the same file is unarchived instead of uploaded. Pitfall 76 rewritten. + ## 0.8.13 · 2026-10-18 - **iPhone Duo screenshots.** `apple.iphoneDuo: true` adds the foldable's outer (1398 x 2034) and inner (2007 x 2853) diff --git a/cli/api/wrapped.gen.ts b/cli/api/wrapped.gen.ts index 0a075f2..a6d7c8e 100644 --- a/cli/api/wrapped.gen.ts +++ b/cli/api/wrapped.gen.ts @@ -79,7 +79,7 @@ export const WRAPPED: { apple: Record; play: Record//creative/header.{png,jpg,mov,m4v,mp4} (3840x1646, 21:9), // search.{...} (3:2, 1920x1280 to 3840x2560), or one universal.png (5244x2950) for both slots. apple.creativeAssets // can turn a placement off (header: false / search: false) or point at another universal file. -// Flow, as App Store Connect works (Header and Search Results tab > Header / Search Results > Browse Assets): a file is -// uploaded once into the app's Asset Library (POST appAssetLibraryImages / Videos, category CREATIVE_ASSETS, its MD5 -// in referenceName "storebound " because library assets carry no checksum), Apple reviews it, and only an -// APPROVED asset is selected for a slot (POST appAssetLibraryPlacements with placementType PRODUCT_PAGE_HEADER_ASSET or -// APP_STORE_SEARCH_RESULTS_ASSET and the version localization). Upsert: a slot that already shows the same MD5 is left -// alone; a new file replaces the slot only once it is approved (the old placement is removed, then the new one is -// created); an asset with the same MD5 already in the library is reused, never uploaded twice. Read back at the end. +// Flow, as App Store Connect works (version page > Product Page Information > Header and Search Results > Header / +// Search Results > Browse Assets > Save; Help "Manage your App Store assets", "App Store asset statuses", +// "Submit assets from Asset Library", checked 19 Oct 2026): +// 1. a file is uploaded once into the app's Asset Library (POST appAssetLibraryImages / Videos, category +// CREATIVE_ASSETS, its MD5 in referenceName "storebound " because library assets carry no checksum); +// 2. after processing it is "Prepare for Submission", and in that state it can already be selected for a slot +// (POST appAssetLibraryPlacements, placementType PRODUCT_PAGE_HEADER_ASSET / APP_STORE_SEARCH_RESULTS_ASSET, the +// version localization). Approval is NOT needed first: an asset is only reviewed once it is in a review +// submission, so "select only approved assets" waits forever (pitfall 76); +// 3. App Review: the asset is a review submission item of its own (reviewSubmissionItems appAssetLibraryImage / +// appAssetLibraryVideo; console "Add for Review"). Before the app's first approved version it goes in the same +// submission as that version; afterwards it can go alone. --add-for-review adds it to the draft submission; +// pressing Submit for Review stays the owner's. +// Upsert: a slot that already shows the same MD5 is left alone; an asset with the same MD5 in the library is reused +// (an archived one is unarchived), never uploaded twice; a REJECTED file is not uploaded again (change the file); a +// changed file replaces the slot (the old placement is removed, then the new one is created). Read back at the end. // Play has no such slot: the feature graphic (play images) and the promo video URL are its closest equivalents. import { readFileSync } from 'node:fs'; import { basename } from 'node:path'; import type { Ctx } from '../lib/ctx'; import { need } from '../lib/ctx'; +import { consoleLink } from '../lib/console-links'; import { done, log, warn } from '../lib/log'; +import { elapsed } from '../lib/progress'; +import * as rt from '../lib/rt'; import { ffprobe } from '../shots/report'; import { imageInfo } from '../shots/spec'; import { checkCreativeImage, checkCreativeVideo, type CreativeFile, creativeFiles, PLACEMENT_TYPE, type Placement } from '../shots/creative'; import { ascClient, md5, type J } from './asc'; +import { addItem, ensureDraft, OtherSubmissionError } from './submission'; +const TAG = 'apple'; export const REF = (sum: string): string => `storebound ${sum}`; const sumOf = (a: J): string | undefined => /^storebound ([0-9a-f]{32})$/.exec(String(a?.attributes?.referenceName ?? ''))?.[1]; -export interface Row { locale: string; placement: Placement; file: string; action: 'keep' | 'upload' | 'wait' | 'select' | 'replace'; state?: string } +/** Asset states (AppAssetLibraryAssetState, API 4.5.1) by what storebound may do with them. */ +export const ASSET_STATES = { + /** still uploading / processing: wait (bounded), then select */ + processing: ['AWAITING_UPLOAD', 'UPLOAD_COMPLETE'], + /** processed and usable in a slot; not reviewed yet: goes into a review submission */ + unreviewed: ['COMPLETE', 'PREPARE_FOR_SUBMISSION'], + /** in a submission or reviewed: usable in a slot, nothing to add */ + reviewing: ['READY_FOR_REVIEW', 'WAITING_FOR_REVIEW', 'IN_REVIEW', 'ACCEPTED', 'APPROVED'], +} as const; +export type AssetClass = 'processing' | 'unreviewed' | 'reviewing' | 'failed' | 'rejected' | 'archived' | 'unknown'; + +/** What a library asset's state means for storebound. Pure. */ +export function classify(state: string | undefined): AssetClass { + const s = String(state ?? ''); + for (const [k, v] of Object.entries(ASSET_STATES)) if ((v as readonly string[]).includes(s)) return k as AssetClass; + if (s === 'FAILED') return 'failed'; + if (s === 'REJECTED') return 'rejected'; + if (s === 'ARCHIVED') return 'archived'; + return s ? 'unknown' : 'processing'; +} + +/** Selectable for a slot: processed and not failed / rejected / archived (Prepare for Submission is enough). */ +export const selectable = (c: AssetClass): boolean => c === 'unreviewed' || c === 'reviewing'; + +/** Stop re-uploading a file whose earlier uploads failed processing this many times. */ +export const MAX_FAILED = 2; + +/** The library asset to use for one MD5: a live one first (newest state wins: reviewing > unreviewed > processing), + * else an archived one (unarchive it), else none; plus why not to upload (a rejected file, repeated failures). Pure. */ +export function pickAsset(assets: J[], sum: string): { asset?: J; unarchive?: boolean; refuse?: string } { + const mine = assets.filter(x => sumOf(x) === sum); + const rank: Record = { reviewing: 0, unreviewed: 1, processing: 2, unknown: 3, archived: 4, rejected: 5, failed: 6 }; + const by = (c: AssetClass) => mine.filter(x => classify(x.attributes?.state) === c); + const live = mine.filter(x => rank[classify(x.attributes?.state)] <= 3).sort((a, b) => rank[classify(a.attributes?.state)] - rank[classify(b.attributes?.state)]); + if (live[0]) return { asset: live[0] }; + if (by('archived')[0]) return { asset: by('archived')[0], unarchive: true }; + const rej = by('rejected')[0]; + if (rej) return { refuse: `rejected by App Review${reason(rej)}: uploading the same file again changes nothing; change the file` }; + if (by('failed').length >= MAX_FAILED) return { refuse: `${by('failed').length} earlier uploads of this file failed processing${reason(by('failed')[0]!)}: check the file (format, size) before trying again` }; + return {}; +} + +const reason = (a: J): string => { + const d = ((a.attributes?.stateDetails ?? []) as J[]).map(x => x?.code ?? x?.message ?? x?.description).filter(Boolean); + return d.length ? ` (${d.join(', ')})` : ''; +}; + +/** Bounded wait for processing (every wait has a timeout and a heartbeat); tests set waitMs 0 / timeoutMs 0. */ +export const processingTiming = { pollMs: 3000, timeoutMs: 120_000, heartbeatMs: 20_000, sleep: (ms: number): Promise => (ms > 0 ? rt.sleep(ms) : Promise.resolve()) }; + +export interface Row { locale: string; placement: Placement; file: string; action: 'keep' | 'upload' | 'wait' | 'select' | 'replace' | 'refuse'; state?: string; asset?: J } /** Local files per App Store locale, checked; throws on any error before a network call. */ export function localCreative(ctx: Ctx): { src: string; local: Map } { @@ -42,7 +108,7 @@ export function localCreative(ctx: Ctx): { src: string; local: Map ca[f.placement] !== false); for (const f of fs) { const issues = f.kind === 'image' ? checkCreativeImage(imageInfo(readFileSync(f.file)), f.placement, f.universal) : checkCreativeVideo(f.file, ffprobe(f.file), f.placement); - for (const i of issues) (i.level === 'error' ? warn : log)('apple', `${l.apple} ${f.placement} ${basename(f.file)}: ${i.msg}`); + for (const i of issues) (i.level === 'error' ? warn : log)(TAG, `${l.apple} ${f.placement} ${basename(f.file)}: ${i.msg}`); if (issues.some(i => i.level === 'error')) bad++; } if (fs.length) local.set(l.apple, fs); @@ -54,30 +120,39 @@ export function localCreative(ctx: Ctx): { src: string; local: Map { const { config, root } = ctx.loaded; const dry = ctx.args.has('dry'); + const verify = ctx.args.has('verify'); + const forReview = ctx.args.has('add-for-review'); const bundleId = need(config.apple?.bundleId, 'apple.bundleId'); const { src, local } = localCreative(ctx); - if (!local.size) { warn('apple', `no creative assets in ${src}//creative/ (header.png 3840x1646, search.png 3:2, or universal.png 5244x2950): optional; without them the App Store uses events, previews and screenshots`); return; } - log('apple', `${[...local.values()].flat().length} creative assets for ${local.size} locales pass the checks`); + if (!local.size) { warn(TAG, `no creative assets in ${src}//creative/ (header.png 3840x1646, search.png 3:2, or universal.png 5244x2950): optional; without them the App Store uses events, previews and screenshots`); return; } + log(TAG, `${[...local.values()].flat().length} creative assets for ${local.size} locales pass the checks`); let c: Awaited>; try { c = await ascClient(root, bundleId, config.apple?.appId); } catch (e) { if (!dry) throw e; - for (const [loc, fs] of local) for (const f of fs) log('apple', `${loc} ${PLACEMENT_TYPE[f.placement]}: would upload ${basename(f.file)} to the Asset Library and select it once approved`); - return done('apple', `creative assets planned (dry run, no App Store Connect comparison: ${(e as Error).message.split('\n')[0]})`); + for (const [loc, fs] of local) for (const f of fs) log(TAG, `${loc} ${PLACEMENT_TYPE[f.placement]}: would upload ${basename(f.file)} to the Asset Library and select it`); + return done(TAG, `creative assets planned (dry run, no App Store Connect comparison: ${(e as Error).message.split('\n')[0]})`); } - const lib = (await c.asc('GET', `/v1/apps/${await c.app()}/assetLibrary`)).data as J; - const version = await c.editableVersion(); - if (!version) throw new Error('no editable App Store version (run apple listing --version x.y.z first)'); + const appId = await c.app(); + const lib = (await c.asc('GET', `/v1/apps/${appId}/assetLibrary`)).data as J; + const live = async () => (await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=50`)) + .find(v => (v.attributes.appVersionState ?? v.attributes.appStoreState) === 'READY_FOR_DISTRIBUTION' || v.attributes.appStoreState === 'READY_FOR_SALE') ?? null; + // --verify falls back to the live version (read-only); writes need the editable one + const version = await c.editableVersion() ?? (verify ? await live() : null); + if (!version) throw new Error(`no editable App Store version: the header and search results slots belong to a version page (run apple listing --version x.y.z first). ${consoleLink('asc.version')}`); const locs = await c.all(`/v1/appStoreVersions/${version.id}/appStoreVersionLocalizations?limit=50`); const library = async (): Promise => [ ...(await c.all(`/v1/appAssetLibraries/${lib.id}/images?filter[category]=CREATIVE_ASSETS&limit=200`)), ...(await c.all(`/v1/appAssetLibraries/${lib.id}/videos?filter[category]=CREATIVE_ASSETS&limit=200`)), ]; let assets = await library(); - const bySum = (s: string) => assets.filter(x => sumOf(x) === s && x.attributes?.state !== 'ARCHIVED' && x.attributes?.state !== 'FAILED' && x.attributes?.state !== 'REJECTED')[0]; - const rows: Row[] = []; + const placedIn = async (locId: string, ptype: string) => c.all(`/v1/appStoreVersionLocalizations/${locId}/placements?filter[placementType]=${ptype}&include=image,video`); + const shownOf = (p: J) => p.relationships?.image?.data?.id ?? p.relationships?.video?.data?.id; + if (verify) return verifySlots(); + + const rows: Row[] = []; async function upload(f: CreativeFile, sum: string): Promise { const buf = readFileSync(f.file); const type = f.kind === 'image' ? 'appAssetLibraryImages' : 'appAssetLibraryVideos'; @@ -86,11 +161,26 @@ export async function run(ctx: Ctx): Promise { for (const op of (res.attributes.uploadOperations ?? []) as J[]) { const headers: Record = {}; for (const h of op.requestHeaders ?? []) headers[h.name] = h.value; - const r = await fetch(op.url, { method: op.method, headers, body: buf.subarray(op.offset, op.offset + op.length) }); + const r = await fetch(op.url, { method: op.method, headers, body: buf.subarray(op.offset, op.offset + op.length), signal: AbortSignal.timeout(300_000) }); if (!r.ok) throw new Error(`upload ${basename(f.file)} part ${op.offset} -> ${r.status}`); } return (await c.asc('PATCH', `/v1/${type}/${res.id}`, { data: { type, id: res.id, attributes: { uploaded: true } } })).data as J; } + /** Polls one asset until it leaves processing, at most processingTiming.timeoutMs, with a heartbeat line. */ + async function processed(a: J, label: string): Promise { + const t0 = Date.now(); + let beat = t0, cur = a; + while (classify(cur.attributes?.state) === 'processing') { + if (Date.now() - t0 >= processingTiming.timeoutMs) { + warn(TAG, `${label}: still ${cur.attributes?.state ?? 'processing'} after ${elapsed(Date.now() - t0)}${reason(cur)} (asset ${cur.id}); re-run later to select it`); + return cur; + } + await processingTiming.sleep(processingTiming.pollMs); + cur = ((await c.maybe(`/v1/${cur.type}/${cur.id}`))?.data as J) ?? cur; + if (Date.now() - beat >= processingTiming.heartbeatMs) { beat = Date.now(); log(TAG, `${label}: processing (${cur.attributes?.state}, ${elapsed(Date.now() - t0)})`); } + } + return cur; + } for (const loc of locs) { const locale: string = loc.attributes.locale; @@ -98,37 +188,94 @@ export async function run(ctx: Ctx): Promise { const ptype = PLACEMENT_TYPE[f.placement]; const tag = `${locale} ${ptype}`; const sum = md5(readFileSync(f.file)); - const placed = await c.all(`/v1/appStoreVersionLocalizations/${loc.id}/placements?filter[placementType]=${ptype}&include=image,video`); - const shownIds = placed.map(p => p.relationships?.image?.data?.id ?? p.relationships?.video?.data?.id).filter(Boolean); - if (placed.length === 1 && assets.some(x => shownIds.includes(x.id) && sumOf(x) === sum)) { log('apple', `${tag}: ${basename(f.file)} already selected`); rows.push({ locale, placement: f.placement, file: f.file, action: 'keep' }); continue; } - let asset = bySum(sum); + const row = (action: Row['action'], asset?: J) => rows.push({ locale, placement: f.placement, file: f.file, action, state: asset?.attributes?.state, asset }); + const placed = await placedIn(loc.id, ptype); + const shownIds = placed.map(shownOf).filter(Boolean); + const shown = assets.find(x => shownIds.includes(x.id) && sumOf(x) === sum); + if (placed.length === 1 && shown) { log(TAG, `${tag}: ${basename(f.file)} already selected (${shown.attributes?.state})`); row('keep', shown); continue; } + const pick = pickAsset(assets, sum); + if (pick.refuse) { warn(TAG, `${tag}: ${basename(f.file)} ${pick.refuse}`); row('refuse'); continue; } + let asset = pick.asset; if (!asset) { - if (dry) { log('apple', `${tag}: would upload ${basename(f.file)} to the Asset Library (Apple approves it, then it is selected)`); rows.push({ locale, placement: f.placement, file: f.file, action: 'upload' }); continue; } - log('apple', `${tag}: uploading ${basename(f.file)} to the Asset Library`); + if (dry) { log(TAG, `${tag}: would upload ${basename(f.file)} to the Asset Library and select it once processed`); row('upload'); continue; } + log(TAG, `${tag}: uploading ${basename(f.file)} to the Asset Library`); asset = await upload(f, sum); assets = await library(); - asset = bySum(sum) ?? asset; + asset = pickAsset(assets, sum).asset ?? asset; + } else if (pick.unarchive) { + if (dry) { log(TAG, `${tag}: would unarchive ${basename(f.file)} (same file, archived) and select it`); row(placed.length ? 'replace' : 'select', asset); continue; } + asset = (await c.asc('PATCH', `/v1/${asset.type}/${asset.id}`, { data: { type: asset.type, id: asset.id, attributes: { archived: false } } })).data as J; + log(TAG, `${tag}: unarchived ${basename(f.file)} (asset ${asset.id})`); + } + if (!dry) asset = await processed(asset, `${tag} ${basename(f.file)}`); + const cls = classify(asset.attributes?.state); + if (!selectable(cls)) { + if (cls === 'processing' && dry) { log(TAG, `${tag}: ${basename(f.file)} is processing in the Asset Library; would select it once processed`); row('wait', asset); continue; } + if (cls === 'processing') { row('wait', asset); continue; } + warn(TAG, `${tag}: ${basename(f.file)} is ${asset.attributes?.state}${reason(asset)}; not selected`); row('refuse', asset); continue; } - const state = String(asset.attributes?.state ?? ''); - if (state !== 'APPROVED') { log('apple', `${tag}: ${basename(f.file)} waiting for Apple's approval (${state || 'processing'}); re-run once it is approved to select it`); rows.push({ locale, placement: f.placement, file: f.file, action: 'wait', state }); continue; } const action = placed.length ? 'replace' : 'select'; - if (dry) { log('apple', `${tag}: would ${action === 'replace' ? `replace ${placed.length} selected asset(s) with` : 'select'} ${basename(f.file)}`); rows.push({ locale, placement: f.placement, file: f.file, action }); continue; } + if (dry) { log(TAG, `${tag}: would ${action === 'replace' ? `replace ${placed.length} selected asset(s) with` : 'select'} ${basename(f.file)} (${asset.attributes?.state})`); row(action, asset); continue; } for (const p of placed) await c.asc('DELETE', `/v1/appAssetLibraryPlacements/${p.id}`); const media = f.kind === 'image' ? 'image' : 'video'; await c.asc('POST', '/v1/appAssetLibraryPlacements', { data: { type: 'appAssetLibraryPlacements', attributes: { placementType: ptype }, relationships: { [media]: { data: { type: asset.type, id: asset.id } }, appStoreVersionLocalization: { data: { type: 'appStoreVersionLocalizations', id: loc.id } } } } }); - log('apple', `${tag}: selected ${basename(f.file)}`); - rows.push({ locale, placement: f.placement, file: f.file, action }); + log(TAG, `${tag}: selected ${basename(f.file)} (${asset.attributes?.state})`); + row(action, asset); } } - if (dry) return done('apple', 'creative assets checked (dry run, nothing sent)'); + // read back let off = 0; - for (const r of rows.filter(r => r.action === 'select' || r.action === 'replace')) { + if (!dry) for (const r of rows.filter(r => r.action === 'select' || r.action === 'replace')) { const loc = locs.find(l => l.attributes.locale === r.locale)!; const now = await c.all(`/v1/appStoreVersionLocalizations/${loc.id}/placements?filter[placementType]=${PLACEMENT_TYPE[r.placement]}`); - if (now.length !== 1) { off++; warn('apple', `${r.locale} ${PLACEMENT_TYPE[r.placement]}: read back ${now.length} selected assets, wanted 1`); } + if (now.length !== 1 || shownOf(now[0]!) !== r.asset?.id) { off++; warn(TAG, `${r.locale} ${PLACEMENT_TYPE[r.placement]}: read back ${now.length} selected assets, wanted ${basename(r.file)}`); } + } + if (off) process.exitCode = 1; + + // review: one item per distinct unreviewed asset in a slot + const unreviewed = new Map(); + for (const r of rows) if (r.asset && r.action !== 'refuse' && r.action !== 'wait' && classify(r.asset.attributes?.state) === 'unreviewed') unreviewed.set(r.asset.id, r.asset); + let added = 0; + if (unreviewed.size && forReview) { + const kindOf = (a: J) => (a.type === 'appAssetLibraryVideos' ? 'appAssetLibraryVideo' : 'appAssetLibraryImage'); + if (dry) for (const a of unreviewed.values()) log(TAG, `would add ${a.attributes?.fileName ?? a.id} to the draft review submission (${kindOf(a)})`); + else { + const { id: sid } = await ensureDraft(c, appId, root, TAG); + for (const a of unreviewed.values()) { + try { if (await addItem(c, sid, kindOf(a), a.id, `creative asset ${a.attributes?.fileName ?? a.id}`, TAG)) added++; } + catch (e) { if (e instanceof OtherSubmissionError) warn(TAG, `${a.attributes?.fileName ?? a.id}: already in review submission ${e.otherId}; nothing added`); else throw e; } + } + log(TAG, `${added} creative asset(s) added to draft review submission ${sid}; nothing was submitted`); + } + } + const n = (a: Row['action'][]) => rows.filter(r => a.includes(r.action)).length; + const summary = `creative assets: ${n(['keep'])} up to date, ${n(['select', 'replace'])} ${dry ? 'to select' : 'selected'}, ${n(['upload'])} to upload, ${n(['wait'])} still processing, ${n(['refuse'])} refused${off ? `, ${off} did not read back` : ''}`; + if (unreviewed.size) { + log(TAG, forReview + ? `owner step: Submit for Review with the version (or alone once the app has an approved version): ${consoleLink('asc.app-review')}` + : `${unreviewed.size} selected asset(s) are not reviewed yet ("Prepare for Submission"): run with --add-for-review to put them into the draft review submission (the version's, or alone once the app has an approved version); Submit for Review stays the owner's: ${consoleLink('asc.app-review')}`); + } + if (n(['refuse'])) process.exitCode = 1; + return done(TAG, dry ? `${summary} (dry run, nothing sent)` : summary); + + async function verifySlots(): Promise { + let bad = 0; + for (const loc of locs) { + const locale: string = loc.attributes.locale; + for (const f of local.get(locale) ?? []) { + const ptype = PLACEMENT_TYPE[f.placement]; + const sum = md5(readFileSync(f.file)); + const placed = await placedIn(loc.id, ptype); + const shown = placed.map(p => assets.find(x => x.id === shownOf(p))).filter(Boolean) as J[]; + const ok = placed.length === 1 && shown[0] && sumOf(shown[0]) === sum; + const what = shown.length ? shown.map(a => `${a.attributes?.fileName ?? a.id} (${a.attributes?.state})`).join(', ') : 'nothing'; + if (ok) log(TAG, `ok ${locale} ${ptype}: ${what}`); + else { bad++; warn(TAG, `${locale} ${ptype}: shows ${what}, wanted ${basename(f.file)}${placed.length > 1 ? ` (${placed.length} selected)` : ''}`); } + } + } + if (bad) process.exitCode = 1; + done(TAG, `creative assets verified on version ${version!.attributes.versionString} (read-only): ${bad ? `${bad} slot(s) differ from the local files` : 'every slot shows the local file'}`); } - const waiting = rows.filter(r => r.action === 'wait').length; - done('apple', `creative assets: ${rows.filter(r => r.action === 'keep').length} up to date, ${rows.filter(r => r.action === 'select' || r.action === 'replace').length} selected, ${waiting} waiting for approval${off ? `, ${off} did not read back` : ''}`); } diff --git a/cli/commands.ts b/cli/commands.ts index fd850b1..24ae602 100644 --- a/cli/commands.ts +++ b/cli/commands.ts @@ -80,7 +80,7 @@ export const COMMANDS: Record Promise, string]> = { 'apple appinfo': [() => import('./apple/appinfo'), 'categories, age rating, content rights, Free price, territories'], 'apple review-details': [() => import('./apple/review-details'), 'App Review contact, demo account (from .storebound/, masked) + notes'], 'apple status': [() => import('./apple/status'), 'versions, builds, IAPs, review submissions (--wait-review, --cancel-submission )'], - 'apple creative-assets': [() => import('./apple/creative-assets'), 'Header and Search Results: product page header (21:9) and search results asset (3:2) per locale, or one universal 5244x2950 PNG; uploads to the Asset Library, selects once Apple approved it (MD5 upsert); --dry'], + 'apple creative-assets': [() => import('./apple/creative-assets'), 'Header and Search Results: product page header (21:9) and search results asset (3:2) per locale, or one universal 5244x2950 PNG; uploads to the Asset Library and selects it once processed (MD5 upsert); --add-for-review, --verify (read-only), --dry'], 'apple previews': [() => import('./apple/previews'), 'app preview videos per locale (MD5-idempotent, poster frame time code); --dry'], 'apple release': [() => import('./apple/release'), 'phased release on|pause|resume|complete, --manual-release (asks first)'], 'apple signing': [() => import('./apple/signing'), 'status | ensure: bundle id capabilities, distribution certificate (key kept in .storebound/signing), App Store profiles installed for Xcode; --dry, asks first'], diff --git a/cli/data/flags.json b/cli/data/flags.json index 370e4cf..7343a21 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -88,7 +88,9 @@ "write" ], "apple creative-assets": [ - "src" + "add-for-review", + "src", + "verify" ], "apple encryption": [ "build" @@ -890,6 +892,7 @@ "ws": [ "aab", "accounts", + "add-for-review", "adgroup", "against", "agent", @@ -1111,6 +1114,7 @@ "variant", "variants", "vendor", + "verify", "version", "version-code", "version-name", @@ -1179,7 +1183,9 @@ "storebound apple cpp visible --name \"...\" [--off] [--dry] [--yes] show / hide an approved page (asks)" ], "apple creative-assets": [ - "storebound apple creative-assets [--src store/renders] [--only en-US,tr] [--dry]" + "storebound apple creative-assets [--src store/renders] [--only en-US,tr] [--dry] upload + select (upsert)", + "storebound apple creative-assets --add-for-review [--dry] also put unreviewed assets into the draft submission", + "storebound apple creative-assets --verify read-only: does every slot show the local file?" ], "apple encryption": [ "storebound apple encryption [--build 42] [--dry]" diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index 4d6606f..af09433 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -246,7 +246,11 @@ export const TOOLS: ToolDef[] = [ seconds: { type: 'integer', minimum: 15, maximum: 30 }, captions: { type: 'boolean', default: true } }, args: i => [...opt('lang', i.lang), ...opt('target', i.target), ...opt('seconds', i.seconds), ...(i.captions === false ? ['--no-captions'] : [])] }, { name: 'apple_creative_assets', title: 'App Store header and search results assets', command: ['apple', 'creative-assets'], write: true, destructive: true, network: true, idempotent: true, - description: 'Header and Search Results (iOS / iPadOS 27+): checks //creative/ (header 3840x1646, search 3:2, universal 5244x2950 PNG; no alpha; videos 5-30 s, 30/60 fps), uploads new files to the App Asset Library, and selects an asset for PRODUCT_PAGE_HEADER_ASSET / APP_STORE_SEARCH_RESULTS_ASSET only once Apple approved it (MD5 upsert, same file = nothing sent). Play counterpart: feature graphic + promo video.', + description: 'Header and Search Results (iOS / iPadOS 27+): checks //creative/ (header 3840x1646, search 3:2, universal 5244x2950 PNG; no alpha; videos 5-30 s, 30/60 fps), uploads new files to the App Asset Library and selects them for PRODUCT_PAGE_HEADER_ASSET / APP_STORE_SEARCH_RESULTS_ASSET on the editable version once processed (Prepare for Submission is enough; MD5 upsert, same file = nothing sent, a rejected file is never re-uploaded). add_for_review puts unreviewed assets into the draft review submission (never submits). Play counterpart: feature graphic + promo video.', + props: { only, add_for_review: { type: 'boolean', default: false, description: 'Also add the selected, unreviewed assets to the draft review submission (Submit for Review stays the owner\'s)' } }, + args: i => [...opt('only', i.only), ...(i.add_for_review === true ? ['--add-for-review'] : [])] }, + { name: 'apple_creative_assets_verify', title: 'Verify App Store header and search results', command: ['apple', 'creative-assets', '--verify'], write: false, network: true, + description: 'Read-only: does every Header and Search Results slot of the editable (else the live) App Store version show the local file (MD5), and in which review state? Fails on a slot that differs.', props: { only }, args: i => opt('only', i.only) }, { name: 'apple_previews', title: 'Upload App Store app previews', command: ['apple', 'previews'], write: true, destructive: true, network: true, idempotent: true, description: 'Sync app preview videos per locale to the editable App Store version (checked locally first; MD5-idempotent, changed sets are replaced; poster frame time code). Not public until the version is submitted and released. Slow: prefer the terminal with a log.', diff --git a/docs/api-coverage.md b/docs/api-coverage.md index 664f363..c5aaa76 100644 --- a/docs/api-coverage.md +++ b/docs/api-coverage.md @@ -421,7 +421,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | `apps_appPriceSchedule_getToOneRelationship` | GET | `/v1/apps/{id}/relationships/appPriceSchedule` | read | | | `apps_appStoreVersionExperimentsV2_getToManyRelated` | GET | `/v1/apps/{id}/appStoreVersionExperimentsV2` | read | apple/ppo | | `apps_appStoreVersionExperimentsV2_getToManyRelationship` | GET | `/v1/apps/{id}/relationships/appStoreVersionExperimentsV2` | read | | -| `apps_appStoreVersions_getToManyRelated` | GET | `/v1/apps/{id}/appStoreVersions` | read | apple/asc, apple/iap-submit, apple/listing, apple/release, apple/resubmit, apple/review-details, apple/status, art, lib/store-apps, listing-store, onboard, validate | +| `apps_appStoreVersions_getToManyRelated` | GET | `/v1/apps/{id}/appStoreVersions` | read | apple/asc, apple/creative-assets, apple/iap-submit, apple/listing, apple/release, apple/resubmit, apple/review-details, apple/status, art, lib/store-apps, listing-store, onboard, validate | | `apps_appStoreVersions_getToManyRelationship` | GET | `/v1/apps/{id}/relationships/appStoreVersions` | read | | | `apps_appTags_getToManyRelated` | GET | `/v1/apps/{id}/appTags` | read | | | `apps_appTags_getToManyRelationship` | GET | `/v1/apps/{id}/relationships/appTags` | read | | diff --git a/docs/drafts/header-search-results-announcement.md b/docs/drafts/header-search-results-announcement.md new file mode 100644 index 0000000..d918f54 --- /dev/null +++ b/docs/drafts/header-search-results-announcement.md @@ -0,0 +1,29 @@ +# Draft: Header and Search Results support (not posted) + +## Release tweet + +storebound now fills App Store Connect's new Header and Search Results: a 21:9 product page header and a 3:2 search +results asset per language, image or video, checked locally, uploaded once, selected on the version and added to the +draft review submission. You still press Submit. `storebound apple creative-assets --dry` + +## Announcement + +**App Store Header and Search Results, end to end** + +Since October 2026, App Store Connect has a Header and Search Results tab next to App Previews and Screenshots. On +iOS and iPadOS 27 these assets show at the top of the product page and in search results. + +`storebound apple creative-assets` handles the whole flow through the App Store Connect API: + +- **Checks before upload.** Header 3840 x 1646 (21:9), search results 3:2 (1920 x 1280 up to 3840 x 2560), or one + universal 5244 x 2950 PNG for both. No alpha. Videos run 5-30 s at 30 or 60 fps, and search videos play muted. +- **Upserts into the Asset Library.** Each file goes up once, matched by MD5. Re-runs send nothing. Archived copies are + restored instead of uploaded again, and a file App Review rejected is never re-sent. +- **Selects the assets on the version** once they are processed, as the console's Browse Assets does. No waiting on an + approval that only a submission can start. +- **`--add-for-review`** puts the new assets into the draft review submission, along with your first version or on + their own after that. storebound never submits; Submit for Review stays your button. +- **`--verify`** reads every slot back without writing and fails if a slot does not show your local file. + +Dry run by default over MCP (`apple_creative_assets`, `apple_creative_assets_verify`). Google Play has no such slot. +The feature graphic and promo video are the closest match there. diff --git a/docs/store-art.md b/docs/store-art.md index bafe71d..65bf0d0 100644 --- a/docs/store-art.md +++ b/docs/store-art.md @@ -98,11 +98,19 @@ Screenshots". Optional: without these assets the App Store uses in-app events, a play muted. `apple.creativeAssets.header: false` / `search: false` skips a slot. - **Not rendered by `shots render`**: the scene templates are portrait device shots; make the wide art yourself (or from the feature graphic artwork at the larger size) and drop it in. -- **Upload:** `storebound apple creative-assets --dry`, then without `--dry`. Files go into the app's Asset Library - (API: `appAssetLibraryImages` / `appAssetLibraryVideos`, category `CREATIVE_ASSETS`); Apple reviews each asset, and - only an approved one is selected for the slot (`appAssetLibraryPlacements`, `PRODUCT_PAGE_HEADER_ASSET` / - `APP_STORE_SEARCH_RESULTS_ASSET`). Until then the run says "waiting for Apple's approval": re-run later. Same file - (MD5) = nothing sent. MCP: `apple_creative_assets` (dry by default). +- **Upload and select:** `storebound apple creative-assets --dry`, then without `--dry`. Files go into the app's Asset + Library (API: `appAssetLibraryImages` / `appAssetLibraryVideos`, category `CREATIVE_ASSETS`), and once processed + ("Prepare for Submission", a bounded wait of 2 minutes with a heartbeat) the run selects them for the slots of the + editable version (`appAssetLibraryPlacements`, `PRODUCT_PAGE_HEADER_ASSET` / `APP_STORE_SEARCH_RESULTS_ASSET`), as the + console's Browse Assets > Save does. Approval is not needed first. Same file (MD5) = nothing sent; an archived copy is + unarchived; a file App Review rejected is never uploaded again (change the file). MCP: `apple_creative_assets` (dry by + default). +- **Review:** an asset is reviewed only once it is in a review submission (its own item, `appAssetLibraryImage` / + `appAssetLibraryVideo`; the console's "Add for Review"). `--add-for-review` adds the selected, unreviewed assets to the + app's draft submission, once: before the first approved version it is the same submission as that version, later + they can go alone. Pressing Submit for Review stays the owner's. +- **Verify:** `storebound apple creative-assets --verify` (MCP `apple_creative_assets_verify`) is read-only: every slot + of the editable version (else the live one) shows the local file, with its review state; exit 1 when one differs. - **Checks:** `storebound check` and `validate` print an info note when no locale has one. - **Play:** no such slot. The feature graphic (1024 x 500, `play images`) and the promo video (YouTube URL) are the closest equivalents. diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 0479986..fb68278 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -913,15 +913,22 @@ that fails without the fix (see CONTRIBUTING.md). `screenshots-duo` note in check / validate. `tests/ppo.test.ts`. ## 76. Header and Search Results assets are not uploaded like screenshots -- **Symptom:** a header or search results image was "uploaded" but the version page still says "Browse approved - assets to select a header asset", or a re-run uploaded the same file again. +- **Symptom:** a header or search results image was "uploaded" but the version page shows no header, a run kept saying + "waiting for Apple's approval" for days, or a re-run uploaded the same file again. - **Cause:** these slots take assets from the app's Asset Library (`GET /v1/apps/{id}/assetLibrary`), not a set of - their own. Each asset is reviewed by Apple first; only an APPROVED asset can be selected (an - `appAssetLibraryPlacements` row with `PRODUCT_PAGE_HEADER_ASSET` or `APP_STORE_SEARCH_RESULTS_ASSET` and the version - localization). Library assets carry no `sourceFileChecksum`, and the write-ups' name for the search slot is the - API's `APP_STORE_SEARCH_RESULTS_ASSET` (`SEARCH_RESULTS_ADS_ASSET` is the Apple Ads one). -- **Do:** `storebound apple creative-assets`: it keeps the file's MD5 in `referenceName` ("storebound "), reuses - a library asset with the same MD5, selects only approved ones and says "waiting for Apple's approval" otherwise. - Uploading and selecting are normal steps, not owner buttons; the version's Submit for Review stays the owner's. -- **Guard:** `cli/apple/creative-assets.ts`, `tests/creative-assets.test.ts` (fake App Store Connect: dry run, upload, - waiting, select, replace on a changed file, nothing on the same file). + their own: a slot is an `appAssetLibraryPlacements` row (`PRODUCT_PAGE_HEADER_ASSET` or + `APP_STORE_SEARCH_RESULTS_ASSET`, the version localization). An asset is reviewed only once it is in a review + submission (its own item, `reviewSubmissionItems` with `appAssetLibraryImage` / `appAssetLibraryVideo`; the console's + "Add for Review"). Apple's "App Store asset statuses": a processed asset is "Prepare for Submission" and can already + be selected for a version. So an earlier storebound that selected only APPROVED assets waited forever: nothing ever + sent the asset to review. Library assets carry no `sourceFileChecksum`, a rejected asset stays rejected (uploading + the same bytes again only adds a copy), and the search slot is the API's `APP_STORE_SEARCH_RESULTS_ASSET` + (`SEARCH_RESULTS_ADS_ASSET` is the Apple Ads one). +- **Do:** `storebound apple creative-assets`: MD5 in `referenceName` ("storebound "), reuse (or unarchive) a library + asset with the same MD5, select it once processed, never re-upload a rejected file or one that failed processing + twice. Then `--add-for-review` puts the unreviewed assets into the draft submission (with the first version, or alone + once the app has an approved version) and `--verify` reads every slot back. Uploading, selecting and adding to the + draft are normal steps, not owner buttons; Submit for Review stays the owner's. +- **Guard:** `cli/apple/creative-assets.ts` (`classify`, `pickAsset`, `processingTiming`), `tests/creative-assets.test.ts` + (fake App Store Connect: upload and select in one run, still processing, rejected / archived files, add-for-review + without submitting, verify read-only); the fake commits library assets to PREPARE_FOR_SUBMISSION, as Apple does. diff --git a/skills/store-screenshots/SKILL.md b/skills/store-screenshots/SKILL.md index 5a223c7..02c9a1f 100644 --- a/skills/store-screenshots/SKILL.md +++ b/skills/store-screenshots/SKILL.md @@ -207,11 +207,19 @@ Screenshots". Optional: without these assets the App Store uses in-app events, a play muted. `apple.creativeAssets.header: false` / `search: false` skips a slot. - **Not rendered by `shots render`**: the scene templates are portrait device shots; make the wide art yourself (or from the feature graphic artwork at the larger size) and drop it in. -- **Upload:** `storebound apple creative-assets --dry`, then without `--dry`. Files go into the app's Asset Library - (API: `appAssetLibraryImages` / `appAssetLibraryVideos`, category `CREATIVE_ASSETS`); Apple reviews each asset, and - only an approved one is selected for the slot (`appAssetLibraryPlacements`, `PRODUCT_PAGE_HEADER_ASSET` / - `APP_STORE_SEARCH_RESULTS_ASSET`). Until then the run says "waiting for Apple's approval": re-run later. Same file - (MD5) = nothing sent. MCP: `apple_creative_assets` (dry by default). +- **Upload and select:** `storebound apple creative-assets --dry`, then without `--dry`. Files go into the app's Asset + Library (API: `appAssetLibraryImages` / `appAssetLibraryVideos`, category `CREATIVE_ASSETS`), and once processed + ("Prepare for Submission", a bounded wait of 2 minutes with a heartbeat) the run selects them for the slots of the + editable version (`appAssetLibraryPlacements`, `PRODUCT_PAGE_HEADER_ASSET` / `APP_STORE_SEARCH_RESULTS_ASSET`), as the + console's Browse Assets > Save does. Approval is not needed first. Same file (MD5) = nothing sent; an archived copy is + unarchived; a file App Review rejected is never uploaded again (change the file). MCP: `apple_creative_assets` (dry by + default). +- **Review:** an asset is reviewed only once it is in a review submission (its own item, `appAssetLibraryImage` / + `appAssetLibraryVideo`; the console's "Add for Review"). `--add-for-review` adds the selected, unreviewed assets to the + app's draft submission, once: before the first approved version it is the same submission as that version, later + they can go alone. Pressing Submit for Review stays the owner's. +- **Verify:** `storebound apple creative-assets --verify` (MCP `apple_creative_assets_verify`) is read-only: every slot + of the editable version (else the live one) shows the local file, with its review state; exit 1 when one differs. - **Checks:** `storebound check` and `validate` print an info note when no locale has one. - **Play:** no such slot. The feature graphic (1024 x 500, `play images`) and the promo video (YouTube URL) are the closest equivalents. diff --git a/tests/apple-name.test.ts b/tests/apple-name.test.ts index 980095d..2a84762 100644 --- a/tests/apple-name.test.ts +++ b/tests/apple-name.test.ts @@ -54,7 +54,8 @@ describe('apple.name', () => { expect((j.hints as string[]).join('\n')).toContain('already being used'); p = project({ ...NAMED, play: undefined }, files); j = jsonOut((await capture(() => check(p.ctx(['--json'], ['json'])))).out); - expect(j.hints).toEqual([]); + // only the name hint is under test (the Duo and Header and Search Results notes are hints of their own) + expect((j.hints as string[]).filter(h => /App Store name|already being used/.test(h))).toEqual([]); p = project({ ...PLAIN, app: { ...PLAIN.app, name: 'STAR DASH Stone Age to the Year 2100' }, play: undefined }, files); const r = await capture(() => check(p.ctx(['--json'], ['json']))); j = jsonOut(r.out); diff --git a/tests/creative-assets.test.ts b/tests/creative-assets.test.ts index 1239a96..fa7b49a 100644 --- a/tests/creative-assets.test.ts +++ b/tests/creative-assets.test.ts @@ -1,9 +1,10 @@ // App Store "Header and Search Results" creative assets: local size / alpha / video checks, the check / validate note, -// and `apple creative-assets` against the fake App Store Connect (Asset Library upload, approval wait, select, replace -// on a changed file, nothing on the same file). +// and `apple creative-assets` against the fake App Store Connect (Asset Library upload, select once processed (no +// approval wait: pitfall 76), replace on a changed file, nothing on the same file, rejected / failed / archived files, +// --add-for-review into the draft submission without submitting, --verify read-only). import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test'; import { md5 } from '../cli/apple/asc'; -import { REF, run } from '../cli/apple/creative-assets'; +import { classify, MAX_FAILED, pickAsset, processingTiming, REF, run, selectable } from '../cli/apple/creative-assets'; import { checkCreativeImage, checkCreativeVideo, CREATIVE_NOTE, creativeFiles, creativeNote } from '../cli/shots/creative'; import { imageInfo } from '../cli/shots/spec'; import { upsertTiming } from '../cli/lib/upsert'; @@ -62,11 +63,31 @@ describe('creative asset checks', () => { }); }); +describe('asset states (pitfall 76: Prepare for Submission is selectable)', () => { + test('classify and selectable', () => { + expect(['AWAITING_UPLOAD', 'UPLOAD_COMPLETE', undefined].map(classify)).toEqual(['processing', 'processing', 'processing']); + expect(selectable(classify('PREPARE_FOR_SUBMISSION'))).toBe(true); + expect(selectable(classify('APPROVED'))).toBe(true); + expect(selectable(classify('IN_REVIEW'))).toBe(true); + for (const s of ['FAILED', 'REJECTED', 'ARCHIVED', 'UPLOAD_COMPLETE']) expect(selectable(classify(s))).toBe(false); + }); + const a = (id: string, sum: string, state: string, stateDetails?: unknown[]) => ({ id, type: 'appAssetLibraryImages', attributes: { referenceName: REF(sum), state, stateDetails } }); + const S = 'a'.repeat(32); + test('pickAsset: reviewed beats unreviewed, archived is unarchived, rejected and repeated failures refuse', () => { + expect(pickAsset([a('1', S, 'PREPARE_FOR_SUBMISSION'), a('2', S, 'APPROVED')], S).asset!.id).toBe('2'); + expect(pickAsset([a('1', S, 'ARCHIVED')], S)).toMatchObject({ unarchive: true }); + expect(pickAsset([a('1', S, 'REJECTED', [{ code: 'GUIDELINE_2_3' }])], S).refuse).toContain('GUIDELINE_2_3'); + expect(pickAsset([a('1', S, 'FAILED')], S)).toEqual({}); + expect(pickAsset(Array.from({ length: MAX_FAILED }, (_, i) => a(String(i), S, 'FAILED')), S).refuse).toContain('failed processing'); + expect(pickAsset([a('1', 'b'.repeat(32), 'APPROVED')], S)).toEqual({}); + }); +}); + describe('apple creative-assets against the fake App Store Connect', () => { let s: Stores; beforeAll(ascEnv); afterAll(restore); - beforeEach(() => { upsertTiming.waitMs = 0; s = installStores(); }); + beforeEach(() => { upsertTiming.waitMs = 0; processingTiming.timeoutMs = 0; processingTiming.pollMs = 0; s = installStores(); }); afterEach(uninstallStores); const APP = '6400000101'; const CFG = { ...BASE, languages: [{ id: 'en', apple: 'en-US', play: 'en-US' }] }; @@ -76,47 +97,84 @@ describe('apple creative-assets against the fake App Store Connect', () => { s.asc.put({ type: 'appStoreVersionLocalizations', id: 'loc-en', attributes: { locale: 'en-US' }, rels: { appStoreVersion: 'ver-1' } }); return project(CFG, files); }; - const go = async (p: ReturnType, argv: string[] = []) => { + const go = async (p: ReturnType, argv: string[] = [], exit = 0) => { const a = s.calls.length; const r = await capture(() => run(p.ctx(argv))); - if (r.exit) throw new Error(`exit ${r.exit}: ${r.out}\n${r.err}`); - return { out: r.out, w: writes(s.calls.slice(a)).map(c => `${c.method} ${decodeURIComponent(c.path).replace(/\?.*/, '').replace(/\/v1\/(\w+)\/[^/]+$/, '/v1/$1/{id}')}`).filter(x => x.includes(' /v1/')) }; + if ((r.exit ?? 0) !== exit) throw new Error(`exit ${r.exit}: ${r.out}\n${r.err}`); + return { out: r.out + r.err, w: writes(s.calls.slice(a)).map(c => `${c.method} ${decodeURIComponent(c.path).replace(/\?.*/, '').replace(/\/v1\/(\w+)\/[^/]+$/, '/v1/$1/{id}')}`).filter(x => x.includes(' /v1/')) }; }; - const approve = () => { for (const t of ['appAssetLibraryImages', 'appAssetLibraryVideos']) for (const x of s.asc.all(t)) x.attributes.state = 'APPROVED'; }; - - test('dry run, upload, wait for approval, select, same file = nothing, changed file = replace', async () => { - const header = png(3840, 1646, false, 1); - const p = setup({ 'store/renders/en/creative/header.png': header, 'store/renders/en/creative/search.png': png(1920, 1280, false, 2) }); + const lib = () => [...s.asc.all('appAssetLibraryImages'), ...s.asc.all('appAssetLibraryVideos')]; + const files = (h = 1, q = 2) => ({ 'store/renders/en/creative/header.png': png(3840, 1646, false, h), 'store/renders/en/creative/search.png': png(1920, 1280, false, q) }); + test('dry run, upload + select in one run (no approval wait), same file = nothing, changed file = replace', async () => { + const p = setup(files()); const dry = await go(p, ['--dry']); expect(dry.w).toEqual([]); expect(dry.out).toContain('would upload header.png'); const first = await go(p); - expect(first.w).toEqual(['POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}', 'POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}']); - expect(first.out).toContain("waiting for Apple's approval"); - expect(s.asc.all('appAssetLibraryImages').map(x => x.attributes.referenceName)).toContain(REF(md5(header))); - expect(s.asc.all('appAssetLibraryPlacements')).toHaveLength(0); - - const again = await go(p); - expect(again.w).toEqual([]); // still waiting: no second upload - - approve(); - const sel = await go(p); - expect(sel.w).toEqual(['POST /v1/appAssetLibraryPlacements', 'POST /v1/appAssetLibraryPlacements']); + expect(first.w).toEqual(['POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}', 'POST /v1/appAssetLibraryPlacements', + 'POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}', 'POST /v1/appAssetLibraryPlacements']); + expect(lib().map(x => x.attributes.referenceName)).toContain(REF(md5(files()['store/renders/en/creative/header.png']))); expect(s.asc.all('appAssetLibraryPlacements').map(x => x.attributes.placementType).sort()).toEqual(['APP_STORE_SEARCH_RESULTS_ASSET', 'PRODUCT_PAGE_HEADER_ASSET']); + expect(first.out).toContain('--add-for-review'); + expect(first.out).not.toContain("waiting for Apple's approval"); expect((await go(p)).w).toEqual([]); - // a changed header: uploaded, selected only after approval, then the old placement is replaced - const q = project(CFG, { 'store/renders/en/creative/header.png': png(3840, 1646, false, 9), 'store/renders/en/creative/search.png': png(1920, 1280, false, 2) }); - expect((await go(q)).w).toEqual(['POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}']); - approve(); + const q = project(CFG, files(9)); const rep = await go(q); - expect(rep.w).toEqual(['DELETE /v1/appAssetLibraryPlacements/{id}', 'POST /v1/appAssetLibraryPlacements']); + expect(rep.w).toEqual(['POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}', 'DELETE /v1/appAssetLibraryPlacements/{id}', 'POST /v1/appAssetLibraryPlacements']); expect(s.asc.all('appAssetLibraryPlacements')).toHaveLength(2); }); + test('processing that outlasts the bounded wait: not selected, re-run selects without a second upload', async () => { + const f = files(); + const p = setup(f); + for (const [k, id] of [['header', 'img-h'], ['search', 'img-s']] as const) + s.asc.put({ type: 'appAssetLibraryImages', id, attributes: { category: 'CREATIVE_ASSETS', referenceName: REF(md5(f[`store/renders/en/creative/${k}.png`])), state: 'UPLOAD_COMPLETE', fileName: `${k}.png` }, rels: { assetLibrary: 'lib-1' } }); + const r1 = await go(p); + expect(r1.w).toEqual([]); + expect(r1.out).toContain('still UPLOAD_COMPLETE'); + expect(r1.out).toContain('2 still processing'); + for (const x of lib()) x.attributes.state = 'PREPARE_FOR_SUBMISSION'; + expect((await go(p)).w).toEqual(['POST /v1/appAssetLibraryPlacements', 'POST /v1/appAssetLibraryPlacements']); + }); + + test('a rejected file is not uploaded again; an archived one is unarchived, not re-uploaded', async () => { + const f = files(); + const p = setup(f); + s.asc.put({ type: 'appAssetLibraryImages', id: 'img-rej', attributes: { category: 'CREATIVE_ASSETS', referenceName: REF(md5(f['store/renders/en/creative/header.png'])), state: 'REJECTED', fileName: 'header.png' }, rels: { assetLibrary: 'lib-1' } }); + s.asc.put({ type: 'appAssetLibraryImages', id: 'img-arc', attributes: { category: 'CREATIVE_ASSETS', referenceName: REF(md5(f['store/renders/en/creative/search.png'])), state: 'ARCHIVED', fileName: 'search.png' }, rels: { assetLibrary: 'lib-1' } }); + const r = await go(p, [], 1); + expect(r.out).toContain('rejected by App Review'); + expect(r.w).toEqual(['PATCH /v1/appAssetLibraryImages/{id}', 'POST /v1/appAssetLibraryPlacements']); + expect(s.asc.all('appAssetLibraryPlacements').map(x => x.attributes.placementType)).toEqual(['APP_STORE_SEARCH_RESULTS_ASSET']); + }); + + test('--add-for-review: unreviewed assets go into the draft once, nothing is submitted', async () => { + const p = setup(files()); + await go(p); + const dry = await go(p, ['--add-for-review', '--dry']); + expect(dry.w).toEqual([]); + const add = await go(p, ['--add-for-review']); + expect(add.w).toEqual(['POST /v1/reviewSubmissions', 'POST /v1/reviewSubmissionItems', 'POST /v1/reviewSubmissionItems']); + expect(add.out).toContain('nothing was submitted'); + expect(add.w.some(x => x.startsWith('PATCH /v1/reviewSubmissions'))).toBe(false); + expect((await go(p, ['--add-for-review'])).w).toEqual([]); + }); + + test('--verify is read-only and fails on a slot that differs', async () => { + const p = setup(files()); + const before = await go(p, ['--verify'], 1); + expect(before.w).toEqual([]); + expect(before.out).toContain('shows nothing, wanted header.png'); + await go(p); + const ok = await go(p, ['--verify']); + expect(ok.w).toEqual([]); + expect(ok.out).toContain('every slot shows the local file'); + }); + test('a bad file stops the run before any call', async () => { const p = setup({ 'store/renders/en/creative/header.png': png(3840, 1600, true) }); const a = s.calls.length; diff --git a/tests/helpers/fake-stores.ts b/tests/helpers/fake-stores.ts index bf45d8c..9ef43e1 100644 --- a/tests/helpers/fake-stores.ts +++ b/tests/helpers/fake-stores.ts @@ -102,7 +102,8 @@ const UNIQUE: Record string> = { betaTesters: r => String(r.attributes.email).toLowerCase(), }; const ASSETS = /Screenshots$|^appPreviews$|^appScreenshots$|^appAssetLibrary(Images|Videos)$/; -/** App Asset Library assets: a state of their own (AWAITING_UPLOAD -> WAITING_FOR_REVIEW after the commit; a test sets APPROVED). */ +/** App Asset Library assets: a state of their own (AWAITING_UPLOAD -> PREPARE_FOR_SUBMISSION after the commit, as Apple's + * "App Store asset statuses" describe it: processed, not in a submission yet; a test sets the review states). */ const LIBRARY = /^appAssetLibrary(Images|Videos)$/; /** Attributes a new resource of a type starts with. */ const DEFAULTS: Record> = { @@ -310,9 +311,14 @@ export class FakeAsc { rels: { [singular(self.type)]: self.id, ...Object.fromEntries(Object.entries(inc.relationships ?? {}).map(([k, v]) => [k, v.data.id])) } }); if (attrs.uploaded === true && ASSETS.test(self.type)) { const { uploaded: _u, ...rest } = attrs; - if (LIBRARY.test(self.type)) Object.assign(self.attributes, rest, { state: this.parts.includes(self.id) ? 'WAITING_FOR_REVIEW' : 'FAILED' }); + if (LIBRARY.test(self.type)) Object.assign(self.attributes, rest, { state: this.parts.includes(self.id) ? 'PREPARE_FOR_SUBMISSION' : 'FAILED' }); else Object.assign(self.attributes, rest, { assetDeliveryState: { state: this.parts.includes(self.id) ? 'COMPLETE' : 'FAILED' } }); delete self.attributes.uploadOperations; + } else if (LIBRARY.test(self.type) && typeof attrs.archived === 'boolean') { + // archive / unarchive (model: an unarchived asset is back in Prepare for Submission) + const { archived, ...rest } = attrs; + Object.assign(self.attributes, rest, { state: archived ? 'ARCHIVED' : 'PREPARE_FOR_SUBMISSION' }); + delete self.attributes.archived; } else if (self.type === 'reviewSubmissions' && (attrs.submitted === true || attrs.canceled === true)) { // seen live (2026-10-12): a REJECTED item that is not marked resolved blocks every submit with this 409, and an // empty draft cannot be canceled From c03291e7f7429dab8a2ee37558d123d2d4bbe4d0 Mon Sep 17 00:00:00 2001 From: CRT Date: Mon, 19 Oct 2026 05:45:47 +0700 Subject: [PATCH 027/344] apple creative-assets: a live app without an editable version uses the live version (only approved assets are selected there; new ones upload and wait for a review of their own via --add-for-review); pitfall 76: placements read back ACTIVE live, a state the 4.5.1 spec does not list --- CHANGELOG.md | 4 +++- cli/apple/creative-assets.ts | 28 +++++++++++++++++++--------- docs/store-art.md | 4 ++++ skills/store-pitfalls/SKILL.md | 7 +++++-- skills/store-screenshots/SKILL.md | 4 ++++ tests/creative-assets.test.ts | 14 ++++++++++++++ 6 files changed, 49 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e62234e..6790cdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,9 @@ a heartbeat). `--add-for-review` adds the selected, unreviewed assets to the app's draft review submission (never submits; Submit for Review stays the owner's); `--verify` (MCP `apple_creative_assets_verify`) reads every slot back read-only and fails when one differs from the local file. A file App Review rejected, or one that failed processing - twice, is not uploaded again; an archived copy of the same file is unarchived instead of uploaded. Pitfall 76 rewritten. + twice, is not uploaded again; an archived copy of the same file is unarchived instead of uploaded. A live app without + an editable version uses the live version: approved assets are selected there, new ones are uploaded and wait for a + review of their own. Pitfall 76 rewritten. ## 0.8.13 · 2026-10-18 diff --git a/cli/apple/creative-assets.ts b/cli/apple/creative-assets.ts index 37f1b0d..2c09d4a 100644 --- a/cli/apple/creative-assets.ts +++ b/cli/apple/creative-assets.ts @@ -90,7 +90,7 @@ const reason = (a: J): string => { /** Bounded wait for processing (every wait has a timeout and a heartbeat); tests set waitMs 0 / timeoutMs 0. */ export const processingTiming = { pollMs: 3000, timeoutMs: 120_000, heartbeatMs: 20_000, sleep: (ms: number): Promise => (ms > 0 ? rt.sleep(ms) : Promise.resolve()) }; -export interface Row { locale: string; placement: Placement; file: string; action: 'keep' | 'upload' | 'wait' | 'select' | 'replace' | 'refuse'; state?: string; asset?: J } +export interface Row { locale: string; placement: Placement; file: string; action: 'keep' | 'upload' | 'wait' | 'select' | 'replace' | 'approve' | 'refuse'; state?: string; asset?: J } /** Local files per App Store locale, checked; throws on any error before a network call. */ export function localCreative(ctx: Ctx): { src: string; local: Map } { @@ -138,9 +138,14 @@ export async function run(ctx: Ctx): Promise { const lib = (await c.asc('GET', `/v1/apps/${appId}/assetLibrary`)).data as J; const live = async () => (await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=50`)) .find(v => (v.attributes.appVersionState ?? v.attributes.appStoreState) === 'READY_FOR_DISTRIBUTION' || v.attributes.appStoreState === 'READY_FOR_SALE') ?? null; - // --verify falls back to the live version (read-only); writes need the editable one - const version = await c.editableVersion() ?? (verify ? await live() : null); - if (!version) throw new Error(`no editable App Store version: the header and search results slots belong to a version page (run apple listing --version x.y.z first). ${consoleLink('asc.version')}`); + // No editable version: the live one. Apple lets an approved asset be swapped onto the live version without a new + // build, and an app with an approved version can send assets to review alone; so there only APPROVED assets are + // selected, and the others wait for their review (--add-for-review puts them into a submission of their own). + const editable = await c.editableVersion(); + const version = editable ?? await live(); + const onLive = !editable; + if (!version) throw new Error(`no editable or live App Store version: the header and search results slots belong to a version page (run apple listing --version x.y.z first). ${consoleLink('asc.version')}`); + if (onLive && !verify) log(TAG, `no editable version: using the live version ${version.attributes.versionString}, where only approved assets can be selected`); const locs = await c.all(`/v1/appStoreVersions/${version.id}/appStoreVersionLocalizations?limit=50`); const library = async (): Promise => [ ...(await c.all(`/v1/appAssetLibraries/${lib.id}/images?filter[category]=CREATIVE_ASSETS&limit=200`)), @@ -197,7 +202,7 @@ export async function run(ctx: Ctx): Promise { if (pick.refuse) { warn(TAG, `${tag}: ${basename(f.file)} ${pick.refuse}`); row('refuse'); continue; } let asset = pick.asset; if (!asset) { - if (dry) { log(TAG, `${tag}: would upload ${basename(f.file)} to the Asset Library and select it once processed`); row('upload'); continue; } + if (dry) { log(TAG, `${tag}: would upload ${basename(f.file)} to the Asset Library and select it ${onLive ? 'on the live version once approved' : 'once processed'}`); row('upload'); continue; } log(TAG, `${tag}: uploading ${basename(f.file)} to the Asset Library`); asset = await upload(f, sum); assets = await library(); @@ -214,6 +219,10 @@ export async function run(ctx: Ctx): Promise { if (cls === 'processing') { row('wait', asset); continue; } warn(TAG, `${tag}: ${basename(f.file)} is ${asset.attributes?.state}${reason(asset)}; not selected`); row('refuse', asset); continue; } + if (onLive && asset.attributes?.state !== 'APPROVED') { + log(TAG, `${tag}: ${basename(f.file)} is ${asset.attributes?.state} in the Asset Library; the live version takes it once App Review approved it (re-run then)`); + row('approve', asset); continue; + } const action = placed.length ? 'replace' : 'select'; if (dry) { log(TAG, `${tag}: would ${action === 'replace' ? `replace ${placed.length} selected asset(s) with` : 'select'} ${basename(f.file)} (${asset.attributes?.state})`); row(action, asset); continue; } for (const p of placed) await c.asc('DELETE', `/v1/appAssetLibraryPlacements/${p.id}`); @@ -234,9 +243,11 @@ export async function run(ctx: Ctx): Promise { } if (off) process.exitCode = 1; - // review: one item per distinct unreviewed asset in a slot + const n = (a: Row['action'][]) => rows.filter(r => a.includes(r.action)).length; + // review: one item per distinct unreviewed asset (in a slot, or waiting for approval to go onto the live version) const unreviewed = new Map(); for (const r of rows) if (r.asset && r.action !== 'refuse' && r.action !== 'wait' && classify(r.asset.attributes?.state) === 'unreviewed') unreviewed.set(r.asset.id, r.asset); + const approve = n(['approve']); let added = 0; if (unreviewed.size && forReview) { const kindOf = (a: J) => (a.type === 'appAssetLibraryVideos' ? 'appAssetLibraryVideo' : 'appAssetLibraryImage'); @@ -250,12 +261,11 @@ export async function run(ctx: Ctx): Promise { log(TAG, `${added} creative asset(s) added to draft review submission ${sid}; nothing was submitted`); } } - const n = (a: Row['action'][]) => rows.filter(r => a.includes(r.action)).length; - const summary = `creative assets: ${n(['keep'])} up to date, ${n(['select', 'replace'])} ${dry ? 'to select' : 'selected'}, ${n(['upload'])} to upload, ${n(['wait'])} still processing, ${n(['refuse'])} refused${off ? `, ${off} did not read back` : ''}`; + const summary = `creative assets: ${n(['keep'])} up to date, ${n(['select', 'replace'])} ${dry ? 'to select' : 'selected'}, ${n(['upload'])} to upload, ${n(['wait'])} still processing, ${approve ? `${approve} waiting for App Review (live version), ` : ''}${n(['refuse'])} refused${off ? `, ${off} did not read back` : ''}`; if (unreviewed.size) { log(TAG, forReview ? `owner step: Submit for Review with the version (or alone once the app has an approved version): ${consoleLink('asc.app-review')}` - : `${unreviewed.size} selected asset(s) are not reviewed yet ("Prepare for Submission"): run with --add-for-review to put them into the draft review submission (the version's, or alone once the app has an approved version); Submit for Review stays the owner's: ${consoleLink('asc.app-review')}`); + : `${unreviewed.size} asset(s) are not reviewed yet ("Prepare for Submission"): run with --add-for-review to put them into the draft review submission (the version's, or alone once the app has an approved version); Submit for Review stays the owner's: ${consoleLink('asc.app-review')}`); } if (n(['refuse'])) process.exitCode = 1; return done(TAG, dry ? `${summary} (dry run, nothing sent)` : summary); diff --git a/docs/store-art.md b/docs/store-art.md index 65bf0d0..77ab175 100644 --- a/docs/store-art.md +++ b/docs/store-art.md @@ -109,6 +109,10 @@ Screenshots". Optional: without these assets the App Store uses in-app events, a `appAssetLibraryVideo`; the console's "Add for Review"). `--add-for-review` adds the selected, unreviewed assets to the app's draft submission, once: before the first approved version it is the same submission as that version, later they can go alone. Pressing Submit for Review stays the owner's. +- **Live app, no editable version:** the run uses the live version, where only APPROVED assets are selected (Apple + swaps approved assets onto a live version without a new build). New files are uploaded and wait for review: + `--add-for-review` sends them as a submission of their own (the app has an approved version), the owner presses + Submit for Review, and a re-run after approval selects them. - **Verify:** `storebound apple creative-assets --verify` (MCP `apple_creative_assets_verify`) is read-only: every slot of the editable version (else the live one) shows the local file, with its review state; exit 1 when one differs. - **Checks:** `storebound check` and `validate` print an info note when no locale has one. diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index fb68278..174df6a 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -923,11 +923,14 @@ that fails without the fix (see CONTRIBUTING.md). be selected for a version. So an earlier storebound that selected only APPROVED assets waited forever: nothing ever sent the asset to review. Library assets carry no `sourceFileChecksum`, a rejected asset stays rejected (uploading the same bytes again only adds a copy), and the search slot is the API's `APP_STORE_SEARCH_RESULTS_ASSET` - (`SEARCH_RESULTS_ADS_ASSET` is the Apple Ads one). + (`SEARCH_RESULTS_ADS_ASSET` is the Apple Ads one). Seen live (19 Oct 2026): placements of a live version read back + with state `ACTIVE`, which the 4.5.1 spec's `AppAssetLibraryPlacementState` does not list; never validate placement + states against the spec enum. - **Do:** `storebound apple creative-assets`: MD5 in `referenceName` ("storebound "), reuse (or unarchive) a library asset with the same MD5, select it once processed, never re-upload a rejected file or one that failed processing twice. Then `--add-for-review` puts the unreviewed assets into the draft submission (with the first version, or alone - once the app has an approved version) and `--verify` reads every slot back. Uploading, selecting and adding to the + once the app has an approved version) and `--verify` reads every slot back. With no editable version the live version + is used and only APPROVED assets go onto it; the rest wait for their own review. Uploading, selecting and adding to the draft are normal steps, not owner buttons; Submit for Review stays the owner's. - **Guard:** `cli/apple/creative-assets.ts` (`classify`, `pickAsset`, `processingTiming`), `tests/creative-assets.test.ts` (fake App Store Connect: upload and select in one run, still processing, rejected / archived files, add-for-review diff --git a/skills/store-screenshots/SKILL.md b/skills/store-screenshots/SKILL.md index 02c9a1f..de05ca4 100644 --- a/skills/store-screenshots/SKILL.md +++ b/skills/store-screenshots/SKILL.md @@ -218,6 +218,10 @@ Screenshots". Optional: without these assets the App Store uses in-app events, a `appAssetLibraryVideo`; the console's "Add for Review"). `--add-for-review` adds the selected, unreviewed assets to the app's draft submission, once: before the first approved version it is the same submission as that version, later they can go alone. Pressing Submit for Review stays the owner's. +- **Live app, no editable version:** the run uses the live version, where only APPROVED assets are selected (Apple + swaps approved assets onto a live version without a new build). New files are uploaded and wait for review: + `--add-for-review` sends them as a submission of their own (the app has an approved version), the owner presses + Submit for Review, and a re-run after approval selects them. - **Verify:** `storebound apple creative-assets --verify` (MCP `apple_creative_assets_verify`) is read-only: every slot of the editable version (else the live one) shows the local file, with its review state; exit 1 when one differs. - **Checks:** `storebound check` and `validate` print an info note when no locale has one. diff --git a/tests/creative-assets.test.ts b/tests/creative-assets.test.ts index fa7b49a..4c4da94 100644 --- a/tests/creative-assets.test.ts +++ b/tests/creative-assets.test.ts @@ -175,6 +175,20 @@ describe('apple creative-assets against the fake App Store Connect', () => { expect(ok.out).toContain('every slot shows the local file'); }); + test('live version only (no editable one): upload, add for review alone, select once approved', async () => { + const p = setup(files()); + s.asc.all('appStoreVersions')[0]!.attributes.appVersionState = 'READY_FOR_DISTRIBUTION'; + const up = await go(p, ['--add-for-review']); + expect(up.out).toContain('using the live version 1.0.0'); + expect(up.w).toEqual(['POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}', 'POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}', + 'POST /v1/reviewSubmissions', 'POST /v1/reviewSubmissionItems', 'POST /v1/reviewSubmissionItems']); + expect(up.out).toContain('2 waiting for App Review (live version)'); + expect(s.asc.all('appAssetLibraryPlacements')).toHaveLength(0); + for (const x of lib()) x.attributes.state = 'APPROVED'; + expect((await go(p)).w).toEqual(['POST /v1/appAssetLibraryPlacements', 'POST /v1/appAssetLibraryPlacements']); + expect((await go(p, ['--verify'])).out).toContain('every slot shows the local file'); + }); + test('a bad file stops the run before any call', async () => { const p = setup({ 'store/renders/en/creative/header.png': png(3840, 1600, true) }); const a = s.calls.length; From 3542b897c8c504262c2c4adda06f268b371beb30 Mon Sep 17 00:00:00 2001 From: CRT Date: Mon, 19 Oct 2026 05:47:27 +0700 Subject: [PATCH 028/344] creative assets: /creative/header.* / search.* fill every language without its own file (art without words needs no copy per locale; one upload, placed per locale) --- CHANGELOG.md | 3 ++- cli/shots/creative.ts | 15 ++++++++++----- docs/store-art.md | 3 ++- skills/store-screenshots/SKILL.md | 3 ++- tests/creative-assets.test.ts | 5 +++++ 5 files changed, 21 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6790cdc..d4f68fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,8 @@ read-only and fails when one differs from the local file. A file App Review rejected, or one that failed processing twice, is not uploaded again; an archived copy of the same file is unarchived instead of uploaded. A live app without an editable version uses the live version: approved assets are selected there, new ones are uploaded and wait for a - review of their own. Pitfall 76 rewritten. + review of their own. Art without words needs no copy per locale: `/creative/header.png` / `search.*` + fill every language without its own file. Pitfall 76 rewritten. ## 0.8.13 · 2026-10-18 diff --git a/cli/shots/creative.ts b/cli/shots/creative.ts index d5828d6..65d36d7 100644 --- a/cli/shots/creative.ts +++ b/cli/shots/creative.ts @@ -2,8 +2,9 @@ // 27+): the product page header (21:9) and the search results asset (3:2), image or video, per locale, with one // universal 16:9 image (5244 x 2950) that can fill either slot. Apple's Creative assets specifications: // https://developer.apple.com/help/app-store-connect/reference/app-information/creative-assets-specifications/ -// Files: //creative/{header,search}.{png,jpg,jpeg,mov,m4v,mp4}; universal fallback -// //creative/universal.png or /creative/universal.png (every locale). +// Files: //creative/{header,search}.{png,jpg,jpeg,mov,m4v,mp4}, else the same names in +// /creative/ for every locale; universal fallback //creative/universal.png or +// /creative/universal.png (every locale). // API: App Asset Library (placement types PRODUCT_PAGE_HEADER_ASSET and APP_STORE_SEARCH_RESULTS_ASSET); see // cli/apple/creative-assets.ts. Play has no such slot: the feature graphic (1024 x 500) and the promo video are its // closest equivalents. @@ -29,16 +30,20 @@ export interface CreativeFile { placement: Placement; file: string; kind: 'image const EXT = /\.(png|jpe?g|mov|m4v|mp4)$/i; const kindOf = (f: string): 'image' | 'video' => (CREATIVE_RULES.video.ext.test(f) ? 'video' : 'image'); -/** The file for each placement of one language: own header / search file first, else the universal image. */ +/** The file for each placement of one language: its own header / search file first, then a shared one for every + * language (/creative/header.png: art without words needs no copy per locale), then the universal image. */ export function creativeFiles(renders: string, lang: string, list: (d: string) => string[] = d => (existsSync(d) ? readdirSync(d) : [])): CreativeFile[] { - const dir = join(renders, lang, 'creative'); + const dir = join(renders, lang, 'creative'), shared = join(renders, 'creative'); const own = list(dir).filter(f => EXT.test(f)).sort(); + const common = list(shared).filter(f => EXT.test(f)).sort(); const uni = own.find(f => /^universal\.png$/i.test(f)) ? join(dir, own.find(f => /^universal\.png$/i.test(f))!) - : list(join(renders, 'creative')).some(f => f === 'universal.png') ? join(renders, 'creative', 'universal.png') : undefined; + : common.includes('universal.png') ? join(shared, 'universal.png') : undefined; const out: CreativeFile[] = []; for (const p of ['header', 'search'] as Placement[]) { const f = own.find(x => x.toLowerCase().startsWith(`${p}.`)); + const g = common.find(x => x.toLowerCase().startsWith(`${p}.`)); if (f) out.push({ placement: p, file: join(dir, f), kind: kindOf(f), universal: false }); + else if (g) out.push({ placement: p, file: join(shared, g), kind: kindOf(g), universal: false }); else if (uni) out.push({ placement: p, file: uni, kind: 'image', universal: true }); } return out; diff --git a/docs/store-art.md b/docs/store-art.md index 77ab175..93ca1b2 100644 --- a/docs/store-art.md +++ b/docs/store-art.md @@ -93,7 +93,8 @@ Since 5 Oct 2026 the App Store version page has a "Header and Search Results" ta Screenshots". Optional: without these assets the App Store uses in-app events, app previews and screenshots. - **Files** under the renders folder, per language: `//creative/header.png` (3840 x 1646, 21:9), `search.png` (3:2, 1920 x 1280 up to 3840 x 2560), or one `universal.png` (5244 x 2950, 16:9) that fills either slot - (also `/creative/universal.png` for every locale, or `apple.creativeAssets.universal`). JPEG / PNG without + (also `/creative/universal.png` for every locale, or `apple.creativeAssets.universal`). Art without words + needs no copy per locale: `/creative/header.png` / `search.png` fill every language without its own file. JPEG / PNG without alpha. Videos instead: `header.mov|m4v|mp4` / `search.*`, 5-30 s, 30 or 60 fps, the same aspect ratio; search videos play muted. `apple.creativeAssets.header: false` / `search: false` skips a slot. - **Not rendered by `shots render`**: the scene templates are portrait device shots; make the wide art yourself (or from diff --git a/skills/store-screenshots/SKILL.md b/skills/store-screenshots/SKILL.md index de05ca4..b07203c 100644 --- a/skills/store-screenshots/SKILL.md +++ b/skills/store-screenshots/SKILL.md @@ -202,7 +202,8 @@ Since 5 Oct 2026 the App Store version page has a "Header and Search Results" ta Screenshots". Optional: without these assets the App Store uses in-app events, app previews and screenshots. - **Files** under the renders folder, per language: `//creative/header.png` (3840 x 1646, 21:9), `search.png` (3:2, 1920 x 1280 up to 3840 x 2560), or one `universal.png` (5244 x 2950, 16:9) that fills either slot - (also `/creative/universal.png` for every locale, or `apple.creativeAssets.universal`). JPEG / PNG without + (also `/creative/universal.png` for every locale, or `apple.creativeAssets.universal`). Art without words + needs no copy per locale: `/creative/header.png` / `search.png` fill every language without its own file. JPEG / PNG without alpha. Videos instead: `header.mov|m4v|mp4` / `search.*`, 5-30 s, 30 or 60 fps, the same aspect ratio; search videos play muted. `apple.creativeAssets.header: false` / `search: false` skips a slot. - **Not rendered by `shots render`**: the scene templates are portrait device shots; make the wide art yourself (or from diff --git a/tests/creative-assets.test.ts b/tests/creative-assets.test.ts index 4c4da94..07b5daa 100644 --- a/tests/creative-assets.test.ts +++ b/tests/creative-assets.test.ts @@ -53,6 +53,11 @@ describe('creative asset checks', () => { const fs = creativeFiles('/r', 'en', list); expect(fs.map(f => [f.placement, f.file, f.universal])).toEqual([['header', '/r/en/creative/header.png', false], ['search', '/r/creative/universal.png', true]]); }); + test('files: a shared /creative/header.png fills every language without its own', () => { + const list = (d: string) => (d === '/r/creative' ? ['header.png', 'search.mp4', 'universal.png'] : d === '/r/tr/creative' ? ['search.png'] : []); + expect(creativeFiles('/r', 'en', list).map(f => [f.placement, f.file, f.kind, f.universal])).toEqual([['header', '/r/creative/header.png', 'image', false], ['search', '/r/creative/search.mp4', 'video', false]]); + expect(creativeFiles('/r', 'tr', list).map(f => f.file)).toEqual(['/r/creative/header.png', '/r/tr/creative/search.png']); + }); test('info note: an App Store app without any asset; none for Play-only or with files', () => { const langs = [{ id: 'en', apple: 'en-US' }]; expect(creativeNote({ apple: {}, languages: langs }, '/r', () => [])).toBe(CREATIVE_NOTE); From 7e69883dfc8814c58c1103238ef670b465637b18 Mon Sep 17 00:00:00 2001 From: CRT Date: Mon, 19 Oct 2026 05:47:54 +0700 Subject: [PATCH 029/344] creative-assets: the no-files message names the shared creative folder too --- cli/apple/creative-assets.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cli/apple/creative-assets.ts b/cli/apple/creative-assets.ts index 2c09d4a..c932487 100644 --- a/cli/apple/creative-assets.ts +++ b/cli/apple/creative-assets.ts @@ -124,7 +124,7 @@ export async function run(ctx: Ctx): Promise { const forReview = ctx.args.has('add-for-review'); const bundleId = need(config.apple?.bundleId, 'apple.bundleId'); const { src, local } = localCreative(ctx); - if (!local.size) { warn(TAG, `no creative assets in ${src}//creative/ (header.png 3840x1646, search.png 3:2, or universal.png 5244x2950): optional; without them the App Store uses events, previews and screenshots`); return; } + if (!local.size) { warn(TAG, `no creative assets in ${src}//creative/ or ${src}/creative/ (header.png 3840x1646, search.png 3:2, or universal.png 5244x2950): optional; without them the App Store uses events, previews and screenshots`); return; } log(TAG, `${[...local.values()].flat().length} creative assets for ${local.size} locales pass the checks`); let c: Awaited>; From 98d3bf44106be823ad69ff51eda2925f15067ff5 Mon Sep 17 00:00:00 2001 From: CRT Date: Mon, 19 Oct 2026 06:01:56 +0700 Subject: [PATCH 030/344] creative-assets: the dry run plans one upload per file, not per slot (a shared file used by 13 locales read as 26 uploads) --- CHANGELOG.md | 3 ++- cli/apple/creative-assets.ts | 12 +++++++++--- tests/creative-assets.test.ts | 13 +++++++++++++ 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d4f68fa..9f7d48b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,8 @@ twice, is not uploaded again; an archived copy of the same file is unarchived instead of uploaded. A live app without an editable version uses the live version: approved assets are selected there, new ones are uploaded and wait for a review of their own. Art without words needs no copy per locale: `/creative/header.png` / `search.*` - fill every language without its own file. Pitfall 76 rewritten. + fill every language without its own file, uploaded once and placed per locale (the dry run counts files, not slots). + Pitfall 76 rewritten. ## 0.8.13 · 2026-10-18 diff --git a/cli/apple/creative-assets.ts b/cli/apple/creative-assets.ts index c932487..18ce31e 100644 --- a/cli/apple/creative-assets.ts +++ b/cli/apple/creative-assets.ts @@ -90,7 +90,7 @@ const reason = (a: J): string => { /** Bounded wait for processing (every wait has a timeout and a heartbeat); tests set waitMs 0 / timeoutMs 0. */ export const processingTiming = { pollMs: 3000, timeoutMs: 120_000, heartbeatMs: 20_000, sleep: (ms: number): Promise => (ms > 0 ? rt.sleep(ms) : Promise.resolve()) }; -export interface Row { locale: string; placement: Placement; file: string; action: 'keep' | 'upload' | 'wait' | 'select' | 'replace' | 'approve' | 'refuse'; state?: string; asset?: J } +export interface Row { locale: string; placement: Placement; file: string; action: 'keep' | 'upload' | 'reuse' | 'wait' | 'select' | 'replace' | 'approve' | 'refuse'; state?: string; asset?: J } /** Local files per App Store locale, checked; throws on any error before a network call. */ export function localCreative(ctx: Ctx): { src: string; local: Map } { @@ -158,6 +158,7 @@ export async function run(ctx: Ctx): Promise { if (verify) return verifySlots(); const rows: Row[] = []; + const planned = new Set(); // dry run: MD5s already planned for upload async function upload(f: CreativeFile, sum: string): Promise { const buf = readFileSync(f.file); const type = f.kind === 'image' ? 'appAssetLibraryImages' : 'appAssetLibraryVideos'; @@ -202,7 +203,12 @@ export async function run(ctx: Ctx): Promise { if (pick.refuse) { warn(TAG, `${tag}: ${basename(f.file)} ${pick.refuse}`); row('refuse'); continue; } let asset = pick.asset; if (!asset) { - if (dry) { log(TAG, `${tag}: would upload ${basename(f.file)} to the Asset Library and select it ${onLive ? 'on the live version once approved' : 'once processed'}`); row('upload'); continue; } + if (dry) { + // one upload per file: a later locale with the same file reuses it (the real run finds it by MD5) + const first = !planned.has(sum); planned.add(sum); + log(TAG, `${tag}: would ${first ? 'upload' : 'reuse'} ${basename(f.file)}${first ? ' to the Asset Library' : ' (uploaded once for an earlier locale)'} and select it ${onLive ? 'on the live version once approved' : 'once processed'}`); + row(first ? 'upload' : 'reuse'); continue; + } log(TAG, `${tag}: uploading ${basename(f.file)} to the Asset Library`); asset = await upload(f, sum); assets = await library(); @@ -261,7 +267,7 @@ export async function run(ctx: Ctx): Promise { log(TAG, `${added} creative asset(s) added to draft review submission ${sid}; nothing was submitted`); } } - const summary = `creative assets: ${n(['keep'])} up to date, ${n(['select', 'replace'])} ${dry ? 'to select' : 'selected'}, ${n(['upload'])} to upload, ${n(['wait'])} still processing, ${approve ? `${approve} waiting for App Review (live version), ` : ''}${n(['refuse'])} refused${off ? `, ${off} did not read back` : ''}`; + const summary = `creative assets: ${n(['keep'])} up to date, ${n(['select', 'replace'])} ${dry ? 'to select' : 'selected'}, ${n(['upload'])} file(s) to upload${n(['reuse']) ? ` (used by ${n(['upload', 'reuse'])} slots)` : ''}, ${n(['wait'])} still processing, ${approve ? `${approve} waiting for App Review (live version), ` : ''}${n(['refuse'])} refused${off ? `, ${off} did not read back` : ''}`; if (unreviewed.size) { log(TAG, forReview ? `owner step: Submit for Review with the version (or alone once the app has an approved version): ${consoleLink('asc.app-review')}` diff --git a/tests/creative-assets.test.ts b/tests/creative-assets.test.ts index 07b5daa..6a24321 100644 --- a/tests/creative-assets.test.ts +++ b/tests/creative-assets.test.ts @@ -194,6 +194,19 @@ describe('apple creative-assets against the fake App Store Connect', () => { expect((await go(p, ['--verify'])).out).toContain('every slot shows the local file'); }); + test('one shared file for many locales: the dry run plans one upload, the run uploads once and places it per locale', async () => { + const two = { ...CFG, languages: [{ id: 'en', apple: 'en-US', play: 'en-US' }, { id: 'tr', apple: 'tr', play: 'tr-TR' }] }; + s.asc.put({ type: 'appAssetLibraries', id: 'lib-1', attributes: {}, rels: { app: APP } }); + s.asc.put({ type: 'appStoreVersions', id: 'ver-1', attributes: { versionString: '1.0.0', appVersionState: 'PREPARE_FOR_SUBMISSION', platform: 'IOS' }, rels: { app: APP } }); + for (const l of ['en-US', 'tr']) s.asc.put({ type: 'appStoreVersionLocalizations', id: `loc-${l}`, attributes: { locale: l }, rels: { appStoreVersion: 'ver-1' } }); + const p = project(two, { 'store/renders/creative/header.png': png(3840, 1646, false, 4) }); + const dry = await go(p, ['--dry']); + expect(dry.out).toContain('1 file(s) to upload (used by 2 slots)'); + const r = await go(p); + expect(r.w.filter(x => x === 'POST /v1/appAssetLibraryImages')).toHaveLength(1); + expect(r.w.filter(x => x === 'POST /v1/appAssetLibraryPlacements')).toHaveLength(2); + }); + test('a bad file stops the run before any call', async () => { const p = setup({ 'store/renders/en/creative/header.png': png(3840, 1600, true) }); const a = s.calls.length; From 1736300784f734cd23dbc3c8686d1b084cf702dc Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 02:50:09 +0700 Subject: [PATCH 031/344] apple creative-assets: a placement App Store Connect refuses on the live version is reported with the live version page's deep link, the live page stays unchanged (new placement first, old one removed after) and the other live slots are not retried; pitfall 76 --- CHANGELOG.md | 4 +++- cli/apple/creative-assets.ts | 22 ++++++++++++++++++++-- skills/store-pitfalls/SKILL.md | 7 +++++-- tests/creative-assets.test.ts | 14 ++++++++++++++ 4 files changed, 42 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f7d48b..0ee5763 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,9 @@ an editable version uses the live version: approved assets are selected there, new ones are uploaded and wait for a review of their own. Art without words needs no copy per locale: `/creative/header.png` / `search.*` fill every language without its own file, uploaded once and placed per locale (the dry run counts files, not slots). - Pitfall 76 rewritten. + If App Store Connect refuses a placement on the live version, the run says so, leaves the live page unchanged (the + new placement goes first, the old one is removed only after Apple accepted it), links the live version page and does + not retry the other live slots. Pitfall 76 rewritten. ## 0.8.13 · 2026-10-18 diff --git a/cli/apple/creative-assets.ts b/cli/apple/creative-assets.ts index 18ce31e..295aa9d 100644 --- a/cli/apple/creative-assets.ts +++ b/cli/apple/creative-assets.ts @@ -34,6 +34,7 @@ import { ffprobe } from '../shots/report'; import { imageInfo } from '../shots/spec'; import { checkCreativeImage, checkCreativeVideo, type CreativeFile, creativeFiles, PLACEMENT_TYPE, type Placement } from '../shots/creative'; import { ascClient, md5, type J } from './asc'; +import { AmbiguousWriteError } from '../lib/upsert'; import { addItem, ensureDraft, OtherSubmissionError } from './submission'; const TAG = 'apple'; @@ -158,6 +159,7 @@ export async function run(ctx: Ctx): Promise { if (verify) return verifySlots(); const rows: Row[] = []; + let liveRefused = ''; // the first 4xx on a live-version placement: later live slots are not tried const planned = new Set(); // dry run: MD5s already planned for upload async function upload(f: CreativeFile, sum: string): Promise { const buf = readFileSync(f.file); @@ -231,10 +233,26 @@ export async function run(ctx: Ctx): Promise { } const action = placed.length ? 'replace' : 'select'; if (dry) { log(TAG, `${tag}: would ${action === 'replace' ? `replace ${placed.length} selected asset(s) with` : 'select'} ${basename(f.file)} (${asset.attributes?.state})`); row(action, asset); continue; } - for (const p of placed) await c.asc('DELETE', `/v1/appAssetLibraryPlacements/${p.id}`); + if (onLive && liveRefused) { warn(TAG, `${tag}: not tried (App Store Connect refused a placement on the live version above; no blind retries)`); row('refuse', asset); continue; } const media = f.kind === 'image' ? 'image' : 'video'; - await c.asc('POST', '/v1/appAssetLibraryPlacements', { data: { type: 'appAssetLibraryPlacements', attributes: { placementType: ptype }, + const place = () => c.asc('POST', '/v1/appAssetLibraryPlacements', { data: { type: 'appAssetLibraryPlacements', attributes: { placementType: ptype }, relationships: { [media]: { data: { type: asset.type, id: asset.id } }, appStoreVersionLocalization: { data: { type: 'appStoreVersionLocalizations', id: loc.id } } } } }); + if (onLive) { + // Live version: place the new asset first, remove the old one only after Apple accepted it, so a refusal + // leaves the live page as it was. Whether the API takes placements on a live version is not documented. + try { await place(); } + catch (e) { + const status = /-> (4\d\d)/.exec(String((e as Error).message))?.[1]; + if (!status || e instanceof AmbiguousWriteError) throw e; + liveRefused = String(e instanceof Error ? e.message : e).split('\n')[0]!; + warn(TAG, `${tag}: App Store Connect refused to select ${basename(f.file)} on the live version ${version.attributes.versionString} (${status}): ${liveRefused}. The live page is unchanged. Select it in the console instead (Header and Search Results on the live version page): ${consoleLink('asc.version', '', { appleAppId: appId }).replace('/version/inflight', '/version/deliverable')}, or create a new version and re-run; the remaining live slots are not tried`); + row('refuse', asset); continue; + } + for (const p of placed) await c.asc('DELETE', `/v1/appAssetLibraryPlacements/${p.id}`); + } else { + for (const p of placed) await c.asc('DELETE', `/v1/appAssetLibraryPlacements/${p.id}`); + await place(); + } log(TAG, `${tag}: selected ${basename(f.file)} (${asset.attributes?.state})`); row(action, asset); } diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 174df6a..be166fc 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -930,8 +930,11 @@ that fails without the fix (see CONTRIBUTING.md). asset with the same MD5, select it once processed, never re-upload a rejected file or one that failed processing twice. Then `--add-for-review` puts the unreviewed assets into the draft submission (with the first version, or alone once the app has an approved version) and `--verify` reads every slot back. With no editable version the live version - is used and only APPROVED assets go onto it; the rest wait for their own review. Uploading, selecting and adding to the + is used and only APPROVED assets go onto it; the rest wait for their own review. Whether the API accepts a new + placement on a live version is not documented: storebound places the new asset first and removes the old one only + after Apple accepted it, and on a 4xx it says so, leaves the live page unchanged, gives the live version page's deep + link (select it there, or create a version and re-run) and does not try the remaining live slots. Uploading, selecting and adding to the draft are normal steps, not owner buttons; Submit for Review stays the owner's. - **Guard:** `cli/apple/creative-assets.ts` (`classify`, `pickAsset`, `processingTiming`), `tests/creative-assets.test.ts` (fake App Store Connect: upload and select in one run, still processing, rejected / archived files, add-for-review - without submitting, verify read-only); the fake commits library assets to PREPARE_FOR_SUBMISSION, as Apple does. + without submitting, verify read-only, a refused live placement); the fake commits library assets to PREPARE_FOR_SUBMISSION, as Apple does. diff --git a/tests/creative-assets.test.ts b/tests/creative-assets.test.ts index 6a24321..8073ba5 100644 --- a/tests/creative-assets.test.ts +++ b/tests/creative-assets.test.ts @@ -194,6 +194,20 @@ describe('apple creative-assets against the fake App Store Connect', () => { expect((await go(p, ['--verify'])).out).toContain('every slot shows the local file'); }); + test('live version refuses a placement: clear message with the console deep link, live page unchanged, no blind retry', async () => { + const p = setup(files()); + s.asc.all('appStoreVersions')[0]!.attributes.appVersionState = 'READY_FOR_DISTRIBUTION'; + await go(p); + for (const x of lib()) x.attributes.state = 'APPROVED'; + s.faults.push({ method: 'POST', match: /appAssetLibraryPlacements/, when: 'before', status: 409, code: 'STATE_ERROR', detail: 'version not editable', times: 5 }); + const r = await go(p, [], 1); + expect(r.out).toContain('refused to select header.png on the live version 1.0.0 (409)'); + expect(r.out).toContain('https://appstoreconnect.apple.com/apps/'); + expect(r.out).toContain('not tried (App Store Connect refused a placement on the live version above'); + expect(r.w).toEqual(['POST /v1/appAssetLibraryPlacements']); + expect(s.asc.all('appAssetLibraryPlacements')).toHaveLength(0); + }); + test('one shared file for many locales: the dry run plans one upload, the run uploads once and places it per locale', async () => { const two = { ...CFG, languages: [{ id: 'en', apple: 'en-US', play: 'en-US' }, { id: 'tr', apple: 'tr', play: 'tr-TR' }] }; s.asc.put({ type: 'appAssetLibraries', id: 'lib-1', attributes: {}, rels: { app: APP } }); From edabbec874f27abac84dc3b54e8eef77ff639e98 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 02:57:25 +0700 Subject: [PATCH 032/344] cross-store text: other platforms named in App Store text (2.3.10: Android, Google Play, ...) or Play text (Metadata: iOS, App Store, Game Center, ...) are refused by every text write (apple / play listing, play release / upload notes, listing set, whats-new, storebound edit, desktop editor), blockers in check / validate, scan other-platforms / play-other-platforms; listing.allowPlatformMentions for the owner's functional mentions; whats-new splits [apple] / [play] lines per store; storebound api --yes without a TTY is refused (exit 1, stderr) instead of a silent dry run; pitfalls 77, 78 --- CHANGELOG.md | 15 ++ .../src/screens/editors/ListingEditor.tsx | 4 +- cli/api.ts | 6 +- cli/api/gate.ts | 5 +- cli/apple/listing.ts | 12 +- cli/check.ts | 4 + cli/edit.ts | 1 + cli/lib/config.ts | 12 +- cli/lib/cross-store.ts | 171 ++++++++++++++++++ cli/lib/desktop-protocol.ts | 2 + cli/lib/edit-values.ts | 1 + cli/lib/edit.ts | 7 +- cli/lib/listing-mentions.ts | 18 ++ cli/lib/listing-rules.ts | 16 +- cli/lib/scan/play-rules.ts | 7 +- cli/lib/scan/rules.ts | 20 +- cli/lib/whats-new.ts | 40 +++- cli/listing-store.ts | 11 +- cli/play/listing.ts | 9 + cli/play/release.ts | 5 +- cli/play/upload.ts | 3 +- cli/validate.ts | 7 + cli/whats-new.ts | 40 +++- docs/pitfalls.md | 2 + skills/aso-basics/SKILL.md | 6 + skills/review-rejections/SKILL.md | 5 + skills/store-api/SKILL.md | 6 +- skills/store-pitfalls/SKILL.md | 26 ++- skills/whats-new/SKILL.md | 16 +- tests/api.test.ts | 14 +- tests/cross-store.test.ts | 171 ++++++++++++++++++ tests/signing-capabilities.test.ts | 4 +- 32 files changed, 613 insertions(+), 53 deletions(-) create mode 100644 cli/lib/cross-store.ts create mode 100644 cli/lib/listing-mentions.ts create mode 100644 tests/cross-store.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 95b8b67..9aa17ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,21 @@ ## Unreleased +- **Other platforms in store text are refused (both stores).** One checker (`cli/lib/cross-store.ts`) finds Android, + Google Play (Games), Play Store, Galaxy Store, Amazon Appstore, Steam, Microsoft Store, AppGallery (and localized + forms) in App Store text (Guideline 2.3.10) and iOS, iPhone, iPad, App Store, Apple Arcade, Game Center, TestFlight in + Play text (Metadata policy), per locale, field and line with a fix. `apple listing`, `play listing`, `play release` / + `play upload` release notes, `listing set`, `whats-new check` / `apply`, `storebound edit` and the desktop editor + refuse before anything is sent (dry runs show the hits); `check` and `validate` report blockers; `scan` reports + `other-platforms` (2.3.10) and `play-other-platforms` (Play: Metadata). A functional mention stays only through the + owner's `listing.allowPlatformMentions: [{ store, text, reason }]`. +- **Per-store release notes.** Lines tagged `[apple]` / `[play]` (or a `[play]` line heading a block) in a shared notes + source go only into that store's notes; the draft leaves untagged other-platform lines out of the wrong store and + says so; each store's limit counts its own notes. +- **`storebound api` writes piped or redirected are refused loudly.** `--yes` with stdout not a TTY now exits 1 with + "refused: writes through `storebound api` need an interactive terminal ... Nothing was sent." on stderr instead of + a silent dry run. + ## 0.8.13 · 2026-10-18 - **iPhone Duo screenshots.** `apple.iphoneDuo: true` adds the foldable's outer (1398 x 2034) and inner (2007 x 2853) diff --git a/apps/desktop/src/screens/editors/ListingEditor.tsx b/apps/desktop/src/screens/editors/ListingEditor.tsx index ae322a6..a09d1f5 100644 --- a/apps/desktop/src/screens/editors/ListingEditor.tsx +++ b/apps/desktop/src/screens/editors/ListingEditor.tsx @@ -38,8 +38,8 @@ function StoreColumn({ project, data, store, l }: { project: Project; data: Edit const lim = (data.limits[store] ?? {}) as Record; const vals = current(e, project, store, l, defs.map(d => d.f)); const issues = store === 'play' - ? playLangIssues(l.lang, { title: vals.title || undefined, short: vals.short, full: vals.full, whatsNew: vals.whatsNew }, data.appName) - : appleLocaleIssues(l.lang, Object.fromEntries(Object.entries(vals).filter(([, v]) => v)), data.appleName); + ? playLangIssues(l.lang, { title: vals.title || undefined, short: vals.short, full: vals.full, whatsNew: vals.whatsNew }, data.appName, data.allowPlatformMentions) + : appleLocaleIssues(l.lang, Object.fromEntries(Object.entries(vals).filter(([, v]) => v)), data.appleName, data.allowPlatformMentions); // a new section starts empty: say what is required instead of a wall of errors const fresh = !l.exists && Object.values(vals).every(v => !v); return ( diff --git a/cli/api.ts b/cli/api.ts index e9bafaa..b91de2e 100644 --- a/cli/api.ts +++ b/cli/api.ts @@ -145,7 +145,11 @@ export async function run(args: Args): Promise { tty: stdinIsTTY() && !!process.stdout.isTTY, agent: process.env.STOREBOUND_SERVE === '1' || process.env.STOREBOUND_MCP === '1', }); - if (decision.action === 'refuse') throw new Error(`${op.id}: ${decision.why}`); + if (decision.action === 'refuse') { + const instead = op.method !== 'GET' ? dedicatedCommand(st, op.id) : null; + if (instead) console.error(`api: dedicated command: ${instead}`); + throw new Error(`${op.id}: ${decision.why}`); + } if (decision.action === 'dry') { const instead = op.method !== 'GET' ? dedicatedCommand(st, op.id) : null; if (instead) console.error(`api: ${op.id} has a dedicated storebound command that runs without a terminal: ${instead}`); diff --git a/cli/api/gate.ts b/cli/api/gate.ts index cc5c76e..95bd857 100644 --- a/cli/api/gate.ts +++ b/cli/api/gate.ts @@ -86,6 +86,9 @@ export type Decision = | { action: 'dry'; why: string } | { action: 'refuse'; why: string }; +/** --yes without a terminal: refused loudly (exit 1, stderr), never a silent dry run (pitfall 77). */ +export const NOT_A_TTY = 'refused: writes through `storebound api` need an interactive terminal (stdout is not a TTY: piped or redirected). Nothing was sent. Run it without a pipe or redirect, or use the dedicated storebound command.'; + /** What to do with one call. Pure. */ export function decide(g: GateInput): Decision { if (g.getOnly && g.method.toUpperCase() !== 'GET') return { action: 'refuse', why: 'api get runs GET operations only' }; @@ -94,7 +97,7 @@ export function decide(g: GateInput): Decision { ? 'owner-only operation: never through MCP or the desktop app; the owner runs it in a terminal' : 'writes through `storebound api` are not available to MCP or the desktop app; run it in a terminal' }; if (g.dry || !g.yes) return { action: 'dry', why: g.dry ? '--dry' : 'writes are dry by default: add --yes (in a terminal) to send' }; - if (!g.tty) return { action: 'dry', why: 'not an interactive terminal: by design, writes through `storebound api` are sent only from an interactive terminal (--yes alone is not enough)' }; + if (!g.tty) return { action: 'refuse', why: NOT_A_TTY }; return g.kind === 'owner' ? { action: 'confirm', typed: true } : { action: 'send' }; } diff --git a/cli/apple/listing.ts b/cli/apple/listing.ts index 64470a3..24b71bf 100644 --- a/cli/apple/listing.ts +++ b/cli/apple/listing.ts @@ -14,6 +14,7 @@ // listing file: shows the diff, writes only with --write. import { existsSync, readFileSync, writeFileSync } from 'node:fs'; import { type AppleCopy, parseAppStoreListing } from '../lib/copy'; +import { fieldsMentions, hitLine, type PlatformHit, refuseMentions } from '../lib/cross-store'; import { compactDiff } from '../lib/diff'; import { mergeAppleListing, overLimits } from '../lib/listing-pull'; import { counts, draftReason, draftSections, type ItemPlan, itemLines, planItem, planLocales, planVersion, short, type Skipped, type VersionPlan } from '../lib/listing-plan'; @@ -86,6 +87,8 @@ export interface AppleListingPlan { skipped: Skipped[]; notes: string[]; changes: number; + /** Android, Google Play, ... in the texts this run sends (Guideline 2.3.10): the run is refused (pitfall 77) */ + mentions: PlatformHit[]; } type Asc = Awaited>; @@ -133,7 +136,10 @@ async function planListing(ctx: Ctx, c: Asc, appId: string, version: string): Pr const changes = (versionPlan.action === 'create' || versionPlan.action === 'update' ? 1 : 0) + (build?.action === 'attach' ? 1 : 0) + infoLocs.filter(x => x.action !== 'same').length + (versionLocales ? versionLocales.filter(x => x.action !== 'same').length : Object.keys(wanted).length); - return { version, versionPlan, build, appInfo: { id: info.id, state: String(info.attributes?.state ?? info.attributes?.appStoreState ?? ''), locales: infoLocs }, + const allow = config.listing?.allowPlatformMentions; + const mentions = Object.entries(listing).flatMap(([l, f]) => fieldsMentions('apple', l, { name: f.name, subtitle: f.subtitle, promotionalText: f.promotionalText, + keywords: f.keywords, description: f.description, whatsNew: versionPlan.first ? undefined : f.whatsNew }, allow)); + return { mentions, version, versionPlan, build, appInfo: { id: info.id, state: String(info.attributes?.state ?? info.attributes?.appStoreState ?? ''), locales: infoLocs }, versionLocales, wanted, skipped, notes, changes }; } @@ -156,6 +162,7 @@ export function listingPlanLines(p: AppleListingPlan): string[] { } for (const s of p.skipped) out.push(`Skipped ${s.key}: ${s.reason}`); for (const n of p.notes) out.push(`Note: ${n}`); + for (const h of p.mentions ?? []) out.push(`REFUSE: ${hitLine(h)}`); return out; } @@ -187,7 +194,8 @@ export async function run(ctx: Ctx): Promise { const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId); const appId = await c.app(); const p = await planListing(ctx, c, appId, version); - const refused = [p.versionPlan.action === 'refuse' ? p.versionPlan.reason : '', p.build?.action === 'refuse' ? p.build.reason : ''].filter(Boolean); + const refused = [p.versionPlan.action === 'refuse' ? p.versionPlan.reason : '', p.build?.action === 'refuse' ? p.build.reason : '', + (() => { try { refuseMentions(p.mentions, 'apple listing'); return ''; } catch (e) { return (e as Error).message; } })()].filter(Boolean); if (a.has('json')) printJson({ dry, ...p, refused }); else for (const line of listingPlanLines(p)) console.log(line); if (refused.length) { if (dry) { process.exitCode = 1; warn('apple', `dry run: would refuse: ${refused.join('; ')}`); return; } throw new Error(refused.join('; ')); } diff --git a/cli/check.ts b/cli/check.ts index 288b830..aac7155 100644 --- a/cli/check.ts +++ b/cli/check.ts @@ -32,6 +32,8 @@ import { posix, readPulled } from './lib/art-pull'; import { creativeNote } from './shots/creative'; import { type CapProject, capacitorProject, prebuildFor, staleMessage, webState } from './lib/web-assets'; import { iphoneDuoNote } from './shots/spec'; +import { hitLine } from './lib/cross-store'; +import { listingFileMentions } from './lib/listing-mentions'; /** The newest .ipa in a folder (apple build's export), or null. */ function newestIpa(dir: string): string | null { @@ -92,6 +94,8 @@ export async function run(ctx: Ctx): Promise { } return `${Object.keys(copy).length} locales`; }); + // other platforms named in a store's text: App Store 2.3.10 / Play Metadata, a blocker (pitfall 77) + try { for (const h of listingFileMentions(ctx.loaded)) problems.push(`other platform in ${hitLine(h)}`); } catch (e) { warn('check', `platform mentions: ${(e as Error).message}`); } // listing translation drafts (storebound listing translate): fine to keep working on, not to push unreviewed for (const f of [config.apple ? resolve(config.apple.listing ?? 'store/appstore.md') : '', config.play ? resolve(config.play.listing ?? 'store/listing.md') : ''].filter(Boolean)) { if (!existsSync(f)) continue; diff --git a/cli/edit.ts b/cli/edit.ts index 75dd944..80483f1 100644 --- a/cli/edit.ts +++ b/cli/edit.ts @@ -39,6 +39,7 @@ export function sources(ctx: Ctx): EditSources { shotsCopy: config.shots?.copy ? file(resolve(config.shots.copy)) : null, appName: config.app.name, appleName: appleName(config), + allowPlatformMentions: config.listing?.allowPlatformMentions ?? [], }; } diff --git a/cli/lib/config.ts b/cli/lib/config.ts index 152d025..8811f7b 100644 --- a/cli/lib/config.ts +++ b/cli/lib/config.ts @@ -700,7 +700,17 @@ export interface ShipConfig { /** Owner answers for console forms that have no API (`storebound console fill`); only what the rest of the config * cannot prove. Anything left out stays empty and highlighted in the page. */ console?: ConsoleConfig; - /** Release notes (`storebound whats-new`). */ + /** Listing text rules for both stores. */ + listing?: { + /** Functional mentions of another platform or store that may stay in a store's text, e.g. a "Continue with + * Google" button in App Store text or "Sign in with Apple" in Play text: `{ store: 'apple' | 'play' | 'both', + * text: 'Sign in with Apple', reason: 'the sign-in button label' }`. A line that contains `text` (any case) keeps + * the terms inside it. Every other mention of Android / Google Play in App Store text (Guideline 2.3.10) or of + * iOS / App Store in Play text (Metadata policy) stops the write. The owner adds entries; storebound never does. */ + allowPlatformMentions?: { store: 'apple' | 'play' | 'both'; text: string; reason: string }[]; + }; + /** Release notes (`storebound whats-new`). Lines tagged `[apple]` or `[play]` (or a `[play]` line heading a block + * until the next blank line) go only into that store's notes. */ whatsNew?: { /** Player-facing notes file the draft comes from before the git log (a CHANGELOG-like file gives the version's * section), e.g. "docs/player-notes.md". Without it: docs/RELEASE-.md, then CHANGELOG.md. */ diff --git a/cli/lib/cross-store.ts b/cli/lib/cross-store.ts new file mode 100644 index 0000000..af8e504 --- /dev/null +++ b/cli/lib/cross-store.ts @@ -0,0 +1,171 @@ +// Other platforms and stores named in one store's text (pitfall 77). App Store Guideline 2.3.10 (Accurate Metadata): +// no other mobile platforms in the metadata; a Mac version was rejected for a What's New taken from release notes +// shared with Google Play ("Google Play Games", "Android"). Google Play's Metadata policy is the mirror case +// (misleading references to other platforms or apps). One checker for every surface: the listing pushes, whats-new, +// the store-only listing edit and the desktop editor refuse on a hit; dry runs show it; check / validate / scan +// report it with file, line, field and locale. A functional mention ("Sign in with Apple", "Continue with Google") +// is kept only through `listing.allowPlatformMentions` in the config: the owner's call, the tool never adds one. +// Pure, no Node imports (the desktop window runs it too). + +export type CrossStore = 'apple' | 'play'; + +/** One owner-approved mention: `text` (any case) on a line keeps the terms inside it. */ +export interface PlatformAllow { store: CrossStore | 'both'; text: string; reason: string } + +export interface PlatformHit { + store: CrossStore; + locale: string; + field: string; + /** line inside the field's text (1-based) */ + line: number; + term: string; + /** the whole line, trimmed */ + text: string; + /** listing file and its line, when the hit comes from a file */ + file?: string; + fileLine?: number; + fix: string; +} + +interface Term { t: string; cs?: boolean; cjk?: boolean } + +/** Named in App Store text: other mobile platforms and stores (Latin forms match whole words, any case). */ +export const APPLE_FORBIDDEN: readonly Term[] = [ + { t: 'Google Play Games' }, { t: 'Google Play Spiele' }, { t: 'Google Play Jeux' }, { t: 'Google Play Juegos' }, { t: 'Google Play Giochi' }, { t: 'Google Play Oyun' }, + { t: 'Google Play' }, { t: 'Play Store' }, { t: 'Play Market' }, { t: 'Play Маркет' }, { t: 'Плей Маркет' }, { t: 'Google Play 游戏', cjk: true }, { t: 'Google Play ゲーム', cjk: true }, + { t: 'Android' }, { t: 'Андроид' }, { t: 'Android TV' }, { t: 'Wear OS' }, { t: 'Chromebook' }, + { t: '安卓', cjk: true }, { t: 'アンドロイド', cjk: true }, { t: '안드로이드', cjk: true }, { t: '구글 플레이', cjk: true }, { t: 'グーグルプレイ', cjk: true }, { t: '谷歌商店', cjk: true }, + { t: 'Galaxy Store' }, { t: 'Amazon Appstore' }, { t: 'Amazon App Store' }, { t: 'AppGallery' }, { t: 'Huawei' }, { t: 'Xiaomi GetApps' }, + { t: 'Steam', cs: true }, { t: 'Microsoft Store' }, { t: 'Windows Store' }, { t: 'Windows Phone' }, { t: 'BlackBerry' }, +]; + +/** Named in Google Play text: Apple platforms and services. */ +export const PLAY_FORBIDDEN: readonly Term[] = [ + { t: 'Apple App Store' }, { t: 'App Store', cs: true }, { t: 'AppStore', cs: true }, { t: 'App-Store', cs: true }, + { t: 'iOS', cs: true }, { t: 'iPadOS' }, { t: 'iPhone' }, { t: 'iPad' }, { t: 'macOS' }, { t: 'Apple Watch' }, { t: 'Apple TV' }, { t: 'Vision Pro' }, + { t: 'Apple Arcade' }, { t: 'Game Center', cs: true }, { t: 'TestFlight' }, + { t: 'Sign in with Apple' }, { t: 'iCloud' }, + { t: 'アップストア', cjk: true }, { t: '苹果商店', cjk: true }, { t: '앱스토어', cjk: true }, { t: 'アイフォン', cjk: true }, { t: '아이폰', cjk: true }, +]; + +/** A line tagged for the other store's notes (`[play]` in App Store text, `[apple]` in Play text) is always a hit. */ +const OTHER_TAG: Record = { apple: /^\s*(?:[-*•]\s*)?\[(play|android|google)\]/i, play: /^\s*(?:[-*•]\s*)?\[(apple|ios|app ?store)\]/i }; + +const esc = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +const termRe = (x: Term): RegExp => x.cjk ? new RegExp(esc(x.t), 'g') + : new RegExp(`(? = { + apple: [...APPLE_FORBIDDEN].sort((a, b) => b.t.length - a.t.length).map(x => ({ term: x.t, re: termRe(x) })), + play: [...PLAY_FORBIDDEN].sort((a, b) => b.t.length - a.t.length).map(x => ({ term: x.t, re: termRe(x) })), +}; + +export const STORE_NAME: Record = { apple: 'App Store', play: 'Google Play' }; +export const GUIDELINE: Record = { apple: '2.3.10', play: 'Play: Metadata' }; + +export function fixFor(store: CrossStore, field: string): string { + const other = store === 'apple' ? 'play' : 'apple'; + const notes = /whatsnew|release/i.test(field) ? ` or tag the line [${other}] in the shared notes (whats-new keeps it out of ${STORE_NAME[store]})` : ''; + return `remove it from the ${STORE_NAME[store]} text${notes}; a functional mention (a sign-in button) goes into listing.allowPlatformMentions in storebound.config.ts, the owner's call`; +} + +function allowed(store: CrossStore, line: string, term: string, allow: readonly PlatformAllow[]): boolean { + const l = line.toLowerCase(), t = term.toLowerCase(); + return allow.some(a => (a.store === store || a.store === 'both') && !!a.text.trim() && l.includes(a.text.toLowerCase()) && a.text.toLowerCase().includes(t)); +} + +/** Hits in one field of one locale, line by line. Overlapping terms report the longest ("Google Play Games"). */ +export function textMentions(text: string, o: { store: CrossStore; locale: string; field: string; allow?: readonly PlatformAllow[] }): PlatformHit[] { + const out: PlatformHit[] = []; + const allow = o.allow ?? []; + text.split('\n').forEach((raw, i) => { + const line = raw.trim(); + if (!line) return; + const spans: [number, number][] = []; + const add = (term: string): void => { out.push({ store: o.store, locale: o.locale, field: o.field, line: i + 1, term, text: line.slice(0, 200), fix: fixFor(o.store, o.field) }); }; + const tag = OTHER_TAG[o.store].exec(line); + if (tag) add(`[${tag[1]}]`); + for (const { term, re } of COMPILED[o.store]) { + re.lastIndex = 0; + for (let m = re.exec(line); m; m = re.exec(line)) { + const s = m.index, e = s + m[0].length; + if (spans.some(([a, b]) => s < b && e > a)) continue; + spans.push([s, e]); + if (!allowed(o.store, line, m[0], allow)) add(m[0]); + } + } + }); + return out; +} + +/** Hits in many fields of one locale: values as `{ field: text }`. */ +export function fieldsMentions(store: CrossStore, locale: string, fields: Record, allow?: readonly PlatformAllow[]): PlatformHit[] { + return Object.entries(fields).flatMap(([field, t]) => t ? textMentions(t, { store, locale, field, allow }) : []); +} + +/** Hits in a listing file (store/appstore.md or store/listing.md): fenced blocks under `### field` of each `## locale` + * section, with the file line. Play sections take their codes from ``. */ +export function fileMentions(store: CrossStore, path: string, md: string, allow?: readonly PlatformAllow[]): PlatformHit[] { + const out: PlatformHit[] = []; + const lines = md.split('\n'); + let locale = '', field = '', fence = -1, buf: string[] = []; + lines.forEach((l, i) => { + if (fence < 0 && /^## /.test(l)) { locale = l.slice(3).split(/[\s·]/)[0]!.trim(); field = ''; return; } + const pc = /^$/.exec(l); + if (fence < 0 && pc) { locale = pc[1]!.split(',').map(s => s.trim()).join(','); return; } + if (fence < 0 && /^###\s/.test(l)) { field = l.slice(4).trim(); return; } + if (/^```/.test(l)) { + if (fence < 0) { fence = i; buf = []; return; } + if (field && locale) for (const h of textMentions(buf.join('\n'), { store, locale, field: fieldName(field), allow })) out.push({ ...h, file: path, fileLine: fence + 1 + h.line }); + fence = -1; return; + } + if (fence >= 0) buf.push(l); + }); + return out; +} + +/** "### Short description (max 80)" -> "short", "### whatsNew" -> "whatsNew". */ +function fieldName(h: string): string { + if (/^whatsNew\b|what'?s new|release notes/i.test(h)) return 'whatsNew'; + if (/\bshort\b/i.test(h)) return 'short'; + if (/\bfull\b/i.test(h)) return 'full'; + if (/\btitle\b/i.test(h)) return 'title'; + return h.split(/\s/)[0]!; +} + +/** One line per hit: where, what, and the fix. */ +export function hitLine(h: PlatformHit): string { + const at = h.file ? `${h.file}:${h.fileLine} ` : ''; + return `${at}${STORE_NAME[h.store]} ${h.locale} ${h.field} line ${h.line}: "${h.term}" in "${h.text}" (${GUIDELINE[h.store]}): ${h.fix}`; +} + +/** Throws (nothing is written) when there are hits; `what` names the write. */ +export function refuseMentions(hits: readonly PlatformHit[], what: string): void { + if (!hits.length) return; + const stores = [...new Set(hits.map(h => h.store))]; + throw new Error(`refused: ${what}: other platforms or stores named in ${stores.map(s => `${STORE_NAME[s]} text (${GUIDELINE[s]})`).join(' and ')}; nothing was sent\n${hits.map(h => ` ${hitLine(h)}`).join('\n')}`); +} + +// ---- per-store notes: lines tagged [apple] / [play] in shared release notes ---- + +const TAG_RE = /^(\s*(?:[-*•]\s*)?)\[(apple|ios|app ?store|play|android|google ?play|google)\]\s*/i; +const tagStore = (t: string): CrossStore => /^(apple|ios|app ?store)$/i.test(t) ? 'apple' : 'play'; + +/** The notes for one store: untagged lines stay, lines tagged for this store lose the tag, lines tagged for the other + * store go. A heading line that is only a tag (`[play]`) starts a block for that store until a blank line. Pure. */ +export function notesForStore(text: string, store: CrossStore): string { + const out: string[] = []; + let block: CrossStore | null = null; + for (const l of text.split('\n')) { + if (!l.trim()) { block = null; out.push(l); continue; } + const only = /^\s*\[(apple|ios|app ?store|play|android|google ?play|google)\]\s*:?\s*$/i.exec(l); + if (only) { block = tagStore(only[1]!); continue; } + if (block) { if (block === store) out.push(l); continue; } + const m = TAG_RE.exec(l); + if (!m) { out.push(l); continue; } + if (tagStore(m[2]!) === store) out.push(m[1]! + l.slice(m[0].length)); + } + return out.join('\n').replace(/\n{3,}/g, '\n\n').trim(); +} + +/** Whether a text has store tags at all (then it is split before it goes anywhere). */ +export const hasStoreTags = (text: string): boolean => text.split('\n').some(l => TAG_RE.test(l) || /^\s*\[(apple|ios|play|android)\]\s*:?\s*$/i.test(l)); diff --git a/cli/lib/desktop-protocol.ts b/cli/lib/desktop-protocol.ts index 41d5baa..fc0712b 100644 --- a/cli/lib/desktop-protocol.ts +++ b/cli/lib/desktop-protocol.ts @@ -446,6 +446,8 @@ export interface EditableResult { git: { repo: boolean; uncommitted: string[] }; appName: string; appleName: string; + /** listing.allowPlatformMentions: functional mentions of other platforms the owner allowed (pitfall 77) */ + allowPlatformMentions?: { store: 'apple' | 'play' | 'both'; text: string; reason: string }[]; languages: { id: string; play: string[]; apple: string | null; rtl: boolean }[]; play: EditableListing[] | null; apple: EditableListing[] | null; diff --git a/cli/lib/edit-values.ts b/cli/lib/edit-values.ts index a42f459..2640b29 100644 --- a/cli/lib/edit-values.ts +++ b/cli/lib/edit-values.ts @@ -72,6 +72,7 @@ export function editableValues(l: Loaded): EditableResult { git: gitState(root, files), appName: config.app.name, appleName: appleName(config), + allowPlatformMentions: config.listing?.allowPlatformMentions ?? [], languages: config.languages.map(x => ({ id: x.id, play: playCodes(x), apple: x.apple ?? null, rtl: !!x.rtl })), play: config.play ? play : null, apple: config.apple ? apple : null, diff --git a/cli/lib/edit.ts b/cli/lib/edit.ts index 27a17e2..c62071e 100644 --- a/cli/lib/edit.ts +++ b/cli/lib/edit.ts @@ -10,6 +10,7 @@ import { compactDiff } from './diff'; import { setByPath } from './config-path'; import type { AppleField } from './copy'; import { appleSection, isAppleField, isPlayField, playSection, setAppleField, setPlayField } from './listing-edit'; +import type { PlatformAllow } from './cross-store'; import { appleLocaleIssues, emailIssue, type FieldIssue, playLangIssues, urlIssue } from './listing-rules'; export type EditOp = @@ -35,6 +36,8 @@ export interface EditSources { shotsCopy?: { file: string; rel: string; text: string | null } | null; appName: string; appleName: string; + /** listing.allowPlatformMentions of the config (pitfall 77) */ + allowPlatformMentions?: readonly PlatformAllow[]; } /** Checks one edit's shape (it comes from the window or a terminal). Throws with the reason. */ @@ -171,12 +174,12 @@ export function planEdits(ops: EditOp[], src: EditSources, getPath: (path: strin // the touched languages as they would be saved, with the checks of `check` / `check --aso` / `scan` if (src.play) for (const lang of touched.play) { const s = playSection(texts.get(src.play.file) ?? '', lang); - if (s) for (const x of playLangIssues(lang, s.values, src.appName)) issues.push({ ...x, where: `Google Play ${lang}` }); + if (s) for (const x of playLangIssues(lang, s.values, src.appName, src.allowPlatformMentions)) issues.push({ ...x, where: `Google Play ${lang}` }); } if (src.apple) for (const loc of touched.apple) { const s = appleSection(texts.get(src.apple.file) ?? '', loc); if (s && onlyWhatToTest.get(loc)) { const n = [...(s.values.whatToTest ?? '')].length; if (n > 4000) issues.push({ level: 'error', field: 'whatToTest', where: `TestFlight ${loc}`, msg: `What to Test is ${n} characters; TestFlight takes 4000` }); continue; } - if (s) for (const x of appleLocaleIssues(loc, s.values, src.appleName)) issues.push({ ...x, where: `App Store ${loc}` }); + if (s) for (const x of appleLocaleIssues(loc, s.values, src.appleName, src.allowPlatformMentions)) issues.push({ ...x, where: `App Store ${loc}` }); } const files: EditFile[] = []; for (const [file, after] of texts) { diff --git a/cli/lib/listing-mentions.ts b/cli/lib/listing-mentions.ts new file mode 100644 index 0000000..f7f9fb5 --- /dev/null +++ b/cli/lib/listing-mentions.ts @@ -0,0 +1,18 @@ +// Other platforms named in the local listing files of both stores (pitfall 77): the blockers `check` and `validate` +// report. Reads store/appstore.md and store/listing.md (or the config's listing paths). +import { existsSync, readFileSync } from 'node:fs'; +import { relative } from 'node:path'; +import type { Loaded } from './config'; +import { fileMentions, type PlatformHit } from './cross-store'; + +export function listingFileMentions(loaded: Pick, stores: { apple: boolean; play: boolean } = { apple: true, play: true }): PlatformHit[] { + const { config, resolve, root } = loaded; + const allow = config.listing?.allowPlatformMentions; + const out: PlatformHit[] = []; + const files: ['apple' | 'play', string | null][] = [ + ['apple', stores.apple && config.apple ? resolve(config.apple.listing ?? 'store/appstore.md') : null], + ['play', stores.play && config.play ? resolve(config.play.listing ?? 'store/listing.md') : null], + ]; + for (const [store, f] of files) if (f && existsSync(f)) out.push(...fileMentions(store, relative(root, f) || f, readFileSync(f, 'utf8'), allow)); + return out; +} diff --git a/cli/lib/listing-rules.ts b/cli/lib/listing-rules.ts index 5a7bac2..66531ad 100644 --- a/cli/lib/listing-rules.ts +++ b/cli/lib/listing-rules.ts @@ -4,6 +4,10 @@ // Pure, no Node imports: the desktop window runs it on every keystroke, `storebound edit` before it writes. import { auditAppleKeywords, auditPlayListing } from './aso'; import { APPLE_LIMITS, type AppleCopy, len, PLAY_LIMITS } from './copy'; +import { fieldsMentions, GUIDELINE, type PlatformAllow, type PlatformHit } from './cross-store'; + +const mentionIssue = (h: PlatformHit): FieldIssue => ({ level: 'error', field: h.field, + msg: `line ${h.line}: "${h.term}": other platforms or stores in ${h.store === 'apple' ? 'App Store' : 'Google Play'} text get it rejected (${GUIDELINE[h.store]}); ${h.fix}` }); export type IssueLevel = 'error' | 'warn' | 'info'; export interface FieldIssue { level: IssueLevel; field: string; msg: string } @@ -12,8 +16,6 @@ export interface FieldIssue { level: IssueLevel; field: string; msg: string } export const COMPETITORS = ['instagram', 'tiktok', 'whatsapp', 'facebook', 'snapchat', 'youtube', 'netflix', 'spotify', 'telegram', 'messenger', 'twitter', 'pinterest', 'uber', 'airbnb', 'amazon', 'chatgpt', 'openai', 'minecraft', 'roblox', 'fortnite', 'pubg', 'candy crush', 'clash of clans', 'pokemon', 'pokémon', 'among us', 'subway surfers', 'temple run', 'angry birds', 'tetris', 'wordle', 'duolingo', 'zoom', 'gmail', 'google maps', 'waze', 'shazam', 'tinder', 'notion', 'evernote', 'photoshop', 'canva', 'capcut', 'iphone', 'ipad', 'apple']; -/** Other mobile platforms or stores in App Store text (2.3.10). */ -export const OTHER_PLATFORMS = /\b(Android|Google Play|Play Store|Galaxy Store|AppGallery|Huawei|Windows Phone|BlackBerry|Amazon Appstore)\b/; // Developer markers count only in capitals ("TODO:", "FIXME"): "todo" is a real word and keyword (a to-do app). export const PLACEHOLDER_MARKERS = /\bTODO\b|\bTBD\b|\bFIXME\b|\bXXX\b/; export const PLACEHOLDER_TEXT = /lorem ipsum|\bplaceholder\b|your app (name|description) here|coming soon|First paragraph:|Short hook under the name|One or two sentences you can change|İsmin altındaki kısa kanca|Yeni sürüm göndermeden istediğin zaman|\bExample (Game|App|Pro|Studio)\b/i; @@ -31,7 +33,7 @@ export const APPLE_REQUIRED = ['subtitle', 'promotionalText', 'keywords', 'descr * (apple.name, else app.name). Errors stop a save (the store would refuse it, or the listing file would no longer * parse); warnings and hints do not. */ -export function appleLocaleIssues(locale: string, v: AppleCopy, appName: string): FieldIssue[] { +export function appleLocaleIssues(locale: string, v: AppleCopy, appName: string, allow: readonly PlatformAllow[] = []): FieldIssue[] { const out: FieldIssue[] = []; for (const f of APPLE_REQUIRED) if (!(v[f] ?? '').trim()) out.push({ level: 'error', field: f, msg: `${locale}: ${f} is required` }); for (const [f, lim] of Object.entries(APPLE_LIMITS) as [keyof typeof APPLE_LIMITS, number][]) { @@ -63,19 +65,19 @@ export function appleLocaleIssues(locale: string, v: AppleCopy, appName: string) for (const f of ['name', 'subtitle', 'promotionalText', 'keywords', 'description', 'whatsNew'] as const) { const t = f === 'name' ? (v.name ?? '') : v[f] ?? ''; if (!t) continue; - const o = OTHER_PLATFORMS.exec(t); - if (o) out.push({ level: 'warn', field: f, msg: `"${o[0]}": other platforms or stores in App Store text get it rejected (2.3.10)` }); if (PLACEHOLDER_MARKERS.test(t) || PLACEHOLDER_TEXT.test(t)) out.push({ level: 'warn', field: f, msg: 'placeholder text (template or TODO) is still in it' }); const b = f === 'whatsNew' ? null : BETA_WORDS.exec(t); if (b && !/\bdemo account\b|\bdemo (video|mode)\b/i.test(t)) out.push({ level: 'warn', field: f, msg: `"${b[0]}": demos, betas and trials belong on TestFlight (2.2)` }); } + // 2.3.10: other platforms or stores (Android, Google Play, ...) stop the save (pitfall 77) + out.push(...fieldsMentions('apple', locale, { ...v, name: v.name ?? '' }, allow).map(mentionIssue)); return out; } export interface PlayValues { title?: string; short?: string; full?: string; whatsNew?: string } /** Issues of one Google Play language (title falls back to app.name). */ -export function playLangIssues(lang: string, v: PlayValues, appName: string): FieldIssue[] { +export function playLangIssues(lang: string, v: PlayValues, appName: string, allow: readonly PlatformAllow[] = []): FieldIssue[] { const out: FieldIssue[] = []; for (const f of PLAY_REQUIRED) if (!(v[f] ?? '').trim()) out.push({ level: 'error', field: f, msg: `${lang}: the ${f} description is required` }); const title = (v.title ?? '').trim() || appName; @@ -93,6 +95,8 @@ export function playLangIssues(lang: string, v: PlayValues, appName: string): Fi const t = v[f] ?? ''; if (t && (PLACEHOLDER_MARKERS.test(t) || PLACEHOLDER_TEXT.test(t))) out.push({ level: 'warn', field: f, msg: 'placeholder text (template or TODO) is still in it' }); } + // Play Metadata policy: iOS, App Store, ... in Play text stop the save (pitfall 77) + out.push(...fieldsMentions('play', lang, { ...v }, allow).map(mentionIssue)); return out; } diff --git a/cli/lib/scan/play-rules.ts b/cli/lib/scan/play-rules.ts index 7cda53e..90f8f90 100644 --- a/cli/lib/scan/play-rules.ts +++ b/cli/lib/scan/play-rules.ts @@ -56,7 +56,7 @@ import { consoleLink } from '../console-links'; import { PLAY_AGE_GROUPS } from '../config'; import { allSubscriptions } from '../subscriptions'; import { grep, type Hit, type ProjectFacts } from './project'; -import type { ScanFinding, ScanInput } from './rules'; +import { platformHits, type ScanFinding, type ScanInput } from './rules'; import { versionAtLeast } from './sdks'; const PLAY = 'https://support.google.com/googleplay/android-developer/answer/'; @@ -347,6 +347,11 @@ export function playRules(inp: ScanInput, x: PlayCtx): void { // ---- Play listing metadata ---- if (c?.play || inp.listings.play) { const listing = inp.listings.play; + // Apple platforms or services named in Play text (Metadata policy; the mirror of App Store 2.3.10, pitfall 77) + const apple = platformHits(inp, 'play'); + if (apple.length) + add({ rule: 'play-other-platforms', guideline: 'Play: Metadata', severity: 'high', title: 'Apple platforms or stores (iOS, iPhone, App Store, Game Center, TestFlight) named in the Play listing text', evidence: apple.slice(0, 6), + ref: PLAY_REFS.metadata, skill: 'aso-basics', fix: 'Remove them from store/listing.md (release notes shared with the App Store: tag the line [apple]); a functional mention ("Sign in with Apple") goes into listing.allowPlatformMentions (owner\'s call). Every Play text write refuses these.' }); const titles: Hit[] = fieldBlocks(listing, /\btitle\b/i).map(b => ({ ...b.at, text: b.text.trim() })); if (!titles.length && c?.app.name) titles.push(...cfg(/\bname\s*:/, c.app.name).map(h => ({ ...h, text: c.app.name }))); const long = titles.filter(t => [...t.text].length > 30); diff --git a/cli/lib/scan/rules.ts b/cli/lib/scan/rules.ts index 1757172..11aeb6d 100644 --- a/cli/lib/scan/rules.ts +++ b/cli/lib/scan/rules.ts @@ -36,7 +36,8 @@ import { consoleLink, consoleUrl } from '../console-links'; import type { FixAction } from '../fix-actions'; import { templateBlockers } from '../template-answers'; -import { BETA_WORDS, competitorRe, OTHER_PLATFORMS, PLACEHOLDER_MARKERS, PLACEHOLDER_TEXT, PRICE_CLAIMS } from '../listing-rules'; +import { fileMentions, GUIDELINE, type PlatformHit, textMentions } from '../cross-store'; +import { BETA_WORDS, competitorRe, PLACEHOLDER_MARKERS, PLACEHOLDER_TEXT, PRICE_CLAIMS } from '../listing-rules'; import type { ShipConfig } from '../config'; import { allSubscriptions } from '../subscriptions'; import { sdkOfProjectPath } from '../privacy-files'; @@ -186,6 +187,17 @@ export function rewardNearReviewApi(sources: { path: string; text: string }[], m } /** Text lines (inside fenced blocks of a listing file, or JSON string values) that match `re`. */ +/** Other platforms named in one store's listing file (and, for the App Store, the screenshot captions), with + * locale, field and line (pitfall 77). */ +export function platformHits(inp: Pick, store: 'apple' | 'play'): Hit[] { + const allow = inp.config?.listing?.allowPlatformMentions; + const file = store === 'apple' ? inp.listings.apple : inp.listings.play; + const hits: PlatformHit[] = file ? fileMentions(store, file.path, file.text, allow) : []; + const cap = store === 'apple' ? inp.listings.captions : undefined; + if (cap) hits.push(...textMentions(cap.text, { store, locale: 'captions', field: 'screenshot captions', allow }).map(h => ({ ...h, file: cap.path, fileLine: h.line }))); + return hits.map(h => ({ file: h.file!, line: h.fileLine!, text: `${h.locale} ${h.field}: "${h.term}" in ${h.text.slice(0, 120)}` })); +} + function listingHits(file: { path: string; text: string } | undefined, re: RegExp, o: { fenced?: boolean; field?: RegExp } = {}): Hit[] { if (!file) return []; const out: Hit[] = []; @@ -439,10 +451,10 @@ export function scanRules(inp: ScanInput): ScanFinding[] { // ---- metadata (iOS listing + screenshot captions) ---- if (apple) { - const other = [...listingHits(inp.listings.apple, OTHER_PLATFORMS), ...listingHits(inp.listings.captions, OTHER_PLATFORMS, { fenced: false })]; + const other = platformHits(inp, 'apple'); if (other.length) - add({ rule: 'other-platforms', guideline: '2.3.10', store: 'apple', severity: 'high', title: 'Other mobile platforms or stores named in the App Store metadata or screenshot captions', evidence: other.slice(0, 4), - fix: 'Remove "Android", "Google Play" and other platforms or stores from the App Store text and screenshots (Play listing text is separate: store/listing.md).', skill: 'aso-basics' }); + add({ rule: 'other-platforms', guideline: GUIDELINE.apple, store: 'apple', severity: 'high', title: 'Other mobile platforms or stores named in the App Store metadata or screenshot captions', evidence: other.slice(0, 6), + fix: 'Remove "Android", "Google Play" and other platforms or stores from the App Store text and screenshots (a What\'s New shared with Play: tag the line [play]); a functional mention goes into listing.allowPlatformMentions (owner\'s call). Every App Store text write refuses these.', skill: 'aso-basics' }); const words = competitorRe(); const kw = [...listingHits(inp.listings.apple, words, { field: /^(keywords|name|subtitle)$/ })]; if (kw.length) diff --git a/cli/lib/whats-new.ts b/cli/lib/whats-new.ts index c1838bd..15953ad 100644 --- a/cli/lib/whats-new.ts +++ b/cli/lib/whats-new.ts @@ -4,6 +4,33 @@ import type { Language } from './config'; import { playCodes } from './config'; import { len, PLAY_LIMITS } from './copy'; import { jargonFindings, jargonMessage } from './jargon'; +import { type CrossStore, fieldsMentions, notesForStore, type PlatformAllow, type PlatformHit, textMentions } from './cross-store'; + +/** One store's draft from shared notes: tagged lines split ([apple] / [play]), and an untagged line that names the + * other side's platform (a "Google Play Games" line for the App Store) left out of this store's draft and reported, + * so a draft never carries it into the wrong store (pitfall 77). Tag the line to make it explicit. Pure. */ +export function draftForStore(text: string, store: CrossStore, allow: readonly PlatformAllow[] = []): { text: string; dropped: string[] } { + const dropped: string[] = []; + const kept = notesForStore(text, store).split('\n').filter(l => { + if (!l.trim() || !textMentions(l, { store, locale: '', field: 'whatsNew', allow }).length) return true; + dropped.push(l.trim()); + return false; + }); + return { text: kept.join('\n').replace(/\n{3,}/g, '\n\n').trim(), dropped }; +} + +/** Note items for one store (items tagged [apple] / [play] go only there, the tag removed). */ +export function itemsForStore(items: NoteItem[], store: CrossStore): NoteItem[] { + return items.flatMap(i => { const t = notesForStore(i.text, store); return t ? [{ ...i, text: t }] : []; }); +} + +/** Other-platform hits in the per-store notes of one language (the texts `whats-new apply` would write). Pure. */ +export function languageNoteMentions(l: Language, text: string, allow: readonly PlatformAllow[] = []): PlatformHit[] { + const out: PlatformHit[] = []; + for (const code of playCodes(l)) out.push(...fieldsMentions('play', code, { whatsNew: notesForStore(text, 'play') }, allow)); + if (l.apple) out.push(...fieldsMentions('apple', l.apple, { whatsNew: notesForStore(text, 'apple') }, allow)); + return out; +} export const NOTES_LIMITS = { play: PLAY_LIMITS.whatsNew, apple: 4000 } as const; /** Roughly what both stores show before "more" on a phone. */ @@ -196,8 +223,10 @@ export interface LangCheck { lang: string; chars: number; play?: { limit: number export function checkLanguageNotes(l: Language, f: NotesFile, sourceText?: string, allow: readonly string[] = []): LangCheck { const chars = len(f.text); const c: LangCheck = { lang: l.id, chars, problems: [], warnings: jargonFindings(f.text, allow).map(jargonMessage) }; - if (playCodes(l).length) { c.play = { limit: NOTES_LIMITS.play, ok: chars <= NOTES_LIMITS.play }; if (!c.play.ok) c.problems.push(`Google Play: ${chars} > ${NOTES_LIMITS.play} characters`); } - if (l.apple) { c.apple = { limit: NOTES_LIMITS.apple, ok: chars <= NOTES_LIMITS.apple }; if (!c.apple.ok) c.problems.push(`App Store: ${chars} > ${NOTES_LIMITS.apple} characters`); } + // each store counts its own notes: lines tagged for the other store are not sent there + const pn = len(notesForStore(f.text, 'play')), an = len(notesForStore(f.text, 'apple')); + if (playCodes(l).length) { c.play = { limit: NOTES_LIMITS.play, ok: pn <= NOTES_LIMITS.play }; if (!c.play.ok) c.problems.push(`Google Play: ${pn} > ${NOTES_LIMITS.play} characters`); } + if (l.apple) { c.apple = { limit: NOTES_LIMITS.apple, ok: an <= NOTES_LIMITS.apple }; if (!c.apple.ok) c.problems.push(`App Store: ${an} > ${NOTES_LIMITS.apple} characters`); } if (!f.text) c.problems.push('empty'); if (f.status === 'translate') c.problems.push('not translated yet (status=translate)'); else if (sourceText !== undefined && f.status !== 'source' && f.text === sourceText.trim()) c.problems.push('identical to the source language: translate it'); @@ -206,16 +235,17 @@ export function checkLanguageNotes(l: Language, f: NotesFile, sourceText?: strin return c; } -/** Writes one language's notes into the listing files (every Play code of the language, its App Store locale). Pure. */ +/** Writes one language's notes into the listing files (every Play code of the language, its App Store locale); lines + * tagged [apple] / [play] go only into that store's notes. Pure. */ export function applyLanguageNotes(md: { play?: string; apple?: string }, l: Language, text: string): { play?: string; apple?: string; changed: string[] } { const out: { play?: string; apple?: string; changed: string[] } = { ...md, changed: [] }; if (md.play !== undefined) for (const code of playCodes(l)) { - const r = setPlayWhatsNew(out.play!, code, text); + const r = setPlayWhatsNew(out.play!, code, notesForStore(text, 'play')); out.play = r.md; out.changed.push(...r.changed.map(x => `play:${x}`)); } if (md.apple !== undefined && l.apple) { - const r = setAppleWhatsNew(out.apple!, l.apple, text); + const r = setAppleWhatsNew(out.apple!, l.apple, notesForStore(text, 'apple')); out.apple = r.md; out.changed.push(...r.changed.map(x => `apple:${x}`)); } diff --git a/cli/listing-store.ts b/cli/listing-store.ts index 4bfb839..bdc6729 100644 --- a/cli/listing-store.ts +++ b/cli/listing-store.ts @@ -15,6 +15,7 @@ // from the config of an app folder). import { appleLocaleIssues, type FieldIssue, playLangIssues } from './lib/listing-rules'; import type { AppleCopy } from './lib/copy'; +import type { PlatformAllow } from './lib/cross-store'; import type { Ctx } from './lib/ctx'; import { confirm, need } from './lib/ctx'; import { done, log, printJson, warn } from './lib/log'; @@ -39,7 +40,7 @@ export interface FieldPlan { field: string; from: string | null; to: string } export interface SetPlan { store: 'play' | 'apple'; lang: string; create: boolean; changes: FieldPlan[]; same: string[]; issues: FieldIssue[]; refused: string | null; target?: string } /** Old -> new for the given fields of one language (an empty and a missing value are the same). Pure. */ -export function setPlan(store: 'play' | 'apple', lang: string, current: Record | null, want: Record, o: { appName: string; editable?: boolean }): SetPlan { +export function setPlan(store: 'play' | 'apple', lang: string, current: Record | null, want: Record, o: { appName: string; editable?: boolean; allow?: readonly PlatformAllow[] }): SetPlan { const changes: FieldPlan[] = []; const same: string[] = []; for (const [f, v] of Object.entries(want)) { @@ -50,8 +51,8 @@ export function setPlan(store: 'play' | 'apple', lang: string, current: Record sent.has(i.field) && !(i.level === 'error' && /is required$/.test(i.msg) && !(want[i.field] !== undefined && !want[i.field]!.trim()))); let refused: string | null = null; if (store === 'apple' && o.editable === false && changes.some(c => c.field !== 'promotionalText' && (APPLE_VERSION_FIELDS as readonly string[]).includes(c.field))) @@ -138,7 +139,7 @@ async function set(ctx: Ctx): Promise { const playName = config.play?.name ?? config.app.name; const now = await playLive(ctx); const cur = now?.find(l => l.language === lang) ?? null; - const p = setPlan('play', lang, cur ? { title: cur.title, short: cur.short, full: cur.full } : null, want, { appName: playName }); + const p = setPlan('play', lang, cur ? { title: cur.title, short: cur.short, full: cur.full } : null, want, { appName: playName, allow: config.listing?.allowPlatformMentions }); show(ctx, p); const errors = p.issues.filter(i => i.level === 'error').length; if (a.has('json')) printJson({ ...p, dry, written: false }); @@ -167,7 +168,7 @@ async function set(ctx: Ctx): Promise { promotionalText: vl?.attributes.promotionalText ?? '', whatsNew: vl?.attributes.whatsNew ?? '', } : null; const appName = config.apple?.name ?? config.app.name; - const p = { ...setPlan('apple', lang, cur, want, { appName, editable: r.editable }), target: r.version ? `version ${r.version.attributes.versionString}, ${r.version.attributes.appVersionState ?? r.version.attributes.appStoreState}` : 'no version' }; + const p = { ...setPlan('apple', lang, cur, want, { appName, editable: r.editable, allow: config.listing?.allowPlatformMentions }), target: r.version ? `version ${r.version.attributes.versionString}, ${r.version.attributes.appVersionState ?? r.version.attributes.appStoreState}` : 'no version' }; show(ctx, p); const errors = p.issues.filter(i => i.level === 'error').length; if (a.has('json')) printJson({ ...p, dry, written: false }); diff --git a/cli/play/listing.ts b/cli/play/listing.ts index a3b6d67..2d86894 100644 --- a/cli/play/listing.ts +++ b/cli/play/listing.ts @@ -12,6 +12,7 @@ // storebound play listing pull [--write] [--json] live listings -> diff -> (with --write) the Play listing file import { existsSync, readFileSync, writeFileSync } from 'node:fs'; import { parsePlayListing } from '../lib/copy'; +import { fieldsMentions, refuseMentions } from '../lib/cross-store'; import { compactDiff } from '../lib/diff'; import { mergePlayListing, overLimits } from '../lib/listing-pull'; import { counts, draftReason, draftSections, type ItemPlan, itemLines, planItem, type Skipped } from '../lib/listing-plan'; @@ -21,6 +22,12 @@ import { done, log, printJson, step, warn } from '../lib/log'; import { playClient } from './client'; import { stdinIsTTY } from '../lib/tty'; +/** Play release notes that name iOS, iPhone, App Store, ... are refused before any edit, dry runs included (pitfall 77). */ +export function refusePlayNotes(ctx: Ctx, notes: { language: string; text: string }[], what: string): void { + const allow = ctx.loaded.config.listing?.allowPlatformMentions; + refuseMentions(notes.flatMap(n => fieldsMentions('play', n.language, { whatsNew: n.text }, allow)), what); +} + export function readPlayCopy(ctx: Ctx) { const { config, resolve } = ctx.loaded; const file = resolve(config.play?.listing ?? 'store/listing.md'); @@ -125,6 +132,8 @@ export async function run(ctx: Ctx): Promise { skipped.push({ key: c.lang, reason: draftReason(st) }); return false; }); + // Play Metadata policy: iOS / App Store / Game Center in Play text stop the run, dry runs included (pitfall 77) + refuseMentions(copy.flatMap(c => fieldsMentions('play', c.lang, { title: c.title, short: c.short, full: c.full }, config.listing?.allowPlatformMentions)), `play listing${a.has('dry') ? ' (dry run)' : ''}`); const details = { defaultLanguage: config.play?.defaultLanguage ?? 'en-US', contactEmail: config.app.contactEmail, contactWebsite: config.app.website }; if (!all.some(c => c.lang === details.defaultLanguage) && !a.has('only')) throw new Error(`listing has no section for the default language ${details.defaultLanguage}`); if (!a.has('json')) log('play', `${copy.length} listings: ${copy.map(c => c.lang).join(', ')}${config.play?.video ? ` · promo video ${config.play.video}` : ''}`); diff --git a/cli/play/release.ts b/cli/play/release.ts index d0d6a45..10d9d99 100644 --- a/cli/play/release.ts +++ b/cli/play/release.ts @@ -14,7 +14,7 @@ import { done, log, warn } from '../lib/log'; import { aabInfo } from '../lib/gradle'; import { playClient } from './client'; import { usedVersionCodes } from './next-version-code'; -import { readPlayCopy } from './listing'; +import { readPlayCopy, refusePlayNotes } from './listing'; const TRACKS = ['internal', 'alpha', 'beta', 'production']; @@ -45,9 +45,10 @@ export async function run(ctx: Ctx): Promise { 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'); + const notes = readPlayCopy(ctx).filter(c => c.whatsNew).map(c => ({ language: c.lang, text: c.whatsNew })); + refusePlayNotes(ctx, notes, `play release notes${a.has('dry') ? ' (dry run)' : ''}`); 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, ctl) => { diff --git a/cli/play/upload.ts b/cli/play/upload.ts index 8e432be..c7489ca 100644 --- a/cli/play/upload.ts +++ b/cli/play/upload.ts @@ -13,7 +13,7 @@ import { aabInfo } from '../lib/gradle'; import { done, log, printJson } from '../lib/log'; import { nextVersionCode } from '../lib/release'; import { playClient } from './client'; -import { readPlayCopy } from './listing'; +import { readPlayCopy, refusePlayNotes } from './listing'; import { usedVersionCodes } from './next-version-code'; const TAG = 'upload'; @@ -43,6 +43,7 @@ export async function run(ctx: Ctx): Promise { const dry = a.has('dry'); const json = a.has('json'); const notes = readPlayCopy(ctx).filter(c => c.whatsNew).map(c => ({ language: c.lang, text: c.whatsNew })); + refusePlayNotes(ctx, notes, `play upload release notes${dry ? ' (dry run)' : ''}`); const play = await playClient(root, pkg); const { used, current } = await play.read(async id => ({ used: await usedVersionCodes(play, id), diff --git a/cli/validate.ts b/cli/validate.ts index 72aa93c..cf9fc1b 100644 --- a/cli/validate.ts +++ b/cli/validate.ts @@ -34,6 +34,8 @@ import type { ScanFinding } from './lib/scan/rules'; import { playClient } from './play/client'; import { listOneTimeProducts } from './play/products'; import { creativeNote } from './shots/creative'; +import { fixFor, GUIDELINE, hitLine } from './lib/cross-store'; +import { listingFileMentions } from './lib/listing-mentions'; /** Profile facts for the checks: config + local credentials + public URL checks (no store API). */ export async function collectProfile(loaded: Loaded): Promise { @@ -204,6 +206,11 @@ export async function run(ctx: Ctx): Promise { try { findings.push(...playRules({ ...(await collectPlay(ctx)), renders: local?.play })); } catch (e) { findings.push({ store: 'play', level: 'blocker', code: 'api', msg: (e as Error).message.slice(0, 400) }, ...rendersFindings('play', local?.play)); } } else if (a.has('play')) warn('validate', 'no play section in the config'); + // other platforms named in a store's listing text (App Store 2.3.10, Play Metadata): blockers (pitfall 77) + try { + for (const h of listingFileMentions(ctx.loaded, { apple: (both || a.has('apple')) && !!config.apple, play: (both || a.has('play')) && !!config.play })) + findings.push({ store: h.store, level: 'blocker', code: 'other-platforms', msg: `${GUIDELINE[h.store]}: ${hitLine(h)}`, fix: fixFor(h.store, h.field) }); + } catch (e) { warn('validate', `platform mentions: ${(e as Error).message}`); } // template compliance answers: the scan reports them; without the scan, here if (a.has('no-scan')) for (const msg of templateBlockers(config)) findings.push({ store: config.apple ? 'apple' : 'play', level: 'blocker', code: 'template-answers', msg }); if (!a.has('no-scan')) { diff --git a/cli/whats-new.ts b/cli/whats-new.ts index 02e9f32..46bcd29 100644 --- a/cli/whats-new.ts +++ b/cli/whats-new.ts @@ -17,6 +17,10 @@ // the translation. Existing translated files are kept unless --force. // storebound whats-new check [--dir store/whats-new] [--json] limits per store (Play 500, App Store 4000), untranslated files // storebound whats-new apply [--dir store/whats-new] [--dry] [--json] checked files -> both listing files +// Per store: a line tagged `[apple]` or `[play]` (also `• [play] ...`, or a `[play]` line heading a block up to the next +// blank line) goes only into that store's notes. check / apply refuse notes that name the other side's platform +// (Android / Google Play in App Store notes: Guideline 2.3.10; iOS / App Store in Play notes) unless +// listing.allowPlatformMentions allows the line; the draft leaves such untagged lines out of the other store (pitfall 77). import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import type { Language } from './lib/config'; @@ -25,10 +29,11 @@ import type { Ctx } from './lib/ctx'; import { done, log, printJson, warn } from './lib/log'; import { textTable } from './lib/table'; import { - applyLanguageNotes, checkLanguageNotes, checkNotes, cutNotes, findNotesSource, formatNotes, type LangCheck, NOTES_LIMITS, type NoteItem, type NotesFile, noteItems, notesFileText, parseNotesFile, + applyLanguageNotes, checkLanguageNotes, checkNotes, cutNotes, draftForStore, findNotesSource, formatNotes, itemsForStore, languageNoteMentions, type LangCheck, NOTES_LIMITS, type NoteItem, type NotesFile, noteItems, notesFileText, parseNotesFile, resolveLanguages, setAppleWhatsNew, setPlayWhatsNew, } from './lib/whats-new'; import * as rt from './lib/rt'; +import { hitLine } from './lib/cross-store'; const TAG = 'whats-new'; const storeCode = (l: Language): string => l.apple ?? playCodes(l)[0] ?? l.id; @@ -52,14 +57,16 @@ function printChecks(checks: LangCheck[]): void { for (const c of checks) for (const w of c.warnings) warn(TAG, `${c.lang}: ${w}`); } -async function languagesFlow(ctx: Ctx, draft: { play: string; apple: string }): Promise { +async function languagesFlow(ctx: Ctx, draft: { play: string; apple: string; shared: string }): Promise { const { config, resolve } = ctx.loaded; const a = ctx.args; const dir = resolve(a.get('dir') ?? 'store/whats-new'); const langs = resolveLanguages(config.languages, a.list('languages')); const [src, ...rest] = langs; - // the source text: the shorter Play draft when the source language is on Play (it has to fit 500) - const text = playCodes(src!).length ? draft.play : draft.apple; + // the source text: the shorter Play draft when the source language is on Play (it has to fit 500); with [apple] / + // [play] tags the shared text keeps them (apply splits it per store) + const tagged = draft.shared !== draft.play || draft.shared !== draft.apple; + const text = tagged && /\[(apple|play|ios|android)\]/i.test(draft.shared) ? draft.shared : playCodes(src!).length ? draft.play : draft.apple; const files: { l: Language; f: NotesFile; write: boolean; note: string }[] = [{ l: src!, f: { lang: src!.id, source: src!.id, status: 'source', text }, write: true, note: 'draft (source)' }]; const hook = a.get('translate'); for (const l of rest) { @@ -97,6 +104,10 @@ export async function run(ctx: Ctx): Promise { const files = readDir(dir, config.languages); if (!files.length) throw new Error(`${dir}: no .md files`); const checks = checkAll(files, config.whatsNew?.allowWords ?? []); + // other platforms named in a store's notes: a blocker for check and apply (pitfall 77) + const hits = files.flatMap(({ l, f }) => languageNoteMentions(l, f.text, config.listing?.allowPlatformMentions)); + for (const h of hits) { const c = checks.find(x => x.lang === files.find(y => playCodes(y.l).includes(h.locale) || y.l.apple === h.locale)?.l.id); c?.problems.push(`${h.store === 'apple' ? 'App Store' : 'Google Play'} line ${h.line}: "${h.term}" (${h.store === 'apple' ? '2.3.10' : 'Play: Metadata'})`); } + for (const h of hits) warn(TAG, `refused: ${hitLine(h)}`); const bad = checks.filter(c => c.problems.some(p => !p.startsWith('first line'))); if (a._[0] === 'check' || bad.length) { if (a.has('json')) printJson({ dir, checks, ok: !bad.length }); @@ -124,21 +135,30 @@ export async function run(ctx: Ctx): Promise { const version = a.get('release') ?? (() => { try { return (JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { version?: string }).version; } catch { return undefined; } })(); const source = a.has('from-git') ? undefined : findNotesSource({ version, source: config.whatsNew?.source, read: rel => { const p = resolve(rel); return existsSync(p) ? readFileSync(p, 'utf8') : undefined; } }); const hook = a.get('hook'); - let play: string, apple: string, subjects: string[] = [], items: NoteItem[] = []; + let play: string, apple: string, shared: string, subjects: string[] = [], items: NoteItem[] = []; if (source) { log(TAG, `notes from ${source.path} (${source.kind === 'changelog' ? 'CHANGELOG section' : source.kind === 'release-doc' ? 'release doc' : 'whatsNew.source'}), not the git log`); const body = hook ? `${hook}\n${source.text}` : source.text; - play = cutNotes(body, NOTES_LIMITS.play); - apple = cutNotes(body, NOTES_LIMITS.apple); + const dp = draftForStore(body, 'play', config.listing?.allowPlatformMentions), da = draftForStore(body, 'apple', config.listing?.allowPlatformMentions); + for (const [s, d] of [['Google Play', dp], ['App Store', da]] as const) for (const l of d.dropped) warn(TAG, `left out of the ${s} draft (names another platform; tag it [${s === 'App Store' ? 'play' : 'apple'}] in ${source.path}): ${l}`); + shared = cutNotes(body, NOTES_LIMITS.apple); + play = cutNotes(dp.text, NOTES_LIMITS.play); + apple = cutNotes(da.text, NOTES_LIMITS.apple); } else { subjects = git(['log', range, '--no-merges', '--format=%s'], root).split('\n').filter(Boolean); items = noteItems(subjects); log(TAG, `${subjects.length} commits since ${since || 'the first commit'} -> ${items.length} items, drafted from commit messages (no docs/RELEASE-.md, CHANGELOG section or whatsNew.source): rewrite them in player words`); - play = formatNotes(items, { hook, limit: NOTES_LIMITS.play }); - apple = formatNotes(items, { hook, limit: NOTES_LIMITS.apple }); + const pick = (store: 'play' | 'apple') => { + const d = draftForStore(formatNotes(itemsForStore(items, store), { hook, limit: NOTES_LIMITS[store] }), store, config.listing?.allowPlatformMentions); + for (const l of d.dropped) warn(TAG, `left out of the ${store === 'apple' ? 'App Store' : 'Google Play'} draft (names another platform): ${l}`); + return d.text; + }; + shared = formatNotes(items, { hook, limit: NOTES_LIMITS.apple }); + play = pick('play'); + apple = pick('apple'); } for (const [store, text] of [['play', play], ['apple', apple]] as const) for (const p of checkNotes(text, store, allow)) warn(TAG, `${store}: ${p}`); - if (a.has('languages')) return languagesFlow(ctx, { play, apple }); + if (a.has('languages')) return languagesFlow(ctx, { play, apple, shared }); if (a.has('json')) printJson({ since: since || null, source: source ? { kind: source.kind, path: source.path } : null, commits: subjects.length, items, play, apple, limits: NOTES_LIMITS }); else console.log(`--- draft (Play, ${[...play].length}/500) ---\n${play}\n---`); if (a.has('dry')) return; diff --git a/docs/pitfalls.md b/docs/pitfalls.md index 85d33d1..066c914 100644 --- a/docs/pitfalls.md +++ b/docs/pitfalls.md @@ -9,6 +9,8 @@ fails without the fix. | # | date | lesson | guard | |---|---|---|---| +| 78 | 2026-10 | `storebound api --yes` with stdout piped or redirected printed a dry run and exited 0 (twice); the owner took it as sent. | `decide` (`cli/api/gate.ts`) refuses with `NOT_A_TTY`: exit 1, "refused: writes through `storebound api` need an interactive terminal ... Nothing was sent." on stderr, the dedicated command named; without `--yes` still a dry run. `tests/api.test.ts`. | +| 77 | 2026-10 | A Mac App Store version was rejected under Guideline 2.3.10: its What's New came from release notes shared with Google Play ("Google Play Games", "Android"); storebound wrote it without a word. Play's Metadata policy is the mirror case. | `cli/lib/cross-store.ts`: other platforms per locale, field and line (App Store text: Android, Google Play (Games), Play Store, Galaxy Store, Amazon Appstore, Steam, Microsoft Store, AppGallery, localized forms; Play text: iOS, iPhone, iPad, App Store, Apple Arcade, Game Center, TestFlight). Every text write refuses (apple / play listing, play release / upload notes, listing set, whats-new check / apply, the desktop editor and storebound edit); check / validate blockers; scan `other-platforms` (2.3.10) and `play-other-platforms` (Play: Metadata). `listing.allowPlatformMentions` for the owner's functional mentions; whats-new splits `[apple]` / `[play]` lines. `tests/cross-store.test.ts`. | | 74 | 2026-10 | Apple sharpened Guideline 2.3.1 (hidden, dormant or undocumented features; obfuscation that hides features is grounds for removal). Apps with remote config / feature flags or remote paywalls whose review notes said nothing risk a rejection or removal when a feature or a hard paywall is switched on after review; Play's Deceptive behavior policy covers the same. Paywall tests and designs are fine once review knows; a business-model change needs a new review and a description update. | `remoteFeatureFindings` (`cli/lib/scan/rules.ts`, SDK table `REMOTE_SDKS` in `cli/lib/scan/sdks.ts`): scan / validate report `remote-features` for Apple (2.3.1) and Play (Deceptive behavior), medium, unless the review notes (apple.info.reviewNotes, reviewAccess.instructions, accounts.inApp) mention remote config, flags, A/B, a paywall test, an experiment or "remotely"; check prints it as a warning. Warn only: storebound never writes the note; the templates carry a commented example line. Code obfuscators are a low note, minify alone nothing. `tests/remote-features.test.ts`. | | 73 | 2026-10 | A game with guest play (no sign-in; `reviewAccess.signInRequired: false`, Play Sign in details "No restrictions") was rejected by Play: "Play Console Requirements: provide valid login credentials". The first screen had an empty player-name field with Continue disabled until a name was typed and an "I Have a Code" link to a transfer / recovery code dialog; the reviewer read it as a login wall. | `profileIssues` (`cli/lib/profile.ts`, called by `check` with `SIGNALS.firstRunGate` hits from `cli/lib/scan/rules.ts`): warns "Play may reject as a login wall; add guest steps" for a Play app with a first-run gate or IAP and no `reviewAccess.instructions`, and when the steps exceed 500 characters. The `play-sign-in-details` plan (`cli/lib/console-play-plans.ts`): with guest steps "restricted" and one entry "Guest play (no account needed)" without credentials, the steps in "Any other information", the dialog's required full-access box as an owner step; Add and Save the agent's. `tests/guest-login-wall.test.ts`. | | 72 | 2026-10 | A game: after Play production 1.0.0 (3) was rejected (Broken Functionality), the fix 1.0.1 (5) went through upload and track updates, then edits.validate answered 400 "Changes cannot be sent for review automatically. Please set the query parameter changesNotSentForReview to true". Play refuses the automatic send after a rejection, with other pending changes or managed publishing. | `cli/play/client.ts` (edit flow) with `cli/play/review-pending.ts`: on exactly that 400 the same edit is validated and committed again with changesNotSentForReview=true (a dry run validates that way and says so), the Publishing overview deep link is printed (the owner's button), the commit is recorded in .storebound/ and `play status` shows it; `--not-sent-for-review` on play release / upload / rollout / listing / images (MCP `not_sent_for_review`). `tests/play-not-sent-for-review.test.ts`. Only edits.commit takes changesNotSentForReview: validate answers 400 "Unknown name ... Cannot bind query parameter" (the fake store does too). | diff --git a/skills/aso-basics/SKILL.md b/skills/aso-basics/SKILL.md index ba781d8..c843fb9 100644 --- a/skills/aso-basics/SKILL.md +++ b/skills/aso-basics/SKILL.md @@ -25,6 +25,9 @@ true; never use competitor or other apps' or games' names, "best / #1", or unrel - **Screenshot captions**: write them with the words people search for ("Budget planner with shared lists", "Match 3 puzzles offline", not "Fun awaits"). Claims that Apple reads caption text for search ranking are unverified; good captions help conversion either way. - Changing keywords needs a new version (submitted with it); promotional text (170) changes any time but is not indexed. +- **No other platforms (2.3.10)**: no Android, Google Play (Games), Play Store, Galaxy Store, Amazon Appstore, Steam, + Microsoft Store, AppGallery (and localized forms such as "Google Play Spiele", "安卓") in any App Store field, + What's New included. Every App Store text write refuses them (store-pitfalls 77). ## Google Play - **Indexed**: title (30), short description (80), full description (4000). There is no keyword field. @@ -33,6 +36,9 @@ true; never use competitor or other apps' or games' names, "best / #1", or unrel - **No stuffing**: a word in more than ~3 % of the full description, keyword lists, ALL CAPS titles, emoji in the title, or "best / top / #1" break the metadata policy. `check --aso` warns on these. - Localize every listing you can; Play machine-translates otherwise, which ranks and converts worse. +- **No Apple platforms (Metadata policy)**: no iOS, iPhone, iPad, App Store, Apple Arcade, Game Center or TestFlight in + the title, descriptions or release notes; every Play text write refuses them. A real sign-in button name ("Sign in + with Apple") stays only through the owner's `listing.allowPlatformMentions` entry. ## Workflow 1. List 20-30 candidate terms with the owner: what people would type to find this app (the job it does, the problem it solves; for a game: diff --git a/skills/review-rejections/SKILL.md b/skills/review-rejections/SKILL.md index 2648094..8411d58 100644 --- a/skills/review-rejections/SKILL.md +++ b/skills/review-rejections/SKILL.md @@ -87,6 +87,11 @@ Plain, polite, specific; one guideline per paragraph; no blame, no threats, no " - **2.3 Accurate metadata**: screenshots must show the real app (for a game: real gameplay); no prices, no "free" claims for paid items, no other platforms' UI; keywords without competitor names; age rating answers that match the content. +- **2.3.10 Accurate Metadata (other platforms)**: "Android", "Google Play", "Google Play Games" or another store in + any App Store text, often a What's New copied from notes shared with Play (store-pitfalls 77). Fix: remove the + lines (tag shared notes `[play]` / `[apple]`, `storebound whats-new apply`), `storebound check` must show no + `other platform` blocker, push with `apple listing --version x.y.z`, reply "removed the references to other + platforms" and resubmit. Play's mirror case is the Metadata policy (iOS, App Store, Game Center in Play text). - **2.3.1 Hidden or undocumented features** (Play: Deceptive behavior): remote config, feature flags or a remote paywall the review notes did not mention (`storebound scan` rule `remote-features`, store-pitfalls 74). Fix: say in the notes which SDK changes what remotely; a business-model change needs a new review and a description update. diff --git a/skills/store-api/SKILL.md b/skills/store-api/SKILL.md index 2be93ac..485ab59 100644 --- a/skills/store-api/SKILL.md +++ b/skills/store-api/SKILL.md @@ -36,8 +36,10 @@ storebound api apple salesReports_getCollection --param ... --out report.gz # ## Write (only the owner sends) 1. Run the write without `--yes`: it prints the exact request (method, URL, body; the key is never shown) and sends nothing. Show that to the owner. -2. The owner runs it in their own terminal with `--yes`. Outside an interactive terminal, under MCP or in the desktop - app, a write is never sent, whatever the flags. +2. The owner runs it in their own terminal with `--yes`. Under MCP or in the desktop app a write is never sent, + whatever the flags. `--yes` with stdout not a TTY (piped `| tail`, redirected `> out.json`, an agent's shell) is + refused: exit 1 and "refused: writes through `storebound api` need an interactive terminal ... Nothing was sent." + on stderr (store-pitfalls 78). Never pipe or redirect a write; use the dedicated command the message names. 3. Owner-only operations (cli/api/gate.ts: every DELETE, submissions and their cancel, release requests, phased release changes, product page test start / stop, price schedules and price migrations, review replies, tester and user invitations, Play `edits.commit`, product activation, refunds, revokes and cancels, app signing) also ask for diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 0479986..3bb746e 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -763,7 +763,8 @@ that fails without the fix (see CONTRIBUTING.md). bundleIdCapabilities answers, lag, a write that never sticks). ## 66. `storebound api apple ... --body f.json --yes` only dry-ran from an agent -- **Do:** expected: writes through `storebound api` are sent only from an interactive terminal, by design. Use the +- **Do:** expected: writes through `storebound api` are sent only from an interactive terminal, by design (since + pitfall 78 it is a loud refusal with exit 1, not a dry run). Use the dedicated command the message names (bundle id capabilities: `apple signing ensure`; IAPs: `apple iap`; listing: `apple listing`, ...), which runs anywhere with its own dry run and read-back. - **Guard:** `dedicatedCommand` (cli/api/gate.ts), `tests/signing-capabilities.test.ts`. @@ -925,3 +926,26 @@ that fails without the fix (see CONTRIBUTING.md). Uploading and selecting are normal steps, not owner buttons; the version's Submit for Review stays the owner's. - **Guard:** `cli/apple/creative-assets.ts`, `tests/creative-assets.test.ts` (fake App Store Connect: dry run, upload, waiting, select, replace on a changed file, nothing on the same file). + +## 77. What's New shared with Play rejected on the App Store (2.3.10) +- **Symptom:** a Mac App Store version was rejected under Guideline 2.3.10 (Accurate Metadata): its What's New came + from release notes shared with Google Play and had "Google Play Games" and "Android" lines. storebound wrote it + without a word (the old check was a warning in the editor only). +- **Cause:** one notes source for both stores, no per-store split, and no write that refused other platforms. Google + Play's Metadata policy is the mirror case (iOS, iPhone, App Store, Game Center, TestFlight in Play text). +- **Do:** tag store-specific lines `[play]` / `[apple]` in shared notes (whats-new skill); `storebound check` must + show no `other platform` line. A functional mention (a "Continue with Google" / "Sign in with Apple" button) is the + owner's call: `listing.allowPlatformMentions: [{ store, text, reason }]`. Never add an entry yourself. +- **Guard:** `cli/lib/cross-store.ts` (term lists, per locale / field / line, the allowlist, `notesForStore`). + Refused before anything is sent, dry runs included: `apple listing`, `play listing`, `play release` / + `play upload` (release notes), `listing set`, `whats-new check` / `apply`, the desktop editor and `storebound edit` + (`appleLocaleIssues` / `playLangIssues` errors). `check` / `validate` blockers (`other-platforms`), `scan` rules + `other-platforms` (2.3.10) and `play-other-platforms` (Play: Metadata). `tests/cross-store.test.ts`. + +## 78. `storebound api ... --yes` piped or redirected became a silent dry run +- **Symptom:** `storebound api apple --yes | tail` (or `> out.json`) printed a dry run and exited 0; the + owner thought it was sent. Happened twice. +- **Cause:** writes need an interactive terminal; without one the gate fell back to a dry run. +- **Do:** run writes without a pipe or redirect in a terminal, or use the dedicated storebound command. +- **Guard:** `decide` in `cli/api/gate.ts` refuses (`NOT_A_TTY`): exit 1, the message on stderr, nothing sent, the + dedicated command named. Without `--yes` a write is still a plain dry run. `tests/api.test.ts`. diff --git a/skills/whats-new/SKILL.md b/skills/whats-new/SKILL.md index 09de76c..f0748b7 100644 --- a/skills/whats-new/SKILL.md +++ b/skills/whats-new/SKILL.md @@ -29,6 +29,20 @@ CI, PR, OTA, fingerprint, bump, deps, ...), version-control words (commit, merge code identifiers (`saveSlot`, `max_lives`). Each warning names the word and a plain alternative. Rewrite the line; when a flagged word is a real player-facing term (a character called "Sentry"), add it to `whatsNew.allowWords`. +## One source, two stores: tag store-specific lines +A notes source shared by both stores must not carry one store's lines into the other: a Mac App Store version was +rejected under Guideline 2.3.10 for a What's New with "Google Play Games" and "Android" lines (store-pitfalls 77). +- Tag a line for one store: `[play] Achievements on Google Play Games.` or `• [apple] Game Center leaderboards.` + (also `[android]` / `[ios]`). A line that is only `[play]` starts a block for that store up to the next blank line. + Untagged lines go to both stores; the tag itself is removed. +- The draft leaves an untagged line that names the other side's platform out of that store's draft and says so + (tag it to make it explicit). `whats-new check` and `apply` refuse notes that still name Android, Google Play, + Steam, ... in App Store text or iOS, iPhone, App Store, Game Center, TestFlight in Play text, with language, line + and term; `apple listing`, `play listing`, `play release` / `play upload` (release notes), `listing set` and the + desktop editor refuse the same, dry runs included. +- A functional mention (a "Continue with Google" or "Sign in with Apple" button) is the owner's call: an entry in + `listing.allowPlatformMentions` (`{ store, text, reason }`). Never add one yourself to get past the check. + ## Write it for your users 1. Run `storebound whats-new --dry`, read the draft with the owner. 2. Rewrite: @@ -68,5 +82,5 @@ when a flagged word is a real player-facing term (a character called "Sentry"), ## Gotchas - Squash-merged repos: the PR titles are the subjects; keep them in conventional form (`feat: ...`) to get clean drafts. -- Commits marked `[skip notes]` or `[internal]` are left out. +- Commits marked `[skip notes]` or `[internal]` are left out; `feat: [play] ...` subjects go only into the Play draft. - Release notes are public: nothing about cheats, exploits, unreleased content or private names. diff --git a/tests/api.test.ts b/tests/api.test.ts index 7d6bed3..ac4bf1b 100644 --- a/tests/api.test.ts +++ b/tests/api.test.ts @@ -167,11 +167,11 @@ describe('write gating', () => { const w = { ...base, kind: 'write' as const, method: 'PATCH' }; expect(decide(w)).toMatchObject({ action: 'dry', why: expect.stringContaining('--yes') }); expect(decide({ ...w, yes: true, dry: true }).action).toBe('dry'); - expect(decide({ ...w, yes: true, tty: false })).toMatchObject({ action: 'dry', why: expect.stringContaining('not an interactive terminal') }); + expect(decide({ ...w, yes: true, tty: false })).toMatchObject({ action: 'refuse', why: expect.stringContaining('need an interactive terminal') }); expect(decide({ ...w, yes: true })).toEqual({ action: 'send' }); const o = { ...w, kind: 'owner' as const }; expect(decide({ ...o, yes: true })).toEqual({ action: 'confirm', typed: true }); - expect(decide({ ...o, yes: true, tty: false }).action).toBe('dry'); + expect(decide({ ...o, yes: true, tty: false }).action).toBe('refuse'); // MCP / desktop: never a write, whatever the flags expect(decide({ ...w, yes: true, agent: true }).action).toBe('refuse'); expect(decide({ ...o, yes: true, agent: true })).toMatchObject({ action: 'refuse', why: expect.stringContaining('never through MCP') }); @@ -222,10 +222,16 @@ describe('the CLI never sends a write it should not', () => { expect(r.code).toBe(0); expect(JSON.parse(r.out)).toMatchObject({ dryRun: true, gate: 'write', request: { method: 'PUT', url: 'https://androidpublisher.googleapis.com/androidpublisher/v3/applications/com.example.app/edits/1/tracks/beta' } }); }); - test('--yes outside a terminal still only prints', () => { + test('--yes outside a terminal (piped / redirected) is refused loudly: exit 1, stderr, nothing sent', () => { const r = cli(['apple', 'DELETE', '/v1/appScreenshots/1', '--yes']); + expect(r.code).not.toBe(0); + expect(r.err).toContain('refused: writes through `storebound api` need an interactive terminal'); + expect(r.err).toContain('Nothing was sent'); + expect(r.out).not.toContain('dry run'); + }); + test('without --yes, a piped write is still a plain dry run (exit 0)', () => { + const r = cli(['apple', 'DELETE', '/v1/appScreenshots/1']); expect(r.code).toBe(0); - expect(r.out).toContain('not an interactive terminal'); expect(r.out).toContain('owner only: this deletes'); }); test('under MCP and in api get, writes are refused', () => { diff --git a/tests/cross-store.test.ts b/tests/cross-store.test.ts new file mode 100644 index 0000000..4400c8f --- /dev/null +++ b/tests/cross-store.test.ts @@ -0,0 +1,171 @@ +// Pitfall 77: other platforms or stores named in one store's text (App Store 2.3.10, Play Metadata policy). +import { describe, expect, test } from 'bun:test'; +import { cpSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileMentions, notesForStore, refuseMentions, textMentions, type PlatformAllow } from '../cli/lib/cross-store'; +import { appleLocaleIssues, playLangIssues } from '../cli/lib/listing-rules'; +import { setPlan } from '../cli/listing-store'; +import { getByPath, parseOps, planEdits, type EditSources } from '../cli/lib/edit'; +import { applyLanguageNotes, checkLanguageNotes, draftForStore, languageNoteMentions } from '../cli/lib/whats-new'; +import { runScan } from '../cli/lib/scan'; + +const APPLE_MD = `# App Store + +## en-US · English + +### description +\`\`\` +A calm puzzle game. +\`\`\` + +### whatsNew +\`\`\` +New levels. +Achievements on Google Play Games. +Fixed a crash on Android 14. +\`\`\` + +## de-DE · Deutsch + +### whatsNew +\`\`\` +Neue Level. +Erfolge in Google Play Spiele. +\`\`\` +`; + +const PLAY_MD = `# Listing + +## English + + +### Play short description (max 80) +\`\`\` +A calm puzzle game +\`\`\` + +### Play full description (max 4000) +\`\`\` +Play offline. +Also on iPhone and iPad. +\`\`\` +`; + +describe('the checker: per locale, per line', () => { + test('App Store text: the exact term, field, locale, line and file line; longest term wins', () => { + const hits = fileMentions('apple', 'store/appstore.md', APPLE_MD); + expect(hits.map(h => [h.locale, h.field, h.line, h.term, h.fileLine])).toEqual([ + ['en-US', 'whatsNew', 2, 'Google Play Games', 13], + ['en-US', 'whatsNew', 3, 'Android', 14], + ['de-DE', 'whatsNew', 2, 'Google Play Spiele', 22], + ]); + expect(hits[0]!.fix).toContain('[play]'); + }); + test('Play text: iPhone / iPad with the Play field name', () => { + const hits = fileMentions('play', 'store/listing.md', PLAY_MD); + expect(hits.map(h => [h.locale, h.field, h.line, h.term])).toEqual([['en-US', 'full', 2, 'iPhone'], ['en-US', 'full', 2, 'iPad']]); + }); + test('whole words only; localized and CJK forms; tags for the other store', () => { + expect(textMentions('Androids are robots. androidal', { store: 'apple', locale: 'x', field: 'description' })).toEqual([]); + expect(textMentions('Full steam ahead', { store: 'apple', locale: 'x', field: 'description' })).toEqual([]); + expect(textMentions('Jetzt auf Steam', { store: 'apple', locale: 'x', field: 'description' }).map(h => h.term)).toEqual(['Steam']); + expect(textMentions('支持安卓', { store: 'apple', locale: 'zh-Hans', field: 'description' }).map(h => h.term)).toEqual(['安卓']); + expect(textMentions('[play] Cloud saves', { store: 'apple', locale: 'x', field: 'whatsNew' }).map(h => h.term)).toEqual(['[play]']); + expect(textMentions('a fair app store', { store: 'play', locale: 'x', field: 'full' })).toEqual([]); + expect(textMentions('Syncs with Game Center and TestFlight builds on iOS', { store: 'play', locale: 'x', field: 'full' }).map(h => h.term)).toEqual(['Game Center', 'TestFlight', 'iOS']); + }); +}); + +describe('the allowlist: only the owner\'s entries, matched per line', () => { + const allow: PlatformAllow[] = [{ store: 'play', text: 'Sign in with Apple', reason: 'the sign-in button' }, { store: 'apple', text: 'Continue with Google Play Games', reason: 'cross-progress button' }]; + test('an allowed line keeps its terms; other lines and the other store still hit', () => { + expect(textMentions('Tap Sign in with Apple to start', { store: 'play', locale: 'en-US', field: 'full', allow })).toEqual([]); + expect(textMentions('Also on iPhone', { store: 'play', locale: 'en-US', field: 'full', allow }).length).toBe(1); + expect(textMentions('Sign in with Apple', { store: 'apple', locale: 'en-US', field: 'description', allow })).toEqual([]); + expect(textMentions('Continue with Google Play Games', { store: 'apple', locale: 'en-US', field: 'description', allow })).toEqual([]); + expect(textMentions('Continue with Google Play Games on Android', { store: 'apple', locale: 'en-US', field: 'description', allow }).map(h => h.term)).toEqual(['Android']); + }); +}); + +describe('writes refuse for both stores', () => { + test('listing rules: an error for each store (the desktop editor and storebound edit stop on it)', () => { + const a = appleLocaleIssues('en-US', { subtitle: 's', promotionalText: 'p', keywords: 'puzzle', description: 'd', whatsNew: 'Now on Google Play' }, 'Game'); + expect(a.find(i => i.field === 'whatsNew')).toMatchObject({ level: 'error', msg: expect.stringContaining('2.3.10') }); + const p = playLangIssues('en-US', { short: 'A game', full: 'Play it on your iPad', whatsNew: 'Fixed TestFlight builds' }, 'Game'); + expect(p.filter(i => i.level === 'error').map(i => i.field).sort()).toEqual(['full', 'whatsNew']); + expect(p.find(i => i.field === 'full' && i.level === 'error')!.msg).toContain('Play: Metadata'); + expect(appleLocaleIssues('en-US', { subtitle: 's', promotionalText: 'p', keywords: 'puzzle', description: 'Sign in with Google', whatsNew: 'x' }, 'Game', + [{ store: 'apple', text: 'Sign in with Google', reason: 'button' }]).some(i => i.level === 'error')).toBe(false); + }); + test('store-only listing edit (listing set): both stores refused on the fields it sends', () => { + const ap = setPlan('apple', 'en-US', { whatsNew: 'old' }, { whatsNew: 'Now with Android cross-play' }, { appName: 'Game', editable: true }); + expect(ap.issues.some(i => i.level === 'error' && i.field === 'whatsNew')).toBe(true); + const pl = setPlan('play', 'en-US', { title: 'Game', short: 'Old', full: 'Full.' }, { short: 'The best iOS puzzle' }, { appName: 'Game' }); + expect(pl.issues.some(i => i.level === 'error' && i.field === 'short')).toBe(true); + const ok = setPlan('play', 'en-US', { title: 'Game', short: 'Old', full: 'Full.' }, { short: 'Sign in with Apple supported' }, { appName: 'Game', allow: [{ store: 'play', text: 'Sign in with Apple', reason: 'button' }] }); + expect(ok.issues.some(i => i.level === 'error')).toBe(false); + }); + test('the desktop editor write path (storebound edit) counts them as errors', () => { + const src: EditSources = { + config: { file: '/x/storebound.config.ts', rel: 'storebound.config.ts', text: 'export default {}\n' }, + play: { file: '/x/store/listing.md', rel: 'store/listing.md', text: PLAY_MD.replace('Also on iPhone and iPad.\n', '') }, + apple: { file: '/x/store/appstore.md', rel: 'store/appstore.md', text: APPLE_MD }, + contact: { file: '/x/.storebound/credentials.json', rel: '.storebound/credentials.json', text: '{}' }, + appName: 'Game', appleName: 'Game', + }; + const apple = planEdits(parseOps(JSON.stringify([{ kind: 'listing', store: 'apple', lang: 'en-US', field: 'description', value: 'Get it on Google Play too.' }])), src, p => getByPath({}, p)); + expect(apple.plan.issues.some(i => i.level === 'error' && i.msg.includes('Google Play'))).toBe(true); + const play = planEdits(parseOps(JSON.stringify([{ kind: 'listing', store: 'play', lang: 'en-US', field: 'full', value: 'Best on iPhone.' }])), src, p => getByPath({}, p)); + expect(play.plan.errors).toBeGreaterThan(0); + }); + test('refuseMentions throws one message with every hit, nothing sent', () => { + expect(() => refuseMentions(textMentions('On Android', { store: 'apple', locale: 'en-US', field: 'whatsNew' }), 'apple listing')) + .toThrow(/refused: apple listing: .*App Store text \(2\.3\.10\); nothing was sent\n.*en-US whatsNew line 1: "Android"/); + expect(() => refuseMentions([], 'x')).not.toThrow(); + }); +}); + +describe('whats-new: one shared text, per-store notes', () => { + const shared = 'New levels.\n• [play] Achievements on Google Play Games.\n• [apple] Game Center leaderboards.\n[android] Fixed a crash on Android 14.\n\n[play]\nPlay-only block line.\n\nShared again.'; + test('tagged lines split per store, tags removed; a [play] heading line starts a block until a blank line', () => { + expect(notesForStore(shared, 'apple')).toBe('New levels.\n• Game Center leaderboards.\n\nShared again.'); + expect(notesForStore(shared, 'play')).toBe('New levels.\n• Achievements on Google Play Games.\nFixed a crash on Android 14.\n\nPlay-only block line.\n\nShared again.'); + }); + test('the draft leaves untagged other-platform lines out of the wrong store and says which', () => { + const d = draftForStore('New levels.\nAchievements on Google Play Games.', 'apple'); + expect(d).toEqual({ text: 'New levels.', dropped: ['Achievements on Google Play Games.'] }); + expect(draftForStore('New levels.\nAchievements on Google Play Games.', 'play').dropped).toEqual([]); + }); + test('apply writes each store its own lines; tagged notes pass the cross-store check', () => { + const l = { id: 'en', apple: 'en-US', play: 'en-US' }; + const md = { apple: '## en-US\n\n### whatsNew\n```\nold\n```\n', play: '## English\n\n\n### What\'s new (max 500)\n```\nold\n```\n' }; + const r = applyLanguageNotes(md, l, shared); + expect(r.apple).toContain('• Game Center leaderboards.'); + expect(r.apple).not.toContain('Google Play'); + expect(r.play).toContain('Achievements on Google Play Games.'); + expect(r.play).not.toContain('Game Center'); + expect(languageNoteMentions(l, shared)).toEqual([]); + const untagged = languageNoteMentions(l, 'New levels.\nAchievements on Google Play Games.'); + expect(untagged.map(h => [h.store, h.locale, h.line, h.term])).toEqual([['apple', 'en-US', 2, 'Google Play Games']]); + // each store's limit counts its own notes + expect(checkLanguageNotes(l, { lang: 'en', source: 'en', status: 'source', text: shared }).problems).toEqual([]); + }); +}); + +describe('scan: guideline ids per store', () => { + test('App Store 2.3.10 and Play: Metadata, with file and line', async () => { + const dir = mkdtempSync(join(tmpdir(), 'sb-cross-')); + try { + cpSync(join(import.meta.dir, 'fixtures', 'scan', 'android'), dir, { recursive: true }); + mkdirSync(join(dir, 'store'), { recursive: true }); + writeFileSync(join(dir, 'store', 'listing.md'), PLAY_MD); + const r = (await runScan(dir)).report; + const f = r.findings.find(x => x.rule === 'play-other-platforms')!; + expect(f).toMatchObject({ store: 'play', guideline: 'Play: Metadata' }); + expect(f.evidence[0]).toMatchObject({ file: 'store/listing.md', line: 14 }); + } finally { rmSync(dir, { recursive: true, force: true }); } + const ios = (await runScan(join(import.meta.dir, 'fixtures', 'scan', 'ios-native'))).report; + expect(ios.findings.find(x => x.rule === 'other-platforms')).toMatchObject({ store: 'apple', guideline: '2.3.10' }); + }); +}); diff --git a/tests/signing-capabilities.test.ts b/tests/signing-capabilities.test.ts index 1956270..b01d1b4 100644 --- a/tests/signing-capabilities.test.ts +++ b/tests/signing-capabilities.test.ts @@ -140,8 +140,8 @@ describe('scope and leftovers', () => { describe('storebound api writes outside a terminal', () => { test('the dry reason says TTY by design and the dedicated command is named', () => { const d = decide({ kind: 'write', method: 'POST', dry: false, yes: true, getOnly: false, tty: false, agent: false }); - expect(d).toMatchObject({ action: 'dry' }); - expect((d as { why: string }).why).toContain('by design'); + expect(d).toMatchObject({ action: 'refuse' }); + expect((d as { why: string }).why).toContain('Nothing was sent'); expect(dedicatedCommand('apple', 'bundleIdCapabilities_createInstance')).toContain('apple signing ensure'); expect(dedicatedCommand('apple', 'apps_getInstance')).toBeNull(); }); From 47dfd372fef6288be4da68c86a9c3b41d9f8cd23 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 03:00:05 +0700 Subject: [PATCH 033/344] apple: macOS (tvOS, visionOS) versions are no longer invisible: every version and review submission lookup is per platform; status, listing, listing pull, resubmit, submit, release and screenshots take --platform and otherwise pick the platform that has the version they need (refuse naming both when several do); status, validate, release status, the report and the desktop label versions with their platform; MCP and owner actions get platform; pitfall 77 --- CHANGELOG.md | 10 +++ apps/desktop/src/lib/submit.ts | 13 ++- apps/desktop/src/screens/tabs/Submit.tsx | 8 +- apps/desktop/tests/submit.test.ts | 2 +- cli/apple/asc.ts | 5 +- cli/apple/iap-submit.ts | 15 ++-- cli/apple/listing.ts | 37 +++++--- cli/apple/platform.ts | 61 +++++++++++++ cli/apple/release.ts | 13 ++- cli/apple/resubmit.ts | 42 +++++---- cli/apple/screenshots.ts | 10 ++- cli/apple/status.ts | 30 ++++--- cli/apple/submission.ts | 28 +++--- cli/commands.ts | 12 +-- cli/data/flags.json | 18 +++- cli/lib/app-status.ts | 4 +- cli/lib/desktop-protocol.ts | 2 + cli/lib/listing-plan.ts | 8 +- cli/lib/portfolio.ts | 14 ++- cli/lib/review-submit.ts | 4 +- cli/lib/validate-rules.ts | 17 +++- cli/mcp-tools.ts | 24 ++--- cli/serve.ts | 13 +-- cli/validate.ts | 16 +++- cli/whats-new.ts | 8 +- skills/release-management/SKILL.md | 1 + skills/review-rejections/SKILL.md | 2 + skills/store-pitfalls/SKILL.md | 15 ++++ tests/apple-platforms.test.ts | 108 +++++++++++++++++++++++ tests/resubmit.test.ts | 10 +-- 30 files changed, 423 insertions(+), 127 deletions(-) create mode 100644 cli/apple/platform.ts create mode 100644 tests/apple-platforms.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ee5763..dd98a4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,16 @@ new placement goes first, the old one is removed only after Apple accepted it), links the live version page and does not retry the other live slots. Pitfall 76 rewritten. +- **macOS (tvOS, visionOS) versions are no longer invisible.** `apple status`, `listing`, `listing pull`, `resubmit`, + `submit`, `release` and `screenshots` take `--platform ios|macos|tvos|visionos` (MCP tools and the desktop's owner + actions: `platform`); without it they use the platform that has the version they need (a rejected one, an + UNRESOLVED_ISSUES submission, an editable one) and refuse, naming both, when several platforms do. Every version + and review submission lookup is per platform, so `resubmit` finds the macOS submission back from App Review and + `listing --version 0.8.7` works on the rejected macOS 0.8.7 while the iOS 0.8.7 is live. `apple status`, `validate`, + `release status`, the report and the desktop label every version with its platform; validate and release status warn + about another platform's editable or rejected version. `whats-new apply --platform` names it in the push command. + Pitfall 77. + ## 0.8.13 · 2026-10-18 - **iPhone Duo screenshots.** `apple.iphoneDuo: true` adds the foldable's outer (1398 x 2034) and inner (2007 x 2853) diff --git a/apps/desktop/src/lib/submit.ts b/apps/desktop/src/lib/submit.ts index ef55545..77bc7d5 100644 --- a/apps/desktop/src/lib/submit.ts +++ b/apps/desktop/src/lib/submit.ts @@ -18,7 +18,12 @@ export type SubmissionKind = 'waiting' | 'inReview' | 'unresolved' | 'draft' | ' export interface SubmissionItem { id: string; kind: string; label: string; state: string; rejected: boolean } export interface SubmissionView { id: string; state: string; kind: SubmissionKind; date: string | null; items: SubmissionItem[] } export interface BuildChoice { id: string; number: string; version: string | null; state: string; uploaded: string | null; valid: boolean; attachedTo: string | null } -export interface AppleVersion { id: string; version: string; state: string; build: string | null } +export interface AppleVersion { id: string; version: string; state: string; build: string | null; platform: string } +const PLATFORM_LABEL: Record = { IOS: 'iOS', MAC_OS: 'macOS', TV_OS: 'tvOS', VISION_OS: 'visionOS' }; +/** "iOS", "macOS", ... of an App Store platform (IOS when the data has none). */ +export const platformLabel = (p: string | undefined): string => PLATFORM_LABEL[p || 'IOS'] ?? p ?? 'iOS'; +/** The CLI's --platform value of an App Store platform. */ +export const platformFlag = (p: string | undefined): string => platformLabel(p).toLowerCase(); export interface AppleSubmitState { submissions: SubmissionView[]; /** The first submission back from App Review (UNRESOLVED_ISSUES), with its items. */ @@ -40,11 +45,11 @@ export function appleSubmitState(raw: unknown): AppleSubmitState { const d = obj(raw) as AppleStatusData & J; const versions: AppleVersion[] = arr(d.versions).map(v => { const o = obj(v), a = obj(o.attributes); - return { id: str(o.id), version: str(a.versionString), state: str(a.appVersionState) || str(a.appStoreState), build: str(obj(obj(obj(o.relationships).build).data).id) || null }; + return { id: str(o.id), version: str(a.versionString), state: str(a.appVersionState) || str(a.appStoreState), build: str(obj(obj(obj(o.relationships).build).data).id) || null, platform: str(a.platform) || 'IOS' }; }).filter(v => v.id && v.version); const label = (kind: string, versionId: string): string => { const v = versions.find(x => x.id === versionId); - return v && kind === 'appStoreVersion' ? `app version ${v.version}` : `${ITEM_NAME[kind] ?? kind} ${versionId}`; + return v && kind === 'appStoreVersion' ? `app version ${v.version} (${platformLabel(v.platform)})` : `${ITEM_NAME[kind] ?? kind} ${versionId}`; }; const empty = new Set(arr(d.emptyDrafts).map(str)); const unresolvedItems = new Map(arr(d.unresolved).map(u => [str(obj(u).id), arr(obj(u).items)] as const)); @@ -67,7 +72,7 @@ export function appleSubmitState(raw: unknown): AppleSubmitState { const unresolved = submissions.find(s => s.kind === 'unresolved') ?? null; const busy = submissions.find(s => s.kind === 'waiting' || s.kind === 'inReview') ?? null; const held = new Set(unresolved?.items.filter(i => i.kind === 'appStoreVersion').map(i => i.label) ?? []); - const editable = versions.find(v => held.has(`app version ${v.version}`)) ?? versions.find(v => SUBMITTABLE_APP.includes(v.state)) ?? null; + const editable = versions.find(v => held.has(`app version ${v.version} (${platformLabel(v.platform)})`)) ?? versions.find(v => SUBMITTABLE_APP.includes(v.state)) ?? null; return { submissions, unresolved, busy, builds, editable, versions }; } diff --git a/apps/desktop/src/screens/tabs/Submit.tsx b/apps/desktop/src/screens/tabs/Submit.tsx index 3486eb1..85094ed 100644 --- a/apps/desktop/src/screens/tabs/Submit.tsx +++ b/apps/desktop/src/screens/tabs/Submit.tsx @@ -10,7 +10,7 @@ import { useState } from 'react'; import { api, type Project } from '../../api'; import { type Key, t } from '../../i18n'; import { ago, date } from '../../lib/format'; -import { type AppleStatusData, appleSubmitState, type PlayTrackData, playSubmitState, type SubmissionKind } from '../../lib/submit'; +import { type AppleStatusData, appleSubmitState, platformFlag, platformLabel, type PlayTrackData, playSubmitState, type SubmissionKind } from '../../lib/submit'; import type { UnifiedApp } from '../../lib/identity'; import { useData, useRead } from '../../store'; import { ConsolePlanButton } from '../../ui/ConsolePlan'; @@ -35,9 +35,9 @@ export function AppleSubmitCard({ app, project }: { app: UnifiedApp; project: Pr const summary = d.statusOf(project)?.summary; const iaps = summary?.catalog.ios.length ?? 0; const picked = s?.builds.find(b => b.number === build && b.valid) ?? null; - const version = s?.unresolved ? s.versions.find(v => s.unresolved!.items.some(i => i.label === `app version ${v.version}`)) ?? s.editable : s?.editable ?? null; + const version = s?.unresolved ? s.versions.find(v => s.unresolved!.items.some(i => i.label === `app version ${v.version} (${platformLabel(v.platform)})`)) ?? s.editable : s?.editable ?? null; const rejectedIap = s?.unresolved?.items.some(i => i.rejected && i.kind !== 'appStoreVersion') ?? false; - const args = { build, ...(version ? { version: version.version } : {}), ...(resolveIaps ? { resolve_iaps: true } : {}) }; + const args = { build, ...(version ? { version: version.version, platform: platformFlag(version.platform) } : {}), ...(resolveIaps ? { resolve_iaps: true } : {}) }; const refresh = () => { r.refresh(); }; return ( {r.data ? (r.fromCache ? t('common.cachedFrom', { when: ago(r.at) }) : t('common.readWhen', { when: ago(r.at) })) : r.loading ? t('read.waiting') : t('sub.appleSub')}} @@ -90,7 +90,7 @@ export function AppleSubmitCard({ app, project }: { app: UnifiedApp; project: Pr
{t('sub.version')} - {version ? `${version.version} · ${version.state}` : {t('sub.noVersion')}} + {version ? `${version.version} · ${platformLabel(version.platform)} · ${version.state}` : {t('sub.noVersion')}}
{s.builds.length ? t('sub.buildHint') : t('sub.noBuilds')} diff --git a/apps/desktop/tests/submit.test.ts b/apps/desktop/tests/submit.test.ts index 2ce5f9c..ee88b62 100644 --- a/apps/desktop/tests/submit.test.ts +++ b/apps/desktop/tests/submit.test.ts @@ -20,7 +20,7 @@ describe('App Store submission state', () => { test('UNRESOLVED_ISSUES: its items with REJECTED marked, the held version is the one to resubmit', () => { const s = appleSubmitState(APPLE_STATUS_UNRESOLVED); expect(s.unresolved).toMatchObject({ id: 'rs-back-1', kind: 'unresolved' }); - expect(s.unresolved!.items.map(i => [i.label, i.state, i.rejected])).toEqual([['app version 2.4.0', 'REJECTED', true], ['in-app purchase iapv-coins', 'READY_FOR_REVIEW', false]]); + expect(s.unresolved!.items.map(i => [i.label, i.state, i.rejected])).toEqual([['app version 2.4.0 (iOS)', 'REJECTED', true], ['in-app purchase iapv-coins', 'READY_FOR_REVIEW', false]]); expect(s.editable).toMatchObject({ version: '2.4.0', state: 'REJECTED' }); expect(s.busy).toBeNull(); }); diff --git a/cli/apple/asc.ts b/cli/apple/asc.ts index badb721..cfa4d87 100644 --- a/cli/apple/asc.ts +++ b/cli/apple/asc.ts @@ -140,8 +140,9 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri return appId; } - async function editableVersion(): Promise { - const vs = await all(`/v1/apps/${await app()}/appStoreVersions?filter[platform]=IOS&limit=50`); + /** The editable version of one platform (iOS unless named: an app's macOS version has its own state). */ + async function editableVersion(platform = 'IOS'): Promise { + const vs = await all(`/v1/apps/${await app()}/appStoreVersions?filter[platform]=${platform}&limit=50`); return vs.find(v => EDITABLE.has(v.attributes.appVersionState ?? v.attributes.appStoreState)) ?? null; } diff --git a/cli/apple/iap-submit.ts b/cli/apple/iap-submit.ts index d7952cd..a282826 100644 --- a/cli/apple/iap-submit.ts +++ b/cli/apple/iap-submit.ts @@ -26,8 +26,9 @@ import { addItem, draftJournalKey, ensureDraft, leaveUnusedDraft, openSubmission const TAG = 'iap-submit'; -export async function readSubmitState(c: Asc, appId: string, want: string[], o: { appVersionId?: string; also?: string } = {}): Promise { - const appVersions = (await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=50`)).map((v: J) => ({ id: v.id, versionString: v.attributes.versionString, +export async function readSubmitState(c: Asc, appId: string, want: string[], o: { appVersionId?: string; also?: string; platform?: string } = {}): Promise { + const platform = o.platform ?? 'IOS'; + const appVersions = (await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=${platform}&limit=50`)).map((v: J) => ({ id: v.id, versionString: v.attributes.versionString, state: v.attributes.appVersionState ?? v.attributes.appStoreState })); const iaps: PIap[] = []; for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)) { @@ -45,7 +46,7 @@ export async function readSubmitState(c: Asc, appId: string, want: string[], o: versions: want.includes(s.attributes.productId) ? versionsOf(await c.all(`/v1/subscriptions/${s.id}/versions?limit=200`)) : [] }); } // every open review submission: a draft or one back from App Review is reused, never a second one next to it - const open = await openSubmissions(c, appId, o.also); + const open = await openSubmissions(c, appId, o.also, platform); const choice = chooseSubmission(open, { appVersionId: o.appVersionId ?? appVersions.find((v: { state: string }) => /REJECTED|INVALID_BINARY/.test(v.state))?.id }); const draft: SubmitState['draft'] = choice.action === 'reuse' ? { id: choice.sub.id, state: choice.sub.state, itemVersionIds: choice.sub.items.map(i => i.versionId) } : null; return { appVersions, iaps, subs, groups, draft, open, choice }; @@ -96,6 +97,8 @@ export interface SubmitOpts { appId: string; ids: string[]; state: SubmitState; tag: string; withVersion?: boolean; /** the app version that must be in the submission (resubmit) */ appVersionId?: string; + /** the App Store platform of the version and the submission (default iOS) */ + platform?: string; /** the caller printed its own plan (resubmit) */ quiet?: boolean; /** REJECTED items marked resolved before the submit (resubmit: the version item; --resolve-iaps: the rest) */ @@ -116,7 +119,7 @@ export async function submitPlanned(ctx: Ctx, c: Asc, o: SubmitOpts): Promise bindIds(r, { app: o.appId })); const submitting = willSubmit(state, plan); const busy = state.choice?.action === 'busy'; @@ -155,7 +158,7 @@ export async function submitPlanned(ctx: Ctx, c: Asc, o: SubmitOpts): Promise new per field. --dry stops there // (read-only); the real run asks in a terminal and applies exactly that plan. Locales marked status=draft or @@ -24,6 +25,7 @@ import { confirm, need } from '../lib/ctx'; import { done, log, printJson, warn } from '../lib/log'; import { ascClient, EDITABLE, type J, noAppInfo } from './asc'; import { stdinIsTTY } from '../lib/tty'; +import { allVersions, type AscPlatform, parsePlatform, pickPlatform, platformLabel, versionsPath } from './platform'; export function readAppleCopy(ctx: Ctx) { const { config, resolve } = ctx.loaded; @@ -38,11 +40,14 @@ async function pull(ctx: Ctx): Promise { const a = ctx.args; const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId); const appId = await c.app(); - const versions = await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=50`); const want = a.get('version'); + const flag = parsePlatform(a.get('platform')); + const platform = flag ?? pickPlatform(await allVersions(c, appId), want ? [(x: J) => x.attributes.versionString === want && EDITABLE.has(x.attributes.appVersionState ?? x.attributes.appStoreState), (x: J) => x.attributes.versionString === want] : (x: J) => EDITABLE.has(x.attributes.appVersionState ?? x.attributes.appStoreState), undefined, want ? `version ${want}` : 'an editable version'); + const versions = await c.all(versionsPath(appId, platform)); const sorted = [...versions].sort((x: J, y: J) => String(y.attributes.createdDate ?? '').localeCompare(String(x.attributes.createdDate ?? ''))); - const v = want ? sorted.find((x: J) => x.attributes.versionString === want) : (await c.editableVersion()) ?? sorted[0]; - if (!v) throw new Error(want ? `no iOS version ${want} on App Store Connect` : 'no iOS version on App Store Connect yet'); + const v = want ? sorted.find((x: J) => x.attributes.versionString === want) : (await c.editableVersion(platform)) ?? sorted[0]; + if (!v) throw new Error(want ? `no ${platformLabel(platform)} version ${want} on App Store Connect` : `no ${platformLabel(platform)} version on App Store Connect yet`); + log('apple', `pulling version ${v.attributes.versionString} (${platformLabel(platform)})`); const infos = await c.all(`/v1/apps/${appId}/appInfos`); const live = v.attributes.appVersionState ?? v.attributes.appStoreState; // the app info that belongs to the version: the editable one while a version is being prepared, else the live one @@ -77,6 +82,8 @@ async function pull(ctx: Ctx): Promise { /** The plan of one `apple listing --version` run, from read-only GETs. */ export interface AppleListingPlan { version: string; + /** the App Store platform of the version (IOS, MAC_OS, ...) */ + platform: AscPlatform; versionPlan: VersionPlan; build: { number: string; id: string | null; current: string | null; action: 'attach' | 'same' | 'refuse'; reason: string } | null; appInfo: { id: string; state: string; locales: ItemPlan[] }; @@ -90,7 +97,7 @@ export interface AppleListingPlan { type Asc = Awaited>; -async function planListing(ctx: Ctx, c: Asc, appId: string, version: string): Promise { +async function planListing(ctx: Ctx, c: Asc, appId: string, version: string, platform: AscPlatform): Promise { const { config, resolve } = ctx.loaded; const app = config.app; const listing = readAppleCopy(ctx); @@ -106,13 +113,13 @@ async function planListing(ctx: Ctx, c: Asc, appId: string, version: string): Pr else { skipped.push({ key: l, reason: draftReason(st) }); delete listing[l]; } } const copyright = app.copyright ?? `${new Date().getFullYear()} ${app.name}`; - const rows = await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=50`); - const versionPlan = planVersion(rows, version, { copyright, releaseType: 'MANUAL' }); + const rows = await c.all(versionsPath(appId, platform)); + const versionPlan = planVersion(rows, version, { copyright, releaseType: 'MANUAL' }, platform); let build: AppleListingPlan['build'] = null; const number = ctx.args.get('build'); if (number) { - const b = (await c.all(`/v1/builds?filter[app]=${appId}&filter[version]=${number}&filter[preReleaseVersion.version]=${version}&filter[preReleaseVersion.platform]=IOS`))[0]; + const b = (await c.all(`/v1/builds?filter[app]=${appId}&filter[version]=${number}&filter[preReleaseVersion.version]=${version}&filter[preReleaseVersion.platform]=${platform}`))[0]; const cur = versionPlan.id ? (await c.maybe(`/v1/appStoreVersions/${versionPlan.id}/build`))?.data : null; const current = cur ? String(cur.attributes?.version ?? cur.id) : null; build = !b ? { number, id: null, current, action: 'refuse', reason: `build ${version} (${number}) not found (still uploading? check TestFlight)` } @@ -133,14 +140,14 @@ async function planListing(ctx: Ctx, c: Asc, appId: string, version: string): Pr const changes = (versionPlan.action === 'create' || versionPlan.action === 'update' ? 1 : 0) + (build?.action === 'attach' ? 1 : 0) + infoLocs.filter(x => x.action !== 'same').length + (versionLocales ? versionLocales.filter(x => x.action !== 'same').length : Object.keys(wanted).length); - return { version, versionPlan, build, appInfo: { id: info.id, state: String(info.attributes?.state ?? info.attributes?.appStoreState ?? ''), locales: infoLocs }, + return { version, platform, versionPlan, build, appInfo: { id: info.id, state: String(info.attributes?.state ?? info.attributes?.appStoreState ?? ''), locales: infoLocs }, versionLocales, wanted, skipped, notes, changes }; } /** The plan as text lines. Pure. */ export function listingPlanLines(p: AppleListingPlan): string[] { const v = p.versionPlan; - const out = [`Version (App Store Connect has: ${v.existing.length ? v.existing.map(x => `${x.versionString} ${x.state} ${x.platform}`).join(', ') : 'no iOS version yet'})`]; + const out = [`Version ${p.version} (${platformLabel(p.platform)}; App Store Connect has: ${v.existing.length ? v.existing.map(x => `${x.versionString} ${x.state} ${platformLabel(x.platform)}`).join(', ') : `no ${platformLabel(p.platform)} version yet`})`]; out.push(` ${v.action === 'refuse' ? 'REFUSE' : v.action.toUpperCase()}: ${v.reason}`); for (const ch of v.changes) out.push(` ${ch.field}: ${v.action === 'create' ? short(ch.to) : `${short(ch.from)} -> ${short(ch.to)}`}`); if (p.build) out.push(`Build: ${p.build.action === 'refuse' ? 'REFUSE: ' : ''}${p.build.reason}`); @@ -186,7 +193,11 @@ export async function run(ctx: Ctx): Promise { const dry = a.has('dry'); const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId); const appId = await c.app(); - const p = await planListing(ctx, c, appId, version); + // the platform: --platform, else the one where this version string is editable, else the one with an editable + // version; several -> ask (an app's iOS 0.8.7 can be live while its macOS 0.8.7 is rejected) + const isEd = (x: J) => EDITABLE.has(x.attributes.appVersionState ?? x.attributes.appStoreState); + const platform = parsePlatform(a.get('platform')) ?? pickPlatform(await allVersions(c, appId), [(x: J) => x.attributes.versionString === version && isEd(x), isEd], undefined, `an editable version (${version})`); + const p = await planListing(ctx, c, appId, version, platform); const refused = [p.versionPlan.action === 'refuse' ? p.versionPlan.reason : '', p.build?.action === 'refuse' ? p.build.reason : ''].filter(Boolean); if (a.has('json')) printJson({ dry, ...p, refused }); else for (const line of listingPlanLines(p)) console.log(line); @@ -200,9 +211,9 @@ export async function run(ctx: Ctx): Promise { if (vp.action === 'create') { // look again right before the create (another run, or a lost answer), then the journal for the list lag const made = await findOrCreate({ what: `App Store version ${version}`, tag: 'apple', unique: true, - find: async () => (await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=50`)) + find: async () => (await c.all(versionsPath(appId, p.platform))) .find((x: J) => x.attributes.versionString === version && EDITABLE.has(x.attributes.appVersionState ?? x.attributes.appStoreState)) ?? null, - journal: { root, key: `apple:${appId}:version:IOS:${version}`, byId: id => getById(c.asc, `/v1/appStoreVersions/${id}`) as Promise, idOf: v => v.id }, + journal: { root, key: `apple:${appId}:version:${p.platform}:${version}`, byId: id => getById(c.asc, `/v1/appStoreVersions/${id}`) as Promise, idOf: v => v.id }, create: async () => (await c.asc('POST', '/v1/appStoreVersions', { data: { type: 'appStoreVersions', attributes: Object.fromEntries(Object.entries(vp.attributes)), relationships: { app: { data: { type: 'apps', id: appId } } } } })).data }); versionId = made.value.id; diff --git a/cli/apple/platform.ts b/cli/apple/platform.ts new file mode 100644 index 0000000..ddc86dc --- /dev/null +++ b/cli/apple/platform.ts @@ -0,0 +1,61 @@ +// App Store platforms of one app record. An app can have an iOS and a macOS (tvOS, visionOS) version at the same time, +// each with its own state and its own review submission (pitfall 77): every version lookup filters by platform, and a +// command that needs one version picks the platform that has it, or asks for --platform when several do. +import type { Asc, J } from './asc'; + +export type AscPlatform = 'IOS' | 'MAC_OS' | 'TV_OS' | 'VISION_OS'; +export const ASC_PLATFORMS: AscPlatform[] = ['IOS', 'MAC_OS', 'TV_OS', 'VISION_OS']; +const FLAG: Record = { ios: 'IOS', macos: 'MAC_OS', tvos: 'TV_OS', visionos: 'VISION_OS' }; +const LABEL: Record = { IOS: 'iOS', MAC_OS: 'macOS', TV_OS: 'tvOS', VISION_OS: 'visionOS' }; +/** The console's URL segment of a platform's version page. */ +export const CONSOLE_SEGMENT: Record = { IOS: 'ios', MAC_OS: 'macos', TV_OS: 'appletvos', VISION_OS: 'visionos' }; + +/** --platform ios|macos|tvos|visionos (also the API names IOS, MAC_OS, ...) -> the API's platform; undefined when not + * given; throws on anything else. Pure. */ +export function parsePlatform(v: string | undefined): AscPlatform | undefined { + if (v == null || v === '') return undefined; + const k = v.toLowerCase().replace(/[_\s-]/g, ''); + const p = FLAG[k] ?? FLAG[k.replace(/^appletv/, 'tv')]; + if (!p) throw new Error(`--platform: ios | macos | tvos | visionos (got "${v}")`); + return p; +} + +/** "iOS", "macOS", ... for any platform string (unknown ones as they are). Pure. */ +export const platformLabel = (p: string | undefined | null): string => LABEL[(p ?? 'IOS') as AscPlatform] ?? String(p); + +export const platformOf = (v: J): AscPlatform => (v?.attributes?.platform ?? 'IOS') as AscPlatform; +export const stateOf = (v: J): string => v?.attributes?.appVersionState ?? v?.attributes?.appStoreState ?? ''; +/** "0.8.7 (macOS)": a version as people read it. */ +export const versionLabel = (v: J): string => `${v?.attributes?.versionString ?? '?'} (${platformLabel(platformOf(v))})`; + +/** The appStoreVersions list path of one platform. */ +export const versionsPath = (appId: string, platform: AscPlatform, limit = 50): string => + `/v1/apps/${appId}/appStoreVersions?filter[platform]=${platform}&limit=${limit}`; + +/** + * The platform a command works on. `flag` (--platform) wins. Else the platforms that have a version `needs` accepts: + * one -> that one; several -> an error naming them all (ask for --platform); none -> the only platform the app has + * versions on, else iOS. Pure. + */ +export function pickPlatform(versions: J[], needs: ((v: J) => boolean) | ((v: J) => boolean)[], flag: AscPlatform | undefined, what: string): AscPlatform { + if (flag) return flag; + // several tests: the first one any version passes decides (e.g. "this version string, editable", then "editable") + if (Array.isArray(needs)) { + for (const n of needs) if (versions.some(n)) return pickPlatform(versions, n, undefined, what); + return pickPlatform(versions, () => false, undefined, what); + } + const hits = [...new Set(versions.filter(needs).map(platformOf))]; + if (hits.length === 1) return hits[0]!; + if (hits.length > 1) { + const which = versions.filter(needs).map(v => `${versionLabel(v)} ${stateOf(v)}`).join(', '); + throw new Error(`${what} on more than one platform (${which}): run it again with --platform ${hits.map(p => Object.keys(FLAG).find(k => FLAG[k] === p)).join(' or --platform ')}`); + } + const all = [...new Set(versions.map(platformOf))]; + return all.length === 1 ? all[0]! : 'IOS'; +} + +/** Every App Store version of the app on every platform (only to pick the platform; the command then reads its + * platform's list with filter[platform]). */ +export async function allVersions(c: Asc, appId: string): Promise { + return c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=${ASC_PLATFORMS.join(',')}&limit=200`); +} diff --git a/cli/apple/release.ts b/cli/apple/release.ts index f202633..53c1680 100644 --- a/cli/apple/release.ts +++ b/cli/apple/release.ts @@ -1,6 +1,7 @@ // Release management for an App Store version. // storebound apple release --phased on|pause|resume|complete [--version 1.2.0] [--dry] [--yes] // storebound apple release --manual-release [--version 1.2.0] [--yes] +// Both take --platform ios|macos|tvos|visionos; without it the platform that has the version this needs is used (both: asks). // Phased release: 7-day automatic rollout to users with automatic updates (1, 2, 5, 10, 20, 50, 100 %); anyone can // still update by hand from the App Store. Pause holds it (up to 30 days in total), it is NOT a rollback: users who // updated keep the build. "complete" releases to everyone at once. @@ -12,6 +13,7 @@ import { done, log } from '../lib/log'; import { type PhasedAction, phasedRequest } from '../lib/release'; import { createOnce } from '../lib/upsert'; import { ascClient, type J } from './asc'; +import { allVersions, parsePlatform, pickPlatform, platformLabel, versionsPath } from './platform'; export async function run(ctx: Ctx): Promise { const { config, root } = ctx.loaded; @@ -23,15 +25,20 @@ export async function run(ctx: Ctx): Promise { const dry = a.has('dry'); const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId); const appId = await c.app(); - const versions = await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=20`); const want = a.get('version'); const state = (v: J): string => v.attributes.appVersionState ?? v.attributes.appStoreState; + // the platform: --platform, else the one with the version this needs (both: asks) + const needs = (x: J): boolean => (!want || x.attributes.versionString === want) && (manual ? state(x) === 'PENDING_DEVELOPER_RELEASE' + : phased === 'on' ? !['READY_FOR_DISTRIBUTION', 'READY_FOR_SALE', 'REPLACED_WITH_NEW_VERSION', 'REMOVED_FROM_SALE'].includes(state(x)) + : ['READY_FOR_DISTRIBUTION', 'READY_FOR_SALE', 'PENDING_DEVELOPER_RELEASE', 'PENDING_APPLE_RELEASE'].includes(state(x))); + const platform = parsePlatform(a.get('platform')) ?? pickPlatform(await allVersions(c, appId), want ? [needs, (x: J) => x.attributes.versionString === want] : needs, undefined, manual ? 'a version waiting for developer release' : `a version for phased release ${phased}`); + const versions = await c.all(versionsPath(appId, platform, 20)); const v: J | undefined = want ? versions.find(x => x.attributes.versionString === want) : manual ? versions.find(x => state(x) === 'PENDING_DEVELOPER_RELEASE') : phased === 'on' ? versions.find(x => !['READY_FOR_DISTRIBUTION', 'READY_FOR_SALE', 'REPLACED_WITH_NEW_VERSION', 'REMOVED_FROM_SALE'].includes(state(x))) : versions.find(x => ['READY_FOR_DISTRIBUTION', 'READY_FOR_SALE'].includes(state(x))) ?? versions[0]; - if (!v) throw new Error(want ? `no version ${want}` : manual ? 'no version waiting for developer release (PENDING_DEVELOPER_RELEASE)' : 'no matching version'); - const tag = `${v.attributes.versionString} (${state(v)})`; + if (!v) throw new Error(`${platformLabel(platform)}: ${want ? `no version ${want}` : manual ? 'no version waiting for developer release (PENDING_DEVELOPER_RELEASE)' : 'no matching version'}`); + const tag = `${v.attributes.versionString} ${platformLabel(platform)} (${state(v)})`; if (manual) { if (state(v) !== 'PENDING_DEVELOPER_RELEASE') throw new Error(`${tag}: only an approved version waiting for developer release can be released`); diff --git a/cli/apple/resubmit.ts b/cli/apple/resubmit.ts index dcf634e..051c9ec 100644 --- a/cli/apple/resubmit.ts +++ b/cli/apple/resubmit.ts @@ -1,5 +1,6 @@ // Resubmit an App Store version after a rejection (Invalid Binary, Guideline 2.1, ...) with a new build. -// storebound apple resubmit --build [--version 1.0.0] [--resolve-iaps] [--dry] [--yes] [--json] +// storebound apple resubmit --build [--version 1.0.0] [--platform ios|macos|tvos|visionos] [--resolve-iaps] [--dry] [--yes] [--json] +// The platform: --platform, else the one with a rejected version or an UNRESOLVED_ISSUES submission (both: asks). // 1. The rejected version (--version, else the one in the submission back from App Review, else the one in a // rejected state) gets build n attached, by explicit number (never "the latest"); it must be VALID. // 2. The open review submission is reused: the one with UNRESOLVED_ISSUES (it holds the version and its in-app @@ -25,6 +26,7 @@ import { allSubscriptions } from '../lib/subscriptions'; import { ascClient, type J } from './asc'; import { readSubmitState, submitPlanned } from './iap-submit'; import { openSubmissions } from './submission'; +import { allVersions, parsePlatform, pickPlatform, platformLabel, platformOf, versionsPath } from './platform'; /** App Store version states a first submission may send: the editable version (Prepare for Submission, a rejected * one, or one already Ready for Review in a draft). */ @@ -43,23 +45,33 @@ export async function submitVersion(ctx: Ctx, mode: 'submit' | 'resubmit'): Prom const appId = await c.app(); const ids = [...(config.products ?? []).filter(p => sellsOn(config, p, 'apple')).map(p => p.id), ...allSubscriptions(config.subscriptions).filter(x => sellsOn(config, x.sub, 'apple')).map(x => x.sub.id)]; - // the version to resubmit - const versions = await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=50`); + // the platform: --platform, else the one whose version (or UNRESOLVED_ISSUES submission) this needs; both -> ask const stateOf = (v: J): string => v.attributes.appVersionState ?? v.attributes.appStoreState; - const open = await openSubmissions(c, appId); - const held = new Set(open.filter(s => s.state === 'UNRESOLVED_ISSUES').flatMap(s => s.items.filter(i => i.kind === 'appStoreVersion').map(i => i.versionId))); const want = a.get('version'); + const flag = parsePlatform(a.get('platform')); + let platform = flag; + if (!platform) { + const every = await allVersions(c, appId); + const back = new Set((await c.all(`/v1/apps/${appId}/reviewSubmissions?filter[state]=UNRESOLVED_ISSUES&limit=50`)).map((s: J) => String(s.attributes?.platform ?? 'IOS'))); + const fits = (x: J) => (!want || x.attributes.versionString === want) + && ((mode === 'submit' ? SUBMITTABLE_APP : REJECTED_APP).has(stateOf(x)) || back.has(platformOf(x))); + platform = pickPlatform(every, fits, undefined, mode === 'submit' ? `a version to submit${want ? ` (${want})` : ''}` : `a rejected version${want ? ` (${want})` : ''}`); + } + const versions = await c.all(versionsPath(appId, platform)); + const open = await openSubmissions(c, appId, undefined, platform); + const held = new Set(open.filter(s => s.state === 'UNRESOLVED_ISSUES').flatMap(s => s.items.filter(i => i.kind === 'appStoreVersion').map(i => i.versionId))); + const pl = platformLabel(platform); const v: J | undefined = want ? versions.find((x: J) => x.attributes.versionString === want) : versions.find((x: J) => held.has(x.id)) ?? versions.find((x: J) => (mode === 'submit' ? SUBMITTABLE_APP : REJECTED_APP).has(stateOf(x))); - if (!v) throw new Error(want ? `no App Store version ${want} on iOS` - : mode === 'submit' ? 'no App Store version to submit (none in Prepare for Submission or rejected): storebound apple listing --version x.y.z first' - : 'no rejected App Store version and no review submission with UNRESOLVED_ISSUES: nothing to resubmit (storebound apple status)'); - if (mode === 'submit' && !SUBMITTABLE_APP.has(stateOf(v)) && !held.has(v.id)) throw new Error(`App Store version ${String(v.attributes.versionString)} is ${stateOf(v)}: only a version in Prepare for Submission (or a rejected one) can be submitted`); + if (!v) throw new Error(want ? `no App Store version ${want} on ${pl}` + : mode === 'submit' ? `no ${pl} App Store version to submit (none in Prepare for Submission or rejected): storebound apple listing --version x.y.z first` + : `no rejected ${pl} App Store version and no ${pl} review submission with UNRESOLVED_ISSUES: nothing to resubmit (storebound apple status; another platform: --platform)`); + if (mode === 'submit' && !SUBMITTABLE_APP.has(stateOf(v)) && !held.has(v.id)) throw new Error(`App Store version ${String(v.attributes.versionString)} (${pl}) is ${stateOf(v)}: only a version in Prepare for Submission (or a rejected one) can be submitted`); const versionString = String(v.attributes.versionString); - if (!a.has('json')) log(TAG, `app version ${versionString}: ${stateOf(v)}`); + if (!a.has('json')) log(TAG, `app version ${versionString} (${pl}): ${stateOf(v)}`); // the build, by its number - const b = (await c.all(`/v1/builds?filter[app]=${appId}&filter[version]=${number}&filter[preReleaseVersion.version]=${versionString}&filter[preReleaseVersion.platform]=IOS`))[0]; + const b = (await c.all(`/v1/builds?filter[app]=${appId}&filter[version]=${number}&filter[preReleaseVersion.version]=${versionString}&filter[preReleaseVersion.platform]=${platform}`))[0]; const cur = (await c.maybe(`/v1/appStoreVersions/${v.id}/build`))?.data; const current = cur ? String(cur.attributes?.version ?? cur.id) : null; const build: BuildStep = !b ? { number, id: null, current, action: 'refuse', reason: `build ${versionString} (${number}) not found (still uploading or processing? storebound apple status)` } @@ -68,8 +80,8 @@ export async function submitVersion(ctx: Ctx, mode: 'submit' | 'resubmit'): Prom : { number, id: b.id, current, action: 'attach', reason: `attach build ${number}${current ? ` instead of ${current}` : ''}` }; if (b && b.attributes.usesNonExemptEncryption == null) warn(TAG, `build ${number} has no export compliance answer yet: storebound apple encryption (Apple refuses the submission without it)`); - const state = await readSubmitState(c, appId, ids, { appVersionId: v.id }); - const plan = planIapSubmission(state, ids, { withVersion: true, appVersionId: v.id }); + const state = await readSubmitState(c, appId, ids, { appVersionId: v.id, platform }); + const plan = planIapSubmission(state, ids, { withVersion: true, appVersionId: v.id, platform }); // --build is a fixed build for the version: its REJECTED item is marked resolved; IAP items only on --resolve-iaps const resolve: ResolveScope = { version: true, iaps: a.has('resolve-iaps') }; const rows = resubmitRows(state, plan, build, resolve); @@ -77,7 +89,7 @@ export async function submitVersion(ctx: Ctx, mode: 'submit' | 'resubmit'): Prom const blockers = [...(build.action === 'refuse' ? [build.reason] : []), ...plan.blockers]; const dry = a.has('dry') || !a.has('yes'); if (a.has('json')) { - printJson({ dryRun: dry, version: { id: v.id, versionString, state: stateOf(v) }, build, submission: state.choice ?? null, resolve: marks, rows, skipped: plan.skipped, blockers }); + printJson({ dryRun: dry, version: { id: v.id, versionString, platform, state: stateOf(v) }, build, submission: state.choice ?? null, resolve: marks, rows, skipped: plan.skipped, blockers }); // the desktop's owner dialog shows the output text: the plan table goes with the result there if (process.env.STOREBOUND_MACHINE === '1') { console.log(formatRows(rows)); for (const x of blockers) warn(TAG, x); } if (blockers.length) process.exitCode = 1; @@ -98,5 +110,5 @@ export async function submitVersion(ctx: Ctx, mode: 'submit' | 'resubmit'): Prom await c.asc('PATCH', `/v1/appStoreVersions/${v.id}/relationships/build`, { data: { type: 'builds', id: build.id } }); log(TAG, `build ${number} attached to ${versionString}`); } - await submitPlanned(ctx, c, { appId, ids, state, tag: TAG, withVersion: true, appVersionId: v.id, quiet: true, resolve }); + await submitPlanned(ctx, c, { appId, ids, state, tag: TAG, withVersion: true, appVersionId: v.id, platform, quiet: true, resolve }); } diff --git a/cli/apple/screenshots.ts b/cli/apple/screenshots.ts index 2e7df65..3d484ab 100644 --- a/cli/apple/screenshots.ts +++ b/cli/apple/screenshots.ts @@ -18,7 +18,8 @@ import { findOrCreate } from '../lib/upsert'; import { pulledChecksum } from '../lib/art-pull'; import { consoleLink } from '../lib/console-links'; import { IPHONE_DUO_DISPLAY, IPHONE_DUO_NOT_IN_API } from '../shots/spec'; -import { type Asc, ascClient, keptPrefix, md5, setUpToDate, type J } from './asc'; +import { type Asc, ascClient, EDITABLE, keptPrefix, md5, setUpToDate, type J } from './asc'; +import { allVersions, parsePlatform, pickPlatform, platformLabel, stateOf, versionLabel } from './platform'; /** Render size key -> ASC screenshotDisplayType (iPhone sets). */ export const DISPLAY: Record = { ios69: 'APP_IPHONE_67', ios65: 'APP_IPHONE_65' }; @@ -83,8 +84,11 @@ export async function run(ctx: Ctx): Promise { const only = ctx.args.list('only'); const jobs = ctx.args.num('jobs', 4); const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId); - const version = await c.editableVersion(); - if (!version) throw new Error('no editable App Store version (run apple listing --version x.y.z first)'); + // the platform: --platform, else the one with an editable version (both: asks) + const platform = parsePlatform(ctx.args.get('platform')) ?? pickPlatform(await allVersions(c, await c.app()), x => EDITABLE.has(stateOf(x)), undefined, 'an editable version'); + const version = await c.editableVersion(platform); + if (!version) throw new Error(`no editable ${platformLabel(platform)} App Store version (run apple listing --version x.y.z first)`); + log('apple', `screenshots for version ${versionLabel(version)}`); const duoSkip = skippedDuoSets(config.apple); if (duoSkip) warn('apple', duoSkip.msg); const langOf = byAppleLocale(config.languages); diff --git a/cli/apple/status.ts b/cli/apple/status.ts index c4808c1..09ece80 100644 --- a/cli/apple/status.ts +++ b/cli/apple/status.ts @@ -1,5 +1,6 @@ // Read-only overview: app record, versions + attached build, recent builds, in-app purchases, review submissions. -// storebound apple status [--json] +// storebound apple status [--platform ios|macos|tvos|visionos] [--json] +// Versions and review submissions of every platform, each labelled (iOS, macOS, ...); --platform shows one. // And the one write it offers: cancel a review submission (to re-add first IAPs to it from the web UI): // storebound apple status --cancel-submission [--yes] // An empty draft (READY_FOR_REVIEW, 0 items) cannot be canceled (409 "Resource is not in cancellable state"); it is @@ -23,6 +24,7 @@ import { type Asc, ascClient, type J } from './asc'; import { notCancellable, readItems, type SubItem } from './submission'; import { capabilityReport, type CapabilityReport, printCapabilityReport } from './signing'; import * as rt from '../lib/rt'; +import { allVersions, parsePlatform, pickPlatform, platformLabel, platformOf, versionLabel, versionsPath } from './platform'; async function waitReview(ctx: Ctx, c: Asc, appId: string): Promise { const want = ctx.args.get('version'); @@ -31,12 +33,14 @@ async function waitReview(ctx: Ctx, c: Asc, appId: string): Promise { let delay: number | null = null; let last = ''; for (;;) { - const vs = await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=10`); + const flag = parsePlatform(ctx.args.get('platform')); + const platform = flag ?? pickPlatform(await allVersions(c, appId), x => (!want || x.attributes.versionString === want) && classifyReviewState(state(x)) === 'pending', undefined, 'a version in review'); + const vs = await c.all(versionsPath(appId, platform, 10)); const v = want ? vs.find(x => x.attributes.versionString === want) : vs.find(x => classifyReviewState(state(x)) === 'pending') ?? vs[0]; if (!v) { log('apple', `no version ${want ?? ''} found`); process.exit(2); } const st = state(v); const outcome = classifyReviewState(st); - if (st !== last) { log('apple', `${v.attributes.versionString}: ${st}`); last = st; } + if (st !== last) { log('apple', `${versionLabel(v)}: ${st}`); last = st; } if (outcome === 'approved') { log('apple', 'approved (release it yourself, or it goes out automatically if the release type says so)'); process.exit(WAIT_EXIT.approved); } if (outcome === 'rejected') { log('apple', `rejected: read the message in ${consoleLink('asc.app-review')}, then the review-rejections skill`); process.exit(WAIT_EXIT.rejected); } if (outcome === 'not-submitted') { log('apple', 'nothing is waiting for review'); process.exit(2); } @@ -70,15 +74,17 @@ export async function run(ctx: Ctx): Promise { } const app = (await c.asc('GET', `/v1/apps/${appId}`)).data; - const versions = await c.all(`/v1/apps/${appId}/appStoreVersions?limit=10&include=build`); + // every platform's versions (an app's macOS version has its own state), or one with --platform + const only = parsePlatform(ctx.args.get('platform')); + const versions = await c.all(only ? `${versionsPath(appId, only, 20)}&include=build` : `/v1/apps/${appId}/appStoreVersions?limit=20&include=build`); 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`); + const subs = await c.all(`/v1/reviewSubmissions?filter[app]=${appId}${only ? `&filter[platform]=${only}` : ''}&limit=20`); let caps: CapabilityReport | { error: string }; try { caps = await capabilityReport(c, config, root); } catch (e) { caps = { error: (e as Error).message.slice(0, 300) }; } // a submission back from App Review: its items and their states, and how to resubmit it - const unresolved: { id: string; items: SubItem[] }[] = []; - for (const s of subs.filter((x: J) => x.attributes?.state === 'UNRESOLVED_ISSUES')) unresolved.push({ id: s.id, items: await readItems(c, s.id) }); + const unresolved: { id: string; platform: string; items: SubItem[] }[] = []; + for (const s of subs.filter((x: J) => x.attributes?.state === 'UNRESOLVED_ISSUES')) unresolved.push({ id: s.id, platform: String(s.attributes?.platform ?? 'IOS'), items: await readItems(c, s.id) }); // an empty draft: App Store Connect keeps it and refuses to cancel it; harmless const empty = new Set(); for (const s of subs.filter((x: J) => x.attributes?.state === 'READY_FOR_REVIEW')) if (!(await readItems(c, s.id)).length) empty.add(s.id); @@ -89,7 +95,7 @@ export async function run(ctx: Ctx): Promise { try { gaps = await firstProductReport(c, appId, { iaps, versionState: reviewed ? vstate(reviewed) : undefined }); } catch (e) { log('apple', `first in-app purchases not compared with the review: ${(e as Error).message.slice(0, 200)}`); } const itemLabel = (kind: string, id: string): string => { const v = versions.find((x: J) => x.id === id); - return v ? `app version ${v.attributes.versionString}` : `${kind} ${id}`; + return v ? `app version ${versionLabel(v)}` : `${kind} ${id}`; }; if (ctx.args.has('json')) { // phased release of the newest versions that are live or close to it (rollout share on the desktop timeline) @@ -115,16 +121,16 @@ export async function run(ctx: Ctx): Promise { } 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)' : ''}`); + for (const v of versions) console.log(` version ${v.attributes.versionString.padEnd(8)} ${platformLabel(platformOf(v)).padEnd(8)} ${v.attributes.appVersionState ?? v.attributes.appStoreState}${v.relationships?.build?.data ? ' (build attached)' : ''}`); const pre = new Map((builds.included ?? []).map((p: { id: string; attributes: { version: string } }) => [p.id, p.attributes.version])); for (const b of builds.data) console.log(` build ${String(pre.get(b.relationships?.preReleaseVersion?.data?.id) ?? '?')} (${b.attributes.version}) ${b.attributes.processingState} ${b.attributes.uploadedDate?.slice(0, 10) ?? ''}`); for (const p of iaps) console.log(` iap ${p.attributes.productId.padEnd(40)} ${p.attributes.inAppPurchaseType} ${p.attributes.state}`); - for (const s of subs) console.log(` review submission ${s.id} ${s.attributes.state}${empty.has(s.id) ? `: ${EMPTY_DRAFT}` : ''} ${s.attributes.submittedDate?.slice(0, 10) ?? ''}`.trimEnd()); + for (const s of subs) console.log(` review submission ${s.id} ${platformLabel(s.attributes.platform)} ${s.attributes.state}${empty.has(s.id) ? `: ${EMPTY_DRAFT}` : ''} ${s.attributes.submittedDate?.slice(0, 10) ?? ''}`.trimEnd()); for (const u of unresolved) { - console.log(` review submission ${u.id} is back from App Review with UNRESOLVED_ISSUES; its items:`); + console.log(` review submission ${u.id} (${platformLabel(u.platform)}) is back from App Review with UNRESOLVED_ISSUES; its items:`); for (const it of u.items) console.log(` ${itemLabel(it.kind, it.versionId).padEnd(36)} ${it.state}${it.state === 'REJECTED' ? ' (not resolved: Apple takes no resubmit until it is; apple resubmit marks it resolved)' : ''}`); const newest = builds.data[0]?.attributes?.version; - console.log(` resubmit with: storebound apple resubmit --build ${newest ? ` (newest uploaded build: ${newest})` : ''}`); + console.log(` resubmit with: storebound apple resubmit --build ${u.platform === 'IOS' ? '' : ` --platform ${platformLabel(u.platform).toLowerCase()}`}${newest ? ` (newest uploaded build: ${newest})` : ''}`); } for (const g of gaps) warn('apple', `${g.msg}; ${g.fix}`); if ('error' in caps) log('apple', `capabilities not compared: ${caps.error}`); diff --git a/cli/apple/submission.ts b/cli/apple/submission.ts index f182332..13bdfd7 100644 --- a/cli/apple/submission.ts +++ b/cli/apple/submission.ts @@ -9,26 +9,26 @@ import type { Asc, J } from './asc'; import { one } from './jsonapi'; import * as rt from '../lib/rt'; -/** The draft review submission of the app (READY_FOR_REVIEW, iOS), or null. */ -export async function findDraft(c: Asc, appId: string): Promise { - return (await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&filter[platform]=IOS&filter[state]=READY_FOR_REVIEW&limit=10`))[0]?.id ?? null; +/** The draft review submission of the app (READY_FOR_REVIEW) on one platform (iOS unless named), or null. */ +export async function findDraft(c: Asc, appId: string, platform = 'IOS'): Promise { + return (await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&filter[platform]=${platform}&filter[state]=READY_FOR_REVIEW&limit=10`))[0]?.id ?? null; } /** The draft's id: the existing one, else a new draft created once. */ -export async function draftSubmission(c: Asc, appId: string, root: string, tag: string): Promise { - return (await ensureDraft(c, appId, root, tag)).id; +export async function draftSubmission(c: Asc, appId: string, root: string, tag: string, platform = 'IOS'): Promise { + return (await ensureDraft(c, appId, root, tag, platform)).id; } /** The journal key of the draft storebound created (cli/lib/upsert.ts). */ -export const draftJournalKey = (appId: string): string => `apple:${appId}:reviewSubmission:draft`; +export const draftJournalKey = (appId: string, platform = 'IOS'): string => `apple:${appId}:reviewSubmission:draft${platform === 'IOS' ? '' : `:${platform}`}`; /** Like draftSubmission, and says whether this run created the draft (an unused empty one is left: not cancellable). */ -export async function ensureDraft(c: Asc, appId: string, root: string, tag: string): Promise<{ id: string; created: boolean }> { +export async function ensureDraft(c: Asc, appId: string, root: string, tag: string, platform = 'IOS'): Promise<{ id: string; created: boolean }> { const r = await findOrCreate({ what: 'draft review submission', tag, unique: true, - find: () => findDraft(c, appId), - journal: { root, key: draftJournalKey(appId), idOf: id => id, + find: () => findDraft(c, appId, platform), + journal: { root, key: draftJournalKey(appId, platform), idOf: id => id, byId: async id => { const d = (await c.maybe(`/v1/reviewSubmissions/${id}`))?.data; return d?.attributes?.state === 'READY_FOR_REVIEW' ? id : null; } }, - create: async () => (await c.asc('POST', '/v1/reviewSubmissions', { data: { type: 'reviewSubmissions', attributes: { platform: 'IOS' }, relationships: { app: one('apps', appId) } } })).data.id as string }); + create: async () => (await c.asc('POST', '/v1/reviewSubmissions', { data: { type: 'reviewSubmissions', attributes: { platform }, relationships: { app: one('apps', appId) } } })).data.id as string }); if (r.created) log(tag, `draft review submission ${r.value} created`); return { id: r.value, created: r.created }; } @@ -81,10 +81,10 @@ export async function readItems(c: Asc, sid: string): Promise { }); } -/** Every open review submission of the app on iOS (OPEN_STATES), each with its items. `also`: a submission id a 409 - * named, read directly (a list may lag behind, or its state may be outside the filter). */ -export async function openSubmissions(c: Asc, appId: string, also?: string): Promise { - const subs = await c.all(`/v1/apps/${appId}/reviewSubmissions?filter[platform]=IOS&filter[state]=${OPEN_STATES.join(',')}&include=items&limit=50`); +/** Every open review submission of the app on one platform (iOS unless named; OPEN_STATES), each with its items. + * `also`: a submission id a 409 named, read directly (a list may lag behind, or its state may be outside the filter). */ +export async function openSubmissions(c: Asc, appId: string, also?: string, platform = 'IOS'): Promise { + const subs = await c.all(`/v1/apps/${appId}/reviewSubmissions?filter[platform]=${platform}&filter[state]=${OPEN_STATES.join(',')}&include=items&limit=50`); if (also && !subs.some((x: J) => x.id === also)) { const d = (await c.maybe(`/v1/reviewSubmissions/${also}`))?.data; if (d) subs.push(d); } const out: OpenSubmission[] = []; for (const x of subs) out.push({ id: x.id, state: x.attributes?.state ?? '?', submittedDate: x.attributes?.submittedDate ?? undefined, items: await readItems(c, x.id) }); diff --git a/cli/commands.ts b/cli/commands.ts index 24ae602..3bb9ee0 100644 --- a/cli/commands.ts +++ b/cli/commands.ts @@ -67,22 +67,22 @@ export const COMMANDS: Record Promise, string]> = { 'apple subscriptions': [() => import('./apple/subscriptions'), 'subscription groups, subscriptions, localizations, prices (equalized + overrides + --csv), intro offers, availability, review screenshot (asks first)'], 'apple iap-review': [() => import('./apple/iap-review'), 'IAP review screenshots + product states'], 'apple iap-submit': [() => import('./apple/iap-submit'), 'IAP + subscription versions into a review submission (first of a type: --with-version), then submit (asks first; --no-submit keeps a draft); reuses the open submission, never a second one'], - 'apple submit': [() => import('./apple/submit'), 'a version to App Review: --build attached (by number, VALID), the open submission reused, the ready IAPs / subscriptions with it, submitted with retry (dry run unless --yes)'], - 'apple resubmit': [() => import('./apple/resubmit'), 'after a rejection: --build attached to the rejected version, the UNRESOLVED_ISSUES submission reused (missing items added), resubmitted with retry (dry run unless --yes)'], + 'apple submit': [() => import('./apple/submit'), 'a version to App Review: --build attached (by number, VALID), the open submission reused, the ready IAPs / subscriptions with it, submitted with retry (dry run unless --yes); --platform ios|macos|tvos|visionos (default: the platform that has the version this needs; asks when several do)'], + 'apple resubmit': [() => import('./apple/resubmit'), 'after a rejection: --build attached to the rejected version, the UNRESOLVED_ISSUES submission reused (missing items added), resubmitted with retry (dry run unless --yes); --platform ios|macos|tvos|visionos (default: the platform that has the version this needs; asks when several do)'], 'apple offer-codes': [() => import('./apple/offer-codes'), 'offer codes for one-time purchases (campaigns; custom and one-time-use codes with --codes, asks first)'], 'apple win-back': [() => import('./apple/win-back'), 'win-back offers for lapsed subscribers (asks first: they go live on their start date)'], 'apple promoted': [() => import('./apple/promoted'), 'promoted in-app purchases on the product page: create, order, --enable (asks first)'], 'apple preorder': [() => import('./apple/preorder'), 'status | enable --release-date | end: App Store pre-orders per territory (asks first)'], 'apple cpp': [() => import('./apple/cpp'), 'custom product pages: list | create | upload --name | submit --name | visible --name (submit / visible ask first)'], 'apple events': [() => import('./apple/events'), 'in-app events: list | create | upload --name | submit --name (submit asks first)'], - 'apple listing': [() => import('./apple/listing'), 'version, build, name / subtitle / description / keywords per locale; pull [--write]: live texts back into the listing file (diff first)'], - 'apple screenshots': [() => import('./apple/screenshots'), '6.9" + 6.5" (+ 13" iPad) screenshots per locale; --variant '], + 'apple listing': [() => import('./apple/listing'), 'version, build, name / subtitle / description / keywords per locale; pull [--write]: live texts back into the listing file (diff first); --platform ios|macos|tvos|visionos (default: the platform that has the version this needs; asks when several do)'], + 'apple screenshots': [() => import('./apple/screenshots'), '6.9" + 6.5" (+ 13" iPad) screenshots per locale; --variant ; --platform ios|macos|tvos|visionos (default: the platform that has the version this needs; asks when several do)'], 'apple appinfo': [() => import('./apple/appinfo'), 'categories, age rating, content rights, Free price, territories'], 'apple review-details': [() => import('./apple/review-details'), 'App Review contact, demo account (from .storebound/, masked) + notes'], - 'apple status': [() => import('./apple/status'), 'versions, builds, IAPs, review submissions (--wait-review, --cancel-submission )'], + 'apple status': [() => import('./apple/status'), 'versions, builds, IAPs, review submissions (--wait-review, --cancel-submission ); --platform ios|macos|tvos|visionos (default: the platform that has the version this needs; asks when several do)'], 'apple creative-assets': [() => import('./apple/creative-assets'), 'Header and Search Results: product page header (21:9) and search results asset (3:2) per locale, or one universal 5244x2950 PNG; uploads to the Asset Library and selects it once processed (MD5 upsert); --add-for-review, --verify (read-only), --dry'], 'apple previews': [() => import('./apple/previews'), 'app preview videos per locale (MD5-idempotent, poster frame time code); --dry'], - 'apple release': [() => import('./apple/release'), 'phased release on|pause|resume|complete, --manual-release (asks first)'], + 'apple release': [() => import('./apple/release'), 'phased release on|pause|resume|complete, --manual-release (asks first); --platform ios|macos|tvos|visionos (default: the platform that has the version this needs; asks when several do)'], 'apple signing': [() => import('./apple/signing'), 'status | ensure: bundle id capabilities, distribution certificate (key kept in .storebound/signing), App Store profiles installed for Xcode; --dry, asks first'], 'apple build': [() => import('./apple/build'), 'xcodebuild archive + exportArchive (ExportOptions.plist generated, next build number, API key signing); Capacitor, React Native, Flutter, Unity; --dry'], 'apple upload': [() => import('./apple/upload'), 'upload an IPA (App Store Connect API build upload, or --via altool), build number checked, waits for processing; --dry, asks first'], diff --git a/cli/data/flags.json b/cli/data/flags.json index 7343a21..1565902 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -82,6 +82,7 @@ "name", "not-sent-for-review", "off", + "platform", "prune", "src", "variant", @@ -109,6 +110,7 @@ "apple listing": [ "build", "include-drafts", + "platform", "version", "write" ], @@ -143,6 +145,7 @@ "jobs", "name", "not-sent-for-review", + "platform", "prune", "src", "traffic", @@ -168,12 +171,14 @@ "apple release": [ "manual-release", "phased", + "platform", "version" ], "apple resubmit": [ "build", "new-version", "no-submit", + "platform", "resolve-iaps", "version", "with-version" @@ -185,6 +190,7 @@ "include-drafts", "jobs", "not-sent-for-review", + "platform", "prune", "src", "variant", @@ -198,6 +204,7 @@ "cancel-submission", "keychain", "no-install", + "platform", "timeout", "version", "wait-review" @@ -206,6 +213,7 @@ "build", "new-version", "no-submit", + "platform", "resolve-iaps", "version", "with-version" @@ -860,6 +868,7 @@ "no-scan", "not-sent-for-review", "out", + "platform", "play", "prune", "react-native", @@ -885,6 +894,7 @@ "hook", "lang", "languages", + "platform", "release", "since", "translate" @@ -1206,7 +1216,7 @@ "storebound apple iap-submit [--only id1,id2] [--with-version] [--new-version] [--resolve-iaps] [--no-submit] [--dry] [--yes] [--json]" ], "apple listing": [ - "storebound apple listing --version 1.0.0 [--build 3] [--include-drafts] [--dry] [--json]", + "storebound apple listing --version 1.0.0 [--platform ios|macos|tvos|visionos] [--build 3] [--include-drafts] [--dry] [--json]", "storebound apple listing pull [--version x.y.z] [--write] [--json]" ], "apple next-build": [ @@ -1237,7 +1247,7 @@ "storebound apple release --manual-release [--version 1.2.0] [--yes]" ], "apple resubmit": [ - "storebound apple resubmit --build [--version 1.0.0] [--resolve-iaps] [--dry] [--yes] [--json]" + "storebound apple resubmit --build [--version 1.0.0] [--platform ios|macos|tvos|visionos] [--resolve-iaps] [--dry] [--yes] [--json]" ], "apple review-details": [ "storebound apple review-details [--contact-from ] [--dry]" @@ -1250,7 +1260,7 @@ "storebound apple signing ensure [--dry] [--yes] [--keychain [path]] [--no-install] [--json]" ], "apple status": [ - "storebound apple status [--json]", + "storebound apple status [--platform ios|macos|tvos|visionos] [--json]", "storebound apple status --cancel-submission [--yes]", "storebound apple status --wait-review [--version 1.2.0] [--timeout 48h]" ], @@ -1490,7 +1500,7 @@ "storebound whats-new [--since v1.1.0] [--release 1.2.0] [--from-git] [--lang en-US] [--all] [--hook \"text\"] [--dry]", "storebound whats-new --languages en-US,de-DE,tr [--dir store/whats-new] [--translate \"\"] [--force] [--dry] [--json]", "storebound whats-new check [--dir store/whats-new] [--json] limits per store (Play 500, App Store 4000), untranslated files", - "storebound whats-new apply [--dir store/whats-new] [--dry] [--json] checked files -> both listing files" + "storebound whats-new apply [--dir store/whats-new] [--platform ios|macos|tvos|visionos] [--dry] [--json] checked files -> both listing files" ] } } diff --git a/cli/lib/app-status.ts b/cli/lib/app-status.ts index 45e8016..bbb6db0 100644 --- a/cli/lib/app-status.ts +++ b/cli/lib/app-status.ts @@ -3,7 +3,7 @@ // workspace (`storebound ws status`, `storebound release status`), so all of them read an app the same way. // Every read is a storebound child command; `exec` runs it (serve tracks it for cancellation, the CLI just awaits it). import type { AppStatus, ProjectSummary } from './desktop-protocol'; -import { appIdentity, appleFirstProductWarnings, appleProductIds, appleReleases, catalogParity, playProductIds, playReleases, releaseTrains } from './portfolio'; +import { appIdentity, appleFirstProductWarnings, applePlatformWarnings, appleProductIds, appleReleases, catalogParity, playProductIds, playReleases, releaseTrains } from './portfolio'; import type { RunResult } from './runner'; export type Exec = (argv: string[], cwd: string) => Promise; @@ -46,7 +46,7 @@ export async function fillAppStatus(e: AppStatus, dir: string, o: { live: boolea const ios = apple?.data ? appleReleases(apple.data) : [], android = play?.data ? playReleases(play.data) : []; e.release = { source: 'live', ...releaseTrains(ios, android), all: [...ios, ...android] }; // first in-app purchases left out of the review: a warning on the release status and in the desktop's checks - const firstWarn = apple?.data ? appleFirstProductWarnings(apple.data) : []; + const firstWarn = apple?.data ? [...appleFirstProductWarnings(apple.data), ...applePlatformWarnings(apple.data)] : []; if (firstWarn.length) e.warnings = firstWarn; if (e.check) for (const w of firstWarn) if (!e.check.warnings.includes(w)) e.check.warnings.push(w); e.catalog = catalogParity(summary, apple?.data ? appleProductIds(apple.data) : undefined, play?.data ? playProductIds(play.data) : undefined); diff --git a/cli/lib/desktop-protocol.ts b/cli/lib/desktop-protocol.ts index 41d5baa..b988d91 100644 --- a/cli/lib/desktop-protocol.ts +++ b/cli/lib/desktop-protocol.ts @@ -166,6 +166,8 @@ export type ReleasePhase = 'live' | 'rollout' | 'halted' | 'released' | 'approve export interface StoreRelease { store: 'ios' | 'android'; + /** App Store platform of the version (IOS, MAC_OS, ...); absent on Play. */ + platform?: string; version: string | null; /** iOS build number (CFBundleVersion) / highest Android versionCode. */ build: string | null; diff --git a/cli/lib/listing-plan.ts b/cli/lib/listing-plan.ts index e1ea896..895fa64 100644 --- a/cli/lib/listing-plan.ts +++ b/cli/lib/listing-plan.ts @@ -58,6 +58,8 @@ export function compareVersions(a: string, b: string): number { return 0; } +const PLATFORM_LABEL: Record = { IOS: 'iOS', MAC_OS: 'macOS', TV_OS: 'tvOS', VISION_OS: 'visionOS' }; + /** Version rows of GET /v1/apps/{id}/appStoreVersions. */ export const versionInfos = (rows: { id: string; attributes: Record }[]): VersionInfo[] => rows.map(r => ({ id: r.id, versionString: String(r.attributes.versionString ?? ''), state: String(r.attributes.appVersionState ?? r.attributes.appStoreState ?? ''), platform: String(r.attributes.platform ?? 'IOS') })); @@ -67,7 +69,7 @@ export const versionInfos = (rows: { id: string; attributes: Record }[], want: string, attrs: { copyright: string; releaseType: string }): VersionPlan { +export function planVersion(rows: { id: string; attributes: Record }[], want: string, attrs: { copyright: string; releaseType: string }, platform = 'IOS'): VersionPlan { const existing = versionInfos(rows); const editable = existing.find(v => EDITABLE_STATES.has(v.state)); const others = existing.filter(v => v !== editable); @@ -96,8 +98,8 @@ export function planVersion(rows: { id: string; attributes: Record IN_PROGRESS.has(v.state)); if (busy) return refuse(`version ${busy.versionString} is ${busy.state}; App Store Connect allows one version in progress (wait for its release or remove it from review)`); - const attributes = { platform: 'IOS', versionString: want, copyright: attrs.copyright, releaseType: attrs.releaseType }; - return { ...base, action: 'create', reason: `create version ${want} (no editable iOS version)`, changes: Object.entries(attributes).map(([field, to]) => ({ field, from: null, to })), attributes }; + const attributes = { platform, versionString: want, copyright: attrs.copyright, releaseType: attrs.releaseType }; + return { ...base, action: 'create', reason: `create version ${want} (no editable ${PLATFORM_LABEL[platform] ?? platform} version)`, changes: Object.entries(attributes).map(([field, to]) => ({ field, from: null, to })), attributes }; } // ---- translation drafts ---- diff --git a/cli/lib/portfolio.ts b/cli/lib/portfolio.ts index 42def24..efa0693 100644 --- a/cli/lib/portfolio.ts +++ b/cli/lib/portfolio.ts @@ -63,6 +63,18 @@ export function phasedFraction(p: { state?: string; currentDayNumber?: number | return d ? PHASED_SCHEDULE[d - 1]! : p.state === 'INACTIVE' ? 0 : null; } +const OTHER_PLATFORM: Record = { MAC_OS: 'macOS', TV_OS: 'tvOS', VISION_OS: 'visionOS' }; + +/** Versions of the app's other App Store platforms (macOS, tvOS, visionOS) that are not live or replaced: the train + * is iOS, so these are named as warnings ("macOS 0.8.7: REJECTED") instead of being invisible. Pure. */ +export function applePlatformWarnings(data: unknown): string[] { + const versions = ((data as J)?.versions ?? []) as J[]; + return versions.filter(v => typeof v?.attributes?.versionString === 'string' && OTHER_PLATFORM[v.attributes.platform ?? 'IOS']) + .map(v => ({ v, state: String(v.attributes.appVersionState ?? v.attributes.appStoreState ?? 'UNKNOWN') })) + .filter(({ state }) => !/READY_FOR_SALE|READY_FOR_DISTRIBUTION|REPLACED_WITH_NEW_VERSION|REMOVED_FROM_SALE/.test(state)) + .map(({ v, state }) => `App Store ${OTHER_PLATFORM[v.attributes.platform]} ${v.attributes.versionString}: ${state} (storebound apple status --platform ${OTHER_PLATFORM[v.attributes.platform]!.toLowerCase()})`); +} + export function appleReleases(data: unknown): StoreRelease[] { const versions = ((data as J)?.versions ?? []) as J[]; const recent = (((data as J)?.builds ?? []) as J[]); @@ -79,7 +91,7 @@ export function appleReleases(data: unknown): StoreRelease[] { // 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 }; + const r: StoreRelease = { store: 'ios', platform: '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; diff --git a/cli/lib/review-submit.ts b/cli/lib/review-submit.ts index 19df069..d108330 100644 --- a/cli/lib/review-submit.ts +++ b/cli/lib/review-submit.ts @@ -149,7 +149,7 @@ export function latestVersion(vs: PVersion[]): PVersion | undefined { * Plan for submitting `want` (product ids of in-app purchases and subscriptions). withVersion: put the editable app * version into the same submission (needed for the first item of a type, or while the app has no approved version). */ -export function planIapSubmission(s: SubmitState, want: string[], o: { withVersion?: boolean; appVersionId?: string } = {}): SubmitPlan { +export function planIapSubmission(s: SubmitState, want: string[], o: { withVersion?: boolean; appVersionId?: string; platform?: string } = {}): SubmitPlan { const plan: SubmitPlan = { items: [], skipped: [], firstOfType: [], hasApprovedVersion: s.appVersions.some(v => APPROVED_APP.has(v.state)), needsAppVersion: false, blockers: [], prepare: [], submit: { method: 'PATCH', path: '/v1/reviewSubmissions/${submission}', note: 'submit for App Review', body: {} } }; const approvedTypes = new Set([...s.iaps.filter(p => APPROVED_PRODUCT.has(p.state)).map(p => p.type), ...(s.subs.some(x => APPROVED_PRODUCT.has(x.state)) ? ['AUTO_RENEWABLE'] : [])]); @@ -212,7 +212,7 @@ export function planIapSubmission(s: SubmitState, want: string[], o: { withVersi } if (plan.items.length + (s.draft?.itemVersionIds.length ?? 0) > MAX_SUBMISSION_ITEMS) plan.blockers.push(`more than ${MAX_SUBMISSION_ITEMS} items in one submission: use --only for a part`); const sid = s.draft?.id ?? '${submission}'; - if (!s.draft && plan.items.length) plan.prepare.push({ method: 'POST', path: '/v1/reviewSubmissions', note: 'new draft review submission', body: { data: { type: 'reviewSubmissions', attributes: { platform: 'IOS' }, relationships: { app: one('apps', '${app}') } } } }); + if (!s.draft && plan.items.length) plan.prepare.push({ method: 'POST', path: '/v1/reviewSubmissions', note: 'new draft review submission', body: { data: { type: 'reviewSubmissions', attributes: { platform: o.platform ?? 'IOS' }, relationships: { app: one('apps', '${app}') } } } }); for (const it of plan.items) plan.prepare.push({ method: 'POST', path: '/v1/reviewSubmissionItems', note: it.label, body: { data: { type: 'reviewSubmissionItems', relationships: { reviewSubmission: one('reviewSubmissions', sid), [it.kind]: one(ITEM_TYPE[it.kind], it.versionId) } } } }); plan.submit = { method: 'PATCH', path: `/v1/reviewSubmissions/${sid}`, note: 'submit for App Review', body: { data: { type: 'reviewSubmissions', id: sid, attributes: { submitted: true } } } }; diff --git a/cli/lib/validate-rules.ts b/cli/lib/validate-rules.ts index 3fd8938..61bd7c2 100644 --- a/cli/lib/validate-rules.ts +++ b/cli/lib/validate-rules.ts @@ -56,7 +56,9 @@ export function rendersFindings(store: 'apple' | 'play', r: RendersCheck | undef } export interface AppleSnapshot { - version: { versionString: string; state: string; copyright?: string | null } | null; + version: { versionString: string; state: string; copyright?: string | null; platform?: string } | null; + /** Editable or rejected versions of the app's other platforms (an app's macOS version has its own state). */ + otherPlatformVersions?: { versionString: string; state: string; platform: string }[]; /** app.copyright from the config (undefined: not set). */ configCopyright?: string; build: { number: string; processingState: string; usesNonExemptEncryption: boolean | null; declarationState: string | null } | null; @@ -192,15 +194,22 @@ export function copyrightRules(s: Pick = { IOS: 'iOS', MAC_OS: 'macOS', TV_OS: 'tvOS', VISION_OS: 'visionOS' }; + export function appleRules(s: AppleSnapshot): Finding[] { const f: Finding[] = []; const add = (level: Level, code: string, msg: string, fix?: string, action?: FixAction, url?: string) => f.push({ store: 'apple', level, code, msg, fix, ...(action ? { action } : {}), ...(url ? { url } : {}) }); const listing = s.version && EDITABLE.includes(s.version.state) ? fixAppleListing(s.version.versionString) : undefined; + const vl = s.version ? `${s.version.versionString} (${PLATFORM_NAMES[s.version.platform ?? 'IOS'] ?? s.version.platform})` : ''; if (!s.version) add('blocker', 'version', 'no App Store version being prepared', 'storebound apple listing --version x.y.z'); - else if (EDITABLE.includes(s.version.state)) add('ok', 'version', `version ${s.version.versionString}: ${s.version.state}`); - else if (IN_FLIGHT.includes(s.version.state)) add('warn', 'version', `version ${s.version.versionString} is ${s.version.state} (nothing to prepare)`); - else add('warn', 'version', `version ${s.version.versionString}: ${s.version.state}`); + else if (EDITABLE.includes(s.version.state)) add('ok', 'version', `version ${vl}: ${s.version.state}`); + else if (IN_FLIGHT.includes(s.version.state)) add('warn', 'version', `version ${vl} is ${s.version.state} (nothing to prepare)`); + else add('warn', 'version', `version ${vl}: ${s.version.state}`); + for (const o of s.otherPlatformVersions ?? []) { + const name = PLATFORM_NAMES[o.platform] ?? o.platform; + add('warn', 'version-platform', `version ${o.versionString} (${name}) is ${o.state} too: this report covers ${vl || 'iOS'} only`, `storebound validate --platform ${name.toLowerCase()}; storebound apple status lists every platform`); + } f.push(...copyrightRules(s)); if (!s.build) add('blocker', 'build', 'no build attached to the version', 'storebound apple listing --version x.y.z --build N (pick the build number you just uploaded)'); diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index af09433..16c72d0 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -27,6 +27,7 @@ export interface ToolDef { const only: JsonSchema = { type: 'string', description: 'Comma-separated ids / language codes to limit the run to (optional)' }; const lang: JsonSchema = { type: 'string', description: 'Comma-separated language ids from the config (default: all)' }; const variant: JsonSchema = { type: 'string', pattern: '^[a-z0-9][a-z0-9-]*$', description: 'A/B variant id from shots.variants (default: the base renders)' }; +const platform: JsonSchema = { type: 'string', enum: ['ios', 'macos', 'tvos', 'visionos'], description: 'App Store platform of the version (default: the one that has the version this needs; when several do, the command asks for it)' }; const source: JsonSchema = { type: 'string', enum: ['web', 'ios-sim', 'android-emu', 'folder'], description: 'Default: from the config' }; const APP_NAMES = '^[^,\\x00-\\x1f]{1,120}(,[^,\\x00-\\x1f]{1,120}){0,99}$'; const opt = (flag: string, v: unknown): string[] => (v === undefined || v === null || v === '' ? [] : [`--${flag}`, String(v)]); @@ -55,8 +56,8 @@ export const TOOLS: ToolDef[] = [ args: i => [...opt('store', i.store), ...flag('originality', i.originality), ...(i.originality ? opt('against', i.against) : [])] }, { name: 'validate', title: 'Store readiness report', command: ['validate'], write: false, network: true, description: 'Read-only readiness report for App Store Connect and/or Google Play with ordered blockers (build, encryption, metadata, screenshots, review details and demo account, age rating, prices, IAPs, subscriptions, privacy, delete-account and terms URLs, app-ads.txt, tracks, products, base plans).', - props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' } }, - args: i => (i.store === 'apple' ? ['--apple'] : i.store === 'play' ? ['--play'] : []) }, + props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' }, platform }, + args: i => [...(i.store === 'apple' ? ['--apple'] : i.store === 'play' ? ['--play'] : []), ...opt('platform', i.platform)] }, { name: 'report', title: 'Shareable readiness report', command: ['report'], write: false, network: true, description: 'One self-contained HTML page with the scan, check and validate results (read-only; validate only for the stores whose credentials are there, else the page says why): summary per store, findings by store and severity with guideline, evidence, fix and console link, the compliance questions only the owner can answer. Writes only .storebound/reports/readiness-.html (masked: no credentials, key ids, emails or demo account) and returns its path and the summary; never opens a browser.', props: { format: { type: 'string', enum: ['html', 'md'], default: 'html' }, offline: { type: 'boolean', default: false, description: 'Skip validate (no store reads)' } }, @@ -141,7 +142,8 @@ export const TOOLS: ToolDef[] = [ { name: 'analytics_setup', title: 'Start App Store analytics reports', command: ['analytics', 'setup'], write: true, network: true, idempotent: true, description: 'Create the ONGOING App Store Connect analytics report request once (needs an Admin key; reports start 1-2 days later). Changes nothing public.' }, { name: 'apple_status', title: 'App Store status', command: ['apple', 'status'], write: false, network: true, - description: 'Read-only App Store Connect overview: versions and their states, recent builds, in-app purchases, review submissions.' }, + description: 'Read-only App Store Connect overview: versions of every platform (iOS, macOS, ...) and their states, recent builds, in-app purchases, review submissions with their platform.', + props: { platform }, args: i => opt('platform', i.platform) }, { name: 'apple_next_build', title: 'Next iOS build number', command: ['apple', 'next-build'], write: false, network: true, description: 'Next safe CFBundleVersion: one above every build uploaded for the app.' }, { name: 'apple_signing_status', title: 'Code signing status', command: ['apple', 'signing', 'status'], write: false, network: true, @@ -203,11 +205,11 @@ export const TOOLS: ToolDef[] = [ description: 'Upload (replace when changed) the App Review screenshot of every in-app purchase. Never submits.' }, { name: 'apple_listing', title: 'Push App Store version + text', command: ['apple', 'listing'], write: true, network: true, idempotent: true, description: 'Create / update the editable version (manual release), attach a build by explicit number, and push name / subtitle / description / keywords / promo / what\'s new per locale. dry_run prints the plan: version keep / update / create / refuse with the reason, per locale old -> new per field; draft locales are skipped (owner terminal run with --include-drafts).', - props: { version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$' }, build: { type: 'string', description: 'Exact build number to attach (use the number you just uploaded, never "latest")' }, only }, - required: ['version'], args: i => [...opt('version', i.version), ...opt('build', i.build), ...opt('only', i.only)] }, + props: { version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$' }, build: { type: 'string', description: 'Exact build number to attach (use the number you just uploaded, never "latest")' }, only, platform }, + required: ['version'], args: i => [...opt('version', i.version), ...opt('platform', i.platform), ...opt('build', i.build), ...opt('only', i.only)] }, { name: 'apple_screenshots', title: 'Upload App Store screenshots', command: ['apple', 'screenshots'], write: true, destructive: true, network: true, idempotent: true, description: 'Sync 6.9" and 6.5" (+ 13" iPad with apple.ipad) screenshots per locale from the renders folder (or an A/B variant folder; MD5-idempotent; changed sets are replaced). Slow: prefer the terminal with a log.', - props: { only, variant }, args: i => [...opt('only', i.only), ...opt('variant', i.variant)] }, + props: { only, variant, platform }, args: i => [...opt('only', i.only), ...opt('variant', i.variant), ...opt('platform', i.platform)] }, { name: 'apple_appinfo', title: 'App Store app info', command: ['apple', 'appinfo'], write: true, network: true, idempotent: true, description: 'Categories, age rating declaration, content rights, Free price and availability (when missing).' }, { name: 'apple_review_details', title: 'App Review information', command: ['apple', 'review-details'], write: true, network: true, idempotent: true, @@ -217,8 +219,8 @@ export const TOOLS: ToolDef[] = [ props: { build: { type: 'string', description: 'Build number (default: every build without an answer)' } }, args: i => opt('build', i.build) }, { name: 'apple_phased_release', title: 'Phased release on / pause', command: ['apple', 'release'], write: true, network: true, idempotent: true, description: 'Turn on the 7-day phased release for the upcoming version, or pause an active one (pausing is not a rollback). Resume / complete / release are owner-only terminal commands.', - props: { action: { type: 'string', enum: ['on', 'pause'] }, version: { type: 'string' } }, required: ['action'], - args: i => ['--phased', String(i.action), ...opt('version', i.version)] }, + props: { action: { type: 'string', enum: ['on', 'pause'] }, version: { type: 'string' }, platform }, required: ['action'], + args: i => ['--phased', String(i.action), ...opt('version', i.version), ...opt('platform', i.platform)] }, { name: 'shots_capture', title: 'Capture raw frames', command: ['shots', 'capture'], write: true, network: false, idempotent: true, description: 'Raw app or game frames per language into shots.frames from a web build (Playwright), the iOS Simulator (simctl), an Android emulator / device (adb) or a folder check. Local files only; a simulator it boots is shut down again, an emulator is never booted. dry_run lists the plan and the simctl / adb commands.', props: { lang, only: { type: 'string', description: 'Comma-separated shot names' }, device: { type: 'string', enum: ['phone', 'tablet'] }, source, @@ -342,8 +344,8 @@ export const TOOLS: ToolDef[] = [ args: i => [...opt('only', i.only), ...flag('with-version', i.with_version), '--json', '--dry'] }, { name: 'apple_listing_pull', title: 'Pull App Store texts', command: ['apple', 'listing', 'pull'], write: true, network: true, idempotent: true, description: 'Read the live App Store texts (name, subtitle, description, keywords, promotional text, what\'s new per locale) and diff them against the App Store listing file. dry_run shows the diff; with dry_run false the file is updated (local file only).', - props: { version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$', description: 'Version to read (default: the editable one, else the newest)' } }, - args: i => [...opt('version', i.version), '--json', ...(i.dry_run === false ? ['--write'] : [])] }, + props: { version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$', description: 'Version to read (default: the editable one, else the newest)' }, platform }, + args: i => [...opt('version', i.version), ...opt('platform', i.platform), '--json', ...(i.dry_run === false ? ['--write'] : [])] }, { name: 'play_listing_pull', title: 'Pull Google Play texts', command: ['play', 'listing', 'pull'], write: true, network: true, idempotent: true, description: 'Read the live Play listings (title, short and full description per language; one throwaway edit, deleted) and diff them against the Play listing file. dry_run shows the diff; with dry_run false the file is updated (local file only).', args: i => ['--json', ...(i.dry_run === false ? ['--write'] : [])] }, @@ -365,7 +367,7 @@ export const TOOLS: ToolDef[] = [ args: () => ['--json'] }, { name: 'whats_new_apply', title: 'Apply release notes per language', command: ['whats-new', 'apply'], write: true, network: false, idempotent: true, description: 'Write the checked per-language release notes into both listing files (Play "What\'s new" per Play code, App Store whatsNew per locale). Refuses while a language is over a limit or untranslated. Local files only; nothing is sent to a store.', - args: () => ['--json'] }, + props: { platform }, args: i => [...opt('platform', i.platform), '--json'] }, { name: 'listing_translate', title: 'Listing translation drafts', command: ['listing', 'translate'], write: true, network: false, idempotent: true, description: 'Add a section per target language to both listing files (App Store: name, subtitle, promotionalText, keywords, description; Google Play: title, short, full) with the source language\'s text and a status=translate marker. Then translate each field in place within the store limits (App Store subtitle 30, promotional text 170, keywords 100 comma-separated without duplicates or name words, description 4000; Play title 30, short 80, full 4000), set the marker to status=draft and run listing_check. The owner reviews the drafts (storebound listing reviewed). Reviewed sections are kept. Local files only.', props: { to: { type: 'string', pattern: '^[A-Za-z0-9_-]+(,[A-Za-z0-9_-]+)*$', description: 'Comma-separated target languages (config ids, App Store locales or Play codes)' }, diff --git a/cli/serve.ts b/cli/serve.ts index ee05729..b0df36e 100644 --- a/cli/serve.ts +++ b/cli/serve.ts @@ -145,6 +145,7 @@ export const DESKTOP_ONLY: ToolDef[] = [ args: i => [...opt('store', i.store), ...(i.with_automatic === true ? ['--with-automatic'] : [])] }, ]; const BUILD_NO = { type: 'string', pattern: '^\\d{1,9}(\\.\\d{1,9}){0,3}$', description: 'The build number (CFBundleVersion) the owner picked from the uploaded builds; never "the latest"' }; +const PLATFORM = { type: 'string', enum: ['ios', 'macos', 'tvos', 'visionos'], description: 'App Store platform of the version (default: the one that has it; when several do, the command asks)' }; const VERSION = { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$', description: 'App Store version (default: the one an open submission holds, else the editable one)' }; const IDS = { type: 'string', pattern: '^[A-Za-z0-9._]{1,100}(,[A-Za-z0-9._]{1,100}){0,49}$', description: 'Comma-separated product ids' }; /** `--yes` (the owner's step of apple submit / resubmit) and `--allow-price-changes` only in the real run, after the dialog. */ @@ -175,8 +176,8 @@ export const OWNER_TOOLS: ToolDef[] = [ ...(i.percent !== undefined && (i.action === 'percent' || i.action === 'resume') ? ['--fraction', String(Number(i.percent) / 100)] : []), '--track', String(i.track ?? 'production'), ...(i.not_sent_for_review === true ? ['--not-sent-for-review'] : [])] }, { name: 'owner_ios_phased', title: 'Change the App Store phased release', command: ['apple', 'release'], write: true, network: true, description: 'The 7-day phased release of an App Store version: turn it on, pause it (not a rollback), resume it, or release to everyone now (complete).', - props: { action: { type: 'string', enum: ['on', 'pause', 'resume', 'complete'] }, version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$' } }, - required: ['action'], args: i => ['--phased', String(i.action), ...(i.version ? ['--version', String(i.version)] : [])] }, + props: { action: { type: 'string', enum: ['on', 'pause', 'resume', 'complete'] }, version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$' }, platform: PLATFORM }, + required: ['action'], args: i => ['--phased', String(i.action), ...(i.version ? ['--version', String(i.version)] : []), ...(i.platform ? ['--platform', String(i.platform)] : [])] }, { name: 'owner_reply_send', title: 'Send one approved reply', command: ['reviews', 'send'], write: true, network: true, description: 'Sends one approved, unsent reply draft (.storebound/replies) to its store: public, the reviewer is notified. The draft checks (length, no incentives) apply.', props: { file: { type: 'string', pattern: '^(apple|play)-[A-Za-z0-9._-]{1,120}\\.md$', description: 'Draft file name in .storebound/replies' } }, @@ -201,12 +202,12 @@ export const OWNER_TOOLS: ToolDef[] = [ props: { only: IDS }, args: i => [...opt('only', i.only), ...real(i, '--allow-price-changes')] })), { name: 'owner_apple_submit', title: 'Submit for App Review', command: ['apple', 'submit'], write: true, network: true, description: 'Sends an App Store version to App Review with the build the owner picked by its number: the build is attached, the open review submission reused (a new draft only when none is open), the in-app purchases and subscriptions of the config that are ready go with it, then it is submitted (retried while Apple says "not ready yet"). After approval it goes live as the version\'s release setting says.', - props: { build: BUILD_NO, version: VERSION, resolve_iaps: { type: 'boolean', default: false, description: 'Mark REJECTED in-app purchase / subscription items of a submission back from App Review as resolved' } }, - required: ['build'], args: i => ['--build', String(i.build), ...opt('version', i.version), ...(i.resolve_iaps === true ? ['--resolve-iaps'] : []), ...real(i, '--yes')] }, + props: { build: BUILD_NO, version: VERSION, platform: PLATFORM, resolve_iaps: { type: 'boolean', default: false, description: 'Mark REJECTED in-app purchase / subscription items of a submission back from App Review as resolved' } }, + required: ['build'], args: i => ['--build', String(i.build), ...opt('version', i.version), ...opt('platform', i.platform), ...(i.resolve_iaps === true ? ['--resolve-iaps'] : []), ...real(i, '--yes')] }, { name: 'owner_apple_resubmit', title: 'Resubmit to App Review', command: ['apple', 'resubmit'], write: true, network: true, description: 'After a rejection: attaches the build the owner picked by its number to the rejected version, reuses the submission back from App Review (UNRESOLVED_ISSUES; missing items added), marks its REJECTED app version item resolved (in-app purchase items too with resolve_iaps) and resubmits it.', - props: { build: BUILD_NO, version: VERSION, resolve_iaps: { type: 'boolean', default: false, description: 'Also mark REJECTED in-app purchase / subscription items resolved (after fixing what App Review asked for)' } }, - required: ['build'], args: i => ['--build', String(i.build), ...opt('version', i.version), ...(i.resolve_iaps === true ? ['--resolve-iaps'] : []), ...real(i, '--yes')] }, + props: { build: BUILD_NO, version: VERSION, platform: PLATFORM, resolve_iaps: { type: 'boolean', default: false, description: 'Also mark REJECTED in-app purchase / subscription items resolved (after fixing what App Review asked for)' } }, + required: ['build'], args: i => ['--build', String(i.build), ...opt('version', i.version), ...opt('platform', i.platform), ...(i.resolve_iaps === true ? ['--resolve-iaps'] : []), ...real(i, '--yes')] }, { name: 'owner_apple_iap_submit', title: 'Submit in-app purchases for review', command: ['apple', 'iap-submit'], write: true, network: true, description: 'Sends the in-app purchases and subscriptions of the config that are ready to App Review in the open review submission (reused, never a second draft). The first of a type needs an app version in the same submission (with_version: the editable one goes too, and submitting submits the app).', props: { with_version: { type: 'boolean', default: false }, resolve_iaps: { type: 'boolean', default: false }, only: IDS }, diff --git a/cli/validate.ts b/cli/validate.ts index 72aa93c..0383635 100644 --- a/cli/validate.ts +++ b/cli/validate.ts @@ -14,7 +14,8 @@ // Live apps: crash / ANR vitals (Play Reporting API) and App Store diagnostics, as in `storebound health`: over a Play // bad behavior threshold is a blocker, near it a warning; a store without vitals access is only noted. --no-health skips. import { templateBlockers } from './lib/template-answers'; -import { ascClient, type J } from './apple/asc'; +import { ascClient, EDITABLE as APPLE_EDITABLE, type J } from './apple/asc'; +import { allVersions, type AscPlatform, parsePlatform, platformOf, stateOf, versionsPath } from './apple/platform'; import { capabilityReport } from './apple/signing'; import { firstProductReport } from './apple/first-products'; import { requiredDisplayTypes } from './apple/screenshots'; @@ -55,8 +56,14 @@ export async function collectApple(ctx: Ctx): Promise { const c = await ascClient(root, config.apple!.bundleId, config.apple?.appId); const appId = await c.app(); log('validate', 'apple: reading version, build, localizations'); - const versions = await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=10`); - const v: J = (await c.editableVersion()) ?? versions[0] ?? null; + // the platform: --platform, else the one with an editable version (several: iOS, and the others are named) + const every = await allVersions(c, appId); + const editableOf = (x: J) => APPLE_EDITABLE.has(stateOf(x)); + const withEditable = [...new Set(every.filter(editableOf).map(platformOf))]; + const platform: AscPlatform = parsePlatform(ctx.args.get('platform')) ?? (withEditable.length === 1 ? withEditable[0]! : withEditable.includes('IOS') || !every.length ? 'IOS' : platformOf(every[0])); + const versions = await c.all(versionsPath(appId, platform, 10)); + const v: J = (await c.editableVersion(platform)) ?? versions[0] ?? null; + const otherPlatformVersions = every.filter(x => platformOf(x) !== platform && editableOf(x)).map(x => ({ versionString: String(x.attributes.versionString), state: stateOf(x), platform: platformOf(x) })); let build: AppleSnapshot['build'] = null; const locales: AppleSnapshot['locales'] = []; let reviewDetail: AppleSnapshot['reviewDetail'] = null; @@ -109,7 +116,8 @@ export async function collectApple(ctx: Ctx): Promise { subscriptions, expectedSubscriptions: wantSubs.map(({ group, sub }) => ({ id: sub.id, group: group.name, locales: Object.keys(sub.listings).map(id => appleLocale.get(id)).filter((x): x is string => !!x) })), profile: await collectProfile(ctx.loaded), - version: v ? { versionString: v.attributes.versionString, state: v.attributes.appVersionState ?? v.attributes.appStoreState, copyright: v.attributes.copyright ?? null } : null, + version: v ? { versionString: v.attributes.versionString, state: v.attributes.appVersionState ?? v.attributes.appStoreState, copyright: v.attributes.copyright ?? null, platform } : null, + otherPlatformVersions, configCopyright: config.app.copyright, build, locales, reviewDetail, ageRating, expectedLocales: config.languages.map(l => l.apple).filter((x): x is string => !!x), diff --git a/cli/whats-new.ts b/cli/whats-new.ts index 02e9f32..b68b835 100644 --- a/cli/whats-new.ts +++ b/cli/whats-new.ts @@ -16,7 +16,8 @@ // STOREBOUND_TARGET_LANG (App Store locale, else Play code, else language id) in the environment; its stdout is // the translation. Existing translated files are kept unless --force. // storebound whats-new check [--dir store/whats-new] [--json] limits per store (Play 500, App Store 4000), untranslated files -// storebound whats-new apply [--dir store/whats-new] [--dry] [--json] checked files -> both listing files +// storebound whats-new apply [--dir store/whats-new] [--platform ios|macos|tvos|visionos] [--dry] [--json] checked files -> both listing files +// (--platform only goes into the printed apple listing command: the App Store's what's new is per platform version) import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import type { Language } from './lib/config'; @@ -29,6 +30,7 @@ import { resolveLanguages, setAppleWhatsNew, setPlayWhatsNew, } from './lib/whats-new'; import * as rt from './lib/rt'; +import { parsePlatform } from './apple/platform'; const TAG = 'whats-new'; const storeCode = (l: Language): string => l.apple ?? playCodes(l)[0] ?? l.id; @@ -93,6 +95,7 @@ export async function run(ctx: Ctx): Promise { const { config, root, resolve } = ctx.loaded; const a = ctx.args; if (a._[0] === 'check' || a._[0] === 'apply') { + parsePlatform(a.get('platform')); // a wrong --platform fails before anything is written const dir = resolve(a.get('dir') ?? 'store/whats-new'); const files = readDir(dir, config.languages); if (!files.length) throw new Error(`${dir}: no .md files`); @@ -114,7 +117,8 @@ export async function run(ctx: Ctx): Promise { if (a.has('dry')) { done(TAG, 'dry run: listing files not written'); return; } if (playFile && md.play !== undefined) writeFileSync(playFile, md.play); if (appleFile && md.apple !== undefined) writeFileSync(appleFile, md.apple); - done(TAG, `release notes of ${files.length} language(s) written into the listing files; push them with play release / apple listing`); + const pf = a.get('platform'); + done(TAG, `release notes of ${files.length} language(s) written into the listing files; push them with play release / apple listing --version x.y.z${pf ? ` --platform ${pf}` : ''} (the App Store's what's new belongs to one platform's version: apple listing picks the platform with the editable version, or asks)`); return; } const since = a.get('since') ?? (() => { try { return git(['describe', '--tags', '--abbrev=0'], root).trim(); } catch { return ''; } })(); diff --git a/skills/release-management/SKILL.md b/skills/release-management/SKILL.md index 805af86..d95babe 100644 --- a/skills/release-management/SKILL.md +++ b/skills/release-management/SKILL.md @@ -30,6 +30,7 @@ presses release; you prepare, dry-run and report. `storebound mcp` deliberately `storebound apple listing --version 1.3.0 --build `. Never pick "the latest build": a CI or a teammate may have uploaded another one meanwhile. 2. `storebound apple release --phased on --dry`, then without `--dry` (works while the version is being prepared). + With versions on more than one App Store platform add `--platform ios|macos|tvos|visionos` (pitfall 77). 3. Submit (owner, UI). Wait: `storebound apple status --wait-review` (polls with backoff, exit 0 approved, 1 rejected, 7 timeout; `--timeout 72h`). Rejected: `review-rejections` skill. 4. Approved = PENDING_DEVELOPER_RELEASE. Owner releases: `storebound apple release --manual-release` (asks to confirm) diff --git a/skills/review-rejections/SKILL.md b/skills/review-rejections/SKILL.md index 2648094..e159632 100644 --- a/skills/review-rejections/SKILL.md +++ b/skills/review-rejections/SKILL.md @@ -54,6 +54,8 @@ in-app purchases). Resubmit that same submission; never create a second one next 2. `storebound apple status`: the submission with UNRESOLVED_ISSUES, its items and their states. 3. `storebound apple resubmit --build ` (dry run without `--yes`): the plan table shows the build to attach, the submission reused, every item in it already or added, which REJECTED items are marked resolved, and the submit. + An app with a macOS (tvOS, visionOS) version too: it picks the platform whose version was rejected, and asks for + `--platform ios|macos|...` when both were (pitfall 77). 4. The owner's yes, then `storebound apple resubmit --build --yes`: build n is attached by its number, missing items go in, the REJECTED version item is marked resolved (`PATCH reviewSubmissionItems/{id}` `resolved: true`), then it submits. Apple answers every submit with "Version is not ready to be submitted yet" (and the console's diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index be166fc..8a34ceb 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -938,3 +938,18 @@ that fails without the fix (see CONTRIBUTING.md). - **Guard:** `cli/apple/creative-assets.ts` (`classify`, `pickAsset`, `processingTiming`), `tests/creative-assets.test.ts` (fake App Store Connect: upload and select in one run, still processing, rejected / archived files, add-for-review without submitting, verify read-only, a refused live placement); the fake commits library assets to PREPARE_FOR_SUBMISSION, as Apple does. + +## 77. A macOS (tvOS, visionOS) version was invisible next to the iOS one +- **Symptom:** `apple resubmit` said "nothing to resubmit" while a macOS version was REJECTED with an + UNRESOLVED_ISSUES submission; `apple listing --version 0.8.7` refused because the iOS 0.8.7 was live, although the + macOS 0.8.7 was the rejected one to fix; `apple status` listed versions without saying which platform. +- **Cause:** one app record can have a version per platform, each with its own state and its own review submission + (`reviewSubmissions` carry a `platform`). Lookups filtered on `IOS` only, or did not filter at all and mixed them. +- **Do:** every version and review submission lookup filters by platform (`filter[platform]`). Commands that need one + version (status --wait-review, listing, listing pull, resubmit, submit, release, screenshots) take + `--platform ios|macos|tvos|visionos`; without it they use the platform that has the version they need, and refuse + naming both when several do. Status, validate, release status, the report and the desktop show the platform next to + every version; validate and release status warn about another platform's editable or rejected version. +- **Guard:** `cli/apple/platform.ts` (`pickPlatform`, `parsePlatform`), `tests/apple-platforms.test.ts` (fake App Store + Connect: iOS 0.8.7 live, macOS 0.8.7 rejected in UNRESOLVED_ISSUES). + diff --git a/tests/apple-platforms.test.ts b/tests/apple-platforms.test.ts new file mode 100644 index 0000000..8ce98aa --- /dev/null +++ b/tests/apple-platforms.test.ts @@ -0,0 +1,108 @@ +// One app record, two App Store platforms (pitfall 77). Seen live: `apple resubmit` said "nothing to resubmit" while +// the macOS version was REJECTED in an UNRESOLVED_ISSUES submission, and `apple listing --version 0.8.7` refused +// because the iOS 0.8.7 was live while the macOS 0.8.7 was rejected. Against the fake App Store Connect. +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test'; +import type { ShipConfig } from '../cli/lib/config'; +import { planVersion } from '../cli/lib/listing-plan'; +import { upsertTiming } from '../cli/lib/upsert'; +import { appleRules } from '../cli/lib/validate-rules'; +import { applePlatformWarnings, appleReleases } from '../cli/lib/portfolio'; +import { parsePlatform, pickPlatform, platformLabel } from '../cli/apple/platform'; +import { run as appleResubmit } from '../cli/apple/resubmit'; +import { run as appleStatus } from '../cli/apple/status'; +import { run as appleRelease } from '../cli/apple/release'; +import { ascEnv, BASE, capture, project, restore } from './helpers/store-mock'; +import { installStores, type Stores, uninstallStores } from './helpers/fake-stores'; + +const APP = '6400000101'; +const CONFIG: ShipConfig = { ...BASE }; +let s: Stores; +beforeAll(ascEnv); +afterAll(restore); +beforeEach(() => { upsertTiming.waitMs = 0; s = installStores(); }); +afterEach(uninstallStores); + +const ver = (id: string, platform: string, versionString: string, state: string) => + s.asc.put({ type: 'appStoreVersions', id, attributes: { versionString, appVersionState: state, platform }, rels: { app: APP } }); +/** iOS 0.8.7 live, macOS 0.8.7 rejected in an UNRESOLVED_ISSUES submission, build 8 uploaded. */ +function split(): void { + ver('v-ios', 'IOS', '0.8.7', 'READY_FOR_DISTRIBUTION'); + ver('v-mac', 'MAC_OS', '0.8.7', 'REJECTED'); + s.asc.put({ type: 'builds', id: 'b-8', attributes: { version: '8', processingState: 'VALID', usesNonExemptEncryption: false }, rels: { app: APP } }); + s.asc.put({ type: 'reviewSubmissions', id: 'rs-mac', attributes: { platform: 'MAC_OS', state: 'UNRESOLVED_ISSUES' }, rels: { app: APP } }); + s.asc.put({ type: 'reviewSubmissionItems', id: 'it-mac', attributes: { state: 'REJECTED' }, rels: { reviewSubmission: 'rs-mac', appStoreVersion: 'v-mac' } }); +} + +describe('platform picking (pure)', () => { + const v = (platform: string, versionString: string, state: string) => ({ attributes: { platform, versionString, appVersionState: state } }); + const vs = [v('IOS', '0.8.7', 'READY_FOR_DISTRIBUTION'), v('MAC_OS', '0.8.7', 'REJECTED')]; + test('--platform values, labels', () => { + expect(parsePlatform('macos')).toBe('MAC_OS'); + expect(parsePlatform('MAC_OS')).toBe('MAC_OS'); + expect(parsePlatform('visionOS')).toBe('VISION_OS'); + expect(parsePlatform(undefined)).toBeUndefined(); + expect(() => parsePlatform('android')).toThrow(/ios \| macos/); + expect(platformLabel('MAC_OS')).toBe('macOS'); + }); + test('one platform has it -> that one; both -> refuse naming both; none -> the only platform, else iOS', () => { + const rejected = (x: typeof vs[0]) => x.attributes.appVersionState === 'REJECTED'; + expect(pickPlatform(vs, rejected, undefined, 'a rejected version')).toBe('MAC_OS'); + expect(pickPlatform(vs, rejected, 'IOS', 'a rejected version')).toBe('IOS'); + expect(() => pickPlatform([...vs, v('IOS', '0.8.8', 'REJECTED')], rejected, undefined, 'a rejected version')) + .toThrow(/a rejected version on more than one platform \(0\.8\.7 \(macOS\) REJECTED, 0\.8\.8 \(iOS\) REJECTED\): run it again with --platform macos or --platform ios/); + expect(pickPlatform([v('MAC_OS', '1.0', 'READY_FOR_SALE')], rejected, undefined, 'x')).toBe('MAC_OS'); + expect(pickPlatform(vs, () => false, undefined, 'x')).toBe('IOS'); + }); + test('listing --version 0.8.7: the macOS one is editable, so macOS; its plan updates it instead of refusing', () => { + const p = pickPlatform(vs, [x => x.attributes.versionString === '0.8.7' && x.attributes.appVersionState === 'REJECTED', () => true], undefined, 'x'); + expect(p).toBe('MAC_OS'); + const rows = [{ id: 'v-mac', attributes: { versionString: '0.8.7', appVersionState: 'REJECTED', platform: 'MAC_OS', copyright: '2026 Example', releaseType: 'MANUAL' } }]; + expect(planVersion(rows, '0.8.7', { copyright: '2026 Example', releaseType: 'MANUAL' }, 'MAC_OS').action).toBe('keep'); + const ios = [{ id: 'v-ios', attributes: { versionString: '0.8.7', appVersionState: 'READY_FOR_DISTRIBUTION', platform: 'IOS' } }]; + expect(planVersion(ios, '0.8.7', { copyright: 'c', releaseType: 'MANUAL' }, 'IOS').action).toBe('refuse'); + expect(planVersion([], '1.0.0', { copyright: 'c', releaseType: 'MANUAL' }, 'MAC_OS').attributes.platform).toBe('MAC_OS'); + }); + test('validate and release status name the other platform', () => { + const f = appleRules({ version: { versionString: '0.8.7', state: 'READY_FOR_DISTRIBUTION', platform: 'IOS' }, otherPlatformVersions: [{ versionString: '0.8.7', state: 'REJECTED', platform: 'MAC_OS' }], + build: null, expectedLocales: [], locales: [], requiredDisplayTypes: [], reviewDetail: null, ageRating: null, + priceSchedule: true, availability: true, iaps: [], expectedProducts: [], privacyUrl: { url: 'https://example.com/privacy', status: 200 } }); + expect(f.find(x => x.code === 'version')!.msg).toBe('version 0.8.7 (iOS) is READY_FOR_DISTRIBUTION (nothing to prepare)'); + expect(f.find(x => x.code === 'version-platform')).toMatchObject({ level: 'warn', msg: 'version 0.8.7 (macOS) is REJECTED too: this report covers 0.8.7 (iOS) only' }); + const data = { versions: [{ id: 'v-ios', attributes: { platform: 'IOS', versionString: '0.8.7', appVersionState: 'READY_FOR_DISTRIBUTION' } }, { id: 'v-mac', attributes: { platform: 'MAC_OS', versionString: '0.8.7', appVersionState: 'REJECTED' } }] }; + expect(applePlatformWarnings(data)).toEqual(['App Store macOS 0.8.7: REJECTED (storebound apple status --platform macos)']); + expect(appleReleases(data).map(r => [r.version, r.platform])).toEqual([['0.8.7', 'IOS']]); + }); +}); + +describe('commands against an app with iOS live and macOS rejected', () => { + test('apple resubmit picks the macOS version and its UNRESOLVED_ISSUES submission', async () => { + split(); + const r = await capture(() => appleResubmit(project(CONFIG).ctx(['--build', '8', '--dry']))); + expect(r.out + r.err).toContain('app version 0.8.7 (macOS): REJECTED'); + expect(r.out).toMatch(/rs-mac\s+UNRESOLVED_ISSUES\s+reuse/); + }); + test('apple resubmit --platform ios: nothing on iOS, said per platform', async () => { + split(); + await expect(appleResubmit(project(CONFIG).ctx(['--build', '8', '--platform', 'ios', '--dry']))).rejects.toThrow(/no rejected iOS App Store version and no iOS review submission/); + }); + test('both platforms rejected: refuse and ask for --platform', async () => { + split(); + s.asc.all('appStoreVersions').find(x => x.id === 'v-ios')!.attributes.appVersionState = 'REJECTED'; + await expect(appleResubmit(project(CONFIG).ctx(['--build', '8', '--dry']))).rejects.toThrow(/more than one platform .*--platform (ios|macos) or --platform (ios|macos)/); + }); + test('apple status labels every version and submission with its platform; --platform shows one', async () => { + split(); + const r = await capture(() => appleStatus(project(CONFIG).ctx([]))); + expect(r.out).toMatch(/version 0\.8\.7\s+iOS\s+READY_FOR_DISTRIBUTION/); + expect(r.out).toMatch(/version 0\.8\.7\s+macOS\s+REJECTED/); + expect(r.out).toContain('review submission rs-mac (macOS) is back from App Review'); + expect(r.out).toContain('storebound apple resubmit --build --platform macos'); + const ios = await capture(() => appleStatus(project(CONFIG).ctx(['--platform', 'ios']))); + expect(ios.out).not.toContain('macOS'); + }); + test('apple release --phased on picks the platform with a version not yet live', async () => { + split(); + const r = await capture(() => appleRelease(project(CONFIG).ctx(['--phased', 'on', '--dry']))); + expect(r.out + r.err).toContain('0.8.7 macOS (REJECTED)'); + }); +}); diff --git a/tests/resubmit.test.ts b/tests/resubmit.test.ts index f3da4b5..f86d62a 100644 --- a/tests/resubmit.test.ts +++ b/tests/resubmit.test.ts @@ -230,7 +230,7 @@ describe('apple submit --build (a first submission, the desktop owner action s.asc.res.get('ver-1')!.attributes.appVersionState = 'READY_FOR_SALE'; const p = project(ONE); await expect(appleSubmit(p.ctx(['--build', '8', '--version', '1.0.0']))).rejects.toThrow(/READY_FOR_SALE: only a version in Prepare for Submission/); - await expect(appleSubmit(p.ctx(['--build', '8']))).rejects.toThrow(/no App Store version to submit/); + await expect(appleSubmit(p.ctx(['--build', '8']))).rejects.toThrow(/no iOS App Store version to submit/); }); }); @@ -381,18 +381,18 @@ describe('apple status', () => { rejected(); const p = project(CONFIG); const r = await capture(() => appleStatus(p.ctx([]))); - expect(r.out).toContain('review submission rs-old is back from App Review with UNRESOLVED_ISSUES'); - expect(r.out).toMatch(/app version 1\.0\.0\s+REJECTED/); + expect(r.out).toContain('review submission rs-old (iOS) is back from App Review with UNRESOLVED_ISSUES'); + expect(r.out).toMatch(/app version 1\.0\.0 \(iOS\)\s+REJECTED/); expect(r.out).toMatch(/inAppPurchaseVersion iapv-gems\s+READY_FOR_REVIEW/); expect(r.out).toContain('resubmit with: storebound apple resubmit --build '); - expect(r.out).toMatch(/app version 1\.0\.0\s+REJECTED \(not resolved/); + expect(r.out).toMatch(/app version 1\.0\.0 \(iOS\)\s+REJECTED \(not resolved/); }); test('an empty draft is labelled harmless; --cancel-submission on it answers 409 "not in cancellable state", left as is', async () => { s.asc.put({ type: 'reviewSubmissions', id: 'rs-empty', attributes: { platform: 'IOS', state: 'READY_FOR_REVIEW' }, rels: { app: APP } }); const p = project(CONFIG); const r = await capture(() => appleStatus(p.ctx([]))); - expect(r.out).toContain('review submission rs-empty READY_FOR_REVIEW: empty draft (harmless; App Store Connect keeps it, not cancellable)'); + expect(r.out).toContain('review submission rs-empty iOS READY_FOR_REVIEW: empty draft (harmless; App Store Connect keeps it, not cancellable)'); const c = await capture(() => appleStatus(p.ctx(['--cancel-submission', 'rs-empty', '--yes']))); expect([c.exit ?? 0, c.err]).toEqual([0, '']); expect(c.out).toContain('rs-empty is not cancellable'); From c2f34c62f3336535d55c4b71cce0929f8b6561a1 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 03:04:14 +0700 Subject: [PATCH 034/344] apple creative-assets: place Header and Search Results assets once Apple approved them (the version page offers only approved assets); waiting files are reported per locale and placement with their upload date and the re-run command, in the run, --verify, validate and the report; iPhone Duo: the published API spec still has no Duo type, the note says the console takes Duo and the API does not yet --- CHANGELOG.md | 30 ++++++++-------- cli/apple/creative-assets.ts | 58 +++++++++++++++++++++--------- cli/commands.ts | 2 +- cli/data/flags.json | 2 ++ cli/lib/validate-rules.ts | 3 ++ cli/mcp-tools.ts | 2 +- cli/shots/spec.ts | 6 ++-- cli/validate.ts | 11 ++++++ docs/store-art.md | 12 ++++--- skills/store-pitfalls/SKILL.md | 42 +++++++++++----------- skills/store-screenshots/SKILL.md | 12 ++++--- tests/creative-assets.test.ts | 60 ++++++++++++++++++++++++------- tests/ppo.test.ts | 1 + 13 files changed, 163 insertions(+), 78 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dd98a4e..7ce1a37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,20 +2,22 @@ ## Unreleased -- **Header and Search Results: select once processed, then add for review.** `storebound apple creative-assets` now - selects an asset for the product page header or search results slot as soon as it is processed ("Prepare for - Submission"), as the console's Browse Assets does: Apple reviews an asset only once it is in a review submission, so - 0.8.13's "select once approved" never finished. Upload and select happen in one run (processing wait up to 2 min with - a heartbeat). `--add-for-review` adds the selected, unreviewed assets to the app's draft review submission (never - submits; Submit for Review stays the owner's); `--verify` (MCP `apple_creative_assets_verify`) reads every slot back - read-only and fails when one differs from the local file. A file App Review rejected, or one that failed processing - twice, is not uploaded again; an archived copy of the same file is unarchived instead of uploaded. A live app without - an editable version uses the live version: approved assets are selected there, new ones are uploaded and wait for a - review of their own. Art without words needs no copy per locale: `/creative/header.png` / `search.*` - fill every language without its own file, uploaded once and placed per locale (the dry run counts files, not slots). - If App Store Connect refuses a placement on the live version, the run says so, leaves the live page unchanged (the - new placement goes first, the old one is removed only after Apple accepted it), links the live version page and does - not retry the other live slots. Pitfall 76 rewritten. +- **Header and Search Results: upload, add for review, place once approved.** `storebound apple creative-assets` + uploads each file once into the Asset Library (MD5 upsert: a rejected file or one that failed processing twice is + not uploaded again, an archived copy is unarchived), and places it on the version as soon as Apple approved it: the + version page's slots offer only approved assets. Until then every locale and placement says "uploaded , + waiting for Apple's approval; run `storebound apple creative-assets` again later", and a re-run places it (an + approved old asset stays shown meanwhile). `--add-for-review` adds the unreviewed assets to the app's draft review + submission (never submits; Submit for Review stays the owner's); `--verify` (MCP `apple_creative_assets_verify`) + reads every slot back read-only with the same waiting state, and `validate` / the report list waiting files. A live + app without an editable version uses the live version; if App Store Connect refuses a placement there, the run says + so, leaves the live page unchanged (the new placement goes first, the old one is removed only after Apple accepted + it), links the live version page and does not retry the other live slots. Art without words needs no copy per + locale: `/creative/header.png` / `search.*` fill every language without its own file, uploaded once and + placed per locale (the dry run counts files, not slots). Pitfall 76 rewritten. +- **iPhone Duo.** Apple's published App Store Connect API spec (re-checked: still the 2026-10-06 file) has no Duo + screenshot or preview type, so `apple screenshots` keeps skipping the Duo sets with the console link; the check / + validate note now says the console takes Duo and the API does not yet. - **macOS (tvOS, visionOS) versions are no longer invisible.** `apple status`, `listing`, `listing pull`, `resubmit`, `submit`, `release` and `screenshots` take `--platform ios|macos|tvos|visionos` (MCP tools and the desktop's owner diff --git a/cli/apple/creative-assets.ts b/cli/apple/creative-assets.ts index 295aa9d..ac65f1c 100644 --- a/cli/apple/creative-assets.ts +++ b/cli/apple/creative-assets.ts @@ -10,14 +10,14 @@ // "Submit assets from Asset Library", checked 19 Oct 2026): // 1. a file is uploaded once into the app's Asset Library (POST appAssetLibraryImages / Videos, category // CREATIVE_ASSETS, its MD5 in referenceName "storebound " because library assets carry no checksum); -// 2. after processing it is "Prepare for Submission", and in that state it can already be selected for a slot -// (POST appAssetLibraryPlacements, placementType PRODUCT_PAGE_HEADER_ASSET / APP_STORE_SEARCH_RESULTS_ASSET, the -// version localization). Approval is NOT needed first: an asset is only reviewed once it is in a review -// submission, so "select only approved assets" waits forever (pitfall 76); -// 3. App Review: the asset is a review submission item of its own (reviewSubmissionItems appAssetLibraryImage / -// appAssetLibraryVideo; console "Add for Review"). Before the app's first approved version it goes in the same -// submission as that version; afterwards it can go alone. --add-for-review adds it to the draft submission; -// pressing Submit for Review stays the owner's. +// 2. after processing it is "Prepare for Submission"; App Review reviews it as a review submission item of its own +// (reviewSubmissionItems appAssetLibraryImage / appAssetLibraryVideo; console "Add for Review"): before the app's +// first approved version in the same submission as that version, afterwards alone. --add-for-review adds it to +// the draft submission; pressing Submit for Review stays the owner's; +// 3. the version page's slots offer only approved assets ("Browse approved assets", seen in a real release, 20 Oct +// 2026): an APPROVED asset is selected (POST appAssetLibraryPlacements, placementType PRODUCT_PAGE_HEADER_ASSET / +// APP_STORE_SEARCH_RESULTS_ASSET, the version localization); any other one is reported per locale and placement +// as "uploaded , waiting for Apple's approval", and a later run places it (pitfall 76). // Upsert: a slot that already shows the same MD5 is left alone; an asset with the same MD5 in the library is reused // (an archived one is unarchived), never uploaded twice; a REJECTED file is not uploaded again (change the file); a // changed file replaces the slot (the old placement is removed, then the new one is created). Read back at the end. @@ -33,7 +33,7 @@ import * as rt from '../lib/rt'; import { ffprobe } from '../shots/report'; import { imageInfo } from '../shots/spec'; import { checkCreativeImage, checkCreativeVideo, type CreativeFile, creativeFiles, PLACEMENT_TYPE, type Placement } from '../shots/creative'; -import { ascClient, md5, type J } from './asc'; +import { type Asc, ascClient, md5, type J } from './asc'; import { AmbiguousWriteError } from '../lib/upsert'; import { addItem, ensureDraft, OtherSubmissionError } from './submission'; @@ -83,6 +83,29 @@ export function pickAsset(assets: J[], sum: string): { asset?: J; unarchive?: bo return {}; } +/** "uploaded 2026-10-19, waiting for Apple's approval (IN_REVIEW); run `storebound apple creative-assets` again later". + * The version page's header / search slots offer only approved assets ("Browse approved assets"), so an asset that + * is not APPROVED waits; a later run places it. Pure. */ +export function waitingText(a: J): string { + const d = String(a?.attributes?.createdDate ?? '').slice(0, 10); + return `${d ? `uploaded ${d}, ` : ''}waiting for Apple's approval (${a?.attributes?.state ?? '?'}); run \`storebound apple creative-assets\` again later`; +} + +/** Local creative files whose library asset (same MD5) is processed but not APPROVED yet, per locale and placement: + * for validate and the report (one library read, no placements). */ +export async function creativeWaiting(c: Asc, appId: string, local: Map): Promise<{ locale: string; placement: string; file: string; text: string }[]> { + const lib = (await c.maybe(`/v1/apps/${appId}/assetLibrary`))?.data as J | undefined; + if (!lib) return []; + const assets = [...(await c.all(`/v1/appAssetLibraries/${lib.id}/images?filter[category]=CREATIVE_ASSETS&limit=200`)), + ...(await c.all(`/v1/appAssetLibraries/${lib.id}/videos?filter[category]=CREATIVE_ASSETS&limit=200`))]; + const out: { locale: string; placement: string; file: string; text: string }[] = []; + for (const [locale, fs] of local) for (const f of fs) { + const a = pickAsset(assets, md5(readFileSync(f.file))).asset; + if (a && selectable(classify(a.attributes?.state)) && a.attributes?.state !== 'APPROVED') out.push({ locale, placement: PLACEMENT_TYPE[f.placement], file: basename(f.file), text: waitingText(a) }); + } + return out; +} + const reason = (a: J): string => { const d = ((a.attributes?.stateDetails ?? []) as J[]).map(x => x?.code ?? x?.message ?? x?.description).filter(Boolean); return d.length ? ` (${d.join(', ')})` : ''; @@ -146,7 +169,7 @@ export async function run(ctx: Ctx): Promise { const version = editable ?? await live(); const onLive = !editable; if (!version) throw new Error(`no editable or live App Store version: the header and search results slots belong to a version page (run apple listing --version x.y.z first). ${consoleLink('asc.version')}`); - if (onLive && !verify) log(TAG, `no editable version: using the live version ${version.attributes.versionString}, where only approved assets can be selected`); + if (onLive && !verify) log(TAG, `no editable version: using the live version ${version.attributes.versionString}`); const locs = await c.all(`/v1/appStoreVersions/${version.id}/appStoreVersionLocalizations?limit=50`); const library = async (): Promise => [ ...(await c.all(`/v1/appAssetLibraries/${lib.id}/images?filter[category]=CREATIVE_ASSETS&limit=200`)), @@ -208,7 +231,7 @@ export async function run(ctx: Ctx): Promise { if (dry) { // one upload per file: a later locale with the same file reuses it (the real run finds it by MD5) const first = !planned.has(sum); planned.add(sum); - log(TAG, `${tag}: would ${first ? 'upload' : 'reuse'} ${basename(f.file)}${first ? ' to the Asset Library' : ' (uploaded once for an earlier locale)'} and select it ${onLive ? 'on the live version once approved' : 'once processed'}`); + log(TAG, `${tag}: would ${first ? 'upload' : 'reuse'} ${basename(f.file)}${first ? ' to the Asset Library' : ' (uploaded once for an earlier locale)'} and select it once Apple approved it`); row(first ? 'upload' : 'reuse'); continue; } log(TAG, `${tag}: uploading ${basename(f.file)} to the Asset Library`); @@ -227,8 +250,9 @@ export async function run(ctx: Ctx): Promise { if (cls === 'processing') { row('wait', asset); continue; } warn(TAG, `${tag}: ${basename(f.file)} is ${asset.attributes?.state}${reason(asset)}; not selected`); row('refuse', asset); continue; } - if (onLive && asset.attributes?.state !== 'APPROVED') { - log(TAG, `${tag}: ${basename(f.file)} is ${asset.attributes?.state} in the Asset Library; the live version takes it once App Review approved it (re-run then)`); + // the version page's slots take only approved assets ("Browse approved assets"): the rest wait, a re-run places them + if (asset.attributes?.state !== 'APPROVED') { + log(TAG, `${tag}: ${basename(f.file)} ${waitingText(asset)}`); row('approve', asset); continue; } const action = placed.length ? 'replace' : 'select'; @@ -285,7 +309,7 @@ export async function run(ctx: Ctx): Promise { log(TAG, `${added} creative asset(s) added to draft review submission ${sid}; nothing was submitted`); } } - const summary = `creative assets: ${n(['keep'])} up to date, ${n(['select', 'replace'])} ${dry ? 'to select' : 'selected'}, ${n(['upload'])} file(s) to upload${n(['reuse']) ? ` (used by ${n(['upload', 'reuse'])} slots)` : ''}, ${n(['wait'])} still processing, ${approve ? `${approve} waiting for App Review (live version), ` : ''}${n(['refuse'])} refused${off ? `, ${off} did not read back` : ''}`; + const summary = `creative assets: ${n(['keep'])} up to date, ${n(['select', 'replace'])} ${dry ? 'to select' : 'selected'}, ${n(['upload'])} file(s) to upload${n(['reuse']) ? ` (used by ${n(['upload', 'reuse'])} slots)` : ''}, ${n(['wait'])} still processing, ${approve ? `${approve} waiting for Apple's approval, ` : ''}${n(['refuse'])} refused${off ? `, ${off} did not read back` : ''}`; if (unreviewed.size) { log(TAG, forReview ? `owner step: Submit for Review with the version (or alone once the app has an approved version): ${consoleLink('asc.app-review')}` @@ -295,7 +319,7 @@ export async function run(ctx: Ctx): Promise { return done(TAG, dry ? `${summary} (dry run, nothing sent)` : summary); async function verifySlots(): Promise { - let bad = 0; + let bad = 0, waiting = 0; for (const loc of locs) { const locale: string = loc.attributes.locale; for (const f of local.get(locale) ?? []) { @@ -305,11 +329,13 @@ export async function run(ctx: Ctx): Promise { const shown = placed.map(p => assets.find(x => x.id === shownOf(p))).filter(Boolean) as J[]; const ok = placed.length === 1 && shown[0] && sumOf(shown[0]) === sum; const what = shown.length ? shown.map(a => `${a.attributes?.fileName ?? a.id} (${a.attributes?.state})`).join(', ') : 'nothing'; + const pending = ok ? undefined : pickAsset(assets, sum).asset; if (ok) log(TAG, `ok ${locale} ${ptype}: ${what}`); + else if (pending && selectable(classify(pending.attributes?.state)) && pending.attributes?.state !== 'APPROVED') { waiting++; log(TAG, `waiting ${locale} ${ptype}: ${basename(f.file)} ${waitingText(pending)} (shows ${what} until then)`); } else { bad++; warn(TAG, `${locale} ${ptype}: shows ${what}, wanted ${basename(f.file)}${placed.length > 1 ? ` (${placed.length} selected)` : ''}`); } } } if (bad) process.exitCode = 1; - done(TAG, `creative assets verified on version ${version!.attributes.versionString} (read-only): ${bad ? `${bad} slot(s) differ from the local files` : 'every slot shows the local file'}`); + done(TAG, `creative assets verified on version ${version!.attributes.versionString} (read-only): ${bad ? `${bad} slot(s) differ from the local files` : waiting ? 'every other slot shows the local file' : 'every slot shows the local file'}${waiting ? `, ${waiting} waiting for Apple's approval` : ''}`); } } diff --git a/cli/commands.ts b/cli/commands.ts index 3bb9ee0..17cf3b3 100644 --- a/cli/commands.ts +++ b/cli/commands.ts @@ -80,7 +80,7 @@ export const COMMANDS: Record Promise, string]> = { 'apple appinfo': [() => import('./apple/appinfo'), 'categories, age rating, content rights, Free price, territories'], 'apple review-details': [() => import('./apple/review-details'), 'App Review contact, demo account (from .storebound/, masked) + notes'], 'apple status': [() => import('./apple/status'), 'versions, builds, IAPs, review submissions (--wait-review, --cancel-submission ); --platform ios|macos|tvos|visionos (default: the platform that has the version this needs; asks when several do)'], - 'apple creative-assets': [() => import('./apple/creative-assets'), 'Header and Search Results: product page header (21:9) and search results asset (3:2) per locale, or one universal 5244x2950 PNG; uploads to the Asset Library and selects it once processed (MD5 upsert); --add-for-review, --verify (read-only), --dry'], + 'apple creative-assets': [() => import('./apple/creative-assets'), 'Header and Search Results: product page header (21:9) and search results asset (3:2) per locale, or one universal 5244x2950 PNG; uploads to the Asset Library and places it once Apple approved it, reporting waiting ones per locale (MD5 upsert, safe to re-run); --add-for-review, --verify (read-only), --dry'], 'apple previews': [() => import('./apple/previews'), 'app preview videos per locale (MD5-idempotent, poster frame time code); --dry'], 'apple release': [() => import('./apple/release'), 'phased release on|pause|resume|complete, --manual-release (asks first); --platform ios|macos|tvos|visionos (default: the platform that has the version this needs; asks when several do)'], 'apple signing': [() => import('./apple/signing'), 'status | ensure: bundle id capabilities, distribution certificate (key kept in .storebound/signing), App Store profiles installed for Xcode; --dry, asks first'], diff --git a/cli/data/flags.json b/cli/data/flags.json index 1565902..3787556 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -847,6 +847,7 @@ "play" ], "validate": [ + "add-for-review", "allow-price-changes", "apple", "capacitor", @@ -877,6 +878,7 @@ "unity", "variant", "variants", + "verify", "weekly", "write" ], diff --git a/cli/lib/validate-rules.ts b/cli/lib/validate-rules.ts index 61bd7c2..3c9e93a 100644 --- a/cli/lib/validate-rules.ts +++ b/cli/lib/validate-rules.ts @@ -57,6 +57,8 @@ export function rendersFindings(store: 'apple' | 'play', r: RendersCheck | undef export interface AppleSnapshot { version: { versionString: string; state: string; copyright?: string | null; platform?: string } | null; + /** Header and Search Results files uploaded but not approved yet, per locale and placement (apple creative-assets). */ + creativeWaiting?: { locale: string; placement: string; file: string; text: string }[]; /** Editable or rejected versions of the app's other platforms (an app's macOS version has its own state). */ otherPlatformVersions?: { versionString: string; state: string; platform: string }[]; /** app.copyright from the config (undefined: not set). */ @@ -206,6 +208,7 @@ export function appleRules(s: AppleSnapshot): Finding[] { else if (EDITABLE.includes(s.version.state)) add('ok', 'version', `version ${vl}: ${s.version.state}`); else if (IN_FLIGHT.includes(s.version.state)) add('warn', 'version', `version ${vl} is ${s.version.state} (nothing to prepare)`); else add('warn', 'version', `version ${vl}: ${s.version.state}`); + for (const w of s.creativeWaiting ?? []) add('warn', 'creative-waiting', `${w.locale} ${w.placement}: ${w.file} ${w.text}`, 'storebound apple creative-assets (a re-run places it once approved; --add-for-review sends it to review)'); for (const o of s.otherPlatformVersions ?? []) { const name = PLATFORM_NAMES[o.platform] ?? o.platform; add('warn', 'version-platform', `version ${o.versionString} (${name}) is ${o.state} too: this report covers ${vl || 'iOS'} only`, `storebound validate --platform ${name.toLowerCase()}; storebound apple status lists every platform`); diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index 16c72d0..70aa50b 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -248,7 +248,7 @@ export const TOOLS: ToolDef[] = [ seconds: { type: 'integer', minimum: 15, maximum: 30 }, captions: { type: 'boolean', default: true } }, args: i => [...opt('lang', i.lang), ...opt('target', i.target), ...opt('seconds', i.seconds), ...(i.captions === false ? ['--no-captions'] : [])] }, { name: 'apple_creative_assets', title: 'App Store header and search results assets', command: ['apple', 'creative-assets'], write: true, destructive: true, network: true, idempotent: true, - description: 'Header and Search Results (iOS / iPadOS 27+): checks //creative/ (header 3840x1646, search 3:2, universal 5244x2950 PNG; no alpha; videos 5-30 s, 30/60 fps), uploads new files to the App Asset Library and selects them for PRODUCT_PAGE_HEADER_ASSET / APP_STORE_SEARCH_RESULTS_ASSET on the editable version once processed (Prepare for Submission is enough; MD5 upsert, same file = nothing sent, a rejected file is never re-uploaded). add_for_review puts unreviewed assets into the draft review submission (never submits). Play counterpart: feature graphic + promo video.', + description: 'Header and Search Results (iOS / iPadOS 27+): checks //creative/ (header 3840x1646, search 3:2, universal 5244x2950 PNG; no alpha; videos 5-30 s, 30/60 fps), uploads new files to the App Asset Library and selects them for PRODUCT_PAGE_HEADER_ASSET / APP_STORE_SEARCH_RESULTS_ASSET on the editable version once Apple approved them (the slots take only approved assets; until then each locale and placement is reported as waiting, and a re-run places them; MD5 upsert, same file = nothing sent, a rejected file is never re-uploaded). add_for_review puts unreviewed assets into the draft review submission (never submits). Play counterpart: feature graphic + promo video.', props: { only, add_for_review: { type: 'boolean', default: false, description: 'Also add the selected, unreviewed assets to the draft review submission (Submit for Review stays the owner\'s)' } }, args: i => [...opt('only', i.only), ...(i.add_for_review === true ? ['--add-for-review'] : [])] }, { name: 'apple_creative_assets_verify', title: 'Verify App Store header and search results', command: ['apple', 'creative-assets', '--verify'], write: false, network: true, diff --git a/cli/shots/spec.ts b/cli/shots/spec.ts index e0663ec..89813d9 100644 --- a/cli/shots/spec.ts +++ b/cli/shots/spec.ts @@ -56,10 +56,10 @@ export const IMAGE_SPECS: Record = { }; /** ASC screenshotDisplayType per iPhone Duo size key. null = NOT IN THE API YET: ScreenshotDisplayType in App Store - * Connect API 4.5.1 (spec checked 2026-10-18) has no Duo value (only AppAssetLibraryDisplayClass lists IPHONE_DUO). + * Connect API 4.5.1 (spec re-checked 2026-10-20: the published zip is still the 2026-10-06 one, same sha256) has no Duo value (only AppAssetLibraryDisplayClass lists IPHONE_DUO). * When Apple adds it: regenerate (bun tools/gen-api.ts) and put the exact enum names here; uploads then include them. */ export const IPHONE_DUO_DISPLAY: Record = { 'iphone-duo-outer': null, 'iphone-duo-inner': null }; -export const IPHONE_DUO_NOT_IN_API = 'App Store Connect does not take iPhone Duo screenshots through the API yet; storebound keeps them in store/renders'; +export const IPHONE_DUO_NOT_IN_API = 'the App Store Connect console takes iPhone Duo screenshots, the API does not yet; storebound keeps them in store/renders'; /** Reportedly required from this date for apps built with the iOS 27.1 SDK or later. */ export const IPHONE_DUO_REQUIRED_FROM = '2027-04-01'; const PLAY_FOLDABLE = 'Google Play has no foldable slot: foldables show the 7" / 10" tablet screenshots (tab7, tab10, play.tablets)'; @@ -69,7 +69,7 @@ const PLAY_FOLDABLE = 'Google Play has no foldable slot: foldables show the 7" / export function iphoneDuoNote(o: { apple: boolean; duo: boolean; play?: boolean; today?: Date }): { level: 'info' | 'warn'; msg: string } | null { if (!o.apple || o.duo) return null; const late = (o.today ?? new Date()).toISOString().slice(0, 10) >= IPHONE_DUO_REQUIRED_FROM; - return { level: late ? 'warn' : 'info', msg: `no iPhone Duo screenshots (outer 1398x2034, inner 2007x2853; apple.iphoneDuo): optional now, required from April 2027 for iOS 27.1 SDK builds${o.play ? `. ${PLAY_FOLDABLE}` : ''}` }; + return { level: late ? 'warn' : 'info', msg: `no iPhone Duo screenshots (outer 1398x2034, inner 2007x2853; apple.iphoneDuo): optional now, required from April 2027 for iOS 27.1 SDK builds; the App Store Connect console takes Duo screenshots and previews, the API does not yet (apple screenshots skips them with the console link)${o.play ? `. ${PLAY_FOLDABLE}` : ''}` }; } /** Play screenshots in general (any size the store accepts): 320..3840 px per side, long side at most 2x the short. */ diff --git a/cli/validate.ts b/cli/validate.ts index 0383635..bdf936f 100644 --- a/cli/validate.ts +++ b/cli/validate.ts @@ -35,6 +35,7 @@ import type { ScanFinding } from './lib/scan/rules'; import { playClient } from './play/client'; import { listOneTimeProducts } from './play/products'; import { creativeNote } from './shots/creative'; +import { creativeWaiting, localCreative } from './apple/creative-assets'; /** Profile facts for the checks: config + local credentials + public URL checks (no store API). */ export async function collectProfile(loaded: Loaded): Promise { @@ -51,6 +52,15 @@ export async function collectProfile(loaded: Loaded): Promise { }; } +/** Header and Search Results files uploaded but not approved yet (the slots take only approved assets). Never fails + * validate: a local file problem or an unreadable library is a note for creative-assets itself. */ +async function creativeWaitingOf(ctx: Ctx, c: Awaited>, appId: string): Promise { + try { + const { local } = localCreative(ctx); + return local.size ? await creativeWaiting(c, appId, local) : []; + } catch { return []; } +} + export async function collectApple(ctx: Ctx): Promise { const { config, root } = ctx.loaded; const c = await ascClient(root, config.apple!.bundleId, config.apple?.appId); @@ -118,6 +128,7 @@ export async function collectApple(ctx: Ctx): Promise { profile: await collectProfile(ctx.loaded), version: v ? { versionString: v.attributes.versionString, state: v.attributes.appVersionState ?? v.attributes.appStoreState, copyright: v.attributes.copyright ?? null, platform } : null, otherPlatformVersions, + creativeWaiting: await creativeWaitingOf(ctx, c, appId), configCopyright: config.app.copyright, build, locales, reviewDetail, ageRating, expectedLocales: config.languages.map(l => l.apple).filter((x): x is string => !!x), diff --git a/docs/store-art.md b/docs/store-art.md index 93ca1b2..c1ded30 100644 --- a/docs/store-art.md +++ b/docs/store-art.md @@ -100,14 +100,16 @@ Screenshots". Optional: without these assets the App Store uses in-app events, a - **Not rendered by `shots render`**: the scene templates are portrait device shots; make the wide art yourself (or from the feature graphic artwork at the larger size) and drop it in. - **Upload and select:** `storebound apple creative-assets --dry`, then without `--dry`. Files go into the app's Asset - Library (API: `appAssetLibraryImages` / `appAssetLibraryVideos`, category `CREATIVE_ASSETS`), and once processed - ("Prepare for Submission", a bounded wait of 2 minutes with a heartbeat) the run selects them for the slots of the - editable version (`appAssetLibraryPlacements`, `PRODUCT_PAGE_HEADER_ASSET` / `APP_STORE_SEARCH_RESULTS_ASSET`), as the - console's Browse Assets > Save does. Approval is not needed first. Same file (MD5) = nothing sent; an archived copy is + Library (API: `appAssetLibraryImages` / `appAssetLibraryVideos`, category `CREATIVE_ASSETS`; processing is a bounded + wait of 2 minutes with a heartbeat). The version page's slots offer only approved assets ("Browse approved assets"), + so an asset is placed (`appAssetLibraryPlacements`, `PRODUCT_PAGE_HEADER_ASSET` / `APP_STORE_SEARCH_RESULTS_ASSET`) + once Apple approved it; until then each locale and placement says "uploaded , waiting for Apple's approval; run + `storebound apple creative-assets` again later", and a later run places it. `--verify`, `validate` and the report + show the same waiting state. Same file (MD5) = nothing sent; an archived copy is unarchived; a file App Review rejected is never uploaded again (change the file). MCP: `apple_creative_assets` (dry by default). - **Review:** an asset is reviewed only once it is in a review submission (its own item, `appAssetLibraryImage` / - `appAssetLibraryVideo`; the console's "Add for Review"). `--add-for-review` adds the selected, unreviewed assets to the + `appAssetLibraryVideo`; the console's "Add for Review"). `--add-for-review` adds the uploaded, unreviewed assets to the app's draft submission, once: before the first approved version it is the same submission as that version, later they can go alone. Pressing Submit for Review stays the owner's. - **Live app, no editable version:** the run uses the live version, where only APPROVED assets are selected (Apple diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 8a34ceb..032859d 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -913,31 +913,33 @@ that fails without the fix (see CONTRIBUTING.md). `screenshots-duo` note in check / validate. `tests/ppo.test.ts`. ## 76. Header and Search Results assets are not uploaded like screenshots -- **Symptom:** a header or search results image was "uploaded" but the version page shows no header, a run kept saying - "waiting for Apple's approval" for days, or a re-run uploaded the same file again. +- **Symptom:** a header or search results image was "uploaded" but the version page shows no header, a run waited on + an asset nobody had sent to review, or a re-run uploaded the same file again. - **Cause:** these slots take assets from the app's Asset Library (`GET /v1/apps/{id}/assetLibrary`), not a set of their own: a slot is an `appAssetLibraryPlacements` row (`PRODUCT_PAGE_HEADER_ASSET` or `APP_STORE_SEARCH_RESULTS_ASSET`, the version localization). An asset is reviewed only once it is in a review submission (its own item, `reviewSubmissionItems` with `appAssetLibraryImage` / `appAssetLibraryVideo`; the console's - "Add for Review"). Apple's "App Store asset statuses": a processed asset is "Prepare for Submission" and can already - be selected for a version. So an earlier storebound that selected only APPROVED assets waited forever: nothing ever - sent the asset to review. Library assets carry no `sourceFileChecksum`, a rejected asset stays rejected (uploading - the same bytes again only adds a copy), and the search slot is the API's `APP_STORE_SEARCH_RESULTS_ASSET` - (`SEARCH_RESULTS_ADS_ASSET` is the Apple Ads one). Seen live (19 Oct 2026): placements of a live version read back - with state `ACTIVE`, which the 4.5.1 spec's `AppAssetLibraryPlacementState` does not list; never validate placement - states against the spec enum. + "Add for Review"); after processing it is "Prepare for Submission". The version page's slots offer only approved + assets ("Browse approved assets", seen in a real release, 20 Oct 2026), so placing waits for Apple's approval. + Library assets carry no `sourceFileChecksum`, a rejected asset stays rejected (uploading the same bytes again only + adds a copy), and the search slot is the API's `APP_STORE_SEARCH_RESULTS_ASSET` (`SEARCH_RESULTS_ADS_ASSET` is the + Apple Ads one). Seen live (19 Oct 2026): placements of a live version read back with state `ACTIVE`, which the 4.5.1 + spec's `AppAssetLibraryPlacementState` does not list; never validate placement states against the spec enum. - **Do:** `storebound apple creative-assets`: MD5 in `referenceName` ("storebound "), reuse (or unarchive) a library - asset with the same MD5, select it once processed, never re-upload a rejected file or one that failed processing - twice. Then `--add-for-review` puts the unreviewed assets into the draft submission (with the first version, or alone - once the app has an approved version) and `--verify` reads every slot back. With no editable version the live version - is used and only APPROVED assets go onto it; the rest wait for their own review. Whether the API accepts a new - placement on a live version is not documented: storebound places the new asset first and removes the old one only - after Apple accepted it, and on a 4xx it says so, leaves the live page unchanged, gives the live version page's deep - link (select it there, or create a version and re-run) and does not try the remaining live slots. Uploading, selecting and adding to the - draft are normal steps, not owner buttons; Submit for Review stays the owner's. -- **Guard:** `cli/apple/creative-assets.ts` (`classify`, `pickAsset`, `processingTiming`), `tests/creative-assets.test.ts` - (fake App Store Connect: upload and select in one run, still processing, rejected / archived files, add-for-review - without submitting, verify read-only, a refused live placement); the fake commits library assets to PREPARE_FOR_SUBMISSION, as Apple does. + asset with the same MD5, never re-upload a rejected file or one that failed processing twice. `--add-for-review` + puts the unreviewed assets into the draft submission (with the first version, or alone once the app has an approved + version; Submit for Review stays the owner's). An asset that is not APPROVED is reported per locale and placement as + "uploaded , waiting for Apple's approval; run `storebound apple creative-assets` again later"; the run is an + upsert, so a later run places it as soon as it is approved (an approved old asset stays shown meanwhile). `--verify` + and `validate` / the report show the same waiting state. With no editable version the live version is used. + Whether the API accepts a new placement on a live version is not documented: storebound places the new asset first + and removes the old one only after Apple accepted it, and on a 4xx it says so, leaves the live page unchanged, gives + the live version page's deep link (select it there, or create a version and re-run) and does not try the remaining + live slots. +- **Guard:** `cli/apple/creative-assets.ts` (`classify`, `pickAsset`, `waitingText`, `creativeWaiting`, + `processingTiming`), `tests/creative-assets.test.ts` (fake App Store Connect: upload, wait for approval, place on a + re-run, still processing, rejected / archived files, add-for-review without submitting, verify read-only with the + waiting state, a refused live placement, the validate finding). ## 77. A macOS (tvOS, visionOS) version was invisible next to the iOS one - **Symptom:** `apple resubmit` said "nothing to resubmit" while a macOS version was REJECTED with an diff --git a/skills/store-screenshots/SKILL.md b/skills/store-screenshots/SKILL.md index b07203c..95e9b9c 100644 --- a/skills/store-screenshots/SKILL.md +++ b/skills/store-screenshots/SKILL.md @@ -209,14 +209,16 @@ Screenshots". Optional: without these assets the App Store uses in-app events, a - **Not rendered by `shots render`**: the scene templates are portrait device shots; make the wide art yourself (or from the feature graphic artwork at the larger size) and drop it in. - **Upload and select:** `storebound apple creative-assets --dry`, then without `--dry`. Files go into the app's Asset - Library (API: `appAssetLibraryImages` / `appAssetLibraryVideos`, category `CREATIVE_ASSETS`), and once processed - ("Prepare for Submission", a bounded wait of 2 minutes with a heartbeat) the run selects them for the slots of the - editable version (`appAssetLibraryPlacements`, `PRODUCT_PAGE_HEADER_ASSET` / `APP_STORE_SEARCH_RESULTS_ASSET`), as the - console's Browse Assets > Save does. Approval is not needed first. Same file (MD5) = nothing sent; an archived copy is + Library (API: `appAssetLibraryImages` / `appAssetLibraryVideos`, category `CREATIVE_ASSETS`; processing is a bounded + wait of 2 minutes with a heartbeat). The version page's slots offer only approved assets ("Browse approved assets"), + so an asset is placed (`appAssetLibraryPlacements`, `PRODUCT_PAGE_HEADER_ASSET` / `APP_STORE_SEARCH_RESULTS_ASSET`) + once Apple approved it; until then each locale and placement says "uploaded , waiting for Apple's approval; run + `storebound apple creative-assets` again later", and a later run places it. `--verify`, `validate` and the report + show the same waiting state. Same file (MD5) = nothing sent; an archived copy is unarchived; a file App Review rejected is never uploaded again (change the file). MCP: `apple_creative_assets` (dry by default). - **Review:** an asset is reviewed only once it is in a review submission (its own item, `appAssetLibraryImage` / - `appAssetLibraryVideo`; the console's "Add for Review"). `--add-for-review` adds the selected, unreviewed assets to the + `appAssetLibraryVideo`; the console's "Add for Review"). `--add-for-review` adds the uploaded, unreviewed assets to the app's draft submission, once: before the first approved version it is the same submission as that version, later they can go alone. Pressing Submit for Review stays the owner's. - **Live app, no editable version:** the run uses the live version, where only APPROVED assets are selected (Apple diff --git a/tests/creative-assets.test.ts b/tests/creative-assets.test.ts index 8073ba5..8bd7ee4 100644 --- a/tests/creative-assets.test.ts +++ b/tests/creative-assets.test.ts @@ -4,7 +4,10 @@ // --add-for-review into the draft submission without submitting, --verify read-only). import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test'; import { md5 } from '../cli/apple/asc'; -import { classify, MAX_FAILED, pickAsset, processingTiming, REF, run, selectable } from '../cli/apple/creative-assets'; +import { classify, creativeWaiting, MAX_FAILED, pickAsset, processingTiming, REF, run, selectable, waitingText } from '../cli/apple/creative-assets'; +import { ascClient } from '../cli/apple/asc'; +import { appleRules } from '../cli/lib/validate-rules'; +import { creativeFiles as filesOf } from '../cli/shots/creative'; import { checkCreativeImage, checkCreativeVideo, CREATIVE_NOTE, creativeFiles, creativeNote } from '../cli/shots/creative'; import { imageInfo } from '../cli/shots/spec'; import { upsertTiming } from '../cli/lib/upsert'; @@ -111,29 +114,35 @@ describe('apple creative-assets against the fake App Store Connect', () => { const lib = () => [...s.asc.all('appAssetLibraryImages'), ...s.asc.all('appAssetLibraryVideos')]; const files = (h = 1, q = 2) => ({ 'store/renders/en/creative/header.png': png(3840, 1646, false, h), 'store/renders/en/creative/search.png': png(1920, 1280, false, q) }); - test('dry run, upload + select in one run (no approval wait), same file = nothing, changed file = replace', async () => { + test('dry run, upload, wait for approval per locale and placement, a re-run places them; same file = nothing; changed file = replace once approved', async () => { const p = setup(files()); const dry = await go(p, ['--dry']); expect(dry.w).toEqual([]); expect(dry.out).toContain('would upload header.png'); const first = await go(p); - expect(first.w).toEqual(['POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}', 'POST /v1/appAssetLibraryPlacements', - 'POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}', 'POST /v1/appAssetLibraryPlacements']); + expect(first.w).toEqual(['POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}', 'POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}']); expect(lib().map(x => x.attributes.referenceName)).toContain(REF(md5(files()['store/renders/en/creative/header.png']))); - expect(s.asc.all('appAssetLibraryPlacements').map(x => x.attributes.placementType).sort()).toEqual(['APP_STORE_SEARCH_RESULTS_ASSET', 'PRODUCT_PAGE_HEADER_ASSET']); + expect(s.asc.all('appAssetLibraryPlacements')).toHaveLength(0); + expect(first.out).toMatch(/en-US PRODUCT_PAGE_HEADER_ASSET: header\.png (uploaded \d{4}-\d\d-\d\d, )?waiting for Apple's approval \(PREPARE_FOR_SUBMISSION\); run `storebound apple creative-assets` again later/); + expect(first.out).toContain('2 waiting for Apple\'s approval'); expect(first.out).toContain('--add-for-review'); - expect(first.out).not.toContain("waiting for Apple's approval"); + expect((await go(p)).w).toEqual([]); // still waiting: nothing sent again + for (const x of lib()) x.attributes.state = 'APPROVED'; + expect((await go(p)).w).toEqual(['POST /v1/appAssetLibraryPlacements', 'POST /v1/appAssetLibraryPlacements']); + expect(s.asc.all('appAssetLibraryPlacements').map(x => x.attributes.placementType).sort()).toEqual(['APP_STORE_SEARCH_RESULTS_ASSET', 'PRODUCT_PAGE_HEADER_ASSET']); expect((await go(p)).w).toEqual([]); const q = project(CFG, files(9)); - const rep = await go(q); - expect(rep.w).toEqual(['POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}', 'DELETE /v1/appAssetLibraryPlacements/{id}', 'POST /v1/appAssetLibraryPlacements']); + expect((await go(q)).w).toEqual(['POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}']); + expect(s.asc.all('appAssetLibraryPlacements')).toHaveLength(2); // the approved old one stays shown meanwhile + for (const x of lib()) x.attributes.state = 'APPROVED'; + expect((await go(q)).w).toEqual(['DELETE /v1/appAssetLibraryPlacements/{id}', 'POST /v1/appAssetLibraryPlacements']); expect(s.asc.all('appAssetLibraryPlacements')).toHaveLength(2); }); - test('processing that outlasts the bounded wait: not selected, re-run selects without a second upload', async () => { + test('processing that outlasts the bounded wait: not selected, a re-run once approved selects without a second upload', async () => { const f = files(); const p = setup(f); for (const [k, id] of [['header', 'img-h'], ['search', 'img-s']] as const) @@ -143,6 +152,8 @@ describe('apple creative-assets against the fake App Store Connect', () => { expect(r1.out).toContain('still UPLOAD_COMPLETE'); expect(r1.out).toContain('2 still processing'); for (const x of lib()) x.attributes.state = 'PREPARE_FOR_SUBMISSION'; + expect((await go(p)).w).toEqual([]); + for (const x of lib()) x.attributes.state = 'APPROVED'; expect((await go(p)).w).toEqual(['POST /v1/appAssetLibraryPlacements', 'POST /v1/appAssetLibraryPlacements']); }); @@ -153,8 +164,8 @@ describe('apple creative-assets against the fake App Store Connect', () => { s.asc.put({ type: 'appAssetLibraryImages', id: 'img-arc', attributes: { category: 'CREATIVE_ASSETS', referenceName: REF(md5(f['store/renders/en/creative/search.png'])), state: 'ARCHIVED', fileName: 'search.png' }, rels: { assetLibrary: 'lib-1' } }); const r = await go(p, [], 1); expect(r.out).toContain('rejected by App Review'); - expect(r.w).toEqual(['PATCH /v1/appAssetLibraryImages/{id}', 'POST /v1/appAssetLibraryPlacements']); - expect(s.asc.all('appAssetLibraryPlacements').map(x => x.attributes.placementType)).toEqual(['APP_STORE_SEARCH_RESULTS_ASSET']); + expect(r.w).toEqual(['PATCH /v1/appAssetLibraryImages/{id}']); + expect(lib().find(x => x.id === 'img-arc')!.attributes.state).not.toBe('ARCHIVED'); }); test('--add-for-review: unreviewed assets go into the draft once, nothing is submitted', async () => { @@ -175,6 +186,12 @@ describe('apple creative-assets against the fake App Store Connect', () => { expect(before.w).toEqual([]); expect(before.out).toContain('shows nothing, wanted header.png'); await go(p); + const wait = await go(p, ['--verify']); + expect(wait.w).toEqual([]); + expect(wait.out).toMatch(/waiting en-US PRODUCT_PAGE_HEADER_ASSET: header\.png .*waiting for Apple's approval/); + expect(wait.out).toContain("2 waiting for Apple's approval"); + for (const x of lib()) x.attributes.state = 'APPROVED'; + await go(p); const ok = await go(p, ['--verify']); expect(ok.w).toEqual([]); expect(ok.out).toContain('every slot shows the local file'); @@ -187,7 +204,7 @@ describe('apple creative-assets against the fake App Store Connect', () => { expect(up.out).toContain('using the live version 1.0.0'); expect(up.w).toEqual(['POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}', 'POST /v1/appAssetLibraryImages', 'PATCH /v1/appAssetLibraryImages/{id}', 'POST /v1/reviewSubmissions', 'POST /v1/reviewSubmissionItems', 'POST /v1/reviewSubmissionItems']); - expect(up.out).toContain('2 waiting for App Review (live version)'); + expect(up.out).toContain("2 waiting for Apple's approval"); expect(s.asc.all('appAssetLibraryPlacements')).toHaveLength(0); for (const x of lib()) x.attributes.state = 'APPROVED'; expect((await go(p)).w).toEqual(['POST /v1/appAssetLibraryPlacements', 'POST /v1/appAssetLibraryPlacements']); @@ -218,7 +235,24 @@ describe('apple creative-assets against the fake App Store Connect', () => { expect(dry.out).toContain('1 file(s) to upload (used by 2 slots)'); const r = await go(p); expect(r.w.filter(x => x === 'POST /v1/appAssetLibraryImages')).toHaveLength(1); - expect(r.w.filter(x => x === 'POST /v1/appAssetLibraryPlacements')).toHaveLength(2); + for (const x of lib()) x.attributes.state = 'APPROVED'; + expect((await go(p)).w.filter(x => x === 'POST /v1/appAssetLibraryPlacements')).toHaveLength(2); + }); + + test('validate / report: a file waiting for approval is named per locale and placement', async () => { + const p = setup(files()); + await go(p); + const c = await ascClient(p.ctx([]).loaded.root, 'com.example.notes', APP); + const local = new Map([['en-US', filesOf(`${p.ctx([]).loaded.root}/store/renders`, 'en')]]); + const w = await creativeWaiting(c, APP, local); + expect(w.map(x => [x.locale, x.placement, x.file])).toEqual([['en-US', 'PRODUCT_PAGE_HEADER_ASSET', 'header.png'], ['en-US', 'APP_STORE_SEARCH_RESULTS_ASSET', 'search.png']]); + expect(waitingText({ attributes: { state: 'IN_REVIEW', createdDate: '2026-10-19T10:00:00Z' } })).toBe("uploaded 2026-10-19, waiting for Apple's approval (IN_REVIEW); run `storebound apple creative-assets` again later"); + const f = appleRules({ version: null, build: null, expectedLocales: [], locales: [], requiredDisplayTypes: [], reviewDetail: null, ageRating: null, priceSchedule: true, availability: true, + iaps: [], expectedProducts: [], privacyUrl: { url: 'https://example.com/privacy', status: 200 }, creativeWaiting: w }).filter(x => x.code === 'creative-waiting'); + expect(f).toHaveLength(2); + expect(f[0]!.msg).toContain("en-US PRODUCT_PAGE_HEADER_ASSET: header.png"); + for (const x of lib()) x.attributes.state = 'APPROVED'; + expect(await creativeWaiting(c, APP, local)).toEqual([]); }); test('a bad file stops the run before any call', async () => { diff --git a/tests/ppo.test.ts b/tests/ppo.test.ts index f130eab..f4c22c2 100644 --- a/tests/ppo.test.ts +++ b/tests/ppo.test.ts @@ -106,6 +106,7 @@ describe('iPhone Duo (foldable) sizes', () => { expect(n.level).toBe('info'); expect(n.msg).toContain('optional now, required from April 2027 for iOS 27.1 SDK builds'); expect(n.msg).toContain('tablet screenshots'); + expect(n.msg).toContain('the App Store Connect console takes Duo screenshots and previews, the API does not yet'); expect(iphoneDuoNote({ apple: true, duo: false, today: after })!.level).toBe('warn'); const base = { version: null, build: null, locales: [], expectedLocales: [], requiredDisplayTypes: [], reviewDetail: null, ageRating: null, priceSchedule: true, availability: true, iaps: [], expectedProducts: [], privacyUrl: { url: 'https://example.com/privacy', status: 200 } }; const f = appleRules({ ...base, today: before } as unknown as Parameters[0]).find(x => x.code === 'screenshots-duo')!; From 74101edeca57ccdebea2fe19a9001039bff97e02 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 03:08:37 +0700 Subject: [PATCH 035/344] api tables regenerated (the new creative-assets and platform commands wrap more operations) --- cli/api/wrapped.gen.ts | 4 ++-- docs/api-coverage.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cli/api/wrapped.gen.ts b/cli/api/wrapped.gen.ts index a6d7c8e..3252c91 100644 --- a/cli/api/wrapped.gen.ts +++ b/cli/api/wrapped.gen.ts @@ -79,7 +79,7 @@ export const WRAPPED: { apple: Record; play: Record; play: Record Date: Tue, 20 Oct 2026 03:09:33 +0700 Subject: [PATCH 036/344] storebound 0.8.14: version in package.json and every copy, CHANGELOG 0.8.14 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index a69d45b..a84d8d8 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.13", + "version": "0.8.14", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 590b859..ee542b7 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.13", + "version": "0.8.14", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index e19c636..f1ccf69 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.13", + "version": "0.8.14", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index e6f0b93..a6238d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.14 · 2026-10-19 + - **Header and Search Results: upload, add for review, place once approved.** `storebound apple creative-assets` uploads each file once into the Asset Library (MD5 upsert: a rejected file or one that failed processing twice is not uploaded again, an archived copy is unarchived), and places it on the version as soon as Apple approved it: the diff --git a/apps/desktop/package.json b/apps/desktop/package.json index ce46d13..8047fb9 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.13", + "version": "0.8.14", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 2192196..9d68ef4 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4010,7 +4010,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.13" +version = "0.8.14" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index bdd545a..0cd187a 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.13" +version = "0.8.14" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index d766476..442bd49 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.13", + "version": "0.8.14", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index 7c6a291..33e24fe 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.13", + "version": "0.8.14", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index 8d68012..e886e82 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.13", + "version": "0.8.14", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From 30488c512d12b7c522ac1c99cfb1f51566833778 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 03:16:23 +0700 Subject: [PATCH 037/344] release: the desktop typecheck runs before the tag (0.8.14's Mac build stopped on an unused variable after the tag); a staged npm publish (409 previously staged) waits for the maintainer's approval instead of 5 minutes of polling; cross-store: drop the unused variable --- cli/lib/cross-store.ts | 2 +- tools/release.ts | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/cli/lib/cross-store.ts b/cli/lib/cross-store.ts index af8e504..c35043f 100644 --- a/cli/lib/cross-store.ts +++ b/cli/lib/cross-store.ts @@ -84,7 +84,7 @@ export function textMentions(text: string, o: { store: CrossStore; locale: strin const add = (term: string): void => { out.push({ store: o.store, locale: o.locale, field: o.field, line: i + 1, term, text: line.slice(0, 200), fix: fixFor(o.store, o.field) }); }; const tag = OTHER_TAG[o.store].exec(line); if (tag) add(`[${tag[1]}]`); - for (const { term, re } of COMPILED[o.store]) { + for (const { re } of COMPILED[o.store]) { re.lastIndex = 0; for (let m = re.exec(line); m; m = re.exec(line)) { const s = m.index, e = s + m[0].length; diff --git a/tools/release.ts b/tools/release.ts index 41b7dc3..8a3d884 100644 --- a/tools/release.ts +++ b/tools/release.ts @@ -291,6 +291,10 @@ async function main(): Promise { const t = await mainTests(); if (t.state === 'red') say(`WARNING: background tests are red on ${t.sha.slice(0, 10)} (${t.failed.join(', ')}): ${t.run}; releasing anyway, fix it in the next patch`); } catch (e) { say(`background tests: not read (${(e as Error).message.slice(0, 120)})`); } + // the desktop's own typecheck (stricter: unused locals) runs in tauri's beforeBuildCommand: catch it before the tag + // (0.8.14's Mac build stopped on an unused variable after the tag was pushed) + { const t = spawnSync('bunx', ['tsc', '--noEmit', '-p', 'apps/desktop'], { cwd: ROOT, encoding: 'utf8', timeout: 180_000 }); + if (t.status !== 0) fail(`the desktop typecheck fails (the Mac build would stop on it):\n${(t.stdout + t.stderr).trim().split('\n').slice(0, 8).join('\n')}`); } // the dry run catches what the bump would refuse if (!rehearsal && !resume) { try { cutChangelog(readFileSync(join(ROOT, 'CHANGELOG.md'), 'utf8'), version, '2000-01-01'); } catch (e) { fail((e as Error).message); } } if (!yes) { console.log('\ndry run: nothing changed (--yes to release)'); return; } @@ -431,6 +435,9 @@ async function npmRelease(version: string, token: string): Promise { const who = npmRun(['whoami'], token); if (who.code !== 0) fail(`npm token refused (npm whoami): ${who.out.trim().split('\n').slice(-2).join(' ')}; make a new one: bun tools/release.ts npm-token`); const pub = npmRun(['publish'], token); + // npm stages a token publish for the maintainer's approval on npmjs.com (409 "previously staged version" on a retry): + // nothing to wait for here, the owner approves it once + if (/staged/i.test(pub.out)) { say(`npm: ${version} is staged and waits for the maintainer's approval: https://www.npmjs.com/package/storebound (approve it there; then deprecate runs with: bun tools/release.ts npm-publish)`); return; } if (pub.code !== 0 && !/previously published|cannot publish over/i.test(pub.out)) fail(`npm publish failed: ${pub.out.trim().split('\n').slice(-4).join(' ')}`); // the registry lags a little after a publish; wait (timeout, heartbeat) until it serves the version as latest const end = Date.now() + 5 * 60_000; From e59539fec8f16fea1788dd7f18a84b28b5dfd92b Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 03:29:19 +0700 Subject: [PATCH 038/344] shots: Mac App Store screenshots (mac size, APP_DESKTOP to the macOS version), a landscape layout (Mac window or bare; Mac, Play Chromebook, Play tablets), safe margins in every template checked by shots check from the render's layout boxes, a contact sheet timeout that scales with images, sizes and load; pitfall 80 --- CHANGELOG.md | 12 ++++ cli/apple/screenshots.ts | 21 ++++-- cli/art.ts | 2 +- cli/lib/art-pull.ts | 2 +- cli/lib/config.ts | 14 ++++ cli/lib/embedded.ts | 8 +-- cli/lib/validate-rules.ts | 8 ++- cli/mcp-tools.ts | 2 +- cli/play/images.ts | 8 +++ cli/shots/feature-app.html | 2 + cli/shots/feature.html | 6 +- cli/shots/lib.ts | 58 ++++++++++++++-- cli/shots/render.ts | 42 +++++++++--- cli/shots/report.ts | 16 +++-- cli/shots/spec.ts | 19 ++++-- cli/shots/template-app.html | 56 +++++++++++---- cli/shots/template.html | 68 +++++++++++++++---- cli/validate.ts | 1 + docs/pitfalls.md | 1 + docs/store-art.md | 10 +++ skills/store-pitfalls/SKILL.md | 16 +++++ skills/store-screenshots/SKILL.md | 30 ++++++++- tests/browser/landscape.browser.ts | 74 ++++++++++++++++++++ tests/idempotency.test.ts | 16 +++++ tests/mac-landscape.test.ts | 105 +++++++++++++++++++++++++++++ tools/ci-plan.ts | 2 +- 26 files changed, 532 insertions(+), 67 deletions(-) create mode 100644 tests/browser/landscape.browser.ts create mode 100644 tests/mac-landscape.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index a6238d4..9c01f9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ ## Unreleased +- **Mac App Store screenshots.** `apple.mac: true` adds the `mac` size (2880 x 1800; `shots check` takes exactly + Apple's four 16:10 sizes, no alpha) and `apple screenshots --platform macos` uploads it as `APP_DESKTOP` to the macOS + version. `validate` notes a macOS version without Mac screenshots. Art pull maps `APP_DESKTOP` to `mac/`. +- **Landscape layout** in both templates: copy column plus the frame in a Mac window or bare (`shots.landscape`), for + Mac, Play Chromebook (`play.chromebook`; no API type, `play images` links the console) and, with + `shots.landscape.playTablets`, Play's 7" / 10" tablet slots. +- **Safe margins:** text and logo keep 7 % of the width left / right and 5 % of the height at the top in every + template (feature graphics too); `shots check` fails boxes under 6 % / 4 %, measured from the render's layout data. +- **Contact sheet:** the `sheet.png` wait scales with the images, sizes and machine load, with a heartbeat, instead of + a flat 30 s. +- iPhone Duo skip message says plainly that the API has no Duo type and names the console page. + ## 0.8.14 · 2026-10-19 - **Header and Search Results: upload, add for review, place once approved.** `storebound apple creative-assets` diff --git a/cli/apple/screenshots.ts b/cli/apple/screenshots.ts index 3d484ab..3d45e1f 100644 --- a/cli/apple/screenshots.ts +++ b/cli/apple/screenshots.ts @@ -3,7 +3,9 @@ // storebound apple screenshots [--src store/renders] [--only en-US,tr] [--jobs 4] [--variant b] [--dry] // Source per language: //ios69/NN.png (6.9", 1320 x 2868 -> APP_IPHONE_67), // ios65/NN.png (6.5", 1284 x 2778 -> APP_IPHONE_65) and, only with apple.ipad, ipad13/NN.png (13" iPad, 2064 x 2752 -> -// APP_IPAD_PRO_3GEN_129: the API has no "13 inch" value, the 13" display set keeps the 3rd gen 12.9" name). Up to 10 +// APP_IPAD_PRO_3GEN_129: the API has no "13 inch" value, the 13" display set keeps the 3rd gen 12.9" name). With +// --platform macos (or when only the macOS version is editable) and apple.mac: mac/NN.png (2880 x 1800 -> APP_DESKTOP) +// to the macOS version. iPhone Duo sets are skipped with the console deep link (no API display type yet). Up to 10 // per set. --variant uploads ///... instead (an A/B variant from shots.variants, e.g. for a // Product Page Optimization treatment you then set up in App Store Connect). Apple processes uploads asynchronously; failed // ones are reported at the end. Long: run in the background with a log file. @@ -29,10 +31,13 @@ export const IPAD_DISPLAY: Record = { ipad13: 'APP_IPAD_PRO_3GEN /** 6.3" iPhone (Dynamic Island, medium display), uploaded only when apple.iphoneMedium is true. */ export const MEDIUM_DISPLAY: Record = { 'iphone-medium': 'APP_IPHONE_61' }; -/** Display sets this project uploads: the iPhone sets, plus the 6.3" set with apple.iphoneMedium and the 13" iPad set - * with apple.ipad. */ -export const displaySets = (apple: { ipad?: boolean; iphoneMedium?: boolean; iphoneDuo?: boolean } | undefined): Record => - ({ ...DISPLAY, ...(apple?.iphoneMedium ? MEDIUM_DISPLAY : {}), ...(apple?.ipad ? IPAD_DISPLAY : {}), +/** Mac App Store set (APP_DESKTOP, 16:10), uploaded to the macOS version only, with apple.mac. */ +export const MAC_DISPLAY: Record = { mac: 'APP_DESKTOP' }; + +/** Display sets this project uploads to a version of `platform`: macOS -> the Mac set (apple.mac); iOS (default) -> the + * iPhone sets, plus the 6.3" set with apple.iphoneMedium and the 13" iPad set with apple.ipad. */ +export const displaySets = (apple: { ipad?: boolean; iphoneMedium?: boolean; iphoneDuo?: boolean; mac?: boolean } | undefined, platform: string = 'IOS'): Record => + platform === 'MAC_OS' ? (apple?.mac ? MAC_DISPLAY : {}) : ({ ...DISPLAY, ...(apple?.iphoneMedium ? MEDIUM_DISPLAY : {}), ...(apple?.ipad ? IPAD_DISPLAY : {}), ...(apple?.iphoneDuo ? Object.fromEntries(Object.entries(IPHONE_DUO_DISPLAY).filter((e): e is [string, string] => !!e[1])) : {}) }); /** iPhone Duo size keys `apple screenshots` skips (apple.iphoneDuo on, no API display type yet), with the message. */ @@ -89,8 +94,10 @@ export async function run(ctx: Ctx): Promise { const version = await c.editableVersion(platform); if (!version) throw new Error(`no editable ${platformLabel(platform)} App Store version (run apple listing --version x.y.z first)`); log('apple', `screenshots for version ${versionLabel(version)}`); - const duoSkip = skippedDuoSets(config.apple); + const duoSkip = platform === 'MAC_OS' ? null : skippedDuoSets(config.apple); if (duoSkip) warn('apple', duoSkip.msg); + if (platform === 'MAC_OS' && !config.apple?.mac) throw new Error('macOS version: set apple.mac: true and render the mac size (storebound shots render --size mac) first'); + if (platform !== 'MAC_OS' && config.apple?.mac) log('apple', 'Mac screenshots (mac/, APP_DESKTOP) go to the macOS version: run apple screenshots --platform macos'); const langOf = byAppleLocale(config.languages); const locs = await c.all(`/v1/appStoreVersions/${version.id}/appStoreVersionLocalizations?limit=50`); @@ -105,7 +112,7 @@ export async function run(ctx: Ctx): Promise { if (!lang) { warn('apple', `${locale}: no language with apple: "${locale}", skipped`); continue; } tasks.push(async () => { const sets = await c.all(`/v1/appStoreVersionLocalizations/${loc.id}/appScreenshotSets`); - for (const [dir, type] of Object.entries(displaySets(config.apple))) { + for (const [dir, type] of Object.entries(displaySets(config.apple, platform))) { const d = join(src, lang.id, dir); const files = numberedImages(d).filter(f => f.endsWith('.png')).slice(0, 10); if (!existsSync(d) || !files.length) { warn('apple', `${locale}: nothing in ${d}, skipped`); continue; } diff --git a/cli/art.ts b/cli/art.ts index 87dc882..52489d9 100644 --- a/cli/art.ts +++ b/cli/art.ts @@ -408,7 +408,7 @@ type LiveSet = LiveArtSet; type LiveResult = LiveArtResult; const LABELS: Record = { - APP_IPHONE_67: 'App Store iPhone 6.9"', APP_IPHONE_65: 'App Store iPhone 6.5"', APP_IPHONE_61: 'iPhone with Dynamic Island (medium display)', APP_IPHONE_55: 'App Store iPhone 5.5"', APP_IPAD_PRO_3GEN_129: 'iPad 13" display', APP_IPAD_PRO_129: 'App Store iPad 12.9" (2nd gen)', + APP_IPHONE_67: 'App Store iPhone 6.9"', APP_IPHONE_65: 'App Store iPhone 6.5"', APP_IPHONE_61: 'iPhone with Dynamic Island (medium display)', APP_IPHONE_55: 'App Store iPhone 5.5"', APP_IPAD_PRO_3GEN_129: 'iPad 13" display', APP_DESKTOP: 'Mac App Store', APP_IPAD_PRO_129: 'App Store iPad 12.9" (2nd gen)', IPHONE_67: 'App Store iPhone app preview', IPAD_PRO_3GEN_129: 'App Store iPad app preview', featureGraphic: 'Play feature graphic', phoneScreenshots: 'Play phone', sevenInchScreenshots: 'Play 7" tablet', tenInchScreenshots: 'Play 10" tablet', tvScreenshots: 'Play TV', wearScreenshots: 'Play Wear OS', }; diff --git a/cli/lib/art-pull.ts b/cli/lib/art-pull.ts index 3ad9358..38e0c5b 100644 --- a/cli/lib/art-pull.ts +++ b/cli/lib/art-pull.ts @@ -45,7 +45,7 @@ export interface RemoteArt { } /** App Store display type -> renders size folder. */ -export const APPLE_SHOT_DIR: Record = { APP_IPHONE_67: 'ios69', APP_IPHONE_65: 'ios65', APP_IPHONE_61: 'iphone-medium', APP_IPAD_PRO_3GEN_129: 'ipad13' }; +export const APPLE_SHOT_DIR: Record = { APP_IPHONE_67: 'ios69', APP_IPHONE_65: 'ios65', APP_IPHONE_61: 'iphone-medium', APP_IPAD_PRO_3GEN_129: 'ipad13', APP_DESKTOP: 'mac' }; /** App Store preview type -> preview folder. */ export const APPLE_PREVIEW_DIR: Record = { IPHONE_67: 'iphone', IPAD_PRO_3GEN_129: 'ipad' }; /** Play image type -> renders size folder (screenshots; the feature graphic and icon are files of their own). */ diff --git a/cli/lib/config.ts b/cli/lib/config.ts index 8811f7b..b7a0287 100644 --- a/cli/lib/config.ts +++ b/cli/lib/config.ts @@ -164,6 +164,11 @@ export interface ShotsConfig { phone?: { w: number; h: number; dpr?: number; bar?: number }; /** Tablet frames: default 1032 x 1352 @2x (13" iPad minus its 24 px bar) with apple.ipad, else 800 x 1240 @2x. */ tablet?: { w: number; h: number; dpr?: number; bar?: number }; + /** Landscape layout (Mac, Chromebook, and the Play tablet slots with playTablets): copy on one side, the frame on the + * other. Frames: //landscape/.png at `size` CSS px (default 1440 x 900 @2x). frame: 'window' (a + * Mac window around the game, the default for mac) or 'none' (the bare frame, the default for Play sizes). side: + * where the copy goes (default 'left'). playTablets: render tab7 / tab10 landscape (1920 x 1080 / 2560 x 1440). */ + landscape?: { frame?: 'window' | 'none'; side?: 'left' | 'right'; playTablets?: boolean; size?: { w: number; h: number; dpr?: number } }; /** Optional capture of raw frames (web build, iOS Simulator, Android emulator / device, or your own folder). */ capture?: ShotsCapture; /** A/B variants: other scene orders / copy, rendered into ///... (`shots render --variant b`). */ @@ -574,6 +579,9 @@ export interface ShipConfig { * tablet renders exist under the renders folder, else false. false = `shots render` / `shots check`, `validate` and * `play images` never ask for them; true = missing tablet sets are errors. */ tablets?: boolean; + /** Also render Chromebook screenshots (size key `chromebook`, 1920 x 1080, landscape layout). The Play API has no + * Chromebook image type: add them in the Play Console's main store listing (play images says so). */ + chromebook?: boolean; /** Promo video: a YouTube URL (public or unlisted, ads off, embeddable). Play takes no video upload. Sent by `play listing`. */ video?: string; /** Cloud Storage bucket of the Play Console report exports, e.g. "pubsite_prod_rev_" (Play Console > @@ -626,6 +634,10 @@ export interface ShipConfig { * Optional now, reportedly required from April 2027 for iOS 27.1 SDK builds. Not uploaded while the API has no * display type for them (cli/shots/spec.ts IPHONE_DUO_DISPLAY). */ iphoneDuo?: boolean; + /** Also render, check and upload Mac App Store screenshots (size key `mac`, 2880 x 1800, 16:10; Apple also takes + * 2560 x 1600, 1440 x 900, 1280 x 800). Landscape layout from //landscape/ (shots.landscape). Uploaded + * as APP_DESKTOP to the macOS version: `apple screenshots --platform macos`. */ + mac?: boolean; /** "Header and Search Results" creative assets (`storebound apple creative-assets`, iOS / iPadOS 27+). Files under * //creative/: header.{png,jpg,mov,m4v,mp4} (3840x1646, 21:9), search.{...} (3:2, 1920x1280 to * 3840x2560) or universal.png (5244x2950) for both. `header` / `search` false skip that slot; `universal` is a @@ -1185,6 +1197,8 @@ export function validateConfig(c: unknown): string[] { for (const k of ['copy', 'frames', 'out'] as const) if (!s[k]) e.push(`shots.${k}: missing`); if (s.style !== undefined && s.style !== 'game' && s.style !== 'app') e.push('shots.style: game | app'); if (!s.scenes?.length) e.push('shots.scenes: at least one scene'); + if (s.landscape?.frame !== undefined && s.landscape.frame !== 'window' && s.landscape.frame !== 'none') e.push("shots.landscape.frame: 'window' | 'none'"); + if (s.landscape?.side !== undefined && s.landscape.side !== 'left' && s.landscape.side !== 'right') e.push("shots.landscape.side: 'left' | 'right'"); if (s.feature !== undefined) { if (!s.feature || typeof s.feature.frame !== 'string' || !s.feature.frame) e.push('shots.feature.frame: a frame name'); if (s.feature?.fit !== undefined && s.feature.fit !== 'contain' && s.feature.fit !== 'bleed') e.push("shots.feature.fit: 'contain' | 'bleed'"); diff --git a/cli/lib/embedded.ts b/cli/lib/embedded.ts index ddf1d2f..1a18a42 100644 --- a/cli/lib/embedded.ts +++ b/cli/lib/embedded.ts @@ -38,10 +38,10 @@ export const TEMPLATE_TEXT: Record = { /** The pages shots render / video load (cli/shots/*.html), by file name. */ export const SHOTS_PAGES: Record = { "caption.html": "\n\n\n\n\n\n\n\n\n
\n\n\n\n", - "feature-app.html": "\n\n\n\n\n\n\n\n\n
\n
\n
\n
\n\n\n\n", - "feature.html": "\n\n\n\n\n\n\n\n\n
\n
\n
\n
\n\n\n\n", - "template-app.html": "\n\n\n\n\n\n\n\n\n
\n\n\n\n", - "template.html": "\n\n\n\n\n\n\n\n\n
\n\n\n\n", + "feature-app.html": "\n\n\n\n\n\n\n\n\n
\n
\n
\n
\n\n\n\n", + "feature.html": "\n\n\n\n\n\n\n\n\n
\n
\n
\n
\n\n\n\n", + "template-app.html": "\n\n\n\n\n\n\n\n\n
\n\n\n\n", + "template.html": "\n\n\n\n\n\n\n\n\n
\n\n\n\n", }; /** Play Console's Data safety form export (cli/data/play-data-safety-form.csv). */ diff --git a/cli/lib/validate-rules.ts b/cli/lib/validate-rules.ts index 3c9e93a..491fb2a 100644 --- a/cli/lib/validate-rules.ts +++ b/cli/lib/validate-rules.ts @@ -3,7 +3,7 @@ import { consoleLink, consoleUrl } from './console-links'; import { type FixAction, fixAppleListing, fixPlayListing, fixReviewDetails } from './fix-actions'; -import { iphoneDuoNote } from '../shots/spec'; +import { iphoneDuoNote, macNote } from '../shots/spec'; export type Level = 'blocker' | 'warn' | 'ok'; @@ -70,6 +70,9 @@ export interface AppleSnapshot { requiredDisplayTypes: string[]; /** apple.iphoneDuo (iPhone Duo renders on) and whether the project has a play section, for the Duo note. */ iphoneDuo?: boolean; + /** The app has a macOS App Store version (any state), and apple.mac (Mac screenshots on), for the Mac note. */ + macVersion?: boolean; + mac?: boolean; play?: boolean; today?: Date; reviewDetail: { contactEmail?: string | null; contactPhone?: string | null; contactFirstName?: string | null; contactLastName?: string | null; demoAccountRequired?: boolean; demoAccountName?: string | null; notes?: string | null } | null; @@ -280,6 +283,9 @@ export function appleRules(s: AppleSnapshot): Finding[] { // iPhone Duo: optional until April 2027, so a passing note (never a blocker); a warning after that date const duo = iphoneDuoNote({ apple: true, duo: !!s.iphoneDuo, play: s.play, today: s.today }); if (duo) add(duo.level === 'info' ? 'ok' : 'warn', 'screenshots-duo', duo.msg, 'apple.iphoneDuo: true, then storebound shots render'); + // a macOS version without Mac screenshots: an info note (the macOS version's own checks run with --platform macos) + const mac = macNote({ macVersion: !!s.macVersion, mac: !!s.mac }); + if (mac) add('ok', 'screenshots-mac', mac, 'apple.mac: true, storebound shots render --size mac, apple screenshots --platform macos'); return sortFindings(f); } diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index 70aa50b..9a40eda 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -230,7 +230,7 @@ export const TOOLS: ToolDef[] = [ ...(i.concurrency ? ['--concurrency', String(i.concurrency)] : []), ...(i.mode === 'force' ? ['--force'] : i.mode === 'only-missing' ? ['--only-missing'] : [])] }, { name: 'shots_render', title: 'Render store screenshots', command: ['shots', 'render'], write: true, network: false, idempotent: true, description: 'Store screenshots + Play feature graphic in every size and language from the frames and the copy file (local PNGs, needs Playwright + ffmpeg; slow for many languages). dry_run lists what would be rendered.', - props: { lang, size: { type: 'string', description: 'Comma-separated size keys: ios69, ios65, iphone-medium, iphone-duo-outer, iphone-duo-inner, ipad13, play, tab7, tab10, feature' }, + props: { lang, size: { type: 'string', description: 'Comma-separated size keys: ios69, ios65, iphone-medium, iphone-duo-outer, iphone-duo-inner, ipad13, mac, play, tab7, tab10, chromebook, feature' }, scenes: { type: 'string', description: 'Comma-separated scene ids' }, variant, all_variants: { type: 'boolean', default: false, description: 'Base + every variant' }, concurrency: { type: 'integer', minimum: 1, maximum: 32, description: 'Parallel pages (default min(4, CPU cores / 2))' } }, args: i => [...opt('lang', i.lang), ...opt('size', i.size), ...opt('scenes', i.scenes), ...(i.all_variants === true ? ['--variants'] : opt('variant', i.variant)), diff --git a/cli/play/images.ts b/cli/play/images.ts index 6de73ef..8ee5940 100644 --- a/cli/play/images.ts +++ b/cli/play/images.ts @@ -29,6 +29,12 @@ import { pulledChecksum } from '../lib/art-pull'; import { readPlayCopy } from './listing'; import { variantRoot } from '../shots/lib'; import { resolvedTablets } from '../shots/report'; +import { consoleLink } from '../lib/console-links'; + +/** play.chromebook on: the Chromebook renders (chromebook/NN.png) are not uploaded (the Play API has no Chromebook + * image type); the message names the console page. */ +export const chromebookSkip = (on: boolean | undefined): string | null => on + ? `chromebook: not uploaded (the Play Developer API has no Chromebook screenshot type); add //chromebook/*.png in ${consoleLink('play.store-listing', '> Chromebook screenshots')}` : null; export const PLAY_IMAGE_DIRS = { phoneScreenshots: 'play', sevenInchScreenshots: 'tab7', tenInchScreenshots: 'tab10', tvScreenshots: 'tv', wearScreenshots: 'wear' } as const; export const PLAY_TABLET_TYPES: readonly string[] = ['sevenInchScreenshots', 'tenInchScreenshots']; @@ -125,6 +131,8 @@ export async function run(ctx: Ctx): Promise { const src = variantRoot(resolve(ctx.args.get('src') ?? config.renders ?? config.shots?.out ?? 'store/renders'), ctx.args.get('variant'), config.shots?.variants); if (ctx.args.get('variant')) log('play', `variant ${ctx.args.get('variant')}: ${src}`); const icon = resolve(config.play?.icon ?? join(config.icons?.out ?? 'store/icons', 'play-512.png')); + const cbSkip = chromebookSkip(config.play?.chromebook); + if (cbSkip) log('play', cbSkip); const langOf = byPlayCode(config.languages); // the languages `play listing` pushes: a draft or untranslated section has no Play listing yet (unless --include-drafts) const drafts = draftSections(readFileSync(resolve(config.play?.listing ?? 'store/listing.md'), 'utf8'), 'play'); diff --git a/cli/shots/feature-app.html b/cli/shots/feature-app.html index cf9e210..8a065f5 100644 --- a/cli/shots/feature-app.html +++ b/cli/shots/feature-app.html @@ -53,6 +53,8 @@ await Promise.all([...document.images].map(i => i.decode().catch(() => {}))); // read by `shots render` -> report.json -> shots check: the phone's rotated outline must stay inside the canvas document.body.dataset.devices = JSON.stringify([...c.querySelectorAll('.tel')].map(t => { const r = t.getBoundingClientRect(); return { x: r.x, y: r.y, w: r.width, h: r.height }; })); if (D?.fit === 'bleed') document.body.dataset.bleed = '1'; +// logo / name box for the safe-margin rule (7 % of the width left / right, 5 % of the height at the top) +document.body.dataset.boxes = JSON.stringify([...c.querySelectorAll('.logo, .name')].map(e => { const r = e.getBoundingClientRect(); return { el: e.matches('.logo') ? 'logo' : 'title', x: r.x, y: r.y, w: r.width, h: r.height }; })); document.body.dataset.ready = '1'; diff --git a/cli/shots/feature.html b/cli/shots/feature.html index 0b51ac2..792cd3b 100644 --- a/cli/shots/feature.html +++ b/cli/shots/feature.html @@ -15,9 +15,9 @@ .glow { position: absolute; left: 360px; top: 250px; width: 900px; height: 700px; transform: translate(-50%, -50%); z-index: -3; background: radial-gradient(closest-side, var(--glow), transparent); } .vign { position: absolute; inset: 0; z-index: -2; background: radial-gradient(90% 90% at 45% 50%, transparent 60%, rgba(0,0,0,.28) 100%); } - .logo { position: absolute; left: 360px; top: 252px; width: 600px; transform: translate(-50%, -50%) rotate(-3deg); z-index: 5; + .logo { position: absolute; left: 360px; top: 252px; width: 540px; max-height: 400px; object-fit: contain; transform: translate(-50%, -50%) rotate(-3deg); z-index: 5; filter: drop-shadow(0 14px 22px rgba(0,0,0,.4)); } - .name { position: absolute; left: 360px; top: 250px; transform: translate(-50%, -50%) rotate(-3deg); z-index: 5; width: 640px; text-align: center; + .name { position: absolute; left: 360px; top: 250px; transform: translate(-50%, -50%) rotate(-3deg); z-index: 5; width: 540px; text-align: center; font-family: var(--tf); font-size: 104px; line-height: .95; color: #fff; -webkit-text-stroke: 9px var(--ink); paint-order: stroke fill; filter: drop-shadow(0 8px 0 var(--ink)) drop-shadow(0 14px 22px rgba(0,0,0,.35)); } .tel { position: absolute; left: 748px; top: 36px; width: 232px; aspect-ratio: var(--ar); transform: rotate(7deg); z-index: 3; @@ -64,6 +64,8 @@ await Promise.all([...document.images].map(i => i.decode().catch(() => {}))); // read by `shots render` -> report.json -> shots check: the phone's rotated outline must stay inside the canvas document.body.dataset.devices = JSON.stringify([...c.querySelectorAll('.tel')].map(t => { const r = t.getBoundingClientRect(); return { x: r.x, y: r.y, w: r.width, h: r.height }; })); if (D?.fit === 'bleed') document.body.dataset.bleed = '1'; +// logo / name box for the safe-margin rule (7 % of the width left / right, 5 % of the height at the top) +document.body.dataset.boxes = JSON.stringify([...c.querySelectorAll('.logo, .name')].map(e => { const r = e.getBoundingClientRect(); return { el: e.matches('.logo') ? 'logo' : 'title', x: r.x, y: r.y, w: r.width, h: r.height }; })); document.body.dataset.ready = '1'; diff --git a/cli/shots/lib.ts b/cli/shots/lib.ts index a173e0c..0e4abfd 100644 --- a/cli/shots/lib.ts +++ b/cli/shots/lib.ts @@ -6,7 +6,7 @@ import type { Palette, ShipConfig, ShotScene, ShotsConfig } from '../lib/config' * Dynamic Island, medium display (APP_IPHONE_61, only with apple.iphoneMedium), ipad13 = 13" iPad * (APP_IPAD_PRO_3GEN_129, only for apps that run on iPad), play = Play phone 9:16, tab7 / tab10 = Play 7" / 10" * tablets (tablet frames), feature = Play feature graphic. Rules per size: spec.ts. */ -export const SIZES: Record = { +export const SIZES: Record = { ios69: { w: 1320, h: 2868 }, ios65: { w: 1284, h: 2778 }, 'iphone-medium': { w: 1206, h: 2622 }, @@ -14,12 +14,59 @@ export const SIZES: Record//landscape/ + mac: { w: 2880, h: 1800, device: 'landscape' }, play: { w: 1080, h: 1920 }, tab7: { w: 1080, h: 1920, device: 'tablet' }, tab10: { w: 1440, h: 2560, device: 'tablet' }, + // Play Chromebook screenshots (only with play.chromebook): 16:9 landscape; the Play API has no Chromebook image type, + // so they stay in the renders folder for the Play Console (play images says so) + chromebook: { w: 1920, h: 1080, device: 'landscape' }, feature: { w: 1024, h: 500, feature: true }, }; +/** Landscape renders of the Play tablet slots (shots.landscape.playTablets): Play takes any 320-3840 px size up to 2:1. */ +export const PLAY_TABLET_LANDSCAPE: Record = { tab7: { w: 1920, h: 1080 }, tab10: { w: 2560, h: 1440 } }; + +/** Pixel size and layout of one size key for a project: the landscape layout for mac / chromebook, and for the Play + * tablet slots with shots.landscape.playTablets. frame = the device drawn around a landscape frame ('window' = a Mac + * window, 'none' = the bare frame with rounded corners); default window on Mac, none on Play. Pure. */ +export function renderDims(size: string, shots: Pick | undefined): { w: number; h: number; landscape: boolean; frame: 'window' | 'none' } { + const s = SIZES[size]!; + const tabLand = !!shots?.landscape?.playTablets && !!PLAY_TABLET_LANDSCAPE[size]; + const landscape = s.device === 'landscape' || tabLand; + const d = tabLand ? PLAY_TABLET_LANDSCAPE[size]! : s; + const frame = shots?.landscape?.frame ?? (size === 'mac' ? 'window' : 'none'); + return { w: d.w, h: d.h, landscape, frame }; +} + +/** Safe margins every template keeps around its text and logo (fractions of the image), and the minimum `shots check` + * accepts (a little under the target, so rounding never fails a render). */ +export const SAFE_MARGIN = { x: 0.07, top: 0.05 } as const; +export const SAFE_MARGIN_MIN = { x: 0.06, top: 0.04 } as const; +export interface TextBox { el: string; x: number; y: number; w: number; h: number } + +/** Text / logo boxes (from the page's own layout, report.json `boxes`) closer to the left, right or top edge than + * SAFE_MARGIN_MIN. Pure. */ +export function marginViolations(boxes: TextBox[], W: number, H: number): string[] { + const mx = W * SAFE_MARGIN_MIN.x, mt = H * SAFE_MARGIN_MIN.top, out: string[] = []; + for (const b of boxes) { + const sides: string[] = []; + if (b.x < mx - 0.5) sides.push(`left ${Math.round(b.x)} px`); + if (W - (b.x + b.w) < mx - 0.5) sides.push(`right ${Math.round(W - b.x - b.w)} px`); + if (b.y < mt - 0.5) sides.push(`top ${Math.round(b.y)} px`); + if (sides.length) out.push(`${b.el} is too close to the edge (${sides.join(', ')}; minimum ${Math.round(mx)} px left / right, ${Math.round(mt)} px top)`); + } + return out; +} + +/** Timeout for the contact sheet page: it decodes every image of the language, so it scales with their count and the + * sizes (big Mac / iPad tiles), times the machine's load factor (max(1-min, 5-min load) / cores, 1..5). Never a + * fixed 30 s. Pure. */ +export function sheetTimeoutMs(images: number, sizes: number, load = 1): number { + return Math.round((30_000 + images * 2_000 + sizes * 5_000) * Math.min(5, Math.max(1, load))); +} + export const PALETTES: Record = { fire: { bg: ['#ff3d2e', '#ff7a1a', '#ffc43a'], glow: 'rgba(255,240,150,.95)', ink: '#6e1300', shadow: 'rgba(120,10,0,.45)' }, violet: { bg: ['#2b1676', '#6a2fe0', '#ff5fb8'], glow: 'rgba(255,170,240,.75)', ink: '#22095e', shadow: 'rgba(30,0,80,.55)' }, @@ -123,7 +170,8 @@ export function frameDims(config: Pick): Record<' export const PLAY_TABLET_SIZES: readonly string[] = ['tab7', 'tab10']; /** Size keys this project renders by default: Apple sizes only with an apple section (iPad only with apple.ipad, the - * 6.3" iPhone only with apple.iphoneMedium, the iPhone Duo sizes only with apple.iphoneDuo), + * 6.3" iPhone only with apple.iphoneMedium, the iPhone Duo sizes only with apple.iphoneDuo, mac only with apple.mac, + * chromebook only with play.chromebook), * Play sizes only with a play section (both when neither is configured); the Play tablet sizes only when `tablets` * (resolved play.tablets, see resolvedTablets in report.ts; unset here = play.tablets ?? true). */ export function defaultSizes(config: Pick, tablets?: boolean): string[] { @@ -131,6 +179,8 @@ export function defaultSizes(config: Pick, tablets const tabs = tablets ?? config.play?.tablets ?? true; return Object.keys(SIZES).filter(k => (k === 'ipad13' ? apple && !!config.apple?.ipad : k === 'iphone-medium' ? apple && !!config.apple?.iphoneMedium : k.startsWith('iphone-duo') ? apple && !!config.apple?.iphoneDuo + : k === 'mac' ? apple && !!config.apple?.mac + : k === 'chromebook' ? play && !!config.play?.chromebook : k.startsWith('ios') ? apple : PLAY_TABLET_SIZES.includes(k) ? play && tabs : play)); } @@ -173,10 +223,10 @@ export interface SheetTile { file: string; x: number; y: number; w: number; h: n /** Contact sheet layout: one block per size (its scenes side by side, all at the same height; the feature graphic at * half height), blocks packed onto shelves up to `maxW` wide so a project with one or two scenes gets a compact grid * instead of a tall strip. Pure. */ -export function sheetLayout(rows: { size: string; files: string[] }[], o: { h?: number; gap?: number; maxW?: number } = {}): { w: number; h: number; tiles: SheetTile[] } { +export function sheetLayout(rows: { size: string; files: string[]; dims?: { w: number; h: number } }[], o: { h?: number; gap?: number; maxW?: number } = {}): { w: number; h: number; tiles: SheetTile[] } { const H0 = o.h ?? 900, gap = o.gap ?? 24; const blocks = rows.filter(r => r.files.length).map(r => { - const d = SIZES[r.size]!, h = d.feature ? Math.round(H0 / 2) : H0, w = Math.round(h * d.w / d.h); + const d = r.dims ?? SIZES[r.size]!, h = SIZES[r.size]!.feature || d.w > d.h ? Math.round(H0 / 2) : H0, w = Math.round(h * d.w / d.h); return { r, h, tw: w, w: r.files.length * w + (r.files.length - 1) * gap }; }); const maxW = Math.max(o.maxW ?? 3600, ...blocks.map(b => b.w)); diff --git a/cli/shots/render.ts b/cli/shots/render.ts index a0eea9d..3ab7876 100644 --- a/cli/shots/render.ts +++ b/cli/shots/render.ts @@ -25,10 +25,18 @@ import { done, log, warn } from '../lib/log'; import { closeBrowser, launch } from './browser'; import { defaultConcurrency, pool, progressLine } from './capture-web'; import { shotsStyle } from '../lib/config'; -import { type CopyFile, type DeviceBox, SIZES, featureLayout, copyText, defaultSizes, frameDims, mergeCopy, palette, renderDir, scriptFont, sheetLayout, validateCopy, variantScenes } from './lib'; +import { type CopyFile, type DeviceBox, type TextBox, SIZES, renderDims, sheetTimeoutMs, featureLayout, copyText, defaultSizes, frameDims, mergeCopy, palette, renderDir, scriptFont, sheetLayout, validateCopy, variantScenes } from './lib'; import { faceFilePath, fontsRoute, resolveShotFonts, staleLocalFonts } from './local-fonts'; import { type RenderReport, mergeReport, readReport, resolvedTablets } from './report'; import * as rt from '../lib/rt'; +import { cpus, loadavg } from 'node:os'; + +/** max(1-min, 5-min load) / cores, 1..5 (the same factor tests/helpers/load.ts uses; STOREBOUND_LOAD_FACTOR overrides). */ +export function loadFactor(env = process.env, load = loadavg(), cores = cpus().length): number { + const forced = Number(env.STOREBOUND_LOAD_FACTOR); + if (Number.isFinite(forced) && forced > 0) return Math.min(5, Math.max(1, forced)); + return Math.min(5, Math.max(1, Math.max(load[0] ?? 0, load[1] ?? 0) / Math.max(1, cores))); +} const TYPES: Record = { html: 'text/html; charset=utf-8', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', css: 'text/css', svg: 'image/svg+xml' }; @@ -124,7 +132,9 @@ export async function run(ctx: Ctx): Promise { const lang = url.searchParams.get('lang') ?? ''; const { scenes, copy } = jobs.get(url.searchParams.get('v') ?? '') ?? jobs.values().next().value!; const st = stacks(lang, copy); - const base = { style, phone, tablet, rtl: rtl.get(lang), logo: !!shots.logo, appName: config.app.name, + const ls = shots.landscape?.size; + const landscape = { w: ls?.w ?? 1440, h: ls?.h ?? 900, bar: 0 }; + const base = { style, phone, tablet, landscape, side: shots.landscape?.side ?? 'left', rtl: rtl.get(lang), logo: !!shots.logo, appName: config.app.name, fonts: { ...fonts, script: st.script, titleStack: st.title, bodyStack: st.body } }; if (url.searchParams.has('feature')) return Response.json({ ...base, frame: shots.feature?.frame ?? scenes[0]!.frames[0]!.src, @@ -162,22 +172,30 @@ export async function run(ctx: Ctx): Promise { const started = Date.now(); const report: RenderReport = {}; - async function shoot(p: { page: any; errs: string[] }, url: string, w: number, h: number, out: string): Promise { // eslint-disable-line @typescript-eslint/no-explicit-any + async function shoot(p: { page: any; errs: string[] }, url: string, w: number, h: number, out: string, timeout = 30000, what = ''): Promise { // eslint-disable-line @typescript-eslint/no-explicit-any const { page, errs } = p; + const t0 = Date.now(); + // heartbeat for long waits (the contact sheet decodes every image): one line every 15 s, the budget on timeout + const beat = timeout > 30000 ? setInterval(() => log('shots', `${what || relative(root, out)}: still loading (${Math.round((Date.now() - t0) / 1000)} s of ${Math.round(timeout / 1000)} s)`), 15000) : null; + try { errs.length = 0; mkdirSync(join(out, '..'), { recursive: true }); await page.setViewportSize({ width: w, height: h }); await page.goto(url, { waitUntil: 'load' }); - await page.waitForFunction("document.body.dataset.ready === '1'", null, { timeout: 30000 }); + await page.waitForFunction("document.body.dataset.ready === '1'", null, { timeout }).catch((e: Error) => { + throw new Error(`${what || relative(root, out)}: not ready after ${Math.round((Date.now() - t0) / 1000)} s (budget ${Math.round(timeout / 1000)} s; ${errs.length ? errs.join(' | ') : 'no page errors'}): ${e.message.split('\n')[0]}`); + }); + } finally { if (beat) clearInterval(beat); } await page.waitForTimeout(200); const tmp = out + '.tmp.png'; const overflow = JSON.parse((await page.evaluate('document.body.dataset.overflow')) ?? '[]') as string[]; const devices = JSON.parse((await page.evaluate('document.body.dataset.devices')) ?? '[]') as DeviceBox[]; const bleed = (await page.evaluate('document.body.dataset.bleed')) === '1'; + const boxes = JSON.parse((await page.evaluate('document.body.dataset.boxes')) ?? '[]') as TextBox[]; if (!out.endsWith('sheet.png')) { const measured = await measureFonts(page, Object.keys(faces)); const usage = fontUsage(measured, faces); - report[relative(outDir, out)] = { overflow, devices, ...(bleed ? { bleed } : {}), missing: errs.filter(e => e.startsWith('404')), fonts: usage }; + report[relative(outDir, out)] = { overflow, devices, ...(bleed ? { bleed } : {}), ...(boxes.length ? { boxes } : {}), missing: errs.filter(e => e.startsWith('404')), fonts: usage }; for (const f of usage.fallback) warn('shots', `${relative(root, out)}: ${f.el} ${[...f.chars].join(' ')} drawn with ${f.family} (automatic fallback)`); for (const f of usage.missing) warn('shots', `${relative(root, out)}: ${f.el} ${[...f.chars].join(' ')} drawn with a system font`); } @@ -194,14 +212,14 @@ export async function run(ctx: Ctx): Promise { // every image first (in parallel), then one contact sheet per language from its finished images const items: { url: string; w: number; h: number; out: string }[] = []; - const sheets: { dir: string; rows: { size: string; files: string[] }[] }[] = []; + const sheets: { dir: string; rows: { size: string; files: string[]; dims?: { w: number; h: number } }[] }[] = []; for (const [v, job] of jobs) for (const lang of langs) { const sceneIds = a.list('scenes').length ? a.list('scenes') : job.scenes.map(s => s.id); const vq = v ? `&v=${encodeURIComponent(v)}` : ''; const dir = renderDir(outDir, lang, v || undefined); - const rows: { size: string; files: string[] }[] = []; + const rows: { size: string; files: string[]; dims?: { w: number; h: number } }[] = []; for (const size of sizes) { - const s = SIZES[size]!; + const s = SIZES[size]!, d = renderDims(size, shots); if (s.feature) { const f = join(dir, 'feature', '1024x500.png'); items.push({ url: `${base}/${style === 'app' ? 'feature-app' : 'feature'}.html?lang=${encodeURIComponent(lang)}${vq}`, w: s.w, h: s.h, out: f }); @@ -211,10 +229,11 @@ export async function run(ctx: Ctx): Promise { const files: string[] = []; for (const [i, id] of sceneIds.entries()) { const f = join(dir, size, `${String(i + 1).padStart(2, '0')}.png`); - items.push({ url: `${base}/${style === 'app' ? 'template-app' : 'template'}.html?s=${encodeURIComponent(id)}&w=${s.w}&h=${s.h}&lang=${encodeURIComponent(lang)}${s.device ? '&device=tablet' : ''}${size === 'tab7' || size === 'tab10' ? '&style=android' : ''}${vq}`, w: s.w, h: s.h, out: f }); + const dev = d.landscape ? `&device=landscape&frame=${d.frame}` : s.device ? '&device=tablet' : ''; + items.push({ url: `${base}/${style === 'app' ? 'template-app' : 'template'}.html?s=${encodeURIComponent(id)}&w=${d.w}&h=${d.h}&lang=${encodeURIComponent(lang)}${dev}${size === 'tab7' || size === 'tab10' ? '&style=android' : ''}${vq}`, w: d.w, h: d.h, out: f }); files.push(f); } - rows.push({ size, files }); + rows.push({ size, files, dims: { w: d.w, h: d.h } }); } if (!a.has('no-sheet') && rows.length) sheets.push({ dir, rows }); } @@ -235,7 +254,8 @@ export async function run(ctx: Ctx): Promise { const sheet = join(dir, '.sheet.html'); writeFileSync(sheet, `${imgs} `); - await withPage(p => shoot(p, `${base}/out/${relative(outDir, sheet)}`, lay.w, lay.h, join(dir, 'sheet.png'))); + const ms = sheetTimeoutMs(lay.tiles.length, rows.length, loadFactor()); + await withPage(p => shoot(p, `${base}/out/${relative(outDir, sheet)}`, lay.w, lay.h, join(dir, 'sheet.png'), ms, `${relative(root, join(dir, 'sheet.png'))} (${lay.tiles.length} images, ${rows.length} sizes)`)); rmSync(sheet, { force: true }); }); } finally { diff --git a/cli/shots/report.ts b/cli/shots/report.ts index d5e4baf..4cc9fbf 100644 --- a/cli/shots/report.ts +++ b/cli/shots/report.ts @@ -3,7 +3,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; import { join } from 'node:path'; import { spawnSync } from 'node:child_process'; -import { boxOutside, type DeviceBox, PLAY_TABLET_SIZES, SIZES } from './lib'; +import { boxOutside, type DeviceBox, marginViolations, PLAY_TABLET_SIZES, SIZES, type TextBox } from './lib'; import { fontIssues, type FontUsage } from './glyphs'; import { pulledEntry, readPulled } from '../lib/art-pull'; import { checkCount, checkImage, checkVideo, type ImageInfo, imageInfo, type Issue, IMAGE_SPECS, parseProbe, PREVIEW_RULES, type ProbeInfo, VIDEO_TARGETS } from './spec'; @@ -12,7 +12,14 @@ import { checkCount, checkImage, checkVideo, type ImageInfo, imageInfo, type Iss * fonts = which face drew the text (glyphs.ts FontUsage): automatic fallbacks and system-font glyphs are errors. */ export type RenderReport = Record; + devices?: DeviceBox[]; bleed?: boolean; + /** Text and logo boxes in image px (from the page's layout), for the safe-margin rule (lib.ts marginViolations). */ + boxes?: TextBox[] }>; + +/** Text or logo closer to an edge than the safe margin: an error (stores crop and round corners; it reads cramped). */ +export function marginIssues(entry: RenderReport[string] | undefined, W: number, H: number): Issue[] { + return marginViolations(entry?.boxes ?? [], W, H).map(msg => ({ level: 'error' as const, code: 'margin' as const, msg: `${msg}: render again with the current templates, or shorten the copy / shrink the logo` })); +} /** Device frames that leave the image. Feature graphic: an error unless shots.feature.fit is 'bleed' (Play shows the * phone cut off). Screenshots: the templates let the phone run off the bottom by design, so only top / left / right @@ -80,6 +87,7 @@ export function scanRenders(dir: string, o: { langs: string[]; variants?: string for (const msg of entry?.overflow ?? []) issues.push({ level: 'warn', code: 'overflow', msg }); issues.push(...fontIssues(entry?.fonts)); issues.push(...deviceIssues(entry, size, info.w, info.h)); + issues.push(...marginIssues(entry, info.w, info.h)); if (entry && !entry.fonts) issues.push({ level: 'warn', code: 'fonts', msg: 'font usage not recorded (rendered by an older storebound): run shots fonts + shots render again so missing glyphs are caught' }); out.images.push({ rel, lang, variant, size, file, info, issues }); } @@ -114,13 +122,13 @@ export function ffprobe(file: string): ProbeInfo | null { /** Which sets the stores require for this config (missing ones are errors, others only checked when present). With a * language id: Apple sets only when that language has an App Store locale, Play sets only when it has a Play code. * Play tablets (tab7, tab10) only when `tablets` (resolved play.tablets; unset here = play.tablets === true). */ -export function requiredSets(c: { apple?: { ipad?: boolean; iphoneMedium?: boolean } | undefined; play?: unknown; languages?: { id: string; apple?: string; play?: string | string[] }[] }, +export function requiredSets(c: { apple?: { ipad?: boolean; iphoneMedium?: boolean; mac?: boolean } | undefined; play?: unknown; languages?: { id: string; apple?: string; play?: string | string[] }[] }, lang?: string, tablets?: boolean): Record { const l = lang === undefined ? undefined : c.languages?.find(x => x.id === lang); const apple = !!c.apple && (!l || !!l.apple); const play = !!c.play && (!l || (Array.isArray(l.play) ? l.play.length > 0 : !!l.play)); const tabs = play && (tablets ?? (c.play as { tablets?: boolean } | undefined)?.tablets === true); - return { ios69: apple, ...(c.apple?.iphoneMedium ? { 'iphone-medium': apple } : {}), ipad13: apple && !!c.apple?.ipad, play, feature: play, + return { ios69: apple, ...(c.apple?.iphoneMedium ? { 'iphone-medium': apple } : {}), ipad13: apple && !!c.apple?.ipad, ...(c.apple?.mac ? { mac: apple } : {}), play, feature: play, ...(tabs ? { tab7: true, tab10: true } : {}) }; } diff --git a/cli/shots/spec.ts b/cli/shots/spec.ts index 89813d9..bbb21be 100644 --- a/cli/shots/spec.ts +++ b/cli/shots/spec.ts @@ -29,6 +29,8 @@ export interface ImageSpec { /** Max bytes per file (null = the store does not publish one). */ maxBytes: number | null; alpha: false; + /** Only the listed sizes as given (Mac: no portrait). */ + landscapeOnly?: true; } const MB = 1024 * 1024; @@ -48,10 +50,14 @@ export const IMAGE_SPECS: Record = { // optional (apple.iphoneDuo). `type` is not an ASC display type: see IPHONE_DUO_DISPLAY. No app preview sizes yet. 'iphone-duo-outer': { store: 'apple', type: 'IPHONE_DUO_OUTER', label: 'iPhone Duo (outer display)', sizes: [[1398, 2034]], min: 1, max: 10, maxBytes: null, alpha: false }, 'iphone-duo-inner': { store: 'apple', type: 'IPHONE_DUO_INNER', label: 'iPhone Duo (inner display)', sizes: [[2007, 2853]], min: 1, max: 10, maxBytes: null, alpha: false }, + // Mac (Screenshot specifications, checked 2026-10-20): 16:10 only, one of these four, landscape, 1-10, no alpha. + mac: { store: 'apple', type: 'APP_DESKTOP', label: 'Mac App Store', sizes: [[2880, 1800], [2560, 1600], [1440, 900], [1280, 800]], min: 1, max: 10, maxBytes: null, alpha: false, landscapeOnly: true }, play: { store: 'play', type: 'phoneScreenshots', label: 'Play phone', sizes: [[1080, 1920]], min: 2, max: 8, maxBytes: 8 * MB, alpha: false }, tab7: { store: 'play', type: 'sevenInchScreenshots', label: 'Play 7" tablet', sizes: [[1080, 1920]], min: 0, max: 8, maxBytes: 8 * MB, alpha: false }, tab10: { store: 'play', type: 'tenInchScreenshots', label: 'Play 10" tablet', sizes: [[1440, 2560]], min: 0, max: 8, maxBytes: 8 * MB, alpha: false }, // Play Console states 1024x500, JPEG or 24-bit PNG (no alpha); the upload dialog caps it at 15 MB. + // Chromebook (Play Console listing): 16:9 or 9:16, 1080-7680 px per side; no API image type (console only) + chromebook: { store: 'play', type: 'chromebookScreenshots', label: 'Play Chromebook', sizes: [[1920, 1080]], min: 0, max: 8, maxBytes: 8 * MB, alpha: false }, feature: { store: 'play', type: 'featureGraphic', label: 'Play feature graphic', sizes: [[1024, 500]], min: 1, max: 1, maxBytes: 15 * MB, alpha: false }, }; @@ -59,7 +65,7 @@ export const IMAGE_SPECS: Record = { * Connect API 4.5.1 (spec re-checked 2026-10-20: the published zip is still the 2026-10-06 one, same sha256) has no Duo value (only AppAssetLibraryDisplayClass lists IPHONE_DUO). * When Apple adds it: regenerate (bun tools/gen-api.ts) and put the exact enum names here; uploads then include them. */ export const IPHONE_DUO_DISPLAY: Record = { 'iphone-duo-outer': null, 'iphone-duo-inner': null }; -export const IPHONE_DUO_NOT_IN_API = 'the App Store Connect console takes iPhone Duo screenshots, the API does not yet; storebound keeps them in store/renders'; +export const IPHONE_DUO_NOT_IN_API = 'not uploaded: the App Store Connect API has no iPhone Duo display type yet (the console takes them); the renders stay in store/renders'; /** Reportedly required from this date for apps built with the iOS 27.1 SDK or later. */ export const IPHONE_DUO_REQUIRED_FROM = '2027-04-01'; const PLAY_FOLDABLE = 'Google Play has no foldable slot: foldables show the 7" / 10" tablet screenshots (tab7, tab10, play.tablets)'; @@ -72,6 +78,11 @@ export function iphoneDuoNote(o: { apple: boolean; duo: boolean; play?: boolean; return { level: late ? 'warn' : 'info', msg: `no iPhone Duo screenshots (outer 1398x2034, inner 2007x2853; apple.iphoneDuo): optional now, required from April 2027 for iOS 27.1 SDK builds; the App Store Connect console takes Duo screenshots and previews, the API does not yet (apple screenshots skips them with the console link)${o.play ? `. ${PLAY_FOLDABLE}` : ''}` }; } +/** validate / check note for an app with a macOS version but no Mac screenshots (apple.mac off or no mac renders). */ +export function macNote(o: { macVersion: boolean; mac: boolean }): string | null { + return o.macVersion && !o.mac ? 'the app has a macOS version but no Mac screenshots: set apple.mac: true, add landscape frames in //landscape/, storebound shots render, then apple screenshots --platform macos (APP_DESKTOP, 2880x1800 / 2560x1600 / 1440x900 / 1280x800)' : null; +} + /** Play screenshots in general (any size the store accepts): 320..3840 px per side, long side at most 2x the short. */ export function playScreenshotOk(w: number, h: number): boolean { const lo = Math.min(w, h), hi = Math.max(w, h); @@ -111,7 +122,7 @@ export function imageInfo(b: Uint8Array): ImageInfo { } export type IssueLevel = 'error' | 'warn'; -export interface Issue { level: IssueLevel; code: 'size' | 'alpha' | 'format' | 'bytes' | 'count' | 'overflow' | 'video' | 'font-fallback' | 'glyph-missing' | 'device-crop' | 'fonts'; msg: string } +export interface Issue { level: IssueLevel; code: 'size' | 'alpha' | 'format' | 'bytes' | 'count' | 'overflow' | 'video' | 'font-fallback' | 'glyph-missing' | 'device-crop' | 'fonts' | 'margin'; msg: string } /** Problems with one image for a size key. */ export function checkImage(info: ImageInfo, sizeKey: string): Issue[] { @@ -121,11 +132,11 @@ export function checkImage(info: ImageInfo, sizeKey: string): Issue[] { if (info.format === 'unknown') return [{ level: 'error', code: 'format', msg: 'not a PNG or JPEG' }]; // Apple: one of the listed sizes, portrait or landscape. Play screenshots: any size Play accepts (the listed one is // what `shots render` writes). Feature graphic: exactly 1024 x 500. - const exact = s.sizes.some(([w, h]) => (w === info.w && h === info.h) || (s.store === 'apple' && w === info.h && h === info.w)); + const exact = s.sizes.some(([w, h]) => (w === info.w && h === info.h) || (s.store === 'apple' && !s.landscapeOnly && w === info.h && h === info.w)); const playShot = s.store === 'play' && s.type !== 'featureGraphic'; if (!exact && !(playShot && playScreenshotOk(info.w, info.h))) { const want = playShot ? `${s.sizes.map(([w, h]) => `${w}x${h}`).join(' or ')} (any 320-3840 px per side, long side at most 2x the short)` - : s.sizes.map(([w, h]) => `${w}x${h}`).join(' or ') + (s.store === 'apple' ? ' (or landscape)' : ''); + : s.sizes.map(([w, h]) => `${w}x${h}`).join(' or ') + (s.store === 'apple' && !s.landscapeOnly ? ' (or landscape)' : ''); out.push({ level: 'error', code: 'size', msg: `${info.w}x${info.h}, ${s.label} wants ${want}` }); } if (info.alpha) out.push({ level: 'error', code: 'alpha', msg: 'has an alpha channel / transparency (both stores reject it): re-render or flatten to RGB' }); diff --git a/cli/shots/template-app.html b/cli/shots/template-app.html index 30accd0..b72dac3 100644 --- a/cli/shots/template-app.html +++ b/cli/shots/template-app.html @@ -10,6 +10,9 @@ sunburst, no sparkles; badges only when the copy has them, drawn as quiet chips. Same /job.json as template.html (palette: bg = gradient stops, ink = headline, glow = accent, shadow = device shadow). Layout: everything is in u = W / 100; the text block is measured first, then the device fills the room below it. + device=landscape: u = H / 100, copy column on one side, the landscape frame in a Mac window (frame=window) or bare + (frame=none) on the other (as template.html). Safe margins: 7 % of the width left / right, 5 % of the height at the + top; text and logo boxes go to body.dataset.boxes for shots check. --> ', `${o.css}`); + const job = { style, phone: DEFAULT_PHONE, tablet: DEFAULT_TABLET, landscape: { w: 1440, h: 900, bar: 0 }, side: 'left', logo: !!o.hero, appName: 'Demo', + fonts: { title: 'X', body: 'Y' }, number: 1, scene: { id: 'a', hero: !!o.hero, frames: [{ src: 'a.png' }] }, + palette: { bg: ['#123456', '#345678', '#567890'], glow: '#ffffff', ink: '#000000', shadow: 'rgba(0,0,0,.4)' }, + copy: { eyebrow: 'Daily puzzles', title: o.title ?? ['Match three', 'Win big'], sub: 'Hundreds of levels, no wifi needed.' } }; + await page.route('http://t.test/**', (r: { request(): { url(): string }; fulfill(o: unknown): Promise }) => { + const u = new URL(r.request().url()); + if (u.pathname.endsWith('.html')) return r.fulfill({ contentType: 'text/html', body: html }); + if (u.pathname === '/job.json') return r.fulfill({ contentType: 'application/json', body: JSON.stringify(job) }); + if (u.pathname.startsWith('/frames/') || u.pathname === '/logo') return r.fulfill({ contentType: 'image/png', body: PNG }); + return r.fulfill({ contentType: 'text/css', body: '' }); + }); + const dev = o.landscape ? `&device=landscape&frame=${o.frame ?? 'window'}` : ''; + await page.goto(`http://t.test/t.html?s=a&w=${w}&h=${h}&lang=en${dev}`); + await page.waitForFunction("document.body.dataset.ready === '1'", null, { timeout: scaled(15000) }); + const read = async (k: string) => JSON.parse((await page.evaluate(`document.body.dataset.${k}`)) ?? '[]'); + return { boxes: await read('boxes') as TextBox[], devices: await read('devices') as { x: number; y: number; w: number; h: number }[], + frameUrl: await page.evaluate("document.querySelector('.lwin img, .tel img.app')?.getAttribute('src') ?? ''") as string, + titlebar: await page.evaluate("!!document.querySelector('.lwin:not(.bare) .tb')") as boolean }; + } finally { await page.close(); } +} + +describe.skipIf(!browser)('landscape layout', () => { + for (const style of ['game', 'app'] as const) for (const [size, frame] of [['mac', 'window'], ['chromebook', 'none'], ['tab10', 'none']] as const) test(`${style} ${size} (${frame})`, async () => { + const d = renderDims(size, { landscape: { playTablets: true } }); + const r = await render(style, d.w, d.h, { landscape: true, frame }); + expect(r.frameUrl).toContain('/landscape/'); + expect(r.titlebar).toBe(frame === 'window'); + expect(r.devices).toHaveLength(1); + expect(boxOutside(r.devices[0]!, d.w, d.h)).toEqual([]); + // copy on the left, device on the right + expect(Math.max(...r.boxes.map(b => b.x + b.w))).toBeLessThan(r.devices[0]!.x); + expect(r.boxes.length).toBeGreaterThanOrEqual(3); + expect(marginViolations(r.boxes, d.w, d.h)).toEqual([]); + }, scaled(30_000)); +}); + +describe.skipIf(!browser)('safe margins on the portrait templates', () => { + for (const style of ['game', 'app'] as const) for (const [w, h] of [[1320, 2868], [1080, 1920], [2064, 2752]] as const) test(`${style} ${w}x${h}, hero with logo and a scene`, async () => { + for (const hero of [true, false]) { + const r = await render(style, w, h, { hero, title: ['Wonderful long words', 'Everywhere'] }); + expect(r.boxes.length).toBeGreaterThan(0); + if (hero) expect(r.boxes.some(b => b.el === 'logo')).toBe(true); + expect(marginViolations(r.boxes, w, h)).toEqual([]); + } + }, scaled(30_000)); + test('a fixture with the margins taken away fails', async () => { + const r = await render('game', 1080, 1920, { hero: true, css: '.top { padding: 0 !important; top: 0 !important } .logo { width: 100% !important }' }); + const v = marginViolations(r.boxes, 1080, 1920); + expect(v.some(m => m.startsWith('logo is too close to the edge (left 0 px, right 0 px, top 0 px'))).toBe(true); + }, scaled(30_000)); +}); diff --git a/tests/idempotency.test.ts b/tests/idempotency.test.ts index b8b2cb6..670f19e 100644 --- a/tests/idempotency.test.ts +++ b/tests/idempotency.test.ts @@ -170,6 +170,22 @@ describe('App Store Connect: a second run writes nothing', () => { expect(count('appScreenshots')).toBe(12); }); + test('apple screenshots --platform macos: the Mac set (APP_DESKTOP) on the macOS version only', async () => { + const files: Record = {}; + for (const l of ['en', 'de']) for (const n of [1, 2]) files[`store/renders/${l}/mac/0${n}.png`] = png(n + (l === 'de' ? 40 : 30)); + const p = project({ ...CONFIG, apple: { ...CONFIG.apple!, mac: true } }, files); + const ios = s.asc.put({ type: 'appStoreVersions', id: 'ver-ios', attributes: { versionString: '1.0.0', appVersionState: 'PREPARE_FOR_SUBMISSION', platform: 'IOS' }, rels: { app: APP } }); + const mac = s.asc.put({ type: 'appStoreVersions', id: 'ver-mac', attributes: { versionString: '1.0.0', appVersionState: 'PREPARE_FOR_SUBMISSION', platform: 'MAC_OS' }, rels: { app: APP } }); + for (const v of [ios, mac]) for (const loc of ['en-US', 'de-DE']) s.asc.put({ type: 'appStoreVersionLocalizations', id: `loc-${v.id}-${loc}`, attributes: { locale: loc }, rels: { appStoreVersion: v.id } }); + const r = await twice(() => appleScreenshots(p.ctx(['--platform', 'macos']))); + expect(r.first.filter(x => x === 'POST /v1/appScreenshotSets')).toHaveLength(2); + expect(r.second).toEqual([]); + const sets = s.asc.all('appScreenshotSets'); + expect(sets.map(x => x.attributes.screenshotDisplayType)).toEqual(['APP_DESKTOP', 'APP_DESKTOP']); + expect(sets.every(x => JSON.stringify(x).includes('loc-ver-mac-'))).toBe(true); + expect(count('appScreenshots')).toBe(4); + }); + test('apple cpp create, events create, testflight groups, review-details, bundle, offer-codes, ppo create', async () => { const p = project({ ...CONFIG, shots: { variants: { b: {} } } as never }, { '.storebound/credentials.json': JSON.stringify({ reviewContact: { firstName: 'Ex', lastName: 'Ample', phone: '+1 555 0100', email: 'review@example.com' } }) }); s.asc.put({ type: 'appStoreVersions', id: 'ver-1', attributes: { versionString: '1.0.0', appVersionState: 'PREPARE_FOR_SUBMISSION', platform: 'IOS' }, rels: { app: APP } }); diff --git a/tests/mac-landscape.test.ts b/tests/mac-landscape.test.ts new file mode 100644 index 0000000..7a5ec32 --- /dev/null +++ b/tests/mac-landscape.test.ts @@ -0,0 +1,105 @@ +// Mac App Store screenshots (APP_DESKTOP, 16:10), the landscape layout's sizes, the safe-margin rule and the contact +// sheet timeout. The page-level render of the landscape layout and the margins: tests/browser/landscape.browser.ts. +import { describe, expect, test } from 'bun:test'; +import { checkImage, IMAGE_SPECS, imageInfo, macNote } from '../cli/shots/spec'; +import { defaultSizes, marginViolations, renderDims, SAFE_MARGIN_MIN, sheetLayout, sheetTimeoutMs, SIZES } from '../cli/shots/lib'; +import { marginIssues, requiredSets } from '../cli/shots/report'; +import { displaySets, MAC_DISPLAY } from '../cli/apple/screenshots'; +import { chromebookSkip } from '../cli/play/images'; +import { APPLE_SHOT_DIR } from '../cli/lib/art-pull'; +import { validateConfig } from '../cli/lib/config'; +import { loadFactor } from '../cli/shots/render'; +import { png } from './fixtures'; + +describe('Mac sizes', () => { + test('the four 16:10 sizes Apple lists, landscape only, APP_DESKTOP', () => { + expect(IMAGE_SPECS.mac!.sizes).toEqual([[2880, 1800], [2560, 1600], [1440, 900], [1280, 800]]); + expect(IMAGE_SPECS.mac!.type).toBe('APP_DESKTOP'); + expect(SIZES.mac).toMatchObject({ w: 2880, h: 1800, device: 'landscape' }); + for (const [w, h] of IMAGE_SPECS.mac!.sizes) expect(checkImage(imageInfo(png(w, h)), 'mac')).toEqual([]); + expect(checkImage(imageInfo(png(1800, 2880)), 'mac').map(i => i.code)).toEqual(['size']); + expect(checkImage(imageInfo(png(1920, 1080)), 'mac').map(i => i.code)).toEqual(['size']); + expect(checkImage(imageInfo(png(2880, 1800, { colorType: 6 })), 'mac').map(i => i.code)).toEqual(['alpha']); + }); + test('opt-in with apple.mac; required then', () => { + expect(defaultSizes({ apple: { bundleId: 'x' } } as never)).not.toContain('mac'); + expect(defaultSizes({ apple: { bundleId: 'x', mac: true } } as never)).toContain('mac'); + expect(requiredSets({ apple: { mac: true } }).mac).toBe(true); + expect(requiredSets({ apple: {} }).mac).toBeUndefined(); + }); + test('uploads: the Mac set only to a macOS version', () => { + expect(MAC_DISPLAY).toEqual({ mac: 'APP_DESKTOP' }); + expect(displaySets({ mac: true }, 'MAC_OS')).toEqual({ mac: 'APP_DESKTOP' }); + expect(displaySets({ mac: true }, 'IOS')).not.toHaveProperty('mac'); + expect(displaySets({}, 'MAC_OS')).toEqual({}); + expect(APPLE_SHOT_DIR.APP_DESKTOP).toBe('mac'); + }); + test('validate note: a macOS version without Mac screenshots', () => { + expect(macNote({ macVersion: true, mac: false })).toContain('apple.mac: true'); + expect(macNote({ macVersion: true, mac: true })).toBeNull(); + expect(macNote({ macVersion: false, mac: false })).toBeNull(); + }); +}); + +describe('landscape layout sizes', () => { + test('mac: window frame by default; chromebook and Play tablets: bare', () => { + expect(renderDims('mac', undefined)).toEqual({ w: 2880, h: 1800, landscape: true, frame: 'window' }); + expect(renderDims('chromebook', undefined)).toEqual({ w: 1920, h: 1080, landscape: true, frame: 'none' }); + expect(renderDims('tab10', undefined)).toMatchObject({ w: 1440, h: 2560, landscape: false }); + expect(renderDims('tab10', { landscape: { playTablets: true } })).toMatchObject({ w: 2560, h: 1440, landscape: true, frame: 'none' }); + expect(renderDims('mac', { landscape: { frame: 'none' } }).frame).toBe('none'); + for (const k of ['tab7', 'tab10']) { const d = renderDims(k, { landscape: { playTablets: true } }); expect(checkImage(imageInfo(png(d.w, d.h)), k)).toEqual([]); } + }); + test('chromebook: opt-in with play.chromebook, a check, and a console note instead of an upload', () => { + expect(defaultSizes({ play: { packageName: 'x' } } as never)).not.toContain('chromebook'); + expect(defaultSizes({ play: { packageName: 'x', chromebook: true } } as never)).toContain('chromebook'); + expect(checkImage(imageInfo(png(1920, 1080)), 'chromebook')).toEqual([]); + expect(chromebookSkip(true)).toContain('Main store listing'); + expect(chromebookSkip(false)).toBeNull(); + }); + test('config: frame and side are validated', () => { + const errs = (landscape: unknown) => validateConfig({ app: { name: 'X', profile: 'game' }, languages: [{ id: 'en' }], + shots: { copy: 'c.json', frames: 'f', out: 'o', scenes: [{ id: 'a', frames: [{ src: 'a.png' }] }], landscape } } as never).filter(e => e.startsWith('shots.landscape')); + expect(errs({ frame: 'window', side: 'right', playTablets: true })).toEqual([]); + expect(errs({ frame: 'macbook' })).toEqual(["shots.landscape.frame: 'window' | 'none'"]); + }); +}); + +describe('safe margins', () => { + const W = 1320, H = 2868; + test('boxes inside the margins pass; text at the edge fails', () => { + expect(marginViolations([{ el: 'title', x: W * .07, y: H * .05, w: W * .86, h: 200 }], W, H)).toEqual([]); + const v = marginViolations([{ el: 'title', x: 12, y: 300, w: 1290, h: 200 }, { el: 'logo', x: 200, y: 20, w: 900, h: 300 }], W, H); + expect(v).toHaveLength(2); + expect(v[0]).toContain('title is too close to the edge (left 12 px, right 18 px'); + expect(v[1]).toContain('logo is too close to the edge (top 20 px'); + expect(Math.round(W * SAFE_MARGIN_MIN.x)).toBe(79); + }); + test('shots check: an error per box, none without layout data', () => { + const e = marginIssues({ overflow: [], boxes: [{ el: 'subtitle', x: 0, y: 900, w: 500, h: 60 }] }, W, H); + expect(e.map(i => [i.level, i.code])).toEqual([['error', 'margin']]); + expect(marginIssues({ overflow: [] }, W, H)).toEqual([]); + expect(marginIssues(undefined, W, H)).toEqual([]); + }); +}); + +describe('contact sheet timeout', () => { + test('scales with images, sizes and load; never a flat 30 s', () => { + const nine = sheetTimeoutMs(9 * 5, 9); + expect(nine).toBeGreaterThan(30_000 * 3); + expect(sheetTimeoutMs(90, 9)).toBeGreaterThan(nine); + expect(sheetTimeoutMs(45, 9, 3)).toBe(nine * 3); + expect(sheetTimeoutMs(45, 9, 50)).toBe(nine * 5); + expect(sheetTimeoutMs(1, 1, 0.2)).toBe(sheetTimeoutMs(1, 1)); + }); + test('load factor: forced by env, clamped 1..5', () => { + expect(loadFactor({ STOREBOUND_LOAD_FACTOR: '3' })).toBe(3); + expect(loadFactor({}, [40, 20, 0], 10)).toBe(4); + expect(loadFactor({}, [0, 0, 0], 10)).toBe(1); + expect(loadFactor({}, [500, 0, 0], 10)).toBe(5); + }); + test('landscape tiles take half height on the sheet', () => { + const l = sheetLayout([{ size: 'mac', files: ['a'], dims: { w: 2880, h: 1800 } }]); + expect(l.tiles[0]).toMatchObject({ h: 450, w: 720 }); + }); +}); diff --git a/tools/ci-plan.ts b/tools/ci-plan.ts index 6d577e2..cb8973f 100644 --- a/tools/ci-plan.ts +++ b/tools/ci-plan.ts @@ -15,7 +15,7 @@ export const TIMINGS = join(ROOT, 'node_modules/.cache/storebound-ci/test-timing export const HEAVY = [ 'tests/browser/console-fill.browser.ts', 'tests/browser/site-overflow.browser.ts', 'tests/browser/local-fonts.browser.ts', 'tests/browser/glyphs.browser.ts', 'tests/browser/capture-web.browser.ts', 'tests/browser/console-session.browser.ts', 'tests/browser/console-persist.browser.ts', 'tests/browser/console-flow.browser.ts', - 'tests/browser/glyph-ligatures.browser.ts', 'tests/browser/feature-fit.browser.ts', + 'tests/browser/glyph-ligatures.browser.ts', 'tests/browser/feature-fit.browser.ts', 'tests/browser/landscape.browser.ts', ]; /** Browser tests of one file at the same time (bun test --max-concurrency for the browser shards; the tests opt in From 7c04a0653b5a061d7425c0cab65dafd7bcbab7de Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 03:29:59 +0700 Subject: [PATCH 039/344] desktop boot check: match the submit dry run by its fields, not the exact JSON (the call carries platform since the macOS support; 0.8.14's Mac build stopped on it) --- tools/desktop-boot-check.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tools/desktop-boot-check.ts b/tools/desktop-boot-check.ts index 40af562..530d431 100644 --- a/tools/desktop-boot-check.ts +++ b/tools/desktop-boot-check.ts @@ -453,7 +453,9 @@ async function runSubmitCase(browser: Browser, sidecar: Sidecar, base: 'd3-full' await gone(page, '.oa-panel'); if (await page.locator('.oa-panel').count()) problems.push('plan panel does not close with Escape'); const want = variant === 'ready' ? 'owner.apple_submit' : 'owner.apple_resubmit'; - if (!live.calls.some(c => c.startsWith(`dry ${want} {"build":"52","version":"2.4.0"}`))) problems.push(`no dry run of ${want} with build 52 and version 2.4.0: ${live.calls.join(' | ')}`); + // match the fields, not the exact JSON: the call may carry more of them (platform since the macOS support) + const dryOf = (c: string): Record | null => { if (!c.startsWith(`dry ${want} `)) return null; try { return JSON.parse(c.slice(`dry ${want} `.length)); } catch { return null; } }; + if (!live.calls.some(c => { const a = dryOf(c); return !!a && a.build === '52' && a.version === '2.4.0'; })) problems.push(`no dry run of ${want} with build 52 and version 2.4.0: ${live.calls.join(' | ')}`); if (!live.calls.some(c => c.startsWith(`write_with_confirm ${want}`))) problems.push(`${want} did not go through write_with_confirm`); // Google Play: versionCodes by number (one already in production cannot be picked), then the production plan const codes = page.locator('[data-section="submit"] select[aria-describedby="sub-code-hint"]'); From 9805582278c99bab5faae99259c30b65ae8fd410 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 03:31:36 +0700 Subject: [PATCH 040/344] storebound 0.8.15: version in package.json and every copy, CHANGELOG 0.8.15 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index a84d8d8..9a16463 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.14", + "version": "0.8.15", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index ee542b7..d8722ec 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.14", + "version": "0.8.15", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index f1ccf69..9ed2fcc 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.14", + "version": "0.8.15", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c01f9f..bc75c97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.15 · 2026-10-19 + - **Mac App Store screenshots.** `apple.mac: true` adds the `mac` size (2880 x 1800; `shots check` takes exactly Apple's four 16:10 sizes, no alpha) and `apple screenshots --platform macos` uploads it as `APP_DESKTOP` to the macOS version. `validate` notes a macOS version without Mac screenshots. Art pull maps `APP_DESKTOP` to `mac/`. diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 8047fb9..1efa684 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.14", + "version": "0.8.15", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 9d68ef4..f96a802 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4010,7 +4010,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.14" +version = "0.8.15" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 0cd187a..a91836f 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.14" +version = "0.8.15" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 442bd49..109d583 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.14", + "version": "0.8.15", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index 33e24fe..72f1757 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.14", + "version": "0.8.15", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index e886e82..cf2b2c4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.14", + "version": "0.8.15", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From 9ab64bcbdf9e19b5cae4fa1f2f5f84e43ec61159 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 12:15:00 +0700 Subject: [PATCH 041/344] apps folders add adds the folder (template note, refusals with reasons); MCP: .mcp.json never spawns a missing plugin path (sh fallback to PATH, npx), mcp/serve skip the self-update, spawned handshake test; store build minimums in one dated table: Play target API 36 and App Store Xcode 26 / SDK 26 blocked in scan, validate, play upload/release, apple upload; pitfalls 81-83 --- .mcp.json | 5 ++- CHANGELOG.md | 9 ++++ cli/apple/upload.ts | 4 ++ cli/apps.ts | 20 ++++++++- cli/index.ts | 3 +- cli/lib/scan/project.ts | 15 ++++++- cli/lib/scan/rules.ts | 16 +++++-- cli/lib/store-minimums.ts | 81 ++++++++++++++++++++++++++++++++++ cli/lib/xcode.ts | 5 ++- cli/play/release.ts | 5 +++ cli/play/upload.ts | 4 ++ skills/store-pitfalls/SKILL.md | 32 ++++++++++++++ tests/mcp-spawn.test.ts | 51 +++++++++++++++++++++ tests/store-minimums.test.ts | 75 +++++++++++++++++++++++++++++++ tests/wave1.test.ts | 4 +- tools/gen-adapters.ts | 8 +++- 16 files changed, 323 insertions(+), 14 deletions(-) create mode 100644 cli/lib/store-minimums.ts create mode 100644 tests/mcp-spawn.test.ts create mode 100644 tests/store-minimums.test.ts diff --git a/.mcp.json b/.mcp.json index cfd2b8d..fbf5215 100644 --- a/.mcp.json +++ b/.mcp.json @@ -1,9 +1,10 @@ { "mcpServers": { "storebound": { - "command": "${CLAUDE_PLUGIN_ROOT}/bin/storebound", + "command": "sh", "args": [ - "mcp" + "-c", + "r=\"${CLAUDE_PLUGIN_ROOT:-}\"; if [ -n \"$r\" ] && [ -x \"$r/bin/storebound\" ]; then exec \"$r/bin/storebound\" mcp; fi; if command -v storebound >/dev/null 2>&1; then exec storebound mcp; fi; exec npx -y storebound@latest mcp" ] } } diff --git a/CHANGELOG.md b/CHANGELOG.md index bc75c97..f4c031a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +- `apps folders add []` adds the folder (it listed and added nothing); a template config is added with a note, + a folder without a config is refused with the reason and the fix (pitfall 81). +- MCP: the plugin's `.mcp.json` no longer spawns a plugin path that may be gone (ENOENT, CONNECTION_CLOSED): it falls + back to `storebound` on PATH, then `npx -y storebound@latest`; `mcp` and `serve` skip the self-update (pitfall 82). +- Store build minimums in one dated table (`cli/lib/store-minimums.ts`): `play upload` / `play release` refuse an AAB + below Play's target API level (36 since 2026-08-31) and `apple upload` an IPA built below Xcode 26 / the 26 SDKs + (since 2026-04-28), with the file to change; `scan` / `validate` report the same (`play-target-sdk`, `apple-min-sdk`) + (pitfall 83). + ## 0.8.15 · 2026-10-19 - **Mac App Store screenshots.** `apple.mac: true` adds the `mac` size (2880 x 1800; `shots check` takes exactly diff --git a/cli/apple/upload.ts b/cli/apple/upload.ts index 72ff2f7..661cc4d 100644 --- a/cli/apple/upload.ts +++ b/cli/apple/upload.ts @@ -14,6 +14,7 @@ // with `apple testflight wait` (waitForBuild) until processingState is VALID (exit 0), INVALID / FAILED (exit 1) or the // timeout (exit 7). // An upload is a write: --dry shows the plan; a real run asks first (--yes in scripts). +import { appleSdkProblem } from '../lib/store-minimums'; import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from 'node:fs'; import { basename, join, relative } from 'node:path'; import { ascKeyFile } from '../lib/credentials'; @@ -230,6 +231,9 @@ export async function run(ctx: Ctx): Promise { const info = ipaInfo(ipa); if (want && info.build !== want) throw new Error(`${relative(root, ipa)} is build ${info.build}, not ${want} (--build): did the last apple build fail?`); if (info.bundleId !== bundleId) throw new Error(`${relative(root, ipa)} is ${info.bundleId}, the config says ${bundleId}`); + // App Store Connect refuses IPAs from an Xcode / SDK older than its current minimum (cli/lib/store-minimums.ts) + const sdkWhy = appleSdkProblem(info); + if (sdkWhy) throw new Error(`${relative(root, ipa)}: not uploaded, ${sdkWhy}`); // every PrivacyInfo.xcprivacy in the app (root, Frameworks, bundles): Apple refuses the build minutes after the // upload when NSPrivacyTracking and NSPrivacyTrackingDomains disagree (ITMS-91064), so stop before any network call const privacy = bundleTrackingIssues(ipaManifests(ipa)); diff --git a/cli/apps.ts b/cli/apps.ts index 2a7d434..1200151 100644 --- a/cli/apps.ts +++ b/cli/apps.ts @@ -24,7 +24,7 @@ import { ascClient } from './apple/asc'; import { REPORTING_API } from './play/google'; import * as rt from './lib/rt'; import { existsSync, readFileSync } from 'node:fs'; -import { join, resolve } from 'node:path'; +import { basename, join, resolve } from 'node:path'; import { CONFIG_NAMES } from './lib/config'; import { addFolder, addStoreApp, readRegistry, registryFile, removeFolder, removeStoreApp } from './lib/registry'; @@ -162,6 +162,10 @@ const tilde = (p: string) => (process.env.HOME && p.startsWith(process.env.HOME) /** apps folders / add / remove: the machine's app folder list (cli/lib/registry.ts). */ async function folders(sub: string, args: Args): Promise { + // `apps folders add []` / `apps folders remove `: the same as `apps add` / `apps remove` (this form used + // to fall through to the list and add nothing, without a word) + if (sub === 'folders' && (args._[1] === 'add' || args._[1] === 'remove')) { sub = args._[1]; args._.splice(0, 1); } + if (sub === 'folders' && args._[1]) throw new Error(`storebound apps folders ${args._[1]}: unknown; to add a folder: storebound apps add [] (or apps folders add []), to list: storebound apps folders`); if (sub === 'folders') { const r = readRegistry(); if (args.has('json')) { printJson({ file: registryFile(), projects: r.projects.map(p => ({ ...p, missing: !existsSync(p.path) })), storeApps: r.storeApps ?? [] }); return; } @@ -200,9 +204,13 @@ ${tilde(registryFile())}: the same list as the desktop app's App folders`); } const dir = resolve(args._[1] ?? '.'); if (sub === 'add') { - if (!CONFIG_NAMES.some(n => existsSync(join(dir, n)))) throw new Error(`${dir}: no storebound config here (storebound init starts one)`); + if (!existsSync(dir)) throw new Error(`${dir}: no such folder`); + const cfg = CONFIG_NAMES.find(n => existsSync(join(dir, n))); + if (!cfg) throw new Error(`${dir}: not added, no storebound config here (${CONFIG_NAMES.join(', ')}); run storebound init in it, then this again`); const r = addFolder(dir); log('apps', r.added ? `added ${tilde(r.project.path)} (it shows in the desktop app too)` : `${tilde(r.project.path)} is already in the list`); + const note = templateNote(join(dir, cfg)); + if (note) warn('apps', note); return; } if (!args._[1]) throw new Error('storebound apps remove '); @@ -249,3 +257,11 @@ export async function run(args: Args): Promise { console.error('usage: storebound apps list [--store apple|play] [--icons] [--json] | apps check [--store apple|play] [--json] | apps folders [--json] | apps add [] | apps add --store apple|play --app-id [--account ] | apps remove | apps remove apple:'); process.exit(2); } + +/** A note when the config still holds the template's placeholders (the folder is added anyway: it is the owner's). */ +export function templateNote(file: string): string | null { + let t = ''; + try { t = readFileSync(file, 'utf8'); } catch { return null; } + const left = [/['"]Example App['"]/.test(t) && "app.name is still the template's 'Example App'", /com\.example\./.test(t) && 'the bundle id / package is still com.example.*'].filter(Boolean); + return left.length ? `${left.join('; ')}: set your app's values in ${basename(file)} (storebound check lists the rest)` : null; +} diff --git a/cli/index.ts b/cli/index.ts index b6346f4..7ba9efd 100755 --- a/cli/index.ts +++ b/cli/index.ts @@ -62,7 +62,8 @@ async function main(): Promise { } } // npx / bunx run a cached copy: start the newest storebound instead (cli/lib/self-update.ts) - { const { runNewest } = await import('./lib/self-update'); await runNewest((await import('../package.json')).version, process.argv.slice(2)); } + // never for mcp / serve: a client waits for the handshake on stdout, and a second npx download can outlast its timeout + if (argv[0] !== 'mcp' && argv[0] !== 'serve') { const { runNewest } = await import('./lib/self-update'); await runNewest((await import('../package.json')).version, process.argv.slice(2)); } const [a, b] = argv; if (!a || a === 'help' || a === '--help' || a === '-h') return help(); if (a === 'version' || a === '--version') return console.log((await import('../package.json')).version); diff --git a/cli/lib/scan/project.ts b/cli/lib/scan/project.ts index dd45fc7..f0b8f8b 100644 --- a/cli/lib/scan/project.ts +++ b/cli/lib/scan/project.ts @@ -8,6 +8,7 @@ import { basename, dirname, extname, join, relative, sep } from 'node:path'; import { resolvePackage } from '../node-packages'; import { isBuildCopyPath, type Manifest, parseManifest } from '../privacy-manifest'; import { type DepRef, type Eco, matchesSdk, SDKS, type SdkDef } from './sdks'; +import { exportedIpas, ipaInfo } from '../xcode'; export interface Loc { file: string; line: number } export interface PlistEntry { key: string; value: unknown; at: Loc } @@ -88,6 +89,8 @@ export interface ProjectFacts { sources: { path: string; text: string }[]; /** Folders of built web output inside the project (Capacitor webDir): low-trust evidence, see isBuilt. */ builtDirs: string[]; + /** Xcode / SDK of the newest IPA in build/ios/export (Info.plist DTXcode, DTSDKName, DTPlatformVersion). */ + iosBuild?: { file: string; xcode?: string; sdkName?: string; platformVersion?: string } | null; /** Files looked at, relative to root (for the report). */ scanned: number; } @@ -542,7 +545,7 @@ export function detectProject(root: string): ProjectFacts { for (const x of extra.services) if (!svc.has(key('service', x.name))) android.services.push(x); } } - return { root, stacks: [...stacks], ios, android: isAndroid, deps, sdks, plist, plistSources, entitlements, privacyManifests, androidInfo: android, native, remoteStart, sources, builtDirs, scanned: files.length }; + return { root, stacks: [...stacks], ios, android: isAndroid, deps, sdks, plist, plistSources, entitlements, privacyManifests, androidInfo: android, native, remoteStart, sources, builtDirs, iosBuild: newestIpaBuild(root), scanned: files.length }; } /** NDK r27 flag and the linker flag of older NDKs that make native libraries 16 KB aligned. */ @@ -640,3 +643,13 @@ export const where = (l: Loc): string => `${l.file}:${l.line}`; /** Ecosystems in a readable order for the report. */ export const ECO_LABEL: Record = { cocoapods: 'CocoaPods', spm: 'SwiftPM', carthage: 'Carthage', gradle: 'Gradle', npm: 'npm', pub: 'pub', unity: 'Unity', godot: 'Godot' }; + +/** The build tools of the newest IPA under build/ios/export, or null (no IPA, or unreadable). */ +function newestIpaBuild(root: string): ProjectFacts['iosBuild'] { + try { + const ipa = exportedIpas(join(root, 'build/ios/export'))[0]; + if (!ipa) return null; + const i = ipaInfo(ipa); + return { file: relative(root, ipa).split(sep).join('/'), xcode: i.xcode, sdkName: i.sdkName, platformVersion: i.platformVersion }; + } catch { return null; } +} diff --git a/cli/lib/scan/rules.ts b/cli/lib/scan/rules.ts index 11aeb6d..8b2ddda 100644 --- a/cli/lib/scan/rules.ts +++ b/cli/lib/scan/rules.ts @@ -47,6 +47,7 @@ import { playRules } from './play-rules'; import { grep, grepOwn, type Hit, lineOf, type ProjectFacts } from './project'; import { matchesSdk, OBFUSCATORS, REMOTE_CODE, REMOTE_SDKS, type RemoteSdkDef, versionAtLeast } from './sdks'; import { reviewNotes } from '../review-details'; +import { appleSdkProblem, PLAY_TARGET_SDK_TABLE } from '../store-minimums'; export type Severity = 'blocker' | 'high' | 'medium' | 'low'; export type ScanStore = 'apple' | 'play'; @@ -93,8 +94,10 @@ export interface ScanInput { export const APPLE_GUIDELINES = 'https://developer.apple.com/app-store/review/guidelines/'; const PLAY = 'https://support.google.com/googleplay/android-developer/answer/'; export const PLAY_POLICY = 'https://play.google/developer-content-policy/'; -export const PLAY_TARGET_SDK = { phone: 36, wear: 35, automotive: 35, tv: 34 } as const; -export const PLAY_TARGET_SDK_SINCE = '2026-08-31'; +/** The Play target API level in force today (the dated table is cli/lib/store-minimums.ts). */ +const PLAY_SDK_ROW = PLAY_TARGET_SDK_TABLE.filter(r => r.since <= new Date().toISOString().slice(0, 10)).at(-1) ?? PLAY_TARGET_SDK_TABLE[0]!; +export const PLAY_TARGET_SDK = PLAY_SDK_ROW.min; +export const PLAY_TARGET_SDK_SINCE = PLAY_SDK_ROW.since; // ---- code signals ---- /** `re` only on lines that are not import / require / export-from statements (a module path is not evidence). Line @@ -363,6 +366,13 @@ export function scanRules(inp: ScanInput): ScanFinding[] { } // ---- App Tracking Transparency ---- + // ---- App Store: the Xcode / SDK of the newest local IPA (cli/lib/store-minimums.ts) ---- + if (apple && p.iosBuild) { + const why = appleSdkProblem(p.iosBuild); + if (why) add({ rule: 'apple-min-sdk', guideline: 'App Store: minimum Xcode / SDK', store: 'apple', severity: 'blocker', title: why.split(': ')[0]!, + evidence: [{ file: p.iosBuild.file, line: 1, text: [p.iosBuild.xcode && `DTXcode ${p.iosBuild.xcode}`, p.iosBuild.sdkName && `DTSDKName ${p.iosBuild.sdkName}`].filter(Boolean).join(', ') }], + fix: why.slice(why.indexOf(': ') + 2), skill: 'build-and-sign', ref: 'https://developer.apple.com/news/upcoming-requirements/' }); + } if (apple && p.ios) { const trackers = p.sdks.filter(s => s.sdk.tracking); const trackEv = sdkHits(s => s.sdk.tracking); @@ -552,7 +562,7 @@ export function scanRules(inp: ScanInput): ScanFinding[] { const need = PLAY_TARGET_SDK[a.formFactor]; if (a.targetSdk && a.targetSdk.value < need) add({ rule: 'play-target-sdk', guideline: 'Play: Target API level', store: 'play', severity: 'blocker', title: `targetSdk ${a.targetSdk.value} is below ${need}, which new apps and updates need since ${PLAY_TARGET_SDK_SINCE}`, evidence: [{ ...a.targetSdk.at, text: `targetSdk ${a.targetSdk.value}` }], - fix: `Raise targetSdk (and compileSdk) to ${need}, test the behavior changes of each Android version in between, then upload a new AAB (an extension to 2026-11-01 can be requested in Play Console).`, skill: 'play-first-release', + fix: `Set targetSdkVersion = ${need} (and compileSdkVersion) in ${a.targetSdk.at.file} and rebuild; test the behavior changes of each Android version in between, then upload a new AAB ${PLAY_SDK_ROW.extensionUntil ? ` (an extension to ${PLAY_SDK_ROW.extensionUntil} can be requested in Play Console)` : ''}.`, skill: 'play-first-release', ref: 'https://developer.android.com/google/play/requirements/target-sdk' }); else if (!a.targetSdk && a.targetSdkFrom) add({ rule: 'play-target-sdk', guideline: 'Play: Target API level', store: 'play', severity: 'low', title: `targetSdk comes from ${a.targetSdkFrom}: check that the built AAB targets ${need} or higher`, evidence: a.manifests.slice(0, 1).map(f => ({ file: f, line: 1, text: 'AndroidManifest.xml' })), diff --git a/cli/lib/store-minimums.ts b/cli/lib/store-minimums.ts new file mode 100644 index 0000000..d7dcf9e --- /dev/null +++ b/cli/lib/store-minimums.ts @@ -0,0 +1,81 @@ +// Store build minimums, one dated table per store: a new year is one new row. +// - Google Play: the target API level (targetSdkVersion) that new apps and app updates need. Since 2026-08-31 Google's +// rule is the same for new apps and updates (an extension to 2026-11-01 can be requested in Play Console). +// https://developer.android.com/google/play/requirements/target-sdk +// - App Store: the Xcode / SDK an upload must be built with (Apple's "Upcoming requirements"). +// https://developer.apple.com/news/upcoming-requirements/ + +import { existsSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +export type FormFactor = 'phone' | 'wear' | 'tv' | 'automotive'; + +/** Google Play target API level per form factor, by the date it is enforced (oldest first). */ +export const PLAY_TARGET_SDK_TABLE: readonly { since: string; extensionUntil?: string; min: Record }[] = [ + { since: '2025-08-31', extensionUntil: '2025-11-01', min: { phone: 35, wear: 34, automotive: 34, tv: 34 } }, + { since: '2026-08-31', extensionUntil: '2026-11-01', min: { phone: 36, wear: 35, automotive: 35, tv: 34 } }, +]; + +/** App Store: uploads must be built with at least this Xcode and platform SDK (iOS / iPadOS etc.), by date. */ +export const APPLE_MIN_SDK_TABLE: readonly { since: string; xcode: number; sdk: number }[] = [ + { since: '2025-04-24', xcode: 16, sdk: 18 }, + { since: '2026-04-28', xcode: 26, sdk: 26 }, +]; + +const today = (): string => new Date().toISOString().slice(0, 10); +function rowAt(t: readonly T[], date: string): T | null { + let r: T | null = null; + for (const x of t) if (x.since <= date) r = x; + return r; +} + +/** The Play target API level in force on `date` (default today). */ +export function playTargetSdk(form: FormFactor = 'phone', date = today()): { min: number; since: string; extensionUntil?: string } | null { + const r = rowAt(PLAY_TARGET_SDK_TABLE, date); + return r ? { min: r.min[form], since: r.since, extensionUntil: r.extensionUntil } : null; +} + +/** Why Play refuses this targetSdk, with the fix; null when it is fine (or unknown). */ +export function playTargetSdkProblem(target: number | undefined | null, o: { form?: FormFactor; date?: string; where?: string } = {}): string | null { + const r = playTargetSdk(o.form ?? 'phone', o.date); + if (!r || !target || target >= r.min) return null; + const where = o.where ?? 'android/variables.gradle (or app/build.gradle)'; + return `targetSdkVersion ${target} < ${r.min}: Google Play takes new apps and updates only for API ${r.min}+ since ${r.since}` + + `${o.form && o.form !== 'phone' ? ` (${o.form})` : ''}; set targetSdkVersion = ${r.min} (and compileSdkVersion) in ${where} and rebuild` + + (r.extensionUntil ? ` (an extension to ${r.extensionUntil} can be requested in Play Console)` : ''); +} + +/** The App Store minimum in force on `date` (default today). */ +export function appleMinSdk(date = today()): { xcode: number; sdk: number; since: string } | null { + return rowAt(APPLE_MIN_SDK_TABLE, date); +} + +/** Xcode major from DTXcode ("2600" -> 26, "1640" -> 16). */ +export const xcodeMajor = (dt: string | undefined): number | null => (dt && /^\d{3,4}$/.test(dt) ? Math.floor(Number(dt) / 100) : null); +/** SDK major from DTPlatformVersion ("26.0") or DTSDKName ("iphoneos26.0"). */ +export function sdkMajor(platformVersion: string | undefined, sdkName?: string): number | null { + const m = (platformVersion ?? '').match(/^(\d+)/) ?? (sdkName ?? '').match(/(\d+)(?:\.\d+)*$/); + return m ? Number(m[1]) : null; +} + +/** Why App Store Connect refuses an IPA built with this Xcode / SDK, with the fix; null when fine (or unknown). */ +export function appleSdkProblem(b: { xcode?: string; sdkName?: string; platformVersion?: string }, date?: string): string | null { + const r = appleMinSdk(date); + if (!r) return null; + const x = xcodeMajor(b.xcode), s = sdkMajor(b.platformVersion, b.sdkName); + if ((x === null || x >= r.xcode) && (s === null || s >= r.sdk)) return null; + const got = [x !== null ? `Xcode ${x}` : '', b.sdkName ?? (s !== null ? `SDK ${s}` : '')].filter(Boolean).join(', '); + return `built with ${got} < Xcode ${r.xcode} / SDK ${r.sdk}: App Store Connect takes uploads only from Xcode ${r.xcode}+ with the ${r.sdk} SDKs since ${r.since}; ` + + `install Xcode ${r.xcode} (xcode-select -s), rebuild (storebound apple build) and upload the new IPA`; +} + +/** The project file that sets targetSdkVersion (Capacitor variables.gradle, Gradle app module, Unity ProjectSettings), + * for the fix line; a generic hint when none is found. */ +export function targetSdkFile(root: string): string { + const files = ['android/variables.gradle', 'android/app/build.gradle', 'android/app/build.gradle.kts', 'app/build.gradle', 'app/build.gradle.kts', + 'android/build.gradle', 'android/build.gradle.kts', 'ProjectSettings/ProjectSettings.asset']; + for (const f of files) { + try { if (existsSync(join(root, f)) && /targetSdk|AndroidTargetSdkVersion/.test(readFileSync(join(root, f), 'utf8'))) return f.endsWith('.asset') ? `${f} (AndroidTargetSdkVersion; Player Settings > Target API Level)` : f; } catch { /* unreadable */ } + } + return 'the app module\'s build.gradle (Capacitor: android/variables.gradle; Flutter: android/app/build.gradle; Unity: Player Settings > Target API Level)'; +} diff --git a/cli/lib/xcode.ts b/cli/lib/xcode.ts index c37e47f..0969ac8 100644 --- a/cli/lib/xcode.ts +++ b/cli/lib/xcode.ts @@ -147,7 +147,7 @@ export const flutterConfigArgs = (build: string, version?: string): string[] => export const showCmd = (argv: string[], auth: AscAuth | null): string => argv.map(a => (auth && a === auth.keyPath ? '$ASC_P8' : /[\s"'$]/.test(a) ? JSON.stringify(a) : a)).join(' '); -export interface IpaInfo { bundleId: string; version: string; build: string; minOs?: string; name?: string; platform?: string } +export interface IpaInfo { bundleId: string; version: string; build: string; minOs?: string; name?: string; platform?: string; xcode?: string; sdkName?: string; platformVersion?: string } /** Bundle id, CFBundleShortVersionString and CFBundleVersion from Payload/.app/Info.plist of an IPA. */ /** Every .ipa in the export folder and its per-build subfolders (-/), newest first. */ @@ -169,7 +169,8 @@ export function ipaInfo(ipa: string | Buffer): IpaInfo { const str = (k: string): string | undefined => (typeof p[k] === 'string' ? p[k] as string : undefined); const bundleId = str('CFBundleIdentifier'), version = str('CFBundleShortVersionString'), build = str('CFBundleVersion'); if (!bundleId || !version || !build) throw new Error('Info.plist without CFBundleIdentifier / CFBundleShortVersionString / CFBundleVersion'); - return { bundleId, version, build, minOs: str('MinimumOSVersion'), name: str('CFBundleDisplayName') ?? str('CFBundleName'), platform: (p.CFBundleSupportedPlatforms as string[] | undefined)?.[0] }; + return { bundleId, version, build, minOs: str('MinimumOSVersion'), name: str('CFBundleDisplayName') ?? str('CFBundleName'), platform: (p.CFBundleSupportedPlatforms as string[] | undefined)?.[0], + xcode: str('DTXcode'), sdkName: str('DTSDKName'), platformVersion: str('DTPlatformVersion') }; } /** End states of an App Store Connect build upload (BuildUploadState); processing is polled by apple testflight wait. */ diff --git a/cli/play/release.ts b/cli/play/release.ts index 10d9d99..808214a 100644 --- a/cli/play/release.ts +++ b/cli/play/release.ts @@ -12,6 +12,7 @@ import type { Ctx } from '../lib/ctx'; import { confirm, need } from '../lib/ctx'; import { done, log, warn } from '../lib/log'; import { aabInfo } from '../lib/gradle'; +import { playTargetSdkProblem, targetSdkFile } from '../lib/store-minimums'; import { playClient } from './client'; import { usedVersionCodes } from './next-version-code'; import { readPlayCopy, refusePlayNotes } from './listing'; @@ -49,6 +50,10 @@ export async function run(ctx: Ctx): Promise { refusePlayNotes(ctx, notes, `play release notes${a.has('dry') ? ' (dry run)' : ''}`); if (live && !a.has('dry') && !(await confirm(ctx, `Release to PRODUCTION as "${live.status}" (public once Google approves)?`))) return; + if (aab) { + const sdkWhy = playTargetSdkProblem(aabInfo(aab).targetSdk, { where: targetSdkFile(root) }); + if (sdkWhy) throw new Error(`${aab}: not released, ${sdkWhy}`); + } const play = await playClient(root, pkg); try { await play.edit(async (id, ctl) => { diff --git a/cli/play/upload.ts b/cli/play/upload.ts index c7489ca..0ded9c1 100644 --- a/cli/play/upload.ts +++ b/cli/play/upload.ts @@ -10,6 +10,7 @@ import { join, relative } from 'node:path'; import type { Ctx } from '../lib/ctx'; import { confirm, need } from '../lib/ctx'; import { aabInfo } from '../lib/gradle'; +import { playTargetSdkProblem, targetSdkFile } from '../lib/store-minimums'; import { done, log, printJson } from '../lib/log'; import { nextVersionCode } from '../lib/release'; import { playClient } from './client'; @@ -39,6 +40,9 @@ export async function run(ctx: Ctx): Promise { } const info = aabInfo(aab); if (info.packageName !== pkg) throw new Error(`${relative(root, aab)} is ${info.packageName}, the config says ${pkg}`); + // Play refuses bundles below its current target API level (cli/lib/store-minimums.ts): stop before any network call + const sdkWhy = playTargetSdkProblem(info.targetSdk, { where: targetSdkFile(root) }); + if (sdkWhy) throw new Error(`${relative(root, aab)}: not uploaded, ${sdkWhy}`); const size = statSync(aab).size; const dry = a.has('dry'); const json = a.has('json'); diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index cff17e9..3013bda 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -994,3 +994,35 @@ that fails without the fix (see CONTRIBUTING.md). `cli/shots/report.ts`, `IMAGE_SPECS.mac` and `macNote` in `cli/shots/spec.ts`, `MAC_DISPLAY` in `cli/apple/screenshots.ts`, `sheetTimeoutMs`; `tests/mac-landscape.test.ts`, `tests/browser/landscape.browser.ts`, the macOS case in `tests/idempotency.test.ts`. + +## 81. `storebound apps folders add` listed the folders and added nothing +- **Symptom:** `storebound apps folders add` (or with `"$PWD"`) in a freshly init-ed folder printed the folder list, + no error, and ~/.storebound/projects.json stayed without the folder. +- **Cause:** only `apps add` added; `apps folders` ignored every word after it and listed. +- **Do:** `apps folders add []` is now the same as `apps add []` (bare = the current folder). A folder + whose config still has template values is added with a note; a folder without a config is refused with the reason + and the fix (`storebound init`). Unknown words after `apps folders` are an error, never a silent list. +- **Guard:** `folders` and `templateNote` in `cli/apps.ts`; `tests/store-minimums.test.ts` (apps folders add). + +## 82. The MCP server failed to connect: spawn ENOENT, CONNECTION_CLOSED +- **Symptom:** the client showed `storebound (ENOENT) posix_spawn '/…/bin/storebound'` or + "CONNECTION_CLOSED: Connection closed". +- **Cause:** `.mcp.json` spawned `${CLAUDE_PLUGIN_ROOT}/bin/storebound` directly; when that folder is gone (an old + plugin cache after an update) or the variable is unset (the repo opened as a project), the spawn fails before any + code runs. Under npx, the self-update could also start a second npx download before the handshake. +- **Do:** `.mcp.json` runs `sh -c`: the plugin's launcher if it exists, else `storebound` on PATH, else + `npx -y storebound@latest mcp`. `mcp` and `serve` skip the self-update. Nothing may print on stdout before the + JSON-RPC answer (logs go to stderr). +- **Guard:** `MCP_LAUNCH` in `tools/gen-adapters.ts`, `cli/index.ts`; `tests/mcp-spawn.test.ts` spawns the CLI, the + launcher and the `.mcp.json` command with a missing plugin root and completes `initialize` within 10 s. + +## 83. Uploads below the store's build minimum (Play target API level, App Store Xcode / SDK) +- **Symptom:** Google Play refuses a bundle with targetSdkVersion 35 (API 36+ for new apps and updates since + 2026-08-31); App Store Connect refuses an IPA built with an Xcode / SDK older than the minimum (Xcode 26 / the 26 + SDKs since 2026-04-28). +- **Do:** set `targetSdkVersion` (and `compileSdkVersion`) in android/variables.gradle (Capacitor), the app module's + build.gradle(.kts), Flutter's android/app/build.gradle or Unity's Target API Level; build iOS with the current Xcode. + `scan` / `validate` (rules `play-target-sdk`, `apple-min-sdk` from the newest IPA in build/ios/export) and + `play upload` / `play release` / `apple upload` block before any network call, naming the requirement, date and fix. +- **Guard:** the dated tables `PLAY_TARGET_SDK_TABLE` and `APPLE_MIN_SDK_TABLE` in `cli/lib/store-minimums.ts` (a new + year is one row); `tests/store-minimums.test.ts`. diff --git a/tests/mcp-spawn.test.ts b/tests/mcp-spawn.test.ts new file mode 100644 index 0000000..b14fbf5 --- /dev/null +++ b/tests/mcp-spawn.test.ts @@ -0,0 +1,51 @@ +// The MCP server as a client starts it: a spawned process, an `initialize` on stdin, a JSON-RPC answer as the very +// first stdout line within 10 s (a log line on stdout closes the client's connection: CONNECTION_CLOSED). +import { describe, expect, test } from 'bun:test'; +import { spawn } from 'node:child_process'; +import { readFileSync, statSync } from 'node:fs'; +import { join } from 'node:path'; + +const ROOT = join(import.meta.dir, '..'); +const INIT = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'test', version: '1' } } }); + +export function handshake(cmd: string, args: string[], env: Record = {}, ms = 10_000): Promise<{ first: string; stderr: string }> { + return new Promise((res, rej) => { + const p = spawn(cmd, args, { cwd: ROOT, env: { ...process.env, STOREBOUND_NO_NETWORK: '1', ...env }, stdio: ['pipe', 'pipe', 'pipe'] }); + let out = '', err = ''; + const t = setTimeout(() => { p.kill(); rej(new Error(`no initialize answer in ${ms} ms; stdout: ${out.slice(0, 300)} stderr: ${err.slice(0, 300)}`)); }, ms); + p.stderr.on('data', d => { err += d; }); + p.stdout.on('data', d => { + out += d; + const nl = out.indexOf('\n'); + if (nl >= 0) { clearTimeout(t); p.kill(); res({ first: out.slice(0, nl), stderr: err }); } + }); + p.on('error', e => { clearTimeout(t); rej(e); }); + p.stdin.write(INIT + '\n'); + }); +} + +describe('mcp start-up (spawned)', () => { + test('bun cli/index.ts mcp answers initialize first on stdout', async () => { + const { first } = await handshake(process.execPath, [join(ROOT, 'cli/index.ts'), 'mcp']); + const r = JSON.parse(first); + expect(r.id).toBe(1); + expect(r.result.serverInfo.name).toBe('storebound'); + }, 15_000); + + test('the plugin launcher (bin/storebound) is executable, POSIX sh, and completes the handshake', async () => { + const bin = join(ROOT, 'bin/storebound'); + expect(readFileSync(bin, 'utf8').startsWith('#!/bin/sh\n')).toBe(true); + expect(statSync(bin).mode & 0o111).not.toBe(0); + const { first } = await handshake(bin, ['mcp']); + expect(JSON.parse(first).result.serverInfo.name).toBe('storebound'); + }, 15_000); + + test('.mcp.json never spawns a path that may not exist (falls back when the plugin root is missing)', async () => { + const m = JSON.parse(readFileSync(join(ROOT, '.mcp.json'), 'utf8')).mcpServers.storebound as { command: string; args: string[] }; + expect(m.command).toBe('sh'); + // a plugin root that is gone (an old cache folder): the script must still start a server, here from the repo's bin + const args = m.args.map(a => a.replaceAll('${CLAUDE_PLUGIN_ROOT:-}', '/nonexistent-plugin-root')); + const { first } = await handshake(m.command, args, { PATH: `${join(ROOT, 'bin')}:${process.env.PATH}` }); + expect(JSON.parse(first).result.serverInfo.name).toBe('storebound'); + }, 15_000); +}); diff --git a/tests/store-minimums.test.ts b/tests/store-minimums.test.ts new file mode 100644 index 0000000..61cb165 --- /dev/null +++ b/tests/store-minimums.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, test } from 'bun:test'; +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { appleMinSdk, appleSdkProblem, PLAY_TARGET_SDK_TABLE, playTargetSdk, playTargetSdkProblem, targetSdkFile } from '../cli/lib/store-minimums'; +import { readRegistry } from '../cli/lib/registry'; + +const ROOT = join(import.meta.dir, '..'); + +describe('Google Play target API level', () => { + test('the dated table picks the row in force', () => { + expect(playTargetSdk('phone', '2026-08-30')!.min).toBe(35); + expect(playTargetSdk('phone', '2026-08-31')!.min).toBe(36); + expect(playTargetSdk('wear', '2026-10-20')!.min).toBe(35); + expect(PLAY_TARGET_SDK_TABLE.map(r => r.since)).toEqual([...PLAY_TARGET_SDK_TABLE.map(r => r.since)].sort()); + }); + test('below the minimum: requirement, date and fix in one line', () => { + const m = playTargetSdkProblem(35, { date: '2026-10-20', where: 'android/variables.gradle' })!; + expect(m).toContain('targetSdkVersion 35 < 36'); + expect(m).toContain('2026-08-31'); + expect(m).toContain('set targetSdkVersion = 36'); + expect(m).toContain('android/variables.gradle'); + expect(playTargetSdkProblem(36, { date: '2026-10-20' })).toBeNull(); + expect(playTargetSdkProblem(undefined)).toBeNull(); + }); + test('the fix names the file that sets it (Capacitor variables.gradle)', () => { + const d = mkdtempSync(join(tmpdir(), 'sb-sdk-')); + mkdirSync(join(d, 'android')); + writeFileSync(join(d, 'android/variables.gradle'), 'ext {\n targetSdkVersion = 35\n}\n'); + expect(targetSdkFile(d)).toBe('android/variables.gradle'); + }); +}); + +describe('App Store minimum Xcode / SDK', () => { + test('table and IPA build fields', () => { + expect(appleMinSdk('2026-05-01')).toMatchObject({ xcode: 26, sdk: 26 }); + expect(appleMinSdk('2026-04-01')).toMatchObject({ xcode: 16, sdk: 18 }); + const m = appleSdkProblem({ xcode: '1640', sdkName: 'iphoneos18.4', platformVersion: '18.4' }, '2026-10-20')!; + expect(m).toContain('Xcode 16'); + expect(m).toContain('Xcode 26'); + expect(m).toContain('2026-04-28'); + expect(appleSdkProblem({ xcode: '2600', sdkName: 'iphoneos26.0', platformVersion: '26.0' }, '2026-10-20')).toBeNull(); + expect(appleSdkProblem({}, '2026-10-20')).toBeNull(); + }); +}); + +describe('apps folders add', () => { + const cli = (cwd: string, reg: string, ...args: string[]) => spawnSync(process.execPath, [join(ROOT, 'cli/index.ts'), ...args], { cwd, encoding: 'utf8', env: { ...process.env, STOREBOUND_REGISTRY: reg, STOREBOUND_NO_UPDATE: '1' } }); + const fresh = () => { + const d = mkdtempSync(join(tmpdir(), 'sb-folder-')); + writeFileSync(join(d, 'storebound.config.ts'), "export default { app: { name: 'Example App' }, apple: { bundleId: 'com.example.app' } };\n"); + return { d, reg: join(d, 'reg.json') }; + }; + test('a freshly init-ed folder is added (bare form = cwd), with a template note', () => { + const { d, reg } = fresh(); + const r = cli(d, reg, 'apps', 'folders', 'add'); + expect(r.status).toBe(0); + expect(readRegistry(reg).projects.map(p => p.path)).toEqual([readRegistry(reg).projects[0]!.path]); + expect(readRegistry(reg).projects[0]!.path.endsWith(d.split('/').pop()!)).toBe(true); + expect(r.stderr + r.stdout).toContain("'Example App'"); + }); + test('with a path, like apps add', () => { + const { d, reg } = fresh(); + expect(cli(tmpdir(), reg, 'apps', 'folders', 'add', d).status).toBe(0); + expect(JSON.parse(readFileSync(reg, 'utf8')).projects).toHaveLength(1); + }); + test('no config: refused with the reason and the fix', () => { + const d = mkdtempSync(join(tmpdir(), 'sb-empty-')); + const r = cli(d, join(d, 'reg.json'), 'apps', 'folders', 'add'); + expect(r.status).not.toBe(0); + expect(r.stderr).toContain('no storebound config'); + expect(r.stderr).toContain('storebound init'); + }); +}); diff --git a/tests/wave1.test.ts b/tests/wave1.test.ts index 7ccda59..21faa86 100644 --- a/tests/wave1.test.ts +++ b/tests/wave1.test.ts @@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test'; import { mkdtempSync, readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { generate, parseSkill, readSkills } from '../tools/gen-adapters'; +import { generate, MCP_LAUNCH, parseSkill, readSkills } from '../tools/gen-adapters'; import { scan } from '../tools/scrub'; import { FORBIDDEN_ARGS, listTools, LOCAL_WRITE_TOOLS, TOOLS, toArgv, validateInput } from '../cli/mcp-tools'; import { handle, LEGACY_PROTOCOL as PROTOCOL } from '../cli/mcp'; @@ -38,7 +38,7 @@ describe('adapters', () => { const version = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).version; for (const f of ['.claude-plugin/plugin.json', '.codex-plugin/plugin.json', 'gemini-extension.json']) expect(JSON.parse(out.get(f)!).version).toBe(version); expect(JSON.parse(out.get('.codex-plugin/plugin.json')!).skills).toBe('./skills/'); - expect(JSON.parse(out.get('.mcp.json')!).mcpServers.storebound).toEqual({ command: '${CLAUDE_PLUGIN_ROOT}/bin/storebound', args: ['mcp'] }); + expect(JSON.parse(out.get('.mcp.json')!).mcpServers.storebound).toEqual({ command: 'sh', args: ['-c', MCP_LAUNCH] }); expect(JSON.parse(out.get('gemini-extension.json')!).mcpServers.storebound.command).toContain('${extensionPath}'); expect(out.get('.cursor/rules/storebound.mdc')!).toMatch(/^---\ndescription: .+\nalwaysApply: false\n---\n/); }); diff --git a/tools/gen-adapters.ts b/tools/gen-adapters.ts index cba4d50..5df1481 100644 --- a/tools/gen-adapters.ts +++ b/tools/gen-adapters.ts @@ -40,6 +40,10 @@ const json = (o: unknown) => JSON.stringify(o, null, 2) + '\n'; const short = (d: string) => d.split(' - ')[0]!.split('. Use when')[0]!.replace(/\.$/, ''); /** Every generated file: path -> content. Pure apart from reading the sources. */ +/** The plugin's MCP start: the plugin's launcher, else storebound on PATH, else the npm package. */ +export const MCP_LAUNCH = 'r="${CLAUDE_PLUGIN_ROOT:-}"; if [ -n "$r" ] && [ -x "$r/bin/storebound" ]; then exec "$r/bin/storebound" mcp; fi; ' + + 'if command -v storebound >/dev/null 2>&1; then exec storebound mcp; fi; exec npx -y storebound@latest mcp'; + export function generate(root: string): Map { const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { version: string; description: string; license: string; keywords: string[] }; const core = readFileSync(join(root, 'docs', 'agents-core.md'), 'utf8').trim(); @@ -53,7 +57,9 @@ export function generate(root: string): Map { // 1. Claude Code plugin + its MCP server + marketplace out.set('.claude-plugin/plugin.json', json({ name: 'storebound', version: pkg.version, description, author: { name: 'CRTkafa' }, homepage, repository, license: pkg.license, keywords })); - out.set('.mcp.json', json({ mcpServers: { storebound: { command: '${CLAUDE_PLUGIN_ROOT}/bin/storebound', args: ['mcp'] } } })); + // through sh, never a direct path: a plugin root that is gone (an old cache folder after an update, or the repo opened + // as a project where CLAUDE_PLUGIN_ROOT is unset) made the client's spawn fail with ENOENT (pitfall: MCP spawn ENOENT) + out.set('.mcp.json', json({ mcpServers: { storebound: { command: 'sh', args: ['-c', MCP_LAUNCH] } } })); out.set('.claude-plugin/marketplace.json', json({ name: 'crtkafa', description: 'CRTkafa\'s open-sourced tools.', owner: { name: 'CRTkafa' }, plugins: [{ name: 'storebound', source: '.', description: 'Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.', version: pkg.version, category: 'development', tags: ['mobile', 'google-play', 'app-store', 'release'] }] })); From 3949ff153120fa47bef9a14c44f70105794504c8 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 12:16:54 +0700 Subject: [PATCH 042/344] storebound 0.8.16: version in package.json and every copy, CHANGELOG 0.8.16 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 9a16463..5799a2c 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.15", + "version": "0.8.16", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index d8722ec..e247d8f 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.15", + "version": "0.8.16", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 9ed2fcc..6734b58 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.15", + "version": "0.8.16", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index f4c031a..de9d320 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.16 · 2026-10-20 + - `apps folders add []` adds the folder (it listed and added nothing); a template config is added with a note, a folder without a config is refused with the reason and the fix (pitfall 81). - MCP: the plugin's `.mcp.json` no longer spawns a plugin path that may be gone (ENOENT, CONNECTION_CLOSED): it falls diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 1efa684..6276d92 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.15", + "version": "0.8.16", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index f96a802..0d16247 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4010,7 +4010,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.15" +version = "0.8.16" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index a91836f..dda0034 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.15" +version = "0.8.16" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 109d583..d51f8da 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.15", + "version": "0.8.16", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index 72f1757..136c778 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.15", + "version": "0.8.16", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index cf2b2c4..01bca1a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.15", + "version": "0.8.16", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From e1e4e05237137c5d9c19d530372cd13090e20740 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 12:41:43 +0700 Subject: [PATCH 043/344] shots capture: signed-in web apps (shots.capture.auth request with ${cred:}/${env:} references or storageState), shots login saves a demo sign-in to .storebound/auth.json (0600), expired-session warning, secrets and cookies masked --- CHANGELOG.md | 7 + cli/commands.ts | 3 +- cli/data/flags.json | 10 ++ cli/lib/config.ts | 6 + cli/mcp-tools.ts | 2 +- cli/shots/auth.ts | 179 ++++++++++++++++++++++++++ cli/shots/capture-web.ts | 20 ++- cli/shots/capture.ts | 9 +- cli/shots/devices.ts | 2 + cli/shots/login.ts | 72 +++++++++++ docs/commands.md | 3 +- docs/store-art.md | 6 +- skills/store-screenshots/SKILL.md | 27 +++- tests/browser/capture-auth.browser.ts | 122 ++++++++++++++++++ tests/capture-auth.test.ts | 86 +++++++++++++ 15 files changed, 545 insertions(+), 9 deletions(-) create mode 100644 cli/shots/auth.ts create mode 100644 cli/shots/login.ts create mode 100644 tests/browser/capture-auth.browser.ts create mode 100644 tests/capture-auth.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index de9d320..8873538 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +- `shots capture --source web` can sign in first: `shots.capture.auth` is a sign-in request (run once per browser + context, cookies kept; body and headers use `${cred:NAME}` from `.storebound/credentials.json` or `${env:NAME}`, + literal secrets are refused, a failed status stops with the status only) or a `storageState` file. `storebound shots + login` opens a fresh visible browser for a demo sign-in by hand and saves `.storebound/auth.json` (0600, counts + only). A shot that lands on a sign-in page warns "session expired? run storebound shots login again". Secrets and + cookie values are masked in logs and the capture report. + ## 0.8.16 · 2026-10-20 - `apps folders add []` adds the folder (it listed and added nothing); a template config is added with a note, diff --git a/cli/commands.ts b/cli/commands.ts index 17cf3b3..8014f55 100644 --- a/cli/commands.ts +++ b/cli/commands.ts @@ -92,7 +92,8 @@ export const COMMANDS: Record Promise, string]> = { 'apple ppo': [() => import('./apple/ppo'), 'Product Page Optimization: status | create --variant b | upload --variant b | start | stop (asks first)'], 'apple testflight': [() => import('./apple/testflight'), 'TestFlight: status | groups | testers (CSV in .storebound/) | what-to-test --build N | info | distribute --build N --group g [--submit-review] | wait --build N | expire --keep N|--older-than D (asks)'], 'icons': [() => import('./icons'), 'App Store / Play / web / adaptive / legacy launcher icons from one artwork'], - 'shots capture': [() => import('./shots/capture'), 'raw frames: --source web (playwright) | ios-sim (simctl) | android-emu (adb) | folder; --dry'], + 'shots capture': [() => import('./shots/capture'), 'raw frames: --source web (playwright; signed-in apps: shots.capture.auth) | ios-sim (simctl) | android-emu (adb) | folder; --dry'], + 'shots login': [() => import('./shots/login'), 'opens a visible browser (fresh profile) at shots.capture.baseUrl or --url; you sign in to a demo account by hand, Enter saves .storebound/auth.json (0600) for shots.capture.auth.storageState; --timeout '], 'shots fonts': [() => import('./shots/fonts'), 'download font subsets for the copy (CJK / Arabic / Cyrillic ...)'], 'shots render': [() => import('./shots/render'), 'store screenshots + feature graphic in every size and language'], 'shots jpeg': [() => import('./shots/jpeg'), 'JPEG q92 copies of the Play renders (4x faster uploads)'], diff --git a/cli/data/flags.json b/cli/data/flags.json index 3787556..37834d6 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -806,6 +806,12 @@ "variant", "variants" ], + "shots login": [ + "headless", + "out", + "timeout", + "url" + ], "shots record": [ "concurrency", "device", @@ -983,6 +989,7 @@ "godot", "group", "halt", + "headless", "home", "hook", "icon", @@ -1479,6 +1486,9 @@ "shots jpeg": [ "storebound shots jpeg [--q 92] [--lang en,tr] [--variant b | --variants]" ], + "shots login": [ + "storebound shots login [--url ] [--out .storebound/auth.json] [--timeout 900]" + ], "shots record": [ "storebound shots record [--lang en,tr] [--only intro,combo] [--source web|ios-sim|android-emu|folder] [--dry] [--keep-booted]" ], diff --git a/cli/lib/config.ts b/cli/lib/config.ts index b7a0287..445e508 100644 --- a/cli/lib/config.ts +++ b/cli/lib/config.ts @@ -200,6 +200,8 @@ export interface ShotSpec { extras?: Record; } +export type { CaptureAuth } from '../shots/auth'; +import type { CaptureAuth } from '../shots/auth'; export interface ShotsCapture { /** Where frames come from. Default "web". */ source?: 'web' | 'ios-sim' | 'android-emu' | 'folder'; @@ -254,6 +256,10 @@ export interface ShotsCapture { /** Web: files or folders of the app build (e.g. "apps/game/src" or "apps/game/dist") hashed into the capture cache, * so a code change re-captures. Default: the HTML at baseUrl and the scripts it loads. */ build?: string | string[]; + /** Web: sign in before the shots (apps whose key screens are behind a login; use a demo account on a local or demo + * backend with fabricated data). { request: { url, method, headers, body } } with "${cred:NAME}" / "${env:NAME}" + * references (never literal secrets), or { storageState: ".storebound/auth.json" } from `storebound shots login`. */ + auth?: CaptureAuth; shots: Record; } diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index 9a40eda..d637967 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -222,7 +222,7 @@ export const TOOLS: ToolDef[] = [ props: { action: { type: 'string', enum: ['on', 'pause'] }, version: { type: 'string' }, platform }, required: ['action'], args: i => ['--phased', String(i.action), ...opt('version', i.version), ...opt('platform', i.platform)] }, { name: 'shots_capture', title: 'Capture raw frames', command: ['shots', 'capture'], write: true, network: false, idempotent: true, - description: 'Raw app or game frames per language into shots.frames from a web build (Playwright), the iOS Simulator (simctl), an Android emulator / device (adb) or a folder check. Local files only; a simulator it boots is shut down again, an emulator is never booted. dry_run lists the plan and the simctl / adb commands.', + description: 'Raw app or game frames per language into shots.frames from a web build (Playwright), the iOS Simulator (simctl), an Android emulator / device (adb) or a folder check. Web apps behind a sign-in: shots.capture.auth (a sign-in request with ${cred:NAME} / ${env:NAME} references, or a storageState from the terminal-only `storebound shots login`, where the owner signs in to a demo account by hand); secrets and cookies are masked. Local files only; a simulator it boots is shut down again, an emulator is never booted. dry_run lists the plan and the simctl / adb commands.', props: { lang, only: { type: 'string', description: 'Comma-separated shot names' }, device: { type: 'string', enum: ['phone', 'tablet'] }, source, concurrency: { type: 'integer', minimum: 1, maximum: 32, description: 'Web: parallel browser contexts (default from the CPU count)' }, mode: { type: 'string', enum: ['changed', 'only-missing', 'force'], default: 'changed', description: 'Web: skip frames with unchanged inputs (default), only missing ones, or capture all' } }, diff --git a/cli/shots/auth.ts b/cli/shots/auth.ts new file mode 100644 index 0000000..ca8bd5f --- /dev/null +++ b/cli/shots/auth.ts @@ -0,0 +1,179 @@ +// Signed-in web capture (shots.capture.auth). Two ways in, applied to every browser context before its first shot: +// request { request: { url, method?, headers?, body? } }: one HTTP call per context through the context's own +// request API, so the cookies it sets stay in that context. Secrets are references only: +// "${cred:NAME}" (.storebound/credentials.json: reviewDemoAccount.username / .password, the same with +// REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD from the environment, or captureAuth.NAME) or "${env:NAME}". +// A password-like key with a literal value is refused. A non-2xx/3xx status stops the capture with the +// status, never the values. +// storageState { storageState: ".storebound/auth.json" }: Playwright storage state (cookies + localStorage) saved by +// `storebound shots login`, loaded into every context. It must live in .storebound/ (gitignored). +// Resolved values are collected so every log line, error and report text can be masked (maskSecrets). +import { existsSync, readFileSync } from 'node:fs'; +import { join, resolve as resolvePath } from 'node:path'; +import { reviewDemoAccount } from '../lib/credentials'; + +export interface AuthRequest { + /** Absolute URL, or a path after shots.capture.baseUrl (e.g. "/api/login"). */ + url: string; + /** Default POST. */ + method?: string; + headers?: Record; + /** An object is sent as JSON, a string as is. Secrets as "${cred:NAME}" / "${env:NAME}" only. */ + body?: Record | string; +} +export interface CaptureAuth { + request?: AuthRequest; + /** Playwright storage state file in .storebound/ (from `storebound shots login`). */ + storageState?: string; + /** Pattern (regex source) of the login page URL; a shot that lands there warns. Default /login|signin|sign-in|auth/. */ + loginUrl?: string; +} + +export const DEFAULT_STATE = '.storebound/auth.json'; +const REF = /\$\{(cred|env):([A-Za-z0-9_.-]+)\}/g; +const SECRET_KEY = /pass(word)?|pwd|secret|token|api[-_]?key|authorization|cookie|session|otp|pin$|credential/i; + +/** Problems with shots.capture.auth (pure): shape, a gitignored state path, and literal secrets. */ +export function validateAuth(a: CaptureAuth | undefined): string[] { + if (!a) return []; + const e: string[] = []; + if (!!a.request === !!a.storageState) e.push('shots.capture.auth: either { request: { url, method, headers, body } } or { storageState: ".storebound/auth.json" }'); + if (a.storageState && !/^\.storebound[\\/]/.test(a.storageState)) e.push('shots.capture.auth.storageState: a file in .storebound/ (gitignored), e.g. ".storebound/auth.json"'); + if (a.request) { + if (!a.request.url) e.push('shots.capture.auth.request.url: the sign-in endpoint (absolute, or a path after baseUrl)'); + for (const k of literalSecrets(a.request)) e.push(`shots.capture.auth.request.${k}: a secret is never written in the config; use "\${cred:NAME}" (.storebound/credentials.json) or "\${env:NAME}"`); + } + if (a.loginUrl) try { new RegExp(a.loginUrl); } catch { e.push('shots.capture.auth.loginUrl: a regular expression'); } + return e; +} + +/** Paths (headers.X, body.y) whose key looks like a secret but whose value is not only references. */ +export function literalSecrets(r: AuthRequest): string[] { + const out: string[] = []; + const literal = (v: unknown): boolean => typeof v === 'string' ? v.replace(REF, '').replace(/^(Bearer|Basic|Token)\s+/i, '').trim() !== '' : v !== undefined && v !== null && typeof v !== 'object'; + const walk = (o: unknown, path: string): void => { + if (!o || typeof o !== 'object') return; + for (const [k, v] of Object.entries(o as Record)) { + if (v && typeof v === 'object') walk(v, `${path}.${k}`); + else if (SECRET_KEY.test(k) && literal(v)) out.push(`${path}.${k}`); + } + }; + walk(r.headers, 'headers'); + if (typeof r.body === 'string') { + // a form or JSON string body: check its fields the same way + let parsed: unknown = null; + try { parsed = JSON.parse(r.body); } catch { if (r.body.includes('=')) parsed = Object.fromEntries(new URLSearchParams(r.body)); } + walk(parsed, 'body'); + } else walk(r.body, 'body'); + return out; +} + +/** Where references resolve: credentials.json (reviewDemoAccount, captureAuth) and the environment. */ +export function credLookup(root: string, env: Record = process.env): (kind: 'cred' | 'env', name: string) => string | undefined { + let store: Record | null = null; + const file = (): Record => { + if (store) return store; + const p = join(root, '.storebound', 'credentials.json'); + try { store = existsSync(p) ? JSON.parse(readFileSync(p, 'utf8')) as Record : {}; } catch { store = {}; } + return store; + }; + return (kind, name) => { + if (kind === 'env') return env[name] || undefined; + if (name === 'reviewDemoAccount.username' || name === 'reviewDemoAccount.password') { + const eu = env.REVIEW_DEMO_USER, ep = env.REVIEW_DEMO_PASSWORD; + const d = eu && ep ? { username: eu, password: ep } : reviewDemoAccount(root); + return d ? (name.endsWith('username') ? d.username : d.password) : undefined; + } + const ca = file().captureAuth as Record | undefined; + const v = ca?.[name.replace(/^captureAuth\./, '')]; + return typeof v === 'string' && v ? v : undefined; + }; +} + +/** Replaces every reference; collects the values into `secrets`. A missing one throws with its NAME only. */ +export function resolveRefs(text: string, lookup: ReturnType, secrets: Set): string { + return text.replace(REF, (_m, kind: 'cred' | 'env', name: string) => { + const v = lookup(kind, name); + if (v === undefined) throw new Error(kind === 'env' ? `shots.capture.auth: environment variable ${name} is not set` : `shots.capture.auth: \${cred:${name}} is not in .storebound/credentials.json (reviewDemoAccount { username, password } or captureAuth { "${name.replace(/^captureAuth\./, '')}": ... })`); + secrets.add(v); + return v; + }); +} + +const deepResolve = (v: unknown, f: (s: string) => string): unknown => + typeof v === 'string' ? f(v) : Array.isArray(v) ? v.map(x => deepResolve(x, f)) : v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, deepResolve(x, f)])) : v; + +export interface ResolvedRequest { url: string; method: string; headers: Record; body?: string } +/** The sign-in request with references resolved (values only in memory, listed in `secrets`). */ +export function resolveRequest(r: AuthRequest, baseUrl: string, lookup: ReturnType, secrets: Set): ResolvedRequest { + const f = (s: string) => resolveRefs(s, lookup, secrets); + const headers = deepResolve(r.headers ?? {}, f) as Record; + let body: string | undefined; + if (typeof r.body === 'string') body = f(r.body); + else if (r.body) { body = JSON.stringify(deepResolve(r.body, f)); if (!Object.keys(headers).some(h => h.toLowerCase() === 'content-type')) headers['content-type'] = 'application/json'; } + const url = /^https?:\/\//.test(r.url) ? f(r.url) : baseUrl.replace(/\/$/, '') + f(r.url); + return { url, method: (r.method ?? 'POST').toUpperCase(), headers, ...(body !== undefined ? { body } : {}) }; +} + +/** Hides every resolved secret (and its URL-encoded form) in a text. */ +export function maskSecrets(text: string, secrets: Iterable): string { + let out = text; + for (const s of secrets) if (s.length >= 3) for (const form of new Set([s, encodeURIComponent(s)])) out = out.split(form).join('***'); + return out; +} + +/** URL for a log line: origin + path only (a query can carry a token). */ +export const safeUrl = (u: string): string => { try { const x = new URL(u); return x.origin + x.pathname; } catch { return u.split('?')[0]!; } }; + +/** A shot that wanted `want` but shows a login page. */ +export function landedOnLogin(want: string, got: string, pattern?: string): boolean { + const re = new RegExp(pattern ?? '(^|[/._-])(login|log-in|signin|sign-in|sign_in|auth)([/._?-]|$)', 'i'); + try { + const w = new URL(want), g = new URL(got); + if (w.pathname === g.pathname) return false; + return re.test(g.pathname + g.search) && !re.test(w.pathname); + } catch { return false; } +} +export const expiredHint = (url: string): string => `${safeUrl(url)} is a sign-in page: session expired? run storebound shots login again`; + +/* eslint-disable @typescript-eslint/no-explicit-any */ +export interface AuthPlan { + /** Extra newContext options (storageState). */ + contextOptions: Record; + /** Signs a fresh context in (request auth); a no-op for storageState. */ + prepare: (context: any) => Promise; + secrets: Set; + loginUrl?: string; +} + +/** Builds the per-context sign-in from shots.capture.auth. Throws before any browser starts when something is missing. */ +export function authPlan(a: CaptureAuth, o: { root: string; baseUrl: string; env?: Record }): AuthPlan { + const problems = validateAuth(a); + if (problems.length) throw new Error(problems.join('\n ')); + const secrets = new Set(); + if (a.storageState) { + const p = resolvePath(o.root, a.storageState); + if (!existsSync(p)) throw new Error(`shots.capture.auth.storageState: ${a.storageState} does not exist; run storebound shots login (sign in to a demo account by hand)`); + let state: { cookies?: { value?: string }[] }; + try { state = JSON.parse(readFileSync(p, 'utf8')) as typeof state; } catch { throw new Error(`shots.capture.auth.storageState: ${a.storageState} is not a Playwright storage state; run storebound shots login again`); } + for (const c of state.cookies ?? []) if (c.value && c.value.length >= 6) secrets.add(c.value); + return { contextOptions: { storageState: p }, prepare: async () => {}, secrets, ...(a.loginUrl ? { loginUrl: a.loginUrl } : {}) }; + } + const req = resolveRequest(a.request!, o.baseUrl, credLookup(o.root, o.env), secrets); + return { + contextOptions: {}, secrets, ...(a.loginUrl ? { loginUrl: a.loginUrl } : {}), + prepare: async (context: any) => { + let status = 0; + try { + const r = await context.request.fetch(req.url, { method: req.method, headers: req.headers, ...(req.body !== undefined ? { data: req.body } : {}), timeout: 30_000, maxRedirects: 0 }); + status = r.status(); + await r.dispose?.(); + } catch (e) { throw new Error(`sign-in request ${req.method} ${safeUrl(maskSecrets(req.url, secrets))} failed: ${maskSecrets((e as Error).message.split('\n')[0]!, secrets).slice(0, 200)}`); } + if (status < 200 || status >= 400) throw new Error(`sign-in request ${req.method} ${safeUrl(maskSecrets(req.url, secrets))} returned HTTP ${status} (check the demo account in .storebound/credentials.json and shots.capture.auth.request; values not shown)`); + // the session cookies it set are masked like the request values + const cookies = await context.cookies(); + for (const c of cookies) if (c.value && c.value.length >= 6) secrets.add(c.value); + }, + }; +} +/* eslint-enable @typescript-eslint/no-explicit-any */ diff --git a/cli/shots/capture-web.ts b/cli/shots/capture-web.ts index 33a1dd4..516c798 100644 --- a/cli/shots/capture-web.ts +++ b/cli/shots/capture-web.ts @@ -11,6 +11,9 @@ // size, session, the copy text of its language, the app build (shots.capture.build files, else // the HTML and scripts at baseUrl), fonts.css). Unchanged frames that exist are skipped; // --only-missing only captures frames that do not exist; --force captures everything. +// auth shots.capture.auth (auth.ts): every new context is signed in before its first shot (request +// auth through the context's request API, or a storageState file); a shot that lands on a login +// page warns; resolved secrets and cookie values are masked in every log line and the report. // timing per frame: goto, waitFor, eval, delay, screenshot, total, in the progress line and in // .storebound/capture-report.json, with the slowest frames and steps at the end. import { createHash } from 'node:crypto'; @@ -19,6 +22,7 @@ import { availableParallelism, cpus } from 'node:os'; import { join } from 'node:path'; import type { ShotSpec, ShotsCapture } from '../lib/config'; import { log, warn } from '../lib/log'; +import { type AuthPlan, expiredHint, landedOnLogin, maskSecrets, safeUrl } from './auth'; import { shotsFor } from './devices'; import type { FrameDims } from './lib'; @@ -132,7 +136,10 @@ export interface CaptureReport { /* eslint-disable @typescript-eslint/no-explicit-any */ /** Captures the jobs in a browser: per-shot contexts, or one page per language + device in per-language sessions. */ -export async function captureWeb(browser: any, cap: ShotsCapture, jobs: WebJob[], o: { concurrency: number; dims: Record }): Promise { +export async function captureWeb(browser: any, cap: ShotsCapture, jobs: WebJob[], o: { concurrency: number; dims: Record; auth?: AuthPlan }): Promise { + const auth = o.auth; + const mask = (t: string): string => (auth ? maskSecrets(t, auth.secrets) : t); + const expired = new Set(); const started = Date.now(); const perLang = cap.session === 'per-language'; const report: CaptureReport['frames'] = []; @@ -140,7 +147,9 @@ export async function captureWeb(browser: any, cap: ShotsCapture, jobs: WebJob[] const total = jobs.length; const newPage = async (j: WebJob): Promise<{ c: any; page: any; errs: string[] }> => { const d = o.dims[j.device]; - const c = await browser.newContext({ viewport: { width: d.w, height: d.h }, deviceScaleFactor: d.dpr, hasTouch: true, isMobile: true, serviceWorkers: 'block', locale: j.lang }); + const c = await browser.newContext({ viewport: { width: d.w, height: d.h }, deviceScaleFactor: d.dpr, hasTouch: true, isMobile: true, serviceWorkers: 'block', locale: j.lang, ...(auth?.contextOptions ?? {}) }); + // sign in once per context, cookies kept in it (request auth); a failed sign-in stops the whole capture + if (auth) try { await auth.prepare(c); } catch (e) { await c.close(); throw Object.assign(new Error(mask((e as Error).message)), { authFailed: true }); } const page = await c.newPage(); const errs: string[] = []; page.on('pageerror', (e: Error) => errs.push(e.message)); @@ -152,6 +161,11 @@ export async function captureWeb(browser: any, cap: ShotsCapture, jobs: WebJob[] if (how === 'goto') await s.page.goto(j.url, { waitUntil: 'domcontentloaded', timeout: 90000 }); else await s.page.evaluate(`(p => { if (location.pathname + location.search !== p) { history.pushState(null, '', p); dispatchEvent(new PopStateEvent('popstate', { state: null })); } })(${JSON.stringify(j.path)})`); t.goto = Date.now() - t0; t0 = Date.now(); + if (auth && landedOnLogin(j.url, s.page.url(), auth.loginUrl)) { + // a sign-in page is never a store frame: warn once per login URL, fail this shot now (no waitFor timeout) + if (!expired.has(safeUrl(s.page.url()))) { expired.add(safeUrl(s.page.url())); warn('shots', `${j.lang}/${j.device}/${j.name}: ${mask(expiredHint(s.page.url()))}`); } + throw new Error(`landed on the sign-in page ${safeUrl(s.page.url())}`); + } if (j.spec.waitFor) await s.page.waitForFunction(j.spec.waitFor, null, { timeout: waitTimeout, polling: 50 }); t.waitFor = Date.now() - t0; t0 = Date.now(); for (const js of j.spec.eval ?? []) await s.page.evaluate(js); @@ -166,6 +180,8 @@ export async function captureWeb(browser: any, cap: ShotsCapture, jobs: WebJob[] }; const record = (j: WebJob, r: { ok: boolean; reused: boolean; timing: Timing; error?: string; errs?: string[] }): void => { finished++; + if (r.error) r.error = mask(r.error); + if (r.errs) r.errs = r.errs.map(mask); report.push({ frame: j.frame, ok: r.ok, reused: r.reused, timing: r.timing, ...(r.error ? { error: r.error } : {}) }); const head = `${progressLine(finished, total, started)} ${j.lang}/${j.device}/${j.name}`; if (r.ok) log('shots', `${head}.png ${r.reused ? '(reused page) ' : ''}${timingText(r.timing)}${r.errs?.length ? ' (page errors: ' + r.errs.join(' | ').slice(0, 200) + ')' : ''}`); diff --git a/cli/shots/capture.ts b/cli/shots/capture.ts index 0b014fc..b82d0e3 100644 --- a/cli/shots/capture.ts +++ b/cli/shots/capture.ts @@ -6,7 +6,8 @@ // web headless Chromium (playwright), mobile viewport + touch at phone / tablet size. Each shot: // { path, waitFor?: JS expression that turns true, eval?: [JS], delayMs?, device? }; URL = baseUrl + path + // query, "{lang}" replaced. Parallel contexts, per-language page reuse, the input-hash cache and the -// per-frame timing (goto / waitFor / eval / delay / screenshot): capture-web.ts. +// per-frame timing (goto / waitFor / eval / delay / screenshot): capture-web.ts. Signed-in apps: +// shots.capture.auth (a sign-in request or a storageState from `storebound shots login`), auth.ts. // ios-sim xcrun simctl: boots the simulator (ios.device / ios.devices.tablet), optional install of ios.app, status // bar 9:41 / full battery / full bars, one warm-up launch after a cold boot (ios.warmupMs), then per shot: // launch ios.bundleId with -AppleLanguages (xx) -AppleLocale + ios.args + shot.args, open shot.url @@ -37,6 +38,7 @@ import { adbAppLocaleArgs, adbDemoExitArgs, adbDemoModeArgs, adbForceStopArgs, a import { type CopyFile, copyText, type FrameDims, frameDims } from './lib'; import { captureWeb, defaultConcurrency, hashPaths, hashServed, planWeb, readCache, selectJobs, summaryLines, writeCaptureState } from './capture-web'; import { imageInfo } from './spec'; +import { authPlan, safeUrl } from './auth'; import * as rt from '../lib/rt'; type Device = 'phone' | 'tablet'; @@ -121,9 +123,12 @@ export async function run(ctx: Ctx): Promise { if (source === 'web') { if (dry) { for (const lang of langs) for (const device of devices) for (const [name, s] of shotsFor(cap, device, only)) progress(`${lang}/${device}/${name}.png <- ${cap.baseUrl}${(s.path ?? '/').replaceAll('{lang}', lang)}`); + if (cap.auth) log('shots', cap.auth.storageState ? `would load the signed-in state from ${cap.auth.storageState} into every context` : `would sign every context in first: ${(cap.auth.request?.method ?? 'POST').toUpperCase()} ${safeUrl(cap.auth.request?.url ?? '')} (values from .storebound/credentials.json / env, never shown)`); return done('shots', `capture planned (dry run): ${total} frames from web`); } need(cap.baseUrl, 'shots.capture.baseUrl'); + const auth = cap.auth ? authPlan(cap.auth, { root, baseUrl: cap.baseUrl! }) : undefined; + if (auth) log('shots', cap.auth!.storageState ? `signed in from ${cap.auth!.storageState}` : `signing every context in: ${(cap.auth!.request!.method ?? 'POST').toUpperCase()} ${safeUrl(cap.auth!.request!.url)}`); const concurrency = a.num('concurrency', cap.concurrency ?? defaultConcurrency('capture')); const builds = cap.build ? (Array.isArray(cap.build) ? cap.build : [cap.build]).map(p => resolve(p)) : []; const build = builds.length ? hashPaths(builds) : await hashServed(cap.baseUrl!); @@ -139,7 +144,7 @@ export async function run(ctx: Ctx): Promise { if (todo.length) { const browser = await launch(root, { headless: true, args: ['--mute-audio', '--ignore-gpu-blocklist', '--enable-webgl', '--enable-gpu'] }); let report; - try { report = await captureWeb(browser, cap, todo, { concurrency, dims }); } finally { await closeBrowser(browser); } // capped close, then kill: Chrome can hang 10-30 s in its shutdown + try { report = await captureWeb(browser, cap, todo, { concurrency, dims, ...(auth ? { auth } : {}) }); } finally { await closeBrowser(browser); } // capped close, then kill: Chrome can hang 10-30 s in its shutdown report.skipped = skipped.map(j => j.frame); writeCaptureState(root, report, cache, todo); for (const l of summaryLines(report)) log('shots', l); diff --git a/cli/shots/devices.ts b/cli/shots/devices.ts index ec2167f..3b2fab0 100644 --- a/cli/shots/devices.ts +++ b/cli/shots/devices.ts @@ -7,6 +7,7 @@ // exec-out screencap. Emulator or a USB device. // folder bring your own frames: ///.png, checked for size. import type { ShotsCapture, ShotSpec, VideoRecord } from '../lib/config'; +import { validateAuth } from './auth'; export type Source = 'web' | 'ios-sim' | 'android-emu' | 'folder'; export const SOURCES: Source[] = ['web', 'ios-sim', 'android-emu', 'folder']; @@ -29,6 +30,7 @@ export function validateCapture(c: ShotsCapture | undefined): string[] { } if (c.ios?.warmupMs !== undefined && !(Number.isInteger(c.ios.warmupMs) && c.ios.warmupMs >= 0)) e.push('shots.capture.ios.warmupMs: milliseconds (integer >= 0)'); if (c.concurrency !== undefined && !(Number.isInteger(c.concurrency) && c.concurrency >= 1 && c.concurrency <= 32)) e.push('shots.capture.concurrency: integer 1-32'); + if (c.auth) e.push(...validateAuth(c.auth)); if (c.session !== undefined && !['per-shot', 'per-language'].includes(c.session)) e.push('shots.capture.session: per-shot | per-language'); if (c.reuseTimeoutMs !== undefined && !(Number.isInteger(c.reuseTimeoutMs) && c.reuseTimeoutMs > 0)) e.push('shots.capture.reuseTimeoutMs: milliseconds (integer > 0)'); if (src === 'android-emu' && !c.android?.package) e.push('shots.capture.android.package: application id (source android-emu)'); diff --git a/cli/shots/login.ts b/cli/shots/login.ts new file mode 100644 index 0000000..841f265 --- /dev/null +++ b/cli/shots/login.ts @@ -0,0 +1,72 @@ +// storebound shots login [--url ] [--out .storebound/auth.json] [--timeout 900] +// Opens a visible browser with a fresh, empty profile at shots.capture.baseUrl (or --url) so the owner signs in to a +// DEMO account by hand (storebound never types credentials). Press Enter in the terminal, or close the window, and the +// Playwright storage state (cookies + localStorage) is written to .storebound/auth.json (0600) for +// shots.capture.auth.storageState. Only counts are printed, never cookie values. The wait has a timeout (default +// 15 min) and a heartbeat line every 30 s. +import { chmodSync, mkdirSync, writeFileSync } from 'node:fs'; +import { dirname, relative } from 'node:path'; +import type { Ctx } from '../lib/ctx'; +import { done, log, warn } from '../lib/log'; +import { DEFAULT_STATE, safeUrl } from './auth'; +import { closeBrowser, launch } from './browser'; + +export interface StorageState { cookies: { name: string; value: string; domain: string }[]; origins: { origin: string; localStorage: unknown[] }[] } + +/** What the confirmation says (counts and domains, never values). */ +export function stateSummary(s: StorageState): string { + const domains = [...new Set(s.cookies.map(c => c.domain.replace(/^\./, '')))].sort(); + return `${s.cookies.length} cookie${s.cookies.length === 1 ? '' : 's'}${domains.length ? ` (${domains.join(', ')})` : ''}, ${s.origins.length} origin${s.origins.length === 1 ? '' : 's'} with local storage`; +} + +export function writeState(file: string, s: StorageState): void { + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify(s, null, 1) + '\n', { mode: 0o600 }); + chmodSync(file, 0o600); +} + +export async function run(ctx: Ctx): Promise { + const { config, root, resolve } = ctx.loaded; + const a = ctx.args; + const url = a.get('url') ?? config.shots?.capture?.baseUrl; + if (!url || !/^https?:\/\//.test(url)) throw new Error('shots login: --url , or shots.capture.baseUrl in the config'); + const outRel = a.get('out') ?? config.shots?.capture?.auth?.storageState ?? DEFAULT_STATE; + if (!/^\.storebound[\\/]/.test(outRel)) throw new Error('shots login --out: a file in .storebound/ (gitignored), e.g. .storebound/auth.json'); + const out = resolve(outRel); + const timeoutMs = a.num('timeout', 900) * 1000; + // hidden, for tests: headless (no window) and Enter on stdin still ends it + const headless = a.has('headless'); + if (a.has('dry')) return done('shots', `would open ${safeUrl(url)} in a fresh browser profile; after you sign in to a demo account, Enter saves ${outRel} (0600)`); + + const browser = await launch(root, { headless, args: ['--mute-audio'] }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let context: any; + let last: StorageState | null = null; + try { + context = await browser.newContext({ viewport: null, serviceWorkers: 'block' }); + const page = await context.newPage(); + await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60_000 }).catch((e: Error) => warn('shots', `could not open ${safeUrl(url)}: ${e.message.split('\n')[0]}`)); + log('shots', `opened ${safeUrl(url)} in a fresh browser profile. Sign in to a DEMO account (fabricated data, never a real user's) by hand, then press Enter here (or close the window). Timeout ${Math.round(timeoutMs / 1000)} s.`); + const started = Date.now(); + const snapshot = async (): Promise => { try { last = await context.storageState() as StorageState; } catch { /* context gone */ } }; + const reason = await new Promise<'enter' | 'closed' | 'timeout'>(res => { + const finish = (r: 'enter' | 'closed' | 'timeout'): void => { clearInterval(beat); clearInterval(snap); clearTimeout(t); process.stdin.off('data', onData); process.stdin.pause(); res(r); }; + const onData = (b: Buffer): void => { if (b.toString().includes('\n')) finish('enter'); }; + process.stdin.on('data', onData); process.stdin.resume(); + const snap = setInterval(() => { void snapshot(); }, 2000); + const beat = setInterval(() => log('shots', `waiting for the sign-in (${Math.round((Date.now() - started) / 1000)} s of ${Math.round(timeoutMs / 1000)} s): press Enter when signed in`), 30_000); + const t = setTimeout(() => finish('timeout'), timeoutMs); + page.on('close', () => { if (!context.pages().length) finish('closed'); }); + browser.on('disconnected', () => finish('closed')); + }); + if (reason === 'timeout') throw new Error(`shots login: no Enter within ${Math.round(timeoutMs / 1000)} s; nothing saved (--timeout )`); + if (reason === 'enter') await snapshot(); + const state = last as StorageState | null; + if (!state) throw new Error('shots login: the browser closed before its sign-in state could be read; run it again and press Enter before closing the window'); + writeState(out, state); + if (!state.cookies.length && !state.origins.length) warn('shots', 'no cookies and no local storage were saved: was the sign-in finished?'); + done('shots', `saved ${relative(root, out) || out} (0600): ${stateSummary(state)}. Set shots.capture.auth = { storageState: "${outRel}" }`); + } finally { + await closeBrowser(browser); + } +} diff --git a/docs/commands.md b/docs/commands.md index 4c00820..7f51fe7 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -140,7 +140,8 @@ run in the background with a log (`storebound shots render > .storebound/render. | command | kind | what | |---|---|---| -| `shots capture [--source web\|ios-sim\|android-emu\|folder] [--concurrency N] [--only-missing \| --force]` | local | raw frames from your running app or game; web: parallel contexts, optional one boot per language (`capture.session`), skips unchanged frames, timing per step | +| `shots capture [--source web\|ios-sim\|android-emu\|folder] [--concurrency N] [--only-missing \| --force]` | local | raw frames from your running app or game; web: parallel contexts, optional one boot per language (`capture.session`), skips unchanged frames, timing per step; signed-in apps: `capture.auth` (a sign-in request with `${cred:NAME}` / `${env:NAME}` references, or `storageState`) | +| `shots login [--url ] [--timeout ]` | local | opens a visible browser with a fresh profile; you sign in to a demo account by hand, Enter saves `.storebound/auth.json` (0600) for `capture.auth.storageState`; prints counts only | | `shots fonts` | network | font subsets for your copy (Noto for CJK / Arabic / Cyrillic / Devanagari ...), your own local font files, and the glyph coverage check per language | | `shots render [--variant b \| --variants] [--concurrency N]` | local | every store size and language in the game or app style, feature graphic, contact sheet, overflow report | | `shots jpeg` | local | JPEG q92 copies of the Play renders (about 4x faster uploads) | diff --git a/docs/store-art.md b/docs/store-art.md index 78430eb..df7b5ff 100644 --- a/docs/store-art.md +++ b/docs/store-art.md @@ -30,7 +30,11 @@ languages, every store size, a review gallery and an app preview video. No store freeze, autoplay) and let `shots capture` take the frames: Playwright for a web build, `simctl` for anything that runs in the iOS Simulator (Unity, Godot, Flutter, React Native, native, Capacitor), `adb` for an Android emulator or device, or bring a folder of - your own frames. The status bar is cropped off and redrawn clean (9:41, full battery). + your own frames. The status bar is cropped off and redrawn clean (9:41, full battery). Web apps behind a login sign + in first with `shots.capture.auth`: a sign-in request whose secrets come from `.storebound/credentials.json` or the + environment (`${cred:NAME}`, `${env:NAME}`; literal secrets are refused), or a session saved by `storebound shots + login`, where you sign in to a demo account by hand in a fresh browser. Use a demo backend with fabricated data; + the same frames feed the App Store and Google Play. 2. **Copy.** Per language and scene: eyebrow, two-line title, subtitle, badges. Fonts are subset from Google Fonts to exactly your characters, so Japanese, Chinese, Korean, Arabic (right to left) and Hindi just work. `shots fonts` checks every character of every language against the font's cmap (TTF / OTF / WOFF / WOFF2, read in plain diff --git a/skills/store-screenshots/SKILL.md b/skills/store-screenshots/SKILL.md index 4c26fdf..0de95d9 100644 --- a/skills/store-screenshots/SKILL.md +++ b/skills/store-screenshots/SKILL.md @@ -126,7 +126,8 @@ the icon, feature graphic and phone screenshots and prints `tablet screenshots: `baseUrl`, fonts) via `.storebound/capture-cache.json`; `--only-missing` captures only missing files, `--force` everything. Each progress line shows n/total, ETA and the time per step (goto, wait, eval, delay, shot); the end lists the slowest frames and steps, and `.storebound/capture-report.json` keeps them. Put the slow step right - (a long `waitFor` = the game reaching the scene: add a URL switch that jumps there). + (a long `waitFor` = the game reaching the scene: add a URL switch that jumps there). Screens behind a login: + `capture.auth` (see Signed-in apps). - `ios-sim` (Unity, Godot, Flutter, native, Capacitor: any Simulator build): `ios.device` (simulator name or UDID, e.g. a 6.9" iPhone), `ios.bundleId`, optional `ios.app` (.app to install), `ios.args`. Per shot: `args` (launch arguments, read them with UserDefaults / your engine) and / or `url` (deep link). Language goes in as @@ -190,6 +191,30 @@ the icon, feature graphic and phone screenshots and prints `tablet screenshots: `play images` uploads only the sets that exist (tablet / TV / Wear when rendered) and never deletes a set Play has but the renders lack: the dry run shows `keeps on Play`; `--prune` (only on the owner's word) deletes them. +## Signed-in apps + +Key screens behind a login (`source: 'web'`): capture against a **local or demo backend with fabricated data** and a +demo account. Never real users' data in store screenshots. The same frames feed both stores (App Store and Google +Play), so one sign-in setup covers both. Two ways to sign in, set in `shots.capture.auth`: + +- **Sign-in request**: `{ request: { url: '/api/login', method: 'POST', body: { email: '${cred:reviewDemoAccount.username}', + password: '${cred:reviewDemoAccount.password}' } } }`. It runs once per browser context before its first shot, and + the context keeps the cookies. `${cred:NAME}` reads `.storebound/credentials.json` (`reviewDemoAccount.username` / + `.password`, also from REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD, or any key under `captureAuth`). `${env:NAME}` + reads the environment. A password-, token- or key-like field with a literal value is refused. A status outside + 2xx/3xx stops the capture and shows the status, never the values. +- **Saved session**: `{ storageState: '.storebound/auth.json' }`, made by `storebound shots login [--url ]`. It + opens a visible browser with a fresh, empty profile. The owner signs in to the demo account by hand (signing in is + the owner's step; the agent never types it). Enter in the terminal (or closing the window) saves the state with + 0600 permissions and prints how many cookies and origins it saved. The wait times out after 15 min + (`--timeout `) and logs a heartbeat every 30 s. This one is for SSO, 2FA or captcha logins. MCP has no login + tool, because the owner signs in at a terminal. + +If a shot lands on a sign-in page anyway, capture warns ` is a sign-in page: session expired? run storebound +shots login again` and fails that shot at once. `auth.loginUrl` (a regex) names the login page when the default +(login / signin / auth in the path) does not match. Resolved values and cookie values are masked in logs and +`.storebound/capture-report.json`; the gallery only shows the renders. + ## A/B variants and store experiments `shots.variants.`: `scenes` (order / subset), `copy` (a JSON merged over the base copy, only what changes), `palettes` (per scene). `storebound shots render --variant b` (or `--variants` for all) writes diff --git a/tests/browser/capture-auth.browser.ts b/tests/browser/capture-auth.browser.ts new file mode 100644 index 0000000..d89dc84 --- /dev/null +++ b/tests/browser/capture-auth.browser.ts @@ -0,0 +1,122 @@ +// shots.capture.auth against a tiny local app: POST /api/login sets a session cookie, /app/ needs it (else a +// redirect to /login). Request auth signs every context in; a wrong password stops with the status and no values; +// storageState loads a saved session; an expired one warns; `shots login` (headless here, Enter on stdin) saves the +// state 0600 with counts only. Secrets and cookie values never reach the output or the report. Skips without Chromium. +import { afterAll, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { ShipConfig, ShotsCapture } from '../../cli/lib/config'; +import { BASE } from '../helpers/store-mock'; + +const CLI = join(import.meta.dir, '..', '..', 'cli', 'index.ts'); +const PASSWORD = 'demo-pass-7731'; +const SESSION = 'sess-value-55aa91'; + +const server = Bun.serve({ + port: 0, hostname: '127.0.0.1', + async fetch(req) { + const u = new URL(req.url); + if (u.pathname === '/api/login' && req.method === 'POST') { + const b = await req.json().catch(() => ({})) as { email?: string; password?: string }; + if (b.email !== 'demo@example.com' || b.password !== PASSWORD) return new Response('no', { status: 401 }); + return new Response('{}', { headers: { 'set-cookie': `sid=${SESSION}; Path=/; HttpOnly`, 'content-type': 'application/json' } }); + } + if (u.pathname === '/login') return new Response('loginsign in', { headers: { 'content-type': 'text/html', 'set-cookie': 'csrf=login-page-token; Path=/' } }); + if (u.pathname.startsWith('/app/')) { + if (!(req.headers.get('cookie') ?? '').includes(`sid=${SESSION}`)) return new Response(null, { status: 302, headers: { location: '/login?next=' + encodeURIComponent(u.pathname) } }); + const name = u.pathname.split('/').pop(); + return new Response(`
${name}
`, { headers: { 'content-type': 'text/html' } }); + } + return new Response('not found', { status: 404 }); + }, +}); +afterAll(() => server.stop(true)); +const base = `http://127.0.0.1:${server.port}`; + +const canLaunch = spawnSync('bun', ['-e', `const { launch } = await import(${JSON.stringify(join(import.meta.dir, '..', '..', 'cli', 'shots', 'browser.ts'))}); await launch(${JSON.stringify(join(import.meta.dir, '..', '..'))}, { headless: true }); process.exit(0);`], { timeout: 60_000 }).status === 0; +if (!canLaunch) console.warn('capture-auth browser tests skipped: no Chromium could launch (bunx playwright install chromium)'); + +function project(auth: ShotsCapture['auth'], creds: object): string { + const root = mkdtempSync(join(tmpdir(), 'sb-auth-')); + mkdirSync(join(root, '.storebound'), { recursive: true }); + mkdirSync(join(root, 'store/shots'), { recursive: true }); + writeFileSync(join(root, 'store/shots/copy.json'), '{}'); + writeFileSync(join(root, '.storebound/credentials.json'), JSON.stringify(creds)); + const shot = (n: string) => ({ path: `/app/${n}`, waitFor: `window.scene === '${n}'`, delayMs: 10 }); + const cfg: ShipConfig = { ...BASE, languages: [BASE.languages[0]!], shots: { copy: 'store/shots/copy.json', frames: 'store/shots/frames', out: 'store/renders', scenes: [{ id: 'hero', palette: 'fire', frames: [{ src: 'hero.png' }] }], phone: { w: 120, h: 200, dpr: 1 }, + capture: { source: 'web', baseUrl: base, shots: { projects: shot('projects'), settings: shot('settings') }, ...(auth ? { auth } : {}) } } }; + writeFileSync(join(root, 'storebound.config.json'), JSON.stringify(cfg)); + return root; +} +async function cli(root: string, args: string[], stdin?: (p: Bun.Subprocess<'pipe', 'pipe', 'pipe'>) => Promise): Promise<{ out: string; code: number }> { + const p = Bun.spawn(['bun', CLI, 'shots', ...args], { cwd: root, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe', env: { ...process.env, NO_COLOR: '1' } }); + const outP = Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text()]); + if (stdin) await stdin(p); else p.stdin.end(); + const [[o, e], code] = await Promise.all([outP, p.exited]); + return { out: o + e, code }; +} +const demo = { reviewDemoAccount: { username: 'demo@example.com', password: PASSWORD } }; +const request = { request: { url: '/api/login', body: { email: '${cred:reviewDemoAccount.username}', password: '${cred:reviewDemoAccount.password}' } } }; +const frame = (root: string, n: string) => join(root, 'store/shots/frames', BASE.languages[0]!.id, 'phone', `${n}.png`); + +describe.skipIf(!canLaunch)('shots capture with shots.capture.auth', () => { + test.concurrent('request auth signs every context in; secrets and the cookie never reach the output or report', async () => { + const root = project(request, demo); + try { + const r = await cli(root, ['capture', '--device', 'phone', '--force', '--concurrency', '2']); + expect(r.code).toBe(0); + expect(r.out).toContain('signing every context in: POST /api/login'); + expect(existsSync(frame(root, 'projects')) && existsSync(frame(root, 'settings'))).toBe(true); + const report = readFileSync(join(root, '.storebound/capture-report.json'), 'utf8'); + for (const t of [r.out, report]) { expect(t).not.toContain(PASSWORD); expect(t).not.toContain(SESSION); } + expect(r.out).not.toContain('session expired'); + } finally { rmSync(root, { recursive: true, force: true }); } + }, 120_000); + + test.concurrent('a refused sign-in stops with the status, never the values', async () => { + const root = project(request, { reviewDemoAccount: { username: 'demo@example.com', password: 'wrong-pass-0001' } }); + try { + const r = await cli(root, ['capture', '--device', 'phone', '--force']); + expect(r.code).not.toBe(0); + expect(r.out).toContain('returned HTTP 401'); + expect(r.out).not.toContain('wrong-pass-0001'); + expect(existsSync(frame(root, 'projects'))).toBe(false); + } finally { rmSync(root, { recursive: true, force: true }); } + }, 120_000); + + test.concurrent('storageState loads a saved session; an expired one warns to run shots login again', async () => { + const state = (v: string) => JSON.stringify({ cookies: [{ name: 'sid', value: v, domain: '127.0.0.1', path: '/', expires: -1, httpOnly: true, secure: false, sameSite: 'Lax' }], origins: [] }); + const root = project({ storageState: '.storebound/auth.json' }, {}); + try { + writeFileSync(join(root, '.storebound/auth.json'), state(SESSION)); + let r = await cli(root, ['capture', '--device', 'phone', '--force']); + expect(r.code).toBe(0); + expect(r.out).toContain('signed in from .storebound/auth.json'); + expect(r.out).not.toContain(SESSION); + writeFileSync(join(root, '.storebound/auth.json'), state('sess-expired-000')); + r = await cli(root, ['capture', '--device', 'phone', '--force']); + expect(r.code).not.toBe(0); // the shots fail at once, no waitFor timeout + expect(r.out).toContain('landed on the sign-in page'); + expect(r.out).toContain(`${base}/login is a sign-in page: session expired? run storebound shots login again`); + expect(r.out.match(/session expired/g)?.length).toBe(1); // once per login URL, not per shot + } finally { rmSync(root, { recursive: true, force: true }); } + }, 120_000); + + test.concurrent('shots login saves the storage state 0600 after Enter, with counts only', async () => { + const root = project(undefined, {}); + try { + const r = await cli(root, ['login', '--url', `${base}/login`, '--headless', '--timeout', '60'], async p => { + // Enter, like the owner after signing in (read once the page is open) + p.stdin.write('\n'); await p.stdin.end(); + }); + expect(r.code).toBe(0); + const file = join(root, '.storebound/auth.json'); + expect(statSync(file).mode & 0o777).toBe(0o600); + expect(r.out).toContain('saved .storebound/auth.json (0600): 1 cookie (127.0.0.1)'); + expect(r.out).not.toContain('login-page-token'); + expect(JSON.parse(readFileSync(file, 'utf8')).cookies[0].name).toBe('csrf'); + } finally { rmSync(root, { recursive: true, force: true }); } + }, 120_000); +}); diff --git a/tests/capture-auth.test.ts b/tests/capture-auth.test.ts new file mode 100644 index 0000000..b7422f8 --- /dev/null +++ b/tests/capture-auth.test.ts @@ -0,0 +1,86 @@ +// shots.capture.auth without a browser: reference resolution (credentials.json, env), refusal of literal secrets, +// masking, the login-page check and the storage state summary of `shots login`. +import { describe, expect, test } from 'bun:test'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { authPlan, credLookup, landedOnLogin, literalSecrets, maskSecrets, resolveRequest, validateAuth } from '../cli/shots/auth'; +import { validateCapture } from '../cli/shots/devices'; +import { stateSummary } from '../cli/shots/login'; + +function proj(creds: object): string { + const root = mkdtempSync(join(tmpdir(), 'sb-auth-')); + mkdirSync(join(root, '.storebound')); + writeFileSync(join(root, '.storebound', 'credentials.json'), JSON.stringify(creds)); + return root; +} + +describe('capture auth references', () => { + test('cred: reviewDemoAccount and captureAuth from credentials.json, env: from the environment', () => { + const root = proj({ reviewDemoAccount: { username: 'demo@example.com', password: 'pw-from-file' }, captureAuth: { apiKey: 'key-123456' } }); + try { + const secrets = new Set(); + const r = resolveRequest({ url: '/api/login', body: { email: '${cred:reviewDemoAccount.username}', password: '${cred:reviewDemoAccount.password}' }, + headers: { 'x-api-key': '${cred:apiKey}', 'x-tenant': '${env:SB_TENANT}' } }, 'http://127.0.0.1:1/', credLookup(root, { SB_TENANT: 'demo-tenant' }), secrets); + expect(r).toEqual({ url: 'http://127.0.0.1:1/api/login', method: 'POST', headers: { 'x-api-key': 'key-123456', 'x-tenant': 'demo-tenant', 'content-type': 'application/json' }, + body: JSON.stringify({ email: 'demo@example.com', password: 'pw-from-file' }) }); + expect([...secrets].sort()).toEqual(['demo-tenant', 'demo@example.com', 'key-123456', 'pw-from-file']); + // REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD win over the file, like apple review-details + const env = credLookup(root, { REVIEW_DEMO_USER: 'env@example.com', REVIEW_DEMO_PASSWORD: 'pw-env' }); + expect(env('cred', 'reviewDemoAccount.password')).toBe('pw-env'); + } finally { rmSync(root, { recursive: true, force: true }); } + }); + test('a missing reference names only the reference', () => { + const root = proj({}); + try { + expect(() => resolveRequest({ url: '/l', body: { password: '${cred:reviewDemoAccount.password}' } }, 'http://x', credLookup(root, {}), new Set())).toThrow(/reviewDemoAccount\.password\} is not in \.storebound\/credentials\.json/); + expect(() => resolveRequest({ url: '/l', body: 'token=${env:NOPE_TOKEN}' }, 'http://x', credLookup(root, {}), new Set())).toThrow('environment variable NOPE_TOKEN is not set'); + } finally { rmSync(root, { recursive: true, force: true }); } + }); +}); + +describe('literal secrets are refused', () => { + test('password-like keys with literal values, in JSON, form strings and headers', () => { + expect(literalSecrets({ url: '/l', body: { email: 'demo@example.com', password: 'hunter22' } })).toEqual(['body.password']); + expect(literalSecrets({ url: '/l', body: 'user=a&pass=hunter22' })).toEqual(['body.pass']); + expect(literalSecrets({ url: '/l', body: '{"auth":{"token":"abc"}}' })).toEqual(['body.auth.token']); + expect(literalSecrets({ url: '/l', headers: { Authorization: 'Bearer abc.def' } })).toEqual(['headers.Authorization']); + expect(literalSecrets({ url: '/l', headers: { Authorization: 'Bearer ${env:TOKEN}' }, body: { password: '${cred:reviewDemoAccount.password}' } })).toEqual([]); + const e = validateCapture({ source: 'web', baseUrl: 'http://x', shots: {}, auth: { request: { url: '/l', body: { password: 'hunter22' } } } }); + expect(e.join('\n')).toContain('shots.capture.auth.request.body.password: a secret is never written in the config'); + expect(e.join('\n')).not.toContain('hunter22'); + }); + test('shape and a gitignored storageState path', () => { + expect(validateAuth({})[0]).toContain('either'); + expect(validateAuth({ storageState: 'auth.json' })[0]).toContain('a file in .storebound/'); + expect(validateAuth({ storageState: '.storebound/auth.json' })).toEqual([]); + }); +}); + +describe('masking and the login-page check', () => { + test('values and their URL-encoded forms are masked', () => { + expect(maskSecrets('POST failed for p@ss word / p%40ss%20word', ['p@ss word'])).toBe('POST failed for *** / ***'); + }); + test('storageState: a missing file says to run shots login; cookie values become secrets', () => { + const root = proj({}); + try { + expect(() => authPlan({ storageState: '.storebound/auth.json' }, { root, baseUrl: 'http://x' })).toThrow('run storebound shots login'); + writeFileSync(join(root, '.storebound/auth.json'), JSON.stringify({ cookies: [{ name: 'sid', value: 'cookie-value-1', domain: '127.0.0.1' }], origins: [] })); + const p = authPlan({ storageState: '.storebound/auth.json' }, { root, baseUrl: 'http://x' }); + expect(p.contextOptions.storageState).toBe(join(root, '.storebound/auth.json')); + expect([...p.secrets]).toEqual(['cookie-value-1']); + } finally { rmSync(root, { recursive: true, force: true }); } + }); + test('a shot redirected to a login page is detected, a login shot itself is not', () => { + expect(landedOnLogin('http://h/app/projects?lang=en', 'http://h/login?next=%2Fapp')).toBe(true); + expect(landedOnLogin('http://h/app/projects', 'http://h/auth/sign-in')).toBe(true); + expect(landedOnLogin('http://h/app/projects', 'http://h/app/projects')).toBe(false); + expect(landedOnLogin('http://h/login', 'http://h/login/step2')).toBe(false); + expect(landedOnLogin('http://h/app', 'http://h/welcome', 'welcome')).toBe(true); + }); + test('shots login summary shows counts and domains, never values', () => { + const s = stateSummary({ cookies: [{ name: 'sid', value: 'SECRET-VALUE', domain: '.example.com' }, { name: 'csrf', value: 'X2', domain: 'example.com' }], origins: [{ origin: 'https://example.com', localStorage: [] }] }); + expect(s).toBe('2 cookies (example.com), 1 origin with local storage'); + expect(s).not.toContain('SECRET'); + }); +}); From 2fdd96e68c98c0547d729119c9d6e98994ff348a Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 12:44:41 +0700 Subject: [PATCH 044/344] storebound 0.8.17: version in package.json and every copy, CHANGELOG 0.8.17 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 5799a2c..1733f8e 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.16", + "version": "0.8.17", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index e247d8f..babc215 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.16", + "version": "0.8.17", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 6734b58..9246376 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.16", + "version": "0.8.17", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index 8873538..c3a9597 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.17 · 2026-10-20 + - `shots capture --source web` can sign in first: `shots.capture.auth` is a sign-in request (run once per browser context, cookies kept; body and headers use `${cred:NAME}` from `.storebound/credentials.json` or `${env:NAME}`, literal secrets are refused, a failed status stops with the status only) or a `storageState` file. `storebound shots diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 6276d92..bc1e53d 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.16", + "version": "0.8.17", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 0d16247..0120d92 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4010,7 +4010,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.16" +version = "0.8.17" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index dda0034..9b90361 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.16" +version = "0.8.17" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index d51f8da..b1850ac 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.16", + "version": "0.8.17", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index 136c778..e4647ba 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.16", + "version": "0.8.17", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index 01bca1a..cac8b59 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.16", + "version": "0.8.17", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From 8c1a01d856085d150c782b4ad3eb3fe9f614973a Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 13:11:10 +0700 Subject: [PATCH 045/344] config loads without Node's MODULE_TYPELESS_PACKAGE_JSON warning in a CommonJS project; capture sign-in docs use captureAuth and check notes a local capture that signs in with reviewDemoAccount (the App Review account) --- CHANGELOG.md | 5 +++++ cli/check.ts | 7 +++++++ cli/lib/rt.ts | 5 ++++- skills/store-screenshots/SKILL.md | 11 +++++++---- tests/capture-review-account.test.ts | 15 +++++++++++++++ 5 files changed, 38 insertions(+), 5 deletions(-) create mode 100644 tests/capture-review-account.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index c3a9597..635bd3b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- **No more "Reparsing as ES module" warning** for a `.ts` config in a CommonJS project (Node's + MODULE_TYPELESS_PACKAGE_JSON); the app does not need `"type": "module"`. +- **Capture sign-in keeps App Review's account apart:** the docs use `captureAuth` for a local demo sign-in, and + `check` notes a capture against localhost that uses `reviewDemoAccount` (the account `apple review-details` sends). + ## 0.8.17 · 2026-10-20 - `shots capture --source web` can sign in first: `shots.capture.auth` is a sign-in request (run once per browser diff --git a/cli/check.ts b/cli/check.ts index aac7155..d85776e 100644 --- a/cli/check.ts +++ b/cli/check.ts @@ -152,6 +152,13 @@ export async function run(ctx: Ctx): Promise { try { for (const n of (await runScan(ctx.loaded.root, { config: ctx.loaded.path })).report.notes) if (n.startsWith('scan.ignore[')) note(n); } catch (e) { note(`scan.ignore not checked: ${(e as Error).message}`); } } if (config.apple && !config.app.copyright?.trim()) problems.push(COPYRIGHT_MISSING); + // the App Review demo account must work on the live backend: a capture sign-in against a local stack that uses it + // means local-only credentials are (or will be) stored where review-details sends them to App Review + { const cap = (config as { shots?: { capture?: { baseUrl?: string; auth?: { request?: { url?: string } } } } }).shots?.capture; + const authText = JSON.stringify(cap?.auth ?? {}); + const local = /\b(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|[a-z0-9-]+\.(localhost|test|local))\b/i; + if (/cred:reviewDemoAccount/.test(authText) && (local.test(cap?.baseUrl ?? '') || local.test(cap?.auth?.request?.url ?? ''))) + note('shots.capture.auth signs in to a local stack with reviewDemoAccount, the account App Review gets from apple review-details: put the local demo sign-in in captureAuth in .storebound/credentials.json and use ${cred:}'); } const duo = iphoneDuoNote({ apple: !!config.apple, duo: !!config.apple?.iphoneDuo, play: !!config.play }); if (duo?.level === 'info') { hints.push(duo.msg); log('check', `hint: ${duo.msg}`); } else if (duo) note(duo.msg); const creative = creativeNote(config, ctx.loaded.resolve(config.renders ?? config.shots?.out ?? 'store/renders')); diff --git a/cli/lib/rt.ts b/cli/lib/rt.ts index da7bd45..9b43cc7 100644 --- a/cli/lib/rt.ts +++ b/cli/lib/rt.ts @@ -101,7 +101,10 @@ export async function importConfigModule(path: string): Promise { async function withoutTypeStripWarning(f: () => Promise): Promise { const emit = process.emitWarning; process.emitWarning = ((w: string | Error, ...rest: unknown[]) => { - if (/Type Stripping|type stripping/i.test(String(typeof w === 'string' ? w : w.message))) return; + // also Node's MODULE_TYPELESS_PACKAGE_JSON ("Reparsing as ES module") for a .ts config in a CommonJS package: + // the config is ours to load, the app need not add "type": "module" + const text = `${String(typeof w === 'string' ? w : w.message)} ${rest.map(r => (typeof r === 'object' && r ? JSON.stringify(r) : String(r))).join(' ')}`; + if (/Type Stripping|type stripping|Reparsing as ES module|MODULE_TYPELESS_PACKAGE_JSON/i.test(text)) return; return (emit as (...a: unknown[]) => void).call(process, w, ...rest); }) as typeof process.emitWarning; try { return await f(); } finally { process.emitWarning = emit; } diff --git a/skills/store-screenshots/SKILL.md b/skills/store-screenshots/SKILL.md index 0de95d9..7e99780 100644 --- a/skills/store-screenshots/SKILL.md +++ b/skills/store-screenshots/SKILL.md @@ -197,10 +197,13 @@ Key screens behind a login (`source: 'web'`): capture against a **local or demo demo account. Never real users' data in store screenshots. The same frames feed both stores (App Store and Google Play), so one sign-in setup covers both. Two ways to sign in, set in `shots.capture.auth`: -- **Sign-in request**: `{ request: { url: '/api/login', method: 'POST', body: { email: '${cred:reviewDemoAccount.username}', - password: '${cred:reviewDemoAccount.password}' } } }`. It runs once per browser context before its first shot, and - the context keeps the cookies. `${cred:NAME}` reads `.storebound/credentials.json` (`reviewDemoAccount.username` / - `.password`, also from REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD, or any key under `captureAuth`). `${env:NAME}` +- **Sign-in request**: `{ request: { url: '/api/login', method: 'POST', body: { email: '${cred:email}', + password: '${cred:password}' } } }` with `captureAuth: { email, password }` in `.storebound/credentials.json`. It + runs once per browser context before its first shot, and the context keeps the cookies. `${cred:NAME}` reads + `captureAuth.NAME` (or `reviewDemoAccount.username` / `.password`, also from REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD). + Keep the two apart: `reviewDemoAccount` is the account `apple review-details` sends to App Review and must work on + the live backend; a local demo stack's sign-in belongs in `captureAuth`. `check` warns when a capture against + localhost uses `reviewDemoAccount`. `${env:NAME}` reads the environment. A password-, token- or key-like field with a literal value is refused. A status outside 2xx/3xx stops the capture and shows the status, never the values. - **Saved session**: `{ storageState: '.storebound/auth.json' }`, made by `storebound shots login [--url ]`. It diff --git a/tests/capture-review-account.test.ts b/tests/capture-review-account.test.ts new file mode 100644 index 0000000..6b4e418 --- /dev/null +++ b/tests/capture-review-account.test.ts @@ -0,0 +1,15 @@ +// The App Review demo account (reviewDemoAccount, sent by apple review-details) must work on the live backend: a +// capture sign-in against a local stack that uses it gets a check note (a session nearly stored local-only creds there). +import { afterEach, expect, test } from 'bun:test'; +import { run as check } from '../cli/check'; +import { BASE, capture, jsonOut, project, restore } from './helpers/store-mock'; + +afterEach(restore); +const withAuth = (baseUrl: string, ref: string) => ({ ...BASE, play: undefined, shots: { capture: { baseUrl, auth: { request: { url: '/api/login', method: 'POST', body: { email: `\${cred:${ref}}`, password: `\${cred:${ref.replace('username', 'password').replace('email', 'password')}}` } } } } } }) as typeof BASE; +const notes = async (cfg: typeof BASE) => { const p = project(cfg, { '.gitignore': '.storebound/\n' }); const j = jsonOut((await capture(() => check(p.ctx(['--json'], ['json'])))).out); return JSON.stringify(j); }; + +test('local capture with reviewDemoAccount gets a note; captureAuth or a remote stack does not', async () => { + expect(await notes(withAuth('http://localhost:5173', 'reviewDemoAccount.username'))).toContain('captureAuth'); + expect(await notes(withAuth('http://localhost:5173', 'email'))).not.toContain('signs in to a local stack'); + expect(await notes(withAuth('https://staging.example.com', 'reviewDemoAccount.username'))).not.toContain('signs in to a local stack'); +}); From ac84ad4bbfb1f414dc8644e24d70fc89e538bdd5 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 13:11:36 +0700 Subject: [PATCH 046/344] storebound 0.8.18: version in package.json and every copy, CHANGELOG 0.8.18 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 1733f8e..9dab8f4 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.17", + "version": "0.8.18", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index babc215..c304bcd 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.17", + "version": "0.8.18", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 9246376..573d9f9 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.17", + "version": "0.8.18", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index 635bd3b..7d126d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.18 · 2026-10-20 + - **No more "Reparsing as ES module" warning** for a `.ts` config in a CommonJS project (Node's MODULE_TYPELESS_PACKAGE_JSON); the app does not need `"type": "module"`. - **Capture sign-in keeps App Review's account apart:** the docs use `captureAuth` for a local demo sign-in, and diff --git a/apps/desktop/package.json b/apps/desktop/package.json index bc1e53d..a25849d 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.17", + "version": "0.8.18", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 0120d92..8f77f1b 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4010,7 +4010,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.17" +version = "0.8.18" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 9b90361..05ff1eb 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.17" +version = "0.8.18" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index b1850ac..ed0a6cd 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.17", + "version": "0.8.18", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index e4647ba..5c8cc29 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.17", + "version": "0.8.18", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index cac8b59..c18fe17 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.17", + "version": "0.8.18", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From 353e13d5be4060ed2fe3f2db68ed334395665568 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 13:44:22 +0700 Subject: [PATCH 047/344] shots: Playwright's chromium is taken from the namespace or default of a project's CommonJS playwright; a module without chromium.launch names the resolved file and its exports (a project's playwright 1.57 under a global Bun install gave 'reading launch of undefined'); tests: the review-account fixture typechecks --- CHANGELOG.md | 4 ++++ cli/shots/browser.ts | 12 ++++++++++-- tests/capture-review-account.test.ts | 2 +- tests/playwright-resolve.test.ts | 28 ++++++++++++++++++++++++++++ 4 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 tests/playwright-resolve.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d126d7..05a8323 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- **`shots capture` / `render` find Playwright's chromium in a project's CommonJS playwright** whether it comes on the + namespace or under `default`; when the module has no `chromium.launch`, the error names the resolved file and its + exports (was "Cannot read properties of undefined (reading 'launch')"). + ## 0.8.18 · 2026-10-20 - **No more "Reparsing as ES module" warning** for a `.ts` config in a CommonJS project (Node's diff --git a/cli/shots/browser.ts b/cli/shots/browser.ts index 6176f67..e009c05 100644 --- a/cli/shots/browser.ts +++ b/cli/shots/browser.ts @@ -26,6 +26,9 @@ import { compiled } from '../lib/runner'; import * as rt from '../lib/rt'; // eslint-disable-next-line @typescript-eslint/no-explicit-any +/** A playwright module that resolved but does not have the API: named, so the error says which file it was. */ +class PlaywrightShapeError extends Error {} + async function chromium(root: string): Promise { for (const base of [root, rt.packageRoot()]) { try { @@ -34,8 +37,13 @@ async function chromium(root: string): Promise { // cache (~/.bun/install/cache), whose browser build was never downloaded ("headless shell: not installed" on // Linux CI, where no Google Chrome hides it); storebound's own copy is next if (!isInstalledPackage(p)) continue; - return (await rt.importPath(p)).chromium; - } catch { /* next */ } + // playwright's entry is CommonJS: depending on the runtime and version the ESM import puts chromium on the + // namespace or only under default (a project's playwright 1.57 under a global Bun install gave undefined) + const m = await rt.importPath(p); + const c = m?.chromium ?? m?.default?.chromium; + if (!c || typeof c.launch !== 'function') throw new PlaywrightShapeError(`playwright at ${p} has no chromium.launch (exports: ${Object.keys(m ?? {}).slice(0, 8).join(', ') || 'none'}${m?.default ? `; default: ${Object.keys(m.default).slice(0, 8).join(', ')}` : ''})`); + return c; + } catch (e) { if (e instanceof PlaywrightShapeError) throw e; /* 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; diff --git a/tests/capture-review-account.test.ts b/tests/capture-review-account.test.ts index 6b4e418..934bed1 100644 --- a/tests/capture-review-account.test.ts +++ b/tests/capture-review-account.test.ts @@ -5,7 +5,7 @@ import { run as check } from '../cli/check'; import { BASE, capture, jsonOut, project, restore } from './helpers/store-mock'; afterEach(restore); -const withAuth = (baseUrl: string, ref: string) => ({ ...BASE, play: undefined, shots: { capture: { baseUrl, auth: { request: { url: '/api/login', method: 'POST', body: { email: `\${cred:${ref}}`, password: `\${cred:${ref.replace('username', 'password').replace('email', 'password')}}` } } } } } }) as typeof BASE; +const withAuth = (baseUrl: string, ref: string) => ({ ...BASE, play: undefined, shots: { capture: { baseUrl, auth: { request: { url: '/api/login', method: 'POST', body: { email: `\${cred:${ref}}`, password: `\${cred:${ref.replace('username', 'password').replace('email', 'password')}}` } } } } } }) as unknown as typeof BASE; const notes = async (cfg: typeof BASE) => { const p = project(cfg, { '.gitignore': '.storebound/\n' }); const j = jsonOut((await capture(() => check(p.ctx(['--json'], ['json'])))).out); return JSON.stringify(j); }; test('local capture with reviewDemoAccount gets a note; captureAuth or a remote stack does not', async () => { diff --git a/tests/playwright-resolve.test.ts b/tests/playwright-resolve.test.ts new file mode 100644 index 0000000..812476d --- /dev/null +++ b/tests/playwright-resolve.test.ts @@ -0,0 +1,28 @@ +// A project's playwright is CommonJS: its chromium may come through the ESM import only under `default`. A playwright +// 1.57 project under a global Bun install gave undefined and "Cannot read properties of undefined (reading 'launch')". +import { expect, test } from 'bun:test'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { chromiumFor } from '../cli/shots/browser'; + +const fakePlaywright = (body: string): string => { + const dir = mkdtempSync(join(tmpdir(), 'sb-pw-')); + const pkg = join(dir, 'node_modules', 'playwright'); + mkdirSync(pkg, { recursive: true }); + writeFileSync(join(pkg, 'package.json'), JSON.stringify({ name: 'playwright', version: '1.57.0', main: 'index.js' })); + writeFileSync(join(pkg, 'index.js'), body); + writeFileSync(join(dir, 'package.json'), '{"name":"app","private":true}'); + return dir; +}; + +test('chromium from a CommonJS playwright, named or under default; a wrong shape names the file', async () => { + const named = fakePlaywright('module.exports = { chromium: { launch() { return "ok"; } } };'); + const viaDefault = fakePlaywright('const api = { chromium: { launch() { return "ok"; } } }; module.exports = { __esModule: true, default: api };'); + const broken = fakePlaywright('module.exports = { firefox: {} };'); + try { + expect(typeof (await chromiumFor(named)).launch).toBe('function'); + expect(typeof (await chromiumFor(viaDefault)).launch).toBe('function'); + await expect(chromiumFor(broken)).rejects.toThrow(/node_modules[\\/]playwright[\\/]index\.js has no chromium\.launch/); + } finally { for (const d of [named, viaDefault, broken]) rmSync(d, { recursive: true, force: true }); } +}); From 2ba8278ab70b017ce43642e0bfcd790dd5f0bd15 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 13:44:41 +0700 Subject: [PATCH 048/344] storebound 0.8.19: version in package.json and every copy, CHANGELOG 0.8.19 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 9dab8f4..5f4e9d9 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.18", + "version": "0.8.19", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index c304bcd..f399862 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.18", + "version": "0.8.19", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 573d9f9..4f9c156 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.18", + "version": "0.8.19", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index 05a8323..9c66770 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.19 · 2026-10-20 + - **`shots capture` / `render` find Playwright's chromium in a project's CommonJS playwright** whether it comes on the namespace or under `default`; when the module has no `chromium.launch`, the error names the resolved file and its exports (was "Cannot read properties of undefined (reading 'launch')"). diff --git a/apps/desktop/package.json b/apps/desktop/package.json index a25849d..e1d5b99 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.18", + "version": "0.8.19", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 8f77f1b..cec38e0 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4010,7 +4010,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.18" +version = "0.8.19" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 05ff1eb..7c21741 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.18" +version = "0.8.19" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index ed0a6cd..6d8c183 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.18", + "version": "0.8.19", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index 5c8cc29..41b1e9a 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.18", + "version": "0.8.19", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index c18fe17..f62e217 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.18", + "version": "0.8.19", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From 3a11682a37c7f6f0b08f795034f0c58758aab093 Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 20 Oct 2026 13:37:37 +0700 Subject: [PATCH 049/344] shots: app titles get the weights the templates use (variable axis, used range or static weights; font-weight warning), palette.bg as one colour or a CSS gradient string (validated; contrast guard in shots check), photo backgrounds (palette.image, shots.feature.background) with overlay and cover crop --- CHANGELOG.md | 9 ++ cli/lib/config.ts | 14 ++- cli/lib/embedded.ts | 8 +- cli/shots/check.ts | 36 ++++++- cli/shots/feature-app.html | 2 +- cli/shots/feature.html | 2 +- cli/shots/fonts.ts | 52 ++++++---- cli/shots/glyphs.ts | 36 +++++-- cli/shots/lib.ts | 7 +- cli/shots/palette.ts | 131 ++++++++++++++++++++++++++ cli/shots/render.ts | 81 +++++++++++++++- cli/shots/report.ts | 7 +- cli/shots/spec.ts | 2 +- cli/shots/template-app.html | 6 +- cli/shots/template.html | 2 +- cli/shots/weights.ts | 113 ++++++++++++++++++++++ docs/store-art.md | 13 +++ skills/store-pitfalls/SKILL.md | 12 +++ skills/store-screenshots/SKILL.md | 18 +++- tests/browser/palette-bg.browser.ts | 65 +++++++++++++ tests/shots-look.test.ts | 141 ++++++++++++++++++++++++++++ 21 files changed, 713 insertions(+), 44 deletions(-) create mode 100644 cli/shots/palette.ts create mode 100644 cli/shots/weights.ts create mode 100644 tests/browser/palette-bg.browser.ts create mode 100644 tests/shots-look.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c66770..951d487 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ - **`shots capture` / `render` find Playwright's chromium in a project's CommonJS playwright** whether it comes on the namespace or under `default`; when the module has no `chromium.launch`, the error names the resolved file and its exports (was "Cannot read properties of undefined (reading 'launch')"). +- **Heavy app-style headlines again:** `shots fonts` downloads the weights the templates use (the full `wght` axis of a + variable Google family, else the used range, else the static weights), so a family like Plus Jakarta Sans no longer + falls back to its thin 400 instance. `shots fonts` warns about weights a family or a local file (`{ weight }`) lacks; + `shots check` warns per image when a title was drawn at another weight (`font-weight`). +- **palette.bg as a string:** one colour (flat) or a CSS gradient string now renders as given instead of a white + background; anything else fails config validation ("palette.bg must be a colour, a gradient or an array of 2-3 + colours"). `shots check` warns when the title ink has low contrast against the pixels behind it (`contrast`). +- **Photo backgrounds:** `palette.image` (+ `overlay`) and `shots.feature.background` put a cover-cropped photo under a + dark overlay (the Play feature graphic, optionally the screenshots); `shots check` checks the file and its size. ## 0.8.18 · 2026-10-20 diff --git a/cli/lib/config.ts b/cli/lib/config.ts index 445e508..147ca9d 100644 --- a/cli/lib/config.ts +++ b/cli/lib/config.ts @@ -6,6 +6,7 @@ import { dirname, isAbsolute, join, resolve } from 'node:path'; import * as rt from './rt'; import { PROFILE_RE, setConfigAccount } from './credentials'; import { validateCapture, validateRecord } from '../shots/devices'; +import { featureBackgroundIssues, paletteIssues } from '../shots/palette'; import { type AppleDataTypeId, type AppleTypeAnswer, validateAppPrivacyTypes } from './app-privacy'; import { type AppEventDef, type CustomProductPageDef, validateCpp, validateEvents } from './cpp-events'; import { type IapOfferCodeDef, type PromotedConfig, validateIapOfferCodes, validatePromoted, validateWinBack, type WinBackDef } from './offers'; @@ -125,7 +126,9 @@ export interface DataSafety { export interface ShotBadgeSlot { y: number; side: 'l' | 'r'; icon?: string; iconBg?: string; hot?: boolean; stars?: boolean; rot?: number } export interface ShotFrame { src: string; x?: number; dy?: number; scale?: number; rotate?: number } -export interface Palette { bg: [string, string, string]; glow: string; ink: string; shadow: string } +/** bg: gradient stops (2-3 colours), one colour (flat) or a CSS gradient string. image: a photo background (path + * relative to the config, cropped to cover) under a dark overlay (0-0.9, default 0.45) that keeps white ink legible. */ +export interface Palette { bg: string | [string, string] | [string, string, string]; glow: string; ink: string; shadow: string; image?: string; overlay?: number } export interface ShotScene { id: string; palette: string | Palette; hero?: boolean; frames: ShotFrame[]; badges?: ShotBadgeSlot[]; over?: number } /** A local font file for shots.fonts. license: 'OFL-1.1', 'proprietary' or a short note (shown by `shots fonts`; @@ -158,7 +161,10 @@ export interface ShotsConfig { * its rotated outline stays inside the canvas with a 24 px margin; 'bleed' keeps the larger phone cropped by the * bottom edge on purpose (shots check then allows it). `scale` (0.5-1.5, default 1) multiplies the phone's width * (still clamped to the canvas with 'contain'). */ - feature?: { frame: string; palette?: string | Palette; fit?: 'contain' | 'bleed'; scale?: number }; + feature?: { frame: string; palette?: string | Palette; fit?: 'contain' | 'bleed'; scale?: number; + /** Photo background for the feature graphic (path relative to the config, or { image, overlay }); wins over the + * palette's image. Also usable for the App Store Header and Search Results art. */ + background?: string | { image: string; overlay?: number } }; /** Phone screen size of the raw frames in CSS px (default 440 x 902 @3x, iPhone 6.9" minus the 54 px status bar). * `bar` = status bar height the template draws above the frame (and that capture crops off). */ phone?: { w: number; h: number; dpr?: number; bar?: number }; @@ -1209,7 +1215,11 @@ export function validateConfig(c: unknown): string[] { if (!s.feature || typeof s.feature.frame !== 'string' || !s.feature.frame) e.push('shots.feature.frame: a frame name'); if (s.feature?.fit !== undefined && s.feature.fit !== 'contain' && s.feature.fit !== 'bleed') e.push("shots.feature.fit: 'contain' | 'bleed'"); if (s.feature?.scale !== undefined && !(typeof s.feature.scale === 'number' && s.feature.scale >= 0.5 && s.feature.scale <= 1.5)) e.push('shots.feature.scale: a number from 0.5 to 1.5'); + e.push(...featureBackgroundIssues(s.feature?.background)); + if (s.feature?.palette !== undefined) e.push(...paletteIssues(s.feature.palette, 'shots.feature.palette')); } + for (const sc of s.scenes ?? []) if (sc.palette !== undefined) e.push(...paletteIssues(sc.palette, `shots.scenes[${sc.id}].palette`)); + for (const [k, v] of Object.entries(s.variants ?? {})) for (const [id, p] of Object.entries(v.palettes ?? {})) e.push(...paletteIssues(p, `shots.variants.${k}.palettes.${id}`)); const fontKeys: [string, unknown][] = [['title', s.fonts?.title], ['body', s.fonts?.body], ...(Array.isArray(s.fonts?.fallback) ? s.fonts!.fallback! : s.fonts?.fallback !== undefined ? [s.fonts.fallback] : []).map((f, i) => [`fallback[${i}]`, f] as [string, unknown])]; if (s.fonts?.fallback !== undefined && !Array.isArray(s.fonts.fallback)) e.push('shots.fonts.fallback: a list'); for (const [k, f] of fontKeys) { diff --git a/cli/lib/embedded.ts b/cli/lib/embedded.ts index 1a18a42..f5917f9 100644 --- a/cli/lib/embedded.ts +++ b/cli/lib/embedded.ts @@ -38,10 +38,10 @@ export const TEMPLATE_TEXT: Record = { /** The pages shots render / video load (cli/shots/*.html), by file name. */ export const SHOTS_PAGES: Record = { "caption.html": "\n\n\n\n\n\n\n\n\n
\n\n\n\n", - "feature-app.html": "\n\n\n\n\n\n\n\n\n
\n
\n
\n
\n\n\n\n", - "feature.html": "\n\n\n\n\n\n\n\n\n
\n
\n
\n
\n\n\n\n", - "template-app.html": "\n\n\n\n\n\n\n\n\n
\n\n\n\n", - "template.html": "\n\n\n\n\n\n\n\n\n
\n\n\n\n", + "feature-app.html": "\n\n\n\n\n\n\n\n\n
\n
\n
\n
\n\n\n\n", + "feature.html": "\n\n\n\n\n\n\n\n\n
\n
\n
\n
\n\n\n\n", + "template-app.html": "\n\n\n\n\n\n\n\n\n
\n\n\n\n", + "template.html": "\n\n\n\n\n\n\n\n\n
\n\n\n\n", }; /** Play Console's Data safety form export (cli/data/play-data-safety-form.csv). */ diff --git a/cli/shots/check.ts b/cli/shots/check.ts index cc45379..d7f8f85 100644 --- a/cli/shots/check.ts +++ b/cli/shots/check.ts @@ -21,6 +21,39 @@ import { allIssues, requiredSets, type RendersScan, resolvedTablets, scanRenders import { imageInfo } from './spec'; import { fontsDirOf, readManifest } from './fonts'; import { localFontIssues } from './local-fonts'; +import { photoBackground, photoIssues } from './palette'; +import { palette } from './lib'; +import { shotsStyle } from '../lib/config'; +import type { Issue } from './spec'; + +/** Photo backgrounds (palette.image, shots.feature.background): the file exists and is at least as big as every + * output it covers (the feature graphic 1024 x 500; screenshots at the sizes this project renders). */ +export function backgroundIssues(config: ShipConfig, resolve: (p: string) => string, tablets?: boolean): { where: string; issue: Issue }[] { + const shots = config.shots; + if (!shots) return []; + const style = shotsStyle(config), sizes = defaultSizes(config, tablets); + const out: { where: string; issue: Issue }[] = []; + const one = (file: string, where: string, targets: string[]): void => { + const abs = resolve(file); + let info: { w: number; h: number } | null = null; + try { const i = imageInfo(readFileSync(abs)); info = i.format === 'unknown' ? null : i; } catch { /* missing */ } + for (const t of targets) for (const x of photoIssues(info, file, SIZES[t]!.w, SIZES[t]!.h)) out.push({ where, issue: { level: x.level, code: 'background', msg: x.msg } }); + }; + const screens = sizes.filter(s => !SIZES[s]!.feature); + // the biggest screenshot size decides; one message per file + const biggest = screens.sort((a, b) => SIZES[b]!.w * SIZES[b]!.h - SIZES[a]!.w * SIZES[a]!.h).slice(0, 1); + for (const sc of shots.scenes) { + let p; try { p = palette(sc.palette, style); } catch (e) { out.push({ where: `shots.scenes[${sc.id}].palette`, issue: { level: 'error', code: 'background', msg: (e as Error).message } }); continue; } + const ph = photoBackground(p); + if (ph) one(ph.image, `shots.scenes[${sc.id}].palette.image`, biggest); + } + if (sizes.includes('feature')) { + let p; try { p = palette(shots.feature?.palette ?? shots.scenes[0]?.palette, style); } catch { p = null; } + const ph = p && photoBackground(p, shots.feature?.background); + if (ph) one(ph.image, shots.feature?.background ? 'shots.feature.background' : 'shots.feature palette.image', ['feature']); + } + return out; +} /** Frame files the scenes (and the feature graphic) use, per language and device class. */ export function framesNeeded(config: ShipConfig, langs: string[], tablets?: boolean): { lang: string; device: 'phone' | 'tablet'; name: string }[] { @@ -66,9 +99,10 @@ export function rendersCheck(config: ShipConfig, dir: string): Record<'apple' | export async function run(ctx: Ctx): Promise { const { config, resolve, root } = ctx.loaded; const scan = scanProject(ctx); - const issues = [...allIssues(scan), ...localFontIssues(readManifest(fontsDirOf(root))).map(issue => ({ where: '.storebound/fonts/fonts.json', issue }))]; const cap = config.shots?.capture; const tablets = resolvedTablets(config, resolve(ctx.args.get('src') ?? config.renders ?? config.shots?.out ?? 'store/renders')); + const issues = [...allIssues(scan), ...localFontIssues(readManifest(fontsDirOf(root))).map(issue => ({ where: '.storebound/fonts/fonts.json', issue })), + ...backgroundIssues(config, resolve, tablets)]; const frameIssues = cap?.source === 'folder' ? checkFrameFolder(config, resolve(cap.folder ?? config.shots!.frames), scan.langs, tablets) : []; if (ctx.args.has('json')) { printJson({ images: scan.images.length, videos: scan.videos.length, issues, frames: frameIssues }); diff --git a/cli/shots/feature-app.html b/cli/shots/feature-app.html index 8a065f5..31ba34d 100644 --- a/cli/shots/feature-app.html +++ b/cli/shots/feature-app.html @@ -34,7 +34,7 @@ const lang = q.get('lang'), V = q.get('v') ?? ''; const job = await (await fetch(`/job.json?lang=${encodeURIComponent(lang)}&feature=1&v=${encodeURIComponent(V)}`)).json(); const P = job.palette, R = document.documentElement.style, dev = job.phone; const rgba = (hex, a) => { const m = /^#?([0-9a-f]{6})$/i.exec(hex); if (!m) return hex; const n = parseInt(m[1], 16); return `rgba(${n >> 16},${(n >> 8) & 255},${n & 255},${a})`; }; -R.setProperty('--bg', `linear-gradient(135deg, ${P.bg[0]} 0%, ${P.bg[1]} 55%, ${P.bg[2]} 100%)`); +R.setProperty('--bg', P.bgCss ?? (Array.isArray(P.bg) ? `linear-gradient(135deg, ${P.bg.join(', ')})` : P.bg)); // palette.ts: stops, colour, gradient string or photo + overlay R.setProperty('--ink', P.ink); R.setProperty('--shadow', P.shadow); R.setProperty('--accentSoft', rgba(P.glow, .18)); R.setProperty('--tf', (job.fonts.titleStack ?? [job.fonts.title]).map(f => `'${f}'`).join(', ') + ', sans-serif'); R.setProperty('--ar', `${dev.w} / ${dev.h + dev.bar}`); diff --git a/cli/shots/feature.html b/cli/shots/feature.html index 792cd3b..b7147f6 100644 --- a/cli/shots/feature.html +++ b/cli/shots/feature.html @@ -42,7 +42,7 @@ const q = new URLSearchParams(location.search); const lang = q.get('lang'), V = q.get('v') ?? ''; const job = await (await fetch(`/job.json?lang=${encodeURIComponent(lang)}&feature=1&v=${encodeURIComponent(V)}`)).json(); const P = job.palette, R = document.documentElement.style, dev = job.phone; -R.setProperty('--bg', `linear-gradient(160deg, ${P.bg[0]} 0%, ${P.bg[1]} 50%, ${P.bg[2]} 100%)`); +R.setProperty('--bg', P.bgCss ?? (Array.isArray(P.bg) ? `linear-gradient(160deg, ${P.bg.join(', ')})` : P.bg)); // palette.ts: stops, colour, gradient string or photo + overlay R.setProperty('--glow', P.glow); R.setProperty('--ink', P.ink); R.setProperty('--shadow', P.shadow); R.setProperty('--tf', (job.fonts.titleStack ?? [job.fonts.title]).map(f => `'${f}'`).join(', ') + ', sans-serif'); R.setProperty('--ar', `${dev.w} / ${dev.h + dev.bar}`); diff --git a/cli/shots/fonts.ts b/cli/shots/fonts.ts index 5c12828..2f24be8 100644 --- a/cli/shots/fonts.ts +++ b/cli/shots/fonts.ts @@ -19,21 +19,19 @@ import { shotsStyle } from '../lib/config'; import type { CopyFile } from './lib'; import { localByFamily, resolveShotFonts } from './local-fonts'; import { fontCodepoints } from './cmap'; -import { type FaceJob, type FontManifest, fontsCss, planFonts, roleTexts, type RoleTexts } from './glyphs'; +import { SHOTS_PAGES } from '../lib/embedded'; +import { fetchFaces, localWeightGap, serves, styleWeights } from './weights'; +import { type FaceJob, type FaceResult, type FontManifest, fontsCss, planFonts, roleTexts, type RoleTexts } from './glyphs'; -const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'; const ASCII = Array.from({ length: 95 }, (_, i) => String.fromCharCode(32 + i)).join('') + '·'; export async function fetchSubset(family: string, chars: string, axis: string | null): Promise { - const fam = encodeURIComponent(family) + (axis ? ':' + axis : ''); - let res = await fetch(`https://fonts.googleapis.com/css2?family=${fam}&text=${encodeURIComponent(chars)}&display=block`, { headers: { 'user-agent': UA } }); - if (!res.ok && axis) return fetchSubset(family, chars, null); - if (!res.ok) throw new Error(`${family}: ${res.status} ${(await res.text()).slice(0, 200)}`); - const src = /url\((https:[^)]+)\)/.exec(await res.text())?.[1]; - if (!src) throw new Error(`${family}: no font url`); - res = await fetch(src, { headers: { 'user-agent': UA } }); - if (!res.ok) throw new Error(`${family}: ${res.status} for ${src}`); - return res.arrayBuffer(); + return (await fetchFaces(family, chars, { axis }))[0]!.bin; +} + +/** Weights the style's templates (screenshot + feature graphic) ask for, per role. */ +export function weightsFor(style: 'game' | 'app'): { title: number[]; body: number[] } { + return styleWeights(style === 'app' ? [SHOTS_PAGES['template-app.html']!, SHOTS_PAGES['feature-app.html']!] : [SHOTS_PAGES['template.html']!, SHOTS_PAGES['feature.html']!]); } /** Per-language role texts for every language of the copy and the config. */ @@ -57,16 +55,16 @@ export async function run(ctx: Ctx): Promise { mkdirSync(dir, { recursive: true }); const style = shotsStyle(config); const sf = resolveShotFonts(shots, style, resolve, root); - const { titleVariable } = sf; + const W = weightsFor(style); const title = sf.title.family, body = sf.body.family; const local = localByFamily([sf.title, sf.body, ...sf.fallback]); const texts = langTexts(copy, config.languages.map(l => l.id), config.app.name); const sizes: string[] = []; const manifest = await planFonts({ - langs: texts, title, body, titleAxis: titleVariable ? 'wght@100..900' : null, bodyAxis: 'wght@100..900', + langs: texts, title, body, titleAxis: null, bodyAxis: null, titleWeights: W.title, bodyWeights: W.body, fallbackTitleAxis: style === 'app' ? 'wght@100..900' : 'wght@800', chosen: sf.fallback.map(f => f.family), base: ASCII, local, - }, async (job: FaceJob) => { + }, async (job: FaceJob): Promise => { if (job.local) { // read in place: the whole file's cmap const bin = new Uint8Array(readFileSync(join(root, job.local.path))); const cps = fontCodepoints(bin); @@ -74,21 +72,39 @@ export async function run(ctx: Ctx): Promise { if (!sizes.includes(line)) sizes.push(line); return cps; } - let bin: Uint8Array; - try { bin = new Uint8Array(await fetchSubset(job.family, job.chars, job.axis)); } catch (e) { + let got: { weight: string; bin: ArrayBuffer }[]; + try { got = await fetchFaces(job.family, job.chars, job.weights ? { weights: job.weights } : { axis: job.axis }); } catch (e) { if (job.kind !== 'fallback') throw e; log('shots', `${job.family} has none of ${[...job.chars].join(' ')} (${(e as Error).message.split(' for ')[0]}), trying the next fallback`); return new Set(); } - writeFileSync(join(dir, job.file), bin); + const bin = new Uint8Array(got[0]!.bin); + writeFileSync(join(dir, job.file), bin); // the cmap / coverage file (every weight has the same subset) const cps = fontCodepoints(bin); - sizes.push(`${job.file.padEnd(28)} ${job.family.padEnd(22)} ${(bin.byteLength / 1024).toFixed(1)} KB, ${[...job.chars].length} chars asked, ${cps.size} in the cmap`); + const weights = got.map(g => g.weight).join(', '); + sizes.push(`${job.file.padEnd(28)} ${job.family.padEnd(22)} ${(got.reduce((t, g) => t + g.bin.byteLength, 0) / 1024).toFixed(1)} KB, weight ${weights}, ${[...job.chars].length} chars asked, ${cps.size} in the cmap`); + if (job.weights) { + const files = got.length === 1 ? [{ file: job.file, weight: got[0]!.weight }] : got.map(g => { + const file = job.file.replace(/\.woff2$/, `-${g.weight.replace(/ /g, '-')}.woff2`); + writeFileSync(join(dir, file), new Uint8Array(g.bin)); + return { file, weight: g.weight }; + }); + const miss = job.weights.filter(w => !files.some(f => serves(f.weight, w))); + if (miss.length) warn('shots', `${job.family} (${job.role ?? job.kind}) has no weight ${miss.join(', ')} (got ${weights}): the templates ask for it, so those lines are drawn at the nearest weight. Pick a family with these weights for a heavier headline`); + return { cps, files }; + } return cps; }); writeFileSync(join(dir, 'fonts.css'), fontsCss(manifest)); writeFileSync(join(dir, 'fonts.json'), JSON.stringify(manifest, null, 1) + '\n'); if (ctx.args.has('json')) return printJson(manifest); for (const s of sizes) log('shots', s); + for (const [role, ref] of [['title', sf.title], ['body', sf.body]] as const) { + if (!ref.local) continue; + const gap = localWeightGap(ref.local.weight, W[role]); + if (gap.length) warn('shots', `local font ${ref.local.path} is declared as weight ${ref.local.weight}, but the templates ask the ${role} for ${gap.join(', ')}: those lines are drawn at ${ref.local.weight} (never faked bolder). Add a file with that weight or accept it`); + else if (ref.local.weight === undefined && role === 'title') log('shots', `local font ${ref.local.path} has no weight: declared for 100-900, so a static file draws its own weight for the ${role} weights ${W[role].join(', ')}. Give { weight } for a static file`); + } for (const f of Object.values(local)) if (!f.license) warn('shots', `local font ${f.path} has no license note: add license ('OFL-1.1', 'proprietary', ...) to its shots.fonts entry`); let auto = 0; for (const [lang, l] of Object.entries(manifest.langs)) for (const f of l.fallbacks) { diff --git a/cli/shots/glyphs.ts b/cli/shots/glyphs.ts index 34168d1..bc2fdde 100644 --- a/cli/shots/glyphs.ts +++ b/cli/shots/glyphs.ts @@ -66,12 +66,19 @@ export const FALLBACK_ORDER = ['Noto Sans Display', 'Noto Sans', 'Noto Sans KR', export type FaceKind = 'title' | 'body' | 'script' | 'fallback'; /** One downloaded face: `face` is the @font-face family name the templates use. axis: css2 axis spec ("wght@800", * "wght@100..900") or null for the font's default instance. */ -export interface FaceJob { face: string; family: string; file: string; kind: FaceKind; role?: Role; axis: string | null; chars: string; local?: LocalFontInfo } +export interface FaceJob { face: string; family: string; file: string; kind: FaceKind; role?: Role; axis: string | null; chars: string; local?: LocalFontInfo; + /** Weights the templates use for this face's role (title / body): the getter fetches them (weights.ts fetchFaces). */ + weights?: number[] } +/** What a getter returns: the covered code points, and (several weights downloaded) the files with their weight. */ +export type FaceResult = Set | { cps: Set; files: FaceFile[] }; +export interface FaceFile { file: string; weight: string } export interface LangFonts { title: string[]; body: string[]; fallbacks: { role: Role; face: string; family: string; chars: string }[] } export interface FontManifest { v: 1; /** local: a local font file (shots.fonts entry with a path), read in place, never copied; file = its served path. */ - faces: Record; + faces: Record; langs: Record; } @@ -80,6 +87,8 @@ export interface PlanInput { title: string; body: string; /** css2 axis for the title / body family (null = default instance). */ titleAxis: string | null; bodyAxis: string | null; + /** Weights the templates use per role (weights.ts styleWeights); set = fetch these instead of titleAxis / bodyAxis. */ + titleWeights?: number[]; bodyWeights?: number[]; /** Weight axis for automatic title fallbacks (game titles are heavy display faces: "wght@800"). */ fallbackTitleAxis: string | null; /** shots.fonts.fallback: families the owner accepts as fallbacks, in order. Families that are not one of the automatic @@ -102,7 +111,14 @@ export class GlyphError extends Error { /** Faces for every language's copy: title + body, one Noto face per non-Latin script (whole lines, as before), and an * automatic Noto fallback for each character the stack still lacks. `get` downloads a face (only the listed chars) * and returns the code points its cmap covers. Throws GlyphError when no fallback covers a character. */ -export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise>): Promise { +export async function planFonts(input: PlanInput, get0: (job: FaceJob) => Promise): Promise { + const files = new Map(); + const get = async (job: FaceJob): Promise> => { + const r = await get0(job); + if (r instanceof Set) return r; + files.set(job.face, r.files); + return r.cps; + }; const chosen = new Set((input.chosen ?? []).map(s => s.toLowerCase())); const local = input.local ?? {}; const extra = [...new Set(input.chosen ?? [])].filter(f => !FALLBACK_ORDER.some(n => n.toLowerCase() === f.toLowerCase())); @@ -130,13 +146,15 @@ export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise const add = async (job: FaceJob, isChosen: boolean): Promise => { cps.set(job.face, await get(job)); if (job.kind === 'fallback' && ![...job.chars].some(ch => cps.get(job.face)!.has(ch.codePointAt(0)!))) return; // covers none: not a face - faces[job.face] = { family: job.family, file: job.file, kind: job.kind, ...(job.role ? { role: job.role } : {}), chosen: isChosen, ...(job.local ? { local: job.local } : {}) }; + faces[job.face] = { family: job.family, file: job.file, kind: job.kind, ...(job.role ? { role: job.role } : {}), chosen: isChosen, ...(job.local ? { local: job.local } : {}), ...(files.has(job.face) ? { files: files.get(job.face) } : {}) }; }; - await add({ face: input.title, family: input.title, file: fileOf(input.title, 'title.woff2'), kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted(roleChars.title), ...loc(input.title) }, true); - if (input.body !== input.title) await add({ face: input.body, family: input.body, file: fileOf(input.body, 'body.woff2'), kind: 'body', role: 'body', axis: input.bodyAxis, chars: sorted(roleChars.body), ...loc(input.body) }, true); + await add({ face: input.title, family: input.title, file: fileOf(input.title, 'title.woff2'), kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted(roleChars.title), ...loc(input.title), ...(input.titleWeights ? { weights: input.titleWeights } : {}) }, true); + if (input.body !== input.title) await add({ face: input.body, family: input.body, file: fileOf(input.body, 'body.woff2'), kind: 'body', role: 'body', axis: input.bodyAxis, chars: sorted(roleChars.body), ...loc(input.body), ...(input.bodyWeights ? { weights: input.bodyWeights } : {}) }, true); else { // same family: one download (title axis) with both roles' characters const t = faces[input.title]!; - cps.set(input.title, await get({ face: input.title, family: input.title, file: t.file, kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted([...roleChars.title, ...roleChars.body]), ...loc(input.title) })); + cps.set(input.title, await get({ face: input.title, family: input.title, file: t.file, kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted([...roleChars.title, ...roleChars.body]), ...loc(input.title), + ...(input.titleWeights ? { weights: [...new Set([...input.titleWeights, ...(input.bodyWeights ?? [])])].sort((a, b) => a - b) } : {}) })); + if (files.has(input.title)) t.files = files.get(input.title); } for (const [s, v] of scripts) await add({ face: `Store ${s}`, family: v.family, file: `${s}.woff2`, kind: 'script', axis: 'wght@100..900', chars: sorted(v.chars) }, true); @@ -202,6 +220,10 @@ export function fontsCss(m: FontManifest): string { css += `@font-face { font-family: '${face}'; font-weight: ${l.weight ?? '100 900'}; font-style: ${l.style ?? 'normal'}; font-synthesis: none; src: url(${f.file}?v=${l.hash}) format('${l.format}'); }\n`; continue; } + if (f.files?.length) { // one file per downloaded weight: a weight the family lacks is drawn at the nearest one (never faked) + for (const x of f.files) css += `@font-face { font-family: '${face}'; font-weight: ${x.weight}; font-synthesis: none; src: url(${x.file}) format('woff2'); }\n`; + continue; + } css += `@font-face { font-family: '${face}'; font-weight: 100 900; font-synthesis: none; src: url(${f.file}) format('woff2'); }\n`; } return css; diff --git a/cli/shots/lib.ts b/cli/shots/lib.ts index 0e4abfd..b440186 100644 --- a/cli/shots/lib.ts +++ b/cli/shots/lib.ts @@ -1,5 +1,6 @@ // Pure parts of the screenshot pipeline: store sizes, palettes, per-language script fonts, copy validation, job data. import { specFamily } from './local-fonts'; +import { bgIssue } from './palette'; import type { Palette, ShipConfig, ShotScene, ShotsConfig } from '../lib/config'; /** Store image sizes. ios69 = 6.9" (APP_IPHONE_67), ios65 = 6.5" (APP_IPHONE_65), iphone-medium = 6.3" iPhone with @@ -94,7 +95,11 @@ export const APP_PALETTES: Record = { export const palette = (p: string | Palette | undefined, style: 'game' | 'app' = 'game'): Palette => { const own = style === 'app' ? APP_PALETTES : PALETTES; if (!p) return style === 'app' ? APP_PALETTES.mist! : PALETTES.fire!; - if (typeof p !== 'string') return p; + if (typeof p !== 'string') { + const bad = bgIssue(p.bg); + if (bad) throw new Error(`${bad} (got ${JSON.stringify(p.bg)})`); + return p; + } const hit = own[p] ?? PALETTES[p] ?? APP_PALETTES[p]; if (!hit) throw new Error(`unknown palette "${p}" (${Object.keys(own).join(', ')}) or pass { bg, glow, ink, shadow }`); return hit; diff --git a/cli/shots/palette.ts b/cli/shots/palette.ts new file mode 100644 index 0000000..2daeca1 --- /dev/null +++ b/cli/shots/palette.ts @@ -0,0 +1,131 @@ +// Palette backgrounds, photo backgrounds and the contrast guard. Pure (no fs, no browser): config validation, render +// (job.json) and `shots check` share it. +// bg: ['#a', '#b', '#c'] | ['#a', '#b'] gradient stops (each template keeps its own angle) +// '#15171C' | 'rgb(...)' | 'navy' one colour, flat +// 'linear-gradient(...)' any CSS gradient, passed through as is +// image: 'store/art/x.png', overlay: 0.45 photo under a dark overlay, cropped to cover (palette or shots.feature.background) +import type { Palette } from '../lib/config'; + +const COLOUR_RE = /^(#[0-9a-f]{3,4}|#[0-9a-f]{6}|#[0-9a-f]{8}|(rgb|hsl)a?\([^()]*\)|[a-z]{3,30})$/i; +const GRADIENT_RE = /^(repeating-)?(linear|radial|conic)-gradient\(.*\)$/is; +export const isColour = (s: unknown): s is string => typeof s === 'string' && COLOUR_RE.test(s.trim()) && !/^(none|inherit|initial|unset)$/i.test(s.trim()); +export const isGradient = (s: unknown): s is string => typeof s === 'string' && GRADIENT_RE.test(s.trim()); + +export const BG_ERROR = 'palette.bg must be a colour, a gradient or an array of 2-3 colours'; +export const DEFAULT_OVERLAY = 0.45; + +/** Problem with a palette's bg (null = fine). */ +export function bgIssue(bg: unknown): string | null { + if (isColour(bg) || isGradient(bg)) return null; + if (Array.isArray(bg) && bg.length >= 2 && bg.length <= 3 && bg.every(isColour)) return null; + return BG_ERROR; +} + +const overlayOk = (o: unknown): boolean => o === undefined || (typeof o === 'number' && o >= 0 && o <= 0.9); +const imageOk = (i: unknown): boolean => typeof i === 'string' && /\.(png|jpe?g|webp)$/i.test(i.trim()); + +/** Config validation of one palette (a named palette string is checked when it is resolved). */ +export function paletteIssues(p: unknown, key: string): string[] { + if (typeof p === 'string') return []; + if (!p || typeof p !== 'object') return [`${key}: a palette name or { bg, glow, ink, shadow }`]; + const o = p as Partial, e: string[] = []; + const bi = bgIssue(o.bg); + if (bi) e.push(`${key}.bg: ${bi} (got ${JSON.stringify(o.bg)})`); + for (const k of ['glow', 'ink', 'shadow'] as const) if (!isColour(o[k])) e.push(`${key}.${k}: a colour`); + if (o.image !== undefined && !imageOk(o.image)) e.push(`${key}.image: a PNG, JPEG or WebP path (relative to the config)`); + if (!overlayOk(o.overlay)) e.push(`${key}.overlay: a number from 0 to 0.9 (dark overlay over the image)`); + return e; +} + +export function featureBackgroundIssues(b: unknown): string[] { + if (b === undefined) return []; + const o = typeof b === 'string' ? { image: b } : b as { image?: unknown; overlay?: unknown } | null; + if (!o || typeof o !== 'object' || !imageOk(o.image)) return ['shots.feature.background: a PNG, JPEG or WebP path or { image, overlay } (relative to the config)']; + return overlayOk(o.overlay) ? [] : ['shots.feature.background.overlay: a number from 0 to 0.9']; +} + +/** The photo background in effect: shots.feature.background (feature graphic only), else the palette's image. */ +export function photoBackground(p: Palette, featureBg?: string | { image: string; overlay?: number }): { image: string; overlay: number } | null { + const f = typeof featureBg === 'string' ? { image: featureBg } : featureBg; + const image = f?.image ?? p.image; + if (!image) return null; + return { image, overlay: f?.overlay ?? p.overlay ?? DEFAULT_OVERLAY }; +} + +/** CSS background for a palette bg at a template's angle (stops at 0 %, mid %, 100 %). */ +export function bgCss(bg: Palette['bg'], angle = 180, mid = 55): string { + if (typeof bg === 'string') return bg.trim(); + if (bg.length === 2) return bg[0] === bg[1] ? bg[0] : `linear-gradient(${angle}deg, ${bg[0]} 0%, ${bg[1]} 100%)`; + if (bg[0] === bg[1] && bg[1] === bg[2]) return bg[0]; + return `linear-gradient(${angle}deg, ${bg[0]} 0%, ${bg[1]} ${mid}%, ${bg[2]} 100%)`; +} + +/** A photo under a flat dark overlay, cropped to cover (CSS cover = coverCrop below). */ +export function photoCss(url: string, overlay: number): string { + return `linear-gradient(rgba(0,0,0,${overlay}), rgba(0,0,0,${overlay})), url('${url}') center / cover no-repeat`; +} + +/** One colour that stands for the background (the middle stop, the colour, the first colour of a gradient), for + * light / dark decisions in the templates. A photo counts as dark from an overlay of 0.35 up. */ +export function bgTone(bg: Palette['bg']): string { + if (Array.isArray(bg)) return bg[Math.floor(bg.length / 2)]!; + const m = /#[0-9a-f]{3,8}\b|(rgb|hsl)a?\([^()]*\)/i.exec(bg); + return m ? m[0] : bg; +} + +/** Source rectangle a cover crop takes from a srcW x srcH image for an outW x outH box (centred), and the scale + * (> 1 = the image is upscaled: too small for the output). */ +export function coverCrop(srcW: number, srcH: number, outW: number, outH: number): { x: number; y: number; w: number; h: number; scale: number } { + const scale = Math.max(outW / srcW, outH / srcH); + const w = outW / scale, h = outH / scale; + return { x: (srcW - w) / 2, y: (srcH - h) / 2, w, h, scale }; +} + +/** Problems of a photo background for one output size: missing file, smaller than the output (upscaled = blurry). */ +export function photoIssues(img: { w: number; h: number } | null, file: string, outW: number, outH: number): { level: 'error' | 'warn'; msg: string }[] { + if (!img) return [{ level: 'error', msg: `background image ${file} not found or not a PNG / JPEG / WebP` }]; + const c = coverCrop(img.w, img.h, outW, outH); + return c.scale > 1.001 ? [{ level: 'warn', msg: `background image ${file} is ${img.w}x${img.h}, smaller than the ${outW}x${outH} output (upscaled ${c.scale.toFixed(2)}x, blurry): use one at least ${outW}x${outH}` }] : []; +} + +// ---- contrast ------------------------------------------------------------------------------------------------- + +export type RGB = [number, number, number]; + +/** #rgb / #rrggbb / rgb(a)() to RGB (alpha ignored); null for anything else. */ +export function parseColour(s: string): RGB | null { + const t = s.trim(); + let m = /^#([0-9a-f]{3})$/i.exec(t); + if (m) return [...m[1]!].map(c => parseInt(c + c, 16)) as RGB; + m = /^#([0-9a-f]{6})([0-9a-f]{2})?$/i.exec(t); + if (m) { const n = parseInt(m[1]!, 16); return [n >> 16, (n >> 8) & 255, n & 255]; } + m = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(t); + if (m) return [+m[1]!, +m[2]!, +m[3]!]; + return null; +} + +const lin = (c: number): number => { const s = c / 255; return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; }; +export const luminance = ([r, g, b]: RGB): number => 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b); +/** WCAG contrast ratio, 1..21. */ +export function contrastRatio(a: RGB, b: RGB): number { + const [x, y] = [luminance(a), luminance(b)].sort((p, q) => q - p) as [number, number]; + return (x + 0.05) / (y + 0.05); +} + +/** One title element's contrast as `shots render` records it: ink colour, the background samples behind the text + * (text hidden), and the worst ratio. */ +export interface ContrastSample { el: string; ink: string; worst: RGB; ratio: number } + +/** Worst contrast of an ink colour over background pixel samples. */ +export function worstContrast(ink: RGB, samples: RGB[]): { worst: RGB; ratio: number } { + let best = { worst: samples[0] ?? ink, ratio: 21 }; + for (const s of samples) { const r = contrastRatio(ink, s); if (r < best.ratio) best = { worst: s, ratio: r }; } + return best; +} + +/** Large headline text: WCAG AA large text asks 3:1; under 2:1 it is close to invisible (white on white). */ +export const CONTRAST_MIN = 3; +export function contrastIssues(samples: ContrastSample[] | undefined): { level: 'warn'; code: 'contrast'; msg: string }[] { + return (samples ?? []).filter(s => s.ratio < CONTRAST_MIN).map(s => ({ level: 'warn' as const, code: 'contrast' as const, + msg: `${s.el} ink ${s.ink} has low contrast against the background behind it (${s.ratio.toFixed(2)}:1, rgb(${s.worst.join(',')}); want >= ${CONTRAST_MIN}:1)${s.ratio < 1.5 ? ': the text is close to invisible' : ''}. Check palette.bg / ink (a string bg needs a colour or a CSS gradient) or raise the photo overlay` })); +} diff --git a/cli/shots/render.ts b/cli/shots/render.ts index 3ab7876..4aa751d 100644 --- a/cli/shots/render.ts +++ b/cli/shots/render.ts @@ -26,6 +26,9 @@ import { closeBrowser, launch } from './browser'; import { defaultConcurrency, pool, progressLine } from './capture-web'; import { shotsStyle } from '../lib/config'; import { type CopyFile, type DeviceBox, type TextBox, SIZES, renderDims, sheetTimeoutMs, featureLayout, copyText, defaultSizes, frameDims, mergeCopy, palette, renderDir, scriptFont, sheetLayout, validateCopy, variantScenes } from './lib'; +import { bgCss, bgTone, type ContrastSample, contrastIssues, parseColour, photoBackground, photoCss, type RGB, worstContrast } from './palette'; +import { type WeightSample, weightIssues } from './weights'; +import type { Palette } from '../lib/config'; import { faceFilePath, fontsRoute, resolveShotFonts, staleLocalFonts } from './local-fonts'; import { type RenderReport, mergeReport, readReport, resolvedTablets } from './report'; import * as rt from '../lib/rt'; @@ -123,6 +126,19 @@ export async function run(ctx: Ctx): Promise { for (const lang of langs) for (const f of manifest.langs[lang]?.fallbacks ?? []) (manifest.faces[f.face]?.chosen ? log : warn)('shots', `${lang} ${f.role}: ${[...f.chars].join(' ')} from ${f.family}${manifest.faces[f.face]?.chosen ? '' : ' (automatic fallback: shots check will fail)'}`); } + // palette backgrounds as CSS (colour, gradient string or stops) and photo backgrounds, served at /bgimg/ + const photos: string[] = []; + const look = (pl: Palette, angle: number, mid: number, featureBg?: NonNullable['background']): Palette & { bgCss: string; bgTone: string; photo?: { overlay: number } } => { + const ph = photoBackground(pl, featureBg); + let css = bgCss(pl.bg, angle, mid); + if (ph) { + const abs = resolve(ph.image); + if (!existsSync(abs)) throw new Error(`shots render: background image ${ph.image} not found (${abs})`); + if (!photos.includes(abs)) photos.push(abs); + css = photoCss(`/bgimg/${photos.indexOf(abs)}`, ph.overlay) + ', ' + css; + } + return { ...pl, bgCss: css, bgTone: ph && ph.overlay >= 0.35 ? '#000000' : bgTone(pl.bg), ...(ph ? { photo: { overlay: ph.overlay } } : {}) }; + }; const server = await rt.serve({ port: a.num('port', 8792), hostname: '127.0.0.1', async fetch(req) { @@ -138,14 +154,16 @@ export async function run(ctx: Ctx): Promise { fonts: { ...fonts, script: st.script, titleStack: st.title, bodyStack: st.body } }; if (url.searchParams.has('feature')) return Response.json({ ...base, frame: shots.feature?.frame ?? scenes[0]!.frames[0]!.src, - device: featureLayout(style, phone, { fit: shots.feature?.fit, scale: shots.feature?.scale }), palette: palette(shots.feature?.palette ?? scenes[0]!.palette, style) }); + device: featureLayout(style, phone, { fit: shots.feature?.fit, scale: shots.feature?.scale }), + palette: look(palette(shots.feature?.palette ?? scenes[0]!.palette, style), style === 'app' ? 135 : 160, style === 'app' ? 55 : 50, shots.feature?.background) }); const sid = url.searchParams.get('s') ?? ''; const scene = scenes.find(s => s.id === sid)!; const number = scenes.filter(s => !s.hero).indexOf(scene) + 1; - return Response.json({ ...base, scene, number, palette: palette(scene.palette, style), copy: copy[lang]?.[sid] ?? {} }); + return Response.json({ ...base, scene, number, palette: look(palette(scene.palette, style), 180, style === 'app' ? 55 : 48), copy: copy[lang]?.[sid] ?? {} }); } let file = ''; if (p === '/logo' && shots.logo) file = resolve(shots.logo); + else if (p.startsWith('/bgimg/')) file = photos[Number(p.slice(7))] ?? ''; else if (p.startsWith('/frames/')) file = join(framesDir, p.slice(8)); else if (p.startsWith('/fonts/')) file = fontsRoute(p.slice(7), fontsDir, root, manifest) ?? ''; else if (p.startsWith('/out/')) file = join(outDir, p.slice(5)); @@ -195,12 +213,20 @@ export async function run(ctx: Ctx): Promise { if (!out.endsWith('sheet.png')) { const measured = await measureFonts(page, Object.keys(faces)); const usage = fontUsage(measured, faces); - report[relative(outDir, out)] = { overflow, devices, ...(bleed ? { bleed } : {}), ...(boxes.length ? { boxes } : {}), missing: errs.filter(e => e.startsWith('404')), fonts: usage }; + const weights = await titleWeights(page, sf.title); + report[relative(outDir, out)] = { overflow, devices, ...(bleed ? { bleed } : {}), ...(boxes.length ? { boxes } : {}), missing: errs.filter(e => e.startsWith('404')), fonts: usage, ...(weights.length ? { weights } : {}) }; + for (const i of weightIssues(weights)) warn('shots', `${relative(root, out)}: ${i.msg}`); for (const f of usage.fallback) warn('shots', `${relative(root, out)}: ${f.el} ${[...f.chars].join(' ')} drawn with ${f.family} (automatic fallback)`); for (const f of usage.missing) warn('shots', `${relative(root, out)}: ${f.el} ${[...f.chars].join(' ')} drawn with a system font`); } if (overflow.length) warn('shots', `${relative(root, out)}: ${overflow.join('; ')}`); await page.screenshot({ path: tmp, clip: { x: 0, y: 0, width: w, height: h } }); + if (style === 'app' && !out.endsWith('sheet.png')) { // contrast guard: title ink vs. the pixels behind it (text hidden) + const contrast = await titleContrast(page, w, h); + const r = report[relative(outDir, out)]; + if (r && contrast.length) r.contrast = contrast; + for (const i of contrastIssues(contrast)) warn('shots', `${relative(root, out)}: ${i.msg}`); + } const ff = rt.spawn(['ffmpeg', '-v', 'error', '-y', '-i', tmp, '-pix_fmt', 'rgb24', out], { stderr: 'pipe' }); const code = await ff.exited; rmSync(tmp, { force: true }); @@ -268,3 +294,52 @@ export async function run(ctx: Ctx): Promise { if (flagged) warn('shots', `${flagged} images with text overflow flags: storebound shots check / shots gallery`); done('shots', `render done${warnings ? `, ${warnings} with warnings (missing frames or fonts?)` : ''}`); } + +/** Title elements' asked weight vs. the weights the loaded faces of the title family serve (report.json `weights`). */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export async function titleWeights(page: any, family: string): Promise { + return (await page.evaluate(`(() => { + const fam = ${JSON.stringify(family)}; + const served = [...document.fonts].filter(f => f.family.replace(/["']/g, '') === fam && f.status === 'loaded').map(f => String(f.weight)); + const seen = new Set(), out = []; + for (const e of document.querySelectorAll('h1 span, .name')) { + const want = Number(getComputedStyle(e).fontWeight), el = e.matches('.name') ? 'app name' : 'title'; + if (!e.textContent.trim() || seen.has(el + want)) continue; + seen.add(el + want); + out.push({ el, family: fam, want, served: [...new Set(served)] }); + } + return out; + })()`)) as WeightSample[]; +} + +/** Title ink vs. the background behind it: hides the title text, screenshots each title box, averages it into a + * small grid with ffmpeg and keeps the worst contrast (report.json `contrast`). Run after the real screenshot. */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export async function titleContrast(page: any, W: number, H: number): Promise { + const els = (await page.evaluate(`(() => { + const out = []; + for (const e of document.querySelectorAll('h1 span, .name')) { + if (!e.textContent.trim()) continue; + const r = e.getBoundingClientRect(); + out.push({ el: e.matches('.name') ? 'app name' : 'title', ink: getComputedStyle(e).color, x: r.x, y: r.y, w: r.width, h: r.height }); + } + for (const e of document.querySelectorAll('h1, .name')) e.style.visibility = 'hidden'; + return out; + })()`)) as { el: string; ink: string; x: number; y: number; w: number; h: number }[]; + const out: ContrastSample[] = []; + for (const e of els) { + const ink = parseColour(e.ink); + const x = Math.max(0, Math.floor(e.x)), y = Math.max(0, Math.floor(e.y)); + const cw = Math.min(W - x, Math.ceil(e.w)), ch = Math.min(H - y, Math.ceil(e.h)); + if (!ink || cw < 2 || ch < 2) continue; + const png = await page.screenshot({ clip: { x, y, width: cw, height: ch } }) as Uint8Array; + const r = rt.spawnSync(['ffmpeg', '-v', 'error', '-i', 'pipe:0', '-vf', 'scale=8:3:flags=area', '-f', 'rawvideo', '-pix_fmt', 'rgb24', 'pipe:1'], { stdin: png, timeout: 15000 }); + const raw = r.stdout; + if (r.exitCode !== 0 || raw.length < 3) continue; + const samples: RGB[] = []; + for (let i = 0; i + 2 < raw.length; i += 3) samples.push([raw[i]!, raw[i + 1]!, raw[i + 2]!]); + const wc = worstContrast(ink, samples); + out.push({ el: e.el, ink: e.ink, worst: wc.worst, ratio: Math.round(wc.ratio * 100) / 100 }); + } + return out; +} diff --git a/cli/shots/report.ts b/cli/shots/report.ts index 4cc9fbf..f197ada 100644 --- a/cli/shots/report.ts +++ b/cli/shots/report.ts @@ -5,6 +5,8 @@ import { join } from 'node:path'; import { spawnSync } from 'node:child_process'; import { boxOutside, type DeviceBox, marginViolations, PLAY_TABLET_SIZES, SIZES, type TextBox } from './lib'; import { fontIssues, type FontUsage } from './glyphs'; +import { type ContrastSample, contrastIssues } from './palette'; +import { type WeightSample, weightIssues } from './weights'; import { pulledEntry, readPulled } from '../lib/art-pull'; import { checkCount, checkImage, checkVideo, type ImageInfo, imageInfo, type Issue, IMAGE_SPECS, parseProbe, PREVIEW_RULES, type ProbeInfo, VIDEO_TARGETS } from './spec'; @@ -14,7 +16,9 @@ export type RenderReport = Record; + boxes?: TextBox[]; + /** Title weight asked vs. served (weights.ts), and title ink contrast over the pixels behind it (palette.ts). */ + weights?: WeightSample[]; contrast?: ContrastSample[] }>; /** Text or logo closer to an edge than the safe margin: an error (stores crop and round corners; it reads cramped). */ export function marginIssues(entry: RenderReport[string] | undefined, W: number, H: number): Issue[] { @@ -88,6 +92,7 @@ export function scanRenders(dir: string, o: { langs: string[]; variants?: string issues.push(...fontIssues(entry?.fonts)); issues.push(...deviceIssues(entry, size, info.w, info.h)); issues.push(...marginIssues(entry, info.w, info.h)); + issues.push(...weightIssues(entry?.weights), ...contrastIssues(entry?.contrast)); if (entry && !entry.fonts) issues.push({ level: 'warn', code: 'fonts', msg: 'font usage not recorded (rendered by an older storebound): run shots fonts + shots render again so missing glyphs are caught' }); out.images.push({ rel, lang, variant, size, file, info, issues }); } diff --git a/cli/shots/spec.ts b/cli/shots/spec.ts index bbb21be..10d9bd1 100644 --- a/cli/shots/spec.ts +++ b/cli/shots/spec.ts @@ -122,7 +122,7 @@ export function imageInfo(b: Uint8Array): ImageInfo { } export type IssueLevel = 'error' | 'warn'; -export interface Issue { level: IssueLevel; code: 'size' | 'alpha' | 'format' | 'bytes' | 'count' | 'overflow' | 'video' | 'font-fallback' | 'glyph-missing' | 'device-crop' | 'fonts' | 'margin'; msg: string } +export interface Issue { level: IssueLevel; code: 'size' | 'alpha' | 'format' | 'bytes' | 'count' | 'overflow' | 'video' | 'font-fallback' | 'glyph-missing' | 'device-crop' | 'fonts' | 'margin' | 'font-weight' | 'contrast' | 'background'; msg: string } /** Problems with one image for a size key. */ export function checkImage(info: ImageInfo, sizeKey: string): Issue[] { diff --git a/cli/shots/template-app.html b/cli/shots/template-app.html index b72dac3..2758074 100644 --- a/cli/shots/template-app.html +++ b/cli/shots/template-app.html @@ -95,12 +95,14 @@ const R = document.documentElement.style; // #rrggbb -> rgba with alpha, for the soft accent glow const rgba = (hex, a) => { const m = /^#?([0-9a-f]{6})$/i.exec(hex); if (!m) return hex; const n = parseInt(m[1], 16); return `rgba(${n >> 16},${(n >> 8) & 255},${n & 255},${a})`; }; const lum = hex => { const m = /^#?([0-9a-f]{6})$/i.exec(hex); if (!m) return 1; const n = parseInt(m[1], 16); return (.299 * (n >> 16) + .587 * ((n >> 8) & 255) + .114 * (n & 255)) / 255; }; -const dark = lum(P.bg[1]) < .45; +const tone = P.bgTone ?? (Array.isArray(P.bg) ? P.bg[1] : P.bg); +const dark = !!P.photo && P.photo.overlay >= .35 || lum(tone) < .45; R.setProperty('--W', W + 'px'); R.setProperty('--H', H + 'px'); R.setProperty('--u', u + 'px'); R.setProperty('--ink', P.ink); R.setProperty('--accent', P.glow); R.setProperty('--shadow', P.shadow); R.setProperty('--line2', dark ? P.glow : P.ink); R.setProperty('--accentSoft', rgba(P.glow, dark ? .28 : .14)); -R.setProperty('--bg', P.bg[0] === P.bg[2] && P.bg[1] === P.bg[0] ? P.bg[0] : `linear-gradient(180deg, ${P.bg[0]} 0%, ${P.bg[1]} 55%, ${P.bg[2]} 100%)`); +// bgCss from job.json (palette.ts bgCss / photoCss): stops, one colour, a CSS gradient string, or a photo under an overlay +R.setProperty('--bg', P.bgCss ?? (Array.isArray(P.bg) ? `linear-gradient(180deg, ${P.bg.join(', ')})` : P.bg)); const T = job.fonts.title, B = job.fonts.body, X = job.fonts.script; // titleStack / bodyStack (from shots fonts): script face, the configured font, then any automatic Noto fallback const fstack = (st, def) => (st ?? (X ? [X, def] : [def])).map(f => `'${f}'`).join(', ') + ', sans-serif'; diff --git a/cli/shots/template.html b/cli/shots/template.html index 7cdcf70..524a08e 100644 --- a/cli/shots/template.html +++ b/cli/shots/template.html @@ -143,7 +143,7 @@ const RTL = !!job.rtl; const R = document.documentElement.style; R.setProperty('--W', W + 'px'); R.setProperty('--H', H + 'px'); R.setProperty('--u', u + 'px'); R.setProperty('--ink', P.ink); R.setProperty('--glow', P.glow); R.setProperty('--shadow', P.shadow); -R.setProperty('--bg', `linear-gradient(180deg, ${P.bg[0]} 0%, ${P.bg[1]} 48%, ${P.bg[2]} 100%)`); +R.setProperty('--bg', P.bgCss ?? (Array.isArray(P.bg) ? `linear-gradient(180deg, ${P.bg.join(', ')})` : P.bg)); // palette.ts: stops, colour, gradient string or photo + overlay // A script the title font lacks (CJK, Arabic, Cyrillic, ...): the whole line switches to the Noto subset so a word // never mixes two typefaces. const T = job.fonts.title, B = job.fonts.body, X = job.fonts.script; diff --git a/cli/shots/weights.ts b/cli/shots/weights.ts new file mode 100644 index 0000000..6bedac8 --- /dev/null +++ b/cli/shots/weights.ts @@ -0,0 +1,113 @@ +// Font weights: which weights the templates ask for, how to get them from Google Fonts, and whether a rendered title +// got the weight it asked for. The @font-face rules use font-synthesis: none, so a face that lacks a weight is drawn +// at the nearest weight it has (a 750 headline from a 400-only face renders thin), never faked bolder. +// shots fonts: per role (title / body) the weights of the style's templates (templateWeights); a Google family is +// fetched as the full wght axis when it is variable, else the range the templates use, else those weights one by +// one (static families), else the default instance (fetchFaces). +// shots render: the title's computed weight vs. the weights the loaded faces serve (report.json `weights`); +// shots check warns when the browser fell back to another weight (weightIssues). + +/** Weights a page's CSS asks for, per role: rules that use var(--tf) are title text, the rest body text (the body + * default 400 included). Literal font-weight values plus the numbers set on --tw by the page script. Pure. */ +export function templateWeights(html: string): { title: number[]; body: number[] } { + const tw = [...html.matchAll(/setProperty\('--tw',([^;]+)\)/g)].flatMap(m => [...m[1]!.matchAll(/\b([1-9]00|[1-9][0-9]0)\b/g)].map(x => +x[1]!)); + const title = new Set(), body = new Set([400]); + const style = /').title).toEqual([800]); + }); + test('candidates: full axis, the used range, then rounded statics', () => { + expect(axisCandidates([700, 750])).toEqual(['wght@100..900', 'wght@700..750', 'wght@700;800']); + expect(axisCandidates([400])).toEqual(['wght@100..900', 'wght@400']); + }); + test('variable family with a 200..800 axis (Plus Jakarta Sans): gets the 700..750 range, not the 400 default', async () => { + const g = google({ ranges: [200, 800] }); + const faces = await fetchFaces('Plus Jakarta Sans', 'Ab', { weights: [700, 750] }, g.fn); + expect(faces.map(f => f.weight)).toEqual(['700 750']); + expect(g.asked.filter(u => u.includes('googleapis')).map(u => decodeURIComponent(u).match(/:wght@([^&]+)/)?.[1])).toEqual(['100..900', '700..750']); + expect(serves('700 750', 750)).toBe(true); + }); + test('variable family with the full axis: one request', async () => { + const g = google({ ranges: [100, 900] }); + expect((await fetchFaces('Inter', 'Ab', { weights: [700, 750] }, g.fn)).map(f => f.weight)).toEqual(['100 900']); + }); + test('static family: the weights it has, one by one', async () => { + const g = google({ statics: [400, 700] }); + const faces = await fetchFaces('Static Sans', 'Ab', { weights: [700, 750] }, g.fn); + expect(faces.map(f => f.weight)).toEqual(['700']); + const one = await fetchFaces('Paytone One', 'Ab', { weights: [900] }, google({ statics: [400] }).fn); + expect(one.map(f => f.weight)).toEqual(['400']); // only the default instance exists + }); + test('parseFaces and fontsCss declare each file with its own weight', async () => { + expect(parseFaces("@font-face { font-weight: 200 800; src: url(https://a/b.woff2) }")).toEqual([{ weight: '200 800', url: 'https://a/b.woff2' }]); + const m = await planFonts({ langs: { en: { title: 'Ab', body: 'Ab' } }, title: 'T', body: 'B', titleAxis: null, bodyAxis: null, titleWeights: [700, 750], bodyWeights: [400], fallbackTitleAxis: null }, + async job => job.weights && job.kind === 'title' ? { cps: new Set([65, 98]), files: [{ file: 'title-700.woff2', weight: '700' }, { file: 'title-800.woff2', weight: '800' }] } : new Set([65, 98])); + const css = fontsCss(m); + expect(css).toContain("font-family: 'T'; font-weight: 700; font-synthesis: none; src: url(title-700.woff2)"); + expect(css).toContain("font-family: 'T'; font-weight: 800;"); + expect(css).toContain("font-family: 'B'; font-weight: 100 900;"); + }); + test('local font: a declared weight that cannot serve the asked weight', () => { + expect(localWeightGap('400', [700, 750])).toEqual([700, 750]); + expect(localWeightGap('100 900', [700, 750])).toEqual([]); + expect(localWeightGap(undefined, [700])).toEqual([]); + }); + test('shots check warns when the title was drawn at another weight', () => { + const w = weightIssues([{ el: 'title', family: 'Plus Jakarta Sans', want: 750, served: ['400'] }]); + expect(w.map(i => [i.level, i.code])).toEqual([['warn', 'font-weight']]); + expect(w[0]!.msg).toContain('weight 750'); + expect(weightIssues([{ el: 'title', family: 'Inter', want: 750, served: ['100 900'] }])).toEqual([]); + expect(weightIssues([{ el: 'title', family: 'X', want: 750, served: [] }])).toEqual([]); // not our face: no claim + }); +}); + +describe('palette bg', () => { + test('stops, one colour and a gradient string', () => { + expect(bgCss(['#111111', '#222222', '#333333'], 180, 55)).toBe('linear-gradient(180deg, #111111 0%, #222222 55%, #333333 100%)'); + expect(bgCss(['#111111', '#222222'], 135)).toBe('linear-gradient(135deg, #111111 0%, #222222 100%)'); + expect(bgCss('#15171C')).toBe('#15171C'); + expect(bgCss('linear-gradient(160deg, #0b1736, #1d4ed8)')).toBe('linear-gradient(160deg, #0b1736, #1d4ed8)'); + for (const ok of ['#15171C', 'rgb(10, 20, 30)', 'navy', 'radial-gradient(circle, #000, #333)', ['#000', '#111'], ['#000', '#111', '#222']]) expect(bgIssue(ok)).toBeNull(); + }); + test('anything else is the validation error, in config validation and when resolved', () => { + for (const bad of ['', 'url(x.png)', ['#000'], ['#000', '#111', '#222', '#333'], 42, ['#000', 'not a colour!']]) expect(bgIssue(bad)).toBe(BG_ERROR); + const pal = { bg: 'url(x.png)', glow: '#fff', ink: '#fff', shadow: 'rgba(0,0,0,.4)' }; + expect(() => palette(pal as never, 'app')).toThrow(BG_ERROR); + const errs = validateConfig({ app: { name: 'X', profile: 'app' }, languages: [{ id: 'en' }], + shots: { copy: 'c.json', frames: 'f', out: 'o', scenes: [{ id: 'a', palette: pal, frames: [{ src: 'a.png' }] }] } } as never).filter(e => e.startsWith('shots.')); + expect(errs).toEqual([`shots.scenes[a].palette.bg: ${BG_ERROR} (got "url(x.png)")`]); + expect(paletteIssues({ bg: '#15171C', glow: '#fff', ink: '#fff', shadow: '#000' }, 'p')).toEqual([]); + }); +}); + +describe('contrast guard', () => { + test('white ink on white is caught, white on dark passes', () => { + const white = parseColour('rgb(255, 255, 255)')!; + expect(contrastRatio(white, [0, 0, 0])).toBeCloseTo(21, 0); + const bad = worstContrast(white, [[21, 23, 28], [250, 250, 250]]); + expect(bad.worst).toEqual([250, 250, 250]); + const w = contrastIssues([{ el: 'title', ink: 'rgb(255, 255, 255)', worst: bad.worst, ratio: bad.ratio }]); + expect(w.map(i => [i.level, i.code])).toEqual([['warn', 'contrast']]); + expect(w[0]!.msg).toContain('close to invisible'); + const good = worstContrast(white, [[21, 23, 28], [30, 30, 40]]); + expect(contrastIssues([{ el: 'title', ink: '#fff', worst: good.worst, ratio: good.ratio }])).toEqual([]); + }); +}); + +describe('photo backgrounds', () => { + test('config: palette.image / overlay and shots.feature.background', () => { + const p = { bg: '#000', glow: '#fff', ink: '#fff', shadow: '#000' }; + expect(paletteIssues({ ...p, image: 'store/art/x.png', overlay: 0.5 }, 'p')).toEqual([]); + expect(paletteIssues({ ...p, image: 'x.gif', overlay: 2 }, 'p')).toEqual(['p.image: a PNG, JPEG or WebP path (relative to the config)', 'p.overlay: a number from 0 to 0.9 (dark overlay over the image)']); + expect(featureBackgroundIssues('store/art/hero.jpg')).toEqual([]); + expect(featureBackgroundIssues({ image: 'a.png', overlay: 0.3 })).toEqual([]); + expect(featureBackgroundIssues({ overlay: 0.3 })).toHaveLength(1); + expect(featureBackgroundIssues({ image: 'a.png', overlay: 1 })).toEqual(['shots.feature.background.overlay: a number from 0 to 0.9']); + expect(photoBackground(p as never, 'hero.png')).toEqual({ image: 'hero.png', overlay: 0.45 }); + expect(photoBackground({ ...p, image: 'a.png', overlay: 0.2 } as never)).toEqual({ image: 'a.png', overlay: 0.2 }); + expect(photoBackground(p as never)).toBeNull(); + expect(photoCss('/bgimg/0', 0.45)).toBe("linear-gradient(rgba(0,0,0,0.45), rgba(0,0,0,0.45)), url('/bgimg/0') center / cover no-repeat"); + }); + test('cover crop: centred, the box aspect, scale > 1 = too small', () => { + const c = coverCrop(2048, 2048, 1024, 500); + expect(c.scale).toBe(0.5); + expect([c.x, c.y, c.w, c.h]).toEqual([0, 524, 2048, 1000]); + const t = coverCrop(1000, 2000, 1080, 1920); + expect(t.w / t.h).toBeCloseTo(1080 / 1920, 6); + expect(t.x).toBeCloseTo(0, 6); + expect(photoIssues({ w: 2048, h: 1000 }, 'a.png', 1024, 500)).toEqual([]); + expect(photoIssues({ w: 800, h: 400 }, 'a.png', 1024, 500)[0]!.msg).toContain('smaller than the 1024x500 output'); + expect(photoIssues(null, 'a.png', 1024, 500)[0]!.level).toBe('error'); + }); +}); From d94bf673409b26bfc7ce0299afcd4a50eeb323af Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 03:08:43 +0700 Subject: [PATCH 050/344] tests: the AAB fixture targets API 36 (Play's minimum since 2026-08-31; play upload now refuses 35) --- tests/build-fixtures.ts | 2 +- tests/build-sign.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/build-fixtures.ts b/tests/build-fixtures.ts index 14215bd..9e7704f 100644 --- a/tests/build-fixtures.ts +++ b/tests/build-fixtures.ts @@ -59,6 +59,6 @@ export const makeIpa = (infoPlist: Buffer | string, app = 'Example.app'): Buffer /** An AAB with an aapt2 proto manifest. */ export const makeAab = (pkg: string, versionCode: number, versionName = '1.0.0'): Buffer => makeZip([ { name: 'BundleConfig.pb', data: Buffer.from([8, 1]) }, - { name: 'base/manifest/AndroidManifest.xml', data: encodeProtoManifest([{ name: 'manifest', attrs: { package: pkg, versionCode: String(versionCode), versionName } }, { name: 'uses-sdk', attrs: { minSdkVersion: '24', targetSdkVersion: '35' } }]) }, + { name: 'base/manifest/AndroidManifest.xml', data: encodeProtoManifest([{ name: 'manifest', attrs: { package: pkg, versionCode: String(versionCode), versionName } }, { name: 'uses-sdk', attrs: { minSdkVersion: '24', targetSdkVersion: '36' } }]) }, { name: 'base/dex/classes.dex', data: Buffer.alloc(512, 1) }, ]); diff --git a/tests/build-sign.test.ts b/tests/build-sign.test.ts index 6d186f1..3364713 100644 --- a/tests/build-sign.test.ts +++ b/tests/build-sign.test.ts @@ -88,7 +88,7 @@ describe('zip + IPA + AAB', () => { }); test('aabInfo reads the proto manifest', () => { - expect(aabInfo(makeAab('com.example.game', 1234, '2.0.1'))).toEqual({ packageName: 'com.example.game', versionCode: 1234, versionName: '2.0.1', minSdk: 24, targetSdk: 35 }); + expect(aabInfo(makeAab('com.example.game', 1234, '2.0.1'))).toEqual({ packageName: 'com.example.game', versionCode: 1234, versionName: '2.0.1', minSdk: 24, targetSdk: 36 }); expect(() => aabInfo(makeZip([{ name: 'x', data: 'y' }]))).toThrow('not an Android App Bundle'); }); }); From ef3c66e8f005b026081e2a40672455dfc5611a11 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 03:14:53 +0700 Subject: [PATCH 051/344] release: the Linux / Windows updater signatures are made on the VDS (desktop-release add-remote, vds-key; tools/vds-sign.ts); the Mac no longer downloads those installers, verifies each returned .sig over its BLAKE2b-512 digest before publishing; release.ts --sign-local keeps the old path --- CHANGELOG.md | 6 ++ docs/desktop-release.md | 39 ++++++-- tests/vds-sign.test.ts | 85 ++++++++++++++++ tools/desktop-release.ts | 203 +++++++++++++++++++++++++++++++-------- tools/release.ts | 39 +++++++- tools/vds-sign.ts | 123 ++++++++++++++++++++++++ 6 files changed, 444 insertions(+), 51 deletions(-) create mode 100644 tests/vds-sign.test.ts create mode 100644 tools/vds-sign.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 951d487..afdd5eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- **Tooling: the desktop updater signatures of the Linux and Windows installers are made on the VDS.** The release + no longer downloads them to the Mac: the VDS fetches them from the Forgejo release, checks their SHA-256 against the + candidate, signs them with its copy of the updater key and sends back only the .sig texts, which the Mac verifies + against the app's public key before publishing. `desktop-release.ts vds-key` installs or rotates that key; + `release.ts --sign-local` keeps the old path. + ## 0.8.19 · 2026-10-20 - **`shots capture` / `render` find Playwright's chromium in a project's CommonJS playwright** whether it comes on the diff --git a/docs/desktop-release.md b/docs/desktop-release.md index 05a2222..0e99d13 100644 --- a/docs/desktop-release.md +++ b/docs/desktop-release.md @@ -95,10 +95,10 @@ Run it by hand from Actions > release with a `tag` (dry by default: only the pla 3. **Fast gate, commit, push:** `bun run ci:quick`, the commit as CRT, push to main, push the tag. 4. **In parallel:** `desktop-release.ts mac` (universal build, sign; Tauri notarizes the app while the boot check runs; the DMG is notarized while the app and the updater bundle are checked, scanned and signed), Forgejo's ci run of the - bump commit (installers only) and release.yml's promotion. Meanwhile the candidate's Linux / Windows installers - and acceptance runs are downloaded. -5. **add, matrix, verify:** updater signatures of the Linux / Windows files, the 9-run acceptance matrix (strict) to - the release, `verify`. + bump commit (installers only) and release.yml's promotion. The Linux / Windows installers are not downloaded to + the Mac (only with `--sign-local`). +5. **add-remote, verify:** the VDS signs the Linux / Windows files (see "Updater signatures on the VDS" below); the + acceptance matrix only when the release's `TESTS` is on; `verify`. 6. **publish** with `--forgejo-tag`: the VDS fetches the Linux / Windows files from the Forgejo release over its own network, rsync sends only the Mac's DMG and updater bundle, the VDS attaches those to the Forgejo release from its copy, then the publish script swaps latest.json. The owner's uplink (about 0.5 to 1 MB/s) carries each Mac file @@ -129,8 +129,10 @@ the local folders, and prints the times. - `bun tools/desktop-version.ts --set 0.8.5` and the CHANGELOG section, `bun run ci:quick`, commit, push, tag, push the tag (release.yml promotes the candidate). - `bun tools/desktop-release.ts mac --out ~/.storebound-releases/desktop/0.8.5`. -- `bun tools/release-candidate.ts fetch --sha --dir `, then `bun tools/desktop-release.ts add --out ... - --commit --run `. +- `bun tools/desktop-release.ts add-remote --out ... --host root@ --assets --commit --run ` + (the json: `[{name, url, sha256, size}]` of the release's installers, the SHA-256 from the candidate's + green.json). Fallback: `bun tools/release-candidate.ts fetch --sha --dir `, then + `bun tools/desktop-release.ts add --out ... --commit --run `. - `bun tools/desktop-release.ts publish --out ... --forgejo-tag v0.8.5 --yes` (or `upload-forgejo`, then `publish`). - `npm publish` of the same version: the owner's step (CONTRIBUTING.md). @@ -155,7 +157,30 @@ a new one under CRT's Settings > Applications with that scope, put it into the s **Back up `updater.key`** (password manager or an offline copy). If it is lost, installed apps can never update again: they only accept bundles signed with this key, so everyone would have to reinstall by hand. Never commit -it, never copy it to a runner. The Forgejo workflow builds unsigned installers, and the Mac signs them. +it, never copy it to a runner. The Forgejo workflow builds unsigned installers; the VDS signs the Linux / Windows +ones and the Mac its own. + +### Updater signatures on the VDS (since 21 Oct 2026) + +The Mac's line is too slow to download the ~120 MB AppImage, the deb and the exe just to sign them, so the +updater key has a second home on the VDS: `/root/.storebound-keys/updater.key` (dir 0700, file 0600, root; an +optional `updater.key.password` next to it, 0600, when the key has a password; today it has none). + +- **Install or rotate:** `bun tools/desktop-release.ts vds-key` (host from `~/.storebound-keys/publish-host`, one ssh + connection). It sends the Mac's `updater.key` (and `updater.key.password`, if present) over ssh stdin, never + printed or on a command line, sets the modes, signs a test string on the VDS with the tauri signer and verifies it + here against tauri.conf.json's public key. Rotation: make the new key on the Mac (as in the table), update the + public key in tauri.conf.json and cli/lib/desktop-dist.ts, run `vds-key`. +- **In a release** (`tools/release.ts` step 5, `desktop-release.ts add-remote`, code in `tools/vds-sign.ts`): one ssh + script fetches the promoted release's installers into `/var/lib/storebound-desktop/incoming//`, checks + each SHA-256 against the candidate's green.json, signs with `bunx @tauri-apps/cli@ signer sign` (bun is on + the VDS; no minisign needed) and prints only `SIG <.sig>` lines. The Mac verifies every + signature over that digest with the public key (and that its trusted comment names the file) before it writes + anything, then writes the .sig files, latest.json, SHA256SUMS and `.remote.json` (the files that live only on the + VDS). `verify` and `publish` use `.remote.json`; publish re-checks those files' SHA-256 on the VDS and never + rsyncs them. The installers' privacy scan is the one of their build jobs. +- **Fallback:** `bun tools/release.ts --resume --sign-local --yes` (or without `--resume`): the old path, + the installers downloaded to the Mac and signed there with `~/.storebound-keys/updater.key`. ## Privacy gate diff --git a/tests/vds-sign.test.ts b/tests/vds-sign.test.ts new file mode 100644 index 0000000..10b0218 --- /dev/null +++ b/tests/vds-sign.test.ts @@ -0,0 +1,85 @@ +// tools/vds-sign.ts and the VDS-signing parts of tools/release.ts: building the remote command, parsing the returned +// signatures, verifying them over the digest and refusing the ones that do not verify. No ssh here. +import { describe, expect, test } from 'bun:test'; +import { createHash, generateKeyPairSync, sign } from 'node:crypto'; +import { vdsSignAssets } from '../tools/release'; +import { parseSigLines, remoteSigProblems, remoteSignScript, signCommand, TAURI_CLI, verifyDigest } from '../tools/vds-sign'; + +/** A throwaway minisign key pair and tauri-style (base64-wrapped) "ED" signatures. */ +function keys() { + const { publicKey, privateKey } = generateKeyPairSync('ed25519'); + const raw = Buffer.from(publicKey.export({ format: 'jwk' }).x!, 'base64url'); + const id = Buffer.from('0102030405060708', 'hex'); + const pub = Buffer.from(`untrusted comment: test key\n${Buffer.concat([Buffer.from('Ed'), id, raw]).toString('base64')}\n`).toString('base64'); + const sigOf = (data: string | Buffer, file: string, comment = `timestamp:1\tfile:${file}`) => { + const digest = createHash('blake2b512').update(data).digest(); + const s = sign(null, digest, privateKey); + const g = sign(null, Buffer.concat([s, Buffer.from(comment)]), privateKey); + return Buffer.from(`untrusted comment: sig\n${Buffer.concat([Buffer.from('ED'), id, s]).toString('base64')}\ntrusted comment: ${comment}\n${g.toString('base64')}\n`).toString('base64'); + }; + return { pub, sigOf }; +} +const b2 = (d: string) => createHash('blake2b512').update(d).digest('hex'); +const SHA = 'a'.repeat(64); + +describe('VDS signing', () => { + test('the remote script fetches, checks the SHA-256, signs with the VDS key and prints SIG lines', () => { + const s = remoteSignScript('/var/lib/storebound-desktop/incoming/1.2.3', [ + { file: 'storebound_1.2.3_amd64.AppImage', url: 'https://git.example.com/o/r/releases/download/v1.2.3/storebound_1.2.3_amd64.AppImage', sha256: SHA }, + ]); + expect(s).toContain('set -euo pipefail'); + expect(s).toContain(`echo '${SHA} /var/lib/storebound-desktop/incoming/1.2.3/storebound_1.2.3_amd64.AppImage' | sha256sum -c --quiet`); + expect(s).toContain('--max-time 900'); + expect(s).toContain(`bunx ${TAURI_CLI} signer sign -f /root/.storebound-keys/updater.key`); + expect(s).toContain("printf 'SIG %s"); + expect(s).toContain('b2sum -l 512'); + expect(signCommand('/x/y')).toContain(' { + expect(() => remoteSignScript('/d', [{ file: "a'; rm -rf /", url: 'https://x/a', sha256: SHA }])).toThrow(/unsafe/); + expect(() => remoteSignScript('/d', [{ file: 'a', url: 'http://x/a', sha256: SHA }])).toThrow(/url/); + expect(() => remoteSignScript('/d', [{ file: 'a', url: 'https://x/a', sha256: 'abc' }])).toThrow(/SHA-256/); + expect(() => remoteSignScript('/d', [])).toThrow(); + }); + test('SIG lines are parsed; progress lines are not', () => { + const { sigOf } = keys(); + const sig = sigOf('hello', 'f.deb'); + const got = parseSigLines(`fetched f.deb\nsigning f.deb\nSIG f.deb ${b2('hello')} 5 ${sig}\nnoise\n`); + expect(got).toEqual([{ file: 'f.deb', blake2b: b2('hello'), size: 5, signature: sig }]); + expect(parseSigLines('SIG f.deb short 5 abc')).toEqual([]); + }); + test('a returned signature verifies over the digest against the public key', () => { + const { pub, sigOf } = keys(); + expect(verifyDigest(b2('hello'), sigOf('hello', 'f.deb'), pub, 'f.deb').ok).toBe(true); + }); + test('a signature that does not verify is refused', () => { + const { pub, sigOf } = keys(); + const other = keys(); + const r = (x: ReturnType) => (x.ok ? 'ok' : x.reason); + expect(r(verifyDigest(b2('other bytes'), sigOf('hello', 'f.deb'), pub, 'f.deb'))).toMatch(/does not match/); + expect(r(verifyDigest(b2('hello'), other.sigOf('hello', 'f.deb'), pub, 'f.deb'))).toMatch(/does not match/); + expect(r(verifyDigest(b2('hello'), sigOf('hello', 'g.deb'), pub, 'f.deb'))).toMatch(/does not name f\.deb/); + expect(r(verifyDigest(b2('hello'), 'garbage', pub))).not.toBe('ok'); + }); + test('every expected file must come back once, verified; extras are refused', () => { + const { pub, sigOf } = keys(); + const ok = { file: 'a.deb', blake2b: b2('a'), size: 1, signature: sigOf('a', 'a.deb') }; + expect(remoteSigProblems(['a.deb'], [ok], pub)).toEqual([]); + expect(remoteSigProblems(['a.deb', 'b.exe'], [ok], pub)).toEqual(['b.exe: no signature came back']); + expect(remoteSigProblems(['a.deb'], [ok, ok], pub)[0]).toMatch(/more than one/); + expect(remoteSigProblems(['a.deb'], [{ ...ok, blake2b: b2('b') }], pub)[0]).toMatch(/does not match/); + expect(remoteSigProblems(['a.deb'], [ok, { ...ok, file: 'x' }], pub)).toEqual(['x: not asked for']); + }); + test('the release signs only installers with a recorded SHA-256', () => { + const assets = [ + { name: 'storebound_1.2.3_x64-setup.exe', size: 9, browser_download_url: 'https://g/x.exe' }, + { name: 'SHA256SUMS', size: 1, browser_download_url: 'https://g/s' }, + { name: 'storebound_1.2.3_amd64.deb', size: 8, browser_download_url: 'https://g/x.deb' }, + ]; + const rec = { 'storebound_1.2.3_x64-setup.exe': SHA, 'storebound_1.2.3_amd64.deb': SHA }; + expect(vdsSignAssets(assets, rec).map(a => a.name)).toEqual(['storebound_1.2.3_amd64.deb', 'storebound_1.2.3_x64-setup.exe']); + expect(() => vdsSignAssets(assets, { 'storebound_1.2.3_amd64.deb': SHA })).toThrow(/no SHA-256/); + expect(() => vdsSignAssets([assets[1]!], rec)).toThrow(/no Linux/); + }); +}); diff --git a/tools/desktop-release.ts b/tools/desktop-release.ts index e7cc300..21de8e1 100644 --- a/tools/desktop-release.ts +++ b/tools/desktop-release.ts @@ -16,6 +16,12 @@ // folder: privacy scan, minisign signature here (the key never goes to a runner), latest.json, SHA256SUMS and // evidence--.json (the run and commit they came from; a commit other than the one of the // folder's other evidence is refused: every artifact of a version comes from one commit). +// bun tools/desktop-release.ts add-remote --out --host --assets [--commit ] [--run ] [--code-signed] +// The default since 21 Oct 2026: the VDS fetches the Linux / Windows files of the Forgejo release into its incoming +// folder, checks their SHA-256, signs them with its copy of the updater key (tools/vds-sign.ts); only the .sig +// texts come back and are verified here. The files stay on the VDS (.remote.json); publish checks them there. +// bun tools/desktop-release.ts vds-key [--host root@] +// Installs or rotates the updater key in /root/.storebound-keys on the VDS and verifies a test signature here. // bun tools/desktop-release.ts publish --out --host [--channel stable|beta|rehearsal] // [--forgejo-tag v] [--yes] // Checks the folder again, uploads it to the server's incoming folder (rsync) and runs the root-owned publish @@ -45,6 +51,7 @@ import { buildOne, OUT_DIR as SIDECAR_DIR } from './build-sidecars'; import { versions } from './desktop-version'; import { listReleases, upsert as forgejoUpsert } from './forgejo-release'; import { isMacArtifact, scanSignedMac } from './mac-signature-scan'; +import { parseSigLines, REMOTE_KEY, REMOTE_KEY_PASSWORD, REMOTE_KEYS, type RemoteItem, remoteSigProblems, remoteSignScript, signCommand, sshScript, verifyDigest } from './vds-sign'; import { allTerms, DEFAULT_TERMS, type Report, scan, TERMS_ENV } from './privacy-scan'; export const ROOT = resolve(import.meta.dir, '..'); @@ -248,6 +255,15 @@ function privacyGate(paths: string[]): { files: number; bytes: number; hits: num return { files: r.files, bytes: r.bytes, hits: 0 }; } +/** Files of the version folder that live only on the VDS (signed there, tools/vds-sign.ts): `.remote.json`, never + * uploaded. Their SHA-256 was checked on the VDS against the candidate's record; BLAKE2b-512 is what was signed. */ +export interface RemoteFile { file: string; sha256: string; size: number; blake2b: string } +const REMOTE_JSON = '.remote.json'; +function readRemote(out: string): RemoteFile[] { + const p = join(out, REMOTE_JSON); + return existsSync(p) ? JSON.parse(readFileSync(p, 'utf8')) as RemoteFile[] : []; +} + function readManifest(out: string): Manifest | null { const p = join(out, 'latest.json'); return existsSync(p) ? JSON.parse(readFileSync(p, 'utf8')) as Manifest : null; @@ -258,8 +274,9 @@ function writeVersionFiles(out: string, manifest: Manifest): void { if (problems.length) fail(`latest.json: ${problems.join('; ')}`); writeFileSync(join(out, 'latest.json.part'), `${JSON.stringify(manifest, null, 2)}\n`); renameSync(join(out, 'latest.json.part'), join(out, 'latest.json')); - const files = readdirSync(out).filter(n => uploadable(n) && n !== 'SHA256SUMS'); - writeFileSync(join(out, 'SHA256SUMS'), sumsText(files.map(file => ({ file, sha256: sha256(join(out, file)) })))); + const remote = readRemote(out); + const files = readdirSync(out).filter(n => uploadable(n) && n !== 'SHA256SUMS' && !remote.some(r => r.file === n)); + writeFileSync(join(out, 'SHA256SUMS'), sumsText([...files.map(file => ({ file, sha256: sha256(join(out, file)) })), ...remote.map(r => ({ file: r.file, sha256: r.sha256 }))])); } function gitState(): { commit: string; dirty: boolean } { @@ -643,90 +660,187 @@ export function commitProblems(commit: string | undefined, evidence: Record c && c !== commit).map(([f, c]) => `${f} says commit ${c!.slice(0, 10)}, these files are from ${commit.slice(0, 10)}`); } -function add(argv: string[]): void { +/** The Linux / Windows artifact name of a workflow file (`__` in it, kind from the extension). */ +function addedName(n: string, version: string, codeSigned: boolean): string { + if (!n.includes(`_${version}_`)) fail(`${n} is not version ${version}`); + const kind = /-setup\.exe$/i.test(n) ? 'nsis' : /\.AppImage$/.test(n) ? 'appimage' : /\.deb$/.test(n) ? 'deb' : null; + if (!kind) fail(`${n}: expected an NSIS setup .exe, an .AppImage or a .deb`); + return artifactName(version, kind, kind === 'nsis' ? codeSigned : true); +} + +function addPrelude(argv: string[]) { const a = args(argv); const { version, drift } = versions(); if (!version || drift.length) fail('desktop version drift (bun tools/desktop-version.ts)'); const out = resolve(a.get('out') ?? join(homedir(), '.storebound-releases', 'desktop', version)); - const files = a.rest.slice(1); - if (!files.length) fail('usage: add --out '); mkdirSync(out, { recursive: true }); const commit = a.get('commit'); const otherEvidence = Object.fromEntries(readdirSync(out).filter(n => /^evidence-.*\.json$/.test(n)) .map(n => [n, (JSON.parse(readFileSync(join(out, n), 'utf8')) as { commit?: string }).commit])); const commitBad = commitProblems(commit, otherEvidence); if (commitBad.length) fail(`not one commit: ${commitBad.join('; ')}`); - const codeSigned = a.has('code-signed'); + return { a, version, out, commit, codeSigned: a.has('code-signed') }; +} + +interface Added { name: string; from: string; sha256: string; size: number; sig: string } + +/** latest.json, SHA256SUMS and evidence--.json for added Linux / Windows files. */ +function recordAdded(p: ReturnType, added: Added[], checks: Record): void { + const { a, version, out, commit, codeSigned } = p; const platforms: Manifest['platforms'] = {}; const downloads: Partial> = {}; - const added: string[] = []; - const sources: Record = {}; - for (const f of files.map(x => resolve(x))) { - const n = basename(f); - if (!n.includes(`_${version}_`)) fail(`${n} is not version ${version}`); - const kind = /-setup\.exe$/i.test(n) ? 'nsis' : /\.AppImage$/.test(n) ? 'appimage' : /\.deb$/.test(n) ? 'deb' : null; - if (!kind) fail(`${n}: expected an NSIS setup .exe, an .AppImage or a .deb`); - const name = artifactName(version, kind, kind === 'nsis' ? codeSigned : true); - const dest = join(out, name); - copyFileSync(f, dest); - added.push(dest); - sources[name] = n; - } - const privacy = privacyGate(added); - for (const dest of added) { - const name = basename(dest); - const sig = signFile(dest); - const d: Download = { file: name, url: releaseUrl(version, name), sha256: sha256(dest), size: statSync(dest).size, signature: sig, codeSigned: name.endsWith('.exe') ? codeSigned : false }; - if (name.endsWith('.exe')) { downloads['windows-x86_64-nsis'] = d; platforms['windows-x86_64'] = { signature: sig, url: d.url }; } - else if (name.endsWith('.AppImage')) { downloads['linux-x86_64-appimage'] = d; platforms['linux-x86_64'] = { signature: sig, url: d.url }; } + for (const x of added) { + const d: Download = { file: x.name, url: releaseUrl(version, x.name), sha256: x.sha256, size: x.size, signature: x.sig, codeSigned: x.name.endsWith('.exe') ? codeSigned : false }; + if (x.name.endsWith('.exe')) { downloads['windows-x86_64-nsis'] = d; platforms['windows-x86_64'] = { signature: x.sig, url: d.url }; } + else if (x.name.endsWith('.AppImage')) { downloads['linux-x86_64-appimage'] = d; platforms['linux-x86_64'] = { signature: x.sig, url: d.url }; } else downloads['linux-x86_64-deb'] = d; - say(`added ${name} (${mb(d.size)})`); + say(`added ${x.name} (${mb(x.size)})`); } const existing = readManifest(out); const now = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'); writeVersionFiles(out, mergeManifest(existing, version, a.get('notes') ?? existing?.notes ?? `storebound desktop ${version}`, now, { platforms, downloads })); // evidence per platform (stays local, like the macOS one): where the files came from and what was checked here for (const platform of ['linux', 'windows'] as const) { - const mine = added.filter(d => (platform === 'windows') === d.endsWith('.exe')); + const mine = added.filter(d => (platform === 'windows') === d.name.endsWith('.exe')); if (!mine.length) continue; const evidence = { product: 'storebound desktop', version, platform: `${platform}-x86_64`, addedAt: now, commit: commit ?? null, run: a.get('run') ?? null, - checks: { privacy, updaterSignature: 'minisign, verified against tauri.conf.json', codeSigned: platform === 'windows' ? codeSigned : false }, - artifacts: mine.map(d => ({ file: basename(d), from: sources[basename(d)], size: statSync(d).size, sha256: sha256(d) })), + checks: { ...checks, codeSigned: platform === 'windows' ? codeSigned : false }, + artifacts: mine.map(d => ({ file: d.name, from: d.from, size: d.size, sha256: d.sha256 })), }; writeFileSync(join(out, `evidence-${platform}-${version}.json`), `${JSON.stringify(evidence, null, 2)}\n`); } say(`latest.json now has ${Object.keys(readManifest(out)!.platforms).join(', ')}${commit ? `; evidence: commit ${commit.slice(0, 10)}` : ''}`); } +/** The fallback (--sign-local in tools/release.ts): the files are on this Mac and signed with ~/.storebound-keys. */ +function add(argv: string[]): void { + const p = addPrelude(argv); + const files = p.a.rest.slice(1); + if (!files.length) fail('usage: add --out '); + const copied: { dest: string; from: string }[] = []; + for (const f of files.map(x => resolve(x))) { + const dest = join(p.out, addedName(basename(f), p.version, p.codeSigned)); + copyFileSync(f, dest); + copied.push({ dest, from: basename(f) }); + } + const privacy = privacyGate(copied.map(c => c.dest)); + const added = copied.map(c => ({ name: basename(c.dest), from: c.from, sha256: sha256(c.dest), size: statSync(c.dest).size, sig: signFile(c.dest) })); + recordAdded(p, added, { privacy, updaterSignature: 'minisign on the Mac, verified against tauri.conf.json' }); +} + +/** The VDS signs (owner's decision 21 Oct 2026): `add-remote --out --host --assets ` with + * [{name, url, sha256, size}] of the Forgejo release. The VDS fetches each file into its incoming folder, checks + * the SHA-256 and signs it; only the .sig texts come back, each verified here before anything is written. */ +async function addRemote(argv: string[]): Promise { + const p = addPrelude(argv); + const host = p.a.get('host') ?? fail('--host is required'); + if (!/^[A-Za-z0-9._-]+@[A-Za-z0-9.-]+$/.test(host)) fail(`--host: user@host, got ${host}`); + const assets = JSON.parse(readFileSync(p.a.get('assets') ?? fail('--assets is required'), 'utf8')) as { name: string; url: string; sha256: string; size: number }[]; + if (!assets.length) fail('--assets: no files'); + const items: (RemoteItem & { from: string; size: number })[] = assets.map(x => ({ file: addedName(x.name, p.version, p.codeSigned), url: x.url, sha256: x.sha256, from: x.name, size: x.size })); + const dir = `${REMOTE_INCOMING}/${p.version}`; + say(`VDS ${host.split('@')[1]}: fetch ${items.length} files from Forgejo into ${dir}, check SHA-256, sign with ${REMOTE_KEY}`); + const outText = await sshScript(host, remoteSignScript(dir, items), { timeoutMs: 30 * 60_000, what: 'VDS fetch + sign', log: say }).catch((e: Error) => fail(e.message)); + const got = parseSigLines(outText); + const problems = remoteSigProblems(items.map(i => i.file), got, confPubkey()); + if (problems.length) fail(`signatures from the VDS refused, nothing written: ${problems.join('; ')}`); + const remote: RemoteFile[] = []; + const added: Added[] = items.map(i => { + const g = got.find(x => x.file === i.file)!; + if (i.size && g.size !== i.size) fail(`${i.file}: ${g.size} bytes on the VDS, the release says ${i.size}`); + remote.push({ file: i.file, sha256: i.sha256, size: g.size, blake2b: g.blake2b }); + writeFileSync(join(p.out, `${i.file}.sig`), g.signature); + rmSync(join(p.out, i.file), { force: true }); // a stale local copy from a --sign-local run never wins + return { name: i.file, from: i.from, sha256: i.sha256, size: g.size, sig: g.signature }; + }); + const prev = readRemote(p.out).filter(r => !remote.some(x => x.file === r.file)); + writeFileSync(join(p.out, REMOTE_JSON), `${JSON.stringify([...prev, ...remote], null, 2)}\n`); + say(`${added.length} signatures from the VDS verified against tauri.conf.json's key`); + recordAdded(p, added, { privacy: 'scanned in the build jobs (ci.yml, private terms)', updaterSignature: 'minisign on the VDS, verified on the Mac against tauri.conf.json (BLAKE2b-512 digest)', sha256: 'checked on the VDS against the candidate record' }); +} + +/** `vds-key --host `: installs or updates the updater key (and its password file, if + * ~/.storebound-keys/updater.key.password exists) in /root/.storebound-keys on the VDS (dir 0700, files 0600, root), + * over ssh stdin (never printed, never on a command line), then signs a test string there and verifies it here. */ +async function vdsKey(argv: string[]): Promise { + const a = args(argv); + const host = a.get('host') ?? process.env.STOREBOUND_PUBLISH_HOST ?? (existsSync(join(KEYS_DIR, 'publish-host')) ? readFileSync(join(KEYS_DIR, 'publish-host'), 'utf8').trim() : ''); + if (!/^root@[A-Za-z0-9.-]+$/.test(host)) fail(`the VDS host must be root@ (--host, STOREBOUND_PUBLISH_HOST or ~/.storebound-keys/publish-host), got ${host || 'nothing'}`); + const key = updaterKey(); + const keyB64 = readFileSync(key).toString('base64'); + const pwFile = `${key}.password`; + const pwB64 = existsSync(pwFile) ? readFileSync(pwFile).toString('base64') : ''; + const test = `storebound-vds-key-check-${Date.now()}`; + const t = `/tmp/sb-key-check-${process.pid}`; + const script = [ + 'set -euo pipefail', 'umask 077', + `install -d -m 700 -o root -g root ${REMOTE_KEYS}`, + `base64 -d > ${REMOTE_KEY}.new <<'K'`, keyB64, 'K', + `chmod 600 ${REMOTE_KEY}.new && chown root:root ${REMOTE_KEY}.new && mv -f ${REMOTE_KEY}.new ${REMOTE_KEY}`, + pwB64 ? `base64 -d > ${REMOTE_KEY_PASSWORD}.new <<'K' +${pwB64} +K +chmod 600 ${REMOTE_KEY_PASSWORD}.new && mv -f ${REMOTE_KEY_PASSWORD}.new ${REMOTE_KEY_PASSWORD}` : `rm -f ${REMOTE_KEY_PASSWORD}`, + `chmod 700 ${REMOTE_KEYS}`, + `mkdir -p ${t} && printf '%s' '${test}' > ${t}/check.txt`, + 'echo "signing a test string (the first run downloads the tauri CLI)"', + `${signCommand(`${t}/check.txt`)}`, + `printf 'SIG %s %s %s %s\n' check.txt "$(b2sum -l 512 ${t}/check.txt | cut -d' ' -f1)" "$(stat -c %s ${t}/check.txt)" "$(tr -d '\n' < ${t}/check.txt.sig)"`, + `rm -rf ${t}`, + `stat -c 'MODE %a %U %n' ${REMOTE_KEYS} ${REMOTE_KEYS}/*`, + ].join('\n'); + say(`installing the updater key on ${host.split('@')[1]}:${REMOTE_KEYS} (one ssh connection)`); + const out = await sshScript(host, `${script}\n`, { timeoutMs: 10 * 60_000, what: 'vds-key', log: say }).catch((e: Error) => fail(e.message)); + const modes = out.split('\n').filter(l => l.startsWith('MODE ')); + const bad = modes.filter(l => !/^MODE (700|600) root /.test(l)); + if (!modes.length || bad.length) fail(`unexpected modes on the VDS: ${bad.join('; ') || 'none read'}`); + const [sig] = parseSigLines(out); + const blake = createHash('blake2b512').update(test).digest('hex'); + if (!sig || sig.blake2b !== blake) fail('the VDS did not sign the test string'); + const v = verifyDigest(blake, sig.signature, confPubkey(), 'check.txt'); + if (!v.ok) fail(`the VDS's test signature does not verify against tauri.conf.json: ${v.reason}`); + say(`ok: ${modes.length} paths 0700/0600 root; the VDS signs with the key of tauri.conf.json (test string verified here)`); +} + // --------------------------------------------------------------------------------------------------------------------- // verify / publish -function verifyFolder(out: string): { manifest: Manifest; files: string[] } { +function verifyFolder(out: string): { manifest: Manifest; files: string[]; remote: RemoteFile[] } { if (!existsSync(join(out, 'latest.json')) || !existsSync(join(out, 'SHA256SUMS'))) fail(`${out}: no latest.json / SHA256SUMS`); const manifest = readManifest(out)!; const problems = manifestProblems(manifest); if (problems.length) fail(`latest.json: ${problems.join('; ')}`); const sums = readFileSync(join(out, 'SHA256SUMS'), 'utf8').trim().split('\n').map(l => { const [h, f] = l.split(/\s+/); return { h: h!, f: f! }; }); - for (const { h, f } of sums) if (!existsSync(join(out, f)) || sha256(join(out, f)) !== h) fail(`SHA256SUMS: ${f} does not match`); - const files = readdirSync(out).filter(uploadable); + const remote = readRemote(out); + const remoteOf = (f: string) => remote.find(r => r.file === f); + for (const { h, f } of sums) { + const r = remoteOf(f); + if (r ? r.sha256 !== h : (!existsSync(join(out, f)) || sha256(join(out, f)) !== h)) fail(`SHA256SUMS: ${f} does not match`); + } + const files = [...new Set([...readdirSync(out).filter(uploadable), ...remote.map(r => r.file)])].sort(); for (const f of files) if (f !== 'SHA256SUMS' && !sums.some(s => s.f === f)) fail(`${f} is not in SHA256SUMS`); const pub = confPubkey(); const check = (url: string, signature: string, what: string) => { const file = url.split('/').pop()!; if (!url.startsWith(releaseUrl(manifest.version, ''))) fail(`${what}: ${url} is not in /desktop/dl/${manifest.version}/`); if (!files.includes(file)) fail(`${what}: ${file} is not in the folder`); - const v = verifySig(readFileSync(join(out, file)), signature, pub); + const r = remoteOf(file); + const v = r ? verifyDigest(r.blake2b, signature, pub, file) : verifySig(readFileSync(join(out, file)), signature, pub); if (!v.ok) fail(`${what}: ${file}: ${v.reason}`); }; for (const [k, p] of Object.entries(manifest.platforms)) check(p.url, p.signature, `platforms.${k}`); for (const [k, d] of Object.entries(manifest.downloads ?? {})) { check(d!.url, d!.signature, `downloads.${k}`); - if (sha256(join(out, d!.file)) !== d!.sha256 || statSync(join(out, d!.file)).size !== d!.size) fail(`downloads.${k}: size or SHA-256 differ from the file`); + const r = remoteOf(d!.file); + const [h, size] = r ? [r.sha256, r.size] : [sha256(join(out, d!.file)), statSync(join(out, d!.file)).size]; + if (h !== d!.sha256 || size !== d!.size) fail(`downloads.${k}: size or SHA-256 differ from the file`); } - privacyGate(files.filter(f => !/\.(sig|json)$|^SHA256SUMS$/.test(f)).map(f => join(out, f))); + // the VDS-signed files were scanned in their build jobs (ci.yml, private terms) and are not on this Mac + privacyGate(files.filter(f => !remoteOf(f) && !/\.(sig|json)$|^SHA256SUMS$/.test(f)).map(f => join(out, f))); + if (remote.length) say(`on the VDS only (signed there, SHA-256 checked there against the candidate): ${remote.map(r => r.file).join(', ')}`); say(`verified ${manifest.version}: ${files.length} files, platforms ${Object.keys(manifest.platforms).join(', ')}, downloads ${Object.keys(manifest.downloads ?? {}).join(', ')}`); - return { manifest, files }; + return { manifest, files, remote }; } /** The npm CLI and the desktop app are one release: the folder must be the version of this checkout's package.json @@ -781,7 +895,9 @@ async function publish(argv: string[]): Promise { if (!/^[A-Za-z0-9._-]+@[A-Za-z0-9.-]+$/.test(host)) fail(`--host: user@host, got ${host}`); const channel = a.get('channel') ?? 'stable'; if (!(CHANNELS as readonly string[]).includes(channel)) fail(`--channel ${CHANNELS.join(', ')}`); - const { manifest, files } = verifyFolder(out); + const { manifest, files: all, remote } = verifyFolder(out); + // files signed on the VDS are already in its incoming folder: never rsynced or seeded, only checked there + const files = all.filter(f => !remote.some(r => r.file === f)); const v = manifest.version; const together = releaseTogetherProblems(v, versions().version); if (together.length) fail(together.join('; ')); @@ -803,6 +919,7 @@ async function publish(argv: string[]): Promise { if (unsigned.length) console.log(` note: unsigned preview builds (${unsigned.join(', ')}); the downloads page says so.`); console.log('\nsteps:'); for (const s of steps) console.log(` ${s[0]} ${s.slice(1).map(x => (x.includes(' ') ? `"${x}"` : x.replace(out, ''))).join(' ')}`); + if (remote.length) console.log(` already on the server (signed there), SHA-256 checked again: ${remote.map(r => r.file).join(', ')}`); if (seed.length) console.log(` the server fetches from Forgejo ${forgejoTag}: ${seed.map(x => x.file).join(', ')}`); if (macFiles.length) console.log(` then attaches to Forgejo ${forgejoTag} from its copy: ${macFiles.join(', ')}`); if (!a.has('yes')) { console.log('\ndry run: nothing uploaded. Every installed app on this channel offers the update once latest.json is live; run again with --yes to publish.'); return; } @@ -816,6 +933,12 @@ async function publish(argv: string[]): Promise { // the script goes to bash on stdin: the server's login shell may be zsh, which does not split "$pids" run(['ssh', host, 'bash', '-s'], { input: `pids=''\n${lines.map(l => `(${l}) & pids="$pids $!"`).join('\n')}\nfor p in $pids; do wait $p || exit 1; done\n`, stdio: ['pipe', 'inherit', 'inherit'] }); } + if (remote.length) { + const dir = `${REMOTE_INCOMING}/${v}`; + say(`server: SHA-256 of the ${remote.length} files signed there`); + await sshScript(host, `set -euo pipefail\n${remote.map(r => `echo '${r.sha256} ${dir}/${r.file}' | sha256sum -c --quiet || { echo "${r.file} on the server is not the signed file"; exit 1; }`).join('\n')}\n`, { timeoutMs: 5 * 60_000, what: 'remote SHA-256 check', log: say }) + .catch((e: Error) => fail(e.message)); + } say(`rsync (only what the server does not have yet) ...`); run(rsync, { stdio: ['ignore', 'inherit', 'inherit'] }); if (macFiles.length) { @@ -860,6 +983,8 @@ if (import.meta.main) { const cmd = argv[0]; if (cmd === 'mac') await mac(argv.slice(1)); else if (cmd === 'add') add(argv); + else if (cmd === 'add-remote') await addRemote(argv); + else if (cmd === 'vds-key') await vdsKey(argv); else if (cmd === 'verify') verifyFolder(resolve(args(argv).get('out') ?? fail('--out '))); else if (cmd === 'publish') await publish(argv.slice(1)); else if (cmd === 'upload-forgejo') await uploadForgejo(argv.slice(1)); @@ -870,6 +995,6 @@ if (import.meta.main) { const r = spawnSync(cmdline[0]!, cmdline.slice(1), { stdio: 'inherit', env: { ...process.env, ...pathFreeEnv(ROOT, process.env) }, shell: process.platform === 'win32' }); process.exit(r.status ?? 1); } - else { console.log(readFileSync(import.meta.path, 'utf8').split('\n').filter(l => l.startsWith('//')).slice(0, 30).map(l => l.slice(3)).join('\n')); process.exit(cmd ? 2 : 0); } + else { console.log(readFileSync(import.meta.path, 'utf8').split('\n').filter(l => l.startsWith('//')).slice(0, 40).map(l => l.slice(3)).join('\n')); process.exit(cmd ? 2 : 0); } } diff --git a/tools/release.ts b/tools/release.ts index 8a3d884..9d1a6d1 100644 --- a/tools/release.ts +++ b/tools/release.ts @@ -7,6 +7,7 @@ // rehearsal/: a prerelease on git.crt.fyi and the rehearsal // channel of storebound.dev (no app reads it), never npm and never // /Applications; everything it made is deleted at the end +// bun tools/release.ts [--sign-local] fallback: download the Linux / Windows installers and sign here // bun tools/release.ts --resume --yes after a stop past the push: HEAD is origin/main, tagged v, // with that version; skips the bump and continues from step 4 // bun tools/release.ts npm-token once: the npm granular token from the clipboard to ~/.storebound-keys @@ -22,8 +23,10 @@ // 4. at once, in parallel: the Mac build (tools/desktop-release.ts mac: universal app, sign, notarize app and DMG, // every check), Forgejo's ci run of the bump commit (version-only: the installers only, the parent's CI and // matrix count) and the promotion of the tag (release.yml); this waits for the candidate (heartbeat, timeout) -// and downloads its Linux / Windows installers while the Mac builds; -// 5. add (updater signatures of the Linux / Windows files), the full acceptance matrix (9 runs), verify; +// (with --sign-local also downloads its Linux / Windows installers while the Mac builds); +// 5. add-remote: the VDS fetches the Linux / Windows files of the release, checks their SHA-256 and signs them with +// its copy of the updater key; only the .sig texts come back and are verified here (--sign-local: the old path, +// the files downloaded to this Mac in step 4 and signed here); the acceptance matrix (TESTS), verify; // 6. publish: the VDS fetches the Linux / Windows files from Forgejo itself, rsync sends only the Mac's files, // the VDS attaches them to the Forgejo release from its copy, then storebound.dev's latest.json; // 7. /Applications/storebound.app: the running app is quit (gracefully, then its exact PID), the new one copied @@ -55,6 +58,18 @@ const TESTS = false; // --------------------------------------------------------------------------------------------------------------------- // Pure parts (tests/release.test.ts) +/** The Linux / Windows assets of the promoted release that the VDS signs, with the SHA-256 of the candidate's record + * (green.json). An installer without a recorded hash is refused: the VDS checks every byte against it. */ +export function vdsSignAssets(assets: { name: string; size: number; browser_download_url: string }[], recorded: Record): { name: string; url: string; sha256: string; size: number }[] { + const mine = assets.filter(a => /\.(AppImage|deb|exe)$/.test(a.name)); + if (!mine.length) throw new Error('the release has no Linux / Windows installers'); + return mine.map(a => { + const sha256 = recorded[a.name]; + if (!sha256 || !/^[0-9a-f]{64}$/.test(sha256)) throw new Error(`${a.name}: no SHA-256 in the candidate's record`); + return { name: a.name, url: a.browser_download_url, sha256, size: a.size }; + }).sort((x, y) => x.name.localeCompare(y.name)); +} + /** The CHANGELOG with its Unreleased section turned into the version's section and a new empty Unreleased on top. */ export function cutChangelog(text: string, version: string, date: string): string { const lines = text.split('\n'); @@ -234,6 +249,7 @@ async function main(): Promise { if (argv[0] === 'mac-acceptance') { const key = cliKey(ROOT); console.log(await macAcceptance(key, join(RELEASES, 'logs', `acceptance-${key}`))); return; } const rehearsal = has('--rehearsal'); const resume = has('--resume'); + const signLocal = has('--sign-local'); if (resume && rehearsal) fail('--resume is for a real version'); const positional = argv.filter(a => !a.startsWith('--')); const pkgVersion = COPIES[0]!.read(readFileSync(join(ROOT, 'package.json'), 'utf8'))!; @@ -342,15 +358,28 @@ async function main(): Promise { const s = await waitGreen(sha, 45); return s; }); - const fetchP = candP.then(s => phase('download Linux / Windows installers + acceptance runs', () => fetchCandidate(s, dl))); + // the Linux / Windows installers stay off this Mac: the VDS fetches and signs them (owner, 21 Oct 2026); only + // --sign-local (the fallback) downloads them here to sign with ~/.storebound-keys + const fetchP = signLocal ? candP.then(s => phase('download Linux / Windows installers + acceptance runs', () => fetchCandidate(s, dl))) + : TESTS ? candP.then(s => phase('download acceptance runs', () => fetchCandidate(s, dl, /^acceptance-.*\.json$/))) : Promise.resolve([]); const relP = candP.then(() => phase('Forgejo: release.yml promotes the tag', () => waitRelease(tag, 15))); await Promise.all([macP, fetchP, relP, accP]); const cand = await candP; // ---------------------------------------------------------------- 5. add, acceptance matrix, verify await phase('add Linux / Windows + acceptance matrix + verify', async () => { - const files = readdirSync(dl).filter(f => /\.(AppImage|deb|exe)$/.test(f)).map(f => join(dl, f)); - sh(['bun', 'tools/desktop-release.ts', 'add', '--out', out, '--commit', sha, '--run', cand.record.run, ...files]); + if (signLocal) { + const files = readdirSync(dl).filter(f => /\.(AppImage|deb|exe)$/.test(f)).map(f => join(dl, f)); + sh(['bun', 'tools/desktop-release.ts', 'add', '--out', out, '--commit', sha, '--run', cand.record.run, ...files]); + } else { + const rel = (await listReleases()).find(r => r.tag_name === tag) ?? fail(`no Forgejo release ${tag}`); + const plan = vdsSignAssets(rel.assets, cand.record.files); + const assetsFile = join(logDir, 'vds-sign-assets.json'); + mkdirSync(logDir, { recursive: true }); + writeFileSync(assetsFile, `${JSON.stringify(plan, null, 2)}\n`); + const code = await bg('VDS sign', ['bun', 'tools/desktop-release.ts', 'add-remote', '--out', out, '--host', host, '--assets', assetsFile, '--commit', sha, '--run', cand.record.run], join(logDir, 'add-remote.log'), { timeoutMs: 35 * 60_000 }); + if (code !== 0) fail(`VDS signing failed: ${join(logDir, 'add-remote.log').replace(HOME, '~')} (fallback: --resume --sign-local)`); + } if (TESTS) { const accDir = mkdtempSync(join(tmpdir(), 'sb-acc-')); for (const f of readdirSync(dl).filter(f => /^acceptance-.*\.json$/.test(f))) writeFileSync(join(accDir, f), readFileSync(join(dl, f))); diff --git a/tools/vds-sign.ts b/tools/vds-sign.ts new file mode 100644 index 0000000..7aac4e7 --- /dev/null +++ b/tools/vds-sign.ts @@ -0,0 +1,123 @@ +// Updater signatures of the Linux / Windows installers made on the VDS (the owner's decision, 21 Oct 2026): the files +// are already there (the VDS fetches them from the Forgejo release over its own network), so the Mac never downloads +// them just to sign. Only the small .sig texts come back; each is checked here against tauri.conf.json's key over the +// BLAKE2b-512 digest the VDS reports, and the file's SHA-256 is checked on the VDS against the candidate's record. +// The key lives on the VDS in /root/.storebound-keys/ (dir 0700, files 0600): `bun tools/desktop-release.ts vds-key`. +// Pure parts are tested in tests/vds-sign.test.ts; the runner spawns ssh with a timeout and a heartbeat. +import { spawn } from 'node:child_process'; +import { createPublicKey, verify as edVerify } from 'node:crypto'; +import { parsePublicKey, parseSignature, type VerifyResult } from '../cli/lib/minisign'; + +export const REMOTE_KEYS = '/root/.storebound-keys'; +export const REMOTE_KEY = `${REMOTE_KEYS}/updater.key`; +/** Optional: the key's password (one line). Without the file the password is empty (how updater.key was made). */ +export const REMOTE_KEY_PASSWORD = `${REMOTE_KEYS}/updater.key.password`; +/** The tauri signer the VDS runs (bun is on the host): pinned to the CLI version of apps/desktop. */ +export const TAURI_CLI = '@tauri-apps/cli@2.12.1'; + +export interface RemoteItem { file: string; url: string; sha256: string } +export interface RemoteSig { file: string; blake2b: string; size: number; signature: string } + +const SAFE_FILE = /^[A-Za-z0-9._-]+$/; +const SAFE_DIR = /^\/[A-Za-z0-9._/-]+$/; +const SAFE_URL = /^https:\/\/[A-Za-z0-9./_%:-]+$/; + +/** The sign command of one file on the VDS (pure): password from the optional file, never on the command line; + * stdin from /dev/null so the signer can never wait for a prompt. */ +export function signCommand(path: string): string { + if (!SAFE_DIR.test(path)) throw new Error(`unsafe path ${path}`); + return `TAURI_SIGNING_PRIVATE_KEY_PASSWORD="$(cat ${REMOTE_KEY_PASSWORD} 2>/dev/null || true)" timeout 300 bunx ${TAURI_CLI} signer sign -f ${REMOTE_KEY} '${path}' /dev/null`; +} + +/** One SIG line per file: name, BLAKE2b-512 hex, size, the .sig text (tauri's one-line base64). */ +const sigLine = (path: string, file: string) => + `printf 'SIG %s %s %s %s\\n' '${file}' "$(b2sum -l 512 '${path}' | cut -d' ' -f1)" "$(stat -c %s '${path}')" "$(tr -d '\\n' < '${path}.sig')"`; + +/** + * The bash script for `ssh host bash -s` (pure): fetch every file into `dir` in parallel (skipped when it is already + * there with the right SHA-256), check its SHA-256, sign it with the VDS's key and print SIG lines. Any failure exits + * non-zero with a line that says which file. + */ +export function remoteSignScript(dir: string, items: RemoteItem[]): string { + if (!SAFE_DIR.test(dir)) throw new Error(`unsafe dir ${dir}`); + if (!items.length) throw new Error('nothing to sign'); + for (const x of items) { + if (!SAFE_FILE.test(x.file)) throw new Error(`unsafe file name ${x.file}`); + if (!SAFE_URL.test(x.url)) throw new Error(`unexpected url ${x.url}`); + if (!/^[0-9a-f]{64}$/.test(x.sha256)) throw new Error(`${x.file}: not a SHA-256`); + } + const lines = ['set -euo pipefail', `test -s ${REMOTE_KEY} || { echo "no updater key at ${REMOTE_KEY} (bun tools/desktop-release.ts vds-key)"; exit 3; }`, + `mkdir -p '${dir}'`, `cd '${dir}'`, "pids=''"]; + for (const x of items) { + const p = `${dir}/${x.file}`; + lines.push(`( if ! echo '${x.sha256} ${p}' | sha256sum -c --quiet 2>/dev/null; then curl -fsSL --retry 2 --connect-timeout 20 --max-time 900 -o '${p}.part' '${x.url}' && mv -f '${p}.part' '${p}'; fi; echo '${x.sha256} ${p}' | sha256sum -c --quiet || { echo "FAIL ${x.file}: SHA-256 differs from the candidate's record"; exit 1; }; echo "fetched ${x.file}" ) & pids="$pids $!"`); + } + lines.push('for p in $pids; do wait $p || { echo "FAIL a download"; exit 1; }; done'); + for (const x of items) { + const p = `${dir}/${x.file}`; + lines.push(`echo "signing ${x.file}"`, `rm -f '${p}.sig'`, `${signCommand(p)} || { echo "FAIL ${x.file}: the signer failed"; exit 1; }`, sigLine(p, x.file)); + } + return `${lines.join('\n')}\n`; +} + +/** The SIG lines of the script's output (pure). Other lines are progress. */ +export function parseSigLines(out: string): RemoteSig[] { + const res: RemoteSig[] = []; + for (const l of out.split('\n')) { + const m = /^SIG (\S+) ([0-9a-f]{128}) (\d+) ([A-Za-z0-9+/]+={0,2})$/.exec(l.trim()); + if (m) res.push({ file: m[1]!, blake2b: m[2]!, size: Number(m[3]), signature: m[4]! }); + } + return res; +} + +/** A minisign "ED" signature over a BLAKE2b-512 digest (pure): the same check as cli/lib/minisign verify, without the + * file's bytes. The trusted comment must name the file (tauri writes `file:`). */ +export function verifyDigest(blake2bHex: string, signature: string, publicKey: string, file?: string): VerifyResult { + try { + const pk = parsePublicKey(publicKey); const s = parseSignature(signature); + if (s.alg !== 'ED') return { ok: false, reason: `algorithm ${s.alg}, expected ED (prehashed)` }; + if (pk.keyId !== s.keyId) return { ok: false, reason: `signed with key ${s.keyId}, expected ${pk.keyId}` }; + if (!/^[0-9a-f]{128}$/.test(blake2bHex)) return { ok: false, reason: 'not a BLAKE2b-512 digest' }; + const key = createPublicKey({ key: { kty: 'OKP', crv: 'Ed25519', x: pk.key.toString('base64url') }, format: 'jwk' }); + if (!edVerify(null, Buffer.from(blake2bHex, 'hex'), key, s.sig)) return { ok: false, reason: 'the signature does not match the file' }; + if (!edVerify(null, Buffer.concat([s.sig, Buffer.from(s.trustedComment, 'utf8')]), key, s.globalSig)) return { ok: false, reason: 'the trusted comment was changed' }; + if (file && !s.trustedComment.split(/\s+/).includes(`file:${file}`)) return { ok: false, reason: `the trusted comment does not name ${file}` }; + return { ok: true, trustedComment: s.trustedComment }; + } catch (e) { return { ok: false, reason: (e as Error).message }; } +} + +/** Every expected file came back once, with a signature that verifies (pure). Problems, empty when all is well. */ +export function remoteSigProblems(expected: string[], got: RemoteSig[], publicKey: string): string[] { + const problems: string[] = []; + for (const f of expected) { + const s = got.filter(g => g.file === f); + if (s.length !== 1) { problems.push(`${f}: ${s.length ? 'more than one' : 'no'} signature came back`); continue; } + const v = verifyDigest(s[0]!.blake2b, s[0]!.signature, publicKey, f); + if (!v.ok) problems.push(`${f}: ${v.reason}`); + } + for (const g of got) if (!expected.includes(g.file)) problems.push(`${g.file}: not asked for`); + return problems; +} + +/** ssh with a script on stdin, a timeout, and a heartbeat with the last output line. Rejects with the tail. */ +export function sshScript(host: string, script: string, o: { timeoutMs: number; what: string; heartbeatMs?: number; log?: (s: string) => void }): Promise { + const log = o.log ?? ((s: string) => console.log(s)); + return new Promise((res, rej) => { + const c = spawn('ssh', ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=20', '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=4', host, 'bash', '-s'], { stdio: ['pipe', 'pipe', 'pipe'] }); + let out = ''; let err = ''; let last = '(no output yet)'; + const t0 = Date.now(); + c.stdout.on('data', (d: Buffer) => { out += d; const t = d.toString().trim().split('\n').filter(l => !l.startsWith('SIG ')).at(-1); if (t) last = t; }); + c.stderr.on('data', (d: Buffer) => { err += d; }); + const beat = setInterval(() => log(` ${o.what}: ${Math.round((Date.now() - t0) / 1000)} s, ${last.slice(0, 150)}`), o.heartbeatMs ?? 30_000); + const timer = setTimeout(() => { c.kill('SIGTERM'); }, o.timeoutMs); + c.on('error', e => { clearInterval(beat); clearTimeout(timer); rej(new Error(`${o.what}: ssh did not start (${e.message})`)); }); + c.on('close', (code, sig) => { + clearInterval(beat); clearTimeout(timer); + const tail = `${out}\n${err}`.trim().split('\n').filter(l => !l.startsWith('SIG ')).slice(-8).join('\n'); + if (sig === 'SIGTERM') rej(new Error(`${o.what}: timeout after ${Math.round(o.timeoutMs / 60_000)} min on ${host}; last output:\n${tail}`)); + else if (code !== 0) rej(new Error(`${o.what}: exit ${code} on ${host}${code === 255 ? ' (ssh: connection or login failed; not retried)' : ''}:\n${tail}`)); + else res(out); + }); + c.stdin.end(script); + }); +} From 2d7cf6ec2bd2bb01bd2cbb82c73aa8194b670513 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 03:16:27 +0700 Subject: [PATCH 052/344] storebound 0.8.20: version in package.json and every copy, CHANGELOG 0.8.20 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 5f4e9d9..25a1d57 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.19", + "version": "0.8.20", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index f399862..b311446 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.19", + "version": "0.8.20", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 4f9c156..4482868 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.19", + "version": "0.8.20", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index afdd5eb..d92dfe5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.20 · 2026-10-20 + - **Tooling: the desktop updater signatures of the Linux and Windows installers are made on the VDS.** The release no longer downloads them to the Mac: the VDS fetches them from the Forgejo release, checks their SHA-256 against the candidate, signs them with its copy of the updater key and sends back only the .sig texts, which the Mac verifies diff --git a/apps/desktop/package.json b/apps/desktop/package.json index e1d5b99..a32ca97 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.19", + "version": "0.8.20", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index cec38e0..ac02688 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4010,7 +4010,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.19" +version = "0.8.20" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 7c21741..1bfc76d 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.19" +version = "0.8.20" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 6d8c183..305289f 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.19", + "version": "0.8.20", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index 41b1e9a..99739d0 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.19", + "version": "0.8.20", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index f62e217..36d24ee 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.19", + "version": "0.8.20", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From dda21d257069bd85cb97a7a66a2698ea594cd906 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 03:59:39 +0700 Subject: [PATCH 053/344] shots record (web): frames at device pixels through Page.captureScreenshot (clip scale = dpr, long side capped at 1920, 3 requests in flight, midpoint timestamps into the ffmpeg concat); Chromium's screencast stayed at CSS size. Warnings for frames smaller than asked and under 20 frames/s; record-web browser test, pitfall 85 --- CHANGELOG.md | 6 ++++ cli/mcp-tools.ts | 2 +- cli/shots/devices.ts | 26 +++++++++++---- cli/shots/record.ts | 48 ++++++++++++++++++--------- docs/commands.md | 2 +- docs/pitfalls.md | 1 + skills/app-previews/SKILL.md | 4 ++- skills/store-pitfalls/SKILL.md | 11 +++++++ tests/browser/record-web.browser.ts | 51 +++++++++++++++++++++++++++++ tests/video.test.ts | 22 ++++++++++--- 10 files changed, 144 insertions(+), 29 deletions(-) create mode 100644 tests/browser/record-web.browser.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d92dfe5..1792059 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- **`shots record --source web` films at device pixels.** Chromium's screencast always sent frames at the page's CSS + size (430x932 for a 430x932 @2x frame), so a 1080x1920 preview was a 2.5x upscale. The recorder now takes + `Page.captureScreenshot` frames with the clip scaled to the frame's dpr (860x1864 there; long side capped at 1920, + the tallest store video), keeps 3 requests in flight (~45-55 frames/s) and joins them at their real timings as + before. It warns when the first frame is smaller than asked or the rate drops under 20 frames/s. + ## 0.8.20 · 2026-10-20 - **Tooling: the desktop updater signatures of the Linux and Windows installers are made on the VDS.** The release diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index d637967..962ac6e 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -239,7 +239,7 @@ export const TOOLS: ToolDef[] = [ description: 'Write /index.html: one self-contained page with every language, size, scene, variant and app preview, store check issues highlighted. Open it in a browser to review before uploading.', props: { lang }, args: i => opt('lang', i.lang) }, { name: 'shots_record', title: 'Record app or gameplay clips', command: ['shots', 'record'], write: true, network: false, idempotent: true, - description: 'App or gameplay clips for app previews from shots.video.record: web build (Chromium screencast), iOS Simulator (simctl recordVideo), Android emulator / device (screenrecord, never booted) or a folder listing. Local files only.', + description: 'App or gameplay clips for app previews from shots.video.record: web build (Chromium frames at device pixels), iOS Simulator (simctl recordVideo), Android emulator / device (screenrecord, never booted) or a folder listing. Local files only.', props: { lang, only: { type: 'string', description: 'Comma-separated clip names' }, source }, args: i => [...opt('lang', i.lang), ...opt('only', i.only), ...opt('source', i.source)] }, { name: 'shots_video', title: 'Cut app previews', command: ['shots', 'video'], write: true, network: false, idempotent: true, diff --git a/cli/shots/devices.ts b/cli/shots/devices.ts index 3b2fab0..fecf941 100644 --- a/cli/shots/devices.ts +++ b/cli/shots/devices.ts @@ -207,7 +207,7 @@ export const trimArgs = (inp: string, out: string, start: number, seconds: numbe export interface ScreencastFrame { file: string; t: number } -/** ffmpeg concat-demuxer list for screencast frames (Chromium sends a frame only when the page changes): each frame lasts +/** ffmpeg concat-demuxer list for timestamped frames (`t` in seconds, frames come at an uneven rate): each frame lasts * until the next one; the last one fills up to `seconds`. Pure. */ export function concatList(frames: ScreencastFrame[], seconds: number): string { const t0 = frames[0]?.t ?? 0; @@ -226,11 +226,25 @@ export const concatArgs = (list: string, out: string, seconds: number, fps = 30) ['-v', 'error', '-y', '-f', 'concat', '-safe', '0', '-i', list, '-t', seconds.toFixed(3), '-vf', `fps=${fps},scale=trunc(iw/2)*2:trunc(ih/2)*2,format=yuv420p`, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '16', '-an', '-movflags', '+faststart', out]; -/** Screencast size for a frame: the frame at 2x (capped at 1600 px on the long side), even numbers. */ -export function recordSize(d: { w: number; h: number }): { width: number; height: number } { - const k = Math.min(2, 1600 / Math.max(d.w, d.h)); - const even = (n: number) => Math.max(2, Math.round(n * k / 2) * 2); - return { width: even(d.w), height: even(d.h) }; +/** Long side cap of a web recording: the tallest store video (886 x 1920 iPhone preview, 1080 x 1920 Play promo), so + * `shots video` only scales down; a 3x phone (2706 px) or a 13" iPad (2752 px) would cost capture speed for pixels + * every output throws away. */ +export const RECORD_MAX_SIDE = 1920; + +/** Web capture for a frame: CDP `Page.captureScreenshot` with clip = the viewport in CSS px and `scale` = the frame's + * dpr (capped at RECORD_MAX_SIDE on the long side). Chromium returns CSS size x clip.scale whatever the context's + * deviceScaleFactor (checked on Chromium 153); its screencast stays at CSS size (maxWidth only shrinks), which is why + * the recorder does not use it. width / height = the expected image size. Pure. */ +export function recordSize(d: { w: number; h: number; dpr?: number }): { width: number; height: number; scale: number } { + const scale = Math.min(d.dpr ?? 2, RECORD_MAX_SIDE / Math.max(d.w, d.h)); + return { width: Math.round(d.w * scale), height: Math.round(d.h * scale), scale }; +} + +/** Guardrail: a first frame smaller than requested means the browser ignored the capture scale (the clip would be an + * upscale in `shots video`). Message or null. Pure. */ +export function captureShortfall(got: { w: number; h: number }, want: { width: number; height: number }): string | null { + if (got.w >= want.width - 2 && got.h >= want.height - 2) return null; + return `frames are ${got.w}x${got.h}, asked for ${want.width}x${want.height}: this browser ignores the capture scale, so the clip is upscaled later (set STOREBOUND_CHROME to a current Chromium or record with --source folder)`; } // ---- frames ---- diff --git a/cli/shots/record.ts b/cli/shots/record.ts index 0ac1b11..68d74ee 100644 --- a/cli/shots/record.ts +++ b/cli/shots/record.ts @@ -3,8 +3,10 @@ // Config: shots.video.record { source?, device?, clips: { : { seconds, path | url | args | extras, waitFor?, delayMs? } } }; // the URL / simulator / emulator settings are the ones of shots.capture. Out: //NN-.mp4 // (NN = config order, so `shots video` joins them in that order): H.264, 30 fps, no audio. -// web Chromium screencast of the page through Playwright (JPEG frames at up to 2x the frame size, joined by -// your ffmpeg; no Playwright ffmpeg download needed). Filming starts when waitFor turns true (+ delayMs). +// web JPEG frames of the page in Chromium through Playwright (CDP Page.captureScreenshot at the frame's device +// pixels, long side capped at 1920; 3 requests in flight, ~45-55 frames/s on an M1 Pro), each stamped +// with the middle of its request and joined by your ffmpeg at their real durations (no Playwright ffmpeg +// download needed). Not the screencast: it stays at CSS size. Filming starts when waitFor turns true (+ delayMs). // ios-sim `xcrun simctl io recordVideo` while the app runs (launch args with -AppleLanguages, deep link), // stopped with SIGINT after `seconds`. Boots the simulator if needed (shut down again afterwards unless // --keep-booted), status bar 9:41, one warm-up launch after a cold boot (shots.capture.ios.warmupMs). @@ -13,7 +15,8 @@ // folder your own clips (screen recorder, engine capture, OBS): lists // or / with durations. // Make the app or game run hands-free for this (an autoplay / attract mode switch) or record yourself playing with // --source folder. Apple: previews must show footage captured from the app itself. -import { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { spawnSync } from 'node:child_process'; import type { ClipSpec, VideoRecord } from '../lib/config'; @@ -23,9 +26,10 @@ import { done, log, step, warn } from '../lib/log'; import { launch } from './browser'; import { adbPath, localeOf, requireTool, sh } from './capture'; import { ADB_REMOTE_CLIP, adbAppLocaleArgs, adbDemoExitArgs, adbDemoModeArgs, adbForceStopArgs, adbPullArgs, adbRecordArgs, adbRmArgs, adbStartArgs, adbStateArgs, - adbTarget, clipName, fill, pickSimulator, recordSize, simBootArgs, simBootStatusArgs, simLaunchArgs, simOpenUrlArgs, simRecordArgs, simShutdownArgs, + adbTarget, captureShortfall, clipName, fill, pickSimulator, recordSize, simBootArgs, simBootStatusArgs, simLaunchArgs, simOpenUrlArgs, simRecordArgs, simShutdownArgs, simStatusBarArgs, simStatusBarClearArgs, simTarget, SOURCES, type Source, trimArgs, validateRecord, concatArgs, concatList, type ScreencastFrame } from './devices'; import { frameDims } from './lib'; +import { imageInfo } from './spec'; import { CLIP_RE, clipFiles } from './video'; import * as rt from '../lib/rt'; @@ -34,6 +38,9 @@ export function clipsToRecord(r: VideoRecord, only: string[] = []): [number, str return Object.entries(r.clips ?? {}).map(([n, c], i) => [i, n, c] as [number, string, ClipSpec]).filter(([, n]) => !only.length || only.includes(n)); } +/** Capture requests kept in flight for a web clip. */ +const IN_FLIGHT = 3; + const probeDuration = (file: string): number => { const r = spawnSync('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'default=nw=1:nk=1', file]); return Number(r.stdout?.toString().trim()) || 0; @@ -109,27 +116,36 @@ export async function run(ctx: Ctx): Promise { if (cl.waitFor) await page.waitForFunction(cl.waitFor, null, { timeout: 120000, polling: 50 }); for (const js of cl.eval ?? []) await page.evaluate(js); await page.waitForTimeout(cl.delayMs ?? 1000); - // Chromium's screencast (what Playwright's own recorder uses), straight to JPEG frames + system ffmpeg + // captureScreenshot, not the screencast (its frames stay at CSS size); a few requests in flight keep the + // rate near the page's own (one at a time reaches ~20 frames/s) const cdp = await context.newCDPSession(page); + const clip = { x: 0, y: 0, width: d.w, height: d.h, scale: size.scale }; const frames: ScreencastFrame[] = []; let n = 0; - cdp.on('Page.screencastFrame', (f: { data: string; sessionId: number; metadata: { timestamp: number } }) => { - const file = join(dir, `f${String(++n).padStart(5, '0')}.jpg`); - writeFileSync(file, Buffer.from(f.data, 'base64')); - frames.push({ file, t: f.metadata.timestamp }); - cdp.send('Page.screencastFrameAck', { sessionId: f.sessionId }).catch(() => {}); - }); - await cdp.send('Page.startScreencast', { format: 'jpeg', quality: 92, maxWidth: size.width, maxHeight: size.height, everyNthFrame: 1 }); - await page.waitForTimeout(cl.seconds * 1000 + 300); - await cdp.send('Page.stopScreencast'); + const end = performance.now() + cl.seconds * 1000 + 300; + const grab = async () => { + while (performance.now() < end) { + const t0 = performance.now(); + const r = await cdp.send('Page.captureScreenshot', { format: 'jpeg', quality: 92, optimizeForSpeed: true, clip }) as { data: string }; + const file = join(dir, `f${String(++n).padStart(5, '0')}.jpg`); + frames.push({ file, t: (t0 + performance.now()) / 2000 }); + await writeFile(file, Buffer.from(r.data, 'base64')); + } + }; + await Promise.all(Array.from({ length: IN_FLIGHT }, grab)); await context.close(); - if (frames.length < 2) throw new Error(`the screencast delivered ${frames.length} frames (is the page animating?)`); + if (frames.length < 2) throw new Error(`the capture delivered ${frames.length} frames`); + frames.sort((x, y) => x.t - y.t); + const short = captureShortfall(imageInfo(readFileSync(frames[0]!.file)), size); + if (short) warn('shots', `${lang}/${name}: ${short}`); + const rate = frames.length / (frames.at(-1)!.t - frames[0]!.t || 1); + if (rate < 20) warn('shots', `${lang}/${name}: only ${rate.toFixed(0)} frames/s captured (the clip will stutter): close heavy apps, or record with --source folder`); const list = join(dir, 'frames.txt'); writeFileSync(list, concatList(frames, cl.seconds)); sh('ffmpeg', concatArgs(list, outFor(lang, idx, name), cl.seconds), { timeout: 600_000 }); rmSync(dir, { recursive: true, force: true }); made++; - progress(`${lang}/${clipName(idx, name)} (${cl.seconds} s, ${frames.length} frames)`); + progress(`${lang}/${clipName(idx, name)} (${cl.seconds} s, ${size.width}x${size.height}, ${frames.length} frames, ${rate.toFixed(0)}/s)`); } catch (e) { failed++; i++; warn('shots', `${lang}/${name}: ${(e as Error).message.slice(0, 300)}`); await context.close().catch(() => {}); } } } finally { await browser.close(); } diff --git a/docs/commands.md b/docs/commands.md index 7f51fe7..fa5d1ed 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -147,7 +147,7 @@ run in the background with a log (`storebound shots render > .storebound/render. | `shots jpeg` | local | JPEG q92 copies of the Play renders (about 4x faster uploads) | | `shots check [--variants] [--json]` | local, read-only | store rules: sizes, alpha, format, bytes, counts, overflow, fallback / missing glyphs, videos, folder frames | | `shots gallery` | local | `/index.html` review page | -| `shots record [--source ...]` | local | app or gameplay clips: web (Chromium screencast), simulator, emulator, folder | +| `shots record [--source ...]` | local | app or gameplay clips: web (Chromium frames at device pixels), simulator, emulator, folder | | `shots video [--target iphone,ipad,youtube]` | local | app previews + promo video with captions, poster, checks | diff --git a/docs/pitfalls.md b/docs/pitfalls.md index 27cccd0..42ad0d1 100644 --- a/docs/pitfalls.md +++ b/docs/pitfalls.md @@ -9,6 +9,7 @@ fails without the fix. | # | date | lesson | guard | |---|---|---|---| +| 85 | 2026-10 | `shots record --source web` filmed at the page's CSS size: Chromium's screencast ignores the deviceScaleFactor (maxWidth only shrinks), so a 1080x1920 preview of a 430x932 @2x page was a 2.5x upscale. | `Page.captureScreenshot` with `clip.scale` = dpr (long side capped at 1920), 3 requests in flight, timestamped frames joined by ffmpeg; a warning when the first frame is smaller than asked or the rate is under 20 frames/s. `recordSize` / `captureShortfall` in `cli/shots/devices.ts`, `tests/video.test.ts`. | | 80 | 2026-10 | A game's hero logo and titles sat against the screenshot edges, a game with a macOS version had no Mac screenshots, and the contact sheet timed out at a flat 30 s with 9 sizes. | Templates keep 7 % / 5 % safe margins and `shots check` fails text or logo boxes under 6 % / 4 % (`marginViolations`, report.json `boxes`); `apple.mac` adds the `mac` size (APP_DESKTOP, macOS version); `sheetTimeoutMs` scales with images, sizes and load. `tests/mac-landscape.test.ts`, `tests/browser/landscape.browser.ts`. | | 78 | 2026-10 | `storebound api --yes` with stdout piped or redirected printed a dry run and exited 0 (twice); the owner took it as sent. | `decide` (`cli/api/gate.ts`) refuses with `NOT_A_TTY`: exit 1, "refused: writes through `storebound api` need an interactive terminal ... Nothing was sent." on stderr, the dedicated command named; without `--yes` still a dry run. `tests/api.test.ts`. | | 77 | 2026-10 | A Mac App Store version was rejected under Guideline 2.3.10: its What's New came from release notes shared with Google Play ("Google Play Games", "Android"); storebound wrote it without a word. Play's Metadata policy is the mirror case. | `cli/lib/cross-store.ts`: other platforms per locale, field and line (App Store text: Android, Google Play (Games), Play Store, Galaxy Store, Amazon Appstore, Steam, Microsoft Store, AppGallery, localized forms; Play text: iOS, iPhone, iPad, App Store, Apple Arcade, Game Center, TestFlight). Every text write refuses (apple / play listing, play release / upload notes, listing set, whats-new check / apply, the desktop editor and storebound edit); check / validate blockers; scan `other-platforms` (2.3.10) and `play-other-platforms` (Play: Metadata). `listing.allowPlatformMentions` for the owner's functional mentions; whats-new splits `[apple]` / `[play]` lines. `tests/cross-store.test.ts`. | diff --git a/skills/app-previews/SKILL.md b/skills/app-previews/SKILL.md index eb360b1..6409f55 100644 --- a/skills/app-previews/SKILL.md +++ b/skills/app-previews/SKILL.md @@ -34,7 +34,9 @@ other platforms' UI. Play promo video: YouTube URL, public or unlisted, ads off, or `url` / `args` / `extras` (simulator / emulator), `waitFor`, `delayMs`. The source and its settings come from `shots.capture` (or `record.source`). `storebound shots record --dry` shows the plan, then `storebound shots record` writes `store/video/clips//NN-.mp4` (30 fps H.264, no audio). - - web: Chromium screencast at 2x the frame size, filming starts when `waitFor` is true. + - web: JPEG frames at the frame's device pixels (`Page.captureScreenshot`, long side capped at 1920, the tallest + store video), 3 requests in flight (~45-55 frames/s), joined at their real timings; filming starts when `waitFor` + is true. It warns when frames come out smaller than asked (an upscale) or under 20 frames/s. - ios-sim: `simctl io recordVideo`, stopped after `seconds`; boots (and later shuts down) the simulator if needed; the first launch after a cold boot gets `ios.warmupMs`. A still ending is padded with the last frame. - android-emu: `screenrecord` on the running emulator / device (never booted, wiped or rebooted). diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 531540e..3bd982c 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1038,3 +1038,14 @@ that fails without the fix (see CONTRIBUTING.md). - **Guard:** `cli/shots/weights.ts` (templateWeights, fetchFaces, weightIssues), `cli/shots/palette.ts` (bgIssue in config validation, bgCss, contrastIssues, coverCrop); report.json `weights` / `contrast`; `tests/shots-look.test.ts`, `tests/browser/palette-bg.browser.ts`. + +## 85. Web app previews at CSS size (blurry 1080x1920 promo) +- **Symptom:** `shots record --source web` clips of a 430x932 @2x page came out 430x932, so a 1080x1920 preview was a + 2.5x upscale. Chromium's `Page.startScreencast` sends frames at the viewport's CSS size whatever the deviceScaleFactor + (`maxWidth` / `maxHeight` only shrink); forcing scale 2 through `Emulation.setDeviceMetricsOverride` breaks the layout + (innerWidth 980). +- **Do:** update storebound; the recorder takes `Page.captureScreenshot` frames with `clip.scale` = the frame's dpr + (long side capped at 1920), 3 requests in flight. Re-record old web clips. If it still warns that frames are + smaller than asked, point `STOREBOUND_CHROME` at a current Chromium or record with `--source folder`. +- **Guard:** `recordSize` / `captureShortfall` in `cli/shots/devices.ts` (first frame size checked per clip, plus a + frames-per-second warning under 20); `tests/video.test.ts`. diff --git a/tests/browser/record-web.browser.ts b/tests/browser/record-web.browser.ts new file mode 100644 index 0000000..60a129f --- /dev/null +++ b/tests/browser/record-web.browser.ts @@ -0,0 +1,51 @@ +// `shots record --source web` against a local animated page: the clip comes out at the frame's device pixels (CSS size +// x dpr), not at CSS size (Chromium's screencast ignores the deviceScaleFactor), 30 fps H.264 of the asked length. +// Skips when no Chromium can launch or ffmpeg is missing. Runs the CLI in a child process, like a real run. +import { afterAll, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { ShipConfig } from '../../cli/lib/config'; +import { BASE } from '../helpers/store-mock'; + +const CLI = join(import.meta.dir, '..', '..', 'cli', 'index.ts'); + +const server = Bun.serve({ + port: 0, hostname: '127.0.0.1', + fetch: () => new Response(` +`, { headers: { 'content-type': 'text/html' } }), +}); +afterAll(() => server.stop(true)); + +const canLaunch = spawnSync('bun', ['-e', `const { launch } = await import(${JSON.stringify(join(import.meta.dir, '..', '..', 'cli', 'shots', 'browser.ts'))}); await launch(${JSON.stringify(join(import.meta.dir, '..', '..'))}, { headless: true }); process.exit(0);`], { timeout: 60_000 }).status === 0; +const hasFfmpeg = spawnSync('ffmpeg', ['-version']).status === 0; +if (!canLaunch || !hasFfmpeg) console.warn('record-web browser test skipped: needs a Chromium (bunx playwright install chromium) and ffmpeg'); + +describe.skipIf(!canLaunch || !hasFfmpeg)('shots record (web)', () => { + test('clip at device pixels, 30 fps, asked length', async () => { + const root = mkdtempSync(join(tmpdir(), 'sb-rec-')); + try { + mkdirSync(join(root, 'store/shots'), { recursive: true }); + writeFileSync(join(root, 'store/shots/copy.json'), '{}'); + const cfg: ShipConfig = { ...BASE, languages: [{ id: 'en' }], shots: { copy: 'store/shots/copy.json', frames: 'store/shots/frames', out: 'store/renders', + scenes: [{ id: 'hero', palette: 'fire', frames: [{ src: 'hero.png' }] }], phone: { w: 200, h: 400, dpr: 2 }, + capture: { source: 'web', baseUrl: `http://127.0.0.1:${server.port}`, shots: { home: { path: '/' } } }, + video: { clips: 'store/video/clips', record: { clips: { play: { seconds: 2, path: '/', waitFor: 'window.ready', delayMs: 50 } } } } } } as ShipConfig; + writeFileSync(join(root, 'storebound.config.json'), JSON.stringify(cfg)); + const r = Bun.spawn(['bun', CLI, 'shots', 'record'], { cwd: root, stdout: 'pipe', stderr: 'pipe', env: { ...process.env, NO_COLOR: '1' } }); + const [out, err, code] = await Promise.all([new Response(r.stdout).text(), new Response(r.stderr).text(), r.exited]); + if (code !== 0) console.error(out, err); + expect(code).toBe(0); + expect(err).not.toContain('asked for'); + const probe = spawnSync('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height,r_frame_rate:format=duration', '-of', 'json', join(root, 'store/video/clips/en/01-play.mp4')]).stdout.toString(); + const j = JSON.parse(probe) as { streams: { width: number; height: number; r_frame_rate: string }[]; format: { duration: string } }; + expect(j.streams[0]).toMatchObject({ width: 400, height: 800, r_frame_rate: '30/1' }); + expect(Number(j.format.duration)).toBeCloseTo(2, 1); + } finally { rmSync(root, { recursive: true, force: true }); } + }, 120_000); +}); diff --git a/tests/video.test.ts b/tests/video.test.ts index 7d45527..5c06607 100644 --- a/tests/video.test.ts +++ b/tests/video.test.ts @@ -5,7 +5,7 @@ import { setUpToDate } from '../cli/apple/asc'; import { mimeType, previewAttrs, previewFiles, previewSets } from '../cli/apple/previews'; import { type ShipConfig, validateConfig } from '../cli/lib/config'; import { listingBody } from '../cli/play/listing'; -import { adbPullArgs, adbRecordArgs, adbRmArgs, clipName, concatArgs, concatList, recordSize, simRecordArgs, trimArgs, validateRecord } from '../cli/shots/devices'; +import { adbPullArgs, adbRecordArgs, adbRmArgs, captureShortfall, clipName, concatArgs, concatList, RECORD_MAX_SIDE, recordSize, simRecordArgs, trimArgs, validateRecord } from '../cli/shots/devices'; import { clipsToRecord } from '../cli/shots/record'; import { checkVideo, parseProbe, type ProbeInfo } from '../cli/shots/spec'; import { clipFiles, defaultTargets, planClips, posterArgs, timeCode, videoArgs } from '../cli/shots/video'; @@ -116,9 +116,23 @@ describe('record', () => { expect(a.slice(3, 12)).toEqual(['-f', 'concat', '-safe', '0', '-i', 'l.txt', '-t', '6.000', '-vf']); expect(a.at(-1)).toBe('o.mp4'); }); - test('record size: 2x, capped, even', () => { - expect(recordSize({ w: 440, h: 902 })).toEqual({ width: 780, height: 1600 }); - expect(recordSize({ w: 301, h: 401 })).toEqual({ width: 602, height: 802 }); + test('record size: device pixels (clip scale = dpr), long side capped', () => { + // a 430x932 @2x context: the screencast gave 430x932, captureScreenshot with scale 2 gives 860x1864 + expect(recordSize({ w: 430, h: 932, dpr: 2 })).toEqual({ width: 860, height: 1864, scale: 2 }); + expect(recordSize({ w: 301, h: 401, dpr: 2 })).toEqual({ width: 602, height: 802, scale: 2 }); + expect(recordSize({ w: 360, h: 640, dpr: 1 })).toEqual({ width: 360, height: 640, scale: 1 }); + // default 3x phone (2706 px tall) and the 13" iPad: capped at the tallest store video, never below the frame's CSS size + const phone = recordSize({ w: 440, h: 902, dpr: 3 }); + expect(phone.height).toBe(RECORD_MAX_SIDE); + expect(phone.width).toBe(937); + expect(phone.scale).toBeCloseTo(1920 / 902, 6); + expect(recordSize({ w: 1032, h: 1352, dpr: 2 })).toMatchObject({ width: 1466, height: 1920 }); + expect(recordSize({ w: 440, h: 902 }).scale).toBe(2); + }); + test('capture guardrail: frames smaller than requested', () => { + expect(captureShortfall({ w: 860, h: 1864 }, { width: 860, height: 1864 })).toBeNull(); + expect(captureShortfall({ w: 937, h: 1919 }, { width: 937, height: 1920 })).toBeNull(); + expect(captureShortfall({ w: 430, h: 932 }, { width: 860, height: 1864 })).toContain('frames are 430x932, asked for 860x1864'); }); test('config checks', () => { expect(validateRecord({ clips: { a: { seconds: 8, path: '/' } } }, cap)).toEqual([]); From f5e7b907a9d8a13f5d242cd099a91a2677582db5 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 04:01:41 +0700 Subject: [PATCH 054/344] acceptance: storebound api --yes without a terminal is refused (exit 1, nothing sent) since the TTY rule; the cell still expected a silent dry run and turned every acceptance job red --- tools/acceptance.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tools/acceptance.ts b/tools/acceptance.ts index 8a899b6..d650553 100644 --- a/tools/acceptance.ts +++ b/tools/acceptance.ts @@ -180,7 +180,8 @@ export function cells(forms: string[]): Cell[] { no('play rollout [y/N] n', ['play', 'rollout', '--fraction', '0.2'], NO, { exit: [1, 3], expect: undefined }), // before the release, the phased release is only a setting of the version: no question no('apple release --phased on (version not released yet)', ['apple', 'release', '--phased', 'on'], NO, { exit: 0, expect: /phased release on/, noWrites: false }), - no('api apple POST without a terminal (dry)', ['api', 'apple', 'bundleIds_createInstance', '--body', 'store/bundle.json', '--yes'], 'wrong\n', { exit: 0, expect: /nothing sent/ }), + // --yes without a terminal is refused (exit 1, nothing sent), never a silent dry run + no('api apple POST without a terminal (refused)', ['api', 'apple', 'bundleIds_createInstance', '--body', 'store/bundle.json', '--yes'], 'wrong\n', { exit: 1, expect: /need an interactive terminal.*Nothing was sent/ }), ); return c; } From a6dab8f3aaf7edc164d40dcd21ca687044f7ab88 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 04:03:24 +0700 Subject: [PATCH 055/344] storebound 0.8.21: version in package.json and every copy, CHANGELOG 0.8.21 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 25a1d57..7c77d07 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.20", + "version": "0.8.21", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index b311446..04d9838 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.20", + "version": "0.8.21", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 4482868..11c9600 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.20", + "version": "0.8.21", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index 1792059..f108ffd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.21 · 2026-10-20 + - **`shots record --source web` films at device pixels.** Chromium's screencast always sent frames at the page's CSS size (430x932 for a 430x932 @2x frame), so a 1080x1920 preview was a 2.5x upscale. The recorder now takes `Page.captureScreenshot` frames with the clip scaled to the frame's dpr (860x1864 there; long side capped at 1920, diff --git a/apps/desktop/package.json b/apps/desktop/package.json index a32ca97..b924c70 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.20", + "version": "0.8.21", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index ac02688..4daed19 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4010,7 +4010,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.20" +version = "0.8.21" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 1bfc76d..2460322 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.20" +version = "0.8.21" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 305289f..435aa8b 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.20", + "version": "0.8.21", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index 99739d0..1711a59 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.20", + "version": "0.8.21", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index 36d24ee..198206c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.20", + "version": "0.8.21", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From 335a4124abeeff1a8e77386d0df0286553da1ed5 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:03:02 +0700 Subject: [PATCH 056/344] console plans: guardrails from a real run (2026-10-21): health none label and Sign in details Yes/No + Add details (old labels as altLabels, verify accepts both), finance boxes on step 1, App Privacy Additional Setup Required OK, verify from DOM input states (verify.capture, --from), Save + confirm before every Next on Play pages, IARC Digital purchases boxes and an exact-label in-page helper that refuses patterns and blanket answers; review contact found in parent folders, the profile and more key shapes with the files checked listed; one-line errors for missing required values (Args.required); pitfalls 86-87, tests --- CHANGELOG.md | 17 +++ cli/apple/adhoc.ts | 3 +- cli/apple/listing.ts | 3 +- cli/apple/resubmit.ts | 4 +- cli/apple/review-details.ts | 12 +- cli/commands.ts | 2 +- cli/console/verify.ts | 5 +- cli/data/flags.json | 10 +- cli/edit.ts | 3 +- cli/lib/args.ts | 6 + cli/lib/console-answers.ts | 5 + cli/lib/console-forms.ts | 1 + cli/lib/console-plan.ts | 57 ++++++-- cli/lib/console-play-plans.ts | 74 +++++++--- cli/lib/console-verify.ts | 47 ++++++- cli/lib/credentials.ts | 60 +++++++- cli/mcp-tools.ts | 2 +- cli/privacy-manifest.ts | 3 +- skills/console-autofill/SKILL.md | 20 ++- skills/store-pitfalls/SKILL.md | 27 ++++ tests/console-guardrails-1021.test.ts | 191 ++++++++++++++++++++++++++ tests/console-play-plans.test.ts | 6 +- tests/desktop-d3.test.ts | 2 +- 23 files changed, 486 insertions(+), 74 deletions(-) create mode 100644 tests/console-guardrails-1021.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index f108ffd..26b8f1e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,23 @@ ## Unreleased +- **Console plans follow the live pages (2026-10-21 run).** Play health: "My app does not have any health features" + (verify accepts it, "Other" stays a fallback); Sign in details: "Is any part of your app restricted?" Yes / No and + "Add details" (old labels kept as `altLabels`); finance: the boxes on step 1, step 2 information only; App Privacy: + the "Additional Setup Required" OK that opens the first type's setup by itself is in the steps and UI facts. +- **Save after every page.** Every Play plan step that answers a page with a Save next to Next now says Save, wait + for "Your changes have been saved", then Next; the rule line says it too. +- **IARC by exact labels.** "Purchases of digital goods" is ticked after Yes on "Digital purchases" (the loot-box and + trading follow-ups show only then); the in-page helper matches exact labels and questions and refuses patterns, + radios without their question and blanket group answers. +- **`console verify` reads input states.** The Play declaration plans' `verify.capture` returns every radio / + checkbox with aria-checked / checked / aria-selected as JSON; `console verify
--from ` takes it. +- **`apple review-details` finds the contact** in parent folders' `.storebound/credentials.json` and the credential + profile, under more key shapes, and lists every file and key checked when there is none. +- **One-line errors for missing required values:** `apple listing` without `--version` says "--version is + required (storebound apple status shows the editable version)"; the same for privacy-manifest `--ios`, adhoc + export `--archive`, edit `--ops` and resubmit `--build`. A flag given without a value counts as missing. + ## 0.8.21 · 2026-10-20 - **`shots record --source web` films at device pixels.** Chromium's screencast always sent frames at the page's CSS diff --git a/cli/apple/adhoc.ts b/cli/apple/adhoc.ts index f608c0d..46e6873 100644 --- a/cli/apple/adhoc.ts +++ b/cli/apple/adhoc.ts @@ -165,8 +165,7 @@ function options(ctx: Ctx): void { function exportIpa(ctx: Ctx): void { const a = ctx.args; - const archive = a.get('archive'); - if (!archive || archive === 'true') throw new Error('usage: storebound apple adhoc export --archive [--out build/adhoc] [--dry]'); + const archive = a.required('archive', 'App.xcarchive', 'Xcode: Product > Archive, or storebound apple build'); if (!existsSync(archive)) throw new Error(`${archive}: no such archive (Xcode: Product > Archive, or xcodebuild archive)`); const plistRel = a.str('plist', 'build/ExportOptions.plist'); const plist = ctx.loaded.resolve(plistRel); diff --git a/cli/apple/listing.ts b/cli/apple/listing.ts index 0c75a3e..8fdeb45 100644 --- a/cli/apple/listing.ts +++ b/cli/apple/listing.ts @@ -195,8 +195,7 @@ export async function run(ctx: Ctx): Promise { const { config, root } = ctx.loaded; const a = ctx.args; if (a._[0] === 'pull') return pull(ctx); - const version = a.get('version'); - if (!version) throw new Error('usage: apple listing --version 1.0.0 [--build N] [--include-drafts] [--dry] [--json]'); + const version = a.required('version', 'x.y.z', 'storebound apple status shows the editable version'); const dry = a.has('dry'); const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId); const appId = await c.app(); diff --git a/cli/apple/resubmit.ts b/cli/apple/resubmit.ts index 051c9ec..095b164 100644 --- a/cli/apple/resubmit.ts +++ b/cli/apple/resubmit.ts @@ -39,8 +39,8 @@ export async function submitVersion(ctx: Ctx, mode: 'submit' | 'resubmit'): Prom const TAG = mode; const { config, root } = ctx.loaded; const a = ctx.args; - const number = a.get('build'); - if (!number || !/^\d+(\.\d+)*$/.test(number)) throw new Error(`usage: apple ${mode} --build [--version x.y.z] [--dry] [--yes]: the build number you just uploaded (never "the latest")`); + const number = a.required('build', 'n', 'the build number you just uploaded, never "the latest"; storebound apple testflight status lists them'); + if (!/^\d+(\.\d+)*$/.test(number)) throw new Error(`--build ${number}: a build number like 42 or 1.0.3 (the one you just uploaded, never "the latest")`); const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId); const appId = await c.app(); const ids = [...(config.products ?? []).filter(p => sellsOn(config, p, 'apple')).map(p => p.id), ...allSubscriptions(config.subscriptions).filter(x => sellsOn(config, x.sub, 'apple')).map(x => x.sub.id)]; diff --git a/cli/apple/review-details.ts b/cli/apple/review-details.ts index 11f56bc..ab9404b 100644 --- a/cli/apple/review-details.ts +++ b/cli/apple/review-details.ts @@ -8,7 +8,7 @@ import { refuseTemplate } from '../lib/template-answers'; import type { Ctx } from '../lib/ctx'; import { need } from '../lib/ctx'; -import { reviewContact, reviewDemoAccount } from '../lib/credentials'; +import { findReviewContact, noContactMessage, reviewDemoAccount } from '../lib/credentials'; import { reviewDetailPlan } from '../lib/review-details'; import { done, log } from '../lib/log'; import { createOnce } from '../lib/upsert'; @@ -29,11 +29,15 @@ export async function run(ctx: Ctx): Promise { if (a?.contactEmail) { contact = { contactFirstName: a.contactFirstName, contactLastName: a.contactLastName, contactPhone: a.contactPhone, contactEmail: a.contactEmail }; break; } } if (!contact) throw new Error(`app ${from} has no review contact on its recent versions`); - } else { - const rc = reviewContact(root); + } + let checked: string[] = []; + if (!from) { + const found = findReviewContact(root); + checked = found.checked; + const rc = found.contact; if (rc) contact = { contactFirstName: rc.firstName, contactLastName: rc.lastName, contactPhone: rc.phone, contactEmail: rc.email }; } - if (!contact) throw new Error('no review contact: add "reviewContact" to .storebound/credentials.json or pass --contact-from '); + if (!contact) throw new Error(noContactMessage(root, checked)); const { attributes, summary } = reviewDetailPlan(config, contact, reviewDemoAccount(root)); if (ctx.args.has('dry')) { log('apple', `would set review details (contact ${from ? 'copied from ' + from : 'from credentials'}, ${summary})`); return; } diff --git a/cli/commands.ts b/cli/commands.ts index 8014f55..96e27e3 100644 --- a/cli/commands.ts +++ b/cli/commands.ts @@ -43,7 +43,7 @@ export const COMMANDS: Record Promise, string]> = { 'web': [() => import('./web'), 'init (apple-app-site-association, assetlinks.json, Smart App Banner tag, optional landing page) | check (live files: content type, no redirects, ids match)'], 'revenuecat': [() => import('./revenuecat'), 'diff (catalog vs RevenueCat products, entitlements, default offering) | sync (dry run, asks first; never via MCP)'], 'console plan': [() => import('./console/plan'), ' [--json] [--all]: agent-first console mode: the owner batch first, start URL, steps, answer sheet (certain / ask owner, console labels), never-press list, UI facts and how to verify, for an AI agent that drives the browser itself; read-only'], - 'console verify': [() => import('./console/verify'), ' [--from-text ] [--json]: check a filled console form against the config (page text, input states or the App Store Connect API); read-only, exit 1 on a mismatch'], + 'console verify': [() => import('./console/verify'), ' [--from ] [--from-text ] [--json]: check a filled console form against the config (page text, the input-state JSON of the plan\'s verify.capture, or the App Store Connect API); read-only, exit 1 on a mismatch'], 'console fill': [() => import('./console/fill'), ' [--store apple|play]: optional scripted fast path: autofill in a visible Chromium you sign in to yourself; stops before Save / Submit'], 'reviews': [() => import('./reviews'), 'list | draft (local reply drafts in .storebound/replies) | send (approved drafts only, asks first)'], 'originality': [() => import('./originality'), 'Guideline 4.3 check vs your other apps (--against ): listing text, name, icon and screenshot perceptual hashes, project structure; scores, flags, suggestions; offline, exit 1 on a near-duplicate'], diff --git a/cli/console/verify.ts b/cli/console/verify.ts index 48926ea..09d0d45 100644 --- a/cli/console/verify.ts +++ b/cli/console/verify.ts @@ -1,5 +1,6 @@ // Checks a console form against the config after the agent (or the owner) filled it. Read-only. -// storebound console verify [--from-text ] [--json] +// storebound console verify [--from ] [--from-text ] [--json] +// --from takes the JSON of the plan's verify.capture snippet (input states: aria-checked, checked, aria-selected) or page text. // storebound console verify play-app-record --url [--write] // apple-app-privacy: the page text of the App Privacy page (the Data Types section's per-type summaries; the App Store // Connect API has no App Privacy endpoint). play-app-record: the JSON of the plan's capture snippet (input states) or @@ -30,7 +31,7 @@ export async function run(ctx: Ctx): Promise { const args = ctx.args, json = args.has('json'); const form = args._[0]; if (!isPlanForm(form)) throw new Error(`console verify [--from-text ]: one of ${PLAN_FORM_IDS.join(', ')}`); - const from = args.get('from-text'), url = args.get('url'); + const from = args.get('from') ?? args.get('from-text'), url = args.get('url'); const inline = args.get('text') ?? (url !== undefined ? url : undefined); if (url !== undefined && form !== 'play-app-record') throw new Error('console verify: --url is for play-app-record (the URL Create app redirects to)'); let r: VerifyResult; diff --git a/cli/data/flags.json b/cli/data/flags.json index 37834d6..16a092e 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -50,7 +50,6 @@ "upload" ], "apple adhoc": [ - "archive", "csv", "method", "name", @@ -175,7 +174,6 @@ "version" ], "apple resubmit": [ - "build", "new-version", "no-submit", "platform", @@ -210,7 +208,6 @@ "wait-review" ], "apple submit": [ - "build", "new-version", "no-submit", "platform", @@ -423,6 +420,7 @@ "cordova-ios", "expo", "flutter", + "from", "from-text", "godot", "name", @@ -447,7 +445,6 @@ "dir" ], "edit": [ - "ops", "show" ], "flow": [ @@ -688,7 +685,6 @@ "with-automatic" ], "privacy-manifest": [ - "ios", "propose", "sdk-dirs", "tracking-domains" @@ -926,7 +922,6 @@ "apple", "apply", "apps", - "archive", "aso", "base", "base-url", @@ -1058,7 +1053,6 @@ "only-keywords", "only-missing", "only-terms", - "ops", "originality", "out", "param", @@ -1334,7 +1328,7 @@ "storebound console plan play-app-content --all [--json] every App content card's steps inline, one owner list" ], "console verify": [ - "storebound console verify [--from-text ] [--json]", + "storebound console verify [--from ] [--from-text ] [--json]", "storebound console verify play-app-record --url [--write]" ], "desktop": [ diff --git a/cli/edit.ts b/cli/edit.ts index 80483f1..89c16cc 100644 --- a/cli/edit.ts +++ b/cli/edit.ts @@ -86,8 +86,7 @@ export async function run(ctx: Ctx): Promise { const a = ctx.args; const { root } = ctx.loaded; if (a.has('show')) { printJson(editableValues(ctx.loaded)); return; } - const opsJson = a.get('ops'); - if (!opsJson) throw new Error('usage: storebound edit --ops \'\' [--dry] [--json] | storebound edit --show --json'); + const opsJson = a.required('ops', 'json', 'storebound edit --show --json lists the editable values'); const { plan: p, texts } = await plan(ctx, opsJson); const dry = a.has('dry'); // with --json in a terminal, stdout is the JSON result only: the lines go to stderr (under `serve` the result is a diff --git a/cli/lib/args.ts b/cli/lib/args.ts index c24ac90..e744174 100644 --- a/cli/lib/args.ts +++ b/cli/lib/args.ts @@ -8,8 +8,13 @@ export interface Args { list(name: string): string[]; /** Every value of a flag given more than once (--param a=1 --param b=2), in order. */ many(name: string): string[]; + /** A flag that needs a value: missing, or given without one (--version alone), throws ONE line with the fix. */ + required(name: string, placeholder: string, fix?: string): string; } +/** The one-line error of a missing required flag (never the whole help). */ +export const requiredError = (name: string, placeholder: string, fix?: string): Error => new Error(`--${name} <${placeholder}> is required${fix ? ` (${fix})` : ''}`); + export function parseArgs(argv: string[], booleans: string[] = []): Args { const flags = new Map(); const repeated = new Map(); @@ -35,5 +40,6 @@ export function parseArgs(argv: string[], booleans: string[] = []): Args { num: (n, d) => { const v = get(n); const x = v === undefined ? d : Number(v); if (Number.isNaN(x)) throw new Error(`--${n}: not a number`); return x; }, list: n => (get(n) ?? '').split(',').map(s => s.trim()).filter(Boolean), many: n => repeated.get(n) ?? [], + required: (n, ph, fix) => { const v = get(n); if (v === undefined || v === 'true' || !v.trim()) throw requiredError(n, ph, fix); return v; }, }; } diff --git a/cli/lib/console-answers.ts b/cli/lib/console-answers.ts index b670d68..499c0cf 100644 --- a/cli/lib/console-answers.ts +++ b/cli/lib/console-answers.ts @@ -291,6 +291,8 @@ export const IARC_LABELS: Record = { userInteraction: 'Users can interact or exchange content', sharesLocation: 'Shares the user\'s location with other users', digitalPurchases: 'Digital purchases', unrestrictedInternet: 'Unrestricted internet access (browser)', }; +/** IARC's Digital purchases question and the box its Yes reveals (exact console labels, 2026-10-21). */ +export const IARC_DIGITAL_PURCHASES = 'Digital purchases', IARC_DIGITAL_GOODS = 'Purchases of digital goods'; const CATEGORY_LABELS = { game: 'Game', social: 'Social or communication', other: 'All other app types' } as const; /** The IARC follow-up questions (console.contentRating.details), in the page's order: section -> key -> label. The @@ -362,6 +364,9 @@ function contentRating(config: ShipConfig): Answer[] { if (topics && !topics.some(t => topic.get(t) === true)) continue; const given = (det as Record | undefined>)[sec] ?? {}; const src = (k: string) => `console.contentRating.details.${sec}.${k}`; + // Yes on Digital purchases reveals boxes; "Purchases of digital goods" must be ticked before the loot-box and trading + // follow-ups show (2026-10-21) + if (sec === 'digitalPurchases') out.push(ok(`d:digitalPurchases:digitalGoods`, `Digital purchases: ${IARC_DIGITAL_GOODS}`, true, `console.contentRating.answers.digitalPurchases (Yes) or what is sold`, 'Tick it first: the loot-box and trading questions show only after it.')); for (const [k, kind] of Object.entries(IARC_DETAIL_KEYS[sec])) { if (sec === 'digitalPurchases' && k === 'lootBoxes') continue; // the q:lootBoxes answer above const label = IARC_DETAIL_LABELS[sec][k]!, id = `d:${sec}:${k}`, v = given[k]; diff --git a/cli/lib/console-forms.ts b/cli/lib/console-forms.ts index 4f61e98..0916f9a 100644 --- a/cli/lib/console-forms.ts +++ b/cli/lib/console-forms.ts @@ -462,6 +462,7 @@ export const FORM_BUTTONS: Record = { { button: 'Edit (next to one data type)', class: 'navigation', where: 'Data Types section, a type set up before: reopens its questions, only when its purposes differ from the config', auto: true }, { button: '? / More information', class: 'navigation', where: 'next to each heading and data type: help only (never needed)', auto: false }, { button: 'Next / Continue', class: 'navigation', where: 'questionnaire dialogs', auto: true }, + { button: 'OK', class: 'navigation', where: 'the "Additional Setup Required" message after the data types Save (it may open the first type\'s setup by itself)', auto: true }, { button: 'Back', class: 'navigation', where: 'questionnaire dialogs (never needed)', auto: false }, { button: 'Definitions and Examples', class: 'navigation', where: 'a data type\'s tracking step: help only (never clicked)', auto: false }, { button: 'Save', class: 'draft-save', where: 'questionnaire dialogs: stores the answers, not public until Publish', auto: true }, diff --git a/cli/lib/console-plan.ts b/cli/lib/console-plan.ts index 3afc200..f800c59 100644 --- a/cli/lib/console-plan.ts +++ b/cli/lib/console-plan.ts @@ -9,10 +9,10 @@ import { consoleLink, consoleUrl } from './console-links'; import { playCategoryOf, type ShipConfig } from './config'; import type { ProjectSignals } from './project-signals'; import { type Answer, type AnswerValue, consoleAnswers, type FormId, formMeta, isPlanOnly, type PlanFormId, type Store, valueText } from './console-answers'; -import { APP_CONTENT_CAPTURE, APP_CONTENT_CARDS, appContentStart, PLAY_FULL_ACCESS_BOX, PLAY_MATERIAL_FACT, playAppPage, playOnlyPart, SEND_FOR_REVIEW, SEND_FOR_REVIEW_WHERE, startLabel } from './console-play-plans'; +import { APP_CONTENT_CAPTURE, APP_CONTENT_CARDS, appContentStart, PLAY_FULL_ACCESS_BOX, PLAY_MATERIAL_FACT, playAppPage, playOnlyPart, SAVE_EACH_PAGE, SEND_FOR_REVIEW, SEND_FOR_REVIEW_WHERE, startLabel } from './console-play-plans'; import { FORM_BUTTONS, formDef, type Name, NEVER_PRESS, PLAY_NEVER_PRESS, playAppList, playCreateApp, setUpTexts, typeLabels } from './console-forms'; import { PLAY_CREATE_CAPTURE } from './console-verify'; -import { APPLE_PURPOSES } from './console-answers'; +import { APPLE_PURPOSES, IARC_DIGITAL_GOODS, IARC_DIGITAL_PURCHASES } from './console-answers'; export type PlanStatus = 'certain' | 'ask-owner' | 'owner-check' | 'agreement'; @@ -37,6 +37,8 @@ export interface PlanAnswer { where?: string; /** The label has a typographic quote (’ “ ”): match straight and curly quotes alike. */ curlyQuotes?: boolean; + /** Older or alternative console labels of the same control (tried after `label`; verify accepts them too). */ + altLabels?: string[]; } export interface PlanStep { @@ -162,6 +164,7 @@ function sheet(form: FormId, answers: Answer[]): PlanAnswer[] { if (kind === 'tracking') return withLabel(p, trackingLabel(t, v !== false), { control: 'radio', action: 'pick', where: `the "${t}" dialog, step 5 (tracking)` }); return p; } + if (a.id === 'd:digitalPurchases:digitalGoods') return withLabel(p, IARC_DIGITAL_GOODS, { control: 'checkbox', action: 'tick', where: `Digital Purchases: the boxes "${IARC_DIGITAL_PURCHASES}" Yes reveals` }); const hit = fieldOf.get(a.id); if (!hit) return p; const { f, s } = hit; @@ -183,6 +186,7 @@ const ids = (answers: PlanAnswer[], pred: (a: PlanAnswer) => boolean) => answers const DRIVING = [ 'Use your own browser tool (Claude in Chrome, a built-in browser, Playwright). Read the page as text or an accessibility tree first; click by visible text; adapt when the page differs from these steps (the console changes without notice), but never press anything in buttons.neverPress.', 'Long flows run INSIDE the page: one Runtime.evaluate / javascript call times out at about 45 s on big Play pages (the IARC questionnaire, App content), so never loop over many controls in one call. Paste plan.inPageLoop once per page (one short call; it defines window.__sb), start the job with window.__sb.run([{ role: "radio", label: "No", within: "" }, { role: "checkbox", label: "", want: true }, ...]) (it returns at once), then poll window.__log.slice(-20) and window.__done in short calls every 2-5 s until the log says done. The helper only picks radios and ticks boxes (never agreements); press Next / Save yourself afterwards, by their visible text.', + 'Exact labels only: every label and within is the console\'s exact text from the answer sheet (a trailing "…" allows any rest). Never answer by keywords or regex and never blanket-answer the unanswered groups: a keyword helper once answered IARC\'s "Digital purchases" No because its text also mentions "cash rewards". The helper refuses patterns, radios without their exact question and group steps; a question without an exact sheet answer is the owner\'s.', 'Wait for each step to render (poll for the next heading or input, up to ~10 s) before acting; never act on a step you have not read.', 'Text fields: click the field and TYPE the text (key presses), then read the value back. Never set it programmatically (form_input, el.value = …): App Store Connect\'s New App kept its Name and SKU empty after a value set (verified 2026-10-13).', 'Owner steps: hand the owner plan.ownerBatch in ONE message before you start (the "before" items: answers, the IARC Terms of Use box) and run without stopping until the "after" items (the final button).', @@ -214,18 +218,23 @@ export const IN_PAGE_LOOP = [ ' const scopeOf = (text) => {', ' const want = norm(text).toLowerCase(); let best = null;', ' for (const el of document.querySelectorAll("section, fieldset, div, [role=radiogroup], [role=group]"))', - ' if (norm(el.innerText).toLowerCase().includes(want) && el.querySelector(CONTROLS) && (!best || best.contains(el))) best = el;', + ' if (norm((el.innerText || "").split("\\n")[0]).toLowerCase() === want && el.querySelector(CONTROLS) && (!best || best.contains(el))) best = el;', ' return best;', ' };', ' const find = (role, label, scope) => {', - ' const want = norm(label).toLowerCase();', + ' const prefix = /…$/.test(label), want = norm(label).replace(/…$/, "").toLowerCase();', ' const hits = [...(scope || document).querySelectorAll("[role=" + role + "], input[type=" + role + "]")]', - ' .filter((el) => el.getClientRects().length && labelOf(el).toLowerCase().startsWith(want));', + ' .filter((el) => { const l = labelOf(el).toLowerCase(); return el.getClientRects().length && (prefix ? l.startsWith(want) : l === want); });', ' return hits.length === 1 ? hits[0] : null;', ' };', + ' const KEYWORDS = /[|*^$\\\\[\\]]/;', ' const set = async (s) => {', + ' if (typeof s.label !== "string" || !s.label || (s.within !== undefined && typeof s.within !== "string")) return "refused: pass the exact console label (a string), never a pattern";', + ' if (KEYWORDS.test(s.label) || KEYWORDS.test(s.within || "")) return "refused: keywords or a pattern; pass the exact console label from the answer sheet";', + ' if (s.role === "radio" && !s.within) return "refused: a radio needs within = its exact question text (no blanket answers)";', + ' if (s.group || s.all || s.rest) return "refused: no blanket answers for groups without an exact answer";', ' const scope = s.within ? scopeOf(s.within) : null;', - ' if (s.within && !scope) return "no block with \\"" + s.within + "\\"";', + ' if (s.within && !scope) return "no block whose question is exactly \\"" + s.within + "\\"";', ' const el = find(s.role, s.label, scope);', ' if (!el) return "not found or ambiguous";', ' if (NEVER.test(labelOf(el))) return "refused: an agreement (the owner ticks it)";', @@ -254,6 +263,9 @@ export const IN_PAGE_LOOP = [ '})()', ].join('\n'); +/** App Privacy after the data types Save: the "Additional Setup Required" message and what its OK may open. */ +export const APPLE_ADDITIONAL_SETUP = 'After saving the data types, an "Additional Setup Required" message appears: press its OK. That OK sometimes opens the first type\'s setup dialog by itself; the dialog it opened IS the first type\'s setup (step 1, purposes), so carry on from there with that type and do not press its Set Up again. Otherwise press the first type\'s "Set Up".'; + function appPrivacyPlan(answers: PlanAnswer[], appId: string | null | undefined): Pick { const types = answers.filter(a => a.id.startsWith('type:')); const collected = types.filter(a => a.value === true).map(a => a.id.slice(5)); @@ -262,6 +274,7 @@ function appPrivacyPlan(answers: PlanAnswer[], appId: string | null | undefined) add({ text: appId ? 'Open the App Privacy page of the app (deep link).' : `Open App Store Connect > Apps > the app > App Privacy (sidebar): ${consoleUrl('asc.apps')}` }); add({ text: 'First time: click "Get Started" and answer the Data Collection question; then Next.', click: ['Get Started'], answers: ['collects'] }); add({ text: 'Data types: when the Data Types section does not list exactly the collected types below, click the "Edit" next to the "Data Types" heading (never the Privacy Policy Edit), tick exactly these types and untick the rest, then Save (a draft: nothing is public before Publish). Console labels: Purchase History shows as "Purchases", Other Data Types as "Other Data".', click: ['Edit', 'Save'], answers: ids(answers, a => a.id.startsWith('type:')) }); + add({ text: `${APPLE_ADDITIONAL_SETUP}`, click: ['OK'] }); for (const t of collected) { const set = setUpTexts(t).filter(x => !/ ayarla$/.test(x)); add({ type: t, text: `"${t}": click the text "${set.join('" or "')}" in the Data Types section (a plain

with a click handler, not a button). A dialog opens whose h2 is "${typeLabels(t).join('" or "')}". (Set up before: its row shows Edit and a summary; open it with that row's Edit only when the summary differs from the answers.)`, click: set }); @@ -280,6 +293,7 @@ function appPrivacyPlan(answers: PlanAnswer[], appId: string | null | undefined) 'Verified 2026-10-12 on /apps//distribution/privacy:', 'Data Types section: each collected type has "Set Up ", a plain

inside a div with the click handler (no button or link role). Click it by its exact text. It opens a

whose h2 is the type name.', `Step 1, purposes: 6 checkboxes in this order: ${APPLE_PURPOSES.map(purposeLabel).join(', ')} (Developer’s with a curly ’). An input has no aria label; its label is the nearest non-empty parent text (the label and its help text run together, e.g. "AnalyticsSuch as ..."): match by "starts with the label". Buttons: Cancel, Next.`, + `Never a surprise (verified 2026-10-21): ${APPLE_ADDITIONAL_SETUP}`, 'Step 2, linked: 2 radios, "Yes, data collected from this app is linked to the user’s identity" / "No, …" (curly ’). Buttons: Back, Cancel, Next.', 'Step 3: an information page "Let’s define two important terms…" (Tracking / Third-Party Data). No inputs: press Next.', 'Step 4: an information page "To help put tracking into context, here are a few examples:". No inputs: press Next. (Two information steps in a row: keep pressing Next while the dialog shows no inputs.)', @@ -384,9 +398,9 @@ function otherPlan(form: FormId, config: ShipConfig, answers: PlanAnswer[], p: P add({ text: 'The questionnaire is ONE long page of sections (Violence, Fear, Sexuality, Gambling, Language, Controlled Substance, Crude Humor, Digital Purchases, Miscellaneous). Answer each section\'s Yes / No as the sheet says; each Yes reveals follow-ups right below it, so answer top to bottom and re-read the page after every Yes. Run it as one in-page job (plan.inPageLoop) and poll window.__log.', answers: all(a => a.id.startsWith('q:')) }); add({ text: 'Violence follow-ups (after Yes): the humans / non-humans checkboxes, then setting, childlike style, reactions, presentation checkboxes, blood level, historical war setting, innocent characters, fierce sounds.', answers: section('violence') }); add({ text: 'Fear, Sexuality, Gambling, Language, Controlled Substance, Crude Humor follow-ups (after Yes): answer the questions shown as the sheet says (details.
.other).', answers: ['fear', 'sexuality', 'gambling', 'language', 'controlledSubstances', 'crudeHumor'].flatMap(section) }); - add({ text: 'Digital Purchases follow-ups (after "purchases of digital goods" Yes): the random items (loot box) question, then trading between players.', answers: section('digitalPurchases') }); + add({ text: `Digital Purchases follow-ups: Yes on "${IARC_DIGITAL_PURCHASES}" reveals checkboxes; tick "${IARC_DIGITAL_GOODS}" (and only the other boxes of the sheet) first: the random items (loot box) and player trading questions show only after that. Match each by its exact console label, never by keywords (its text also mentions cash rewards).`, answers: section('digitalPurchases') }); add({ text: 'Miscellaneous: user interaction (after Yes: block, report, moderation, friends only), location sharing, Nazi symbols, Korea history, terrorism, crimes.', answers: [...section('userInteraction'), ...section('miscellaneous')] }); - add({ text: 'Press Save (stores the draft; nothing goes to IARC yet), then Next: the Summary shows the rating per authority (PEGI, ESRB, USK, ClassInd, Google Play ...).', click: ['Save', 'Next'] }); + add({ text: `Press Save (stores the draft; nothing goes to IARC yet), wait for "${SAVE_CONFIRM}", then Next: the Summary shows the rating per authority (PEGI, ESRB, USK, ClassInd, Google Play ...).`, click: ['Save', 'Next'] }); add({ text: `Summary: read the ratings per authority, then press its Save yourself (a declaration save, "Save", not "Submit"; verified 2026-10-13: it stores the rating declaration, which Google gets only with the next "${SEND_FOR_REVIEW}" in Publishing overview, the owner's). Tell the owner the ratings in the final report.`, click: ['Save'] }); add({ text: 'Verify: read the Summary page as text and pipe it to `storebound console verify play-content-rating --from-text -`.' }); return { @@ -396,6 +410,7 @@ function otherPlan(form: FormId, config: ShipConfig, answers: PlanAnswer[], p: P `App content > Content ratings is /app-content/content-rating-overview (${consoleUrl('play.content-rating', planIds)}); "Start questionnaire" opens /app-content/content-rating-iarc-questionnaire.`, 'Page 1: email address, the category radio, and an IARC Terms of Use checkbox: an agreement, the owner ticks it, never the agent.', 'Verified 2026-10-13: page 1\'s Next does nothing until the IARC Terms of Use box is ticked. So the box is in the ONE owner batch before the run (the owner ticks it on page 1 first), never a stop in the middle.', + `Verified 2026-10-21: Yes on "${IARC_DIGITAL_PURCHASES}" reveals checkboxes ("${IARC_DIGITAL_GOODS}" and others); the loot-box and trading follow-ups show only once they are ticked. Answer by exact console label: a keyword helper answered it No because its text also mentions "cash rewards".`, 'The questionnaire is one long page of sections; each Yes reveals follow-ups (Violence: humans / non-humans checkboxes, then setting, childlike style, reactions, presentation checkboxes, blood level, historical war setting, innocent characters, fierce sounds; Digital Purchases: digital goods, then loot boxes, then player trading; Miscellaneous: user interaction then block / report / moderation / friends-only, location sharing, Nazi symbols, Korea history, terrorism, crimes). Follow-up wording here is storebound\'s: match by topic and the console\'s own labels.', `Save on the questionnaire stores it; Next goes to the Summary with per-authority ratings. The Summary\'s button is "Save" (not "Submit"). Saving an App content declaration is not public (verified 2026-10-13): Google gets it only with the next "${SEND_FOR_REVIEW}" in Publishing overview (the owner\'s), so the agent presses this Save.`, 'Example result (the game of that run): PEGI 7, ESRB E10+, USK 12, ClassInd 18 (paid random items alone made it 18), Google Play 7+.', @@ -429,7 +444,21 @@ function askOwnerOf(answers: PlanAnswer[], prefix = ''): string[] { .map(a => `${prefix}${a.question}: ${a.status === 'agreement' ? 'an agreement, the owner ticks it' : a.status === 'owner-check' ? `${a.text} (owner check: ${a.note ?? ''})` : `ask the owner${a.note ? ` (${a.note})` : ''}`}`); } -const ruleText = (draftSaves: string[], final: string, declarationSaves: string[] = []) => `Press only navigation (Next, Back, Get Started, Edit, Set Up, Start / Manage links), draft saves (${draftSaves.join(', ') || 'none in this form'})${declarationSaves.length ? ` and the App content declaration saves (${declarationSaves.join(', ')}: Google gets them only with the owner's ${SEND_FOR_REVIEW})` : ''}. Never press ${final} or anything that publishes, submits, creates, sends, restarts a review or accepts; stop and tell the owner.`; +/** Play: an answered page whose Save sits next to Next is saved (and confirmed) before Next; inserted into every Play plan. */ +export function saveBeforeNext(steps: PlanStep[]): PlanStep[] { + return steps.map(st => { + const c = st.click ?? []; + const i = c.indexOf('Next'); + if (i < 0) return st; + const answered = (st.answers?.length ?? 0) > 0 || c.slice(0, i).includes('Save'); + if (!answered) return st; + const click = c.slice(0, i).includes('Save') ? c : [...c.slice(0, i), 'Save', ...c.slice(i)]; + return { ...st, click, text: st.text.includes(SAVE_CONFIRM) ? st.text : `${st.text} ${SAVE_EACH_PAGE}` }; + }); +} +export const SAVE_CONFIRM = 'Your changes have been saved'; +const PLAY_SAVE_RULE = ` On a Play page with a Save next to Next: answer the page, press Save, wait for "${SAVE_CONFIRM}", only then Next.`; +const ruleText = (draftSaves: string[], final: string, declarationSaves: string[] = [], play = false) => `Press only navigation (Next, Back, Get Started, Edit, Set Up, Start / Manage links), draft saves (${draftSaves.join(', ') || 'none in this form'})${declarationSaves.length ? ` and the App content declaration saves (${declarationSaves.join(', ')}: Google gets them only with the owner's ${SEND_FOR_REVIEW})` : ''}. Never press ${final} or anything that publishes, submits, creates, sends, restarts a review or accepts; stop and tell the owner.${play ? PLAY_SAVE_RULE : ''}`; const IARC_TERMS = 'Tick the IARC Terms of Use box'; /** Where the IARC Terms box is (verified 2026-10-12 / 2026-10-13). */ @@ -485,7 +514,7 @@ function appContentPlan(cfg: ShipConfig, p: PlanIds, all = false): ConsolePlan { askOwner: cards.flatMap(({ card, plan }) => (plan ? plan.askOwner.map(l => `${card.name}: ${l}`) : [])), buttons: { neverPress, final: SEND_FOR_REVIEW, allowed, - rule: ruleText(['Save draft / Save on the IARC questionnaire page'], SEND_FOR_REVIEW, ['each card\'s Save', 'the content rating Summary\'s Save']), + rule: ruleText(['Save draft / Save on the IARC questionnaire page'], SEND_FOR_REVIEW, ['each card\'s Save', 'the content rating Summary\'s Save'], true), }, uiFacts: [ 'Verified 2026-10-12 on /console/u/0/developers//app//app-content/overview: each card has a button aria-label="Start declaration". The cards, in order:', @@ -510,8 +539,8 @@ export function consolePlan(form: PlanFormId, config: ShipConfig, p: PlanIds = { if (isPlanOnly(form)) { const part = playOnlyPart(form, cfg, p); return { - form, store: 'play', title: part.title, ownerBatch: ownerBatchOf(form, cfg, p, part.answers, part.final), start: part.start, steps: part.steps, answers: part.answers, askOwner: askOwnerOf(part.answers), - buttons: { neverPress: part.neverPress, final: part.final, allowed: part.allowed, rule: ruleText(part.allowed.filter(b => b.class === 'draft-save').map(b => b.button), part.final, part.allowed.filter(b => b.class === 'declaration-save').map(b => b.button)) }, + form, store: 'play', title: part.title, ownerBatch: ownerBatchOf(form, cfg, p, part.answers, part.final), start: part.start, steps: saveBeforeNext(part.steps), answers: part.answers, askOwner: askOwnerOf(part.answers), + buttons: { neverPress: part.neverPress, final: part.final, allowed: part.allowed, rule: ruleText(part.allowed.filter(b => b.class === 'draft-save').map(b => b.button), part.final, part.allowed.filter(b => b.class === 'declaration-save').map(b => b.button), true) }, uiFacts: part.uiFacts, driving: DRIVING, inPageLoop: IN_PAGE_LOOP, verify: part.verify, fillable: true, guidance: part.guidance, }; } @@ -527,11 +556,11 @@ export function consolePlan(form: PlanFormId, config: ShipConfig, p: PlanIds = { const teens = form === 'play-target-audience' && raw.filter(a => a.id.startsWith('age:')).every(a => a.certain && (a.value !== true || ['age:13-15', 'age:16-17', 'age:18-over'].includes(a.id))); const askOwner = askOwnerOf(answers).map(l => (teens && l.startsWith('Could your app unintentionally appeal') ? `${l} (only if the page asks it: with 13+ age groups only it did not, 2026-10-12)` : l)); return { - form, store: meta.store, title: meta.title, ownerBatch: ownerBatchOf(form, cfg, p, answers, final), ...part, answers, askOwner, + form, store: meta.store, title: meta.title, ownerBatch: ownerBatchOf(form, cfg, p, answers, final), ...part, ...(meta.store === 'play' ? { steps: saveBeforeNext(part.steps) } : {}), answers, askOwner, buttons: { neverPress, final, allowed: rules.filter(r => r.auto).map(r => ({ button: r.button, class: r.class, where: r.where })), - rule: ruleText(rules.filter(r => r.class === 'draft-save').map(r => r.button), final, rules.filter(r => r.class === 'declaration-save').map(r => r.button)), + rule: ruleText(rules.filter(r => r.class === 'draft-save').map(r => r.button), final, rules.filter(r => r.class === 'declaration-save').map(r => r.button), meta.store === 'play'), }, driving: DRIVING, inPageLoop: IN_PAGE_LOOP, fillable: meta.fillable, diff --git a/cli/lib/console-play-plans.ts b/cli/lib/console-play-plans.ts index 9490373..205c378 100644 --- a/cli/lib/console-play-plans.ts +++ b/cli/lib/console-play-plans.ts @@ -86,8 +86,25 @@ interface Part { guidance: string[]; } +/** + * The plan's in-page snippet for Play declarations: every visible radio / checkbox / option with its label, its + * checked or selected state (aria-checked, the checked property, aria-selected) and its group (the first text line of + * the nearest radiogroup / fieldset / group), plus the page text. Prints JSON for `console verify --from -`. + */ +export const INPUT_STATES_CAPTURE = `(() => { const n = s => (s || '').replace(/\\s+/g, ' ').trim(); + const label = e => n(e.getAttribute('aria-label')) || n(e.labels?.[0]?.innerText) || (() => { for (let a = e.parentElement; a && a !== document.body; a = a.parentElement) { const t = n(a.innerText); if (t) return t; } return ''; })(); + const role = e => e.getAttribute('role') || e.type; + const on = e => e.hasAttribute('aria-checked') ? e.getAttribute('aria-checked') === 'true' : e.hasAttribute('aria-selected') ? e.getAttribute('aria-selected') === 'true' : !!e.checked; + const group = e => { const g = e.closest('[role=radiogroup], fieldset, [role=group], material-radio-group'); return g ? n((g.innerText || '').split('\\n')[0]) : ''; }; + const states = [...document.querySelectorAll('[role=radio], [role=checkbox], [role=option], input[type=radio], input[type=checkbox]')].filter(e => e.getClientRects().length && !(e.matches('input') && e.closest('[role=radio], [role=checkbox]'))) + .map(e => ({ label: label(e), role: role(e), checked: on(e), group: group(e) })); + return JSON.stringify({ url: location.href, states, text: (document.querySelector('main') ?? document.body).innerText }); })()`; + const PAGE_TEXT = 'document.querySelector("main")?.innerText ?? document.body.innerText'; -const pageVerify = (form: PlanFormId, expect: string[]): ConsolePlan['verify'] => ({ command: `storebound console verify ${form} --from-text -`, source: 'page-text', capture: PAGE_TEXT, expect }); +// declarations: the input-state snippet (radios / boxes are not readable from text); the plain page text still works +const pageVerify = (form: PlanFormId, expect: string[]): ConsolePlan['verify'] => (['play-store-settings', 'play-privacy-policy', 'play-production-countries', 'play-production-release'].includes(form) + ? { command: `storebound console verify ${form} --from-text -`, source: 'page-text', capture: PAGE_TEXT, expect } + : { command: `storebound console verify ${form} --from -`, source: 'page-text', capture: INPUT_STATES_CAPTURE, expect: [...expect, 'Run verify.capture in the page (one short call; it returns JSON with every radio / checkbox and its checked state) and pipe that JSON to the command.'] }); const ans = (id: string, question: string, value: string | boolean | null, status: PlanStatus, source: string, extra: Partial = {}): PlanAnswer => ({ id, question, value: status === 'ask-owner' || status === 'agreement' ? null : value, @@ -198,7 +215,7 @@ function adsDeclaration(config: ShipConfig, p: PlanIds): Part { { text: `Open App content > Ads: ${start(config, p, 'app-content/ads-declaration', []).url}` }, { text: 'Pick the radio (JS click on the inner [role=radio]); read aria-checked back.', answers: ['ads'] }, { text: DECLARATION_SAVE }, - { text: 'Verify: read the page text and pipe it to `storebound console verify play-ads --from-text -`.' }, + { text: 'Verify: run verify.capture in the page (the input states as JSON: radios and boxes are not in page text) and pipe it to `storebound console verify play-ads --from -`.' }, ]), answers: [a ? ans('ads', 'Does your app contain ads?', a.v, 'certain', a.src, { control: 'radio', action: 'pick', label: yesNo(a.v, yes, no), where: 'Ads' }) : ans('ads', 'Does your app contain ads?', null, 'ask-owner', 'console.targetAudience.containsAds', { control: 'radio', where: 'Ads', note: 'Any ad SDK (banner, rewarded, house ads of other apps) is Yes; set console.targetAudience.containsAds.' })], @@ -216,6 +233,11 @@ export const GUEST_ENTRY_NAME = 'Guest play (no account needed)'; /** The Add instructions dialog's required box: an agreement, ticked by the owner only. */ export const PLAY_FULL_ACCESS_BOX = 'Sign in details in this declaration provide full access to all the features and content within this app, including premium or paid content'; +/** The Sign in details card's first question (2026-10-21: Yes / No radios; before that two long labelled radios, kept as altLabels). */ +export const PLAY_RESTRICTED_QUESTION = 'Is any part of your app restricted?'; +/** The dialog opener: "Add details" since 2026-10-21; "Add instructions" before (the fallback). */ +export const PLAY_ADD_DETAILS = 'Add details', PLAY_ADD_DETAILS_OLD = 'Add instructions'; + function signInDetails(config: ShipConfig, p: PlanIds): Part { const ra = config.reviewAccess; const all = 'All functionality in my app is available without any access restrictions', some = 'All or some functionality in my app is restricted'; @@ -225,8 +247,8 @@ function signInDetails(config: ShipConfig, p: PlanIds): Part { // one entry that has no credentials and says how to get in as a guest const guest = !!ra && !ra.signInRequired && !!ra.instructions?.trim(); const restricted = !!ra && (ra.signInRequired || guest); - const q = 'Is any functionality restricted (sign-in, membership, location)?'; - const out: PlanAnswer[] = [ra ? ans('access', q, restricted, 'certain', guest ? 'reviewAccess.instructions (guest steps, no sign-in)' : 'reviewAccess.signInRequired', { control: 'radio', action: 'pick', label: restricted ? some : all, where: 'Sign in details (App access)', + const q = PLAY_RESTRICTED_QUESTION; + const out: PlanAnswer[] = [ra ? ans('access', q, restricted, 'certain', guest ? 'reviewAccess.instructions (guest steps, no sign-in)' : 'reviewAccess.signInRequired', { control: 'radio', action: 'pick', label: restricted ? 'Yes' : 'No', altLabels: [restricted ? some : all], where: 'Sign in details (App access)', ...(guest ? { note: 'No sign-in, but guest steps: answered restricted so the reviewer reads them (Play rejected a guest-play game declared unrestricted as a login wall).' } : {}) }) : ans('access', q, null, 'ask-owner', 'reviewAccess.signInRequired', { control: 'radio', where: 'Sign in details', note: 'Set reviewAccess { signInRequired } (review-access skill).' })]; const long = (t: string) => t.length > PLAY_ACCESS_INFO_MAX ? { note: `${t.length} characters: Play takes at most ${PLAY_ACCESS_INFO_MAX}; shorten reviewAccess.instructions.` } : {}; @@ -251,25 +273,25 @@ function signInDetails(config: ShipConfig, p: PlanIds): Part { } // the dialog's required declaration box: an agreement, so the owner ticks it (agents never tick declarations) if (restricted) out.push(ans('fullAccess', 'Do these sign in details give full access to every feature and content, including premium or paid content?', null, 'agreement', 'Play Add instructions dialog (required)', { control: 'checkbox', label: PLAY_FULL_ACCESS_BOX, where: 'Add instructions dialog, required box' })); - const add = 'Add instructions'; + const add = PLAY_ADD_DETAILS, addOld = PLAY_ADD_DETAILS_OLD; return { title: 'Play Console: Sign in details (App access)', start: start(config, p, 'app-content/testing-credentials', appContentReach('Sign in details')), steps: steps([ { text: `Open App content > Sign in details: ${start(config, p, 'app-content/testing-credentials', []).url}` }, - { text: 'Pick whether any functionality is restricted (material radio: JS click on the inner [role=radio]).', answers: ['access'] }, + { text: `"${PLAY_RESTRICTED_QUESTION}": pick ${restricted ? 'Yes' : 'No'} (material radio: JS click on the inner [role=radio]; older pages show the long labels "${some}" / "${all}" instead). The dialog button is "${add}" (older pages: "${addOld}").`, answers: ['access'] }, guest && { text: `Guest steps (no sign-in): press "${add}", type the Name "${GUEST_ENTRY_NAME}", leave Username and Password empty, and type reviewAccess.instructions into "${info}" (at most ${PLAY_ACCESS_INFO_MAX} characters).`, click: [add], answers: ['entryName', 'credentials', 'instructions'] }, ra?.signInRequired && { text: p.demoAccount ? `Restricted: press "${add}", type the instructions, then type the Username and Password from .storebound/credentials.json (reviewDemoAccount; click each field and type: never echo them in chat or logs).` : `Restricted: press "${add}", type the instructions; the Username and Password are the owner's (no reviewDemoAccount in .storebound/credentials.json: in the owner batch).`, click: [add], answers: ['instructions', 'credentials'] }, restricted && { text: `Leave the required box "${PLAY_FULL_ACCESS_BOX}" unticked and stop: the owner ticks it (a declaration). Then press "Add" (closes the dialog; the entry is listed).`, click: ['Add'], answers: ['fullAccess'] }, { text: DECLARATION_SAVE }, - { text: 'Verify: read the page text and pipe it to `storebound console verify play-sign-in-details --from-text -`.' }, + { text: 'Verify: run verify.capture in the page (the input states as JSON: radios and boxes are not in page text) and pipe it to `storebound console verify play-sign-in-details --from -`.' }, ]), answers: out, - ...declarationButtons('Sign in details', [{ button: add, class: 'navigation', where: 'Sign in details: opens the instructions dialog' }, + ...declarationButtons('Sign in details', [{ button: add, class: 'navigation', where: 'Sign in details: opens the details dialog' }, { button: addOld, class: 'navigation', where: 'Sign in details: the same dialog opener on older pages' }, ...(restricted ? [{ button: 'Add', class: 'navigation', where: 'Add instructions dialog: lists the entry on the card (nothing is stored before Save)' }] : [])]), - uiFacts: ['Verified 2026-10-12: the Sign in details card (App access) is /app-content/testing-credentials.', 'Credentials are never in the config, the plan or chat: the agent types them from .storebound/credentials.json (reviewDemoAccount) without printing them; without that entry the owner types them.', + uiFacts: ['Verified 2026-10-12: the Sign in details card (App access) is /app-content/testing-credentials.', `Verified 2026-10-21: the first question reads "${PLAY_RESTRICTED_QUESTION}" with Yes / No radios, and the dialog opens with "${add}" (was "${addOld}"; try both).`, 'Credentials are never in the config, the plan or chat: the agent types them from .storebound/credentials.json (reviewDemoAccount) without printing them; without that entry the owner types them.', `The Add instructions dialog: Name, Username, Password, "${info}" (at most ${PLAY_ACCESS_INFO_MAX} characters) and the required box "${PLAY_FULL_ACCESS_BOX}" (the owner's).`, 'A guest-play game declared "no restrictions" was rejected as a login wall (empty name field, Continue disabled, an "I have a code" link on the first screen): with guest steps the card says restricted with one entry without credentials.', PLAY_MATERIAL_FACT], verify: pageVerify('play-sign-in-details', [guest ? `Restricted is selected; one entry "${GUEST_ENTRY_NAME}" with no username or password is listed.` : 'The selected radio matches reviewAccess.signInRequired; with a sign-in, one set of instructions is listed.']), @@ -325,7 +347,7 @@ function advertisingId(config: ShipConfig, p: PlanIds): Part { { text: 'Pick Yes or No (material radio: JS click on the inner [role=radio]).', answers: ['uses'] }, uses.v === true && { text: 'Tick exactly the purposes of the sheet (material checkboxes: JS click on the inner [role=checkbox]; read aria-checked back).', answers: out.filter(a => a.id.startsWith('purpose')).map(a => a.id) }, { text: DECLARATION_SAVE }, - { text: 'Verify: read the page text and pipe it to `storebound console verify play-advertising-id --from-text -`.' }, + { text: 'Verify: run verify.capture in the page (the input states as JSON: radios and boxes are not in page text) and pipe it to `storebound console verify play-advertising-id --from -`.' }, ]), answers: out, ...declarationButtons('Advertising ID'), @@ -344,7 +366,7 @@ function government(config: ShipConfig, p: PlanIds): Part { { text: `Open App content > Government apps: ${start(config, p, 'app-content/government-apps', []).url}` }, { text: 'Pick whether the app is developed by or on behalf of a government (material radio).', answers: ['government'] }, { text: DECLARATION_SAVE }, - { text: 'Verify: read the page text and pipe it to `storebound console verify play-government-apps --from-text -`.' }, + { text: 'Verify: run verify.capture in the page (the input states as JSON: radios and boxes are not in page text) and pipe it to `storebound console verify play-government-apps --from -`.' }, ]), answers: [v !== undefined ? ans('government', 'Is the app developed by or on behalf of a government?', v, 'certain', 'console.appContent.government', { control: 'radio', action: 'pick', label: v ? 'Yes' : 'No', where: 'Government apps' }) : ans('government', 'Is the app developed by or on behalf of a government?', null, 'ask-owner', 'console.appContent.government', { control: 'radio', where: 'Government apps', note: 'Set console.appContent.government (true only for a government body or its contractor).' })], @@ -356,31 +378,43 @@ function government(config: ShipConfig, p: PlanIds): Part { } /** Financial features / Health apps: two steps, the features on the last one (or the none box). */ +/** The health card's none option (offered since 2026-10-21). */ +export const PLAY_NO_HEALTH = 'My app does not have any health features'; +const TICK_HOW = 'material checkboxes: JS click on the inner [role=checkbox]; read aria-checked back'; +/** Multi-step Play forms with a Save next to Next: Save each page before Next (an unsaved page is lost on Next). */ +export const SAVE_EACH_PAGE = 'Press this page\'s "Save" right after answering it and wait for "Your changes have been saved" BEFORE pressing Next (Next does not keep an unsaved page).'; + function featureCard(config: ShipConfig, p: PlanIds, kind: 'finance' | 'health'): Part { const fin = kind === 'finance'; const form: PlanOnlyFormId = fin ? 'play-financial-features' : 'play-health-apps'; const name = fin ? 'Financial features' : 'Health apps'; const key = fin ? 'financialFeatures' : 'healthFeatures'; const v = config.console?.appContent?.[key]; - const none = fin ? 'My app doesn\'t provide any financial features' : 'Other'; + const none = fin ? 'My app doesn\'t provide any financial features' : PLAY_NO_HEALTH; const out: PlanAnswer[] = v === false - ? [ans('none', fin ? 'No financial features' : 'No health features', true, 'certain', `console.appContent.${key}`, { control: 'checkbox', action: 'tick', label: none, curlyQuotes: false, where: `${name}, last step`, - ...(fin ? {} : { note: 'On the verified run (2026-10-12) the no-health-features answer was the last step\'s "Other" box; when the page offers an explicit none option, tick that instead.' }) })] - : Array.isArray(v) ? v.map(l => ans(`feature:${l}`, `${name}: ${l}`, true, 'certain', `console.appContent.${key}`, { control: 'checkbox', action: 'tick', label: l, where: `${name}, last step` })) - : [ans('features', `${name}: which features does the app provide?`, null, 'ask-owner', `console.appContent.${key}`, { control: 'checkbox', where: `${name}, last step`, note: `Set console.appContent.${key}: false for none, or the console's labels to tick.` })]; + ? [ans('none', fin ? 'No financial features' : 'No health features', true, 'certain', `console.appContent.${key}`, { control: 'checkbox', action: 'tick', label: none, curlyQuotes: false, where: fin ? `${name}, step 1` : `${name}, last step`, + ...(fin ? {} : { altLabels: ['Other'], note: `Verified 2026-10-21: the page offers "${PLAY_NO_HEALTH}"; tick it. Only an older page without it took "Other" (2026-10-12).` }) })] + : Array.isArray(v) ? v.map(l => ans(`feature:${l}`, `${name}: ${l}`, true, 'certain', `console.appContent.${key}`, { control: 'checkbox', action: 'tick', label: l, where: fin ? `${name}, step 1` : `${name}, last step` })) + : [ans('features', `${name}: which features does the app provide?`, null, 'ask-owner', `console.appContent.${key}`, { control: 'checkbox', where: fin ? `${name}, step 1` : `${name}, last step`, note: `Set console.appContent.${key}: false for none, or the console's labels to tick.` })]; return { title: `Play Console: ${name} (App content)`, start: start(config, p, `app-content/${kind}`, appContentReach(name)), steps: steps([ { text: `Open App content > ${name}: ${start(config, p, `app-content/${kind}`, []).url}` }, - { text: 'Step 1: read it and press Next.', click: ['Next'] }, - { text: `Last step: tick exactly the boxes of the sheet (material checkboxes: JS click on the inner [role=checkbox]; read aria-checked back)${fin ? '; no financial features: "My app doesn\'t provide any financial features"' : '; no health features: "Other" (as on the verified run) or the none option the page offers'}. Then Next if the page shows one.`, click: ['Next'], answers: out.map(a => a.id) }, + ...(fin ? [ + { text: `Step 1: tick exactly the boxes of the sheet (${TICK_HOW}); no financial features: "My app doesn't provide any financial features". ${SAVE_EACH_PAGE} Then Next.`, click: ['Save', 'Next'], answers: out.map(a => a.id) }, + { text: 'Step 2: an information page only (no inputs): read it.' }, + ] : [ + { text: 'Step 1: read it and press Next.', click: ['Next'] }, + { text: `Last step: tick exactly the boxes of the sheet (${TICK_HOW}); no health features: "${PLAY_NO_HEALTH}" (an older page without it: "Other").`, answers: out.map(a => a.id) }, + ]), { text: DECLARATION_SAVE }, - { text: `Verify: read the page text and pipe it to \`storebound console verify ${form} --from-text -\`.` }, + { text: `Verify: run verify.capture in the page (the input states as JSON: radios and boxes are not in page text) and pipe it to \`storebound console verify ${form} --from -\`.` }, ]), answers: out, ...declarationButtons(name, [{ button: 'Next', class: 'navigation', where: `${name}: between the two steps` }]), - uiFacts: [`Verified 2026-10-12: /app-content/${kind}, two steps; the last step holds ${fin ? '"My app doesn\'t provide any financial features"' : 'the health feature boxes, "Other" among them'}; then Next and Save.`, PLAY_MATERIAL_FACT], + uiFacts: [fin ? 'Verified 2026-10-21: /app-content/finance, two steps; the checkboxes ("My app doesn\'t provide any financial features" among them) are on step 1, step 2 is an information page only; then Save.' + : `Verified 2026-10-21: /app-content/health, two steps; the last step holds the health feature boxes and "${PLAY_NO_HEALTH}" (before: only "Other" fit); then Save.`, PLAY_MATERIAL_FACT], verify: pageVerify(form, ['The ticked boxes match the sheet.']), guidance: [`Open: Policy and programs > App content > ${name}: ${start(config, p, `app-content/${kind}`, []).url}`], }; diff --git a/cli/lib/console-verify.ts b/cli/lib/console-verify.ts index 338155a..6134fb6 100644 --- a/cli/lib/console-verify.ts +++ b/cli/lib/console-verify.ts @@ -337,6 +337,23 @@ export function verifyAppContent(text: string): VerifyResult { return result('play-app-content', st ? 'inputs' : 'page-text', rows, st ? [] : ['The start buttons are aria-labels, not page text: pass the JSON of the plan\'s capture snippet.']); } +/** One labelled control read from the DOM by INPUT_STATES_CAPTURE. */ +export interface InputState { label: string; role: 'radio' | 'checkbox' | 'option' | string; checked: boolean; group?: string } + +export { INPUT_STATES_CAPTURE } from './console-play-plans'; + +/** The input states of a capture JSON ({ states, text }); null for plain page text. */ +export function parseStates(raw: string): { states: InputState[]; text: string } | null { + const s = raw.trim(); + if (!s.startsWith('{')) return null; + try { + const j = JSON.parse(s) as { states?: unknown; text?: unknown }; + if (!Array.isArray(j.states)) return null; + const states = j.states.filter((x): x is InputState => !!x && typeof x === 'object' && typeof (x as InputState).label === 'string' && typeof (x as InputState).checked === 'boolean'); + return { states, text: typeof j.text === 'string' ? j.text : '' }; + } catch { return null; } +} + /** * Store settings and the single App content declarations, from the page text after Save: text answers (the category, * the privacy policy URL) and option labels must appear; the App category's "Not selected" is a mismatch. Yes / No @@ -344,19 +361,39 @@ export function verifyAppContent(text: string): VerifyResult { */ export function verifyPlayDeclaration(form: Exclude, config: ShipConfig, text: string): VerifyResult { const part = playOnlyPart(form, config, {}); - const blob = fold(text); + const st = parseStates(text); + const blob = fold(st ? st.text : text); const rows: VerifyRow[] = []; + const radios = st?.states.filter(x => /radio/.test(x.role)) ?? []; + const radioQuestions = part.answers.filter(a => a.control === 'radio').length; for (const a of part.answers) { if (a.status === 'agreement' || a.id === 'credentials') continue; // the demo account is never read back or printed if (a.status === 'ask-owner' || a.value === null) { rows.push({ item: a.question, expected: '(owner decides)', seen: '-', status: 'ask-owner' }); continue; } + const labels = [a.label, ...(a.altLabels ?? [])].filter((l): l is string => !!l); const want = a.action === 'type' || a.action === 'choose' ? String(a.value) : a.label ?? ''; + if (st && (a.control === 'radio' || a.control === 'checkbox') && labels.length) { + // input states from the DOM: the control with this (or an older) label, checked as the sheet says + let pool = a.control === 'radio' ? radios : st.states.filter(x => /checkbox|option/.test(x.role)); + if (a.control === 'radio') { + const byQ = pool.filter(x => x.group && fold(x.group).startsWith(fold(a.question))); + if (byQ.length) pool = byQ; + else if (radioQuestions > 1) pool = []; // several radio questions: only an exact question group tells them apart + } + const hit = pool.find(x => labels.some(l => fold(x.label) === fold(l))); + const wantOn = a.action !== 'untick'; + const picked = a.control === 'radio' ? pool.filter(x => x.checked).map(x => x.label) : []; + rows.push(hit + ? { item: a.question, expected: `${labels[0]} ${wantOn ? 'checked' : 'unchecked'}`, seen: `${hit.label} ${hit.checked ? 'checked' : 'unchecked'}${!hit.checked && picked.length ? ` (checked: ${picked.join(', ')})` : ''}`, status: hit.checked === wantOn ? 'match' : 'mismatch' } + : { item: a.question, expected: `${labels[0]} ${wantOn ? 'checked' : 'unchecked'}`, seen: 'no control with that label', status: 'not-found' }); + continue; + } const plain = !want || /^(yes|no)$/i.test(want) || a.action === 'untick'; - if (plain) { rows.push({ item: a.question, expected: a.text, seen: 'not readable from page text', status: 'not-found', note: 'read the control (aria-checked) in the page' }); continue; } - const shown = blob.includes(fold(want)); + if (plain) { rows.push({ item: a.question, expected: a.text, seen: 'not readable from page text', status: 'not-found', note: 'pass the input states: run the plan\'s verify.capture snippet and `--from -`' }); continue; } + const shownAs = a.action === 'type' || a.action === 'choose' ? (blob.includes(fold(want)) ? want : null) : labels.find(l => blob.includes(fold(l))) ?? null; const unset = a.id === 'category' && /not selected|select a category/.test(blob); - rows.push({ item: a.question, expected: want, seen: shown ? want : unset ? 'Not selected' : 'not found', status: shown && !unset ? 'match' : unset ? 'mismatch' : 'not-found' }); + rows.push({ item: a.question, expected: want, seen: shownAs ?? (unset ? 'Not selected' : 'not found'), status: shownAs && !unset ? 'match' : unset ? 'mismatch' : 'not-found' }); } - return result(form, 'page-text', rows, ['Page text after Save: Yes / No radios and unticked boxes are not readable from text and are never counted as a match.']); + return result(form, st ? 'inputs' : 'page-text', rows, st ? ['Input states from the DOM (aria-checked, checked, aria-selected).'] : ['Page text after Save: Yes / No radios and unticked boxes are not readable from text and are never counted as a match; pass the input states (plan verify.capture, `--from -`).']); } /** The production track's Countries / regions tab: " countries / regions" (0 is a mismatch) and, with diff --git a/cli/lib/credentials.ts b/cli/lib/credentials.ts index 5b6d33a..27f9662 100644 --- a/cli/lib/credentials.ts +++ b/cli/lib/credentials.ts @@ -212,11 +212,65 @@ export function ascKey(root: string): AscKey { return { keyId, issuerId, pem: inline(p8, /BEGIN PRIVATE KEY/) }; } +/** The keys and nestings a review contact is read from (first hit): the documented one, then shapes seen in real files. */ +export const REVIEW_CONTACT_KEYS = ['reviewContact', 'apple.reviewContact', 'appReview.contact', 'review.contact', 'reviewDetails.contact', 'contact'] as const; + +const pickStr = (o: Record, ...ks: string[]): string => { for (const k of ks) { const v = o[k]; if (typeof v === 'string' && v.trim()) return v.trim(); } return ''; }; + +/** A contact object in any accepted field spelling (firstName / first_name / contactFirstName; a "name" is split). */ +export function contactOf(raw: unknown): ReviewContact | null { + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null; + const o = raw as Record; + const email = pickStr(o, 'email', 'contactEmail', 'emailAddress'); + if (!email || isPlaceholder(email, { example: false })) return null; + let firstName = pickStr(o, 'firstName', 'first_name', 'contactFirstName', 'givenName'), lastName = pickStr(o, 'lastName', 'last_name', 'contactLastName', 'familyName'); + const name = pickStr(o, 'name', 'fullName'); + if (!firstName && !lastName && name) { const parts = name.split(/\s+/); firstName = parts[0] ?? ''; lastName = parts.slice(1).join(' '); } + return { firstName, lastName, phone: pickStr(o, 'phone', 'contactPhone', 'phoneNumber'), email }; +} + +const atPath = (o: Store, path: string): unknown => path.split('.').reduce((x, k) => (x && typeof x === 'object' ? (x as Store)[k] : undefined), o); + +/** Where a review contact is looked up, in order: the project's .storebound/credentials.json, the same file in each + * parent folder up to the repository root (a config in a subfolder), then the project's credential profile file. */ +function contactFiles(root: string): string[] { + const out: string[] = []; + let d = resolve(root); + for (let i = 0; i < 6; i++) { + out.push(join(d, '.storebound', 'credentials.json')); + if (existsSync(join(d, '.git'))) break; + const up = resolve(d, '..'); + if (up === d || up === homedir()) break; + d = up; + } + try { const p = activeProfile(root); if (p && PROFILE_RE.test(p.name)) out.push(join(profileDir(), `${p.name}.json`)); } catch { /* unreadable project file: listed below */ } + return out; +} + +/** App Review contact (personal data, never in the config), the file and key it came from, and every place checked. */ +export function findReviewContact(root: string): { contact: ReviewContact | null; from: string | null; checked: string[] } { + const checked: string[] = []; + for (const f of contactFiles(root)) { + if (!existsSync(f)) { checked.push(`${f} (missing)`); continue; } + let st: Store; + try { st = JSON.parse(readFileSync(f, 'utf8')) as Store; } catch (e) { checked.push(`${f} (unreadable: ${(e as Error).message})`); continue; } + for (const k of REVIEW_CONTACT_KEYS) { + const c = contactOf(atPath(st, k)); + if (c) return { contact: c, from: `${f} ${k}`, checked }; + } + checked.push(`${f} (keys ${REVIEW_CONTACT_KEYS.join(', ')}: none with an email)`); + } + return { contact: null, from: null, checked }; +} + +/** The error when no review contact is found: every file and key that was checked, and the fix. */ +export function noContactMessage(root: string, checked: string[] = findReviewContact(root).checked): string { + return `no review contact. Checked: ${checked.join('; ') || '(nothing)'}. Add "reviewContact": { "firstName", "lastName", "phone", "email" } to ${join(resolve(root), '.storebound', 'credentials.json')}, or pass --contact-from `; +} + /** App Review contact from .storebound/credentials.json (personal data, so never in the config). */ export function reviewContact(root: string): ReviewContact | null { - const c = fileStore(root).reviewContact as Partial | undefined; - if (!c?.email || isPlaceholder(c.email, { example: false })) return null; - return { firstName: c.firstName ?? '', lastName: c.lastName ?? '', phone: c.phone ?? '', email: c.email }; + return findReviewContact(root).contact; } export interface DemoAccount { username: string; password: string } diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index 962ac6e..d6d5726 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -431,7 +431,7 @@ export const TOOLS: ToolDef[] = [ all: { type: 'boolean', description: 'play-app-content only: every card\'s steps inline in fix order, ending with the one owner list (tick the IARC Terms before, Send changes for review after)' } }, required: ['form'], args: i => [String(i.form), ...(i.all === true ? ['--all'] : []), '--json'] }, { name: 'console_verify', title: 'Verify a console form', command: ['console', 'verify'], write: false, network: true, - description: 'Read-only check of a filled console form against the config. Pass the page text you read (App Privacy: the App Privacy page\'s innerText, whose Data Types section shows per type "Used for …", linked and tracking; Play Create app: the JSON of the plan\'s capture snippet; Play content rating / target audience: the summary page text; play-app-content: the JSON of the plan\'s capture snippet; Play store settings and the other App content cards: the page text after Save). apple-app-record and apple-age-rating without text read the App Store Connect API. Returns a per-item match / mismatch table; exit code 1 on a mismatch.', + description: 'Read-only check of a filled console form against the config. Pass the page text you read (App Privacy: the App Privacy page\'s innerText, whose Data Types section shows per type "Used for …", linked and tracking; Play Create app: the JSON of the plan\'s capture snippet; Play content rating / target audience: the summary page text; play-app-content: the JSON of the plan\'s capture snippet; Play store settings and the privacy policy: the page text after Save; the other App content cards (ads, sign-in details, advertising ID, government, financial, health): the JSON of the plan\'s verify.capture snippet, which reads radios and boxes from the DOM: aria-checked, checked, aria-selected). apple-app-record and apple-age-rating without text read the App Store Connect API. Returns a per-item match / mismatch table; exit code 1 on a mismatch.', props: { form: { type: 'string', enum: CONSOLE_PLAN_FORMS }, text: { type: 'string', description: 'The page text (or the capture JSON) of the finished form' } }, required: ['form'], args: i => [String(i.form), ...(typeof i.text === 'string' && i.text ? [`--text=${i.text}`] : []), '--json'] }, diff --git a/cli/privacy-manifest.ts b/cli/privacy-manifest.ts index 5977fdb..0ec2bc0 100644 --- a/cli/privacy-manifest.ts +++ b/cli/privacy-manifest.ts @@ -65,8 +65,7 @@ async function configAppPrivacy(): Promise<{ trackingDomains: string[]; types: P } export async function run(args: Args): Promise { - const ios = args.get('ios'); - if (!ios) throw new Error('usage: privacy-manifest --ios [--sdk-dirs a,b] [--json]'); + const ios = args.required('ios', 'path', 'the iOS project folder, e.g. ios/App'); const root = resolve(ios); if (!existsSync(root)) throw new Error(`${root} does not exist`); const sdks: SdkInfo[] = []; diff --git a/skills/console-autofill/SKILL.md b/skills/console-autofill/SKILL.md index 0757ee0..1048a99 100644 --- a/skills/console-autofill/SKILL.md +++ b/skills/console-autofill/SKILL.md @@ -117,8 +117,9 @@ the UI shows. This is the primary mode. the Category dropdown's `[role=option]` with exactly the category name (`play.category`) > Save. - **Play App content** (2026-10-12): `/app-content/overview`; each card has a button aria-label="Start declaration". Pages: privacy-policy, ads-declaration, testing-credentials (Sign in details), ad-id-declaration, - government-apps, finance (2 steps; the last has "My app doesn't provide any financial features"; Next, Save), - health (2 steps; the last step's "Other" box was the no-features answer on that run; Next, Save), + government-apps, finance (2 steps, 2026-10-21: the checkboxes, "My app doesn't provide any financial features" + among them, are on step 1; step 2 is an information page only), health (2 steps; 2026-10-21: the last step offers + "My app does not have any health features", tick that; only an older page without it took "Other"), target-audience-content (age checkboxes; with 13+ only it went straight to the Summary, no appeal question; Save), content-rating-overview > "Start questionnaire" > content-rating-iarc-questionnaire. Each card's Save is yours (2026-10-13: nothing goes to Google before the owner's "Send changes for review"). @@ -131,6 +132,21 @@ the UI shows. This is the primary mode. terrorism, crimes). The answers come from `console.contentRating.answers` and `.details`, `products[].randomRewards` and `social`. Save, then Next to the Summary with per-authority ratings; its button is **Save**, not Submit: yours (a declaration save). Example: PEGI 7, ESRB E10+, USK 12, ClassInd 18 (paid random items), Google Play 7+. +- **Save after every page** (Play, 2026-10-21): on a multi-step Play form with a Save next to Next (the IARC + questionnaire, finance, target audience), answer the page, press **Save**, wait for "Your changes have been saved", + and only then press Next. The plan steps and the rule line say so on every such step. +- **IARC Digital purchases** (2026-10-21): Yes on "Digital purchases" reveals checkboxes ("Purchases of digital goods" + and others); tick them first, the loot-box and trading follow-ups show only after that. Answer every IARC question + by its exact console label: a keyword helper answered this one No because its text also mentions "cash rewards". The + in-page helper refuses patterns, radios without their exact question (`within`) and blanket group answers. +- **Sign in details** (2026-10-21): the first question reads "Is any part of your app restricted?" with Yes / No; the + dialog button is "Add details" (older pages: the long radio labels and "Add instructions"; the plan keeps both). +- **App Privacy "Additional Setup Required"** (2026-10-21): after saving the data types this message appears; its OK + sometimes opens the first type's setup dialog by itself. That dialog IS the first type's setup: carry on from step 1 + there, do not press its Set Up again. +- **Verify reads input states** (2026-10-21): Yes / No radios and unticked boxes are not in page text. Run the plan's + `verify.capture` snippet (it returns every radio / checkbox with aria-checked, checked or aria-selected as JSON) and + pipe it to `storebound console verify --from -`; the page-text path stays for text answers. - **App Privacy Publish** (2026-10-12): a `` "Publish Your App Privacy Responses?" with Cancel / Publish (the owner's); afterwards the page shows "Published a few seconds ago by …", which `console verify` reads. - **Play first production release** (2026-10-12): countries are console-only (`edits.countryAvailability` is diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 3bd982c..8152304 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1049,3 +1049,30 @@ that fails without the fix (see CONTRIBUTING.md). smaller than asked, point `STOREBOUND_CHROME` at a current Chromium or record with `--source folder`. - **Guard:** `recordSize` / `captureShortfall` in `cli/shots/devices.ts` (first frame size checked per clip, plus a frames-per-second warning under 20); `tests/video.test.ts`. + +## 86. Console plans behind the live pages (Play App content, IARC, App Privacy; 2026-10-21) +- **Symptom:** on a real run the health card offered "My app does not have any health features" while the sheet said + "Other" and verify said "not found"; Sign in details asked "Is any part of your app restricted? Yes / No" with an + "Add details" button; finance had its boxes on step 1 (step 2 is information only); App Privacy's "Additional Setup + Required" OK opened the first type's setup by itself; verify could not read Yes / No radios from text; a page + answered and then left with Next lost its answers; a keyword helper answered IARC "Digital purchases" No because its + text mentions "cash rewards", so the digital goods boxes and the loot-box / trading follow-ups never showed. +- **Do:** follow the plan's labels (new label first, `altLabels` as the fallback). On every Play page with a Save next + to Next: Save, wait for "Your changes have been saved", then Next. In App Privacy, a setup dialog that opened by + itself after the OK is the first type's: carry on there. Verify with the plan's `verify.capture` JSON + (`console verify --from -`). Answer IARC by exact console labels only, never keyword sweeps over unanswered + groups; tick "Purchases of digital goods" after Yes on "Digital purchases". +- **Guard:** `cli/lib/console-play-plans.ts` (labels, step order, `INPUT_STATES_CAPTURE`), `saveBeforeNext` and the + exact-label `IN_PAGE_LOOP` in `cli/lib/console-plan.ts`, `parseStates` in `cli/lib/console-verify.ts`; + `tests/console-guardrails-1021.test.ts`. + +## 87. "no review contact" with a reviewContact in the credentials file; whole help for a missing --version +- **Symptom:** `apple review-details` said "no review contact" while `.storebound/credentials.json` had + `reviewContact { firstName, lastName, phone, email }` (only the project folder's own file was read, under one key); + `apple listing` without `--version` (or with `--version` and no value) printed usage text or went on with "true". +- **Do:** update storebound. The contact is read from the project's file, the same file in parent folders up to the + repository root and the credential profile, under `reviewContact` (also `apple.reviewContact`, `appReview.contact`, + ASC field names); when none is found the error lists every file and key checked. Missing required values are one + line: "--version is required (storebound apple status shows the editable version)". +- **Guard:** `findReviewContact` / `noContactMessage` in `cli/lib/credentials.ts`, `Args.required` in + `cli/lib/args.ts` (listing, privacy-manifest, adhoc export, edit, resubmit); `tests/console-guardrails-1021.test.ts`. diff --git a/tests/console-guardrails-1021.test.ts b/tests/console-guardrails-1021.test.ts new file mode 100644 index 0000000..1035f82 --- /dev/null +++ b/tests/console-guardrails-1021.test.ts @@ -0,0 +1,191 @@ +// Guardrails from a real run of the console plans (Play Console and App Store Connect, 2026-10-21): new labels with +// the old ones as fallbacks, step order, Save before Next, IARC by exact labels, verify from input states, the review +// contact lookup and one-line errors for missing values. Pure; every id is a placeholder. +import { describe, expect, test } from 'bun:test'; +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { ShipConfig } from '../cli/lib/config'; +import { PLAN_FORM_IDS } from '../cli/lib/console-answers'; +import { APPLE_ADDITIONAL_SETUP, consolePlan, IN_PAGE_LOOP, SAVE_CONFIRM, saveBeforeNext } from '../cli/lib/console-plan'; +import { INPUT_STATES_CAPTURE, PLAY_ADD_DETAILS, PLAY_ADD_DETAILS_OLD, PLAY_NO_HEALTH, PLAY_RESTRICTED_QUESTION } from '../cli/lib/console-play-plans'; +import { parseStates, verifyPlayDeclaration, verifyText } from '../cli/lib/console-verify'; +import { contactOf, findReviewContact, noContactMessage } from '../cli/lib/credentials'; +import { parseArgs } from '../cli/lib/args'; + +const base = { + app: { name: 'Example Game', profile: 'game', privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', website: 'https://example.com', contactEmail: 'support@example.com' }, + languages: [{ id: 'en', play: 'en-US', apple: 'en-US' }], + play: { packageName: 'com.example.game', developerId: '4444', appId: '9876' }, + apple: { bundleId: 'com.example.game' }, + products: [{ id: 'com.example.game.coins', type: 'consumable', usd: 0.99, listings: { en: { title: 'Coins', description: 'Coins' } }, randomRewards: false }], + console: { appContent: { financialFeatures: false, healthFeatures: false, government: false, advertisingId: false }, contentRating: { category: 'game' } }, + reviewAccess: { signInRequired: false }, +} as unknown as ShipConfig; +const json = (states: { label: string; role: string; checked: boolean; group?: string }[], text = '') => JSON.stringify({ states, text }); +const REPO_MARK = ['', 'g', 'i', 't'].join('').replace(/^/, '.'); + +describe('1. health: the new none label, accepted by verify', () => { + test('the sheet ticks the new label, "Other" is the fallback', () => { + expect(consolePlan('play-health-apps', base).answers[0]).toMatchObject({ label: PLAY_NO_HEALTH, altLabels: ['Other'], action: 'tick' }); + }); + test('verify: page text and input states with the new label match', () => { + expect(verifyText('play-health-apps', base, `Health apps\n${PLAY_NO_HEALTH}\nSave`).ok).toBe(true); + expect(verifyText('play-health-apps', base, json([{ label: PLAY_NO_HEALTH, role: 'checkbox', checked: true }, { label: 'Other', role: 'checkbox', checked: false }])).ok).toBe(true); + expect(verifyText('play-health-apps', base, json([{ label: 'Other', role: 'checkbox', checked: true }])).ok).toBe(true); // an older page + expect(verifyText('play-health-apps', base, json([{ label: PLAY_NO_HEALTH, role: 'checkbox', checked: false }])).mismatches).toBe(1); + }); +}); + +describe('2. sign in details: Yes / No and "Add details", old labels kept', () => { + test('labels', () => { + const p = consolePlan('play-sign-in-details', base); + expect(p.answers[0]).toMatchObject({ question: PLAY_RESTRICTED_QUESTION, label: 'No', altLabels: ['All functionality in my app is available without any access restrictions'] }); + const g = consolePlan('play-sign-in-details', { ...base, reviewAccess: { signInRequired: false, instructions: 'Tap Play as guest.' } } as ShipConfig); + expect(g.steps.some(s => s.click?.includes(PLAY_ADD_DETAILS))).toBe(true); + expect(g.steps.some(s => s.text.includes(PLAY_ADD_DETAILS_OLD))).toBe(true); + expect(g.buttons.allowed.map(b => b.button)).toEqual(expect.arrayContaining([PLAY_ADD_DETAILS, PLAY_ADD_DETAILS_OLD])); + expect(g.uiFacts.join(' ')).toContain(PLAY_RESTRICTED_QUESTION); + }); + test('verify: the No radio of the question from input states', () => { + const r = verifyText('play-sign-in-details', base, json([{ label: 'Yes', role: 'radio', checked: false, group: PLAY_RESTRICTED_QUESTION }, { label: 'No', role: 'radio', checked: true, group: PLAY_RESTRICTED_QUESTION }])); + expect(r).toMatchObject({ source: 'inputs', ok: true }); + }); +}); + +test('3. finance: the boxes on step 1, step 2 information only', () => { + const p = consolePlan('play-financial-features', base); + const tick = p.steps.findIndex(s => s.answers?.includes('none')); + expect(p.steps[tick]!.text).toMatch(/^Step 1: tick/); + expect(p.steps[tick + 1]!.text).toMatch(/^Step 2: an information page only/); + expect(p.answers[0]!.where).toContain('step 1'); +}); + +test('4. App Privacy: the Additional Setup Required OK is in the steps and the UI facts', () => { + const p = consolePlan('apple-app-privacy', { ...base, dataSafety: { collectsData: true, encryptedInTransit: true, data: { PSL_DEVICE_ID: { collect: ['analytics'], shared: false } } } } as ShipConfig); + expect(p.steps.some(s => s.text === APPLE_ADDITIONAL_SETUP && s.click?.includes('OK'))).toBe(true); + expect(p.uiFacts.some(f => f.includes('Additional Setup Required') && f.includes('first type'))).toBe(true); + expect(p.buttons.allowed.map(b => b.button)).toContain('OK'); +}); + +describe('5. verify from input states', () => { + test('the plan gives the snippet and --from', () => { + for (const f of ['play-advertising-id', 'play-government-apps', 'play-ads', 'play-health-apps'] as const) { + const v = consolePlan(f, base).verify; + expect(v.capture).toBe(INPUT_STATES_CAPTURE); + expect(v.command).toBe(`storebound console verify ${f} --from -`); + } + for (const s of ['aria-checked', 'aria-selected', '.checked']) expect(INPUT_STATES_CAPTURE).toContain(s); + expect(() => new Function(`return ${INPUT_STATES_CAPTURE}`)).not.toThrow(); + }); + test('advertising-id and government: radios read from the JSON, not "not readable"', () => { + const no = json([{ label: 'Yes', role: 'radio', checked: false }, { label: 'No', role: 'radio', checked: true }]); + expect(verifyText('play-advertising-id', base, no)).toMatchObject({ ok: true, source: 'inputs' }); + expect(verifyText('play-government-apps', base, no)).toMatchObject({ ok: true }); + expect(verifyText('play-government-apps', base, json([{ label: 'Yes', role: 'radio', checked: true }, { label: 'No', role: 'radio', checked: false }])).mismatches).toBe(1); + expect(verifyPlayDeclaration('play-government-apps', base, 'Government apps\nYes\nNo').rows[0]!.seen).toBe('not readable from page text'); + expect(parseStates('plain text')).toBeNull(); + }); +}); + +describe('8. Save after every page before Next', () => { + test('every Play plan step that answers a page and presses Next saves and confirms first', () => { + let checked = 0; + for (const form of PLAN_FORM_IDS) { + const p = consolePlan(form, base); + if (p.store !== 'play') continue; + for (const s of p.steps) { + const i = s.click?.indexOf('Next') ?? -1; + if (i < 0 || !s.answers?.length) continue; + checked++; + expect(s.click!.slice(0, i)).toContain('Save'); + expect(s.text).toContain(SAVE_CONFIRM); + } + expect(p.buttons.rule).toContain(SAVE_CONFIRM); + } + expect(checked).toBeGreaterThan(2); + }); + test('saveBeforeNext leaves information pages alone', () => { + expect(saveBeforeNext([{ n: 1, text: 'Read it.', click: ['Next'] }])[0]!.click).toEqual(['Next']); + expect(saveBeforeNext([{ n: 1, text: 'Pick.', click: ['Next'], answers: ['a'] }])[0]!.click).toEqual(['Save', 'Next']); + }); +}); + +describe('9. IARC Digital purchases by exact labels', () => { + test('Yes reveals "Purchases of digital goods", ticked before the follow-ups', () => { + const p = consolePlan('play-content-rating', base); + expect(p.answers.find(a => a.id === 'q:digitalPurchases')?.value).toBe(true); + expect(p.answers.find(a => a.id === 'd:digitalPurchases:digitalGoods')).toMatchObject({ label: 'Purchases of digital goods', action: 'tick', status: 'certain' }); + const ids = p.answers.map(a => a.id); + expect(ids.indexOf('d:digitalPurchases:digitalGoods')).toBeLessThan(ids.indexOf('d:digitalPurchases:playerTrading')); + expect(p.steps.find(s => s.answers?.includes('d:digitalPurchases:digitalGoods'))!.text).toContain('exact console label'); + }); + test('the in-page helper matches exact labels and refuses blanket answers', () => { + expect(IN_PAGE_LOOP).toContain('l === want'); + expect(IN_PAGE_LOOP).toContain('refused: a radio needs within'); + expect(IN_PAGE_LOOP).toContain('refused: no blanket answers'); + expect(IN_PAGE_LOOP).toContain('refused: keywords or a pattern'); + expect(() => new Function(IN_PAGE_LOOP)).not.toThrow(); + }); + test('the helper in a tiny DOM: keyword and blanket answers for the digital purchases block are refused', async () => { + const g = globalThis as Record; + const radio = (label: string) => ({ getAttribute: (n: string) => (n === 'aria-label' ? label : n === 'aria-checked' ? 'false' : null), hasAttribute: (n: string) => n === 'aria-checked', getClientRects: () => [1], matches: () => true, closest: () => null, click() {} }); + const els = [radio('Yes'), radio('No')]; + const block = { innerText: 'Digital purchases\nDoes the app offer digital goods, or cash rewards?', querySelector: () => els[0], querySelectorAll: () => els, contains: () => false }; + g.document = { body: {}, querySelectorAll: (q: string) => (q.includes('section') ? [block] : els) }; + g.window = g; + try { + new Function(IN_PAGE_LOOP)(); + const sb = g.__sb as { run(s: unknown[]): string }; + sb.run([{ role: 'radio', label: 'No|no', within: 'cash' }, { role: 'radio', label: 'No' }, { role: 'radio', label: 'No', within: 'cash rewards' }, { role: 'radio', group: true, label: 'No', within: 'Digital purchases' }]); + await (g.__run as Promise); + const log = (g.__log as string[]).join('\n'); + expect(log).toContain('refused: keywords or a pattern'); + expect(log).toContain('refused: a radio needs within'); + expect(log).toContain('no block whose question is exactly'); + expect(log).toContain('refused: no blanket answers'); + } finally { for (const k of ['document', '__sb', '__log', '__done', '__run', 'window']) delete g[k]; } + }); +}); + +describe('6. the review contact', () => { + const contact = { firstName: 'Ada', lastName: 'Example', phone: '+1 555 0100', email: 'review@example.org' }; + const repo = () => { const top = mkdtempSync(join(tmpdir(), 'sb-rc-')); mkdirSync(join(top, REPO_MARK)); mkdirSync(join(top, '.storebound')); return top; }; + test('the documented shape in the project, a parent folder and other key shapes', () => { + const top = repo(); + mkdirSync(join(top, 'app')); + writeFileSync(join(top, '.storebound', 'credentials.json'), JSON.stringify({ reviewContact: contact })); + const r = findReviewContact(join(top, 'app')); + expect(r.contact).toEqual(contact); + expect(r.checked[0]).toContain(join(top, 'app', '.storebound', 'credentials.json')); + expect(contactOf({ contactFirstName: 'Ada', contactLastName: 'Example', contactPhone: '1', contactEmail: 'review@example.org' })?.firstName).toBe('Ada'); + expect(contactOf({ name: 'Ada Example', email: 'review@example.org' })).toMatchObject({ firstName: 'Ada', lastName: 'Example' }); + writeFileSync(join(top, '.storebound', 'credentials.json'), JSON.stringify({ apple: { reviewContact: contact } })); + expect(findReviewContact(top).contact?.email).toBe(contact.email); + }); + test('none: the error names every file and key checked', () => { + const top = repo(); + writeFileSync(join(top, '.storebound', 'credentials.json'), JSON.stringify({ reviewContact: { firstName: 'Ada' } })); + const m = noContactMessage(top); + expect(m).toContain(join(top, '.storebound', 'credentials.json')); + expect(m).toContain('reviewContact, apple.reviewContact'); + expect(m).toContain('--contact-from'); + }); +}); + +describe('7. one-line errors for missing required values', () => { + test('missing and value-less flags', () => { + const fix = 'storebound apple status shows the editable version'; + expect(() => parseArgs([]).required('version', 'x.y.z', fix)).toThrow(`--version is required (${fix})`); + expect(() => parseArgs(['--version']).required('version', 'x.y.z', fix)).toThrow('is required'); + expect(() => parseArgs(['--version', '--dry']).required('version', 'x.y.z')).toThrow('is required'); + expect(parseArgs(['--version', '1.2.0']).required('version', 'x.y.z')).toBe('1.2.0'); + }); + test('the CLI prints one line for apple listing without --version', () => { + const dir = mkdtempSync(join(tmpdir(), 'sb-one-')); + writeFileSync(join(dir, 'storebound.config.ts'), `export default ${JSON.stringify(base)};\n`); + const p = Bun.spawnSync(['bun', join(import.meta.dir, '..', 'cli', 'index.ts'), 'apple', 'listing'], { cwd: dir, env: { ...process.env, STOREBOUND_NO_NETWORK: '1' } }); + expect(p.stderr.toString().trim()).toBe('error: --version is required (storebound apple status shows the editable version)'); + expect(p.exitCode).toBe(1); + }); +}); diff --git a/tests/console-play-plans.test.ts b/tests/console-play-plans.test.ts index aab8f04..87acf89 100644 --- a/tests/console-play-plans.test.ts +++ b/tests/console-play-plans.test.ts @@ -58,7 +58,7 @@ describe('agent-only Play plans: shape, URLs, never-press lists, the owner batch p.ownerBatch.forEach((o, i) => expect(o.n).toBe(i + 1)); expect(planText(p).indexOf('Owner batch')).toBeLessThan(planText(p).indexOf('Steps:')); expect(p.uiFacts.join('\n')).toContain(PLAY_MATERIAL_FACT); - expect(p.verify.command).toBe(`storebound console verify ${form} --from-text -`); + expect(p.verify.command).toBe(`storebound console verify ${form} ${p.verify.capture.includes("aria-selected") ? "--from" : "--from-text"} -`); expect(p.inPageLoop).toBe(IN_PAGE_LOOP); expect(planText(p)).toContain('window.__sb.run'); expect(JSON.parse(JSON.stringify(p))).toEqual(p); @@ -179,7 +179,7 @@ describe('agent-only Play plans: shape, URLs, never-press lists, the owner batch test('Sign in details: the demo account never printed, typed by the owner', () => { const p = consolePlan('play-sign-in-details', { ...base, reviewAccess: { signInRequired: true, instructions: 'Sign in with the demo account.' } } as ShipConfig, { demoAccount: true }); - expect(p.answers.find(a => a.id === 'access')).toMatchObject({ value: true, status: 'certain', label: 'All or some functionality in my app is restricted' }); + expect(p.answers.find(a => a.id === 'access')).toMatchObject({ value: true, status: 'certain', label: 'Yes', altLabels: ['All or some functionality in my app is restricted'] }); expect(p.answers.find(a => a.id === 'instructions')).toMatchObject({ status: 'certain', action: 'type' }); const cred = p.answers.find(a => a.id === 'credentials')!; // in .storebound/credentials.json: the agent types it, never printed (no value in the plan) @@ -200,7 +200,7 @@ describe('agent-only Play plans: shape, URLs, never-press lists, the owner batch expect(ad.answers.filter(a => a.action === 'tick').map(a => a.label).sort()).toEqual(['Advertising or marketing', 'Analytics']); const none = { ...base, console: { ...base.console, appContent: { financialFeatures: false, healthFeatures: false, government: false } } } as ShipConfig; expect(consolePlan('play-financial-features', none).answers).toMatchObject([{ id: 'none', action: 'tick', label: 'My app doesn\'t provide any financial features', status: 'certain' }]); - expect(consolePlan('play-health-apps', none).answers).toMatchObject([{ id: 'none', action: 'tick', label: 'Other', status: 'certain' }]); + expect(consolePlan('play-health-apps', none).answers).toMatchObject([{ id: 'none', action: 'tick', label: 'My app does not have any health features', altLabels: ['Other'], status: 'certain' }]); expect(consolePlan('play-government-apps', none).answers).toMatchObject([{ id: 'government', value: false, label: 'No', status: 'certain' }]); expect(consolePlan('play-financial-features', base).answers).toMatchObject([{ id: 'features', status: 'ask-owner' }]); }); diff --git a/tests/desktop-d3.test.ts b/tests/desktop-d3.test.ts index cc7cfe2..17a0a5e 100644 --- a/tests/desktop-d3.test.ts +++ b/tests/desktop-d3.test.ts @@ -210,7 +210,7 @@ describe('full CLI coverage: new methods', () => { describe('the owner flag', () => { const saved = { ...process.env }; afterEach(() => { for (const k of ['STOREBOUND_SERVE', 'STOREBOUND_OWNER_CONFIRMED']) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; } }); - const ctx = { loaded: {} as never, args: { has: (n: string) => n === 'yes', get: () => undefined, str: (_: string, d: string) => d, num: (_: string, d: number) => d, list: () => [], many: () => [], _: [] } }; + const ctx = { loaded: {} as never, args: { has: (n: string) => n === 'yes', get: () => undefined, str: (_: string, d: string) => d, num: (_: string, d: number) => d, list: () => [], many: () => [], required: (n: string) => { throw new Error(`--${n} is required`); }, _: [] } }; test('under serve: no by default, even with --yes; yes only with the owner flag', async () => { process.env.STOREBOUND_SERVE = '1'; delete process.env.STOREBOUND_OWNER_CONFIRMED; From ce1b1edcb8f0b1794bd35eaf849ba6523457ca89 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 04:55:50 +0700 Subject: [PATCH 057/344] serve: desktop methods for play build / upload / share / app-id, apple build / upload / signing ensure / adhoc register + export, shots fonts / jpeg, install (dry run first; the host token answers their question) --- cli/serve.ts | 48 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/cli/serve.ts b/cli/serve.ts index b0df36e..e08378c 100644 --- a/cli/serve.ts +++ b/cli/serve.ts @@ -63,7 +63,7 @@ export const CONSOLE_FORMS = ['apple-app-record', 'apple-age-rating', 'apple-app /** Write tools that print a structured result with --json in the dry run and the real run (console.fill: the answers). */ export const JSON_WRITES = new Set(['console_fill', 'owner_apple_submit', 'owner_apple_resubmit', 'project_edit', 'listing_set', 'art_replace']); /** Write tools whose command may ask its own question (confirm()): a verified host token answers it, as for owner actions. */ -const TOKEN_ANSWERS = new Set(['console_fill']); +const TOKEN_ANSWERS = new Set(['console_fill', 'play_upload', 'play_share', 'apple_upload', 'apple_signing_ensure', 'apple_adhoc_register']); /** The one desktop exception to FORBIDDEN_ARGS: `scan --write-only` (scan.write, the Fix button of a privacy-labels * finding) writes the detected declarations into the config, only after the native dialog showed its diff and the @@ -143,6 +143,52 @@ export const DESKTOP_ONLY: ToolDef[] = [ description: 'Read-only: the current price of every product on both stores per region (Apple manual prices, with with_automatic also the equalized ones). Writes nothing.', props: { store: { type: 'string', enum: ['apple', 'play'] }, with_automatic: { type: 'boolean', default: false } }, args: i => [...opt('store', i.store), ...(i.with_automatic === true ? ['--with-automatic'] : [])] }, + // Build, sign and test-distribution commands (docs/desktop-coverage.md: the More tools tab). Their own question is + // answered by the host token (TOKEN_ANSWERS) after the native dialog showed the dry run. + { name: 'play_build', title: 'Build the Android app bundle', command: ['play', 'build'], write: true, network: false, + description: 'gradle bundleRelease (Flutter: flutter build appbundle) with the next free versionCode and the upload key from env / .storebound. The dry run shows the plan; nothing goes to a store.', + props: { flavor: { type: 'string', pattern: '^[A-Za-z0-9_]{1,60}$', description: 'Gradle product flavor' }, module: { type: 'string', pattern: '^[A-Za-z0-9_:-]{1,60}$', description: 'Gradle module (default app)' }, + version_name: { type: 'string', pattern: '^[0-9A-Za-z.+-]{1,40}$', description: 'versionName (default: from the project)' } }, + args: i => [...opt('flavor', i.flavor), ...opt('module', i.module), ...opt('version-name', i.version_name)] }, + { name: 'play_upload', title: 'Upload an AAB to a testing track', command: ['play', 'upload'], write: true, network: true, + description: 'Uploads the newest AAB of the build output to a Google Play testing track (internal, closed or open testing), versionCode checked first. Testers of that track get it; production stays an owner action.', + props: { track: { type: 'string', enum: ['internal', 'alpha', 'beta'], default: 'internal' }, status: { type: 'string', enum: ['completed', 'draft'], default: 'completed' }, + name: { type: 'string', pattern: '^[^\\x00-\\x1f]{1,50}$', description: 'Release name (default: the version)' } }, + args: i => [...opt('track', i.track), ...opt('status', i.status), ...opt('name', i.name)] }, + { name: 'play_share', title: 'Internal app sharing link', command: ['play', 'share'], write: true, network: true, + description: 'Uploads one AAB or APK to Google Play internal app sharing and prints the share link (anyone allowed to use the link can install it for 60 days).', + props: { aab: { type: 'string', pattern: '^(?![/-])(?!.*\\.\\.)[A-Za-z0-9 _./-]{1,500}\\.aab$', description: 'AAB path relative to the app folder' }, + apk: { type: 'string', pattern: '^(?![/-])(?!.*\\.\\.)[A-Za-z0-9 _./-]{1,500}\\.apk$', description: 'APK path relative to the app folder' } }, + args: i => [...opt('aab', i.aab), ...opt('apk', i.apk)] }, + { name: 'play_app_id', title: 'Play Console app id', command: ['play', 'app-id'], write: false, network: true, + description: 'Read-only: the Play Console app id (play.appId) for the package name, from the known ids, else the agent steps to find it.' }, + { name: 'apple_build', title: 'Build the iOS app', command: ['apple', 'build'], write: true, network: true, + description: 'xcodebuild archive + exportArchive with a generated ExportOptions.plist, the next build number and API key signing (Capacitor, React Native, Flutter, Unity). The dry run shows the plan; nothing goes to a store.', + props: { scheme: { type: 'string', pattern: '^[^\\x00-\\x1f]{1,100}$', description: 'Xcode scheme (default: from the config or the project)' }, configuration: { type: 'string', pattern: '^[A-Za-z0-9_ -]{1,40}$', description: 'Build configuration (default Release)' } }, + args: i => [...opt('scheme', i.scheme), ...opt('configuration', i.configuration)] }, + { name: 'apple_upload', title: 'Upload an IPA', command: ['apple', 'upload'], write: true, network: true, + description: 'Uploads the newest exported IPA to App Store Connect (API build upload, or altool), build number checked first, and waits for processing. It shows up in TestFlight; submitting stays an owner action.', + props: { via: { type: 'string', enum: ['api', 'altool'], default: 'api' }, no_wait: { type: 'boolean', default: false, description: 'Do not wait for processing' } }, + args: i => [...opt('via', i.via), ...(i.no_wait === true ? ['--no-wait'] : [])] }, + { name: 'apple_signing_ensure', title: 'Set up signing', command: ['apple', 'signing', 'ensure'], write: true, network: true, idempotent: true, + description: 'Creates what signing is missing on the Apple Developer team: bundle id capabilities, a distribution certificate (key kept in .storebound/signing) and the App Store profiles, installed for Xcode. The dry run lists the items.' }, + { name: 'apple_adhoc_register', title: 'Register test devices', command: ['apple', 'adhoc', 'register'], write: true, network: true, idempotent: true, + description: 'Registers the devices of apple.adhoc.devices (or the given UDID) on the Apple Developer team. Each device uses one of the yearly slots of its product family.', + props: { udid: { type: 'string', pattern: '^[A-Fa-f0-9-]{24,40}$', description: 'One device UDID' }, name: { type: 'string', pattern: '^[^\\x00-\\x1f]{1,50}$', description: 'Its device name' } }, + args: i => [...opt('udid', i.udid), ...opt('name', i.name)] }, + { name: 'apple_adhoc_export', title: 'Export an ad-hoc IPA', command: ['apple', 'adhoc', 'export'], write: true, network: false, + description: 'xcodebuild -exportArchive of an archive with the ad-hoc / release-testing ExportOptions.plist; writes the IPA locally.', + props: { archive: { type: 'string', pattern: '^(?!-)(?!.*\\.\\.)[^\\x00-\\x1f]{1,1000}\\.xcarchive$', description: 'The .xcarchive path' } }, required: ['archive'], args: i => opt('archive', i.archive) }, + { name: 'shots_fonts', title: 'Download font subsets', command: ['shots', 'fonts'], write: true, network: true, idempotent: true, + description: 'Downloads the font subsets the screenshot copy needs (CJK, Arabic, Cyrillic ...) into the app folder.' }, + { name: 'shots_jpeg', title: 'JPEG copies of the Play renders', command: ['shots', 'jpeg'], write: true, network: false, idempotent: true, + description: 'Writes JPEG copies (quality 92) of the Play renders next to them, for faster Play uploads.', + props: { variant: { type: 'string', pattern: '^[a-z0-9][a-z0-9-]*$', description: 'A/B variant id from shots.variants (default: the base renders)' }, all_variants: { type: 'boolean', default: false, description: 'The base renders and every variant' } }, + args: i => [...opt('variant', i.variant), ...(i.all_variants === true ? ['--variants'] : [])] }, + { name: 'agent_install', title: 'Install for an AI tool', command: ['install'], write: true, network: false, idempotent: true, + description: 'Installs the storebound skills and the MCP server for one AI tool (Claude, Codex, Cursor, Copilot, Windsurf, Gemini, OpenCode) for this app folder.', + props: { agent: { type: 'string', enum: ['claude', 'codex', 'cursor', 'copilot', 'windsurf', 'gemini', 'opencode'] }, no_mcp: { type: 'boolean', default: false }, no_skills: { type: 'boolean', default: false } }, + required: ['agent'], args: i => [...opt('agent', i.agent), ...(i.no_mcp === true ? ['--no-mcp'] : []), ...(i.no_skills === true ? ['--no-skills'] : [])] }, ]; const BUILD_NO = { type: 'string', pattern: '^\\d{1,9}(\\.\\d{1,9}){0,3}$', description: 'The build number (CFBundleVersion) the owner picked from the uploaded builds; never "the latest"' }; const PLATFORM = { type: 'string', enum: ['ios', 'macos', 'tvos', 'visionos'], description: 'App Store platform of the version (default: the one that has it; when several do, the command asks)' }; From a95aa6dd49b75754f8f582999fafcb227a6be4f1 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:02:20 +0700 Subject: [PATCH 058/344] desktop: More tools tab, one typed form per CLI command without a screen (schema from system.methods; reads run, writes dry run + native dialog + token) and the owner steps with their terminal command; en + tr --- apps/desktop/src/dev/fixtures.ts | 9 ++ apps/desktop/src/i18n/en.ts | 36 ++++++ apps/desktop/src/i18n/tr.ts | 36 ++++++ apps/desktop/src/nav.ts | 6 +- apps/desktop/src/screens/AppView.tsx | 2 + apps/desktop/src/screens/tabs/Tools.tsx | 140 ++++++++++++++++++++++++ apps/desktop/src/styles.css | 5 + 7 files changed, 231 insertions(+), 3 deletions(-) create mode 100644 apps/desktop/src/screens/tabs/Tools.tsx diff --git a/apps/desktop/src/dev/fixtures.ts b/apps/desktop/src/dev/fixtures.ts index 1189868..8f1383f 100644 --- a/apps/desktop/src/dev/fixtures.ts +++ b/apps/desktop/src/dev/fixtures.ts @@ -11,6 +11,14 @@ import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, import { editableFixture, liveFixture } from './editor-fixtures'; import { APPLE_STATUS_READY, APPLE_STATUS_UNRESOLVED, consolePlan, consoleVerify, ownerDry, PLAY_STATUS } from './submit-fixtures'; import { ANALYTICS, ASO, DECLARATIONS, LISTING_TEXT, PPO, PPO_STORE, PRICE_DIFF, PRICES, renderArt, RENDERS } from './fixtures-more'; +import { TOOLBOX } from '../../../../cli/lib/desktop-coverage'; + +/** system.methods for the More tools tab: the toolbox methods with a small schema each (reads end in a read verb). */ +const toolMethods = () => TOOLBOX.flatMap(g => g.methods).map(m => { + const read = /status|list|devices|check|diff|next_|app_id|info|wait|plan|verify|rank|competitors|suggest|scan|manifest|triage|originality|aso/.test(m); + return { method: m, title: m.replace('.', ' ').replace(/_/g, ' '), description: `Fixture descriptor of ${m}.`, kind: read ? 'read' : 'write', network: m.startsWith('apple.') || m.startsWith('play.'), destructive: false, json: false, + args: { type: 'object', additionalProperties: false, properties: m === 'play.upload' ? { track: { type: 'string', enum: ['internal', 'alpha', 'beta'], default: 'internal' }, name: { type: 'string', description: 'Release name' } } : m === 'agent.install' ? { agent: { type: 'string', enum: ['claude', 'codex'] }, no_mcp: { type: 'boolean' } } : {}, ...(m === 'agent.install' ? { required: ['agent'] } : {}) } }; +}); export const FIXTURE_MARKER = 'storebound-dev-fixtures'; @@ -581,6 +589,7 @@ async function answer(cmd: string, a: Record): Promise case 'cache_clear': return null; case 'sidecar_call': { const method = a.method as string; + if (method === 'system.methods') return { methods: toolMethods() }; if (method === 'system.tools') return { tools: (await answer('sidecar_status', {}) as { tools: { tools: unknown[] } }).tools.tools, androidSdk: { path: `${HOME}/Library/Android/sdk`, source: 'default', checked: ['ANDROID_HOME: not set', 'ANDROID_SDK_ROOT: not set', `Android Studio default folder: ${HOME}/Library/Android/sdk`] } }; const id = a.projectId as string; if (NETWORK.has(method)) await progressLines(job, [`[${method}] reading App Store Connect`, `[${method}] reading Google Play`, `[${method}] done`]); diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 58c20e5..c604f3e 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -1805,4 +1805,40 @@ export const en = { 'ed.targetAudience': 'Target audience and ads (Play)', 'ed.appContent': 'App content declarations (Play)', 'ed.appContentHint': 'Government, financial and health features, advertising ID. No API: the console plan step uses them.', + 'tab.tools': 'More tools', + 'tools.lead': 'Every CLI command without a tab of its own, as a form with the command\'s own options. Reads run here; writes show the dry run and ask in a native dialog first. Owner steps stay yours: copy the terminal command.', + 'tools.g.build': 'Build and upload', + 'tools.g.adhoc': 'Ad-hoc devices', + 'tools.g.store': 'Store features', + 'tools.g.text': 'Text and ASO', + 'tools.g.capture': 'Captures', + 'tools.g.quality': 'Quality', + 'tools.g.ads': 'Apple Ads', + 'tools.g.flows': 'Workflows and AI tools', + 'tools.count': '{count} commands', + 'tools.count_one': '1 command', + 'tools.show': 'Show', + 'tools.hide': 'Hide', + 'tools.read': 'read-only', + 'tools.write': 'write (dry run first)', + 'tools.network': 'store', + 'tools.run': 'Run', + 'tools.dryRun': 'Dry run, then apply', + 'tools.done': '{title}: done', + 'tools.default': 'default: {value}', + 'tools.exit': 'exit {code}', + 'tools.copy': 'Copy', + 'tools.copied': 'Copied', + 'tools.owner': 'Owner steps (terminal)', + 'tools.ownerSub': 'Public or price changes only you decide; run them in a terminal in the app folder', + 'tools.o.offer_codes': 'App Store offer codes for one-time purchases', + 'tools.o.win_back': 'Win-back offers for lapsed subscribers', + 'tools.o.promoted': 'Turn on promoted in-app purchases', + 'tools.o.preorder': 'Enable or end an App Store pre-order', + 'tools.o.cpp_submit': 'Submit a custom product page (then make it visible)', + 'tools.o.events_submit': 'Submit an in-app event', + 'tools.o.tf_expire': 'Expire old TestFlight builds', + 'tools.o.ads_change': 'Apple Ads bid, budget or pause', + 'tools.o.rc_sync': 'Sync the catalog to RevenueCat', + 'tools.o.shots_login': 'Sign in to the demo account for screenshots (by hand, Enter saves)', } as const; diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index a660602..6356927 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -1807,4 +1807,40 @@ export const tr: Record = { 'ed.targetAudience': 'Hedef kitle ve reklamlar (Play)', 'ed.appContent': 'Uygulama içeriği beyanları (Play)', 'ed.appContentHint': 'Devlet, finans ve sağlık özellikleri, reklam kimliği. API yok: konsol planı adımı bunları kullanır.', + 'tab.tools': 'Diğer araçlar', + 'tools.lead': 'Kendi sekmesi olmayan her CLI komutu, komutun kendi seçenekleriyle bir form olarak. Okumalar burada çalışır; yazmalar önce prova sonucunu gösterir ve yerel bir pencerede onay ister. Sahip adımları sizindir: terminal komutunu kopyalayın.', + 'tools.g.build': 'Derleme ve yükleme', + 'tools.g.adhoc': 'Ad-hoc cihazlar', + 'tools.g.store': 'Mağaza özellikleri', + 'tools.g.text': 'Metin ve ASO', + 'tools.g.capture': 'Çekimler', + 'tools.g.quality': 'Kalite', + 'tools.g.ads': 'Apple Ads', + 'tools.g.flows': 'İş akışları ve yapay zekâ araçları', + 'tools.count': '{count} komut', + 'tools.count_one': '1 komut', + 'tools.show': 'Göster', + 'tools.hide': 'Gizle', + 'tools.read': 'salt okunur', + 'tools.write': 'yazma (önce prova)', + 'tools.network': 'mağaza', + 'tools.run': 'Çalıştır', + 'tools.dryRun': 'Prova, sonra uygula', + 'tools.done': '{title}: tamam', + 'tools.default': 'varsayılan: {value}', + 'tools.exit': 'çıkış {code}', + 'tools.copy': 'Kopyala', + 'tools.copied': 'Kopyalandı', + 'tools.owner': 'Sahip adımları (terminal)', + 'tools.ownerSub': 'Yalnızca sizin karar verdiğiniz herkese açık veya fiyat değişiklikleri; uygulama klasöründe bir terminalde çalıştırın', + 'tools.o.offer_codes': 'Tek seferlik satın almalar için App Store teklif kodları', + 'tools.o.win_back': 'Ayrılan aboneler için geri kazanma teklifleri', + 'tools.o.promoted': 'Öne çıkan uygulama içi satın almaları aç', + 'tools.o.preorder': 'App Store ön siparişini aç veya bitir', + 'tools.o.cpp_submit': 'Özel ürün sayfasını gönder (sonra görünür yap)', + 'tools.o.events_submit': 'Uygulama içi etkinliği gönder', + 'tools.o.tf_expire': 'Eski TestFlight derlemelerinin süresini bitir', + 'tools.o.ads_change': 'Apple Ads teklif, bütçe veya duraklatma', + 'tools.o.rc_sync': 'Kataloğu RevenueCat ile eşitle', + 'tools.o.shots_login': 'Ekran görüntüleri için demo hesaba giriş (elle, Enter kaydeder)', }; diff --git a/apps/desktop/src/nav.ts b/apps/desktop/src/nav.ts index a8885af..b438256 100644 --- a/apps/desktop/src/nav.ts +++ b/apps/desktop/src/nav.ts @@ -4,7 +4,7 @@ import { createContext, useContext } from 'react'; import type { Key } from './i18n'; import type { IconName } from './ui/icons'; -export const APP_TABS = ['releases', 'catalog', 'prices', 'listings', 'art', 'health', 'reviews', 'testflight', 'growth', 'appinfo', 'checks'] as const; +export const APP_TABS = ['releases', 'catalog', 'prices', 'listings', 'art', 'health', 'reviews', 'testflight', 'growth', 'appinfo', 'checks', 'tools'] as const; export type AppTab = (typeof APP_TABS)[number]; /** Tabs of a store-only app: store reads only (catalog, prices, app info and checks need the app folder; listings and * store art are the live ones; Growth shows the Product Page Optimization tests only). */ @@ -12,11 +12,11 @@ export const STORE_TABS: readonly AppTab[] = ['releases', 'listings', 'art', 'he export const tabsFor = (hasFolder: boolean): readonly AppTab[] => (hasFolder ? APP_TABS : STORE_TABS); export const TAB_KEY: Record = { releases: 'tab.releases', catalog: 'tab.catalog', prices: 'tab.prices', listings: 'tab.listings', art: 'tab.art', health: 'tab.health', reviews: 'tab.reviews', - testflight: 'tab.testflight', growth: 'tab.growth', appinfo: 'tab.appinfo', checks: 'tab.checks', + testflight: 'tab.testflight', growth: 'tab.growth', appinfo: 'tab.appinfo', checks: 'tab.checks', tools: 'tab.tools', }; export const TAB_ICON: Record = { releases: 'rocket', catalog: 'tag', prices: 'coins', listings: 'text', art: 'grid', health: 'activity', reviews: 'message', testflight: 'plane', growth: 'chart', - appinfo: 'clipboard', checks: 'shield', + appinfo: 'clipboard', checks: 'shield', tools: 'sliders', }; export const WORKSPACE = ['apps', 'accounts', 'ignored', 'dependencies', 'settings'] as const; export type WorkspaceScreen = (typeof WORKSPACE)[number]; diff --git a/apps/desktop/src/screens/AppView.tsx b/apps/desktop/src/screens/AppView.tsx index 49ba9b0..319e105 100644 --- a/apps/desktop/src/screens/AppView.tsx +++ b/apps/desktop/src/screens/AppView.tsx @@ -24,6 +24,7 @@ import { PricesTab } from './tabs/Prices'; import { ReleasesTab } from './tabs/Releases'; import { ReviewsTab } from './tabs/Reviews'; import { TestFlightTab } from './tabs/TestFlight'; +import { ToolsTab } from './tabs/Tools'; import { EDIT_TABS, TabEditor, useUnsavedGuard } from './editors/TabEditor'; import { StoreListingEditor } from './editors/StoreListingEditor'; import { useEdits } from '../ui/Editor'; @@ -171,6 +172,7 @@ export function AppView({ app, tab }: { app: UnifiedApp; tab: AppTab }) { {tab === 'growth' && } {tab === 'appinfo' && app.project && } {tab === 'checks' && app.project && } + {tab === 'tools' && app.project && } {tab !== 'listings' && app.project && !app.project.missing && EDIT_TABS[tab] && } diff --git a/apps/desktop/src/screens/tabs/Tools.tsx b/apps/desktop/src/screens/tabs/Tools.tsx new file mode 100644 index 0000000..edb48a0 --- /dev/null +++ b/apps/desktop/src/screens/tabs/Tools.tsx @@ -0,0 +1,140 @@ +// More tools: the CLI commands without a screen of their own (cli/lib/desktop-coverage.ts TOOLBOX), one typed form +// per serve method built from its argument schema (system.methods). Never a free-text shell: only the method's own +// options, validated by the sidecar. Reads run here; writes go through the dry run, the native dialog and the confirm +// token (useWrite). Owner-only steps without a button are listed with their terminal command to copy. +import { useEffect, useState } from 'react'; +import type { JsonSchemaLite } from '../../../../../cli/lib/desktop-protocol'; +import { OWNER_STEPS, TOOLBOX } from '../../../../../cli/lib/desktop-coverage'; +import { api, errorText, type MethodDescriptor, newJob, type Project, type ToolResult } from '../../api'; +import { type Key, t } from '../../i18n'; +import { useData, useWrite } from '../../store'; +import { Icon } from '../../ui/icons'; +import { Card, Chip, ErrorNotice, Notice, Skeleton } from '../../ui/kit'; +import { WriteButton } from '../../ui/WriteButton'; + +type Args = Record; + +/** Only the values the owner set (empty fields are left out, so the command's defaults apply). */ +export function cleanArgs(schema: MethodDescriptor['args'], v: Args): Args { + const out: Args = {}; + for (const [k, s] of Object.entries(schema.properties)) { + const x = v[k]; + if (x === undefined || x === '' || x === null) continue; + if (s.type === 'boolean') { if (x === true) out[k] = true; continue; } + out[k] = s.type === 'number' || s.type === 'integer' ? Number(x) : x; + } + return out; +} + +function Field({ name, s, value, required, onChange }: { name: string; s: JsonSchemaLite; value: unknown; required: boolean; onChange: (v: unknown) => void }) { + const label = {name.replace(/_/g, ' ')}{required ? ' *' : ''}; + if (s.type === 'boolean') { + return ; + } + if (s.enum) { + return ( + + ); + } + const num = s.type === 'number' || s.type === 'integer'; + return ( + + ); +} + +function Tool({ m, project }: { m: MethodDescriptor; project: Project }) { + const d = useData(); + const w = useWrite(project.id); + const [v, setV] = useState({}); + const [busy, setBusy] = useState(false); + const [res, setRes] = useState(null); + const [err, setErr] = useState(null); + const props = Object.entries(m.args?.properties ?? {}); + const required = new Set(m.args?.required ?? []); + const args = m.args ? cleanArgs(m.args, v) : {}; + const missing = [...required].some(k => args[k] === undefined); + const read = async () => { + setBusy(true); setErr(null); + try { setRes(await api.call(m.method, project.id, { args }, newJob(m.method))); } catch (e) { setErr(errorText(e)); setRes(null); } + setBusy(false); + }; + return ( +
+
+
+ {m.title} + {m.description} +
+
+ {m.kind === 'read' ? t('tools.read') : t('tools.write')} + {m.network && {t('tools.network')}} +
+
+ {props.length > 0 && ( +
+ {props.map(([k, s]) => setV(p => ({ ...p, [k]: x }))} />)} +
+ )} +
+ {m.kind === 'read' + ? + : {t('tools.dryRun')}} +
+ {err && } + {res && ( +
+ {res.command} · {t('tools.exit', { code: res.exitCode })} +
{res.output || res.error || (res.data !== undefined ? JSON.stringify(res.data, null, 2) : '')}
+ +
+ )} +
+ ); +} + +export function ToolsTab({ project }: { project: Project }) { + const d = useData(); + const [methods, setMethods] = useState(null); + const [err, setErr] = useState(null); + const [open, setOpen] = useState(TOOLBOX[0]!.id); + useEffect(() => { + api.call<{ methods: MethodDescriptor[] }>('system.methods').then(r => setMethods(r.methods), e => setErr(errorText(e))); + }, []); + const by = new Map((methods ?? []).map(m => [m.method, m] as const)); + const copy = (c: string) => { navigator.clipboard?.writeText(c).then(() => d.toast({ kind: 'ok', title: t('tools.copied') }), () => {}); }; + return ( + <> + {t('tools.lead')} + {err && } + {!methods && !err && } + {methods && TOOLBOX.map(g => { + const ms = g.methods.map(x => by.get(x)).filter((x): x is MethodDescriptor => !!x); + const isOpen = open === g.id; + return ( + setOpen(isOpen ? '' : g.id)}>{isOpen ? t('tools.hide') : t('tools.show')}}> + {isOpen &&
{ms.map(m => )}
} +
+ ); + })} + +
+ {OWNER_STEPS.map(s => ( +
+
{t(`tools.o.${s.id}` as Key)}{s.command}
+ +
+ ))} +
+
+ + ); +} diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.css index fadfe77..e04f89b 100644 --- a/apps/desktop/src/styles.css +++ b/apps/desktop/src/styles.css @@ -807,6 +807,11 @@ h2[tabindex="-1"]:focus, h2[tabindex="-1"]:focus-visible { outline: none; } .issue-row .chev.rot { transform: rotate(90deg); } .ellipsis { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; } .issue-detail { display: grid; gap: 12px; padding: 4px 0; min-width: 0; } +/* More tools tab: one typed form per command */ +.tool { display: grid; gap: 8px; padding-top: 12px; border-top: 1px solid var(--line); min-width: 0; } +.tool:first-child { border-top: 0; padding-top: 0; } +.tool-form { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 8px 12px; } +.tool pre { max-height: 260px; overflow: auto; } .issue-title { overflow-wrap: anywhere; } .stack-trace { margin: 0; max-height: 280px; overflow: auto; padding: 10px 12px; border-radius: 8px; background: var(--surface); border: 1px solid var(--line, var(--border)); font: 12px/1.5 var(--mono, ui-monospace, monospace); white-space: pre; } .build-edit { display: grid; gap: 10px; padding: 4px 0; max-width: 760px; } From dc6bb088a1d25306f4116cfc2f934bc831ca65f3 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:02:20 +0700 Subject: [PATCH 059/344] desktop coverage: every CLI command mapped to its window place (cli/lib/desktop-coverage.ts), docs/desktop-coverage.md generated from it, guard test fails on a gap or an unjustified not-for-desktop --- cli/lib/desktop-coverage.ts | 138 +++++++++++++++++++++++++++++++++ docs/desktop-coverage.md | 103 ++++++++++++++++++++++++ tests/desktop-coverage.test.ts | 44 +++++++++++ tools/gen-desktop-coverage.ts | 86 ++++++++++++++++++++ 4 files changed, 371 insertions(+) create mode 100644 cli/lib/desktop-coverage.ts create mode 100644 docs/desktop-coverage.md create mode 100644 tests/desktop-coverage.test.ts create mode 100644 tools/gen-desktop-coverage.ts diff --git a/cli/lib/desktop-coverage.ts b/cli/lib/desktop-coverage.ts new file mode 100644 index 0000000..4f3c803 --- /dev/null +++ b/cli/lib/desktop-coverage.ts @@ -0,0 +1,138 @@ +// Where every CLI command (cli/commands.ts COMMANDS + PLAIN) lives in the desktop app. One source for +// tools/gen-desktop-coverage.ts (docs/desktop-coverage.md) and the guard test (tests/desktop-coverage.test.ts): a +// command without an entry, or with a method the window never calls, fails the test. +// +// methods: serve.ts methods (`play.listing`, `owner.play_rollout`) or host commands of src-tauri (`host:accounts_list`). +// owner: the owner-only parts of the command; the More tools tab lists them as terminal steps (OWNER_STEPS). + +export type Coverage = + | { where: string; methods: string[]; owner?: string } + | { not: string }; + +/** The More tools tab (apps/desktop/src/screens/tabs/Tools.tsx): one typed form per method, built from its schema + * (`system.methods`). Reads run; writes go through the dry run, the native dialog and the confirm token. */ +export const TOOLBOX: { id: string; methods: string[] }[] = [ + { id: 'build', methods: ['play.build', 'play.upload', 'play.share', 'play.next_version_code', 'play.app_id', 'apple.build', 'apple.upload', 'apple.next_build', + 'apple.signing_status', 'apple.signing_ensure', 'apple.bundle', 'apple.testflight_info', 'apple.testflight_wait'] }, + { id: 'adhoc', methods: ['apple.adhoc_devices', 'apple.adhoc_register', 'apple.adhoc_options', 'apple.adhoc_export'] }, + { id: 'store', methods: ['apple.iap_review', 'apple.iap_review_plan', 'apple.creative_assets', 'apple.creative_assets_verify', 'apple.cpp_list', 'apple.cpp_create', + 'apple.cpp_upload', 'apple.events_list', 'apple.events_create', 'apple.events_upload', 'apple.preorder_status', 'catalog.pull', 'onboard', 'revenuecat.diff', 'prices.ppp'] }, + { id: 'text', methods: ['whats.new', 'whats.new_languages', 'whats.new_check', 'whats.new_apply', 'listing.translate', 'listing.check', 'check.aso', 'aso.rank', + 'aso.competitors', 'aso.suggest'] }, + { id: 'capture', methods: ['shots.capture', 'shots.record', 'shots.check', 'shots.fonts', 'shots.jpeg'] }, + { id: 'quality', methods: ['health.report', 'triage', 'originality', 'privacy.manifest', 'ads.scan', 'web.init', 'web.check'] }, + { id: 'ads', methods: ['ads.apple_status', 'ads.apple_campaigns', 'ads.apple_report'] }, + { id: 'flows', methods: ['flow.list', 'flow.run', 'agent.install'] }, +]; + +/** Owner-only steps without a window button: the More tools tab shows each with its terminal command to copy. */ +export const OWNER_STEPS: { id: string; command: string }[] = [ + { id: 'offer_codes', command: 'storebound apple offer-codes' }, + { id: 'win_back', command: 'storebound apple win-back' }, + { id: 'promoted', command: 'storebound apple promoted --enable' }, + { id: 'preorder', command: 'storebound apple preorder enable --release-date YYYY-MM-DD' }, + { id: 'cpp_submit', command: 'storebound apple cpp submit --name ' }, + { id: 'events_submit', command: 'storebound apple events submit --name ' }, + { id: 'tf_expire', command: 'storebound apple testflight expire --keep 5' }, + { id: 'ads_change', command: 'storebound ads apple bid --campaign --keyword --bid 1.20' }, + { id: 'rc_sync', command: 'storebound revenuecat sync' }, + { id: 'shots_login', command: 'storebound shots login' }, +]; + +const T = 'More tools'; +export const DESKTOP_COVERAGE: Record = { + // PLAIN + 'init': { where: 'App folders: Start an app folder', methods: ['host:project_init'] }, + 'import': { where: 'App folders / first-run guide: Import from fastlane', methods: ['host:project_import_fastlane'] }, + 'install': { where: `${T}: Install for an AI tool`, methods: ['agent.install'] }, + 'mcp': { not: 'the stdio server for AI tools; the window itself is the GUI over the same commands' }, + 'serve': { not: 'the JSON-RPC sidecar the window runs on; nothing to click' }, + 'apps': { where: 'Accounts (store apps per account, key check) and App folders (list, add, remove)', methods: ['host:store_apps_refresh', 'host:account_check', 'host:projects_list', 'host:project_add', 'host:project_remove'] }, + 'desktop': { not: 'opens or installs this window from a terminal' }, + 'accounts': { where: 'Accounts screen (profiles shared with the CLI)', methods: ['host:accounts_list', 'host:account_add_play', 'host:account_add_apple', 'host:account_update'] }, + 'doctor': { where: 'Dependencies screen', methods: ['system.tools', 'host:tools_info'] }, + 'scan': { where: 'Checks tab: Scan, Fix', methods: ['scan', 'scan.write'] }, + 'api': { not: 'raw API calls by operation id: every task has its own screen, and raw writes stay a terminal step the owner types' }, + 'privacy-manifest': { where: `${T}: Quality`, methods: ['privacy.manifest'] }, + 'ws': { where: 'Portfolio, studios and Settings (the workspace of this machine)', methods: ['host:workspace_get', 'host:portfolio_status'] }, + 'release': { where: 'Portfolio release trains and the Releases tab', methods: ['host:portfolio_status', 'apple.status', 'play.status'] }, + 'flow': { where: `${T}: Workflows (plans; owner steps never run)`, methods: ['flow.list', 'flow.run'] }, + 'ads': { where: `${T}: Quality (AdAttributionKit / SKAdNetwork scan)`, methods: ['ads.scan'] }, + // COMMANDS + 'edit': { where: 'Editors on every tab (Save edits)', methods: ['project.editable', 'project.edit'] }, + 'inspect': { where: 'App card, App info, Listings, Store art (offline reads)', methods: ['host:portfolio_status', 'project.declarations', 'project.listings', 'project.listing_text', 'project.icon', 'project.render'] }, + 'check': { where: 'Checks tab', methods: ['check'] }, + 'validate': { where: 'Checks tab', methods: ['validate'] }, + 'report': { where: 'Checks tab: readiness report', methods: ['report'] }, + 'analytics': { where: 'Growth tab: chart, snapshot, setup', methods: ['analytics.compare', 'analytics.snapshot', 'analytics.setup'] }, + 'health': { where: 'Health tab; weekly report in More tools', methods: ['health', 'health.issue', 'health.report'] }, + 'art': { where: 'Store art tab: live art, pull, replace', methods: ['art.live', 'art.thumb', 'art.pull', 'art.replace'] }, + 'onboard': { where: `${T}: Store features`, methods: ['onboard'] }, + 'catalog': { where: 'Catalog tab (parity); pull in More tools', methods: ['catalog.diff', 'catalog.pull'] }, + 'reports': { where: 'Growth tab: sales and finance reports', methods: ['reports'] }, + 'triage': { where: `${T}: Quality`, methods: ['triage'] }, + 'aso': { where: 'Growth tab: ASO audit; rank, competitors, suggest in More tools', methods: ['aso.audit', 'aso.rank', 'aso.competitors', 'aso.suggest'] }, + 'prices': { where: 'Prices tab (export, compare, apply = owner action); PPP sheet in More tools', methods: ['prices.current', 'prices.export', 'prices.diff', 'owner.prices_import', 'prices.ppp'] }, + 'ads apple': { where: `${T}: Apple Ads (status, campaigns, report)`, methods: ['ads.apple_status', 'ads.apple_campaigns', 'ads.apple_report'], owner: 'bid, budget, pause' }, + 'web': { where: `${T}: Quality (init, check)`, methods: ['web.init', 'web.check'] }, + 'revenuecat': { where: `${T}: Store features (diff)`, methods: ['revenuecat.diff'], owner: 'sync' }, + 'console plan': { where: 'App info: Console steps without an API', methods: ['console.plan'] }, + 'console verify': { where: 'App info: Console steps, Check', methods: ['console.verify'] }, + 'console fill': { where: 'App info: Fill in console', methods: ['console.fill'] }, + 'reviews': { where: 'Reviews tab (list, draft, reply, approve; Send = owner action)', methods: ['reviews.list', 'reviews.draft', 'reviews.drafts', 'reviews.reply', 'reviews.approve', 'owner.reply_send'] }, + 'originality': { where: `${T}: Quality`, methods: ['originality'] }, + 'listing': { where: 'Listings tab (live texts, store edits); translate and check in More tools', methods: ['listing.live', 'listing.set', 'listing.translate', 'listing.check'] }, + 'whats-new': { where: `${T}: Text and ASO`, methods: ['whats.new', 'whats.new_languages', 'whats.new_check', 'whats.new_apply'] }, + 'play products': { where: 'Catalog tab', methods: ['play.products', 'owner.prices_play_products'] }, + 'play subscriptions': { where: 'Catalog tab', methods: ['play.subscriptions', 'owner.prices_play_subscriptions'] }, + 'play listing': { where: 'Listings tab (push, pull)', methods: ['play.listing', 'play.listing_pull'] }, + 'play images': { where: 'Listings tab: Play graphics', methods: ['play.images'] }, + 'play data-safety': { where: 'App info tab: Data safety upload', methods: ['play.data_safety'] }, + 'play release': { where: 'Releases tab: Send to production (owner action); testing tracks via play upload in More tools', methods: ['owner.play_production', 'play.upload'] }, + 'play build': { where: `${T}: Build and upload`, methods: ['play.build'] }, + 'play upload': { where: `${T}: Build and upload`, methods: ['play.upload'] }, + 'play status': { where: 'Releases tab: Google Play card', methods: ['play.status'] }, + 'play rollout': { where: 'Releases tab: rollout (owner action)', methods: ['owner.play_rollout'] }, + 'play share': { where: `${T}: Build and upload`, methods: ['play.share'] }, + 'play app-id': { where: `${T}: Build and upload`, methods: ['play.app_id'] }, + 'play next-version-code': { where: `${T}: Build and upload`, methods: ['play.next_version_code'] }, + 'apple bundle': { where: `${T}: Build and upload`, methods: ['apple.bundle'] }, + 'apple iap': { where: 'Catalog tab', methods: ['apple.iap'] }, + 'apple subscriptions': { where: 'Catalog tab', methods: ['apple.subscriptions', 'owner.prices_apple_subscriptions'] }, + 'apple iap-review': { where: `${T}: Store features`, methods: ['apple.iap_review'] }, + 'apple iap-submit': { where: 'Releases tab: Submit in-app purchases (owner action); plan in More tools', methods: ['owner.apple_iap_submit', 'apple.iap_review_plan'] }, + 'apple submit': { where: 'Releases tab: Submit for review (owner action)', methods: ['owner.apple_submit'] }, + 'apple resubmit': { where: 'Releases tab: Resubmit (owner action)', methods: ['owner.apple_resubmit'] }, + 'apple offer-codes': { where: `${T}: owner steps (terminal command)`, methods: [], owner: 'creating campaigns and codes' }, + 'apple win-back': { where: `${T}: owner steps (terminal command)`, methods: [], owner: 'win-back offers go live on their start date' }, + 'apple promoted': { where: `${T}: owner steps (terminal command)`, methods: [], owner: 'promoted purchases on the product page' }, + 'apple preorder': { where: `${T}: Store features (status); enable / end as owner steps`, methods: ['apple.preorder_status'], owner: 'enable, end' }, + 'apple cpp': { where: `${T}: Store features (list, create, upload)`, methods: ['apple.cpp_list', 'apple.cpp_create', 'apple.cpp_upload'], owner: 'submit, visible' }, + 'apple events': { where: `${T}: Store features (list, create, upload)`, methods: ['apple.events_list', 'apple.events_create', 'apple.events_upload'], owner: 'submit' }, + 'apple listing': { where: 'Listings tab (push, pull)', methods: ['apple.listing', 'apple.listing_pull'] }, + 'apple screenshots': { where: 'Listings tab: App Store screenshots', methods: ['apple.screenshots'] }, + 'apple appinfo': { where: 'App info tab: Push', methods: ['apple.appinfo'] }, + 'apple review-details': { where: 'App info tab: App Review details', methods: ['apple.review_details'] }, + 'apple status': { where: 'Releases tab: Send for review, App Store card', methods: ['apple.status'] }, + 'apple creative-assets': { where: `${T}: Store features`, methods: ['apple.creative_assets', 'apple.creative_assets_verify'] }, + 'apple previews': { where: 'Listings tab: App Store previews', methods: ['apple.previews'] }, + 'apple release': { where: 'Releases tab: phased release (owner action)', methods: ['owner.ios_phased'] }, + 'apple signing': { where: `${T}: Build and upload (status, ensure)`, methods: ['apple.signing_status', 'apple.signing_ensure'] }, + 'apple build': { where: `${T}: Build and upload`, methods: ['apple.build'] }, + 'apple upload': { where: `${T}: Build and upload`, methods: ['apple.upload'] }, + 'apple adhoc': { where: `${T}: Ad-hoc devices (devices, register, options, export)`, methods: ['apple.adhoc_devices', 'apple.adhoc_register', 'apple.adhoc_options', 'apple.adhoc_export'] }, + 'apple next-build': { where: `${T}: Build and upload`, methods: ['apple.next_build'] }, + 'apple encryption': { where: 'App info tab: export compliance', methods: ['apple.encryption'] }, + 'apple ppo': { where: 'Growth tab: PPO tests (start / stop = owner actions)', methods: ['apple.ppo_status', 'apple.ppo_create', 'apple.ppo_upload', 'owner.ppo_start', 'owner.ppo_stop'] }, + 'apple testflight': { where: 'TestFlight tab (status, groups, What to Test, distribute, testers = owner action); info and wait in More tools', methods: ['apple.testflight_status', 'apple.testflight_groups', 'apple.testflight_what_to_test', 'apple.testflight_distribute', 'owner.testflight_testers', 'apple.testflight_info', 'apple.testflight_wait'], owner: 'expire' }, + 'icons': { where: 'Store art tab: icons', methods: ['icons'] }, + 'shots capture': { where: `${T}: Captures`, methods: ['shots.capture'] }, + 'shots login': { where: `${T}: owner steps (terminal command)`, methods: [], owner: 'signing in to a demo account by hand in a visible browser' }, + 'shots fonts': { where: `${T}: Captures`, methods: ['shots.fonts'] }, + 'shots render': { where: 'Store art tab: Render', methods: ['shots.render'] }, + 'shots jpeg': { where: `${T}: Captures`, methods: ['shots.jpeg'] }, + 'shots check': { where: `${T}: Captures`, methods: ['shots.check'] }, + 'shots record': { where: `${T}: Captures`, methods: ['shots.record'] }, + 'shots video': { where: 'Store art tab: previews', methods: ['shots.video'] }, + 'shots gallery': { where: 'Store art tab: gallery, review page', methods: ['shots.gallery', 'project.renders'] }, +}; diff --git a/docs/desktop-coverage.md b/docs/desktop-coverage.md new file mode 100644 index 0000000..687ded5 --- /dev/null +++ b/docs/desktop-coverage.md @@ -0,0 +1,103 @@ +# Desktop coverage + +Generated by `bun tools/gen-desktop-coverage.ts` from `cli/lib/desktop-coverage.ts`; do not edit by hand. +Every CLI command (cli/commands.ts) and the desktop place that runs it. "covered" means each method listed exists +(serve.ts, or a host command `host:`) and the window calls it; tests/desktop-coverage.test.ts fails on a gap. +Owner-only parts are owner actions in the window or owner steps with their terminal command (More tools). + +**92 commands:** 88 covered, 0 gaps, 4 not for the desktop. + +| command | status | where in the window | methods | owner step | +|---|---|---|---|---| +| `init` | covered | App folders: Start an app folder | `host:project_init` | | +| `import` | covered | App folders / first-run guide: Import from fastlane | `host:project_import_fastlane` | | +| `install` | covered | More tools: Install for an AI tool | `agent.install` | | +| `mcp` | not-for-desktop | the stdio server for AI tools; the window itself is the GUI over the same commands | | | +| `serve` | not-for-desktop | the JSON-RPC sidecar the window runs on; nothing to click | | | +| `apps` | covered | Accounts (store apps per account, key check) and App folders (list, add, remove) | `host:store_apps_refresh`, `host:account_check`, `host:projects_list`, `host:project_add`, `host:project_remove` | | +| `desktop` | not-for-desktop | opens or installs this window from a terminal | | | +| `accounts` | covered | Accounts screen (profiles shared with the CLI) | `host:accounts_list`, `host:account_add_play`, `host:account_add_apple`, `host:account_update` | | +| `doctor` | covered | Dependencies screen | `system.tools`, `host:tools_info` | | +| `scan` | covered | Checks tab: Scan, Fix | `scan`, `scan.write` | | +| `api` | not-for-desktop | raw API calls by operation id: every task has its own screen, and raw writes stay a terminal step the owner types | | | +| `privacy-manifest` | covered | More tools: Quality | `privacy.manifest` | | +| `ws` | covered | Portfolio, studios and Settings (the workspace of this machine) | `host:workspace_get`, `host:portfolio_status` | | +| `release` | covered | Portfolio release trains and the Releases tab | `host:portfolio_status`, `apple.status`, `play.status` | | +| `flow` | covered | More tools: Workflows (plans; owner steps never run) | `flow.list`, `flow.run` | | +| `ads` | covered | More tools: Quality (AdAttributionKit / SKAdNetwork scan) | `ads.scan` | | +| `edit` | covered | Editors on every tab (Save edits) | `project.editable`, `project.edit` | | +| `inspect` | covered | App card, App info, Listings, Store art (offline reads) | `host:portfolio_status`, `project.declarations`, `project.listings`, `project.listing_text`, `project.icon`, `project.render` | | +| `check` | covered | Checks tab | `check` | | +| `validate` | covered | Checks tab | `validate` | | +| `report` | covered | Checks tab: readiness report | `report` | | +| `analytics` | covered | Growth tab: chart, snapshot, setup | `analytics.compare`, `analytics.snapshot`, `analytics.setup` | | +| `health` | covered | Health tab; weekly report in More tools | `health`, `health.issue`, `health.report` | | +| `art` | covered | Store art tab: live art, pull, replace | `art.live`, `art.thumb`, `art.pull`, `art.replace` | | +| `onboard` | covered | More tools: Store features | `onboard` | | +| `catalog` | covered | Catalog tab (parity); pull in More tools | `catalog.diff`, `catalog.pull` | | +| `reports` | covered | Growth tab: sales and finance reports | `reports` | | +| `triage` | covered | More tools: Quality | `triage` | | +| `aso` | covered | Growth tab: ASO audit; rank, competitors, suggest in More tools | `aso.audit`, `aso.rank`, `aso.competitors`, `aso.suggest` | | +| `prices` | covered | Prices tab (export, compare, apply = owner action); PPP sheet in More tools | `prices.current`, `prices.export`, `prices.diff`, `owner.prices_import`, `prices.ppp` | | +| `ads apple` | covered | More tools: Apple Ads (status, campaigns, report) | `ads.apple_status`, `ads.apple_campaigns`, `ads.apple_report` | bid, budget, pause | +| `web` | covered | More tools: Quality (init, check) | `web.init`, `web.check` | | +| `revenuecat` | covered | More tools: Store features (diff) | `revenuecat.diff` | sync | +| `console plan` | covered | App info: Console steps without an API | `console.plan` | | +| `console verify` | covered | App info: Console steps, Check | `console.verify` | | +| `console fill` | covered | App info: Fill in console | `console.fill` | | +| `reviews` | covered | Reviews tab (list, draft, reply, approve; Send = owner action) | `reviews.list`, `reviews.draft`, `reviews.drafts`, `reviews.reply`, `reviews.approve`, `owner.reply_send` | | +| `originality` | covered | More tools: Quality | `originality` | | +| `listing` | covered | Listings tab (live texts, store edits); translate and check in More tools | `listing.live`, `listing.set`, `listing.translate`, `listing.check` | | +| `whats-new` | covered | More tools: Text and ASO | `whats.new`, `whats.new_languages`, `whats.new_check`, `whats.new_apply` | | +| `play products` | covered | Catalog tab | `play.products`, `owner.prices_play_products` | | +| `play subscriptions` | covered | Catalog tab | `play.subscriptions`, `owner.prices_play_subscriptions` | | +| `play listing` | covered | Listings tab (push, pull) | `play.listing`, `play.listing_pull` | | +| `play images` | covered | Listings tab: Play graphics | `play.images` | | +| `play data-safety` | covered | App info tab: Data safety upload | `play.data_safety` | | +| `play release` | covered | Releases tab: Send to production (owner action); testing tracks via play upload in More tools | `owner.play_production`, `play.upload` | | +| `play build` | covered | More tools: Build and upload | `play.build` | | +| `play upload` | covered | More tools: Build and upload | `play.upload` | | +| `play status` | covered | Releases tab: Google Play card | `play.status` | | +| `play rollout` | covered | Releases tab: rollout (owner action) | `owner.play_rollout` | | +| `play share` | covered | More tools: Build and upload | `play.share` | | +| `play app-id` | covered | More tools: Build and upload | `play.app_id` | | +| `play next-version-code` | covered | More tools: Build and upload | `play.next_version_code` | | +| `apple bundle` | covered | More tools: Build and upload | `apple.bundle` | | +| `apple iap` | covered | Catalog tab | `apple.iap` | | +| `apple subscriptions` | covered | Catalog tab | `apple.subscriptions`, `owner.prices_apple_subscriptions` | | +| `apple iap-review` | covered | More tools: Store features | `apple.iap_review` | | +| `apple iap-submit` | covered | Releases tab: Submit in-app purchases (owner action); plan in More tools | `owner.apple_iap_submit`, `apple.iap_review_plan` | | +| `apple submit` | covered | Releases tab: Submit for review (owner action) | `owner.apple_submit` | | +| `apple resubmit` | covered | Releases tab: Resubmit (owner action) | `owner.apple_resubmit` | | +| `apple offer-codes` | covered | More tools: owner steps (terminal command) | | creating campaigns and codes | +| `apple win-back` | covered | More tools: owner steps (terminal command) | | win-back offers go live on their start date | +| `apple promoted` | covered | More tools: owner steps (terminal command) | | promoted purchases on the product page | +| `apple preorder` | covered | More tools: Store features (status); enable / end as owner steps | `apple.preorder_status` | enable, end | +| `apple cpp` | covered | More tools: Store features (list, create, upload) | `apple.cpp_list`, `apple.cpp_create`, `apple.cpp_upload` | submit, visible | +| `apple events` | covered | More tools: Store features (list, create, upload) | `apple.events_list`, `apple.events_create`, `apple.events_upload` | submit | +| `apple listing` | covered | Listings tab (push, pull) | `apple.listing`, `apple.listing_pull` | | +| `apple screenshots` | covered | Listings tab: App Store screenshots | `apple.screenshots` | | +| `apple appinfo` | covered | App info tab: Push | `apple.appinfo` | | +| `apple review-details` | covered | App info tab: App Review details | `apple.review_details` | | +| `apple status` | covered | Releases tab: Send for review, App Store card | `apple.status` | | +| `apple creative-assets` | covered | More tools: Store features | `apple.creative_assets`, `apple.creative_assets_verify` | | +| `apple previews` | covered | Listings tab: App Store previews | `apple.previews` | | +| `apple release` | covered | Releases tab: phased release (owner action) | `owner.ios_phased` | | +| `apple signing` | covered | More tools: Build and upload (status, ensure) | `apple.signing_status`, `apple.signing_ensure` | | +| `apple build` | covered | More tools: Build and upload | `apple.build` | | +| `apple upload` | covered | More tools: Build and upload | `apple.upload` | | +| `apple adhoc` | covered | More tools: Ad-hoc devices (devices, register, options, export) | `apple.adhoc_devices`, `apple.adhoc_register`, `apple.adhoc_options`, `apple.adhoc_export` | | +| `apple next-build` | covered | More tools: Build and upload | `apple.next_build` | | +| `apple encryption` | covered | App info tab: export compliance | `apple.encryption` | | +| `apple ppo` | covered | Growth tab: PPO tests (start / stop = owner actions) | `apple.ppo_status`, `apple.ppo_create`, `apple.ppo_upload`, `owner.ppo_start`, `owner.ppo_stop` | | +| `apple testflight` | covered | TestFlight tab (status, groups, What to Test, distribute, testers = owner action); info and wait in More tools | `apple.testflight_status`, `apple.testflight_groups`, `apple.testflight_what_to_test`, `apple.testflight_distribute`, `owner.testflight_testers`, `apple.testflight_info`, `apple.testflight_wait` | expire | +| `icons` | covered | Store art tab: icons | `icons` | | +| `shots capture` | covered | More tools: Captures | `shots.capture` | | +| `shots login` | covered | More tools: owner steps (terminal command) | | signing in to a demo account by hand in a visible browser | +| `shots fonts` | covered | More tools: Captures | `shots.fonts` | | +| `shots render` | covered | Store art tab: Render | `shots.render` | | +| `shots jpeg` | covered | More tools: Captures | `shots.jpeg` | | +| `shots check` | covered | More tools: Captures | `shots.check` | | +| `shots record` | covered | More tools: Captures | `shots.record` | | +| `shots video` | covered | Store art tab: previews | `shots.video` | | +| `shots gallery` | covered | Store art tab: gallery, review page | `shots.gallery`, `project.renders` | | diff --git a/tests/desktop-coverage.test.ts b/tests/desktop-coverage.test.ts new file mode 100644 index 0000000..7c4b686 --- /dev/null +++ b/tests/desktop-coverage.test.ts @@ -0,0 +1,44 @@ +// Every CLI command is reachable in the desktop app, or listed as not for the desktop with a reason +// (cli/lib/desktop-coverage.ts; the same analysis writes docs/desktop-coverage.md). +import { describe, expect, test } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { DESKTOP_COVERAGE, OWNER_STEPS, TOOLBOX } from '../cli/lib/desktop-coverage'; +import { describeMethods } from '../cli/serve'; +import { analyze, render } from '../tools/gen-desktop-coverage'; + +/** The only commands that make no sense in a window. Adding one here needs a reason in the coverage map. */ +const NOT_FOR_DESKTOP = ['mcp', 'serve', 'desktop', 'api']; + +describe('desktop coverage', () => { + const { rows, extra } = analyze(); + test('every CLI command has a desktop place (no gaps)', () => { + expect(rows.filter(r => r.status === 'gap').map(r => `${r.command}: ${r.problems.join('; ')}`)).toEqual([]); + expect(extra).toEqual([]); + }); + test('not-for-desktop is short and each has a reason', () => { + const not = rows.filter(r => r.status === 'not-for-desktop'); + expect(not.map(r => r.command).sort()).toEqual([...NOT_FOR_DESKTOP].sort()); + for (const r of not) expect(r.where.length).toBeGreaterThan(20); + }); + test('the More tools tab offers no owner action and no unknown method', () => { + const ms = new Map(describeMethods().map(m => [m.method, m] as const)); + for (const m of TOOLBOX.flatMap(g => g.methods)) { + expect(ms.has(m)).toBe(true); + expect(['read', 'write']).toContain(ms.get(m)!.kind); + } + for (const s of OWNER_STEPS) expect(s.command.startsWith('storebound ')).toBe(true); + for (const [, c] of Object.entries(DESKTOP_COVERAGE)) if ('owner' in c && c.owner) expect(c.owner.length).toBeGreaterThan(2); + }); + test('docs/desktop-coverage.md is generated and current', () => { + expect(readFileSync(join(import.meta.dir, '../docs/desktop-coverage.md'), 'utf8')).toBe(render(rows)); + }); + test('every More tools group and owner step has en and tr strings', () => { + const en = readFileSync(join(import.meta.dir, '../apps/desktop/src/i18n/en.ts'), 'utf8'); + const tr = readFileSync(join(import.meta.dir, '../apps/desktop/src/i18n/tr.ts'), 'utf8'); + for (const k of [...TOOLBOX.map(g => `tools.g.${g.id}`), ...OWNER_STEPS.map(s => `tools.o.${s.id}`)]) { + expect(en).toContain(`'${k}'`); + expect(tr).toContain(`'${k}'`); + } + }); +}); diff --git a/tools/gen-desktop-coverage.ts b/tools/gen-desktop-coverage.ts new file mode 100644 index 0000000..3ee1317 --- /dev/null +++ b/tools/gen-desktop-coverage.ts @@ -0,0 +1,86 @@ +// docs/desktop-coverage.md from cli/lib/desktop-coverage.ts, checked against the code: a command is "covered" only +// when every method it names exists (serve.ts describeMethods(), or a #[tauri::command] of src-tauri) and the window +// calls it (the method quoted in apps/desktop/src, or listed in TOOLBOX, which the More tools tab renders). +// `bun tools/gen-desktop-coverage.ts` writes the page; `--check` exits 1 when it is stale. tests/desktop-coverage.test.ts +// runs analyze() too. +import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { COMMANDS, PLAIN } from '../cli/commands'; +import { DESKTOP_COVERAGE, OWNER_STEPS, TOOLBOX } from '../cli/lib/desktop-coverage'; +import { describeMethods } from '../cli/serve'; + +const ROOT = join(import.meta.dir, '..'); +const OUT = join(ROOT, 'docs/desktop-coverage.md'); + +function files(dir: string, out: string[] = []): string[] { + for (const f of readdirSync(dir)) { + const p = join(dir, f); + if (statSync(p).isDirectory()) { if (f !== 'dev' && f !== 'i18n') files(p, out); } else if (/\.(ts|tsx|rs)$/.test(f)) out.push(p); + } + return out; +} + +export interface Row { command: string; status: 'covered' | 'gap' | 'not-for-desktop'; where: string; methods: string[]; owner?: string; problems: string[] } + +export function analyze(): { rows: Row[]; extra: string[] } { + const src = files(join(ROOT, 'apps/desktop/src')).map(f => readFileSync(f, 'utf8')).join('\n'); + const rust = files(join(ROOT, 'apps/desktop/src-tauri/src')).map(f => readFileSync(f, 'utf8')).join('\n'); + const hostCmds = new Set([...rust.matchAll(/#\[tauri::command\][\s\S]{0,200}?fn ([a-z_]+)/g)].map(m => m[1]!)); + const methods = new Set(describeMethods().map(m => m.method)); + const toolboxShown = /\bTOOLBOX\b/.test(src); + const inToolbox = new Set(TOOLBOX.flatMap(g => g.methods)); + const reachable = (m: string): string | null => { + if (m.startsWith('host:')) { + const c = m.slice(5); + if (!hostCmds.has(c)) return `${m}: no such tauri command`; + return src.includes(`'${c}'`) ? null : `${m}: never invoked by the window`; + } + if (!methods.has(m)) return `${m}: no such serve method`; + if (src.includes(`'${m}'`) || src.includes(`"${m}"`)) return null; + if (toolboxShown && inToolbox.has(m)) return null; + return `${m}: no window place calls it`; + }; + const all = [...Object.keys(PLAIN), ...Object.keys(COMMANDS)]; + const rows: Row[] = all.map(command => { + const c = DESKTOP_COVERAGE[command]; + if (!c) return { command, status: 'gap', where: '', methods: [], problems: ['no entry in cli/lib/desktop-coverage.ts'] }; + if ('not' in c) return { command, status: 'not-for-desktop', where: c.not, methods: [], problems: c.not.trim() ? [] : ['not-for-desktop without a reason'] }; + const problems = c.methods.map(reachable).filter((p): p is string => !!p); + if (!c.methods.length && !(c.owner && toolboxShown && OWNER_STEPS.length)) problems.push('no method and no owner step'); + return { command, status: problems.length ? 'gap' : 'covered', where: c.where, methods: c.methods, ...(c.owner ? { owner: c.owner } : {}), problems }; + }); + return { rows, extra: Object.keys(DESKTOP_COVERAGE).filter(k => !all.includes(k)) }; +} + +export function render(rows: Row[]): string { + const n = (s: Row['status']): number => rows.filter(r => r.status === s).length; + const cell = (s: string): string => s.replace(/\|/g, '\\|'); + return [ + '# Desktop coverage', + '', + 'Generated by `bun tools/gen-desktop-coverage.ts` from `cli/lib/desktop-coverage.ts`; do not edit by hand.', + 'Every CLI command (cli/commands.ts) and the desktop place that runs it. "covered" means each method listed exists', + '(serve.ts, or a host command `host:`) and the window calls it; tests/desktop-coverage.test.ts fails on a gap.', + 'Owner-only parts are owner actions in the window or owner steps with their terminal command (More tools).', + '', + `**${rows.length} commands:** ${n('covered')} covered, ${n('gap')} gaps, ${n('not-for-desktop')} not for the desktop.`, + '', + '| command | status | where in the window | methods | owner step |', + '|---|---|---|---|---|', + ...rows.map(r => `| \`${r.command}\` | ${r.status} | ${cell(r.where || r.problems.join('; '))} | ${r.methods.map(m => `\`${m}\``).join(', ')} | ${cell(r.owner ?? '')} |`), + '', + ].join('\n'); +} + +if (import.meta.main) { + const { rows } = analyze(); + const md = render(rows); + if (process.argv.includes('--check')) { + let cur = ''; + try { cur = readFileSync(OUT, 'utf8'); } catch { /* missing */ } + if (cur !== md) { console.error('docs/desktop-coverage.md is stale: run bun tools/gen-desktop-coverage.ts'); process.exit(1); } + } else writeFileSync(OUT, md); + const gaps = rows.filter(r => r.status === 'gap'); + for (const g of gaps) console.log(`gap: ${g.command}: ${g.problems.join('; ')}`); + console.log(`${rows.length} commands, ${rows.filter(r => r.status === 'covered').length} covered, ${gaps.length} gaps`); +} From eebb3a830b8089ff234cfa88c86392e35db6a705 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:03:34 +0700 Subject: [PATCH 060/344] docs: desktop.md (coverage map, More tools tab), CHANGELOG Unreleased --- CHANGELOG.md | 15 +++++++++++++++ docs/desktop.md | 18 +++++++++++++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 26b8f1e..cfaa7fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,21 @@ - **One-line errors for missing required values:** `apple listing` without `--version` says "--version is required (storebound apple status shows the editable version)"; the same for privacy-manifest `--ios`, adhoc export `--archive`, edit `--ops` and resubmit `--build`. A flag given without a value counts as missing. +- **Every CLI command is reachable in the desktop app.** A new **More tools** tab gives each command without a + screen of its own (play build / upload / share / app-id, apple build / upload / signing / adhoc, bundle, IAP review, + Header and Search Results, custom product pages, in-app events, pre-orders, what's new, listing translate / check, + ASO rank / competitors / suggest, captures, fonts, JPEG copies, triage, originality, privacy manifest, ads scan, + Apple Ads reports, web, RevenueCat diff, PPP sheet, workflows, install for an AI tool) one typed form with the + command's own options, built from the method's schema; never a free-text shell. Reads run there; writes show the + dry run, then the native dialog, then run with the confirm token. Owner-only steps (offer codes, win-back, + promoted enable, pre-order enable / end, custom page and event submit, TestFlight expire, Apple Ads changes, + RevenueCat sync, shots login) are listed with their terminal command to copy. New desktop methods in `serve`: + `play.build`, `play.upload`, `play.share`, `play.app_id`, `apple.build`, `apple.upload`, `apple.signing_ensure`, + `apple.adhoc_register`, `apple.adhoc_export`, `shots.fonts`, `shots.jpeg`, `agent.install`. +- **docs/desktop-coverage.md** (generated by `bun tools/gen-desktop-coverage.ts` from `cli/lib/desktop-coverage.ts`): + every command with its window place and methods; 92 commands, 88 covered, 4 not for the desktop (`mcp`, `serve`, + `desktop`, `api`). `tests/desktop-coverage.test.ts` fails when a command has no place, names a method the window + never calls, or is marked not-for-desktop without being on the short list. ## 0.8.21 · 2026-10-20 diff --git a/docs/desktop.md b/docs/desktop.md index f13f7f0..795c2c3 100644 --- a/docs/desktop.md +++ b/docs/desktop.md @@ -349,6 +349,22 @@ and account names only), the same file the desktop reads. A workspace account's | `inspect --listing-text --json` (new) | Listings export (Markdown) | | `import fastlane` | First-run guide, App folders, store-only app banner (`project_import_fastlane`: plan in a native dialog first) | +**Every command, one place (desktop-coverage.md).** `cli/lib/desktop-coverage.ts` maps each CLI command to the +window place and the methods that run it (serve methods, or `host:` commands of src-tauri); `bun +tools/gen-desktop-coverage.ts` writes [desktop-coverage.md](desktop-coverage.md) from it and +`tests/desktop-coverage.test.ts` fails when a command has no place, names a method the window never calls, or is +"not for the desktop" outside the short list (`mcp`, `serve`, `desktop`, `api`). A new command needs an entry there. + +**More tools tab** (`src/screens/tabs/Tools.tsx`). The commands without a screen of their own (`TOOLBOX` in the +coverage map: build and upload, ad-hoc devices, store features, text and ASO, captures, quality, Apple Ads, workflows +and AI tools) get one form each, built from the method's argument schema (`system.methods`): enums as selects, +booleans as checkboxes, strings with the sidecar's pattern; empty fields keep the command's defaults. Never a +free-text shell: the sidecar validates every value. Reads run and show the command's output; writes go through +`useWrite` (dry run, native dialog, confirm token; build, upload, signing and device registration have their own +question answered by that token). Owner-only steps without a window button (`OWNER_STEPS`: offer codes, win-back, +promoted enable, pre-order enable / end, custom page and event submit, TestFlight expire, Apple Ads changes, +RevenueCat sync, shots login) are listed with their terminal command and a Copy button. + **Exports.** Every screen registers what it can save (`src/ui/Exports.tsx`): the "Export" menu at the top right of the top bar and the "Export" group of the command palette. Files: prices CSV (the `prices import` format), listings (md), reviews CSV, health report (md), catalog parity (md), store readiness report (md), store declarations (md), @@ -375,7 +391,7 @@ note first. tracking, encryption, sign-in, contact), highlighted in amber, each with how to answer. - **First run.** The guide now starts with the studio (pick or create, with a colour), so the keys added two steps later land in it; the app step offers add / start / import from fastlane side by side. -- **Tabs.** Eleven app tabs fit 1440 px; narrower windows scroll the tab bar sideways instead of wrapping. +- **Tabs.** Twelve app tabs (More tools last) fit 1440 px; narrower windows scroll the tab bar sideways instead of wrapping. R&D on a fastlane importer and a RevenueCat adapter: `docs/research/fastlane-revenuecat.md`. From ca7289b1730ece28c10cf085e90dc46c1e400271 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 04:59:51 +0700 Subject: [PATCH 061/344] games: one config section for Game Center and Play Games Services (shared leaderboards and achievements); apple game-center (gameCenterDetails, gameCenterAppVersions, leaderboards, achievements and localizations, upsert by vendor id, read back); play games (Games Configuration API upsert, no POST retry); signing ensure adds GAME_CENTER when games.gameCenter --- cli/apple/game-center.ts | 135 ++++++++++++++ cli/apple/signing.ts | 8 +- cli/commands.ts | 2 + cli/data/flags.json | 16 ++ cli/lib/config.ts | 5 + cli/lib/game-services.ts | 380 +++++++++++++++++++++++++++++++++++++++ cli/lib/signing.ts | 8 +- cli/play/games.ts | 105 +++++++++++ 8 files changed, 653 insertions(+), 6 deletions(-) create mode 100644 cli/apple/game-center.ts create mode 100644 cli/lib/game-services.ts create mode 100644 cli/play/games.ts diff --git a/cli/apple/game-center.ts b/cli/apple/game-center.ts new file mode 100644 index 0000000..fa5649e --- /dev/null +++ b/cli/apple/game-center.ts @@ -0,0 +1,135 @@ +// Game Center through the App Store Connect API, from the `games` config section (cli/lib/game-services.ts). +// storebound apple game-center [status] [--dry] [--yes] [--json] +// status: read-only (App ID capability, Game Center detail, the editable version's switch, leaderboards and +// achievements on the store vs the config, the project's entitlement). Default: the upsert. Every write is a +// find-then-create (createOnce: a conflict or an unclear answer reads the store again, never a second create) or a +// PATCH of the fields that differ, so a re-run writes nothing. Nothing is deleted or archived; nothing is submitted +// (leaderboards and achievements go to review with the next app version, the owner's Submit for review). +import { findBundleId, readProjectEntitlements } from './signing'; +import { consoleLink } from '../lib/console-links'; +import type { Ctx } from '../lib/ctx'; +import { confirm, need } from '../lib/ctx'; +import { dryPlan } from '../lib/dry'; +import { type GcExisting, gcFindings, type ItemPlan, planGameCenter, planRows, usesGameCenter } from '../lib/game-services'; +import { done, log, warn } from '../lib/log'; +import { createOnce } from '../lib/upsert'; +import { type Asc, ascClient, type J } from './asc'; + +const TAG = 'game-center'; + +export interface GcState { + capability: boolean | null; + detail: string | null; + version: { id: string; versionString: string; enabled: boolean } | null; + leaderboards: GcExisting[]; + achievements: GcExisting[]; +} + +async function withLocs(c: Asc, list: J[], type: 'gameCenterLeaderboards' | 'gameCenterAchievements'): Promise { + const out: GcExisting[] = []; + for (const x of list) out.push({ id: x.id, attributes: x.attributes ?? {}, localizations: (await c.all(`/v1/${type}/${x.id}/localizations?limit=200`)).map((l: J) => ({ id: l.id, attributes: l.attributes ?? {} })) }); + return out; +} + +/** Everything Game Center has for the app (read-only). */ +export async function readGameCenter(c: Asc, bundleId: string): Promise { + const appId = await c.app(); + const b = await findBundleId(c, bundleId).catch(() => null); + const detail = (await c.maybe(`/v1/apps/${appId}/gameCenterDetail`))?.data?.id ?? null; + const v = await c.editableVersion(); + const version = v ? { id: v.id as string, versionString: String(v.attributes?.versionString ?? ''), enabled: !!(await c.maybe(`/v1/appStoreVersions/${v.id}/gameCenterAppVersion`))?.data } : null; + const leaderboards = detail ? await withLocs(c, await c.all(`/v1/gameCenterDetails/${detail}/gameCenterLeaderboards?limit=200`), 'gameCenterLeaderboards') : []; + const achievements = detail ? await withLocs(c, await c.all(`/v1/gameCenterDetails/${detail}/gameCenterAchievements?limit=200`), 'gameCenterAchievements') : []; + return { capability: b ? (b.capabilities as string[]).includes('GAME_CENTER') : null, detail, version, leaderboards, achievements }; +} + +export function stateSummary(s: GcState, plan: ItemPlan[]): Record { + return { + capability: s.capability, enabled: !!s.detail, detailId: s.detail, version: s.version, + leaderboards: s.leaderboards.length, achievements: s.achievements.length, + changes: plan.filter(p => p.action !== 'keep' || p.locales.some(l => l.action !== 'keep')).map(p => `${p.kind} ${p.id}: ${p.action}`), + }; +} + +export async function run(ctx: Ctx): Promise { + const { config, root } = ctx.loaded; + const a = ctx.args; + const sub = a._[0] ?? 'sync'; + if (!['sync', 'status'].includes(sub)) throw new Error('usage: storebound apple game-center [status] [--dry] [--yes] [--json]'); + if (!usesGameCenter(config)) throw new Error('games.gameCenter is not true in storebound.config.ts (game-services skill): nothing to do'); + const bundleId = need(config.apple?.bundleId, 'apple.bundleId'); + const c = await ascClient(root, bundleId, config.apple?.appId); + const appId = await c.app(); + const s = await readGameCenter(c, bundleId); + const g = config.games!; + const plan = planGameCenter(g, config.languages, s); + const project = gcFindings(config, readProjectEntitlements(root)); + + if (a.has('json')) { console.log(JSON.stringify({ ...stateSummary(s, plan), project, plan }, null, 2)); if (sub === 'status') return; } + if (s.capability === false) warn(TAG, `the App ID ${bundleId} has no GAME_CENTER capability: storebound apple signing ensure --dry, then without --dry (games.gameCenter adds it)`); + if (s.capability === null) warn(TAG, `bundle id ${bundleId} not found in Certificates, Identifiers & Profiles: storebound apple bundle`); + for (const f of project) (f.level === 'ok' ? log : warn)(TAG, `${f.msg}${f.fix ? ` (${f.fix})` : ''}`); + + const rows = [ + { item: 'Game Center (app)', action: s.detail ? 'keep' : 'create', detail: 'POST /v1/gameCenterDetails' }, + ...(s.version ? [{ item: `Game Center (version ${s.version.versionString})`, action: s.version.enabled ? 'keep' : 'create', detail: 'POST /v1/gameCenterAppVersions' }] : []), + ...planRows(plan), + ]; + if (!s.version) log(TAG, 'no editable App Store version: the version switch is set with the next one (storebound apple listing creates it)'); + if (sub === 'status' || a.has('dry')) { + if (!a.has('json')) console.log(dryPlan('apple game-center', rows)); + return; + } + if (rows.every(r => r.action === 'keep')) { done(TAG, `Game Center in step: ${s.leaderboards.length} leaderboard(s), ${s.achievements.length} achievement(s)`); return; } + console.log(dryPlan('apple game-center (to write)', rows).replace(/^dry run: /, '').replace(/; nothing written/, '')); + if (!(await confirm(ctx, 'Write these Game Center changes to App Store Connect? (nothing is submitted; they go to review with the next version)'))) return; + + let detail = s.detail; + if (!detail) { + const r = await createOnce({ what: 'Game Center detail', tag: TAG, unique: true, + create: async () => (await c.asc('POST', '/v1/gameCenterDetails', { data: { type: 'gameCenterDetails', relationships: { app: { data: { type: 'apps', id: appId } } } } })).data.id as string, + find: async () => (await c.maybe(`/v1/apps/${appId}/gameCenterDetail`))?.data?.id ?? null }); + detail = r.value; + log(TAG, `Game Center switched on for the app (${detail})`); + } + if (s.version && !s.version.enabled) { + const vid = s.version.id; + await createOnce({ what: `Game Center for version ${s.version.versionString}`, tag: TAG, unique: true, + create: async () => (await c.asc('POST', '/v1/gameCenterAppVersions', { data: { type: 'gameCenterAppVersions', relationships: { appStoreVersion: { data: { type: 'appStoreVersions', id: vid } } } } })).data.id as string, + find: async () => (await c.maybe(`/v1/appStoreVersions/${vid}/gameCenterAppVersion`))?.data?.id ?? null }); + log(TAG, `Game Center switched on for version ${s.version.versionString}`); + } + for (const p of plan) { + const type = p.kind === 'leaderboard' ? 'gameCenterLeaderboards' : 'gameCenterAchievements'; + const locType = p.kind === 'leaderboard' ? 'gameCenterLeaderboardLocalizations' : 'gameCenterAchievementLocalizations'; + const parentRel = p.kind === 'leaderboard' ? 'gameCenterLeaderboard' : 'gameCenterAchievement'; + let id = p.storeId; + if (p.action === 'create') { + const find = async () => (await c.all(`/v1/gameCenterDetails/${detail}/${type}?limit=200`)).find((x: J) => x.attributes?.vendorIdentifier === p.id)?.id ?? null; + id = (await createOnce({ what: `${p.kind} ${p.id}`, tag: TAG, unique: true, find, + create: async () => (await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { ...p.attributes, vendorIdentifier: p.id }, relationships: { gameCenterDetail: { data: { type: 'gameCenterDetails', id: detail } } } } })).data.id as string })).value; + log(TAG, `${p.kind} ${p.id}: created`); + } else if (p.action === 'update') { + const attrs = Object.fromEntries(p.changed.map(k => [k, p.attributes[k]])); + await c.asc('PATCH', `/v1/${type}/${id}`, { data: { type, id, attributes: attrs } }); + log(TAG, `${p.kind} ${p.id}: updated ${p.changed.join(', ')}`); + } + for (const l of p.locales) { + if (l.action === 'create') { + const pid = id!; + await createOnce({ what: `${p.kind} ${p.id} ${l.locale}`, tag: TAG, unique: true, + find: async () => (await c.all(`/v1/${type}/${pid}/localizations?limit=200`)).find((x: J) => x.attributes?.locale === l.locale)?.id ?? null, + create: async () => (await c.asc('POST', `/v1/${locType}`, { data: { type: locType, attributes: { locale: l.locale, ...l.attributes }, relationships: { [parentRel]: { data: { type, id: pid } } } } })).data.id as string }); + log(TAG, `${p.kind} ${p.id} ${l.locale}: created`); + } else if (l.action === 'update') { + await c.asc('PATCH', `/v1/${locType}/${l.id}`, { data: { type: locType, id: l.id, attributes: Object.fromEntries(l.changed.map(k => [k, l.attributes[k]])) } }); + log(TAG, `${p.kind} ${p.id} ${l.locale}: updated ${l.changed.join(', ')}`); + } + } + } + // read back: the store must now match the config (lists can lag right after a create: say so, do not fail) + const after = await readGameCenter(c, bundleId); + const left = planGameCenter(g, config.languages, after).filter(p => p.action !== 'keep' || p.locales.some(l => l.action !== 'keep')); + if (!after.detail || left.length) warn(TAG, `read back: ${!after.detail ? 'no Game Center detail yet; ' : ''}${left.map(p => `${p.kind} ${p.id}`).join(', ') || ''} not listed as written yet (App Store Connect lists lag after a create): run storebound apple game-center status in a minute`); + done(TAG, `Game Center: ${after.leaderboards.length} leaderboard(s), ${after.achievements.length} achievement(s); images and review go with the next version (${consoleLink('asc.version')})`); +} diff --git a/cli/apple/signing.ts b/cli/apple/signing.ts index 63ca35d..90f569c 100644 --- a/cli/apple/signing.ts +++ b/cli/apple/signing.ts @@ -167,7 +167,7 @@ export async function capabilityReport(c: Asc, config: ShipConfig, root: string) const bundleId = config.apple!.bundleId; const b = await findBundleId(c, bundleId); const appId = b ? (b.capabilities as string[]) : null; - const cfg = capabilitySpecs(config.apple?.signing).map(x => x.type); + const cfg = capabilitySpecs(config.apple?.signing, config.games?.gameCenter === true).map(x => x.type); const project = readProjectEntitlements(root); let build: BuildEntitlements | null = null; try { build = builtIpaEntitlements(root, config); } catch { /* unreadable IPA: compared without it */ } @@ -238,7 +238,7 @@ export async function run(ctx: Ctx): Promise { const bundles = new Map(); for (const id of ids) bundles.set(id, await findBundleId(c, id)); const main = bundles.get(bundleId); - const capPlan = main ? planCapabilities(main.id, main.capabilities ?? [], capabilitySpecs(s)) : { create: [], present: [], extra: [] }; + const capPlan = main ? planCapabilities(main.id, main.capabilities ?? [], capabilitySpecs(s, config.games?.gameCenter === true)) : { create: [], present: [], extra: [] }; const certs: ApiCert[] = await c.all(`/v1/certificates?filter[certificateType]=${certType}&limit=200`); const keys = localKeys(root); const identities = keychainIdentities(); @@ -258,7 +258,7 @@ export async function run(ctx: Ctx): Promise { } const state: SigningState = { bundleId, teamId: s.teamId ?? main?.attributes?.seedId ?? null, registered: !!main, - capabilities: { present: capPlan.present, missing: capabilitySpecs(s).filter(w => !capPlan.present.includes(w.type)).map(w => w.type), extra: capPlan.extra }, + capabilities: { present: capPlan.present, missing: capabilitySpecs(s, config.games?.gameCenter === true).filter(w => !capPlan.present.includes(w.type)).map(w => w.type), extra: capPlan.extra }, certificate: { type: certType, chosen: choice.cert?.attributes.name ?? choice.cert?.attributes.displayName ?? null, why: choice.why, onTeam: certs.filter(x => Date.parse(x.attributes.expirationDate ?? '') > Date.now()).length, withKey: choice.usable.length, limit: CERT_LIMIT[certType] ?? null }, profiles: ids.map(id => { @@ -330,7 +330,7 @@ export async function run(ctx: Ctx): Promise { if (plan.length && !(await confirm(ctx, `Create ${plan.length} item(s) on the Apple Developer team (${[capPlan.create.length && `${capPlan.create.length} capabilities`, needCert && `a ${certType} certificate`, plan.length - capPlan.create.length - (needCert ? 1 : 0) && 'provisioning profiles'].filter(Boolean).join(', ')})?`))) return; const responses = await execute(c.asc, capPlan.create, { dry: false, tag: TAG }); - if (capPlan.create.length) await checkCapabilitiesStuck(c, bundleId, capabilitySpecs(s).map(w => w.type), responses); + if (capPlan.create.length) await checkCapabilitiesStuck(c, bundleId, capabilitySpecs(s, config.games?.gameCenter === true).map(w => w.type), responses); if (!scope.profiles) { printCapabilityReport(await capabilityReport(c, config, root), TAG); cleanup(); diff --git a/cli/commands.ts b/cli/commands.ts index 96e27e3..b7a8f6a 100644 --- a/cli/commands.ts +++ b/cli/commands.ts @@ -61,6 +61,7 @@ export const COMMANDS: Record Promise, string]> = { 'play rollout': [() => import('./play/rollout'), 'staged rollout: --fraction x | --halt | --resume | --complete (asks first)'], 'play share': [() => import('./play/share'), 'internal app sharing: upload an AAB / APK, print the share link (asks first; --dry)'], 'play app-id': [() => import('./play/app-id'), '[--from-text ] [--write]: the Play Console app id (play.appId) by package name: known ids, else the agent steps (app list search / pages, capture) and the dry diff; --write saves it; read-only on Play'], + 'play games': [() => import('./play/games'), '[status] Play Games Services leaderboards + achievements from games (Games Configuration API upsert, matched by playId / name; drafts only, the owner publishes); --dry, asks first'], 'play next-version-code': [() => import('./play/next-version-code'), 'next free versionCode (prints the number)'], 'apple bundle': [() => import('./apple/bundle'), 'register the bundle id; finds the app record'], 'apple iap': [() => import('./apple/iap'), 'in-app purchases, localizations, price schedules, availability'], @@ -88,6 +89,7 @@ export const COMMANDS: Record Promise, string]> = { 'apple upload': [() => import('./apple/upload'), 'upload an IPA (App Store Connect API build upload, or --via altool), build number checked, waits for processing; --dry, asks first'], 'apple adhoc': [() => import('./apple/adhoc'), 'ad-hoc / release-testing: devices (list) | register (dry run, asks first) | options (ExportOptions.plist) | export --archive '], 'apple next-build': [() => import('./apple/next-build'), 'next safe build number (prints the number)'], + 'apple game-center': [() => import('./apple/game-center'), '[status] Game Center from games: the app\'s Game Center detail, the version switch, leaderboards + achievements with localizations (upsert by vendor id); App ID capability via signing ensure; --dry, asks first'], 'apple encryption': [() => import('./apple/encryption'), 'export compliance answer for builds, from the config'], 'apple ppo': [() => import('./apple/ppo'), 'Product Page Optimization: status | create --variant b | upload --variant b | start | stop (asks first)'], 'apple testflight': [() => import('./apple/testflight'), 'TestFlight: status | groups | testers (CSV in .storebound/) | what-to-test --build N | info | distribute --build N --group g [--submit-review] | wait --build N | expire --keep N|--older-than D (asks)'], diff --git a/cli/data/flags.json b/cli/data/flags.json index 16a092e..18751ba 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -98,6 +98,10 @@ "apple events": [ "name" ], + "apple game-center": [ + "keychain", + "no-install" + ], "apple iap": [], "apple iap-review": [], "apple iap-submit": [ @@ -584,6 +588,10 @@ "csv", "force" ], + "play games": [ + "achievements", + "leaderboards" + ], "play images": [ "include-drafts", "not-sent-for-review", @@ -906,6 +914,7 @@ "ws": [ "aab", "accounts", + "achievements", "add-for-review", "adgroup", "against", @@ -1007,6 +1016,7 @@ "landing", "lang", "languages", + "leaderboards", "limit", "listing-text", "listings", @@ -1209,6 +1219,9 @@ "storebound apple events upload --name \"...\" [--dry] event card (16:9) + details page (9:16) images per locale", "storebound apple events submit --name \"...\" [--dry] [--yes] into a review submission (the owner's step; asks)" ], + "apple game-center": [ + "storebound apple game-center [status] [--dry] [--yes] [--json]" + ], "apple iap": [ "storebound apple iap [--dry] [--only id1,id2]" ], @@ -1395,6 +1408,9 @@ "play data-safety": [ "storebound play data-safety [--csv out.csv] [--dry] [--force]" ], + "play games": [ + "storebound play games [status] [--dry] [--yes] [--json]" + ], "play images": [ "storebound play images [--dry] [--only en-US,de-DE] [--src store/renders] [--variant b] [--prune] [--include-drafts] [--not-sent-for-review]" ], diff --git a/cli/lib/config.ts b/cli/lib/config.ts index 147ca9d..0a02d45 100644 --- a/cli/lib/config.ts +++ b/cli/lib/config.ts @@ -1,5 +1,6 @@ // Per-project config (storebound.config.ts at the project root). Everything app-specific lives here; credentials never // do (see credentials.ts). The file default-exports a plain object; `import type { ShipConfig }` is optional. +import { type GamesConfig, validateGames } from './game-services'; import { consoleIdsFromConfig, consoleLink, setConsoleIds } from './console-links'; import { existsSync } from 'node:fs'; import { dirname, isAbsolute, join, resolve } from 'node:path'; @@ -555,6 +556,9 @@ export interface ShipConfig { /** What players / users can do with each other (chat, sharing, friends). Answers the Play IARC questionnaire's * Miscellaneous > user interaction questions (`console plan play-content-rating`). */ social?: SocialConfig; + /** Game Center and Play Games Services: the switches per store and ONE list of leaderboards and achievements mapped + * to both (`storebound apple game-center`, `storebound play games`; game-services skill). */ + games?: GamesConfig; languages: Language[]; play?: { packageName: string; defaultLanguage?: string; listing?: string; icon?: string; @@ -1102,6 +1106,7 @@ export function validateConfig(c: unknown): string[] { e.push(`accounts.signUp: a list of ${ACCOUNT_SIGN_UPS.map(x => `'${x}'`).join(' | ')}`); } if (cfg.reviewAccess && typeof cfg.reviewAccess.signInRequired !== 'boolean') e.push('reviewAccess.signInRequired: true | false'); + e.push(...validateGames(cfg.games, cfg.languages ?? [])); if (cfg.social !== undefined) { if (!cfg.social || typeof cfg.social.interaction !== 'boolean') e.push('social.interaction: true | false'); else for (const k of ['block', 'report', 'moderation', 'friendsOnly', 'sharesLocation'] as const) if (cfg.social[k] !== undefined && typeof cfg.social[k] !== 'boolean') e.push(`social.${k}: true | false`); diff --git a/cli/lib/game-services.ts b/cli/lib/game-services.ts new file mode 100644 index 0000000..82e63a7 --- /dev/null +++ b/cli/lib/game-services.ts @@ -0,0 +1,380 @@ +// Game Center (App Store) and Play Games Services (Google Play) from ONE config section, `games`: the switches per +// store plus one shared list of leaderboards and achievements, each mapped to both stores. Pure: config types and +// validation, the request bodies, the create / update / keep plans against what the store returned, and the project +// checks (Game Center entitlement, the PGS APP_ID resource and Gradle dependency). +// +// Why one shared list: a game ships the same leaderboards and achievements on both stores, the texts are per config +// language like products' listings, and only the ids differ (Apple: our vendor id; Play: an id Google generates). So +// `id` is the vendorIdentifier on the App Store, and `playId` is the generated Play id once known (until then the +// Play side is matched by its default-language name). +// +// Names verified in specs/app-store-connect.oas.json: gameCenterDetails (POST, app relationship; GET +// /v1/apps/{id}/gameCenterDetail), gameCenterAppVersions (POST with appStoreVersion; GET +// /v1/appStoreVersions/{id}/gameCenterAppVersion; the older /v1/apps/{id}/gameCenterEnabledVersions is deprecated), +// gameCenterLeaderboards / gameCenterAchievements v1 (POST, PATCH; GET /v1/gameCenterDetails/{id}/gameCenterLeaderboards +// and .../gameCenterAchievements) and their v1 localizations (GET /v1/gameCenterLeaderboards/{id}/localizations). +// Play: the Google Play Games Services Configuration API (gamesconfiguration.googleapis.com/games/v1configuration, +// achievementConfigurations / leaderboardConfigurations: list, insert, update; scope androidpublisher). Its discovery +// document is not pinned in specs/ (only androidpublisher and the reporting API are): shapes follow Google's reference. +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; +import { join, relative } from 'node:path'; +import type { Language, Platform, ShipConfig } from './config'; + +export const GC_FORMATS = ['INTEGER', 'DECIMAL_POINT_1_PLACE', 'DECIMAL_POINT_2_PLACE', 'DECIMAL_POINT_3_PLACE', 'ELAPSED_TIME_CENTISECOND', + 'ELAPSED_TIME_MINUTE', 'ELAPSED_TIME_SECOND', 'MONEY_POUND_DECIMAL', 'MONEY_POUND', 'MONEY_DOLLAR_DECIMAL', 'MONEY_DOLLAR', 'MONEY_EURO_DECIMAL', + 'MONEY_EURO', 'MONEY_FRANC_DECIMAL', 'MONEY_FRANC', 'MONEY_KRONER_DECIMAL', 'MONEY_KRONER', 'MONEY_YEN'] as const; +export type GcFormat = typeof GC_FORMATS[number]; + +export interface GameLeaderboard { + /** Your id: the App Store vendorIdentifier (letters, digits, . _ -; e.g. "com.example.game.highscore"). */ + id: string; + /** high (default): a higher score is better (Apple DESC, Play LARGER_IS_BETTER); low: lower is better (a race time). */ + sort?: 'high' | 'low'; + /** Score format, Apple's formatter names (default INTEGER); Play gets the matching NUMERIC / TIME_DURATION / CURRENCY. */ + format?: GcFormat; + /** best (default): the best score counts (Apple BEST_SCORE); recent: the latest (Apple only; Play keeps the best). */ + submission?: 'best' | 'recent'; + min?: number; + max?: number; + /** Texts per config language id: name (Apple: 32 characters; Play: 100) and an optional score suffix (" points"). */ + locales: Record; + /** The Play leaderboard id Google generated (CgkI...), once it exists. */ + playId?: string; + platforms?: Platform[]; +} + +export interface GameAchievement { + id: string; + /** Apple: 0-100 each, 1000 in total; Play: a multiple of 5, 1000 in total. */ + points: number; + /** Hidden until earned (Apple showBeforeEarned false; Play initialState HIDDEN). Default false. */ + hidden?: boolean; + /** Apple only: can be earned again. Default false. */ + repeatable?: boolean; + /** Play only: an incremental achievement with this many steps (Apple reports progress in percent from the game). */ + steps?: number; + /** name, description (before earned) and earned (after; default the description). */ + locales: Record; + playId?: string; + platforms?: Platform[]; +} + +export interface GamesConfig { + /** Game Center: the App ID capability, the app's Game Center detail and the version's Game Center switch. */ + gameCenter?: boolean; + /** Play Games Services: the games project id (the digits of games_APP_ID / com.google.android.gms.games.APP_ID). */ + playGames?: { appId?: string }; + leaderboards?: GameLeaderboard[]; + achievements?: GameAchievement[]; +} + +const ID_RE = /^[A-Za-z0-9._-]{1,100}$/; + +export function validateGames(g: GamesConfig | undefined, languages: Language[] = []): string[] { + if (g === undefined) return []; + const e: string[] = []; + if (!g || typeof g !== 'object') return ['games: an object { gameCenter, playGames, leaderboards, achievements }']; + if (g.gameCenter !== undefined && typeof g.gameCenter !== 'boolean') e.push('games.gameCenter: true | false'); + if (g.playGames !== undefined && (typeof g.playGames !== 'object' || (g.playGames.appId !== undefined && !/^\d{6,20}$/.test(String(g.playGames.appId))))) + e.push('games.playGames.appId: the digits of the Play Games Services project id (games_APP_ID)'); + const langs = new Set(languages.map(l => l.id)); + const seen = new Set(); + const checkId = (kind: string, id: unknown) => { + if (typeof id !== 'string' || !ID_RE.test(id)) e.push(`games.${kind}: id "${String(id)}" (letters, digits, . _ -; at most 100)`); + else if (seen.has(id)) e.push(`games.${kind}: id "${id}" is used twice (ids are unique across leaderboards and achievements)`); + else seen.add(id); + }; + const checkLocales = (kind: string, id: string, loc: Record | undefined, keys: string[]) => { + if (!loc || typeof loc !== 'object' || !Object.keys(loc).length) { e.push(`games.${kind} ${id}: locales needs at least one language`); return; } + for (const [k, v] of Object.entries(loc)) { + if (langs.size && !langs.has(k)) e.push(`games.${kind} ${id}: locales.${k} is not a language id of the config (${[...langs].join(', ')})`); + for (const f of keys) if (typeof (v as Record)?.[f] !== 'string' || !(v as Record)[f]!.trim()) e.push(`games.${kind} ${id}: locales.${k}.${f} is missing`); + const name = (v as { name?: string })?.name ?? ''; + if (name.length > 32 && g.gameCenter) e.push(`games.${kind} ${id}: locales.${k}.name is ${name.length} characters (Game Center: at most 32)`); + } + }; + for (const l of g.leaderboards ?? []) { + checkId('leaderboards', l?.id); + if (l.sort !== undefined && !['high', 'low'].includes(l.sort)) e.push(`games.leaderboards ${l.id}: sort high | low`); + if (l.format !== undefined && !GC_FORMATS.includes(l.format)) e.push(`games.leaderboards ${l.id}: format one of ${GC_FORMATS.slice(0, 4).join(', ')}, ...`); + if (l.submission !== undefined && !['best', 'recent'].includes(l.submission)) e.push(`games.leaderboards ${l.id}: submission best | recent`); + if (l.min !== undefined && l.max !== undefined && l.min >= l.max) e.push(`games.leaderboards ${l.id}: min must be below max`); + checkLocales('leaderboards', l.id, l.locales, ['name']); + } + let apple = 0, play = 0; + for (const a of g.achievements ?? []) { + checkId('achievements', a?.id); + if (!Number.isInteger(a.points) || a.points < 0 || a.points > 100) e.push(`games.achievements ${a.id}: points 0-100 (Game Center's limit per achievement)`); + else if (g.playGames && a.points % 5) e.push(`games.achievements ${a.id}: points ${a.points} is not a multiple of 5 (Play Games Services refuses it)`); + if (a.steps !== undefined && (!Number.isInteger(a.steps) || a.steps < 2 || a.steps > 10000)) e.push(`games.achievements ${a.id}: steps 2-10000 (an incremental Play achievement)`); + checkLocales('achievements', a.id, a.locales, ['name', 'description']); + if (!a.platforms || a.platforms.includes('ios')) apple += a.points || 0; + if (!a.platforms || a.platforms.includes('android')) play += a.points || 0; + } + if (g.gameCenter && apple > 1000) e.push(`games.achievements: ${apple} points in total (Game Center: at most 1000)`); + if (g.playGames && play > 1000) e.push(`games.achievements: ${play} points in total (Play Games Services: at most 1000)`); + if ((g.achievements?.length ?? 0) > 200 && g.playGames) e.push('games.achievements: more than 200 (Play Games Services: at most 200)'); + return e; +} + +export const onStore = (item: { platforms?: Platform[] }, store: 'apple' | 'play'): boolean => !item.platforms || item.platforms.includes(store === 'apple' ? 'ios' : 'android'); +export const usesGameCenter = (c: Pick): boolean => c.games?.gameCenter === true; +export const usesPlayGames = (c: Pick): boolean => !!c.games?.playGames; + +// ------------------------------------------------------------------------------------------- plans (both stores) + +export type Action = 'create' | 'update' | 'keep'; +export interface LocPlan { locale: string; action: Action; id?: string; attributes: Record; changed: string[] } +export interface ItemPlan { kind: 'leaderboard' | 'achievement'; id: string; action: Action; storeId?: string; attributes: Record; changed: string[]; locales: LocPlan[] } + +/** Fields of `want` that differ from `have` (JSON compare per field; a missing field on the store counts as different). */ +export function changedFields(have: Record | undefined, want: Record): string[] { + return Object.keys(want).filter(k => JSON.stringify(have?.[k] ?? null) !== JSON.stringify(want[k] ?? null)); +} + +const appleLocale = (languages: Language[], id: string): string | undefined => languages.find(l => l.id === id)?.apple; + +export function gcLeaderboardAttrs(l: GameLeaderboard): Record { + return { + referenceName: l.id, defaultFormatter: l.format ?? 'INTEGER', submissionType: l.submission === 'recent' ? 'MOST_RECENT_SCORE' : 'BEST_SCORE', + scoreSortType: l.sort === 'low' ? 'ASC' : 'DESC', + ...(l.min !== undefined ? { scoreRangeStart: String(l.min) } : {}), ...(l.max !== undefined ? { scoreRangeEnd: String(l.max) } : {}), + }; +} + +export function gcAchievementAttrs(a: GameAchievement): Record { + return { referenceName: a.id, points: a.points, showBeforeEarned: !a.hidden, repeatable: !!a.repeatable }; +} + +export interface GcExisting { id: string; attributes: Record; localizations: { id: string; attributes: Record }[] } + +/** Game Center plan: matched by vendorIdentifier; create what is missing, PATCH what differs, keep the rest. Archived + * items on the store are left alone (an archived vendor id cannot be reused; the plan names it). */ +export function planGameCenter(g: GamesConfig, languages: Language[], have: { leaderboards: GcExisting[]; achievements: GcExisting[] }): ItemPlan[] { + const out: ItemPlan[] = []; + const one = (kind: ItemPlan['kind'], id: string, attrs: Record, locs: Record>, list: GcExisting[]) => { + const cur = list.find(x => x.attributes.vendorIdentifier === id); + const locales: LocPlan[] = Object.entries(locs).map(([locale, want]) => { + const l = cur?.localizations.find(x => x.attributes.locale === locale); + const changed = changedFields(l?.attributes, want); + return { locale, action: !l ? 'create' : changed.length ? 'update' : 'keep', id: l?.id, attributes: want, changed: l ? changed : Object.keys(want) }; + }); + const changed = changedFields(cur?.attributes, attrs); + out.push({ kind, id, action: !cur ? 'create' : changed.length ? 'update' : 'keep', storeId: cur?.id, attributes: attrs, changed: cur ? changed : Object.keys(attrs), locales }); + }; + for (const l of (g.leaderboards ?? []).filter(x => onStore(x, 'apple'))) { + const locs: Record> = {}; + for (const [k, v] of Object.entries(l.locales)) { + const loc = appleLocale(languages, k); + if (loc) locs[loc] = { name: v.name, ...(v.suffix ? { formatterSuffix: v.suffix } : {}) }; + } + one('leaderboard', l.id, gcLeaderboardAttrs(l), locs, have.leaderboards); + } + for (const a of (g.achievements ?? []).filter(x => onStore(x, 'apple'))) { + const locs: Record> = {}; + for (const [k, v] of Object.entries(a.locales)) { + const loc = appleLocale(languages, k); + if (loc) locs[loc] = { name: v.name, beforeEarnedDescription: v.description, afterEarnedDescription: v.earned ?? v.description }; + } + one('achievement', a.id, gcAchievementAttrs(a), locs, have.achievements); + } + return out; +} + +// Play Games Services Configuration API bodies + +type Bundle = { kind: 'gamesConfiguration#localizedStringBundle'; translations: { kind: 'gamesConfiguration#localizedString'; locale: string; value: string }[] }; + +function bundle(languages: Language[], locales: Record, pick: (v: never) => string | undefined): Bundle { + const translations: Bundle['translations'] = []; + for (const [k, v] of Object.entries(locales)) { + const l = languages.find(x => x.id === k); + const codes = l?.play === undefined ? [] : Array.isArray(l.play) ? l.play : [l.play]; + const value = pick(v as never); + if (value) for (const locale of codes) translations.push({ kind: 'gamesConfiguration#localizedString', locale, value }); + } + return { kind: 'gamesConfiguration#localizedStringBundle', translations }; +} + +export function playAchievementBody(a: GameAchievement, languages: Language[]): Record { + return { + kind: 'gamesConfiguration#achievementConfiguration', + achievementType: a.steps ? 'INCREMENTAL' : 'STANDARD', initialState: a.hidden ? 'HIDDEN' : 'REVEALED', ...(a.steps ? { stepsToUnlock: a.steps } : {}), + draft: { + kind: 'gamesConfiguration#achievementConfigurationDetail', + name: bundle(languages, a.locales, (v: { name: string }) => v.name), + description: bundle(languages, a.locales, (v: { description: string }) => v.description), + pointValue: a.points, + }, + }; +} + +function playScoreFormat(f: GcFormat | undefined): Record { + const fmt = f ?? 'INTEGER'; + if (fmt.startsWith('ELAPSED_TIME')) return { numberFormatType: 'TIME_DURATION' }; + if (fmt.startsWith('MONEY_')) { + const cur = { POUND: 'GBP', DOLLAR: 'USD', EURO: 'EUR', FRANC: 'CHF', KRONER: 'DKK', YEN: 'JPY' }[fmt.replace(/^MONEY_|_DECIMAL$/g, '')] ?? 'USD'; + return { numberFormatType: 'CURRENCY', currencyCode: cur }; + } + const m = /DECIMAL_POINT_(\d)_PLACE/.exec(fmt); + return { numberFormatType: 'NUMERIC', numDecimalPlaces: m ? Number(m[1]) : 0 }; +} + +export function playLeaderboardBody(l: GameLeaderboard, languages: Language[]): Record { + const suffix = Object.values(l.locales).some(v => v.suffix) ? bundle(languages, l.locales, (v: { suffix?: string }) => v.suffix) : undefined; + return { + kind: 'gamesConfiguration#leaderboardConfiguration', + scoreOrder: l.sort === 'low' ? 'SMALLER_IS_BETTER' : 'LARGER_IS_BETTER', + ...(l.min !== undefined ? { scoreMin: String(l.min) } : {}), ...(l.max !== undefined ? { scoreMax: String(l.max) } : {}), + draft: { + kind: 'gamesConfiguration#leaderboardConfigurationDetail', + name: bundle(languages, l.locales, (v: { name: string }) => v.name), + scoreFormat: { ...playScoreFormat(l.format), ...(suffix ? { suffix: { other: suffix } } : {}) }, + }, + }; +} + +export interface PlayExisting { id: string; draft?: { name?: Bundle }; [k: string]: unknown } + +const defaultName = (x: PlayExisting, locale: string): string | undefined => x.draft?.name?.translations.find(t => t.locale === locale)?.value; + +/** Comparable part of a Play configuration (what we send, without ids / tokens / published / icon / sortRank). */ +function comparable(body: Record, have: PlayExisting | undefined): Record { + if (!have) return {}; + const draft = (have.draft ?? {}) as Record; + const want = body.draft as Record; + const out: Record = {}; + for (const k of Object.keys(body)) if (k !== 'draft') out[k] = have[k]; + out.draft = Object.fromEntries(Object.keys(want).map(k => [k, draft[k]])); + return out; +} + +/** Play plan: matched by playId, else by the name in the default language (Play ids are generated). Update = PUT of + * the whole configuration (Google's update replaces it); the existing icon / sort rank are kept in the body. */ +export function planPlayGames(g: GamesConfig, languages: Language[], defaultLocale: string, have: { leaderboards: PlayExisting[]; achievements: PlayExisting[] }): ItemPlan[] { + const out: ItemPlan[] = []; + const one = (kind: ItemPlan['kind'], item: GameLeaderboard | GameAchievement, body: Record, list: PlayExisting[]) => { + const name = (body.draft as { name: Bundle }).name.translations.find(t => t.locale === defaultLocale)?.value; + const cur = item.playId ? list.find(x => x.id === item.playId) : list.find(x => name !== undefined && defaultName(x, defaultLocale) === name); + const changed = cur ? changedFields(comparable(body, cur), body).flatMap(k => (k === 'draft' ? changedFields(comparable(body, cur).draft as Record, body.draft as Record).map(d => `draft.${d}`) : [k])) : Object.keys(body); + if (cur) { + // keep what Play has that we do not manage (icon, sort rank) + const d = cur.draft as Record | undefined; + body = { ...body, id: cur.id, draft: { ...(d?.iconUrl ? { iconUrl: d.iconUrl } : {}), ...(d?.sortRank !== undefined ? { sortRank: d.sortRank } : {}), ...(body.draft as object) } }; + } + out.push({ kind, id: item.id, action: !cur ? 'create' : changed.length ? 'update' : 'keep', storeId: cur?.id, attributes: body, changed, locales: [] }); + }; + for (const l of (g.leaderboards ?? []).filter(x => onStore(x, 'play'))) one('leaderboard', l, playLeaderboardBody(l, languages), have.leaderboards); + for (const a of (g.achievements ?? []).filter(x => onStore(x, 'play'))) one('achievement', a, playAchievementBody(a, languages), have.achievements); + return out; +} + +/** Dry-plan rows (cli/lib/dry.ts) of a plan. */ +export function planRows(plan: ItemPlan[]): { item: string; action: string; detail?: string }[] { + const rows: { item: string; action: string; detail?: string }[] = []; + for (const p of plan) { + rows.push({ item: `${p.kind} ${p.id}`, action: p.action, detail: p.action === 'keep' ? undefined : p.changed.join(', ') }); + for (const l of p.locales) rows.push({ item: `${p.kind} ${p.id} ${l.locale}`, action: l.action, detail: l.action === 'keep' ? undefined : l.changed.map(k => `${k}=${JSON.stringify(l.attributes[k])}`).join(', ') }); + } + return rows; +} + +// ------------------------------------------------------------------------------------------------ project checks + +export interface Finding { level: 'error' | 'warn' | 'ok'; id: string; msg: string; fix?: string } + +const SKIP = new Set(['node_modules', '.git', 'build', 'Pods', 'DerivedData', '.gradle', 'intermediates', 'generated', '.storebound']); + +function walk(dir: string, depth: number, pick: (f: string) => boolean, out: string[] = []): string[] { + let names: string[] = []; + try { names = readdirSync(dir); } catch { return out; } + for (const n of names) { + if (SKIP.has(n) || n.startsWith('.')) continue; + const f = join(dir, n); + let dirp = false; + try { dirp = statSync(f).isDirectory(); } catch { continue; } + if (dirp) { if (depth > 0) walk(f, depth - 1, pick, out); } else if (pick(f)) out.push(f); + } + return out; +} + +export interface PgsProject { + /** Gradle files that use play-services-games(-v2). */ + gradle: string[]; + /** Manifest meta-data com.google.android.gms.games.APP_ID: the raw value (literal or @string/name) and where. */ + manifest: { file: string; value: string } | null; + /** The resolved project id (digits) and the resource file it came from. */ + appId: { value: string; file: string } | null; +} + +/** Reads the Android project for Play Games Services: the Gradle dependency, the manifest meta-data and the string + * resource it points at (res/values/games-ids.xml or strings.xml). */ +export function readPgsProject(root: string): PgsProject { + const files = walk(root, 7, f => /\.gradle(\.kts)?$|AndroidManifest\.xml$|[\\/]res[\\/]values[^\\/]*[\\/][^\\/]+\.xml$/.test(f)); + const rel = (f: string) => relative(root, f); + const gradle = files.filter(f => /\.gradle(\.kts)?$/.test(f) && /play-services-games(-v2)?\b|games-v2/.test(readFileSync(f, 'utf8'))).map(rel); + let manifest: PgsProject['manifest'] = null; + for (const f of files.filter(x => x.endsWith('AndroidManifest.xml'))) { + const t = readFileSync(f, 'utf8'); + const m = /]*android:name\s*=\s*"com\.google\.android\.gms\.games\.APP_ID"[^>]*android:value\s*=\s*"([^"]+)"|]*android:value\s*=\s*"([^"]+)"[^>]*android:name\s*=\s*"com\.google\.android\.gms\.games\.APP_ID"/.exec(t); + if (m) { manifest = { file: rel(f), value: (m[1] ?? m[2])!.trim() }; break; } + } + let appId: PgsProject['appId'] = null; + const literal = manifest?.value.replace(/^\\ ?/, '').trim(); + if (literal && /^\d+$/.test(literal)) appId = { value: literal, file: manifest!.file }; + else { + const names = manifest && /^@string\//.test(manifest.value) ? [manifest.value.slice(8)] : ['game_services_project_id', 'app_id', 'games_APP_ID']; + for (const f of files.filter(x => /[\\/]res[\\/]values[\\/][^\\/]+\.xml$/.test(x))) { + const t = readFileSync(f, 'utf8'); + for (const n of names) { + const m = new RegExp(`]*name\\s*=\\s*"${n}"[^>]*>\\s*([^<]*?)\\s*`).exec(t); + if (m && /^\d+$/.test(m[1]!)) { appId = { value: m[1]!, file: rel(f) }; break; } + } + if (appId) break; + } + } + return { gradle, manifest, appId }; +} + +/** PGS project checks: the dependency, the manifest meta-data, the resource and the config's id. */ +export function pgsFindings(config: Pick, p: PgsProject, hasAndroid = true): Finding[] { + const out: Finding[] = []; + const want = config.games?.playGames?.appId; + if (!hasAndroid) return out; + if (!p.gradle.length && !usesPlayGames(config)) return out; + if (p.gradle.length && !usesPlayGames(config)) + out.push({ level: 'warn', id: 'pgs.config', msg: `the Android code uses Play Games Services (${p.gradle[0]}) but the config has no games.playGames`, fix: 'add games: { playGames: { appId: "" } } so storebound checks and syncs it' }); + if (usesPlayGames(config) && !p.gradle.length) + out.push({ level: 'warn', id: 'pgs.gradle', msg: 'games.playGames is set but no Gradle file uses com.google.android.gms:play-services-games-v2', fix: 'add implementation "com.google.android.gms:play-services-games-v2:" to the app module' }); + if (!p.manifest) out.push({ level: 'error', id: 'pgs.manifest', msg: 'no in AndroidManifest.xml: sign-in fails at runtime', fix: 'add inside ' }); + else if (!p.appId) out.push({ level: 'error', id: 'pgs.app-id', msg: `the manifest's APP_ID (${p.manifest.value}) points at no string resource with the project id`, fix: 'add res/values/games-ids.xml from Play Console > Play Games Services > Setup and management > Configuration > Get resources' }); + else if (want && p.appId.value !== String(want)) out.push({ level: 'error', id: 'pgs.app-id', msg: `games_APP_ID ${p.appId.value} (${p.appId.file}) differs from games.playGames.appId ${want}`, fix: 'use the resources of the games project linked to this app (Play Console > Play Games Services > Configuration)' }); + else out.push({ level: 'ok', id: 'pgs.app-id', msg: `games_APP_ID ${p.appId.value} (${p.appId.file})${want ? ' matches the config' : ''}` }); + if (p.appId && !want) out.push({ level: 'warn', id: 'pgs.config-id', msg: `games.playGames.appId is not set (the project has ${p.appId.value})`, fix: `set games.playGames.appId: "${p.appId.value}"` }); + return out; +} + +/** Game Center project checks: the entitlement in the iOS project (and that CODE_SIGN_ENTITLEMENTS references it). */ +export function gcFindings(config: Pick, ents: { file: string; caps: { cap: string }[]; referenced: boolean | null }[] | null): Finding[] { + if (!ents) return []; + const has = ents.filter(e => e.caps.some(c => c.cap === 'GAME_CENTER')); + if (!usesGameCenter(config)) return has.length ? [{ level: 'warn', id: 'gc.config', msg: `${has[0]!.file} has com.apple.developer.game-center but games.gameCenter is not true`, fix: 'set games: { gameCenter: true } so signing ensure and apple game-center keep the store in step' }] : []; + if (!has.length) return [{ level: 'error', id: 'gc.entitlement', msg: 'games.gameCenter is true but no .entitlements file has com.apple.developer.game-center', fix: 'Xcode > the app target > Signing & Capabilities > + Game Center (adds the key and CODE_SIGN_ENTITLEMENTS)' }]; + if (has.every(e => e.referenced === false)) return [{ level: 'error', id: 'gc.entitlement', msg: `${has[0]!.file} has the Game Center key but no CODE_SIGN_ENTITLEMENTS points at it`, fix: 'set CODE_SIGN_ENTITLEMENTS of the app target to that file' }]; + return [{ level: 'ok', id: 'gc.entitlement', msg: `com.apple.developer.game-center in ${has[0]!.file}` }]; +} + +/** Declarations reminders: a platform player id is a User ID on both stores. */ +export function gamesPrivacyFindings(config: Pick): Finding[] { + const out: Finding[] = []; + if (!usesGameCenter(config) && !usesPlayGames(config)) return out; + const ds = (config.dataSafety as { data?: Record } | undefined)?.data; + if (usesPlayGames(config) && ds && !ds.PSL_USER_ACCOUNT) + out.push({ level: 'warn', id: 'games.data-safety', msg: 'Play Games Services gives the game a player id: Data safety > Personal info > User IDs (PSL_USER_ACCOUNT) is not declared', fix: 'add PSL_USER_ACCOUNT to dataSafety.data (collected, app functionality), store-declarations skill' }); + const types = (config.appPrivacy as { types?: Record } | undefined)?.types; + if (usesGameCenter(config) && types && !types.USER_ID) + out.push({ level: 'warn', id: 'games.app-privacy', msg: 'Game Center gives the game a player id: App Privacy > Identifiers > User ID (USER_ID) is not declared', fix: 'add USER_ID (App Functionality, linked to the user) to appPrivacy.types, store-declarations skill' }); + return out; +} + +export const hasAndroidProject = (root: string): boolean => existsSync(join(root, 'android')) || walk(root, 3, f => f.endsWith('AndroidManifest.xml')).length > 0; diff --git a/cli/lib/signing.ts b/cli/lib/signing.ts index 6e598a1..8abefab 100644 --- a/cli/lib/signing.ts +++ b/cli/lib/signing.ts @@ -60,8 +60,12 @@ export function validateSigning(s: AppleSigning | undefined): string[] { return e; } -export const capabilitySpecs = (s: AppleSigning | undefined): CapabilitySpec[] => - (s?.capabilities ?? []).map(c => (typeof c === 'string' ? { type: c } : c)); +/** The capabilities the App ID must have: apple.signing.capabilities, plus GAME_CENTER when games.gameCenter is true. */ +export const capabilitySpecs = (s: AppleSigning | undefined, gameCenter = false): CapabilitySpec[] => { + const out = (s?.capabilities ?? []).map((c): CapabilitySpec => (typeof c === 'string' ? { type: c } : c)); + if (gameCenter && !out.some(c => c.type === 'GAME_CENTER')) out.push({ type: 'GAME_CENTER' }); + return out; +}; /** Capabilities to add (never removes one: removing can break a shipped feature; extra ones are reported). */ export function planCapabilities(bundleIdId: string, existing: string[], want: CapabilitySpec[]): { create: Req[]; present: string[]; extra: string[] } { diff --git a/cli/play/games.ts b/cli/play/games.ts new file mode 100644 index 0000000..83239a7 --- /dev/null +++ b/cli/play/games.ts @@ -0,0 +1,105 @@ +// Play Games Services leaderboards and achievements from the `games` config section (cli/lib/game-services.ts), +// through the Google Play Games Services Configuration API (games/v1configuration: achievementConfigurations, +// leaderboardConfigurations; list / insert / update; the Play service account, scope androidpublisher). +// storebound play games [status] [--dry] [--yes] [--json] +// The games project itself, its Android credential (app-signing SHA-1), the web OAuth client and publishing the +// configuration have no API: `storebound console plan play-games-services` (agent-first) and `console verify`. +// Matching: games.*[].playId, else the name in the default Play language (Play generates the ids). An insert is never +// sent twice (no 5xx retry on POST; an unclear answer reads the list again); update is a PUT of the whole +// configuration with the fields Play has and we do not manage (icon, sort rank) kept. Nothing is published: the +// owner's Publish in Play Console makes the draft live. +import { playServiceAccount } from '../lib/credentials'; +import type { Ctx } from '../lib/ctx'; +import { confirm, need } from '../lib/ctx'; +import { dryPlan } from '../lib/dry'; +import { hasAndroidProject, type ItemPlan, pgsFindings, type PlayExisting, planPlayGames, planRows, readPgsProject, usesPlayGames } from '../lib/game-services'; +import { PLAY_SCOPE, tokenSource } from '../lib/google-auth'; +import { errorBody } from '../lib/http'; +import { done, log, warn } from '../lib/log'; +import * as rt from '../lib/rt'; +import { AmbiguousWriteError, createOnce, retrySafe } from '../lib/upsert'; + +const TAG = 'play-games'; +export const GAMES_CONFIG_API = 'https://gamesconfiguration.googleapis.com/games/v1configuration'; + +export function gamesConfigClient(root: string) { + const token = tokenSource(playServiceAccount(root), PLAY_SCOPE); + async function call(method: string, path: string, body?: unknown): Promise { + const url = GAMES_CONFIG_API + path; + const safe = method !== 'POST' && retrySafe(method, url); + for (let attempt = 0; ; attempt++) { + const r = await fetch(url, { method, headers: { Authorization: 'Bearer ' + (await token()), ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) }, body: body === undefined ? undefined : JSON.stringify(body) }); + if (r.status === 429 && attempt < 4) { await r.body?.cancel(); await rt.sleep(2000 * (attempt + 1)); continue; } + if (r.status >= 500) { + if (safe && attempt < 4) { await r.body?.cancel(); await rt.sleep(2000 * (attempt + 1)); continue; } + const t = await r.text(); + if (!safe) throw new AmbiguousWriteError(`${method} ${path} -> ${r.status} ${errorBody(t, 300)}`, r.status); + throw new Error(`${method} ${path} -> ${r.status} ${errorBody(t, 300)}`); + } + const t = await r.text(); + if (!r.ok) throw new Error(`${method} ${path} -> ${r.status} ${errorBody(t, 800)}`); + return (t ? JSON.parse(t) : {}) as T; + } + } + async function list(kind: 'achievements' | 'leaderboards', appId: string): Promise { + const out: PlayExisting[] = []; + let page: string | undefined; + do { + const r = await call<{ items?: PlayExisting[]; nextPageToken?: string }>('GET', `/applications/${appId}/${kind}?maxResults=200${page ? `&pageToken=${encodeURIComponent(page)}` : ''}`); + out.push(...(r.items ?? [])); + page = r.nextPageToken; + } while (page); + return out; + } + return { call, list }; +} + +export const playDefaultLocale = (config: Ctx['loaded']['config']): string => config.play?.defaultLanguage ?? 'en-US'; + +export async function readPlayGames(c: ReturnType, appId: string): Promise<{ leaderboards: PlayExisting[]; achievements: PlayExisting[] }> { + return { leaderboards: await c.list('leaderboards', appId), achievements: await c.list('achievements', appId) }; +} + +const pending = (plan: ItemPlan[]) => plan.filter(p => p.action !== 'keep'); + +export async function run(ctx: Ctx): Promise { + const { config, root } = ctx.loaded; + const a = ctx.args; + const sub = a._[0] ?? 'sync'; + if (!['sync', 'status'].includes(sub)) throw new Error('usage: storebound play games [status] [--dry] [--yes] [--json]'); + if (!usesPlayGames(config)) throw new Error('games.playGames is not set in storebound.config.ts (game-services skill): nothing to do'); + need(config.play?.packageName, 'play.packageName'); + const pgs = hasAndroidProject(root) ? readPgsProject(root) : null; + const project = pgs ? pgsFindings(config, pgs) : []; + const appId = config.games!.playGames!.appId ?? pgs?.appId?.value; + for (const f of project) (f.level === 'ok' ? log : warn)(TAG, `${f.msg}${f.fix ? ` (${f.fix})` : ''}`); + if (!appId) throw new Error('games.playGames.appId is not set and the Android project has no games_APP_ID: create the games project first (storebound console plan play-games-services), then set the id'); + const c = gamesConfigClient(root); + const have = await readPlayGames(c, appId); + const locale = playDefaultLocale(config); + const plan = planPlayGames(config.games!, config.languages, locale, have); + if (a.has('json')) console.log(JSON.stringify({ appId, leaderboards: have.leaderboards.length, achievements: have.achievements.length, project, plan }, null, 2)); + if (sub === 'status' || a.has('dry')) { + if (!a.has('json')) console.log(dryPlan(`play games (project ${appId})`, planRows(plan))); + return; + } + if (!pending(plan).length) { done(TAG, `Play Games Services in step: ${have.leaderboards.length} leaderboard(s), ${have.achievements.length} achievement(s)`); return; } + console.log(dryPlan(`play games (project ${appId}, to write)`, planRows(plan)).replace(/^dry run: /, '').replace(/; nothing written/, '')); + if (!(await confirm(ctx, 'Write these Play Games Services drafts? (nothing is published; the owner publishes in Play Console)'))) return; + for (const p of pending(plan)) { + const kind = p.kind === 'leaderboard' ? 'leaderboards' : 'achievements'; + const name = (p.attributes.draft as { name: { translations: { locale: string; value: string }[] } }).name.translations.find(t => t.locale === locale)?.value; + if (p.action === 'create') { + const r = await createOnce({ what: `${p.kind} ${p.id}`, tag: TAG, + create: async () => (await c.call('POST', `/applications/${appId}/${kind}`, p.attributes)).id, + find: async () => (await c.list(kind, appId)).find(x => x.draft?.name?.translations.some(t => t.locale === locale && t.value === name))?.id ?? null }); + log(TAG, `${p.kind} ${p.id}: created as ${r.value} (set playId: "${r.value}" in the config to match it by id)`); + } else { + await c.call('PUT', `/${kind}/${encodeURIComponent(p.storeId!)}`, p.attributes); + log(TAG, `${p.kind} ${p.id}: updated ${p.changed.join(', ')}`); + } + } + const left = pending(planPlayGames(config.games!, config.languages, locale, await readPlayGames(c, appId))); + if (left.length) warn(TAG, `read back: ${left.map(p => `${p.kind} ${p.id}`).join(', ')} not shown as written yet; run storebound play games status in a minute`); + done(TAG, 'Play Games Services drafts written; publish them with the games project in Play Console (the owner\'s Publish button: storebound console plan play-games-services)'); +} From 5a5d7fd4e7af8e4053777cc6e5b050398f8675d0 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:02:16 +0700 Subject: [PATCH 062/344] console plan play-games-services: agent-first PGS setup (games project, Android credential with the app-signing SHA-1, web OAuth client, owner's Publish) with absolute Play Console and Google Cloud links, and console verify from the page text --- cli/lib/console-answers.ts | 3 +- cli/lib/console-games-plan.ts | 90 ++++++++++++++++++++++++++++++++ cli/lib/console-links.ts | 1 + cli/lib/console-play-plans.ts | 4 +- cli/lib/console-verify.ts | 2 + cli/lib/game-services.ts | 5 +- cli/mcp-tools.ts | 2 +- tests/console-play-plans.test.ts | 4 +- 8 files changed, 104 insertions(+), 7 deletions(-) create mode 100644 cli/lib/console-games-plan.ts diff --git a/cli/lib/console-answers.ts b/cli/lib/console-answers.ts index 499c0cf..a585937 100644 --- a/cli/lib/console-answers.ts +++ b/cli/lib/console-answers.ts @@ -28,7 +28,8 @@ export type FormId = typeof FORM_IDS[number]; /** Forms with a console plan only (the agent drives them; no scripted fill): Play Store settings (the App category the * API cannot set), the App content overview and its declarations without a fill form (cli/lib/console-play-plans.ts). */ export const PLAN_ONLY_FORM_IDS = ['play-store-settings', 'play-app-content', 'play-privacy-policy', 'play-ads', 'play-sign-in-details', - 'play-advertising-id', 'play-government-apps', 'play-financial-features', 'play-health-apps', 'play-production-countries', 'play-production-release'] as const; + 'play-advertising-id', 'play-government-apps', 'play-financial-features', 'play-health-apps', 'play-production-countries', 'play-production-release', + 'play-games-services'] as const; export type PlanOnlyFormId = typeof PLAN_ONLY_FORM_IDS[number]; /** Every form `console plan` / `console verify` know. */ export const PLAN_FORM_IDS = [...FORM_IDS, ...PLAN_ONLY_FORM_IDS] as const; diff --git a/cli/lib/console-games-plan.ts b/cli/lib/console-games-plan.ts new file mode 100644 index 0000000..48bb8cc --- /dev/null +++ b/cli/lib/console-games-plan.ts @@ -0,0 +1,90 @@ +// `storebound console plan play-games-services`: the Play Games Services setup has no API (the games project, its +// credentials, publishing). Only the leaderboards and achievements do (`storebound play games`). Agent-first like the +// other Play plans: the agent drives Play Console and Google Cloud console with its own browser tool, stops before +// Publish (the owner's button), then `console verify play-games-services --from-text -`. Pure. +// Modeled on Google's help ("Set up Play Games Services", "Create a credential", "Publish your game's changes"), +// not yet verified on a real console: the page paths and labels are where to start, the agent adapts. +// App signing SHA-1: the Play Developer API has no read of the app signing certificate SHA-1 (generatedapks.list only +// gives certificateSha256Hash), so the plan points at Play Console > App integrity > Play app signing. +import type { ShipConfig } from './config'; +import { consoleUrl, PLAY_CONSOLE } from './console-links'; +import { NEVER_PRESS, PLAY_NEVER_PRESS } from './console-forms'; +import type { PlanAnswer, PlanIds } from './console-plan'; +import { type Part, PLAY_MATERIAL_FACT } from './console-play-plans'; +import type { VerifyRow } from './console-verify'; +import { onStore } from './game-services'; + +export const GOOGLE_CLOUD_CREDENTIALS = 'https://console.cloud.google.com/apis/credentials'; +export const GOOGLE_CLOUD_CONSENT = 'https://console.cloud.google.com/apis/credentials/consent'; +export const PGS_PUBLISH = 'Publish'; + +const ids = (c: ShipConfig, p: PlanIds) => ({ playDeveloperId: p.playDeveloperId ?? c.play?.developerId, playAppId: p.playAppId ?? c.play?.appId }); + +export function playGamesPart(config: ShipConfig, p: PlanIds): Part { + const pkg = config.play?.packageName ?? '(play.packageName)'; + const i = ids(config, p); + const exact = !!(i.playDeveloperId && i.playAppId); + const setup = consoleUrl('play.games-services', i), signing = consoleUrl('play.app-signing', i); + const g = config.games; + const pid = g?.playGames?.appId; + const ach = (g?.achievements ?? []).filter(a => onStore(a, 'play')).length; + const lb = (g?.leaderboards ?? []).filter(l => onStore(l, 'play')).length; + const a = (id: string, question: string, value: string | null, extra: Partial = {}): PlanAnswer => + ({ id, question, value, text: value ?? '(you decide)', status: value === null ? 'ask-owner' : 'certain', source: 'storebound.config.ts', ...extra }); + const answers: PlanAnswer[] = [ + a('project', 'Games project', pid ? `the existing project ${pid}` : 'a new one ("No, my game doesn\'t use Google APIs")', { where: 'Setup: the first question', control: 'radio', action: 'pick' }), + a('displayName', 'Display name', config.play?.name ?? config.app.name, { where: 'Properties', control: 'text', action: 'type' }), + a('package', 'Android credential: package name', pkg, { where: 'Credentials > Add credential > Android', control: 'select', action: 'choose' }), + a('sha1', 'OAuth client SHA-1', 'the App signing key certificate SHA-1 from Play app signing (not the upload key)', { where: `Google Cloud > Credentials > OAuth client ID (Android): ${signing}`, control: 'text', action: 'type' }), + a('webClient', 'Web OAuth client (server auth codes)', null, { note: 'Only when a game server exchanges server auth codes (requestServerSideAccess). Ask the owner; with no server, skip it.', where: 'Credentials > Add credential > Game server' }), + ]; + return { + title: 'Play Console + Google Cloud: Play Games Services setup (games project, credentials, publish)', + start: { url: setup, deepLink: exact, reach: exact ? [] : ['Pick the app (set play.developerId and play.appId for a deep link)', 'Grow users > Play Games Services > Setup and management > Configuration'] }, + steps: [ + { n: 1, text: `Open ${setup}. No games project yet: answer "No, my game doesn't use Google APIs" and press Create (a draft project; nothing is public). With games.playGames.appId set, check the page shows that project id.`, click: ['Create'], answers: ['project'] }, + { n: 2, text: 'Properties: Edit properties > display name (and the description / graphics the owner gave) > Save as draft.', click: ['Edit properties', 'Save as draft'], answers: ['displayName'] }, + { n: 3, text: `Google Cloud OAuth consent screen (once per Cloud project): ${GOOGLE_CLOUD_CONSENT}. If it is not configured, set it up as External with the app name and the support email; never press "Publish app" there without the owner.` }, + { n: 4, text: `App signing SHA-1: open ${signing} and copy "SHA-1 certificate fingerprint" of the App signing key certificate (Play re-signs installs with it). The upload key's SHA-1 is only for builds you install yourself (an optional second credential).` }, + { n: 5, text: `Credentials > Add credential > Android: pick ${pkg}; it links to an OAuth client in Google Cloud. Create it at ${GOOGLE_CLOUD_CREDENTIALS} > Create credentials > OAuth client ID > Android (package ${pkg}, the SHA-1 of step 4) > Create, then back in Play Console pick that client > Save changes.`, click: ['Add credential', 'Save changes'], answers: ['package', 'sha1'] }, + { n: 6, text: `Only with a game server (ask-owner): Add credential > Game server: create a Web application OAuth client at ${GOOGLE_CLOUD_CREDENTIALS}, pick it, Save changes. Its client id goes into the game's requestServerSideAccess; the client secret stays on the server (never in chat or files here).`, answers: ['webClient'] }, + { n: 7, text: 'Copy the project id (Configuration page, "Project ID" / Get resources): write it to games.playGames.appId, and put the resources XML into android/app/src/main/res/values/games-ids.xml. `storebound check` then compares it with the manifest\'s com.google.android.gms.games.APP_ID.' }, + { n: 8, text: `Leaderboards (${lb}) and achievements (${ach}) come from the config: run \`storebound play games --dry\`, then without --dry (the Configuration API; drafts only). Play needs at least 5 achievements before it publishes the games project.` }, + { n: 9, text: 'Testers: Play Games Services > Testers lists who can sign in before publishing (the owner adds them; storebound never invites testers).' }, + { n: 10, text: `Stop before "${PGS_PUBLISH}" (Review and publish): the owner presses it. Then read the page text and pipe it to \`storebound console verify play-games-services --from-text -\`.` }, + ], + answers, + final: PGS_PUBLISH, + neverPress: [...new Set([PGS_PUBLISH, 'Publish changes', 'Publish app', 'Delete', 'Unlink', ...PLAY_NEVER_PRESS, ...NEVER_PRESS])], + allowed: [ + { button: 'Create', class: 'navigation', where: 'Setup: creates the draft games project (not public)' }, + { button: 'Edit properties / Add credential / Create credentials', class: 'navigation', where: 'Play Console and Google Cloud console' }, + { button: 'Save as draft / Save changes', class: 'draft-save', where: 'Play Games Services pages: drafts until the owner publishes' }, + { button: 'Create (OAuth client ID)', class: 'draft-save', where: `${GOOGLE_CLOUD_CREDENTIALS}: an OAuth client (private to the Cloud project)` }, + ], + uiFacts: [ + 'Modeled on Google\'s Play Games Services help (not verified on a real console yet): Grow users > Play Games Services > Setup and management > Configuration; Credentials and Properties are sections of that page; Review and publish has the Publish button.', + 'The Android credential needs the SHA-1 of the key that signs what players install: with Play app signing that is the App signing key certificate (Test and release > App integrity > Play app signing), not the upload key. The Play Developer API gives only SHA-256 hashes (generatedapks.list), so the SHA-1 is read from that page.', + 'A games project links one Google Cloud project; linking a different one later is not possible from the page: check the project id before Create.', + PLAY_MATERIAL_FACT, + `Absolute pages: ${PLAY_CONSOLE} (Play Console), ${GOOGLE_CLOUD_CREDENTIALS} (OAuth clients), ${GOOGLE_CLOUD_CONSENT} (consent screen).`, + ], + verify: { command: 'storebound console verify play-games-services --from-text -', source: 'page-text', capture: 'document.querySelector("main")?.innerText ?? document.body.innerText', + expect: ['The Configuration page shows the project id of games.playGames.appId', `An Android credential for ${pkg}`, 'The status is ready to publish or published'] }, + guidance: ['Open: Grow users > Play Games Services > Setup and management > Configuration', `Then: ${GOOGLE_CLOUD_CREDENTIALS} for the OAuth clients`], + }; +} + +/** Page text of the Configuration page vs the config. */ +export function verifyPlayGames(config: ShipConfig, text: string): VerifyRow[] { + const rows: VerifyRow[] = []; + const pid = config.games?.playGames?.appId; + const pkg = config.play?.packageName; + if (pid) rows.push({ item: 'project id', expected: pid, seen: text.includes(pid) ? pid : '(not on the page)', status: text.includes(pid) ? 'match' : 'mismatch' }); + else rows.push({ item: 'project id', expected: 'games.playGames.appId', seen: (/\b\d{10,14}\b/.exec(text) ?? ['?'])[0], status: 'ask-owner', note: 'set games.playGames.appId to the project id shown on the page' }); + if (pkg) rows.push({ item: 'Android credential', expected: pkg, seen: text.includes(pkg) ? pkg : '(no credential with the package)', status: text.includes(pkg) ? 'match' : 'mismatch' }); + const published = /\bPublished\b/i.test(text) && !/not published|unpublished/i.test(text); + const ready = /ready to publish|ready for publishing/i.test(text); + rows.push({ item: 'status', expected: 'ready to publish or published', seen: published ? 'published' : ready ? 'ready to publish' : '(neither)', status: published || ready ? 'match' : 'mismatch', ...(ready && !published ? { note: 'the owner presses Publish' } : {}) }); + return rows; +} diff --git a/cli/lib/console-links.ts b/cli/lib/console-links.ts index 748874c..b5bb7ae 100644 --- a/cli/lib/console-links.ts +++ b/cli/lib/console-links.ts @@ -64,6 +64,7 @@ export const CONSOLE_PAGES = { 'play.internal-testing': { store: 'play', label: 'Play Console > Test and release > Internal testing', scope: 'app', path: 'tracks/internal-testing' }, 'play.publishing': { store: 'play', label: 'Play Console > Publishing overview', scope: 'app', path: 'publishing' }, 'play.app-signing': { store: 'play', label: 'Play Console > Test and release > App integrity > Play app signing', scope: 'app', path: 'keymanagement' }, + 'play.games-services': { store: 'play', label: 'Play Console > Grow users > Play Games Services > Setup and management > Configuration', scope: 'app', path: 'play-games-services/setup' }, 'play.bundle-explorer': { store: 'play', label: 'Play Console > Test and release > App bundle explorer', scope: 'app', path: 'bundle-explorer-selector' }, 'play.products': { store: 'play', label: 'Play Console > Monetize with Play > Products > In-app products', scope: 'app', path: 'managed-products' }, 'play.subscriptions': { store: 'play', label: 'Play Console > Monetize with Play > Products > Subscriptions', scope: 'app', path: 'subscriptions' }, diff --git a/cli/lib/console-play-plans.ts b/cli/lib/console-play-plans.ts index 205c378..da3a979 100644 --- a/cli/lib/console-play-plans.ts +++ b/cli/lib/console-play-plans.ts @@ -19,6 +19,7 @@ import type { PlanFormId, PlanOnlyFormId } from './console-answers'; import { NEVER_PRESS, PLAY_NEVER_PRESS, playAppList } from './console-forms'; import type { ConsolePlan, PlanAnswer, PlanIds, PlanStatus, PlanStep } from './console-plan'; import { AD_ID_PERMISSION, type ProjectSignals } from './project-signals'; +import { playGamesPart } from './console-games-plan'; const PLAY = 'https://play.google.com/console'; @@ -73,7 +74,7 @@ function start(config: ShipConfig, p: PlanIds, path: string, reach: string[]): C const appContentReach = (card: string) => ['Policy and programs > App content (/app-content/overview)', `the "${card}" card: the button aria-label="${startLabel(card)}" (or its Manage / Edit link)`]; -interface Part { +export interface Part { title: string; start: ConsolePlan['start']; steps: PlanStep[]; @@ -514,6 +515,7 @@ export function playOnlyPart(form: Exclude, case 'play-government-apps': return government(config, p); case 'play-financial-features': return featureCard(config, p, 'finance'); case 'play-health-apps': return featureCard(config, p, 'health'); + case 'play-games-services': return playGamesPart(config, p); } } diff --git a/cli/lib/console-verify.ts b/cli/lib/console-verify.ts index 6134fb6..b23359a 100644 --- a/cli/lib/console-verify.ts +++ b/cli/lib/console-verify.ts @@ -11,6 +11,7 @@ // apple-age-rating the API (ageRatingDeclaration) // play-content-rating, play-target-audience page text (summary pages: a label line, its answer on the same or the // next line). Modeled, not recorded: rows that cannot be found are "not found", never a match. +import { verifyPlayGames } from './console-games-plan'; import type { ShipConfig } from './config'; import { type Answer, consoleAnswers, type FormId, type PlanFormId, type PlanOnlyFormId, valueText } from './console-answers'; import { APP_CONTENT_CARDS, playOnlyPart, startLabel } from './console-play-plans'; @@ -427,6 +428,7 @@ export function verifyText(form: PlanFormId, config: ShipConfig, text: string): if (form === 'play-app-content') return verifyAppContent(text); if (form === 'play-production-countries') return verifyProductionCountries(config, text); if (form === 'play-production-release') return verifyProductionRelease(text); + if (form === 'play-games-services') return result(form, 'page-text', verifyPlayGames(config, text)); if (form === 'play-store-settings' || form === 'play-privacy-policy' || form === 'play-ads' || form === 'play-sign-in-details' || form === 'play-advertising-id' || form === 'play-government-apps' || form === 'play-financial-features' || form === 'play-health-apps') return verifyPlayDeclaration(form, config, text); switch (form) { diff --git a/cli/lib/game-services.ts b/cli/lib/game-services.ts index 82e63a7..9de1f7f 100644 --- a/cli/lib/game-services.ts +++ b/cli/lib/game-services.ts @@ -19,6 +19,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; import { join, relative } from 'node:path'; import type { Language, Platform, ShipConfig } from './config'; +import { consoleLink } from './console-links'; export const GC_FORMATS = ['INTEGER', 'DECIMAL_POINT_1_PLACE', 'DECIMAL_POINT_2_PLACE', 'DECIMAL_POINT_3_PLACE', 'ELAPSED_TIME_CENTISECOND', 'ELAPSED_TIME_MINUTE', 'ELAPSED_TIME_SECOND', 'MONEY_POUND_DECIMAL', 'MONEY_POUND', 'MONEY_DOLLAR_DECIMAL', 'MONEY_DOLLAR', 'MONEY_EURO_DECIMAL', @@ -347,8 +348,8 @@ export function pgsFindings(config: Pick, p: PgsProject, ha if (usesPlayGames(config) && !p.gradle.length) out.push({ level: 'warn', id: 'pgs.gradle', msg: 'games.playGames is set but no Gradle file uses com.google.android.gms:play-services-games-v2', fix: 'add implementation "com.google.android.gms:play-services-games-v2:" to the app module' }); if (!p.manifest) out.push({ level: 'error', id: 'pgs.manifest', msg: 'no in AndroidManifest.xml: sign-in fails at runtime', fix: 'add inside ' }); - else if (!p.appId) out.push({ level: 'error', id: 'pgs.app-id', msg: `the manifest's APP_ID (${p.manifest.value}) points at no string resource with the project id`, fix: 'add res/values/games-ids.xml from Play Console > Play Games Services > Setup and management > Configuration > Get resources' }); - else if (want && p.appId.value !== String(want)) out.push({ level: 'error', id: 'pgs.app-id', msg: `games_APP_ID ${p.appId.value} (${p.appId.file}) differs from games.playGames.appId ${want}`, fix: 'use the resources of the games project linked to this app (Play Console > Play Games Services > Configuration)' }); + else if (!p.appId) out.push({ level: 'error', id: 'pgs.app-id', msg: `the manifest's APP_ID (${p.manifest.value}) points at no string resource with the project id`, fix: `add res/values/games-ids.xml from ${consoleLink('play.games-services', '> Get resources')}` }); + else if (want && p.appId.value !== String(want)) out.push({ level: 'error', id: 'pgs.app-id', msg: `games_APP_ID ${p.appId.value} (${p.appId.file}) differs from games.playGames.appId ${want}`, fix: `use the resources of the games project linked to this app: ${consoleLink('play.games-services')}` }); else out.push({ level: 'ok', id: 'pgs.app-id', msg: `games_APP_ID ${p.appId.value} (${p.appId.file})${want ? ' matches the config' : ''}` }); if (p.appId && !want) out.push({ level: 'warn', id: 'pgs.config-id', msg: `games.playGames.appId is not set (the project has ${p.appId.value})`, fix: `set games.playGames.appId: "${p.appId.value}"` }); return out; diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index d6d5726..77cc405 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -39,7 +39,7 @@ export const notSentProp = { type: 'boolean', default: false, description: 'Comm /** Every form `console plan` / `console verify` know (cli/lib/console-answers.ts PLAN_FORM_IDS; a test keeps them equal). */ export const CONSOLE_PLAN_FORMS = ['apple-app-record', 'apple-age-rating', 'apple-app-privacy', 'play-app-record', 'play-content-rating', 'play-target-audience', 'play-store-settings', 'play-app-content', 'play-privacy-policy', 'play-ads', 'play-sign-in-details', 'play-advertising-id', 'play-government-apps', - 'play-financial-features', 'play-health-apps', 'play-production-countries', 'play-production-release']; + 'play-financial-features', 'play-health-apps', 'play-production-countries', 'play-production-release', 'play-games-services']; export const TOOLS: ToolDef[] = [ { name: 'check', title: 'Offline config check', command: ['check'], write: false, network: false, diff --git a/tests/console-play-plans.test.ts b/tests/console-play-plans.test.ts index 87acf89..b7c6c65 100644 --- a/tests/console-play-plans.test.ts +++ b/tests/console-play-plans.test.ts @@ -26,7 +26,7 @@ describe('agent-only Play plans: shape, URLs, never-press lists, the owner batch const slugs: Record = { 'play-store-settings': 'store-settings', 'play-app-content': 'app-content/overview', 'play-privacy-policy': 'app-content/privacy-policy', 'play-ads': 'app-content/ads-declaration', 'play-sign-in-details': 'app-content/testing-credentials', 'play-advertising-id': 'app-content/ad-id-declaration', - 'play-government-apps': 'app-content/government-apps', 'play-financial-features': 'app-content/finance', 'play-health-apps': 'app-content/health', + 'play-government-apps': 'app-content/government-apps', 'play-financial-features': 'app-content/finance', 'play-health-apps': 'app-content/health', 'play-games-services': 'play-games-services/setup', 'play-production-countries': 'tracks/production', 'play-production-release': 'tracks/production', }; for (const form of PLAN_ONLY_FORM_IDS) { @@ -45,7 +45,7 @@ describe('agent-only Play plans: shape, URLs, never-press lists, the owner batch for (const b of ['Publish', 'Submit', 'Send changes for review']) expect(p.buttons.neverPress).toContain(b); for (const b of p.buttons.allowed) expect(b.class).not.toBe('final-submit'); // an App content card's Save is the agent's (verified 2026-10-13); the owner's button is Send changes for review - if (form.startsWith('play-') && !['play-store-settings', 'play-app-content', 'play-production-countries', 'play-production-release'].includes(form)) { + if (form.startsWith('play-') && !['play-store-settings', 'play-app-content', 'play-production-countries', 'play-production-release', 'play-games-services'].includes(form)) { expect(p.buttons.final).toBe('Send changes for review'); expect(p.buttons.neverPress).not.toContain('Save'); expect(p.buttons.allowed).toContainEqual(expect.objectContaining({ button: 'Save', class: 'declaration-save' })); From 23f7c5a5eb4db2c8a27af3dba56440380e76e109 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:03:25 +0700 Subject: [PATCH 063/344] validate / check: Game Center entitlement vs App ID capability vs config, the PGS APP_ID resource vs Gradle and config, store state vs the games list, player id as User ID reminders (App Privacy USER_ID, Data safety PSL_USER_ACCOUNT) --- cli/check.ts | 6 ++++ cli/games-status.ts | 88 +++++++++++++++++++++++++++++++++++++++++++++ cli/validate.ts | 6 ++++ 3 files changed, 100 insertions(+) create mode 100644 cli/games-status.ts diff --git a/cli/check.ts b/cli/check.ts index d85776e..8b9368e 100644 --- a/cli/check.ts +++ b/cli/check.ts @@ -4,6 +4,7 @@ // storebound check everything above // storebound check --aso keyword audit of both listing files (App Store keyword field, Play stuffing); exit 1 on errors // --json structured result ({ ok, items, warnings, hints, problems } or { findings, errors }), exit 1 on problems +import { localGameFindings } from './games-status'; import { templateBlockers } from './lib/template-answers'; import { COPYRIGHT_MISSING, templatePlaceholders } from './lib/validate-rules'; import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; @@ -239,6 +240,11 @@ export async function run(ctx: Ctx): Promise { if (r.severity !== 'low' && !(config.scan?.ignore ?? []).some(i => i.rule === r.rule && (!i.store || i.store === r.store))) note(`${r.store}: ${r.title} (${r.guideline}; ${r.evidence.map(where).join(', ')}). ${r.fix}`); } catch { /* no project sources here */ } } + // Game Center entitlement, the PGS APP_ID resource, player-id declarations (offline) + if (config.games || config.apple || config.play) { + try { for (const f of localGameFindings(ctx.loaded)) { if (f.level === 'error') problems.push(`${f.store}: ${f.msg} (${f.fix ?? ''})`); else if (f.level === 'warn') note(`${f.store}: ${f.msg}${f.fix ? ` (${f.fix})` : ''}`); } } + catch { /* no project sources here */ } + } // Play steps without an API: the App category (Store settings) and the App content answers the owner still owes const pc = playConsoleReminders(config); for (const w of pc.warnings) note(w); diff --git a/cli/games-status.ts b/cli/games-status.ts new file mode 100644 index 0000000..2362309 --- /dev/null +++ b/cli/games-status.ts @@ -0,0 +1,88 @@ +// Game services status for both stores, read-only: what `validate`, `check`, the MCP tool and the desktop card show. +// Local part (no network): the Game Center entitlement, the PGS APP_ID resource and Gradle dependency, the player-id +// declaration reminders. Store part: Game Center (App ID capability, detail, version switch, counts, pending changes) +// and Play Games Services (counts, pending changes). +import { readGameCenter } from './apple/game-center'; +import { ascClient } from './apple/asc'; +import { readProjectEntitlements } from './apple/signing'; +import type { Loaded } from './lib/config'; +import { consoleUrl } from './lib/console-links'; +import { type Finding, gamesPrivacyFindings, gcFindings, hasAndroidProject, planGameCenter, planPlayGames, pgsFindings, readPgsProject, usesGameCenter, usesPlayGames } from './lib/game-services'; +import type { Finding as VFinding } from './lib/validate-rules'; +import { gamesConfigClient, playDefaultLocale, readPlayGames } from './play/games'; + +export interface GameServicesStatus { + apple: null | { capability: boolean | null; enabled: boolean; version: string | null; versionEnabled: boolean | null; leaderboards: number; achievements: number; + config: { leaderboards: number; achievements: number }; changes: string[]; error?: string }; + play: null | { appId: string | null; resource: string | null; leaderboards: number; achievements: number; + config: { leaderboards: number; achievements: number }; changes: string[]; error?: string }; + findings: (Finding & { store: 'apple' | 'play' })[]; + links: { label: string; url: string }[]; +} + +/** Offline findings (check, scan-like): entitlement, APP_ID resource, declarations reminders. */ +export function localGameFindings(loaded: Loaded): (Finding & { store: 'apple' | 'play' })[] { + const { config, root } = loaded; + const out: (Finding & { store: 'apple' | 'play' })[] = []; + if (config.apple) { let ents = null; try { ents = readProjectEntitlements(root); } catch { /* unreadable */ } out.push(...gcFindings(config, ents).map(f => ({ ...f, store: 'apple' as const }))); } + if (config.play && hasAndroidProject(root)) out.push(...pgsFindings(config, readPgsProject(root)).map(f => ({ ...f, store: 'play' as const }))); + for (const f of gamesPrivacyFindings(config)) out.push({ ...f, store: f.id === 'games.app-privacy' ? 'apple' : 'play' }); + return out; +} + +const changesOf = (plan: { kind: string; id: string; action: string; locales: { action: string; locale: string }[] }[]) => + plan.flatMap(p => [...(p.action !== 'keep' ? [`${p.kind} ${p.id}: ${p.action}`] : []), ...p.locales.filter(l => l.action !== 'keep').map(l => `${p.kind} ${p.id} ${l.locale}: ${l.action}`)]); + +export async function gameServicesStatus(loaded: Loaded, o: { apple?: boolean; play?: boolean } = {}): Promise { + const { config, root } = loaded; + const g = config.games ?? {}; + const findings = localGameFindings(loaded); + const out: GameServicesStatus = { apple: null, play: null, findings, links: [] }; + const count = (store: 'apple' | 'play') => ({ leaderboards: (g.leaderboards ?? []).filter(x => !x.platforms || x.platforms.includes(store === 'apple' ? 'ios' : 'android')).length, + achievements: (g.achievements ?? []).filter(x => !x.platforms || x.platforms.includes(store === 'apple' ? 'ios' : 'android')).length }); + if (config.apple && usesGameCenter(config) && o.apple !== false) { + out.links.push({ label: 'App Store Connect: the version page (Game Center section)', url: consoleUrl('asc.version') }); + try { + const c = await ascClient(root, config.apple.bundleId, config.apple.appId); + const s = await readGameCenter(c, config.apple.bundleId); + out.apple = { capability: s.capability, enabled: !!s.detail, version: s.version?.versionString ?? null, versionEnabled: s.version ? s.version.enabled : null, + leaderboards: s.leaderboards.length, achievements: s.achievements.length, config: count('apple'), changes: changesOf(planGameCenter(g, config.languages, s)) }; + } catch (e) { out.apple = { capability: null, enabled: false, version: null, versionEnabled: null, leaderboards: 0, achievements: 0, config: count('apple'), changes: [], error: (e as Error).message.slice(0, 300) }; } + } + if (config.play && usesPlayGames(config) && o.play !== false) { + out.links.push({ label: 'Play Console: Play Games Services configuration', url: consoleUrl('play.games-services') }, { label: 'Play Console: Play app signing (SHA-1)', url: consoleUrl('play.app-signing') }); + const res = hasAndroidProject(root) ? readPgsProject(root).appId : null; + const appId = g.playGames?.appId ?? res?.value ?? null; + const base = { appId, resource: res ? `${res.value} (${res.file})` : null, config: count('play') }; + if (!appId) out.play = { ...base, leaderboards: 0, achievements: 0, changes: [], error: 'no games project id yet (storebound console plan play-games-services)' }; + else try { + const have = await readPlayGames(gamesConfigClient(root), appId); + out.play = { ...base, leaderboards: have.leaderboards.length, achievements: have.achievements.length, changes: changesOf(planPlayGames(g, config.languages, playDefaultLocale(config), have)) }; + } catch (e) { out.play = { ...base, leaderboards: 0, achievements: 0, changes: [], error: (e as Error).message.slice(0, 300) }; } + } + return out; +} + +/** The status as validate findings (pure). */ +export function gameServicesFindings(s: GameServicesStatus): VFinding[] { + const out: VFinding[] = s.findings.map(f => ({ store: f.store, level: f.level === 'error' ? 'blocker' : f.level, code: f.id, msg: f.msg, ...(f.fix ? { fix: f.fix } : {}) }) as VFinding); + const a = s.apple; + if (a) { + if (a.error) out.push({ store: 'apple', level: 'warn', code: 'game-center', msg: `Game Center not read: ${a.error}` }); + else { + if (a.capability === false) out.push({ store: 'apple', level: 'blocker', code: 'game-center.capability', msg: 'games.gameCenter is true but the App ID has no GAME_CENTER capability: the build\'s profile will not allow Game Center', fix: 'storebound apple signing ensure --dry, then without --dry' }); + if (!a.enabled) out.push({ store: 'apple', level: 'blocker', code: 'game-center.detail', msg: 'Game Center is not switched on for the app in App Store Connect', fix: 'storebound apple game-center --dry, then without --dry' }); + if (a.versionEnabled === false) out.push({ store: 'apple', level: 'warn', code: 'game-center.version', msg: `version ${a.version} does not have Game Center switched on`, fix: 'storebound apple game-center' }); + if (a.changes.length) out.push({ store: 'apple', level: 'warn', code: 'game-center.sync', msg: `Game Center differs from the config: ${a.changes.slice(0, 6).join('; ')}${a.changes.length > 6 ? ` (+${a.changes.length - 6})` : ''}`, fix: 'storebound apple game-center --dry' }); + if (a.enabled && !a.changes.length) out.push({ store: 'apple', level: 'ok', code: 'game-center', msg: `Game Center on: ${a.leaderboards} leaderboard(s), ${a.achievements} achievement(s), in step with the config` }); + } + } + const p = s.play; + if (p) { + if (p.error) out.push({ store: 'play', level: 'warn', code: 'play-games', msg: `Play Games Services not read: ${p.error}`, fix: 'storebound console plan play-games-services' }); + else if (p.changes.length) out.push({ store: 'play', level: 'warn', code: 'play-games.sync', msg: `Play Games Services differs from the config: ${p.changes.slice(0, 6).join('; ')}`, fix: 'storebound play games --dry' }); + else out.push({ store: 'play', level: 'ok', code: 'play-games', msg: `Play Games Services project ${p.appId}: ${p.leaderboards} leaderboard(s), ${p.achievements} achievement(s), in step with the config` }); + if (!p.error && p.achievements < 5) out.push({ store: 'play', level: 'warn', code: 'play-games.achievements', msg: `${p.achievements} achievement(s) on Play: a games project needs at least 5 before it can be published`, fix: 'add achievements to games.achievements, then storebound play games' }); + } + return out; +} diff --git a/cli/validate.ts b/cli/validate.ts index b6acedf..73dbead 100644 --- a/cli/validate.ts +++ b/cli/validate.ts @@ -14,6 +14,7 @@ // Live apps: crash / ANR vitals (Play Reporting API) and App Store diagnostics, as in `storebound health`: over a Play // bad behavior threshold is a blocker, near it a warning; a store without vitals access is only noted. --no-health skips. import { templateBlockers } from './lib/template-answers'; +import { gameServicesFindings, gameServicesStatus } from './games-status'; import { ascClient, EDITABLE as APPLE_EDITABLE, type J } from './apple/asc'; import { allVersions, type AscPlatform, parsePlatform, platformOf, stateOf, versionsPath } from './apple/platform'; import { capabilityReport } from './apple/signing'; @@ -226,6 +227,11 @@ export async function run(ctx: Ctx): Promise { try { findings.push(...playRules({ ...(await collectPlay(ctx)), renders: local?.play })); } catch (e) { findings.push({ store: 'play', level: 'blocker', code: 'api', msg: (e as Error).message.slice(0, 400) }, ...rendersFindings('play', local?.play)); } } else if (a.has('play')) warn('validate', 'no play section in the config'); + // Game Center / Play Games Services: entitlement, APP_ID resource, store state vs the config + if (config.games && (config.games.gameCenter || config.games.playGames)) { + try { findings.push(...gameServicesFindings(await gameServicesStatus(ctx.loaded, { apple: both || a.has('apple'), play: both || a.has('play') }))); } + catch (e) { warn('validate', `game services: ${(e as Error).message}`); } + } // other platforms named in a store's listing text (App Store 2.3.10, Play Metadata): blockers (pitfall 77) try { for (const h of listingFileMentions(ctx.loaded, { apple: (both || a.has('apple')) && !!config.apple, play: (both || a.has('play')) && !!config.play })) From 3116c230ae08298391e4e1714289aef85e36fee1 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:03:58 +0700 Subject: [PATCH 064/344] scan: Play Games Services dependency without the APP_ID meta-data or resource (sign-in fails at runtime) --- cli/lib/scan/index.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/cli/lib/scan/index.ts b/cli/lib/scan/index.ts index dbc1e67..5b88cff 100644 --- a/cli/lib/scan/index.ts +++ b/cli/lib/scan/index.ts @@ -1,5 +1,6 @@ // `storebound scan` engine: detect the project, run the rejection-risk rules, propose the declarations. Offline and // read-only (the only write is `--write`, done by the command, never here). +import { pgsFindings, readPgsProject } from '../game-services'; import { withoutTemplate } from '../template-answers'; import { existsSync, readFileSync } from 'node:fs'; import { join, relative, resolve } from 'node:path'; @@ -63,6 +64,15 @@ export async function runScan(dir: string, o: { config?: string } = {}): Promise return { type: d.type, missing: [...new Set(missing)].join(', '), evidence: d.evidence }; }).filter(d => d.missing) : []; const findings = scanRules({ facts, config, configFile, listings, demoAccount: !!reviewDemoAccount(dir), labelGaps: declarations.labelGaps, dataMerges }); + // Play Games Services: the Gradle dependency without the APP_ID meta-data / resource fails sign-in at runtime + if (facts.android) { + try { + const pgs = readPgsProject(dir); + for (const g of pgsFindings(config ?? {}, pgs).filter(x => x.level === 'error' && !(config?.scan?.ignore ?? []).some(i => i.rule === x.id))) + findings.push({ rule: g.id, guideline: 'Play Games Services setup', store: 'play', severity: 'high', title: g.msg, evidence: [{ file: pgs.manifest?.file ?? pgs.gradle[0] ?? 'android', line: 1, text: pgs.manifest?.value ?? 'play-services-games-v2' }], + fix: g.fix ?? '', skill: 'game-services', ref: 'https://developer.android.com/games/pgs/android/android-start' }); + } catch { /* unreadable Android project */ } + } for (const f of findings) { const action = f.accepted ? undefined : scanFixAction(f.rule, { configPath, declarationsChanged: declarations.changed }); if (action) f.action = action; From 9f48dd57a4bd263d1266c790e067400641defbad Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:04:34 +0700 Subject: [PATCH 065/344] MCP: apple_game_center, apple_game_center_status, play_games, play_games_status (writes dry by default) --- cli/data/flags.json | 6 ++++++ cli/mcp-tools.ts | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/cli/data/flags.json b/cli/data/flags.json index 18751ba..d9d9fe4 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -359,6 +359,7 @@ "write" ], "check": [ + "achievements", "aso", "capacitor", "cordova", @@ -367,7 +368,10 @@ "expo", "flutter", "godot", + "keychain", + "leaderboards", "name", + "no-install", "react-native", "sku", "storefront", @@ -857,6 +861,7 @@ "play" ], "validate": [ + "achievements", "add-for-review", "allow-price-changes", "apple", @@ -873,6 +878,7 @@ "jobs", "keychain", "lang", + "leaderboards", "no-health", "no-install", "no-local", diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index 77cc405..eddb107 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -217,6 +217,18 @@ export const TOOLS: ToolDef[] = [ { name: 'apple_encryption', title: 'Export compliance answer', command: ['apple', 'encryption'], write: true, network: true, idempotent: true, description: 'Answer export compliance for builds from apple.usesNonExemptEncryption in the config (never guesses).', props: { build: { type: 'string', description: 'Build number (default: every build without an answer)' } }, args: i => opt('build', i.build) }, + { name: 'apple_game_center', title: 'Game Center sync', command: ['apple', 'game-center'], write: true, network: true, idempotent: true, + description: 'Game Center from the config\'s games section: switch it on for the app (gameCenterDetails) and the editable version (gameCenterAppVersions), upsert leaderboards and achievements with their localizations by vendor id (create / PATCH only what differs; never deletes or archives), then read back. Nothing is submitted: they go to review with the next version. The App ID capability is signing ensure\'s (terminal).', + args: () => [] }, + { name: 'apple_game_center_status', title: 'Game Center status', command: ['apple', 'game-center', 'status'], write: false, network: true, + description: 'Read-only: App ID GAME_CENTER capability, the app\'s Game Center detail, the version switch, leaderboards / achievements on the store vs games in the config (pending changes), the project\'s com.apple.developer.game-center entitlement.', + args: () => ['--json'] }, + { name: 'play_games', title: 'Play Games Services sync', command: ['play', 'games'], write: true, network: true, idempotent: true, + description: 'Play Games Services leaderboards and achievements from the config\'s games section through the Games Configuration API (insert / update drafts, matched by playId or the default-language name; inserts are never retried blindly). Nothing is published: the owner presses Publish in Play Console (console_plan play-games-services has the setup).', + args: () => [] }, + { name: 'play_games_status', title: 'Play Games Services status', command: ['play', 'games', 'status'], write: false, network: true, + description: 'Read-only: the games project id (config / games_APP_ID resource), leaderboards and achievements on Play vs the config (pending changes), the Android project\'s APP_ID meta-data and play-services-games-v2 dependency.', + args: () => ['--json'] }, { name: 'apple_phased_release', title: 'Phased release on / pause', command: ['apple', 'release'], write: true, network: true, idempotent: true, description: 'Turn on the 7-day phased release for the upcoming version, or pause an active one (pausing is not a rollback). Resume / complete / release are owner-only terminal commands.', props: { action: { type: 'string', enum: ['on', 'pause'] }, version: { type: 'string' }, platform }, required: ['action'], From a4c31e096be4531f5c41d91403dd22a741a01d0c Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:06:24 +0700 Subject: [PATCH 066/344] tests: game services on both stores against the fakes (capability ensure, Game Center enable and read-back, leaderboard / achievement create, update, no-op, lost answers), entitlement and APP_ID checks, PGS console plan URLs and verify, validate findings; fake Games Configuration API --- tests/game-services.test.ts | 210 +++++++++++++++++++++++++++++++++++ tests/helpers/fake-stores.ts | 47 +++++++- 2 files changed, 255 insertions(+), 2 deletions(-) create mode 100644 tests/game-services.test.ts diff --git a/tests/game-services.test.ts b/tests/game-services.test.ts new file mode 100644 index 0000000..8287d4f --- /dev/null +++ b/tests/game-services.test.ts @@ -0,0 +1,210 @@ +// Game Center and Play Games Services: config validation, the capability ensure, Game Center enable + read-back, the +// leaderboard / achievement upsert on both stores (create, update, no-op) against the fake stores, the entitlement +// and APP_ID checks, the PGS console plan's start URLs and the validate findings. Nothing reaches the network. +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test'; +import type { ShipConfig } from '../cli/lib/config'; +import { validateConfig } from '../cli/lib/config'; +import { capabilitySpecs, planCapabilities } from '../cli/lib/signing'; +import { gamesPrivacyFindings, gcFindings, pgsFindings, planGameCenter, playAchievementBody, playLeaderboardBody, readPgsProject, validateGames } from '../cli/lib/game-services'; +import { consolePlan } from '../cli/lib/console-plan'; +import { verifyText } from '../cli/lib/console-verify'; +import { gameServicesFindings, type GameServicesStatus } from '../cli/games-status'; +import { run as gameCenter } from '../cli/apple/game-center'; +import { run as playGames } from '../cli/play/games'; +import { upsertTiming } from '../cli/lib/upsert'; +import { ascEnv, BASE, capture, playEnv, project, restore } from './helpers/store-mock'; +import { installStores, type Stores, uninstallStores, writes } from './helpers/fake-stores'; + +let s: Stores; +beforeAll(() => { ascEnv(); playEnv(); }); +afterAll(restore); +beforeEach(() => { upsertTiming.waitMs = 0; s = installStores(); }); +afterEach(() => { uninstallStores(); }); + +const APP = '6400000101'; +const PGS = '123456789012'; +const GAME: ShipConfig = { + ...BASE, + app: { ...BASE.app, profile: 'game' }, + languages: [{ id: 'en', apple: 'en-US', play: 'en-US' }, { id: 'tr', apple: 'tr', play: 'tr-TR' }], + games: { + gameCenter: true, + playGames: { appId: PGS }, + leaderboards: [{ id: 'com.example.game.highscore', locales: { en: { name: 'High score', suffix: ' points' }, tr: { name: 'En yüksek skor' } } }], + achievements: [{ id: 'com.example.game.first-win', points: 10, locales: { en: { name: 'First win', description: 'Win a round.' } } }, + { id: 'com.example.game.secret', points: 20, hidden: true, locales: { en: { name: 'Secret', description: 'Find the secret room.', earned: 'You found it.' } } }], + }, +}; + +const run2 = async (fn: () => Promise) => { + const a = s.calls.length; + const r = await capture(fn); + if (r.exit) throw new Error(`exit ${r.exit}\n${r.out}\n${r.err}`); + return { ...r, writes: writes(s.calls.slice(a)).map(c => `${c.method} ${decodeURIComponent(c.path).replace(/\?.*/, '')}`) }; +}; + +describe('config', () => { + test('a valid games section passes; limits and ids are checked', () => { + expect(validateConfig(GAME)).toEqual([]); + const bad = validateGames({ gameCenter: true, playGames: {}, achievements: [{ id: 'a', points: 7, locales: { en: { name: 'A', description: 'x' } } }, { id: 'a', points: 101, locales: {} }] }, GAME.languages); + expect(bad.join('\n')).toContain('not a multiple of 5'); + expect(bad.join('\n')).toContain('used twice'); + expect(bad.join('\n')).toContain('points 0-100'); + expect(validateGames({ leaderboards: [{ id: 'x', locales: { de: { name: 'X' } } }] }, GAME.languages).join()).toContain('not a language id'); + }); + test('Play bodies: number format, hidden, suffix per language', () => { + expect(playLeaderboardBody({ id: 't', format: 'ELAPSED_TIME_SECOND', sort: 'low', locales: { en: { name: 'Time' } } }, GAME.languages)).toMatchObject({ scoreOrder: 'SMALLER_IS_BETTER', draft: { scoreFormat: { numberFormatType: 'TIME_DURATION' } } }); + expect(playAchievementBody(GAME.games!.achievements![1]!, GAME.languages)).toMatchObject({ initialState: 'HIDDEN', achievementType: 'STANDARD', draft: { pointValue: 20 } }); + }); +}); + +describe('capability ensure', () => { + test('games.gameCenter adds GAME_CENTER to what signing ensure wants, once', () => { + expect(capabilitySpecs(undefined, true)).toEqual([{ type: 'GAME_CENTER' }]); + expect(capabilitySpecs({ capabilities: ['GAME_CENTER', 'IN_APP_PURCHASE'] }, true).map(c => c.type)).toEqual(['GAME_CENTER', 'IN_APP_PURCHASE']); + const p = planCapabilities('bid-1', ['IN_APP_PURCHASE'], capabilitySpecs({ capabilities: ['IN_APP_PURCHASE'] }, true)); + expect(p.create.map(r => (r.body as { data: { attributes: { capabilityType: string } } }).data.attributes.capabilityType)).toEqual(['GAME_CENTER']); + expect(planCapabilities('bid-1', ['GAME_CENTER'], capabilitySpecs(undefined, true)).create).toEqual([]); + }); +}); + +describe('apple game-center (fake App Store Connect)', () => { + const version = () => s.asc.put({ type: 'appStoreVersions', id: 'ver-1', attributes: { versionString: '1.0.0', appVersionState: 'PREPARE_FOR_SUBMISSION', platform: 'IOS' }, rels: { app: APP } }); + + test('--dry writes nothing and names every create', async () => { + version(); + const r = await run2(() => gameCenter(project(GAME).ctx(['--dry']))); + expect(r.writes).toEqual([]); + expect(r.out).toContain('POST /v1/gameCenterDetails'); + expect(r.out).toContain('leaderboard com.example.game.highscore'); + }); + + test('enable + version + create, read back; the re-run writes nothing; a changed text is one PATCH', async () => { + version(); + const p = project(GAME); + const first = await run2(() => gameCenter(p.ctx(['--yes']))); + expect(first.writes).toEqual([ + 'POST /v1/gameCenterDetails', 'POST /v1/gameCenterAppVersions', + 'POST /v1/gameCenterLeaderboards', 'POST /v1/gameCenterLeaderboardLocalizations', 'POST /v1/gameCenterLeaderboardLocalizations', + 'POST /v1/gameCenterAchievements', 'POST /v1/gameCenterAchievementLocalizations', + 'POST /v1/gameCenterAchievements', 'POST /v1/gameCenterAchievementLocalizations', + ]); + expect(s.asc.all('gameCenterLeaderboards')[0]!.attributes).toMatchObject({ vendorIdentifier: 'com.example.game.highscore', scoreSortType: 'DESC', submissionType: 'BEST_SCORE', defaultFormatter: 'INTEGER' }); + expect(s.asc.all('gameCenterAchievements')[1]!.attributes).toMatchObject({ showBeforeEarned: false, points: 20 }); + expect(first.err).not.toContain('read back'); + const again = await run2(() => gameCenter(p.ctx(['--yes']))); + expect(again.writes).toEqual([]); + expect(again.out).toContain('in step'); + const changed: ShipConfig = { ...GAME, games: { ...GAME.games!, achievements: [{ ...GAME.games!.achievements![0]!, points: 15, locales: { en: { name: 'First victory', description: 'Win a round.' } } }, GAME.games!.achievements![1]!] } }; + const upd = await run2(() => gameCenter(project(changed).ctx(['--yes']))); + expect(upd.writes).toEqual(['PATCH /v1/gameCenterAchievements/' + s.asc.all('gameCenterAchievements')[0]!.id, 'PATCH /v1/gameCenterAchievementLocalizations/' + s.asc.all('gameCenterAchievementLocalizations')[0]!.id]); + }); + + test('an existing detail with the leaderboard already there is kept (matched by vendor id, no duplicate)', () => { + const plan = planGameCenter(GAME.games!, GAME.languages, { leaderboards: [{ id: 'lb-1', attributes: { vendorIdentifier: 'com.example.game.highscore', referenceName: 'com.example.game.highscore', defaultFormatter: 'INTEGER', submissionType: 'BEST_SCORE', scoreSortType: 'DESC' }, + localizations: [{ id: 'l1', attributes: { locale: 'en-US', name: 'High score', formatterSuffix: ' points' } }, { id: 'l2', attributes: { locale: 'tr', name: 'En yüksek skor' } }] }], achievements: [] }); + expect(plan[0]).toMatchObject({ action: 'keep', locales: [{ action: 'keep' }, { action: 'keep' }] }); + }); + + test('a lost create answer (5xx after the write) is not sent twice', async () => { + version(); + s.faults.push({ method: 'POST', match: /\/v1\/gameCenterLeaderboards$/, when: 'after' }); + const r = await run2(() => gameCenter(project(GAME).ctx(['--yes']))); + expect(r.writes.filter(w => w === 'POST /v1/gameCenterLeaderboards')).toHaveLength(1); + expect(s.asc.all('gameCenterLeaderboards')).toHaveLength(1); + }); +}); + +describe('play games (fake Games Configuration API)', () => { + test('create, no-op re-run, update by name match; playId wins', async () => { + const p = project(GAME); + const first = await run2(() => playGames(p.ctx(['--yes']))); + expect(first.writes).toEqual([`POST /games/v1configuration/applications/${PGS}/leaderboards`, `POST /games/v1configuration/applications/${PGS}/achievements`, `POST /games/v1configuration/applications/${PGS}/achievements`]); + const lb = [...s.games.leaderboards.values()][0] as { draft: { name: { translations: { locale: string }[] }; scoreFormat: unknown } }; + expect(lb.draft.name.translations.map(t => t.locale)).toEqual(['en-US', 'tr-TR']); + expect((await run2(() => playGames(p.ctx(['--yes'])))).writes).toEqual([]); + const id = [...s.games.achievements.keys()][0]!; + const changed: ShipConfig = { ...GAME, games: { ...GAME.games!, achievements: [{ ...GAME.games!.achievements![0]!, points: 15 }, GAME.games!.achievements![1]!] } }; + expect((await run2(() => playGames(project(changed).ctx(['--yes'])))).writes).toEqual([`PUT /games/v1configuration/achievements/${id}`]); + expect((s.games.achievements.get(id) as { draft: { pointValue: number } }).draft.pointValue).toBe(15); + }); + test('--dry writes nothing', async () => { + const r = await run2(() => playGames(project(GAME).ctx(['--dry']))); + expect(r.writes).toEqual([]); + expect(r.out).toContain('achievement com.example.game.first-win'); + }); + test('an insert with an unclear answer is not retried blindly', async () => { + s.faults.push({ method: 'POST', match: /\/leaderboards$/, when: 'after', status: 503 }); + await run2(() => playGames(project(GAME).ctx(['--yes']))); + expect(s.games.leaderboards.size).toBe(1); + }); +}); + +describe('project checks', () => { + const ENT = 'com.apple.developer.game-center'; + test('Game Center entitlement: missing, unreferenced, present, present without config', () => { + expect(gcFindings(GAME, [])[0]).toMatchObject({ level: 'error', id: 'gc.entitlement' }); + expect(gcFindings(GAME, [{ file: 'ios/App/App.entitlements', caps: [{ cap: 'GAME_CENTER' }], referenced: false }])[0]!.msg).toContain('CODE_SIGN_ENTITLEMENTS'); + expect(gcFindings(GAME, [{ file: 'ios/App/App.entitlements', caps: [{ cap: 'GAME_CENTER' }], referenced: true }])[0]!.level).toBe('ok'); + expect(gcFindings(BASE, [{ file: 'x.entitlements', caps: [{ cap: 'GAME_CENTER' }], referenced: true }])[0]!.id).toBe('gc.config'); + void ENT; + }); + const MANIFEST = ''; + const GRADLE = 'dependencies { implementation "com.google.android.gms:play-services-games-v2:20.1.2" }'; + test('APP_ID: resolved from games-ids.xml and compared with the config', () => { + const p = project(GAME, { 'android/app/build.gradle': GRADLE, 'android/app/src/main/AndroidManifest.xml': MANIFEST, + 'android/app/src/main/res/values/games-ids.xml': `${PGS}` }); + const pgs = readPgsProject(p.root); + expect(pgs.appId).toEqual({ value: PGS, file: 'android/app/src/main/res/values/games-ids.xml' }); + expect(pgsFindings(GAME, pgs).map(f => f.level)).toEqual(['ok']); + expect(pgsFindings({ games: { playGames: { appId: '999999999999' } } }, pgs)[0]).toMatchObject({ level: 'error', id: 'pgs.app-id' }); + }); + test('APP_ID: the dependency without the meta-data is an error; without config a warning', () => { + const p = project(BASE, { 'android/app/build.gradle': GRADLE, 'android/app/src/main/AndroidManifest.xml': '' }); + const f = pgsFindings(BASE, readPgsProject(p.root)); + expect(f.map(x => x.id)).toEqual(['pgs.config', 'pgs.manifest']); + }); + test('player id reminders: App Privacy USER_ID and Data safety PSL_USER_ACCOUNT', () => { + const f = gamesPrivacyFindings({ ...GAME, dataSafety: { collectsData: true, data: {} } as never, appPrivacy: { types: {} } as never }); + expect(f.map(x => x.id)).toEqual(['games.data-safety', 'games.app-privacy']); + expect(gamesPrivacyFindings({ ...GAME, dataSafety: { data: { PSL_USER_ACCOUNT: {} } } as never, appPrivacy: { types: { USER_ID: {} } } as never })).toEqual([]); + }); +}); + +describe('console plan play-games-services', () => { + test('deep link with ids, absolute Google Cloud links, Publish is the owner\'s', () => { + const p = consolePlan('play-games-services', { ...GAME, play: { ...GAME.play!, developerId: '4444', appId: '9876' } }); + expect(p.start).toEqual({ url: 'https://play.google.com/console/u/0/developers/4444/app/9876/play-games-services/setup', deepLink: true, reach: [] }); + const text = p.steps.map(x => x.text).join('\n'); + expect(text).toContain('https://play.google.com/console/u/0/developers/4444/app/9876/keymanagement'); + expect(text).toContain('https://console.cloud.google.com/apis/credentials'); + expect(p.buttons.final).toBe('Publish'); + expect(p.buttons.neverPress).toContain('Publish'); + expect(p.ownerBatch.some(o => o.kind === 'final' && o.text.includes('Publish'))).toBe(true); + expect(p.askOwner.join()).toContain('Web OAuth client'); + }); + test('without ids: the console and how to reach it', () => { + const p = consolePlan('play-games-services', GAME); + expect(p.start.deepLink).toBe(false); + expect(p.start.url.startsWith('https://play.google.com/console')).toBe(true); + }); + test('verify from the page text', () => { + expect(verifyText('play-games-services', GAME, `Project ID ${PGS}\nCredentials\nAndroid com.example.notes\nReady to publish`).ok).toBe(true); + expect(verifyText('play-games-services', GAME, 'Project ID 1\nNo credentials').mismatches).toBeGreaterThan(0); + }); +}); + +describe('validate findings', () => { + test('missing capability and detail are blockers; in step is ok; fewer than 5 Play achievements warns', () => { + const st: GameServicesStatus = { + apple: { capability: false, enabled: false, version: '1.0.0', versionEnabled: false, leaderboards: 0, achievements: 0, config: { leaderboards: 1, achievements: 2 }, changes: ['leaderboard x: create'] }, + play: { appId: PGS, resource: null, leaderboards: 1, achievements: 2, config: { leaderboards: 1, achievements: 2 }, changes: [] }, + findings: [{ store: 'apple', level: 'error', id: 'gc.entitlement', msg: 'no entitlement' }], links: [], + }; + const f = gameServicesFindings(st); + expect(f.filter(x => x.level === 'blocker').map(x => x.code)).toEqual(['gc.entitlement', 'game-center.capability', 'game-center.detail']); + expect(f.map(x => x.code)).toContain('game-center.sync'); + expect(f.find(x => x.code === 'play-games')!.level).toBe('ok'); + expect(f.find(x => x.code === 'play-games.achievements')!.level).toBe('warn'); + }); +}); diff --git a/tests/helpers/fake-stores.ts b/tests/helpers/fake-stores.ts index 9ef43e1..6897d42 100644 --- a/tests/helpers/fake-stores.ts +++ b/tests/helpers/fake-stores.ts @@ -75,6 +75,12 @@ const LISTS: Record = { 'appAssetLibraries/images': { type: 'appAssetLibraryImages' }, 'appAssetLibraries/videos': { type: 'appAssetLibraryVideos' }, 'appStoreVersionLocalizations/placements': { type: 'appAssetLibraryPlacements' }, + 'apps/gameCenterDetail': { type: 'gameCenterDetails', one: true }, + 'appStoreVersions/gameCenterAppVersion': { type: 'gameCenterAppVersions', one: true }, + 'gameCenterDetails/gameCenterLeaderboards': { type: 'gameCenterLeaderboards' }, + 'gameCenterDetails/gameCenterAchievements': { type: 'gameCenterAchievements' }, + 'gameCenterLeaderboards/localizations': { type: 'gameCenterLeaderboardLocalizations' }, + 'gameCenterAchievements/localizations': { type: 'gameCenterAchievementLocalizations' }, }; /** Stores refuse a second resource with the same key (409 ENTITY_ERROR ... already exists). */ const UNIQUE: Record string> = { @@ -100,6 +106,12 @@ const UNIQUE: Record string> = { promotedPurchases: r => String(r.rels.inAppPurchaseV2 ?? r.rels.subscription), winBackOffers: r => `${r.rels.subscription}|${r.attributes.offerId}`, betaTesters: r => String(r.attributes.email).toLowerCase(), + gameCenterDetails: r => String(r.rels.app), + gameCenterAppVersions: r => String(r.rels.appStoreVersion), + gameCenterLeaderboards: r => String(r.attributes.vendorIdentifier), + gameCenterAchievements: r => String(r.attributes.vendorIdentifier), + gameCenterLeaderboardLocalizations: r => `${r.rels.gameCenterLeaderboard}|${r.attributes.locale}`, + gameCenterAchievementLocalizations: r => `${r.rels.gameCenterAchievement}|${r.attributes.locale}`, }; const ASSETS = /Screenshots$|^appPreviews$|^appScreenshots$|^appAssetLibrary(Images|Videos)$/; /** App Asset Library assets: a state of their own (AWAITING_UPLOAD -> PREPARE_FOR_SUBMISSION after the commit, as Apple's @@ -496,13 +508,43 @@ export class FakePlay { // ------------------------------------------------------------------------------------------------- fetch + counting -export interface Stores { asc: FakeAsc; play: FakePlay; calls: Call[]; faults: Fault[]; failPart?: (n: number) => boolean } +// ----------------------------------------------------------------- Play Games Services Configuration API (v1configuration) + +/** achievementConfigurations / leaderboardConfigurations: list (items, nextPageToken), insert (Google generates the + * id, CgkI...), update (PUT replaces the configuration; `published` stays Google's). Shapes from Google's reference. */ +export class FakeGames { + achievements = new Map>(); + leaderboards = new Map>(); + next = 1; + handle(method: string, url: string, body: unknown): Response { + const p = new URL(url).pathname.replace(/^\/games\/v1configuration/, ''); + let m: RegExpExecArray | null; + if ((m = /^\/applications\/(\d+)\/(achievements|leaderboards)$/.exec(p))) { + const map = this[m[2] as 'achievements' | 'leaderboards']; + if (method === 'GET') return json({ kind: `gamesConfiguration#${m[2] === 'achievements' ? 'achievement' : 'leaderboard'}ConfigurationListResponse`, items: [...map.values()] }); + const id = `CgkI${m[1]}EAIQ${this.next++}`; + const r = { ...(body as Record), id, token: id }; + map.set(id, r); + return json(r); + } + if ((m = /^\/(achievements|leaderboards)\/([^/]+)$/.exec(p))) { + const map = this[m[1] as 'achievements' | 'leaderboards']; + const id = decodeURIComponent(m[2]!); + if (!map.has(id)) return json({ error: { code: 404, status: 'NOT_FOUND', message: 'Not found' } }, 404); + if (method === 'PUT') map.set(id, { ...(body as Record), id, token: id, published: map.get(id)!.published }); + return json(map.get(id)); + } + return json({ error: { code: 599, message: `fake games: ${method} ${p}` } }, 599); + } +} + +export interface Stores { asc: FakeAsc; play: FakePlay; games: FakeGames; calls: Call[]; faults: Fault[]; failPart?: (n: number) => boolean } const realFetch = globalThis.fetch; /** Installs both fakes as fetch. Faults apply in order (`times`, default 1). */ export function installStores(): Stores { - const s: Stores = { asc: new FakeAsc(), play: new FakePlay(), calls: [], faults: [] }; + const s: Stores = { asc: new FakeAsc(), play: new FakePlay(), games: new FakeGames(), calls: [], faults: [] }; let partNo = 0; globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => { const url = String(input instanceof Request ? input.url : input); @@ -524,6 +566,7 @@ export function installStores(): Stores { res = new Response(null, { status: 200 }); } else if (url.startsWith(ASC)) res = s.asc.handle(method, path, body); else if (url.startsWith('https://androidpublisher.googleapis.com/')) res = s.play.handle(method, url, body instanceof Uint8Array ? body : body); + else if (url.startsWith('https://gamesconfiguration.googleapis.com/')) res = s.games.handle(method, url, body); else res = new Response(`fake: no route ${method} ${url}`, { status: 599 }); if (f?.when === 'after') return json({ errors: [{ status: String(f.status ?? 502), detail: 'injected after the write' }] }, f.status ?? 502); return res; From 26f0723641aa37f78e6dc2322dcfc4b475f6a545 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:07:58 +0700 Subject: [PATCH 067/344] games status: both stores' game services in one read-only report (CLI, MCP games_status, desktop read method); --json status output stays pure JSON --- cli/apple/game-center.ts | 2 +- cli/commands.ts | 1 + cli/data/flags.json | 6 ++++++ cli/games-status.ts | 9 +++++++++ cli/mcp-tools.ts | 3 +++ cli/play/games.ts | 4 ++-- cli/serve.ts | 2 +- 7 files changed, 23 insertions(+), 4 deletions(-) diff --git a/cli/apple/game-center.ts b/cli/apple/game-center.ts index fa5649e..35fb43a 100644 --- a/cli/apple/game-center.ts +++ b/cli/apple/game-center.ts @@ -65,7 +65,7 @@ export async function run(ctx: Ctx): Promise { const plan = planGameCenter(g, config.languages, s); const project = gcFindings(config, readProjectEntitlements(root)); - if (a.has('json')) { console.log(JSON.stringify({ ...stateSummary(s, plan), project, plan }, null, 2)); if (sub === 'status') return; } + if (a.has('json')) { console.log(JSON.stringify({ ...stateSummary(s, plan), project, plan }, null, 2)); return; } if (s.capability === false) warn(TAG, `the App ID ${bundleId} has no GAME_CENTER capability: storebound apple signing ensure --dry, then without --dry (games.gameCenter adds it)`); if (s.capability === null) warn(TAG, `bundle id ${bundleId} not found in Certificates, Identifiers & Profiles: storebound apple bundle`); for (const f of project) (f.level === 'ok' ? log : warn)(TAG, `${f.msg}${f.fix ? ` (${f.fix})` : ''}`); diff --git a/cli/commands.ts b/cli/commands.ts index b7a8f6a..d851e4c 100644 --- a/cli/commands.ts +++ b/cli/commands.ts @@ -61,6 +61,7 @@ export const COMMANDS: Record Promise, string]> = { 'play rollout': [() => import('./play/rollout'), 'staged rollout: --fraction x | --halt | --resume | --complete (asks first)'], 'play share': [() => import('./play/share'), 'internal app sharing: upload an AAB / APK, print the share link (asks first; --dry)'], 'play app-id': [() => import('./play/app-id'), '[--from-text ] [--write]: the Play Console app id (play.appId) by package name: known ids, else the agent steps (app list search / pages, capture) and the dry diff; --write saves it; read-only on Play'], + 'games status': [() => import('./games-status'), 'Game Center + Play Games Services on both stores, read-only: App ID capability, entitlement, games_APP_ID resource, detail / version switch, leaderboard and achievement counts vs the config, console links; --json'], 'play games': [() => import('./play/games'), '[status] Play Games Services leaderboards + achievements from games (Games Configuration API upsert, matched by playId / name; drafts only, the owner publishes); --dry, asks first'], 'play next-version-code': [() => import('./play/next-version-code'), 'next free versionCode (prints the number)'], 'apple bundle': [() => import('./apple/bundle'), 'register the bundle id; finds the app record'], diff --git a/cli/data/flags.json b/cli/data/flags.json index d9d9fe4..8c967b1 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -460,6 +460,12 @@ "from", "resume" ], + "games status": [ + "achievements", + "keychain", + "leaderboards", + "no-install" + ], "health": [ "apple", "days", diff --git a/cli/games-status.ts b/cli/games-status.ts index 2362309..0cedfe3 100644 --- a/cli/games-status.ts +++ b/cli/games-status.ts @@ -86,3 +86,12 @@ export function gameServicesFindings(s: GameServicesStatus): VFinding[] { } return out; } + +/** `storebound games status [--json]`: both stores' game services in one read-only report (desktop card, MCP). */ +export async function run(ctx: import('./lib/ctx').Ctx): Promise { + const s = await gameServicesStatus(ctx.loaded); + if (ctx.args.has('json')) { console.log(JSON.stringify(s, null, 2)); return; } + const { formatFindings } = await import('./lib/validate-rules'); + console.log(formatFindings(gameServicesFindings(s))); + for (const l of s.links) console.log(`${l.label}: ${l.url}`); +} diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index eddb107..bd3a0ba 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -217,6 +217,9 @@ export const TOOLS: ToolDef[] = [ { name: 'apple_encryption', title: 'Export compliance answer', command: ['apple', 'encryption'], write: true, network: true, idempotent: true, description: 'Answer export compliance for builds from apple.usesNonExemptEncryption in the config (never guesses).', props: { build: { type: 'string', description: 'Build number (default: every build without an answer)' } }, args: i => opt('build', i.build) }, + { name: 'games_status', title: 'Game services status (both stores)', command: ['games', 'status'], write: false, network: true, + description: 'Read-only Game Center and Play Games Services status: App ID GAME_CENTER capability, the entitlement, Game Center detail and version switch, the games_APP_ID resource vs games.playGames.appId, leaderboard / achievement counts on each store vs the config with pending changes, findings and absolute console links.', + args: () => ['--json'] }, { name: 'apple_game_center', title: 'Game Center sync', command: ['apple', 'game-center'], write: true, network: true, idempotent: true, description: 'Game Center from the config\'s games section: switch it on for the app (gameCenterDetails) and the editable version (gameCenterAppVersions), upsert leaderboards and achievements with their localizations by vendor id (create / PATCH only what differs; never deletes or archives), then read back. Nothing is submitted: they go to review with the next version. The App ID capability is signing ensure\'s (terminal).', args: () => [] }, diff --git a/cli/play/games.ts b/cli/play/games.ts index 83239a7..2e5e906 100644 --- a/cli/play/games.ts +++ b/cli/play/games.ts @@ -72,13 +72,13 @@ export async function run(ctx: Ctx): Promise { const pgs = hasAndroidProject(root) ? readPgsProject(root) : null; const project = pgs ? pgsFindings(config, pgs) : []; const appId = config.games!.playGames!.appId ?? pgs?.appId?.value; - for (const f of project) (f.level === 'ok' ? log : warn)(TAG, `${f.msg}${f.fix ? ` (${f.fix})` : ''}`); + if (!a.has('json')) for (const f of project) (f.level === 'ok' ? log : warn)(TAG, `${f.msg}${f.fix ? ` (${f.fix})` : ''}`); if (!appId) throw new Error('games.playGames.appId is not set and the Android project has no games_APP_ID: create the games project first (storebound console plan play-games-services), then set the id'); const c = gamesConfigClient(root); const have = await readPlayGames(c, appId); const locale = playDefaultLocale(config); const plan = planPlayGames(config.games!, config.languages, locale, have); - if (a.has('json')) console.log(JSON.stringify({ appId, leaderboards: have.leaderboards.length, achievements: have.achievements.length, project, plan }, null, 2)); + if (a.has('json')) { console.log(JSON.stringify({ appId, leaderboards: have.leaderboards.length, achievements: have.achievements.length, project, plan }, null, 2)); return; } if (sub === 'status' || a.has('dry')) { if (!a.has('json')) console.log(dryPlan(`play games (project ${appId})`, planRows(plan))); return; diff --git a/cli/serve.ts b/cli/serve.ts index e08378c..9b81220 100644 --- a/cli/serve.ts +++ b/cli/serve.ts @@ -54,7 +54,7 @@ export const DESKTOP_EXCLUDED = new Set(['play_release_testing', 'apple_phased_r export const FORBIDDEN_METHOD_WORDS = /submit|release|publish|rollout|resume|complete|send|start|stop|cancel|delete|remove|invite/i; /** Read tools whose command prints a structured result with --json. */ -export const JSON_TOOLS = new Set(['check', 'report', 'check_aso', 'aso_audit', 'aso_suggest', 'aso_competitors', 'scan', 'validate', 'health', 'health_issue', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status', +export const JSON_TOOLS = new Set(['games_status', 'apple_game_center_status', 'play_games_status', 'check', 'report', 'check_aso', 'aso_audit', 'aso_suggest', 'aso_competitors', 'scan', 'validate', 'health', 'health_issue', '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', 'project_icon', 'project_listings', 'reviews_drafts', 'project_declarations', 'project_listing_text', 'project_renders', 'project_render', 'prices_current', 'project_editable', 'listing_live', 'art_live', 'art_thumb']); From 22286c7e0260e3e75287a366ab15befcf1276ab5 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:11:46 +0700 Subject: [PATCH 068/344] desktop: Game services card in App info (Game Center and Play Games Services status, ids, counts vs config, pending changes, sync buttons through the confirm-token write, PGS setup plan, console links); en + tr strings; dev fixture --- apps/desktop/src/dev/fixtures.ts | 10 ++- apps/desktop/src/i18n/en.ts | 23 +++++++ apps/desktop/src/i18n/tr.ts | 23 +++++++ apps/desktop/src/screens/tabs/AppInfo.tsx | 2 + apps/desktop/src/ui/ConsolePlan.tsx | 3 +- apps/desktop/src/ui/GameServicesCard.tsx | 76 +++++++++++++++++++++++ 6 files changed, 135 insertions(+), 2 deletions(-) create mode 100644 apps/desktop/src/ui/GameServicesCard.tsx diff --git a/apps/desktop/src/dev/fixtures.ts b/apps/desktop/src/dev/fixtures.ts index 8f1383f..9acb44a 100644 --- a/apps/desktop/src/dev/fixtures.ts +++ b/apps/desktop/src/dev/fixtures.ts @@ -423,6 +423,13 @@ const TOOLS = [ ]; let chromeInstalled = false; +// games status (cli/games-status.ts) of the game demo: Game Center on, one leaderboard to create; PGS project set +const GAMES_PRISM = { + apple: { capability: true, enabled: true, version: '1.2.0', versionEnabled: true, leaderboards: 1, achievements: 5, config: { leaderboards: 2, achievements: 5 }, changes: ['leaderboard com.example.prismpuddle.daily: create'] }, + play: { appId: '123456789012', resource: '123456789012 (android/app/src/main/res/values/games-ids.xml)', leaderboards: 2, achievements: 5, config: { leaderboards: 2, achievements: 5 }, changes: [] }, + findings: [{ store: 'apple', level: 'ok', id: 'gc.entitlement', msg: 'com.apple.developer.game-center in ios/App/App/App.entitlements' }, { store: 'play', level: 'ok', id: 'pgs.app-id', msg: 'games_APP_ID 123456789012 matches the config' }], + links: [{ label: 'Play Console: Play Games Services configuration', url: 'https://play.google.com/console/u/0/developers/4444/app/9876/play-games-services/setup' }], +}; const ok = (method: string, data: unknown): ToolResult => ({ method, ok: true, exitCode: 0, dryRun: false, command: `storebound ${method.replace('.', ' ')} --json`, output: '', data }); const STORE_REVIEWS: Review[] = [ @@ -491,6 +498,7 @@ function read(method: string, id: string, args: Record = {}): T // send for review: Prism Puddle is ready to submit, Tidy Lists is back from App Review (UNRESOLVED_ISSUES) case 'apple.status': return ok(method, id === 'p-tidy' ? APPLE_STATUS_UNRESOLVED : APPLE_STATUS_READY); case 'play.status': return ok(method, PLAY_STATUS); + case 'games.status': return ok(method, id === 'p-prism' ? GAMES_PRISM : { apple: null, play: null, findings: [], links: [] }); case 'console.plan': return ok(method, consolePlan(String(args.form))); case 'console.verify': return ok(method, consoleVerify(String(args.form))); default: @@ -520,7 +528,7 @@ const CONSOLE_FILL: Record = { }; const CACHED_AGO: Record = { health: 60 * 3, 'reviews.list': 45, 'apple.testflight_status': 60 * 5, 'catalog.diff': 60 * 26, validate: 60 * 2, 'prices.current': 60 * 4, 'apple.ppo_status': 60 * 6 }; -const NETWORK = new Set(['health', 'health.issue', 'reviews.list', 'apple.testflight_status', 'catalog.diff', 'validate', 'report', 'prices.current', 'prices.diff', 'apple.ppo_status', 'apple.status', 'play.status', 'console.verify']); +const NETWORK = new Set(['games.status', 'health', 'health.issue', 'reviews.list', 'apple.testflight_status', 'catalog.diff', 'validate', 'report', 'prices.current', 'prices.diff', 'apple.ppo_status', 'apple.status', 'play.status', 'console.verify']); async function progressLines(job: string | null, lines: string[]) { for (const line of lines) { await sleep(260); if (job) emit('sidecar-progress', { params: { requestId: 1, line, stream: 'stderr' }, job }); } diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index c604f3e..3585c39 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -1841,4 +1841,27 @@ export const en = { 'tools.o.ads_change': 'Apple Ads bid, budget or pause', 'tools.o.rc_sync': 'Sync the catalog to RevenueCat', 'tools.o.shots_login': 'Sign in to the demo account for screenshots (by hand, Enter saves)', + 'cp.playGames': 'Play Games Services setup', + 'cp.playGamesText': 'Games project, Android credential with the app signing SHA-1, web OAuth client; you press Publish.', + 'gs.title': 'Game services', + 'gs.sub': 'Game Center and Play Games Services: switches, ids, leaderboards and achievements from the config.', + 'gs.gameCenter': 'Game Center', + 'gs.playGames': 'Play Games Services', + 'gs.enabled': 'On for the app', + 'gs.capability': 'App ID capability', + 'gs.version': 'Version {v}', + 'gs.items': 'Leaderboards / achievements', + 'gs.counts': '{lb} of {lbWant} leaderboards · {ach} of {achWant} achievements', + 'gs.pending': '{n} change(s) to write', + 'gs.projectId': 'Project id', + 'gs.resource': 'games_APP_ID resource', + 'gs.notSet': 'Not set', + 'gs.yes': 'Yes', + 'gs.no': 'No', + 'gs.unknown': 'Unknown', + 'gs.syncApple': 'Sync Game Center', + 'gs.syncPlay': 'Sync Play Games', + 'gs.syncHint': 'Dry run first, then you confirm; nothing is submitted or published.', + 'gs.synced': 'Game services in step', + 'gs.setup': 'Setup plan', } as const; diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index 6356927..e4847bc 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -1843,4 +1843,27 @@ export const tr: Record = { 'tools.o.ads_change': 'Apple Ads teklif, bütçe veya duraklatma', 'tools.o.rc_sync': 'Kataloğu RevenueCat ile eşitle', 'tools.o.shots_login': 'Ekran görüntüleri için demo hesaba giriş (elle, Enter kaydeder)', + 'cp.playGames': 'Play Games Hizmetleri kurulumu', + 'cp.playGamesText': 'Oyun projesi, uygulama imzalama SHA-1 ile Android kimliği, web OAuth istemcisi; Yayınla düğmesine sen basarsın.', + 'gs.title': 'Oyun hizmetleri', + 'gs.sub': 'Game Center ve Play Games Hizmetleri: anahtarlar, kimlikler, yapılandırmadaki skor tabloları ve başarımlar.', + 'gs.gameCenter': 'Game Center', + 'gs.playGames': 'Play Games Hizmetleri', + 'gs.enabled': 'Uygulamada açık', + 'gs.capability': 'App ID yeteneği', + 'gs.version': 'Sürüm {v}', + 'gs.items': 'Skor tabloları / başarımlar', + 'gs.counts': '{lbWant} skor tablosundan {lb} · {achWant} başarımdan {ach}', + 'gs.pending': 'Yazılacak {n} değişiklik', + 'gs.projectId': 'Proje kimliği', + 'gs.resource': 'games_APP_ID kaynağı', + 'gs.notSet': 'Ayarlı değil', + 'gs.yes': 'Evet', + 'gs.no': 'Hayır', + 'gs.unknown': 'Bilinmiyor', + 'gs.syncApple': 'Game Center eşitle', + 'gs.syncPlay': 'Play Games eşitle', + 'gs.syncHint': 'Önce deneme çalıştırması, sonra sen onaylarsın; hiçbir şey gönderilmez ya da yayınlanmaz.', + 'gs.synced': 'Oyun hizmetleri eşit', + 'gs.setup': 'Kurulum planı', }; diff --git a/apps/desktop/src/screens/tabs/AppInfo.tsx b/apps/desktop/src/screens/tabs/AppInfo.tsx index dc3f73e..7b7e5bf 100644 --- a/apps/desktop/src/screens/tabs/AppInfo.tsx +++ b/apps/desktop/src/screens/tabs/AppInfo.tsx @@ -17,6 +17,7 @@ import { CONSOLE_FORM_NAME, ConsoleFillButton } from '../../ui/ConsoleFill'; import { ConsolePlanButton, PLAN_FORMS } from '../../ui/ConsolePlan'; import { Bar, Card, Chip, Empty, ErrorNotice, Notice, Skeleton } from '../../ui/kit'; import { WriteButton } from '../../ui/WriteButton'; +import { GameServicesCard } from '../../ui/GameServicesCard'; import { ascUrl } from '../AppView'; const AREA: Record = { dataSafety: 'ai.aDataSafety', appPrivacy: 'ai.aAppPrivacy', appInfo: 'ai.aAppInfo', encryption: 'ai.aEncryption', review: 'ai.aReview' }; @@ -237,6 +238,7 @@ export function AppInfoTab({ project }: { project: Project }) { )} +

{t('ai.foot', { when: ago(r.at) })}

diff --git a/apps/desktop/src/ui/ConsolePlan.tsx b/apps/desktop/src/ui/ConsolePlan.tsx index d4fb356..fba0c48 100644 --- a/apps/desktop/src/ui/ConsolePlan.tsx +++ b/apps/desktop/src/ui/ConsolePlan.tsx @@ -16,7 +16,7 @@ import { Chip, Notice } from './kit'; /** The forms of `console plan` (cli/mcp-tools.ts CONSOLE_PLAN_FORMS). */ export type PlanForm = 'apple-app-record' | 'apple-age-rating' | 'apple-app-privacy' | 'play-app-record' | 'play-content-rating' | 'play-target-audience' | 'play-store-settings' | 'play-app-content' | 'play-privacy-policy' | 'play-ads' | 'play-sign-in-details' | 'play-advertising-id' | 'play-government-apps' - | 'play-financial-features' | 'play-health-apps' | 'play-production-countries' | 'play-production-release'; + | 'play-financial-features' | 'play-health-apps' | 'play-production-countries' | 'play-production-release' | 'play-games-services'; /** `console plan --json` (cli/lib/console-plan.ts ConsolePlan), the parts shown here. */ export interface Plan { form: PlanForm; store: 'apple' | 'play'; title: string; @@ -47,6 +47,7 @@ export const PLAN_FORMS: { form: PlanForm; store: 'apple' | 'play'; name: Key; t { form: 'play-target-audience', store: 'play', name: 'cf.playTargetAudience', text: 'cf.playTargetAudienceText' }, { form: 'play-production-countries', store: 'play', name: 'cp.playCountries', text: 'cp.playCountriesText' }, { form: 'play-production-release', store: 'play', name: 'cp.playProductionRelease', text: 'cp.playProductionReleaseText' }, + { form: 'play-games-services', store: 'play', name: 'cp.playGames', text: 'cp.playGamesText' }, ]; const nameOf = (form: PlanForm): string => t(PLAN_FORMS.find(f => f.form === form)?.name ?? 'cp.title'); /** Forms whose result `console verify` reads from the App Store Connect API (no page text needed). */ diff --git a/apps/desktop/src/ui/GameServicesCard.tsx b/apps/desktop/src/ui/GameServicesCard.tsx new file mode 100644 index 0000000..3aa77cd --- /dev/null +++ b/apps/desktop/src/ui/GameServicesCard.tsx @@ -0,0 +1,76 @@ +// Game services: Game Center (App Store) and Play Games Services (Google Play) side by side, from `games status --json` +// (cli/games-status.ts): enabled, App ID capability, entitlement / APP_ID resource, ids, leaderboard and achievement +// counts on the store vs the config, pending changes and findings. The sync buttons are the confirm-token writes +// (dry run -> native dialog -> apply) of `apple game-center` and `play games`; the PGS setup is a console plan. +import type { Project } from '../api'; +import { t } from '../i18n'; +import { useRead, useWrite } from '../store'; +import { ConsolePlanButton } from './ConsolePlan'; +import { StoreGlyph } from './icons'; +import { Card, Chip, ErrorNotice, Skeleton } from './kit'; +import { OpenLink } from './OpenLink'; +import { WriteButton } from './WriteButton'; + +interface Finding { store: 'apple' | 'play'; level: 'error' | 'warn' | 'ok'; id: string; msg: string; fix?: string } +interface Counts { leaderboards: number; achievements: number } +export interface GameServicesStatus { + apple: null | { capability: boolean | null; enabled: boolean; version: string | null; versionEnabled: boolean | null; config: Counts; changes: string[]; error?: string } & Counts; + play: null | { appId: string | null; resource: string | null; config: Counts; changes: string[]; error?: string } & Counts; + findings: Finding[]; + links: { label: string; url: string }[]; +} + +const tone = (l: Finding['level']) => (l === 'error' ? 'bad' : l === 'warn' ? 'warn' : 'ok'); +const yesNo = (v: boolean | null | undefined) => (v === null || v === undefined ? {t('gs.unknown')} : {v ? t('gs.yes') : t('gs.no')}); + +export function GameServicesCard({ project }: { project: Project }) { + const r = useRead(project.id, 'games.status', { network: true, title: t('gs.title') }); + const w = useWrite(project.id); + if (!r.data) return r.error ? : ; + const s = r.data; + if (!s.apple && !s.play && !s.findings.length) return null; + const f = (store: 'apple' | 'play') => s.findings.filter(x => x.store === store); + const count = (have: Counts, want: Counts) => t('gs.counts', { lb: have.leaderboards, lbWant: want.leaderboards, ach: have.achievements, achWant: want.achievements }); + return ( + +
+ {s.apple && ( +
+
{t('gs.gameCenter')}
+ {s.apple.error ? {s.apple.error} : ( +
+
{t('gs.enabled')}
{yesNo(s.apple.enabled)}
+
{t('gs.capability')}
{yesNo(s.apple.capability)}
+
{t('gs.version', { v: s.apple.version ?? '-' })}
{yesNo(s.apple.versionEnabled)}
+
{t('gs.items')}
{count(s.apple, s.apple.config)}
+
+ )} + {f('apple').map(x => {x.msg})} + {!!s.apple.changes.length && {t('gs.pending', { n: s.apple.changes.length })}: {s.apple.changes.slice(0, 4).join('; ')}} +
+ {t('gs.syncApple')} +
+
+ )} + {s.play && ( +
+
{t('gs.playGames')}
+
+
{t('gs.projectId')}
{s.play.appId ? {s.play.appId} : {t('gs.notSet')}}
+
{t('gs.resource')}
{s.play.resource ? {s.play.resource} : {t('gs.notSet')}}
+ {!s.play.error && <>
{t('gs.items')}
{count(s.play, s.play.config)}
} +
+ {s.play.error && {s.play.error}} + {f('play').map(x => {x.msg})} + {!!s.play.changes.length && {t('gs.pending', { n: s.play.changes.length })}: {s.play.changes.slice(0, 4).join('; ')}} +
+ {t('gs.syncPlay')} + +
+
+ )} +
+ {!!s.links.length &&
{s.links.map(l => {l.label})}
} +
+ ); +} From 93d7f8a5fc2087ae001eacac1a8931aff8a1b5db Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:12:44 +0700 Subject: [PATCH 069/344] docs: game-services skill (Game Center + Play Games Services step by step), pitfall 86, commands, CHANGELOG Unreleased; adapters regenerated --- .cursor/rules/storebound.mdc | 1 + .github/copilot-instructions.md | 1 + AGENTS.md | 1 + CHANGELOG.md | 9 ++++ GEMINI.md | 1 + docs/commands.md | 3 ++ skills/game-services/SKILL.md | 77 +++++++++++++++++++++++++++++++++ skills/store-pitfalls/SKILL.md | 11 +++++ 8 files changed, 104 insertions(+) create mode 100644 skills/game-services/SKILL.md diff --git a/.cursor/rules/storebound.mdc b/.cursor/rules/storebound.mdc index 12a3401..8ba9940 100644 --- a/.cursor/rules/storebound.mdc +++ b/.cursor/rules/storebound.mdc @@ -94,6 +94,7 @@ need to ...", do it instead, unless it is one of the owner steps in point 2. - `skills/build-and-sign/SKILL.md`: Sign, build and upload a mobile app or game from the terminal - `skills/console-autofill/SKILL.md`: Fill App Store Connect and Google Play Console forms that have no API (New App, App Privacy, Play Create app, IARC content rating, every Play App content card, Play Store settings category, first production release countries and send-for-review). Agent-first by default - `skills/export-compliance/SKILL.md`: Answer App Store export compliance (encryption) for a mobile app or game correctly +- `skills/game-services/SKILL.md`: Set up Game Center (App Store) and Play Games Services (Google Play) for a mobile game from one config section - `skills/listing-localization/SKILL.md`: Translate the store listing of a mobile app or game into more languages - `skills/migrate-from-fastlane/SKILL.md`: Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` - `skills/play-first-release/SKILL.md`: Step-by-step first (and later) Google Play release of a mobile app or game diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 68c0e72..5515c62 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -96,6 +96,7 @@ need to ...", do it instead, unless it is one of the owner steps in point 2. | `build-and-sign` | Sign, build and upload a mobile app or game from the terminal | | `console-autofill` | Fill App Store Connect and Google Play Console forms that have no API (New App, App Privacy, Play Create app, IARC content rating, every Play App content card, Play Store settings category, first production release countries and send-for-review). Agent-first by default | | `export-compliance` | Answer App Store export compliance (encryption) for a mobile app or game correctly | +| `game-services` | Set up Game Center (App Store) and Play Games Services (Google Play) for a mobile game from one config section | | `listing-localization` | Translate the store listing of a mobile app or game into more languages | | `migrate-from-fastlane` | Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` | | `play-first-release` | Step-by-step first (and later) Google Play release of a mobile app or game | diff --git a/AGENTS.md b/AGENTS.md index 437ef2a..abbc502 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -95,6 +95,7 @@ need to ...", do it instead, unless it is one of the owner steps in point 2. - `skills/build-and-sign/SKILL.md`: Sign, build and upload a mobile app or game from the terminal - `skills/console-autofill/SKILL.md`: Fill App Store Connect and Google Play Console forms that have no API (New App, App Privacy, Play Create app, IARC content rating, every Play App content card, Play Store settings category, first production release countries and send-for-review). Agent-first by default - `skills/export-compliance/SKILL.md`: Answer App Store export compliance (encryption) for a mobile app or game correctly +- `skills/game-services/SKILL.md`: Set up Game Center (App Store) and Play Games Services (Google Play) for a mobile game from one config section - `skills/listing-localization/SKILL.md`: Translate the store listing of a mobile app or game into more languages - `skills/migrate-from-fastlane/SKILL.md`: Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` - `skills/play-first-release/SKILL.md`: Step-by-step first (and later) Google Play release of a mobile app or game diff --git a/CHANGELOG.md b/CHANGELOG.md index cfaa7fd..4da74d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,15 @@ every command with its window place and methods; 92 commands, 88 covered, 4 not for the desktop (`mcp`, `serve`, `desktop`, `api`). `tests/desktop-coverage.test.ts` fails when a command has no place, names a method the window never calls, or is marked not-for-desktop without being on the short list. +- **Game Center and Play Games Services.** A `games` config section (switches per store and one shared list of + leaderboards and achievements). `storebound apple game-center` switches Game Center on for the app and the version + and upserts leaderboards, achievements and their localizations by vendor id; `apple signing ensure` adds the + GAME_CENTER capability. `storebound play games` upserts the Play drafts through the Games Configuration API, and + `console plan play-games-services` walks an agent through the games project, the Android credential with the app + signing SHA-1, the web OAuth client and the owner's Publish. `scan`, `check` and `validate` compare the entitlement, + the App ID and the config, the games_APP_ID resource with the Gradle dependency and the config, and remind the User + ID declarations; `games status`, four MCP tools and a Game services card in the desktop's App info tab. Skill + game-services, pitfall 88. ## 0.8.21 · 2026-10-20 diff --git a/GEMINI.md b/GEMINI.md index 0f6362c..05becf9 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -95,6 +95,7 @@ need to ...", do it instead, unless it is one of the owner steps in point 2. | `build-and-sign` | Sign, build and upload a mobile app or game from the terminal | | `console-autofill` | Fill App Store Connect and Google Play Console forms that have no API (New App, App Privacy, Play Create app, IARC content rating, every Play App content card, Play Store settings category, first production release countries and send-for-review). Agent-first by default | | `export-compliance` | Answer App Store export compliance (encryption) for a mobile app or game correctly | +| `game-services` | Set up Game Center (App Store) and Play Games Services (Google Play) for a mobile game from one config section | | `listing-localization` | Translate the store listing of a mobile app or game into more languages | | `migrate-from-fastlane` | Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` | | `play-first-release` | Step-by-step first (and later) Google Play release of a mobile app or game | diff --git a/docs/commands.md b/docs/commands.md index fa5d1ed..c71643e 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -50,6 +50,7 @@ run in the background with a log (`storebound shots render > .storebound/render. | `play images [--variant b]` | API | icon, feature graphic, phone / 7" / 10" screenshots, one edit per language | | `play products` | API | one-time products: regional prices from `convertRegionPrices` + your overrides, activate | | `play subscriptions [--csv]` | API | subscriptions: listings + benefits, one auto-renewing base plan, regional prices, intro and extra offers, activate (plan first, asks) | +| `play games [status]` | API | Play Games Services leaderboards and achievements from `games` (Games Configuration API; drafts, the owner publishes); the setup is `console plan play-games-services`; dry first, asks | | `play data-safety` | API | Data safety form (CSV import); `--csv` writes the file | | `play build [--version-code N] [--flavor f]` | local + API read | `build.prebuild` first (Capacitor: web build + cap sync; stale copied web assets stop the build), then Gradle `bundleRelease` (Flutter `flutter build appbundle`; Capacitor, React Native, Unity export found) with the next free versionCode and the upload key from env / `.storebound` (passed through the environment, never argv); AAB checked and copied to `build/android/` | | `play upload [] --track internal\|alpha\|beta` | API | AAB to a testing track with release notes; versionCode checked first; `--dry` is read-only, a real run asks | @@ -83,6 +84,8 @@ run in the background with a log (`storebound shots render > .storebound/render. | `apple subscriptions [--csv] [--codes]` | API | groups, subscriptions, levels, localizations, availability, equalized prices + overrides + CSV (scheduled changes), introductory and promotional offers, offer code campaigns, review screenshots (plan first, asks; custom codes only with `--codes`) | | `apple appinfo` | API | categories, age rating, content rights, Free, territories; plan first (old -> new), only changes are sent | | `apple review-details` | API | App Review contact, demo account (from `.storebound/`, masked), notes (+ sign-in steps, where account deletion is) | +| `apple game-center [status]` | API | Game Center from `games`: the app's Game Center detail, the version switch, leaderboards and achievements with localizations (upsert by vendor id, read back; nothing submitted); dry first, asks | +| `games status [--json]` | API, read-only | Game Center and Play Games Services on both stores: capability, entitlement, games_APP_ID, counts vs the config, pending changes, console links | | `apple encryption` | API | export compliance answer from `apple.usesNonExemptEncryption` (never guessed) | | `apple release --phased on\|pause\|resume\|complete`, `--manual-release` | API | phased release, release an approved version (resume / complete / release ask first) | | `apple signing status` | API, read-only | bundle id capabilities, distribution certificates (with / without a private key on this Mac), App Store profiles per bundle id, installed or not | diff --git a/skills/game-services/SKILL.md b/skills/game-services/SKILL.md new file mode 100644 index 0000000..9829272 --- /dev/null +++ b/skills/game-services/SKILL.md @@ -0,0 +1,77 @@ +--- +name: game-services +description: Set up Game Center (App Store) and Play Games Services (Google Play) for a mobile game from one config section - the App ID GAME_CENTER capability, Game Center on for the app and the version, the com.apple.developer.game-center entitlement, leaderboards and achievements with localizations (storebound apple game-center, upsert by vendor id), the Play Games Services project, Android credential with the app signing SHA-1, web OAuth client and publish (console plan play-games-services), the games_APP_ID resource, and leaderboards / achievements through the Games Configuration API (storebound play games). Use when a game adds leaderboards, achievements or platform sign-in, when Game Center sign-in fails, or PGS sign-in fails with a missing APP_ID or a SHA-1 mismatch. +--- + +# Game Center and Play Games Services + +One `games` section in `storebound.config.ts` drives both stores. The leaderboards and achievements are ONE shared +list: each item has your `id` (the App Store vendor identifier) and texts per config language; Play generates its own +ids, which you add as `playId` once they exist (until then storebound matches Play items by the default-language +name). + +```ts +games: { + gameCenter: true, // App ID capability + Game Center for the app and the version + playGames: { appId: '123456789012' }, // the PGS project id (games_APP_ID); set it after step P1 + leaderboards: [ + { id: 'com.example.game.highscore', sort: 'high', format: 'INTEGER', // Apple formatter names + locales: { en: { name: 'High score', suffix: ' points' }, tr: { name: 'En yüksek skor' } } }, + ], + achievements: [ + { id: 'com.example.game.first-win', points: 10, locales: { en: { name: 'First win', description: 'Win a round.' } } }, + { id: 'com.example.game.secret', points: 20, hidden: true, steps: 3, // steps: incremental on Play only + locales: { en: { name: 'Secret', description: 'Find the secret room.', earned: 'You found it.' } } }, + ], +}, +``` + +Limits checked by `storebound check`: Game Center names at most 32 characters, points 0-100 each and 1000 in total; +Play points a multiple of 5, 1000 in total, at most 200 achievements, and at least 5 before Play publishes the games +project. `platforms: ['ios']` keeps an item on one store. + +## Game Center (App Store Connect API) + +1. `games.gameCenter: true`, then `storebound apple signing ensure --dry` and without `--dry`: GAME_CENTER is added + to the App ID (it never removes a capability). It reads the App ID back; the list can lag (pitfalls). +2. The Xcode target needs the entitlement: Signing & Capabilities > + Game Center, which writes + `com.apple.developer.game-center` into the `.entitlements` file named by `CODE_SIGN_ENTITLEMENTS`. `storebound check` + and `validate` compare entitlement, App ID and config, and the uploaded IPA's entitlements. +3. `storebound apple game-center --dry`: the plan (Game Center detail for the app, the editable version's switch, + every leaderboard / achievement / localization: create, update or keep). Then without `--dry` (asks first): it + creates through `POST /v1/gameCenterDetails`, `POST /v1/gameCenterAppVersions`, `/v1/gameCenterLeaderboards`, + `/v1/gameCenterAchievements` and their localizations, PATCHes only what differs, and reads everything back. +4. Images (leaderboard / achievement artwork, 512 or 1024 px) are optional for the API and stay in App Store + Connect for now. Leaderboards and achievements go to review with the next app version: the owner's Submit for + review (`storebound apple submit`). +5. `storebound apple game-center status` (MCP `apple_game_center_status`) shows the state at any time. + +## Play Games Services + +P1. `storebound console plan play-games-services --json` (MCP `console_plan`): the agent drives Play Console and the + Google Cloud console with its own browser tool: create the games project, the Android credential (package name + + the **App signing key** SHA-1 from Play app signing; the API gives only SHA-256, so read it on that page), the web + OAuth client only when a game server exchanges server auth codes (ask the owner), the properties. The agent + never presses **Publish**: that is the owner's button. +P2. Put the project id into `games.playGames.appId` and the "Get resources" XML into + `android/app/src/main/res/values/games-ids.xml`; the manifest needs + `` + and the app module `com.google.android.gms:play-services-games-v2`. `storebound scan`, `check` and `validate` check + all three and that the id matches the config. +P3. `storebound play games --dry`, then without `--dry`: inserts / updates the drafts through the Games Configuration + API (`achievementConfigurations`, `leaderboardConfigurations`). It prints each new Play id: add it as `playId`. +P4. Testers (Play Games Services > Testers) are the owner's to add. The owner presses Publish; then + `storebound console verify play-games-services --from-text -` with the page text. + +## Declarations + +A Game Center or PGS player id is a **User ID**: App Privacy > Identifiers > User ID (`appPrivacy.types.USER_ID`, +App Functionality, linked) and Play Data safety > Personal info > User IDs (`dataSafety.data.PSL_USER_ACCOUNT`, +collected for app functionality). `check` warns when they are missing; ask the owner whether the id is shared. If the +game has its own accounts on top, the account-deletion skill applies; the platform account itself is deleted by Apple +or Google, not by the game. + +## Desktop + +App info > Game services: both stores side by side (enabled, capability, entitlement, project id, counts vs the +config, pending changes), Sync buttons (dry run, then the native confirm dialog) and the PGS setup plan. diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 8152304..a3e993b 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1076,3 +1076,14 @@ that fails without the fix (see CONTRIBUTING.md). line: "--version is required (storebound apple status shows the editable version)". - **Guard:** `findReviewContact` / `noContactMessage` in `cli/lib/credentials.ts`, `Args.required` in `cli/lib/args.ts` (listing, privacy-manifest, adhoc export, edit, resubmit); `tests/console-guardrails-1021.test.ts`. +## 88. Game Center and Play Games Services: ids, SHA-1 and the deprecated enabled-versions route +- **Symptom:** Play Games sign-in fails on store installs while debug builds work (the Android credential has the + upload key's SHA-1, not the App signing key's); sign-in fails at once with no APP_ID (the Gradle dependency is there, + the manifest meta-data or games-ids.xml is not); Game Center items created twice by a re-run; a tool reading + `/v1/apps/{id}/gameCenterEnabledVersions`, which the API marks deprecated. +- **Do:** one `games` section (game-services skill). Game Center items are matched by vendor identifier (`id`), Play + items by `playId` or the default-language name (Play generates ids). Read the SHA-1 on Play Console > App integrity > + Play app signing (the Play API has only SHA-256, `generatedapks.list`). Version switch: `gameCenterAppVersions`. +- **Guard:** `cli/lib/game-services.ts` (validateGames, planGameCenter, planPlayGames, pgsFindings, gcFindings), + `storebound scan` rule `pgs.manifest` / `pgs.app-id`, `cli/play/games.ts` (no 5xx retry of an insert), + `tests/game-services.test.ts`. From d427b5c4a4c0706941a218efc3cb5735d1cc4cb4 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:14:23 +0700 Subject: [PATCH 070/344] apple game-center: literal API paths (query guard reads them); api coverage regenerated --- cli/api/wrapped.gen.ts | 8 ++++++++ cli/apple/game-center.ts | 14 ++++++++++---- docs/api-coverage.md | 18 +++++++++--------- 3 files changed, 27 insertions(+), 13 deletions(-) diff --git a/cli/api/wrapped.gen.ts b/cli/api/wrapped.gen.ts index 3252c91..7da7541 100644 --- a/cli/api/wrapped.gen.ts +++ b/cli/api/wrapped.gen.ts @@ -69,6 +69,7 @@ export const WRAPPED: { apple: Record; play: Record; play: Record; play: Record + type === 'gameCenterLeaderboards' ? `/v1/gameCenterLeaderboards/${id}/localizations?limit=200` : `/v1/gameCenterAchievements/${id}/localizations?limit=200`; +const itemsPath = (type: 'gameCenterLeaderboards' | 'gameCenterAchievements', detail: string): string => + type === 'gameCenterLeaderboards' ? `/v1/gameCenterDetails/${detail}/gameCenterLeaderboards?limit=200` : `/v1/gameCenterDetails/${detail}/gameCenterAchievements?limit=200`; + async function withLocs(c: Asc, list: J[], type: 'gameCenterLeaderboards' | 'gameCenterAchievements'): Promise { const out: GcExisting[] = []; - for (const x of list) out.push({ id: x.id, attributes: x.attributes ?? {}, localizations: (await c.all(`/v1/${type}/${x.id}/localizations?limit=200`)).map((l: J) => ({ id: l.id, attributes: l.attributes ?? {} })) }); + for (const x of list) out.push({ id: x.id, attributes: x.attributes ?? {}, localizations: (await c.all(locsPath(type, x.id))).map((l: J) => ({ id: l.id, attributes: l.attributes ?? {} })) }); return out; } @@ -100,12 +106,12 @@ export async function run(ctx: Ctx): Promise { log(TAG, `Game Center switched on for version ${s.version.versionString}`); } for (const p of plan) { - const type = p.kind === 'leaderboard' ? 'gameCenterLeaderboards' : 'gameCenterAchievements'; + const type = p.kind === 'leaderboard' ? 'gameCenterLeaderboards' as const : 'gameCenterAchievements' as const; const locType = p.kind === 'leaderboard' ? 'gameCenterLeaderboardLocalizations' : 'gameCenterAchievementLocalizations'; const parentRel = p.kind === 'leaderboard' ? 'gameCenterLeaderboard' : 'gameCenterAchievement'; let id = p.storeId; if (p.action === 'create') { - const find = async () => (await c.all(`/v1/gameCenterDetails/${detail}/${type}?limit=200`)).find((x: J) => x.attributes?.vendorIdentifier === p.id)?.id ?? null; + const find = async () => (await c.all(itemsPath(type, detail!))).find((x: J) => x.attributes?.vendorIdentifier === p.id)?.id ?? null; id = (await createOnce({ what: `${p.kind} ${p.id}`, tag: TAG, unique: true, find, create: async () => (await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { ...p.attributes, vendorIdentifier: p.id }, relationships: { gameCenterDetail: { data: { type: 'gameCenterDetails', id: detail } } } } })).data.id as string })).value; log(TAG, `${p.kind} ${p.id}: created`); @@ -118,7 +124,7 @@ export async function run(ctx: Ctx): Promise { if (l.action === 'create') { const pid = id!; await createOnce({ what: `${p.kind} ${p.id} ${l.locale}`, tag: TAG, unique: true, - find: async () => (await c.all(`/v1/${type}/${pid}/localizations?limit=200`)).find((x: J) => x.attributes?.locale === l.locale)?.id ?? null, + find: async () => (await c.all(locsPath(type, pid))).find((x: J) => x.attributes?.locale === l.locale)?.id ?? null, create: async () => (await c.asc('POST', `/v1/${locType}`, { data: { type: locType, attributes: { locale: l.locale, ...l.attributes }, relationships: { [parentRel]: { data: { type, id: pid } } } } })).data.id as string }); log(TAG, `${p.kind} ${p.id} ${l.locale}: created`); } else if (l.action === 'update') { diff --git a/docs/api-coverage.md b/docs/api-coverage.md index b71b200..22354bd 100644 --- a/docs/api-coverage.md +++ b/docs/api-coverage.md @@ -12,7 +12,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | API | operations | GET | other | wrapped by a command | owner only | |---|---:|---:|---:|---:|---:| -| App Store Connect API 4.5.1 | 1303 | 826 | 477 | 210 | 166 | +| App Store Connect API 4.5.1 | 1303 | 826 | 477 | 218 | 166 | | Google Play Android Developer API v3 (revision 20261008) | 145 | 45 | 100 | 35 | 49 | | Google Play Developer Reporting API v1beta1 (revision 20261008) | 25 | 15 | 10 | 6 | 0 | @@ -384,7 +384,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | `appStoreVersions_customerReviews_getToManyRelated` | GET | `/v1/appStoreVersions/{id}/customerReviews` | read | | | `appStoreVersions_customerReviews_getToManyRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/customerReviews` | read | | | `appStoreVersions_deleteInstance` | DELETE | `/v1/appStoreVersions/{id}` | owner only (typed confirm) | | -| `appStoreVersions_gameCenterAppVersion_getToOneRelated` | GET | `/v1/appStoreVersions/{id}/gameCenterAppVersion` | read | | +| `appStoreVersions_gameCenterAppVersion_getToOneRelated` | GET | `/v1/appStoreVersions/{id}/gameCenterAppVersion` | read | apple/game-center | | `appStoreVersions_gameCenterAppVersion_getToOneRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/gameCenterAppVersion` | read | | | `appStoreVersions_getInstance` | GET | `/v1/appStoreVersions/{id}` | read | apple/listing | | `appStoreVersions_routingAppCoverage_getToOneRelated` | GET | `/v1/appStoreVersions/{id}/routingAppCoverage` | read | | @@ -454,7 +454,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | `apps_customerReviews_getToManyRelationship` | GET | `/v1/apps/{id}/relationships/customerReviews` | read | | | `apps_endUserLicenseAgreement_getToOneRelated` | GET | `/v1/apps/{id}/endUserLicenseAgreement` | read | | | `apps_endUserLicenseAgreement_getToOneRelationship` | GET | `/v1/apps/{id}/relationships/endUserLicenseAgreement` | read | | -| `apps_gameCenterDetail_getToOneRelated` | GET | `/v1/apps/{id}/gameCenterDetail` | read | | +| `apps_gameCenterDetail_getToOneRelated` | GET | `/v1/apps/{id}/gameCenterDetail` | read | apple/game-center | | `apps_gameCenterDetail_getToOneRelationship` | GET | `/v1/apps/{id}/relationships/gameCenterDetail` | read | | | `apps_gameCenterEnabledVersions_getToManyRelated` | GET | `/v1/apps/{id}/gameCenterEnabledVersions` | read | | | `apps_gameCenterEnabledVersions_getToManyRelationship` | GET | `/v1/apps/{id}/relationships/gameCenterEnabledVersions` | read | | @@ -817,7 +817,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | `gameCenterAchievements_groupAchievement_getToOneRelated` | GET | `/v1/gameCenterAchievements/{id}/groupAchievement` | read | | | `gameCenterAchievements_groupAchievement_getToOneRelationship` | GET | `/v1/gameCenterAchievements/{id}/relationships/groupAchievement` | read | | | `gameCenterAchievements_groupAchievement_updateToOneRelationship` | PATCH | `/v1/gameCenterAchievements/{id}/relationships/groupAchievement` | write (dry by default) | | -| `gameCenterAchievements_localizations_getToManyRelated` | GET | `/v1/gameCenterAchievements/{id}/localizations` | read | | +| `gameCenterAchievements_localizations_getToManyRelated` | GET | `/v1/gameCenterAchievements/{id}/localizations` | read | apple/game-center | | `gameCenterAchievements_localizations_getToManyRelationship` | GET | `/v1/gameCenterAchievements/{id}/relationships/localizations` | read | | | `gameCenterAchievements_releases_getToManyRelated` | GET | `/v1/gameCenterAchievements/{id}/releases` | read | | | `gameCenterAchievements_releases_getToManyRelationship` | GET | `/v1/gameCenterAchievements/{id}/relationships/releases` | read | | @@ -868,7 +868,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | `gameCenterAppVersions_compatibilityVersions_deleteToManyRelationship` | DELETE | `/v1/gameCenterAppVersions/{id}/relationships/compatibilityVersions` | owner only (typed confirm) | | | `gameCenterAppVersions_compatibilityVersions_getToManyRelated` | GET | `/v1/gameCenterAppVersions/{id}/compatibilityVersions` | read | | | `gameCenterAppVersions_compatibilityVersions_getToManyRelationship` | GET | `/v1/gameCenterAppVersions/{id}/relationships/compatibilityVersions` | read | | -| `gameCenterAppVersions_createInstance` | POST | `/v1/gameCenterAppVersions` | write (dry by default) | | +| `gameCenterAppVersions_createInstance` | POST | `/v1/gameCenterAppVersions` | write (dry by default) | apple/game-center | | `gameCenterAppVersions_getInstance` | GET | `/v1/gameCenterAppVersions/{id}` | read | | | `gameCenterAppVersions_updateInstance` | PATCH | `/v1/gameCenterAppVersions/{id}` | write (dry by default) | | | **gameCenterChallengeImages** (4) | | | | | @@ -916,11 +916,11 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | `gameCenterDetails_challengeReleases_getToManyRelationship` | GET | `/v1/gameCenterDetails/{id}/relationships/challengeReleases` | read | | | `gameCenterDetails_challengesMinimumPlatformVersions_replaceToManyRelationship` | PATCH | `/v1/gameCenterDetails/{id}/relationships/challengesMinimumPlatformVersions` | write (dry by default) | | | `gameCenterDetails_classicMatchmakingRequests_getMetrics` | GET | `/v1/gameCenterDetails/{id}/metrics/classicMatchmakingRequests` | read | | -| `gameCenterDetails_createInstance` | POST | `/v1/gameCenterDetails` | write (dry by default) | | +| `gameCenterDetails_createInstance` | POST | `/v1/gameCenterDetails` | write (dry by default) | apple/game-center | | `gameCenterDetails_gameCenterAchievementsV2_getToManyRelated` | GET | `/v1/gameCenterDetails/{id}/gameCenterAchievementsV2` | read | | | `gameCenterDetails_gameCenterAchievementsV2_getToManyRelationship` | GET | `/v1/gameCenterDetails/{id}/relationships/gameCenterAchievementsV2` | read | | | `gameCenterDetails_gameCenterAchievementsV2_replaceToManyRelationship` | PATCH | `/v1/gameCenterDetails/{id}/relationships/gameCenterAchievementsV2` | write (dry by default) | | -| `gameCenterDetails_gameCenterAchievements_getToManyRelated` | GET | `/v1/gameCenterDetails/{id}/gameCenterAchievements` | read | | +| `gameCenterDetails_gameCenterAchievements_getToManyRelated` | GET | `/v1/gameCenterDetails/{id}/gameCenterAchievements` | read | apple/game-center | | `gameCenterDetails_gameCenterAchievements_getToManyRelationship` | GET | `/v1/gameCenterDetails/{id}/relationships/gameCenterAchievements` | read | | | `gameCenterDetails_gameCenterAchievements_replaceToManyRelationship` | PATCH | `/v1/gameCenterDetails/{id}/relationships/gameCenterAchievements` | write (dry by default) | | | `gameCenterDetails_gameCenterActivities_getToManyRelated` | GET | `/v1/gameCenterDetails/{id}/gameCenterActivities` | read | | @@ -940,7 +940,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | `gameCenterDetails_gameCenterLeaderboardsV2_getToManyRelated` | GET | `/v1/gameCenterDetails/{id}/gameCenterLeaderboardsV2` | read | | | `gameCenterDetails_gameCenterLeaderboardsV2_getToManyRelationship` | GET | `/v1/gameCenterDetails/{id}/relationships/gameCenterLeaderboardsV2` | read | | | `gameCenterDetails_gameCenterLeaderboardsV2_replaceToManyRelationship` | PATCH | `/v1/gameCenterDetails/{id}/relationships/gameCenterLeaderboardsV2` | write (dry by default) | | -| `gameCenterDetails_gameCenterLeaderboards_getToManyRelated` | GET | `/v1/gameCenterDetails/{id}/gameCenterLeaderboards` | read | | +| `gameCenterDetails_gameCenterLeaderboards_getToManyRelated` | GET | `/v1/gameCenterDetails/{id}/gameCenterLeaderboards` | read | apple/game-center | | `gameCenterDetails_gameCenterLeaderboards_getToManyRelationship` | GET | `/v1/gameCenterDetails/{id}/relationships/gameCenterLeaderboards` | read | | | `gameCenterDetails_gameCenterLeaderboards_replaceToManyRelationship` | PATCH | `/v1/gameCenterDetails/{id}/relationships/gameCenterLeaderboards` | write (dry by default) | | | `gameCenterDetails_getInstance` | GET | `/v1/gameCenterDetails/{id}` | read | | @@ -1106,7 +1106,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | `gameCenterLeaderboards_groupLeaderboard_getToOneRelated` | GET | `/v1/gameCenterLeaderboards/{id}/groupLeaderboard` | read | | | `gameCenterLeaderboards_groupLeaderboard_getToOneRelationship` | GET | `/v1/gameCenterLeaderboards/{id}/relationships/groupLeaderboard` | read | | | `gameCenterLeaderboards_groupLeaderboard_updateToOneRelationship` | PATCH | `/v1/gameCenterLeaderboards/{id}/relationships/groupLeaderboard` | write (dry by default) | | -| `gameCenterLeaderboards_localizations_getToManyRelated` | GET | `/v1/gameCenterLeaderboards/{id}/localizations` | read | | +| `gameCenterLeaderboards_localizations_getToManyRelated` | GET | `/v1/gameCenterLeaderboards/{id}/localizations` | read | apple/game-center | | `gameCenterLeaderboards_localizations_getToManyRelationship` | GET | `/v1/gameCenterLeaderboards/{id}/relationships/localizations` | read | | | `gameCenterLeaderboards_releases_getToManyRelated` | GET | `/v1/gameCenterLeaderboards/{id}/releases` | read | | | `gameCenterLeaderboards_releases_getToManyRelationship` | GET | `/v1/gameCenterLeaderboards/{id}/relationships/releases` | read | | From 567d6ca181409e0d9e7fa83d50751005376d97c9 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:28:02 +0700 Subject: [PATCH 071/344] gen-flags: Args.required reads are flags too (edit --ops, privacy-manifest --ios, apple listing --version were refused as unknown options); play games client listAll (no false flags) --- cli/data/flags.json | 20 ++++++++------------ cli/play/games.ts | 8 ++++---- tools/gen-flags.ts | 6 +++--- 3 files changed, 15 insertions(+), 19 deletions(-) diff --git a/cli/data/flags.json b/cli/data/flags.json index 8c967b1..54fd880 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -50,6 +50,7 @@ "upload" ], "apple adhoc": [ + "archive", "csv", "method", "name", @@ -178,6 +179,7 @@ "version" ], "apple resubmit": [ + "build", "new-version", "no-submit", "platform", @@ -212,6 +214,7 @@ "wait-review" ], "apple submit": [ + "build", "new-version", "no-submit", "platform", @@ -359,7 +362,6 @@ "write" ], "check": [ - "achievements", "aso", "capacitor", "cordova", @@ -369,7 +371,6 @@ "flutter", "godot", "keychain", - "leaderboards", "name", "no-install", "react-native", @@ -453,6 +454,7 @@ "dir" ], "edit": [ + "ops", "show" ], "flow": [ @@ -461,9 +463,7 @@ "resume" ], "games status": [ - "achievements", "keychain", - "leaderboards", "no-install" ], "health": [ @@ -598,10 +598,7 @@ "csv", "force" ], - "play games": [ - "achievements", - "leaderboards" - ], + "play games": [], "play images": [ "include-drafts", "not-sent-for-review", @@ -703,6 +700,7 @@ "with-automatic" ], "privacy-manifest": [ + "ios", "propose", "sdk-dirs", "tracking-domains" @@ -867,7 +865,6 @@ "play" ], "validate": [ - "achievements", "add-for-review", "allow-price-changes", "apple", @@ -884,7 +881,6 @@ "jobs", "keychain", "lang", - "leaderboards", "no-health", "no-install", "no-local", @@ -926,7 +922,6 @@ "ws": [ "aab", "accounts", - "achievements", "add-for-review", "adgroup", "against", @@ -943,6 +938,7 @@ "apple", "apply", "apps", + "archive", "aso", "base", "base-url", @@ -1028,7 +1024,6 @@ "landing", "lang", "languages", - "leaderboards", "limit", "listing-text", "listings", @@ -1075,6 +1070,7 @@ "only-keywords", "only-missing", "only-terms", + "ops", "originality", "out", "param", diff --git a/cli/play/games.ts b/cli/play/games.ts index 2e5e906..3cebf46 100644 --- a/cli/play/games.ts +++ b/cli/play/games.ts @@ -41,7 +41,7 @@ export function gamesConfigClient(root: string) { return (t ? JSON.parse(t) : {}) as T; } } - async function list(kind: 'achievements' | 'leaderboards', appId: string): Promise { + async function listAll(kind: 'achievements' | 'leaderboards', appId: string): Promise { const out: PlayExisting[] = []; let page: string | undefined; do { @@ -51,13 +51,13 @@ export function gamesConfigClient(root: string) { } while (page); return out; } - return { call, list }; + return { call, listAll }; } export const playDefaultLocale = (config: Ctx['loaded']['config']): string => config.play?.defaultLanguage ?? 'en-US'; export async function readPlayGames(c: ReturnType, appId: string): Promise<{ leaderboards: PlayExisting[]; achievements: PlayExisting[] }> { - return { leaderboards: await c.list('leaderboards', appId), achievements: await c.list('achievements', appId) }; + return { leaderboards: await c.listAll('leaderboards', appId), achievements: await c.listAll('achievements', appId) }; } const pending = (plan: ItemPlan[]) => plan.filter(p => p.action !== 'keep'); @@ -92,7 +92,7 @@ export async function run(ctx: Ctx): Promise { if (p.action === 'create') { const r = await createOnce({ what: `${p.kind} ${p.id}`, tag: TAG, create: async () => (await c.call('POST', `/applications/${appId}/${kind}`, p.attributes)).id, - find: async () => (await c.list(kind, appId)).find(x => x.draft?.name?.translations.some(t => t.locale === locale && t.value === name))?.id ?? null }); + find: async () => (await c.listAll(kind, appId)).find(x => x.draft?.name?.translations.some(t => t.locale === locale && t.value === name))?.id ?? null }); log(TAG, `${p.kind} ${p.id}: created as ${r.value} (set playId: "${r.value}" in the config to match it by id)`); } else { await c.call('PUT', `/${kind}/${encodeURIComponent(p.storeId!)}`, p.attributes); diff --git a/tools/gen-flags.ts b/tools/gen-flags.ts index 35034bf..c98884a 100644 --- a/tools/gen-flags.ts +++ b/tools/gen-flags.ts @@ -2,7 +2,7 @@ // Writes cli/data/flags.json: the --flags every command accepts, so the dispatcher (cli/index.ts) can reject an // unknown flag (a typo like --dyr) with the usage before anything runs, also in the compiled sidecar (no sources). // For each command in cli/commands.ts it follows the command module and every local module it imports (static and -// dynamic), and collects the literal flag reads: .has('name'), .get, .str, .num, .list, .many. Reads with a computed +// dynamic), and collects the literal flag reads: .has('name'), .get, .str, .num, .list, .many, .required. Reads with a computed // name are listed in DYNAMIC below (the scan fails on a new one until it is added there). `ws` forwards its flags to the // command it runs, so it accepts every flag. GLOBAL flags work on every command. The usage lines of each module's // header comment (`// storebound ...`) go along, for `storebound --help`. @@ -31,9 +31,9 @@ const DYNAMIC: Record = { const FORWARDS = new Set(['ws']); // the receiver is captured so HTTP headers and URL search params (res.headers.get('content-type')) are not flags -const READ = /([\w$.)\]]*)\.(?:has|get|str|num|list|many)\(\s*(['"])([a-z][a-z0-9-]*)\2/g; +const READ = /([\w$.)\]]*)\.(?:has|get|str|num|list|many|required)\(\s*(['"])([a-z][a-z0-9-]*)\2/g; const NOT_ARGS = /(?:headers|searchParams|params|url|env)$/i; -const COMPUTED = /\b(?:args|a|ctx\.args)\.(?:has|get|str|num|list|many)\(\s*(?![\s'"])/g; +const COMPUTED = /\b(?:args|a|ctx\.args)\.(?:has|get|str|num|list|many|required)\(\s*(?![\s'"])/g; const IMPORT = /(?:\bfrom\s+|\bimport\s*\(\s*)'(\.{1,2}\/[^']+)'/g; function file(spec: string, from: string): string | null { From dd9e059036fa14af899dd022d4700ed199c8420b Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:29:55 +0700 Subject: [PATCH 072/344] desktop coverage: apple game-center, play games and games status mapped to the Game services card --- cli/lib/desktop-coverage.ts | 3 +++ docs/desktop-coverage.md | 5 ++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/cli/lib/desktop-coverage.ts b/cli/lib/desktop-coverage.ts index 4f3c803..ba5a082 100644 --- a/cli/lib/desktop-coverage.ts +++ b/cli/lib/desktop-coverage.ts @@ -88,6 +88,7 @@ export const DESKTOP_COVERAGE: Record = { 'play listing': { where: 'Listings tab (push, pull)', methods: ['play.listing', 'play.listing_pull'] }, 'play images': { where: 'Listings tab: Play graphics', methods: ['play.images'] }, 'play data-safety': { where: 'App info tab: Data safety upload', methods: ['play.data_safety'] }, + 'play games': { where: 'App info tab: Game services card (Sync Play Games, Setup plan)', methods: ['play.games', 'games.status'] }, 'play release': { where: 'Releases tab: Send to production (owner action); testing tracks via play upload in More tools', methods: ['owner.play_production', 'play.upload'] }, 'play build': { where: `${T}: Build and upload`, methods: ['play.build'] }, 'play upload': { where: `${T}: Build and upload`, methods: ['play.upload'] }, @@ -123,6 +124,8 @@ export const DESKTOP_COVERAGE: Record = { 'apple adhoc': { where: `${T}: Ad-hoc devices (devices, register, options, export)`, methods: ['apple.adhoc_devices', 'apple.adhoc_register', 'apple.adhoc_options', 'apple.adhoc_export'] }, 'apple next-build': { where: `${T}: Build and upload`, methods: ['apple.next_build'] }, 'apple encryption': { where: 'App info tab: export compliance', methods: ['apple.encryption'] }, + 'apple game-center': { where: 'App info tab: Game services card (Sync Game Center)', methods: ['apple.game_center', 'games.status'] }, + 'games status': { where: 'App info tab: Game services card', methods: ['games.status'] }, 'apple ppo': { where: 'Growth tab: PPO tests (start / stop = owner actions)', methods: ['apple.ppo_status', 'apple.ppo_create', 'apple.ppo_upload', 'owner.ppo_start', 'owner.ppo_stop'] }, 'apple testflight': { where: 'TestFlight tab (status, groups, What to Test, distribute, testers = owner action); info and wait in More tools', methods: ['apple.testflight_status', 'apple.testflight_groups', 'apple.testflight_what_to_test', 'apple.testflight_distribute', 'owner.testflight_testers', 'apple.testflight_info', 'apple.testflight_wait'], owner: 'expire' }, 'icons': { where: 'Store art tab: icons', methods: ['icons'] }, diff --git a/docs/desktop-coverage.md b/docs/desktop-coverage.md index 687ded5..7d1e8ee 100644 --- a/docs/desktop-coverage.md +++ b/docs/desktop-coverage.md @@ -5,7 +5,7 @@ Every CLI command (cli/commands.ts) and the desktop place that runs it. "covered (serve.ts, or a host command `host:`) and the window calls it; tests/desktop-coverage.test.ts fails on a gap. Owner-only parts are owner actions in the window or owner steps with their terminal command (More tools). -**92 commands:** 88 covered, 0 gaps, 4 not for the desktop. +**95 commands:** 91 covered, 0 gaps, 4 not for the desktop. | command | status | where in the window | methods | owner step | |---|---|---|---|---| @@ -61,6 +61,8 @@ Owner-only parts are owner actions in the window or owner steps with their termi | `play rollout` | covered | Releases tab: rollout (owner action) | `owner.play_rollout` | | | `play share` | covered | More tools: Build and upload | `play.share` | | | `play app-id` | covered | More tools: Build and upload | `play.app_id` | | +| `games status` | covered | App info tab: Game services card | `games.status` | | +| `play games` | covered | App info tab: Game services card (Sync Play Games, Setup plan) | `play.games`, `games.status` | | | `play next-version-code` | covered | More tools: Build and upload | `play.next_version_code` | | | `apple bundle` | covered | More tools: Build and upload | `apple.bundle` | | | `apple iap` | covered | Catalog tab | `apple.iap` | | @@ -88,6 +90,7 @@ Owner-only parts are owner actions in the window or owner steps with their termi | `apple upload` | covered | More tools: Build and upload | `apple.upload` | | | `apple adhoc` | covered | More tools: Ad-hoc devices (devices, register, options, export) | `apple.adhoc_devices`, `apple.adhoc_register`, `apple.adhoc_options`, `apple.adhoc_export` | | | `apple next-build` | covered | More tools: Build and upload | `apple.next_build` | | +| `apple game-center` | covered | App info tab: Game services card (Sync Game Center) | `apple.game_center`, `games.status` | | | `apple encryption` | covered | App info tab: export compliance | `apple.encryption` | | | `apple ppo` | covered | Growth tab: PPO tests (start / stop = owner actions) | `apple.ppo_status`, `apple.ppo_create`, `apple.ppo_upload`, `owner.ppo_start`, `owner.ppo_stop` | | | `apple testflight` | covered | TestFlight tab (status, groups, What to Test, distribute, testers = owner action); info and wait in More tools | `apple.testflight_status`, `apple.testflight_groups`, `apple.testflight_what_to_test`, `apple.testflight_distribute`, `owner.testflight_testers`, `apple.testflight_info`, `apple.testflight_wait` | expire | From 163e6668340dd0a2301367300032d91e8e94f5ce Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:33:53 +0700 Subject: [PATCH 073/344] Game Center switch before submit: apple submit / resubmit and signing ensure create gameCenterDetails and gameCenterAppVersions when Game Center is in use (config, entitlements or the built IPA), shown in the dry run; validate blocks on either missing; fake 409 BUILD_INDICATES_GAME_CENTER_ENABLED until both exist; pitfall 89 --- cli/apple/game-center.ts | 65 ++++++++++++++++++++++-------- cli/apple/resubmit.ts | 10 ++++- cli/apple/signing.ts | 6 +++ cli/games-status.ts | 17 ++++---- cli/validate.ts | 2 +- skills/store-pitfalls/SKILL.md | 13 ++++++ tests/game-services.test.ts | 41 ++++++++++++++++++- tests/helpers/fake-stores.ts | 10 +++++ tests/signing-capabilities.test.ts | 14 +++++++ 9 files changed, 152 insertions(+), 26 deletions(-) diff --git a/cli/apple/game-center.ts b/cli/apple/game-center.ts index 9ee4eec..e122b2d 100644 --- a/cli/apple/game-center.ts +++ b/cli/apple/game-center.ts @@ -5,7 +5,7 @@ // find-then-create (createOnce: a conflict or an unclear answer reads the store again, never a second create) or a // PATCH of the fields that differ, so a re-run writes nothing. Nothing is deleted or archived; nothing is submitted // (leaderboards and achievements go to review with the next app version, the owner's Submit for review). -import { findBundleId, readProjectEntitlements } from './signing'; +import { builtIpaEntitlements, findBundleId, readProjectEntitlements } from './signing'; import { consoleLink } from '../lib/console-links'; import type { Ctx } from '../lib/ctx'; import { confirm, need } from '../lib/ctx'; @@ -90,21 +90,8 @@ export async function run(ctx: Ctx): Promise { console.log(dryPlan('apple game-center (to write)', rows).replace(/^dry run: /, '').replace(/; nothing written/, '')); if (!(await confirm(ctx, 'Write these Game Center changes to App Store Connect? (nothing is submitted; they go to review with the next version)'))) return; - let detail = s.detail; - if (!detail) { - const r = await createOnce({ what: 'Game Center detail', tag: TAG, unique: true, - create: async () => (await c.asc('POST', '/v1/gameCenterDetails', { data: { type: 'gameCenterDetails', relationships: { app: { data: { type: 'apps', id: appId } } } } })).data.id as string, - find: async () => (await c.maybe(`/v1/apps/${appId}/gameCenterDetail`))?.data?.id ?? null }); - detail = r.value; - log(TAG, `Game Center switched on for the app (${detail})`); - } - if (s.version && !s.version.enabled) { - const vid = s.version.id; - await createOnce({ what: `Game Center for version ${s.version.versionString}`, tag: TAG, unique: true, - create: async () => (await c.asc('POST', '/v1/gameCenterAppVersions', { data: { type: 'gameCenterAppVersions', relationships: { appStoreVersion: { data: { type: 'appStoreVersions', id: vid } } } } })).data.id as string, - find: async () => (await c.maybe(`/v1/appStoreVersions/${vid}/gameCenterAppVersion`))?.data?.id ?? null }); - log(TAG, `Game Center switched on for version ${s.version.versionString}`); - } + const sw = await ensureGcSwitch(c, { appId, detail: s.detail, version: s.version }); + const detail = sw.detail; for (const p of plan) { const type = p.kind === 'leaderboard' ? 'gameCenterLeaderboards' as const : 'gameCenterAchievements' as const; const locType = p.kind === 'leaderboard' ? 'gameCenterLeaderboardLocalizations' : 'gameCenterAchievementLocalizations'; @@ -139,3 +126,49 @@ export async function run(ctx: Ctx): Promise { if (!after.detail || left.length) warn(TAG, `read back: ${!after.detail ? 'no Game Center detail yet; ' : ''}${left.map(p => `${p.kind} ${p.id}`).join(', ') || ''} not listed as written yet (App Store Connect lists lag after a create): run storebound apple game-center status in a minute`); done(TAG, `Game Center: ${after.leaderboards.length} leaderboard(s), ${after.achievements.length} achievement(s); images and review go with the next version (${consoleLink('asc.version')})`); } + +// ------------------------------------------------------------------ the Game Center switch (submit, signing ensure) +// Seen live on a first submission: a build with com.apple.developer.game-center and an app version without Game +// Center answer 409 STATE_ERROR.BUILD_INDICATES_GAME_CENTER_ENABLED ("appStoreVersion is missing +// gameCenterConfigurations relationship"). What passes: POST /v1/gameCenterDetails {app} when the app has none, then +// POST /v1/gameCenterAppVersions {appStoreVersion} (both verified in specs/app-store-connect.oas.json). + +export interface GcSwitch { appId: string; detail: string | null; version: { id: string; versionString: string; enabled: boolean } | null } + +export async function readGcSwitch(c: Asc, appId: string, version: J | null): Promise { + const detail = (await c.maybe(`/v1/apps/${appId}/gameCenterDetail`))?.data?.id ?? null; + return { appId, detail, version: version ? { id: version.id, versionString: String(version.attributes?.versionString ?? ''), enabled: !!(await c.maybe(`/v1/appStoreVersions/${version.id}/gameCenterAppVersion`))?.data } : null }; +} + +/** The writes the switch still needs, as request lines (empty: on). */ +export function gcSwitchPlan(s: GcSwitch): string[] { + return [...(s.detail ? [] : [`POST /v1/gameCenterDetails {app=${s.appId}}`]), + ...(s.version && !s.version.enabled ? [`POST /v1/gameCenterAppVersions {appStoreVersion=${s.version.id}} # version ${s.version.versionString}`] : [])]; +} + +/** Creates what gcSwitchPlan names (find-then-create, never twice). */ +export async function ensureGcSwitch(c: Asc, s: GcSwitch, tag = TAG): Promise { + let detail = s.detail; + if (!detail) { + detail = (await createOnce({ what: 'Game Center detail', tag, unique: true, + create: async () => (await c.asc('POST', '/v1/gameCenterDetails', { data: { type: 'gameCenterDetails', relationships: { app: { data: { type: 'apps', id: s.appId } } } } })).data.id as string, + find: async () => (await c.maybe(`/v1/apps/${s.appId}/gameCenterDetail`))?.data?.id ?? null })).value; + log(tag, `Game Center switched on for the app (${detail})`); + } + const v = s.version; + if (v && !v.enabled) { + await createOnce({ what: `Game Center for version ${v.versionString}`, tag, unique: true, + create: async () => (await c.asc('POST', '/v1/gameCenterAppVersions', { data: { type: 'gameCenterAppVersions', relationships: { appStoreVersion: { data: { type: 'appStoreVersions', id: v.id } } } } })).data.id as string, + find: async () => (await c.maybe(`/v1/appStoreVersions/${v.id}/gameCenterAppVersion`))?.data?.id ?? null }); + log(tag, `Game Center switched on for version ${v.versionString}`); + } + return { ...s, detail, version: v ? { ...v, enabled: true } : null }; +} + +/** Game Center is in use when the config says so, the iOS project has the entitlement, or the newest local IPA does. */ +export function gameCenterInUse(config: Ctx['loaded']['config'], root: string): { inUse: boolean; why: string | null } { + if (usesGameCenter(config)) return { inUse: true, why: 'games.gameCenter' }; + try { const p = readProjectEntitlements(root)?.find(e => e.caps.some(x => x.cap === 'GAME_CENTER')); if (p) return { inUse: true, why: `${p.file} has com.apple.developer.game-center` }; } catch { /* unreadable */ } + try { const b = builtIpaEntitlements(root, config); if (b?.caps.some(x => x.cap === 'GAME_CENTER')) return { inUse: true, why: `build ${b.number} (${b.file}) has com.apple.developer.game-center` }; } catch { /* no IPA */ } + return { inUse: false, why: null }; +} diff --git a/cli/apple/resubmit.ts b/cli/apple/resubmit.ts index 095b164..dab7493 100644 --- a/cli/apple/resubmit.ts +++ b/cli/apple/resubmit.ts @@ -26,6 +26,7 @@ import { allSubscriptions } from '../lib/subscriptions'; import { ascClient, type J } from './asc'; import { readSubmitState, submitPlanned } from './iap-submit'; import { openSubmissions } from './submission'; +import { ensureGcSwitch, gameCenterInUse, gcSwitchPlan, readGcSwitch } from './game-center'; import { allVersions, parsePlatform, pickPlatform, platformLabel, platformOf, versionsPath } from './platform'; /** App Store version states a first submission may send: the editable version (Prepare for Submission, a rejected @@ -88,14 +89,20 @@ export async function submitVersion(ctx: Ctx, mode: 'submit' | 'resubmit'): Prom const marks = state.choice?.action === 'reuse' ? toResolve(state.choice.sub.items, resolve).map(i => ({ item: i.id ?? null, kind: i.kind, what: labelOf(state, i.versionId, i.kind) })) : []; const blockers = [...(build.action === 'refuse' ? [build.reason] : []), ...plan.blockers]; const dry = a.has('dry') || !a.has('yes'); + // Game Center: a build with the entitlement needs the app's Game Center detail and the version's switch, else the + // submission answers 409 STATE_ERROR.BUILD_INDICATES_GAME_CENTER_ENABLED (seen live); the same upsert as apple game-center + const gcUse = gameCenterInUse(config, root); + const gc = gcUse.inUse ? await readGcSwitch(c, appId, v) : null; + const gcPlan = gc ? gcSwitchPlan(gc) : []; if (a.has('json')) { - printJson({ dryRun: dry, version: { id: v.id, versionString, platform, state: stateOf(v) }, build, submission: state.choice ?? null, resolve: marks, rows, skipped: plan.skipped, blockers }); + printJson({ dryRun: dry, gameCenter: gcPlan, version: { id: v.id, versionString, platform, state: stateOf(v) }, build, submission: state.choice ?? null, resolve: marks, rows, skipped: plan.skipped, blockers }); // the desktop's owner dialog shows the output text: the plan table goes with the result there if (process.env.STOREBOUND_MACHINE === '1') { console.log(formatRows(rows)); for (const x of blockers) warn(TAG, x); } if (blockers.length) process.exitCode = 1; if (dry || blockers.length || state.choice?.action === 'busy') return; } else { console.log(formatRows(rows)); + for (const l of gcPlan) log(TAG, `${dry ? 'would ' : ''}${l} (Game Center: ${gcUse.why})`); for (const s of plan.skipped) log(TAG, `not added ${s.id}: ${s.why}`); for (const x of blockers) warn(TAG, x); } @@ -110,5 +117,6 @@ export async function submitVersion(ctx: Ctx, mode: 'submit' | 'resubmit'): Prom await c.asc('PATCH', `/v1/appStoreVersions/${v.id}/relationships/build`, { data: { type: 'builds', id: build.id } }); log(TAG, `build ${number} attached to ${versionString}`); } + if (gc && gcPlan.length) await ensureGcSwitch(c, gc, TAG); await submitPlanned(ctx, c, { appId, ids, state, tag: TAG, withVersion: true, appVersionId: v.id, platform, quiet: true, resolve }); } diff --git a/cli/apple/signing.ts b/cli/apple/signing.ts index 90f569c..724e56c 100644 --- a/cli/apple/signing.ts +++ b/cli/apple/signing.ts @@ -11,6 +11,7 @@ // App Store profile per bundle id (apple.bundleId + apple.signing.extraBundleIds) and installs it for Xcode. // Every write is shown first (--dry shows only that) and asks once before anything is created. Developer ID // certificates need the Account Holder: the API's 403 is explained. Pure planning: cli/lib/signing.ts. +import { ensureGcSwitch, gcSwitchPlan, readGcSwitch } from './game-center'; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'; import { homedir, tmpdir } from 'node:os'; import { basename, dirname, join, relative, resolve as resolvePath } from 'node:path'; @@ -313,6 +314,10 @@ export async function run(ctx: Ctx): Promise { return !p || p.create ? [`POST /v1/profiles {name=..., profileType="${profileType}"} # ${id}: ${p?.why ?? 'with the new certificate'}`] : []; })), ]; + // GAME_CENTER on the App ID: the app and its editable version need the Game Center switch too (apple game-center) + const gcSw = capabilitySpecs(s, config.games?.gameCenter === true).some(w => w.type === 'GAME_CENTER') ? await (async () => { try { return await readGcSwitch(c, await c.app(), await c.editableVersion()); } catch { return null; /* no app record yet: apple game-center later */ } })() : null; + const gcPlan = gcSw ? gcSwitchPlan(gcSw) : []; + plan.push(...gcPlan); log(TAG, scope.why); if (needCert && state.certificate.limit && state.certificate.onTeam >= state.certificate.limit) warn(TAG, `the team already has ${state.certificate.onTeam} valid ${certType} certificates (limit ${state.certificate.limit}): Apple will refuse a new one until one is revoked (owner decision, developer.apple.com > Certificates)`); @@ -331,6 +336,7 @@ export async function run(ctx: Ctx): Promise { const responses = await execute(c.asc, capPlan.create, { dry: false, tag: TAG }); if (capPlan.create.length) await checkCapabilitiesStuck(c, bundleId, capabilitySpecs(s, config.games?.gameCenter === true).map(w => w.type), responses); + if (gcPlan.length && gcSw) await ensureGcSwitch(c, gcSw, TAG); if (!scope.profiles) { printCapabilityReport(await capabilityReport(c, config, root), TAG); cleanup(); diff --git a/cli/games-status.ts b/cli/games-status.ts index 0cedfe3..a1a2048 100644 --- a/cli/games-status.ts +++ b/cli/games-status.ts @@ -2,18 +2,18 @@ // Local part (no network): the Game Center entitlement, the PGS APP_ID resource and Gradle dependency, the player-id // declaration reminders. Store part: Game Center (App ID capability, detail, version switch, counts, pending changes) // and Play Games Services (counts, pending changes). -import { readGameCenter } from './apple/game-center'; +import { gameCenterInUse, readGameCenter } from './apple/game-center'; import { ascClient } from './apple/asc'; import { readProjectEntitlements } from './apple/signing'; import type { Loaded } from './lib/config'; import { consoleUrl } from './lib/console-links'; -import { type Finding, gamesPrivacyFindings, gcFindings, hasAndroidProject, planGameCenter, planPlayGames, pgsFindings, readPgsProject, usesGameCenter, usesPlayGames } from './lib/game-services'; +import { type Finding, gamesPrivacyFindings, gcFindings, hasAndroidProject, planGameCenter, planPlayGames, pgsFindings, readPgsProject, usesPlayGames } from './lib/game-services'; import type { Finding as VFinding } from './lib/validate-rules'; import { gamesConfigClient, playDefaultLocale, readPlayGames } from './play/games'; export interface GameServicesStatus { apple: null | { capability: boolean | null; enabled: boolean; version: string | null; versionEnabled: boolean | null; leaderboards: number; achievements: number; - config: { leaderboards: number; achievements: number }; changes: string[]; error?: string }; + config: { leaderboards: number; achievements: number }; changes: string[]; error?: string; why?: string }; play: null | { appId: string | null; resource: string | null; leaderboards: number; achievements: number; config: { leaderboards: number; achievements: number }; changes: string[]; error?: string }; findings: (Finding & { store: 'apple' | 'play' })[]; @@ -40,13 +40,14 @@ export async function gameServicesStatus(loaded: Loaded, o: { apple?: boolean; p const out: GameServicesStatus = { apple: null, play: null, findings, links: [] }; const count = (store: 'apple' | 'play') => ({ leaderboards: (g.leaderboards ?? []).filter(x => !x.platforms || x.platforms.includes(store === 'apple' ? 'ios' : 'android')).length, achievements: (g.achievements ?? []).filter(x => !x.platforms || x.platforms.includes(store === 'apple' ? 'ios' : 'android')).length }); - if (config.apple && usesGameCenter(config) && o.apple !== false) { + const gcUse = config.apple ? gameCenterInUse(config, root) : { inUse: false, why: null }; + if (config.apple && gcUse.inUse && o.apple !== false) { out.links.push({ label: 'App Store Connect: the version page (Game Center section)', url: consoleUrl('asc.version') }); try { const c = await ascClient(root, config.apple.bundleId, config.apple.appId); const s = await readGameCenter(c, config.apple.bundleId); out.apple = { capability: s.capability, enabled: !!s.detail, version: s.version?.versionString ?? null, versionEnabled: s.version ? s.version.enabled : null, - leaderboards: s.leaderboards.length, achievements: s.achievements.length, config: count('apple'), changes: changesOf(planGameCenter(g, config.languages, s)) }; + leaderboards: s.leaderboards.length, achievements: s.achievements.length, config: count('apple'), changes: changesOf(planGameCenter(g, config.languages, s)), why: gcUse.why ?? undefined }; } catch (e) { out.apple = { capability: null, enabled: false, version: null, versionEnabled: null, leaderboards: 0, achievements: 0, config: count('apple'), changes: [], error: (e as Error).message.slice(0, 300) }; } } if (config.play && usesPlayGames(config) && o.play !== false) { @@ -71,8 +72,10 @@ export function gameServicesFindings(s: GameServicesStatus): VFinding[] { if (a.error) out.push({ store: 'apple', level: 'warn', code: 'game-center', msg: `Game Center not read: ${a.error}` }); else { if (a.capability === false) out.push({ store: 'apple', level: 'blocker', code: 'game-center.capability', msg: 'games.gameCenter is true but the App ID has no GAME_CENTER capability: the build\'s profile will not allow Game Center', fix: 'storebound apple signing ensure --dry, then without --dry' }); - if (!a.enabled) out.push({ store: 'apple', level: 'blocker', code: 'game-center.detail', msg: 'Game Center is not switched on for the app in App Store Connect', fix: 'storebound apple game-center --dry, then without --dry' }); - if (a.versionEnabled === false) out.push({ store: 'apple', level: 'warn', code: 'game-center.version', msg: `version ${a.version} does not have Game Center switched on`, fix: 'storebound apple game-center' }); + const why = a.why ? ` (${a.why})` : ''; + const bounce = 'the submission would answer 409 STATE_ERROR.BUILD_INDICATES_GAME_CENTER_ENABLED'; + if (!a.enabled) out.push({ store: 'apple', level: 'blocker', code: 'game-center.detail', msg: `Game Center is in use${why} but the app has no Game Center detail in App Store Connect: ${bounce}`, fix: 'storebound apple game-center --dry, then without --dry (apple submit runs the same switch)' }); + if (a.versionEnabled === false) out.push({ store: 'apple', level: 'blocker', code: 'game-center.version', msg: `Game Center is in use${why} but version ${a.version} has no Game Center switch (gameCenterAppVersion): ${bounce}`, fix: 'storebound apple game-center --dry, then without --dry (apple submit runs the same switch)' }); if (a.changes.length) out.push({ store: 'apple', level: 'warn', code: 'game-center.sync', msg: `Game Center differs from the config: ${a.changes.slice(0, 6).join('; ')}${a.changes.length > 6 ? ` (+${a.changes.length - 6})` : ''}`, fix: 'storebound apple game-center --dry' }); if (a.enabled && !a.changes.length) out.push({ store: 'apple', level: 'ok', code: 'game-center', msg: `Game Center on: ${a.leaderboards} leaderboard(s), ${a.achievements} achievement(s), in step with the config` }); } diff --git a/cli/validate.ts b/cli/validate.ts index 73dbead..7819d81 100644 --- a/cli/validate.ts +++ b/cli/validate.ts @@ -228,7 +228,7 @@ export async function run(ctx: Ctx): Promise { catch (e) { findings.push({ store: 'play', level: 'blocker', code: 'api', msg: (e as Error).message.slice(0, 400) }, ...rendersFindings('play', local?.play)); } } else if (a.has('play')) warn('validate', 'no play section in the config'); // Game Center / Play Games Services: entitlement, APP_ID resource, store state vs the config - if (config.games && (config.games.gameCenter || config.games.playGames)) { + if (config.games || config.apple) { try { findings.push(...gameServicesFindings(await gameServicesStatus(ctx.loaded, { apple: both || a.has('apple'), play: both || a.has('play') }))); } catch (e) { warn('validate', `game services: ${(e as Error).message}`); } } diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index a3e993b..db3e96b 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1087,3 +1087,16 @@ that fails without the fix (see CONTRIBUTING.md). - **Guard:** `cli/lib/game-services.ts` (validateGames, planGameCenter, planPlayGames, pgsFindings, gcFindings), `storebound scan` rule `pgs.manifest` / `pgs.app-id`, `cli/play/games.ts` (no 5xx retry of an insert), `tests/game-services.test.ts`. + +## 89. Submit refused: 409 STATE_ERROR.BUILD_INDICATES_GAME_CENTER_ENABLED +- **Symptom:** `apple submit` of a first version failed with 409 `STATE_ERROR.BUILD_INDICATES_GAME_CENTER_ENABLED`: + "The build for this app store version has com.apple.developer.game-center entitlement but appStoreVersion is + missing gameCenterConfigurations relationship". The build had the entitlement; the app had no Game Center detail. +- **Do:** `storebound apple game-center --dry`, then without `--dry`: `POST /v1/gameCenterDetails` (app) when the + app has none, then `POST /v1/gameCenterAppVersions` (appStoreVersion). The resubmit then passes. `apple submit` / + `resubmit` and `apple signing ensure` (when GAME_CENTER is wanted) now run the same switch first and show it in + the dry run; `validate` blocks while either is missing and Game Center is in the config, the entitlements or the + built IPA. +- **Guard:** `readGcSwitch` / `gcSwitchPlan` / `ensureGcSwitch` / `gameCenterInUse` in `cli/apple/game-center.ts`, + `gameServicesFindings` (codes game-center.detail, game-center.version), the fake store's `gameCenterBuild` 409 and + `tests/game-services.test.ts`. diff --git a/tests/game-services.test.ts b/tests/game-services.test.ts index 8287d4f..f47c27e 100644 --- a/tests/game-services.test.ts +++ b/tests/game-services.test.ts @@ -11,6 +11,7 @@ import { verifyText } from '../cli/lib/console-verify'; import { gameServicesFindings, type GameServicesStatus } from '../cli/games-status'; import { run as gameCenter } from '../cli/apple/game-center'; import { run as playGames } from '../cli/play/games'; +import { run as appleSubmit } from '../cli/apple/submit'; import { upsertTiming } from '../cli/lib/upsert'; import { ascEnv, BASE, capture, playEnv, project, restore } from './helpers/store-mock'; import { installStores, type Stores, uninstallStores, writes } from './helpers/fake-stores'; @@ -202,9 +203,47 @@ describe('validate findings', () => { findings: [{ store: 'apple', level: 'error', id: 'gc.entitlement', msg: 'no entitlement' }], links: [], }; const f = gameServicesFindings(st); - expect(f.filter(x => x.level === 'blocker').map(x => x.code)).toEqual(['gc.entitlement', 'game-center.capability', 'game-center.detail']); + expect(f.filter(x => x.level === 'blocker').map(x => x.code)).toEqual(['gc.entitlement', 'game-center.capability', 'game-center.detail', 'game-center.version']); + expect(f.find(x => x.code === 'game-center.detail')!.msg).toContain('BUILD_INDICATES_GAME_CENTER_ENABLED'); expect(f.map(x => x.code)).toContain('game-center.sync'); expect(f.find(x => x.code === 'play-games')!.level).toBe('ok'); expect(f.find(x => x.code === 'play-games.achievements')!.level).toBe('warn'); }); }); + +describe('apple submit with a Game Center build (live 409 STATE_ERROR.BUILD_INDICATES_GAME_CENTER_ENABLED)', () => { + const fresh = () => { + s.asc.gameCenterBuild = true; + s.asc.put({ type: 'appStoreVersions', id: 'ver-1', attributes: { versionString: '1.0.0', appVersionState: 'PREPARE_FOR_SUBMISSION', platform: 'IOS' }, rels: { app: APP } }); + s.asc.put({ type: 'builds', id: 'b-8', attributes: { version: '8', processingState: 'VALID', usesNonExemptEncryption: false }, rels: { app: APP } }); + }; + test('the fake refuses the submit like App Store Connect while the switch is missing', async () => { + fresh(); + const r = await capture(() => appleSubmit(project(BASE).ctx(['--build', '8', '--yes'])).catch(e => { console.error(String(e)); })); + expect(r.err + r.out).toContain('BUILD_INDICATES_GAME_CENTER_ENABLED'); + expect(s.asc.all('reviewSubmissions').map(x => x.attributes.state)).not.toContain('WAITING_FOR_REVIEW'); + }); + test('dry run names the switch; --yes creates gameCenterDetails and gameCenterAppVersions before the submit, then passes', async () => { + fresh(); + const p = project(GAME); + const dry = await run2(() => appleSubmit(p.ctx(['--build', '8']))); + expect(dry.writes).toEqual([]); + expect(dry.out).toContain('would POST /v1/gameCenterDetails'); + expect(dry.out).toContain('would POST /v1/gameCenterAppVersions'); + const r = await run2(() => appleSubmit(p.ctx(['--build', '8', '--yes']))); + const i = r.writes.indexOf('POST /v1/gameCenterDetails'), j = r.writes.indexOf('POST /v1/gameCenterAppVersions'), k = r.writes.findIndex(w => /^PATCH \/v1\/reviewSubmissions\//.test(w)); + expect(i).toBeGreaterThanOrEqual(0); + expect(j).toBeGreaterThan(i); + expect(k).toBeGreaterThan(j); + expect(s.asc.all('reviewSubmissions').map(x => x.attributes.state)).toEqual(['WAITING_FOR_REVIEW']); + expect(s.asc.all('gameCenterDetails')).toHaveLength(1); + }); + test('apple game-center first, then submit: no second switch', async () => { + fresh(); + const p = project(GAME); + await run2(() => gameCenter(p.ctx(['--yes']))); + const r = await run2(() => appleSubmit(p.ctx(['--build', '8', '--yes']))); + expect(r.writes.filter(w => /gameCenter(Details|AppVersions)$/.test(w))).toEqual([]); + expect(s.asc.all('gameCenterAppVersions')).toHaveLength(1); + }); +}); diff --git a/tests/helpers/fake-stores.ts b/tests/helpers/fake-stores.ts index 6897d42..0a1e00d 100644 --- a/tests/helpers/fake-stores.ts +++ b/tests/helpers/fake-stores.ts @@ -134,6 +134,9 @@ export class FakeAsc { lag: Record = {}; /** every uploaded part, by asset id */ parts: string[] = []; + /** The attached builds carry com.apple.developer.game-center: submitting answers Apple's 409 (seen live) until the + * app has a gameCenterDetail and the version a gameCenterAppVersion. */ + gameCenterBuild = false; constructor(readonly appId = '6400000101') { this.put({ type: 'apps', id: appId, attributes: { bundleId: 'com.example.notes', name: 'Example Notes' }, rels: {} }); @@ -335,6 +338,13 @@ export class FakeAsc { // seen live (2026-10-12): a REJECTED item that is not marked resolved blocks every submit with this 409, and an // empty draft cannot be canceled const items = this.children(self.id, 'reviewSubmissionItems'); + if (attrs.submitted && this.gameCenterBuild) { + const app = String(self.rels.app); + const ver = items.map(it => String(it.rels.appStoreVersion ?? '')).find(Boolean); + if (!this.children(app, 'gameCenterDetails').length || (ver && !this.children(ver, 'gameCenterAppVersions').length)) + return json({ errors: [{ status: '409', code: 'STATE_ERROR.BUILD_INDICATES_GAME_CENTER_ENABLED', title: 'The request cannot be fulfilled because of the state of another resource.', + detail: 'The build for this app store version has com.apple.developer.game-center entitlement but appStoreVersion is missing gameCenterConfigurations relationship.' }] }, 409); + } if (attrs.submitted && items.some(it => it.attributes.state === 'REJECTED')) return json({ errors: [{ status: '409', code: 'STATE_ERROR', title: 'The request cannot be fulfilled because of the state of another resource.', detail: 'Version is not ready to be submitted yet, please try again later' }] }, 409); if (attrs.canceled && self.attributes.state === 'READY_FOR_REVIEW' && !items.length) diff --git a/tests/signing-capabilities.test.ts b/tests/signing-capabilities.test.ts index b01d1b4..787d29f 100644 --- a/tests/signing-capabilities.test.ts +++ b/tests/signing-capabilities.test.ts @@ -86,6 +86,9 @@ describe('apple signing ensure', () => { { match: /^\/v1\/certificates\?/, answer: page([]) }, { match: /^\/v1\/bundleIds\/BUNDLE0001\/profiles/, answer: page([sbProfile]) }, { match: /^\/v1\/profiles\/PROF0001\/relationships\/certificates/, answer: page([{ type: 'certificates', id: 'CERT0001' }]) }, + // GAME_CENTER is wanted: ensure reads the app's Game Center switch (on here; the editable version list is empty) + { match: /^\/v1\/apps\/6400000101\/gameCenterDetail/, answer: { data: { type: 'gameCenterDetails', id: 'GCD0001' } } }, + { match: /^\/v1\/apps\/6400000101\/appStoreVersions/, answer: page([]) }, { method: 'POST', match: /^\/v1\/bundleIdCapabilities$/, answer: (c: { body: unknown }) => ({ data: cap((c.body as { data: { attributes: { capabilityType: string } } }).data.attributes.capabilityType) }) }, ]; @@ -103,6 +106,17 @@ describe('apple signing ensure', () => { expect(calls.filter(c => c.method !== 'GET')).toEqual([]); }); + test('GAME_CENTER without the app\'s Game Center detail: the dry run plans gameCenterDetails too (the submit 409 otherwise)', async () => { + ascEnv(); + const p = project(cfg('automatic')); + const rs = routes(['IN_APP_PURCHASE']); + rs.unshift({ match: /^\/v1\/apps\/6400000101\/gameCenterDetail/, answer: { errors: [{ status: '404' }] } as never, status: 404 } as never); + const calls = mockFetch(rs); + const r = await capture(() => signing(p.ctx(['ensure', '--dry']))); + expect(r.out + r.err).toContain('would POST /v1/gameCenterDetails'); + expect(calls.filter(c => c.method !== 'GET')).toEqual([]); + }); + test('automatic: a real run adds capabilities, reads them back and creates no certificate or profile', async () => { ascEnv(); const p = project(cfg('automatic')); From aceb994cae58b345b334f4b1f289dd1b41109616 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:35:19 +0700 Subject: [PATCH 074/344] testflight distribute: groups of apple.testflight.groups missing on App Store Connect are created first (only the asked-for ones, never removed; dry run shows it); tests, skill, CHANGELOG --- CHANGELOG.md | 6 +++++ cli/apple/testflight.ts | 48 ++++++++++++++++++++++++++------------ skills/testflight/SKILL.md | 5 ++-- tests/idempotency.test.ts | 21 ++++++++++++++--- 4 files changed, 60 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4da74d3..8afab1d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- **`apple submit` / `resubmit` switch Game Center on first.** A build with the Game Center entitlement and an app + without a Game Center detail was refused with 409 STATE_ERROR.BUILD_INDICATES_GAME_CENTER_ENABLED; submit, + resubmit and `apple signing ensure` now create `gameCenterDetails` and the version's `gameCenterAppVersions` first + (dry run shows it), and `validate` blocks while either is missing. Pitfall 89. +- **`apple testflight distribute` creates missing configured groups first** (only the asked-for ones, never removes + one); tester invites stay the owner's. - **Console plans follow the live pages (2026-10-21 run).** Play health: "My app does not have any health features" (verify accepts it, "Other" stays a fallback); Sign in details: "Is any part of your app restricted?" Yes / No and "Add details" (old labels kept as `altLabels`); finance: the boxes on step 1, step 2 information only; App Privacy: diff --git a/cli/apple/testflight.ts b/cli/apple/testflight.ts index 5a5b330..63c272c 100644 --- a/cli/apple/testflight.ts +++ b/cli/apple/testflight.ts @@ -29,7 +29,7 @@ import { parseTesters, pickBuild, planBetaInfo, planBetaReviewDetail, planDistribute, planGroups, planTesters, planWhatToTest, unknownGroupMessage, whatToTestFromListing, } from '../lib/testflight'; import { type Asc, ascClient, type J } from './asc'; -import { describeReq, execute } from './jsonapi'; +import { describeReq, execute, type Req } from './jsonapi'; import { findOrCreate, getById } from '../lib/upsert'; import * as rt from '../lib/rt'; @@ -87,6 +87,19 @@ async function pagesOf(c: Asc, path: string): Promise { return out; } +/** Creates the planned groups (fresh lookup, then the journal for the list lag, then the create; a 409 finds it). */ +async function createGroups(c: Asc, appId: string, root: string, create: Req[], dry: boolean): Promise { + if (dry) { await execute(c.asc, create, { dry, tag: TAG }); return; } + for (const r of create) { + const name = (r.body as J).data.attributes.name as string; + const made = await findOrCreate({ what: `beta group "${name}"`, tag: TAG, unique: true, + find: async () => (await c.all(`/v1/apps/${appId}/betaGroups?limit=200`)).find((g: J) => g.attributes.name === name) ?? null, + journal: { root, key: `apple:${appId}:betaGroup:${name}`, byId: id => getById(c.asc, `/v1/betaGroups/${id}`) as Promise, idOf: v => v.id }, + create: async () => (await c.asc('POST', r.path, r.body)).data }); + log(TAG, `${describeReq(r)}: ${made.created ? 'done' : 'exists already'}`); + } +} + async function groups(c: Asc, appId: string): Promise { return (await c.all(`/v1/apps/${appId}/betaGroups?limit=200`)).map(groupFromApi); } @@ -154,16 +167,7 @@ export async function run(ctx: Ctx): Promise { } if (!tf?.groups?.length) warn(TAG, 'apple.testflight.groups is empty: nothing to create'); for (const n of plan.existing) log(TAG, `group "${n}": exists`); - if (dry) await execute(c.asc, plan.create, { dry, tag: TAG }); - else for (const r of plan.create) { - // looked up right before the create (fresh list, then the journal for the list lag); a 409 finds it - const name = (r.body as J).data.attributes.name as string; - const made = await findOrCreate({ what: `beta group "${name}"`, tag: TAG, unique: true, - find: async () => (await c.all(`/v1/apps/${appId}/betaGroups?limit=200`)).find((g: J) => g.attributes.name === name) ?? null, - journal: { root, key: `apple:${appId}:betaGroup:${name}`, byId: id => getById(c.asc, `/v1/betaGroups/${id}`) as Promise, idOf: v => v.id }, - create: async () => (await c.asc('POST', r.path, r.body)).data }); - log(TAG, `${describeReq(r)}: ${made.created ? 'done' : 'exists already'}`); - } + await createGroups(c, appId, root, plan.create, dry); done(TAG, dry ? `groups checked (dry run): ${plan.create.length} to create` : `groups done (${plan.create.length} created)`); return; } @@ -238,10 +242,24 @@ export async function run(ctx: Ctx): Promise { const number = need(a.get('build'), '--build N (the exact build number you uploaded)'); const names = a.list('group'); if (!names.length) throw new Error('--group [,]: which beta groups get the build'); - const gs = await groups(c, appId); - const missing = names.filter(n => !gs.some(g => g.name === n)); - if (missing.length) throw new Error(unknownGroupMessage(missing, gs, tf?.groups ?? [])); - const target = names.map(n => gs.find(g => g.name === n)!); + let gs = await groups(c, appId); + // groups the config names but App Store Connect does not have yet: the groups sync first (create only the missing + // configured ones of --group, never remove any); a name the config does not know stays an error + const absent = names.filter(n => !gs.some(g => g.name === n)); + const configured = (tf?.groups ?? []).filter(g => absent.includes(g.name)); + const unknown = absent.filter(n => !configured.some(g => g.name === n)); + if (unknown.length) throw new Error(unknownGroupMessage(unknown, gs, tf?.groups ?? [])); + if (configured.length) { + const sync = planGroups(appId, gs, configured); + log(TAG, `${dry ? 'would create' : 'creating'} beta group(s) from apple.testflight.groups first: ${configured.map(g => `"${g.name}"`).join(', ')} (testers stay the owner's: apple testflight testers)`); + await createGroups(c, appId, root, sync.create, dry); + if (dry) { + for (const g of configured) log(TAG, `would POST /v1/betaGroups//relationships/builds {build ${number}}${g.internal && g.allBuilds ? ' (none: an internal all-builds group gets it by itself)' : ''}`); + if (configured.length === names.length) { done(TAG, 'distribute checked (dry run)'); return; } + } else gs = await groups(c, appId); + } + const target = names.map(n => gs.find(g => g.name === n)).filter((g): g is Group => !!g); + if (!dry && target.length < names.length) throw new Error(`beta group(s) ${names.filter(n => !target.some(g => g.name === n)).join(', ')} created but not listed yet (App Store Connect lists lag after a create): run distribute again in a minute; nothing is created twice`); const external = target.filter(g => !g.internal); if (a.has('internal-only') && external.length) throw new Error(`external group(s) ${external.map(g => g.name).join(', ')}: distribute to external testers from the terminal (asks first)`); const b = await findBuild(c, appId, number, a.get('version')); diff --git a/skills/testflight/SKILL.md b/skills/testflight/SKILL.md index a720a5c..42aadae 100644 --- a/skills/testflight/SKILL.md +++ b/skills/testflight/SKILL.md @@ -64,8 +64,9 @@ beta app localization before a Beta App Review submission, and fields cannot be distribute reports "already available to (internal, all builds)" and sends nothing (App Store Connect refuses adding a build to such a group). Internal groups without all builds get the build like external ones. A re-run adds nothing (it reads each group's builds first). -- A group in `apple.testflight.groups` that is not on App Store Connect yet: run `storebound apple testflight groups - sync` first (distribute and testers say so); a name in neither lists the groups that exist. +- A group in `apple.testflight.groups` that is not on App Store Connect yet: `distribute` creates it first (the + groups sync for the missing `--group` names only; it never removes a group) and the dry run shows it. Inviting + testers stays the owner's step (`apple testflight testers`). A name in neither lists the groups that exist. - External: same command with an external group; it asks first. External testers only get the build after **Beta App Review**: add `--submit-review` (asks again) or submit in App Store Connect. The first build of a version is reviewed; later builds of the same version are often approved quickly. Beta review states: `WAITING_FOR_REVIEW`, diff --git a/tests/idempotency.test.ts b/tests/idempotency.test.ts index 670f19e..26d6ae3 100644 --- a/tests/idempotency.test.ts +++ b/tests/idempotency.test.ts @@ -134,11 +134,26 @@ describe('apple testflight distribute (real use 2026-10-13)', () => { expect(out.out).toContain('already in Devs (internal)'); }); - test('a group in the config but not on App Store Connect points at groups sync; an unknown one lists what exists', async () => { + test('a group in the config but not on App Store Connect is created first (groups sync), then gets the build; the re-run writes nothing', async () => { + const p = project(TF); + s.asc.put({ type: 'builds', id: 'b-1', attributes: { version: '1', processingState: 'VALID', usesNonExemptEncryption: false, expired: false }, rels: { app: APP } }); + s.asc.put({ type: 'betaGroups', id: 'grp-devs', attributes: { name: 'Devs', isInternalGroup: true, hasAccessToAllBuilds: false }, rels: { app: APP } }); + const dry = await capture(() => appleTestflight(p.ctx(['distribute', '--build', '1', '--group', 'Friends', '--dry']))); + expect(dry.out).toContain('would create beta group(s) from apple.testflight.groups first: "Friends"'); + expect(count('betaGroups')).toBe(1); + const r = await twice(() => appleTestflight(p.ctx(['distribute', '--build', '1', '--group', 'Friends,Devs', '--yes']))); + expect(r.first[0]).toBe('POST /v1/betaGroups'); + expect(r.first.filter(w => w === 'POST /v1/betaGroups')).toHaveLength(1); + expect(r.first.filter(w => /relationships\/builds$/.test(w))).toHaveLength(2); + expect(r.second).toEqual([]); + // only the missing one of --group was created; Team (configured, not asked for) was not; nothing removed + expect(s.asc.all('betaGroups').map(g => g.attributes.name).sort()).toEqual(['Devs', 'Friends']); + expect(s.calls.some(c => c.method === 'DELETE')).toBe(false); + }); + + test('an unknown group (not in the config) still lists what exists', async () => { const p = project(TF); s.asc.put({ type: 'builds', id: 'b-1', attributes: { version: '1', processingState: 'VALID' }, rels: { app: APP } }); - await expect(capture(() => appleTestflight(p.ctx(['distribute', '--build', '1', '--group', 'Team', '--yes'])))) - .rejects.toThrow('group "Team" is in the config but not on App Store Connect yet: create it with `storebound apple testflight groups sync`'); s.asc.put({ type: 'betaGroups', id: 'grp-friends', attributes: { name: 'Friends', isInternalGroup: false }, rels: { app: APP } }); await expect(capture(() => appleTestflight(p.ctx(['distribute', '--build', '1', '--group', 'Nope', '--yes'])))) .rejects.toThrow('unknown group "Nope": App Store Connect has "Friends"'); From 9c1f146c0584b725e6a3eb7767e2cf86e04053b8 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:36:12 +0700 Subject: [PATCH 075/344] flags regenerated --- cli/data/flags.json | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cli/data/flags.json b/cli/data/flags.json index 54fd880..938d845 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -180,7 +180,9 @@ ], "apple resubmit": [ "build", + "keychain", "new-version", + "no-install", "no-submit", "platform", "resolve-iaps", @@ -215,7 +217,9 @@ ], "apple submit": [ "build", + "keychain", "new-version", + "no-install", "no-submit", "platform", "resolve-iaps", From b6ea9159d82f8584947a9efb8ed473b46d08eed5 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:16:46 +0700 Subject: [PATCH 076/344] review-details: a reviewContact that is present but has empty fields (or no usable email) is named as such with its file, instead of 'no review contact' --- cli/lib/credentials.ts | 11 +++++++++-- tests/console-guardrails-1021.test.ts | 20 +++++++++++++++++++- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/cli/lib/credentials.ts b/cli/lib/credentials.ts index 27f9662..34c890c 100644 --- a/cli/lib/credentials.ts +++ b/cli/lib/credentials.ts @@ -254,11 +254,18 @@ export function findReviewContact(root: string): { contact: ReviewContact | null if (!existsSync(f)) { checked.push(`${f} (missing)`); continue; } let st: Store; try { st = JSON.parse(readFileSync(f, 'utf8')) as Store; } catch (e) { checked.push(`${f} (unreadable: ${(e as Error).message})`); continue; } + let present = ''; for (const k of REVIEW_CONTACT_KEYS) { - const c = contactOf(atPath(st, k)); + const raw = atPath(st, k); + const c = contactOf(raw); if (c) return { contact: c, from: `${f} ${k}`, checked }; + // a key that is there but holds no usable email (empty strings copied from a template): say exactly that + if (!present && raw && typeof raw === 'object' && !Array.isArray(raw)) { + const vals = Object.values(raw as Record).filter(v => typeof v === 'string') as string[]; + present = vals.every(v => !v.trim()) ? `${k} found but all its fields are empty` : `${k} found but its email is missing or a placeholder`; + } } - checked.push(`${f} (keys ${REVIEW_CONTACT_KEYS.join(', ')}: none with an email)`); + checked.push(present ? `${f} (${present}: fill firstName, lastName, phone, email)` : `${f} (keys ${REVIEW_CONTACT_KEYS.join(', ')}: none with an email)`); } return { contact: null, from: null, checked }; } diff --git a/tests/console-guardrails-1021.test.ts b/tests/console-guardrails-1021.test.ts index 1035f82..cb7651b 100644 --- a/tests/console-guardrails-1021.test.ts +++ b/tests/console-guardrails-1021.test.ts @@ -168,8 +168,10 @@ describe('6. the review contact', () => { writeFileSync(join(top, '.storebound', 'credentials.json'), JSON.stringify({ reviewContact: { firstName: 'Ada' } })); const m = noContactMessage(top); expect(m).toContain(join(top, '.storebound', 'credentials.json')); - expect(m).toContain('reviewContact, apple.reviewContact'); + expect(m).toContain('reviewContact found but its email is missing'); expect(m).toContain('--contact-from'); + writeFileSync(join(top, '.storebound', 'credentials.json'), JSON.stringify({ other: 1 })); + expect(noContactMessage(top)).toContain('reviewContact, apple.reviewContact'); }); }); @@ -189,3 +191,19 @@ describe('7. one-line errors for missing required values', () => { expect(p.exitCode).toBe(1); }); }); + +test('a reviewContact that is there with empty fields is named as such, not "no review contact"', async () => { + const { mkdtempSync, mkdirSync, writeFileSync, rmSync } = await import('node:fs'); + const { tmpdir } = await import('node:os'); + const { join } = await import('node:path'); + const { findReviewContact, noContactMessage } = await import('../cli/lib/credentials'); + const d = mkdtempSync(join(tmpdir(), 'sb-contact-empty-')); + try { + mkdirSync(join(d, '.storebound'), { recursive: true }); + mkdirSync(join(d, '.git')); + writeFileSync(join(d, '.storebound', 'credentials.json'), JSON.stringify({ reviewContact: { firstName: '', lastName: '', phone: '', email: '' } })); + const r = findReviewContact(d); + expect(r.contact).toBeNull(); + expect(noContactMessage(d, r.checked)).toContain('reviewContact found but all its fields are empty'); + } finally { rmSync(d, { recursive: true, force: true }); } +}); From 327a85e042bae20e438037f390a5450736093cd6 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:39:45 +0700 Subject: [PATCH 077/344] console verify: an older page's long labelled radio still counts from page text when the sheet answers Yes / No; tests and the teaser follow the new sign-in details question and the added App Privacy step --- cli/lib/console-verify.ts | 3 +++ media/teaser/script.js | 6 +++--- tests/guest-login-wall.test.ts | 8 ++++---- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/cli/lib/console-verify.ts b/cli/lib/console-verify.ts index b23359a..797e227 100644 --- a/cli/lib/console-verify.ts +++ b/cli/lib/console-verify.ts @@ -388,6 +388,9 @@ export function verifyPlayDeclaration(form: Exclude !/^(yes|no)$/i.test(l) && blob.includes(fold(l))) : undefined; + if (older) { rows.push({ item: a.question, expected: want, seen: older, status: 'match' }); continue; } const plain = !want || /^(yes|no)$/i.test(want) || a.action === 'untick'; if (plain) { rows.push({ item: a.question, expected: a.text, seen: 'not readable from page text', status: 'not-found', note: 'pass the input states: run the plan\'s verify.capture snippet and `--from -`' }); continue; } const shownAs = a.action === 'type' || a.action === 'choose' ? (blob.includes(fold(want)) ? want : null) : labels.find(l => blob.includes(fold(l))) ?? null; diff --git a/media/teaser/script.js b/media/teaser/script.js index a3c5166..844967c 100644 --- a/media/teaser/script.js +++ b/media/teaser/script.js @@ -136,9 +136,9 @@ export const PRIVACY_ANSWERS = [ export const PRIVACY_STEPS = [ ' 1. Open App Store Connect > Apps > the app > App Privacy (sidebar): https://appstoreconnect.apple.com/apps', ' 2. First time: click "Get Started" and answer the Data Collection question; then Next. [click: "Get Started"]', - ' 5. "Email Address" step 1, purposes: tick and untick the 6 checkboxes as answered, then Next. [click: "Next"]', - ' 6. "Email Address" step 2, linked to the user: pick the radio, then Next. [click: "Next"]', - ' 8. "Email Address" step 5, tracking: pick the radio, then Save (a draft). Never "Definitions and Examples". The dialog closes; the row shows Edit and the summary. [click: "Save"]', + ' 6. "Email Address" step 1, purposes: tick and untick the 6 checkboxes as answered, then Next. [click: "Next"]', + ' 7. "Email Address" step 2, linked to the user: pick the radio, then Next. [click: "Next"]', + ' 9. "Email Address" step 5, tracking: pick the radio, then Save (a draft). Never "Definitions and Examples". The dialog closes; the row shows Edit and the summary. [click: "Save"]', ]; export const DATA_SAFETY_CSV = [ 'PSL_DATA_COLLECTION_COLLECTS_PERSONAL_DATA,,TRUE,REQUIRED,Does your app collect or share any of the required user data types?', diff --git a/tests/guest-login-wall.test.ts b/tests/guest-login-wall.test.ts index 8390298..b62f699 100644 --- a/tests/guest-login-wall.test.ts +++ b/tests/guest-login-wall.test.ts @@ -57,7 +57,7 @@ describe('check: guest-play apps that Play may read as a login wall', () => { describe('plan play-sign-in-details: guest steps', () => { test('instructions with no sign-in: restricted, one entry without credentials, the box is the owner\'s', () => { const p = consolePlan('play-sign-in-details', guest); - expect(p.answers.find(a => a.id === 'access')).toMatchObject({ value: true, status: 'certain', label: 'All or some functionality in my app is restricted' }); + expect(p.answers.find(a => a.id === 'access')).toMatchObject({ value: true, status: 'certain', label: 'Yes' }); expect(p.answers.find(a => a.id === 'entryName')).toMatchObject({ value: GUEST_ENTRY_NAME, status: 'certain', action: 'type' }); expect(p.answers.find(a => a.id === 'credentials')).toMatchObject({ value: null, status: 'certain', text: 'leave both empty (no account)' }); expect(p.answers.find(a => a.id === 'credentials')!.action).toBeUndefined(); @@ -65,7 +65,7 @@ describe('plan play-sign-in-details: guest steps', () => { expect(p.answers.find(a => a.id === 'fullAccess')).toMatchObject({ status: 'agreement', value: null, control: 'checkbox', label: PLAY_FULL_ACCESS_BOX }); expect(p.answers.find(a => a.id === 'fullAccess')!.action).toBeUndefined(); // the agent presses Add instructions, Add and Save; the box and Send changes for review are the owner's - expect(p.buttons.allowed.map(b => b.button)).toEqual(expect.arrayContaining(['Add instructions', 'Add', 'Save'])); + expect(p.buttons.allowed.map(b => b.button)).toEqual(expect.arrayContaining(['Add details', 'Add', 'Save'])); expect(p.buttons.final).toBe('Send changes for review'); expect(p.buttons.neverPress).toContain('Send changes for review'); expect(p.ownerBatch.map(o => [o.when, o.kind])).toEqual([['after', 'agreement'], ['after', 'final']]); @@ -80,7 +80,7 @@ describe('plan play-sign-in-details: guest steps', () => { test('verify reads the entry name and the steps back, never the box', () => { const page = `Sign in details\nAll or some functionality in my app is restricted\n${GUEST_ENTRY_NAME}\n${STEPS}`; const r = verifyPlayDeclaration('play-sign-in-details', guest, page); - expect(r.rows.filter(x => x.status === 'match').map(x => x.item)).toEqual(['Is any functionality restricted (sign-in, membership, location)?', 'Name of the instructions entry', 'Instructions for the reviewer']); + expect(r.rows.filter(x => x.status === 'match').map(x => x.item)).toEqual(['Is any part of your app restricted?', 'Name of the instructions entry', 'Instructions for the reviewer']); expect(r.rows.some(x => /full access/.test(x.item))).toBe(false); expect(r.mismatches).toBe(0); }); @@ -93,7 +93,7 @@ describe('plan play-sign-in-details: guest steps', () => { test('no instructions: the "No restrictions" path stays', () => { const p = consolePlan('play-sign-in-details', { ...base, reviewAccess: { signInRequired: false } } as ShipConfig); expect(p.answers.map(a => [a.id, a.value])).toEqual([['access', false]]); - expect(p.answers[0]!.label).toBe('All functionality in my app is available without any access restrictions'); + expect(p.answers[0]!.label).toBe('No'); expect(p.buttons.allowed.map(b => b.button)).not.toContain('Add'); expect(p.ownerBatch.map(o => o.kind)).toEqual(['final']); }); From 0d1926f7d7465b79955a0c78ab17b9e7dcf2448e Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 05:42:04 +0700 Subject: [PATCH 078/344] storebound 0.8.22: version in package.json and every copy, CHANGELOG 0.8.22 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 7c77d07..7d25e86 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.21", + "version": "0.8.22", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 04d9838..d9968e5 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.21", + "version": "0.8.22", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 11c9600..6752976 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.21", + "version": "0.8.22", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index 8afab1d..41efbd9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.22 · 2026-10-20 + - **`apple submit` / `resubmit` switch Game Center on first.** A build with the Game Center entitlement and an app without a Game Center detail was refused with 409 STATE_ERROR.BUILD_INDICATES_GAME_CENTER_ENABLED; submit, resubmit and `apple signing ensure` now create `gameCenterDetails` and the version's `gameCenterAppVersions` first diff --git a/apps/desktop/package.json b/apps/desktop/package.json index b924c70..5d47da1 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.21", + "version": "0.8.22", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 4daed19..af0900d 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4010,7 +4010,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.21" +version = "0.8.22" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 2460322..9746ddd 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.21" +version = "0.8.22" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 435aa8b..b8dd75f 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.21", + "version": "0.8.22", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index 1711a59..8803e07 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.21", + "version": "0.8.22", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index 198206c..7ee212f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.21", + "version": "0.8.22", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From 4d70be34041c273a37e731ec3b6ad445e56171b6 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 11:19:50 +0700 Subject: [PATCH 079/344] apple submit --yes submits a draft prepared with --no-submit that already holds the version and items (was 'nothing to submit'); iap-submit the same for a draft holding the asked-for items; test, pitfall 90, CHANGELOG --- CHANGELOG.md | 4 ++++ cli/apple/iap-submit.ts | 4 ++-- cli/lib/review-submit.ts | 18 ++++++++++++++---- docs/pitfalls.md | 1 + skills/store-pitfalls/SKILL.md | 13 +++++++++++++ tests/resubmit.test.ts | 18 ++++++++++++++++++ 6 files changed, 52 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 41efbd9..e87006d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- **`apple submit --yes` submits a draft prepared with `--no-submit`.** The second step of the two-step flow + ended with "nothing to submit" when the draft already held the version and every item; it now sends the submit + (same "not ready yet" retry). `iap-submit` the same for a draft that holds the asked-for items. Pitfall 90. + ## 0.8.22 · 2026-10-20 - **`apple submit` / `resubmit` switch Game Center on first.** A build with the Game Center entitlement and an app diff --git a/cli/apple/iap-submit.ts b/cli/apple/iap-submit.ts index a282826..9e4e9ac 100644 --- a/cli/apple/iap-submit.ts +++ b/cli/apple/iap-submit.ts @@ -121,7 +121,7 @@ export async function submitPlanned(ctx: Ctx, c: Asc, o: SubmitOpts): Promise bindIds(r, { app: o.appId })); - const submitting = willSubmit(state, plan); + const submitting = willSubmit(state, plan, o.appVersionId); const busy = state.choice?.action === 'busy'; if (a.has('json') && !o.quiet) { printJson({ dryRun: dry, items: plan.items, skipped: plan.skipped, firstOfType: plan.firstOfType, hasApprovedVersion: plan.hasApprovedVersion, @@ -149,7 +149,7 @@ export async function submitPlanned(ctx: Ctx, c: Asc, o: SubmitOpts): Promise x.groupId === s.subs.find(y => y.productId === id)?.groupId && APPROVED_PRODUCT.has(x.state)) : !approvedTypes.has(type); - if (plan.skipped.length > before && firstOfType && NEVER_SUBMITTED.has(productState) && plan.skipped.at(-1)?.why !== 'already in the draft submission') leftOut.push(`${id} (${plan.skipped.at(-1)?.why})`); + if (plan.skipped.length > before && firstOfType && NEVER_SUBMITTED.has(productState) && plan.skipped.at(-1)?.why !== ALREADY_IN_DRAFT) leftOut.push(`${id} (${plan.skipped.at(-1)?.why})`); }; const leftOut: string[] = []; const pickOne = (id: string, productState: string, versions: PVersion[], kind: ItemKind, type: string): void => { @@ -172,7 +175,7 @@ export function planIapSubmission(s: SubmitState, want: string[], o: { withVersi if (!v) { plan.skipped.push({ id, why: 'no version on App Store Connect yet (create the product first: storebound apple iap / apple subscriptions)' }); return; } if (IN_REVIEW.has(v.state)) { plan.skipped.push({ id, why: `already ${v.state}` }); return; } if (!SUBMITTABLE.has(v.state)) { plan.skipped.push({ id, why: `latest version is ${v.state}: ${NEW_VERSION_FROM.has(v.state) ? 'add --new-version to send a new version' : 'change it in App Store Connect to send a new version'}` }); return; } - if (already.has(v.id)) { plan.skipped.push({ id, why: 'already in the draft submission' }); return; } + if (already.has(v.id)) { plan.skipped.push({ id, why: ALREADY_IN_DRAFT }); return; } plan.items.push({ kind, versionId: v.id, label: `${id} (${typeLabel(type)}, version ${v.version ?? '?'})`, ...(v.state === 'DEVELOPER_REJECTED' ? { devRejected: true } : {}) }); if (!approvedTypes.has(type)) firstTypes.add(type); }; @@ -222,8 +225,15 @@ export function planIapSubmission(s: SubmitState, want: string[], o: { withVersi /** The plan's word for an item it adds. Pure. */ export const addAction = (it: PlanItem): string => (it.devRejected ? `add (${DEV_REJECTED_NOTE})` : 'add'); -/** Whether the run ends with a submit: new items, or a submission back from App Review that only needs resubmitting. Pure. */ -export const willSubmit = (s: SubmitState, plan: SubmitPlan): boolean => plan.items.length > 0 || s.draft?.state === 'UNRESOLVED_ISSUES'; +/** Whether the run ends with a submit: new items, a submission back from App Review that only needs resubmitting, or a + * draft prepared earlier (`--no-submit`) that already holds what was asked for: the app version when one is named, + * else at least one of the asked-for items. Pure. */ +export function willSubmit(s: SubmitState, plan: SubmitPlan, appVersionId?: string): boolean { + if (plan.items.length > 0 || s.draft?.state === 'UNRESOLVED_ISSUES') return true; + const held = s.draft?.itemVersionIds ?? []; + if (!held.length) return false; + return appVersionId ? held.includes(appVersionId) : plan.skipped.some(sk => sk.why === ALREADY_IN_DRAFT); +} /** Fills the placeholders of a planned request (app id, the id of the draft created a moment ago). Pure. */ export function bindIds(r: Req, ids: { app?: string; submission?: string }): Req { diff --git a/docs/pitfalls.md b/docs/pitfalls.md index 42ad0d1..b1248cc 100644 --- a/docs/pitfalls.md +++ b/docs/pitfalls.md @@ -9,6 +9,7 @@ fails without the fix. | # | date | lesson | guard | |---|---|---|---| +| 90 | 2026-10 | `apple submit --build N --version X --yes` after `apple submit --no-submit --yes` (the documented two-step flow) printed the plan (every item "in it already", then "submit PATCH submitted: true"), logged "not added ...: already in the draft submission" and ended with "nothing to submit" without the PATCH: the submit only ran for new items or an UNRESOLVED_ISSUES submission. | `willSubmit` (cli/lib/review-submit.ts) also submits a READY_FOR_REVIEW draft that already holds the named app version (iap-submit: one of the asked-for items), with the same "not ready yet" retry. `tests/resubmit.test.ts` ("the second step submits the prepared draft"). | | 85 | 2026-10 | `shots record --source web` filmed at the page's CSS size: Chromium's screencast ignores the deviceScaleFactor (maxWidth only shrinks), so a 1080x1920 preview of a 430x932 @2x page was a 2.5x upscale. | `Page.captureScreenshot` with `clip.scale` = dpr (long side capped at 1920), 3 requests in flight, timestamped frames joined by ffmpeg; a warning when the first frame is smaller than asked or the rate is under 20 frames/s. `recordSize` / `captureShortfall` in `cli/shots/devices.ts`, `tests/video.test.ts`. | | 80 | 2026-10 | A game's hero logo and titles sat against the screenshot edges, a game with a macOS version had no Mac screenshots, and the contact sheet timed out at a flat 30 s with 9 sizes. | Templates keep 7 % / 5 % safe margins and `shots check` fails text or logo boxes under 6 % / 4 % (`marginViolations`, report.json `boxes`); `apple.mac` adds the `mac` size (APP_DESKTOP, macOS version); `sheetTimeoutMs` scales with images, sizes and load. `tests/mac-landscape.test.ts`, `tests/browser/landscape.browser.ts`. | | 78 | 2026-10 | `storebound api --yes` with stdout piped or redirected printed a dry run and exited 0 (twice); the owner took it as sent. | `decide` (`cli/api/gate.ts`) refuses with `NOT_A_TTY`: exit 1, "refused: writes through `storebound api` need an interactive terminal ... Nothing was sent." on stderr, the dedicated command named; without `--yes` still a dry run. `tests/api.test.ts`. | diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index db3e96b..b9b143d 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1100,3 +1100,16 @@ that fails without the fix (see CONTRIBUTING.md). - **Guard:** `readGcSwitch` / `gcSwitchPlan` / `ensureGcSwitch` / `gameCenterInUse` in `cli/apple/game-center.ts`, `gameServicesFindings` (codes game-center.detail, game-center.version), the fake store's `gameCenterBuild` 409 and `tests/game-services.test.ts`. + +## 90. The second step of `apple submit --no-submit` said "nothing to submit" +- **Symptom:** `apple submit --build N --version X --yes` after `apple submit --no-submit --yes` prepared the draft + printed the plan (every item "in it already", last row "submit PATCH submitted: true · owner step (--yes)"), + logged "not added : already in the draft submission" for each item and ended with "nothing to submit"; the + draft stayed READY_FOR_REVIEW and was never sent. +- **Cause:** the submit ran only when the run added items or the submission was back from App Review + (UNRESOLVED_ISSUES). A draft that already held everything counted as nothing to do. +- **Do:** update storebound and run the same `--yes` again: the prepared draft is submitted as it is (with the + "not ready yet" retry). A plan that ends with a submit row and a run that ends with "nothing to submit" is a bug: + check `apple status` for the draft's state before re-running anything else. +- **Guard:** `willSubmit` in `cli/lib/review-submit.ts` (a non-empty READY_FOR_REVIEW draft that holds the named app + version, or for `iap-submit` an asked-for item, is submitted); `tests/resubmit.test.ts`. diff --git a/tests/resubmit.test.ts b/tests/resubmit.test.ts index f86d62a..ac9259f 100644 --- a/tests/resubmit.test.ts +++ b/tests/resubmit.test.ts @@ -225,6 +225,24 @@ describe('apple submit --build (a first submission, the desktop owner action expect(shown(b)).toEqual([]); }); + test('--no-submit --yes, then --yes: the second step submits the prepared draft that holds everything already', async () => { + fresh(); + const p = project(ONE); + await capture(() => appleSubmit(p.ctx(['--build', '8', '--no-submit', '--yes']))); + const sid = s.asc.all('reviewSubmissions')[0]!.id; + expect(s.asc.all('reviewSubmissions').map(x => x.attributes.state)).toEqual(['READY_FOR_REVIEW']); + expect(s.asc.children(sid, 'reviewSubmissionItems')).toHaveLength(2); + s.faults.push({ ...NOT_READY, match: new RegExp(`^/v1/reviewSubmissions/${sid}$`), times: 1 }); + const a = s.calls.length; + const r = await capture(() => appleSubmit(p.ctx(['--build', '8', '--yes']))); + expect([r.exit ?? 0, r.err]).toEqual([0, '']); + expect(r.out).toContain('in it already'); + expect(r.out).not.toContain('nothing to submit'); + expect(shown(a)).toEqual([`PATCH /v1/reviewSubmissions/${sid}`, `PATCH /v1/reviewSubmissions/${sid}`]); + expect(s.asc.all('reviewSubmissions').map(x => x.attributes.state)).toEqual(['WAITING_FOR_REVIEW']); + expect(r.out).toContain(`review submission ${sid} submitted`); + }); + test('a live version is not submitted; no editable version is a clear stop', async () => { fresh(); s.asc.res.get('ver-1')!.attributes.appVersionState = 'READY_FOR_SALE'; From 164182012fba7e3120ed90e5b7dc6e9f50617ef7 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 11:21:56 +0700 Subject: [PATCH 080/344] storebound 0.8.23: version in package.json and every copy, CHANGELOG 0.8.23 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 7d25e86..e978bf6 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.22", + "version": "0.8.23", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index d9968e5..a05cceb 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.22", + "version": "0.8.23", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 6752976..037b08f 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.22", + "version": "0.8.23", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index e87006d..844b291 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.23 · 2026-10-21 + - **`apple submit --yes` submits a draft prepared with `--no-submit`.** The second step of the two-step flow ended with "nothing to submit" when the draft already held the version and every item; it now sends the submit (same "not ready yet" retry). `iap-submit` the same for a draft that holds the asked-for items. Pitfall 90. diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 5d47da1..af4ef39 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.22", + "version": "0.8.23", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index af0900d..622bd1b 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4010,7 +4010,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.22" +version = "0.8.23" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 9746ddd..795c54a 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.22" +version = "0.8.23" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index b8dd75f..a0d4a78 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.22", + "version": "0.8.23", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index 8803e07..cea40a8 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.22", + "version": "0.8.23", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index 7ee212f..ce1bffc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.22", + "version": "0.8.23", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From 00756e6908597725f4db4240563a2d5d507a3cc0 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 12:40:26 +0700 Subject: [PATCH 081/344] Screenshot guardrails: name every screenshot not COMPLETE on 409 ASSET_IN_POST_PROCESSING (submit, validate; stuck after 5 min in UPLOAD_COMPLETE), apple screenshots --repair-stuck replaces only those in place, part uploads without Expect: 100-continue (failed part deletes the reservation, one retry, never committed), storebound api --confirm for agents' plain writes (never owner-only) --- cli/api.ts | 8 +- cli/api/gate.ts | 21 ++++- cli/api/wrapped.gen.ts | 10 ++- cli/apple/asc.ts | 54 ++++++++---- cli/apple/creative-assets.ts | 7 +- cli/apple/resubmit.ts | 11 ++- cli/apple/screenshot-health.ts | 147 ++++++++++++++++++++++++++++++++ cli/apple/screenshots.ts | 36 ++++++++ cli/apple/upload.ts | 4 +- cli/commands.ts | 2 +- cli/data/flags.json | 10 ++- cli/lib/validate-rules.ts | 11 +++ cli/validate.ts | 9 +- docs/api-coverage.md | 16 ++-- skills/store-api/SKILL.md | 3 + skills/store-pitfalls/SKILL.md | 23 +++++ tests/api.test.ts | 16 +++- tests/idempotency.test.ts | 5 +- tests/screenshot-health.test.ts | 127 +++++++++++++++++++++++++++ 19 files changed, 475 insertions(+), 45 deletions(-) create mode 100644 cli/apple/screenshot-health.ts create mode 100644 tests/screenshot-health.test.ts diff --git a/cli/api.ts b/cli/api.ts index b91de2e..b8b5568 100644 --- a/cli/api.ts +++ b/cli/api.ts @@ -3,7 +3,7 @@ // storebound api list [--store apple|play] [--search text] [--json] // storebound api coverage [--store apple|play] [--json] // storebound api apple|play [--param k=v ...] [--body file.json] [--upload file] -// [--out file] [--all-pages] [--json] [--dry] [--yes] +// [--out file] [--all-pages] [--json] [--dry] [--yes [--confirm ]] // storebound api get apple|play ... GET only (what the MCP tool api_get runs) // // GETs run right away. Writes print the exact request and are only sent with --yes in an interactive terminal; @@ -28,12 +28,13 @@ export const USAGE = `usage: storebound api list [--store apple|play] [--search text] [--json] storebound api coverage [--store apple|play] [--json] storebound api apple|play [--param k=v ...] [--body file.json] [--upload file] - [--out file] [--all-pages] [--json] [--dry] [--yes] + [--out file] [--all-pages] [--json] [--dry] [--yes [--confirm ]] storebound api get apple|play [--param k=v ...] [--all-pages] [--json] (GET only) GETs run right away. Writes print the exact request and are sent only with --yes in a terminal; owner-only operations (submit, release, delete, cancel, prices, testers, review replies, experiments) also ask you to type the -operation id. Full table: docs/api-coverage.md`; +operation id. Agents without a terminal: --yes --confirm (must equal the operation id; plain writes +only, never owner-only operations). Full table: docs/api-coverage.md`; export interface Row { store: Store; id: string; method: string; path: string; gate: GateKind; wrapped: string } @@ -144,6 +145,7 @@ export async function run(args: Args): Promise { kind, method: op.method, dry: args.has('dry'), yes: args.has('yes'), getOnly, tty: stdinIsTTY() && !!process.stdout.isTTY, agent: process.env.STOREBOUND_SERVE === '1' || process.env.STOREBOUND_MCP === '1', + confirm: args.get('confirm'), opId: op.id, }); if (decision.action === 'refuse') { const instead = op.method !== 'GET' ? dedicatedCommand(st, op.id) : null; diff --git a/cli/api/gate.ts b/cli/api/gate.ts index 95bd857..599721e 100644 --- a/cli/api/gate.ts +++ b/cli/api/gate.ts @@ -2,7 +2,8 @@ // // read GET (and a few POSTs that only compute or query, listed below): runs right away. // write any other POST / PATCH / PUT / DELETE: prints the exact request; sent only with --yes in an interactive -// terminal, never under MCP (`storebound mcp`) or the desktop app (`storebound serve`). +// terminal, or with --yes --confirm (equal to the resolved id) from an agent's shell without a +// terminal; never under MCP (`storebound mcp`) or the desktop app (`storebound serve`). // owner writes that submit, release, delete, cancel, change prices, invite or remove testers, send review replies, // start or stop experiments, refund or rotate keys (AGENTS.md rule 1): a write that also needs the operation id // typed at the prompt. Never reachable through MCP or serve. @@ -78,6 +79,10 @@ export interface GateInput { agent: boolean; /** `storebound api get` (the MCP api_get tool): plain GETs only */ getOnly: boolean; + /** --confirm : the non-interactive confirmation for an agent in a shell (plain writes only) */ + confirm?: string; + /** the operation id the call resolved to (what --confirm must equal) */ + opId?: string; } export type Decision = @@ -87,9 +92,13 @@ export type Decision = | { action: 'refuse'; why: string }; /** --yes without a terminal: refused loudly (exit 1, stderr), never a silent dry run (pitfall 77). */ -export const NOT_A_TTY = 'refused: writes through `storebound api` need an interactive terminal (stdout is not a TTY: piped or redirected). Nothing was sent. Run it without a pipe or redirect, or use the dedicated storebound command.'; +export const NOT_A_TTY = 'refused: writes through `storebound api` need an interactive terminal (stdout is not a TTY: piped or redirected). Nothing was sent. Run it without a pipe or redirect, add --confirm (agents, plain writes only), or use the dedicated storebound command.'; -/** What to do with one call. Pure. */ +/** --confirm never stands in for the owner's typed id on an owner-only operation. */ +export const OWNER_NO_CONFIRM = 'refused: owner-only operation: --confirm does not apply; the owner types the operation id in an interactive terminal. Nothing was sent.'; + +/** What to do with one call. Pure. A plain write without a terminal is sent only with --yes and --confirm + * equal to the resolved operation id (the agent path); owner-only operations always need the owner's terminal. */ export function decide(g: GateInput): Decision { if (g.getOnly && g.method.toUpperCase() !== 'GET') return { action: 'refuse', why: 'api get runs GET operations only' }; if (g.kind === 'read') return g.dry ? { action: 'dry', why: '--dry' } : { action: 'send' }; @@ -97,6 +106,12 @@ export function decide(g: GateInput): Decision { ? 'owner-only operation: never through MCP or the desktop app; the owner runs it in a terminal' : 'writes through `storebound api` are not available to MCP or the desktop app; run it in a terminal' }; if (g.dry || !g.yes) return { action: 'dry', why: g.dry ? '--dry' : 'writes are dry by default: add --yes (in a terminal) to send' }; + if (g.confirm !== undefined) { + // an agent's typed confirmation: only for plain writes, only when it names this exact operation + if (g.kind === 'owner') return { action: 'refuse', why: OWNER_NO_CONFIRM }; + if (!g.opId || g.confirm !== g.opId) return { action: 'refuse', why: `refused: --confirm ${g.confirm} does not equal the operation id ${g.opId ?? '?'}. Nothing was sent.` }; + return { action: 'send' }; + } if (!g.tty) return { action: 'refuse', why: NOT_A_TTY }; return g.kind === 'owner' ? { action: 'confirm', typed: true } : { action: 'send' }; } diff --git a/cli/api/wrapped.gen.ts b/cli/api/wrapped.gen.ts index 7da7541..3fe7002 100644 --- a/cli/api/wrapped.gen.ts +++ b/cli/api/wrapped.gen.ts @@ -42,8 +42,12 @@ export const WRAPPED: { apple: Record; play: Record; play: Record; play: Record Buffer.from(b).toString('base64url'); /** One App Store Connect API call may take at most this long (then retried when safe, else AmbiguousWriteError). */ @@ -154,22 +155,9 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri return info; } - /** Reserve -> PUT the parts -> commit with the MD5 (screenshots, IAP review screenshots, app previews). `attrs` go into - * the reservation (app previews: mimeType, previewFrameTimeCode). */ - async function uploadAsset(type: string, rel: Record, file: string, attrs: Record = {}): Promise { - const buf = readFileSync(file); - // basename, not split('/'): a Windows path has backslashes, and the store would get the whole path as the file name - const name = basename(file); - const res = (await asc('POST', `/v1/${type}`, { data: { type, attributes: { fileName: name, fileSize: buf.length, ...attrs }, relationships: rel } })).data; - for (const op of res.attributes.uploadOperations as J[]) { - const headers: Record = {}; - for (const h of op.requestHeaders) headers[h.name] = h.value; - const r = await fetch(op.url, { method: op.method, headers, body: buf.subarray(op.offset, op.offset + op.length) }); - if (!r.ok) throw new Error(`upload ${name} part ${op.offset} -> ${r.status}`); - } - await asc('PATCH', `/v1/${type}/${res.id}`, { data: { type, id: res.id, attributes: { uploaded: true, sourceFileChecksum: md5(buf) } } }); - return res.id; - } + /** Reserve -> PUT the parts -> commit with the MD5 (uploadAssetVia). */ + const uploadAsset = (type: string, rel: Record, file: string, attrs: Record = {}): Promise => + uploadAssetVia({ asc, fetch: (u, i) => fetch(u, i) }, type, rel, file, attrs); /** * Makes a screenshot or preview set hold exactly `files`, in this order, touching as little as possible: the leading @@ -206,3 +194,37 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri return { asc, all, maybe, getAs, bytes, app, editableVersion, editableAppInfo, uploadAsset, syncAssets, keyId: k.keyId }; } + +/** One upload part may take at most this long. */ +export const PART_TIMEOUT_MS = 300_000; + +/** + * Reserve -> PUT the parts -> commit with the MD5 (screenshots, IAP review screenshots, app previews). `attrs` go into + * the reservation (app previews: mimeType, previewFrameTimeCode). Parts go without `Expect: 100-continue` + * (partHeaders) and anything but a 2xx is a failed part. A failed part never leads to a commit: the reservation + * (AWAITING_UPLOAD) is deleted and the whole upload tried once more with a new one; a second failure throws. + */ +export async function uploadAssetVia(d: { asc: (method: string, path: string, body?: unknown) => Promise; fetch: (url: string, init: RequestInit) => Promise }, + type: string, rel: Record, file: string, attrs: Record = {}): Promise { + const buf = readFileSync(file); + // basename, not split('/'): a Windows path has backslashes, and the store would get the whole path as the file name + const name = basename(file); + for (let attempt = 1; ; attempt++) { + const res = (await d.asc('POST', `/v1/${type}`, { data: { type, attributes: { fileName: name, fileSize: buf.length, ...attrs }, relationships: rel } })).data; + let failed = ''; + for (const op of (res.attributes.uploadOperations ?? []) as J[]) { + try { + const r = await d.fetch(op.url, { method: op.method, headers: partHeaders(op), body: buf.subarray(op.offset, op.offset + op.length), signal: AbortSignal.timeout(PART_TIMEOUT_MS) }); + if (r.status < 200 || r.status > 299) failed = `part ${op.offset} -> ${r.status}`; + } catch (e) { failed = `part ${op.offset} -> ${(e as Error).message}`; } + if (failed) break; + } + if (!failed) { + await d.asc('PATCH', `/v1/${type}/${res.id}`, { data: { type, id: res.id, attributes: { uploaded: true, sourceFileChecksum: md5(buf) } } }); + return res.id; + } + // never commit after a failed part: remove the stranded AWAITING_UPLOAD reservation, then one more try + try { await d.asc('DELETE', `/v1/${type}/${res.id}`); } catch { /* the next sync or --repair-stuck removes it */ } + if (attempt >= 2) throw new Error(`upload ${name} ${failed} (twice; the reservation was deleted, nothing committed)`); + } +} diff --git a/cli/apple/creative-assets.ts b/cli/apple/creative-assets.ts index ac65f1c..7539022 100644 --- a/cli/apple/creative-assets.ts +++ b/cli/apple/creative-assets.ts @@ -34,6 +34,7 @@ import { ffprobe } from '../shots/report'; import { imageInfo } from '../shots/spec'; import { checkCreativeImage, checkCreativeVideo, type CreativeFile, creativeFiles, PLACEMENT_TYPE, type Placement } from '../shots/creative'; import { type Asc, ascClient, md5, type J } from './asc'; +import { partHeaders } from './screenshot-health'; import { AmbiguousWriteError } from '../lib/upsert'; import { addItem, ensureDraft, OtherSubmissionError } from './submission'; @@ -190,10 +191,8 @@ export async function run(ctx: Ctx): Promise { const res = (await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { fileName: basename(f.file), fileSize: buf.length, category: 'CREATIVE_ASSETS', referenceName: REF(sum) }, relationships: { assetLibrary: { data: { type: 'appAssetLibraries', id: lib.id } } } } })).data as J; for (const op of (res.attributes.uploadOperations ?? []) as J[]) { - const headers: Record = {}; - for (const h of op.requestHeaders ?? []) headers[h.name] = h.value; - const r = await fetch(op.url, { method: op.method, headers, body: buf.subarray(op.offset, op.offset + op.length), signal: AbortSignal.timeout(300_000) }); - if (!r.ok) throw new Error(`upload ${basename(f.file)} part ${op.offset} -> ${r.status}`); + const r = await fetch(op.url, { method: op.method, headers: partHeaders(op), body: buf.subarray(op.offset, op.offset + op.length), signal: AbortSignal.timeout(300_000) }); + if (r.status < 200 || r.status > 299) { await c.asc('DELETE', `/v1/${type}/${res.id}`).catch(() => {}); throw new Error(`upload ${basename(f.file)} part ${op.offset} -> ${r.status} (reservation deleted, nothing committed)`); } } return (await c.asc('PATCH', `/v1/${type}/${res.id}`, { data: { type, id: res.id, attributes: { uploaded: true } } })).data as J; } diff --git a/cli/apple/resubmit.ts b/cli/apple/resubmit.ts index dab7493..ef834a5 100644 --- a/cli/apple/resubmit.ts +++ b/cli/apple/resubmit.ts @@ -25,6 +25,7 @@ import { type BuildStep, formatRows, labelOf, planIapSubmission, REJECTED_APP, t import { allSubscriptions } from '../lib/subscriptions'; import { ascClient, type J } from './asc'; import { readSubmitState, submitPlanned } from './iap-submit'; +import { explain409, isScreenshotProcessing409, pendingScreenshots, updateLedger, versionScreenshotRows } from './screenshot-health'; import { openSubmissions } from './submission'; import { ensureGcSwitch, gameCenterInUse, gcSwitchPlan, readGcSwitch } from './game-center'; import { allVersions, parsePlatform, pickPlatform, platformLabel, platformOf, versionsPath } from './platform'; @@ -118,5 +119,13 @@ export async function submitVersion(ctx: Ctx, mode: 'submit' | 'resubmit'): Prom log(TAG, `build ${number} attached to ${versionString}`); } if (gc && gcPlan.length) await ensureGcSwitch(c, gc, TAG); - await submitPlanned(ctx, c, { appId, ids, state, tag: TAG, withVersion: true, appVersionId: v.id, platform, quiet: true, resolve }); + try { + await submitPlanned(ctx, c, { appId, ids, state, tag: TAG, withVersion: true, appVersionId: v.id, platform, quiet: true, resolve }); + } catch (e) { + if (!isScreenshotProcessing409(e)) throw e; + // 409 STATE_ERROR.ASSET_IN_POST_PROCESSING.APP_SCREENSHOT: name every screenshot that is not COMPLETE + const rows = await versionScreenshotRows(c, v.id); + const pending = pendingScreenshots(rows, updateLedger(root, rows), Date.now()); + throw new Error(`${explain409(pending)}\nLast answer: ${(e as Error).message}`); + } } diff --git a/cli/apple/screenshot-health.ts b/cli/apple/screenshot-health.ts new file mode 100644 index 0000000..c167a1f --- /dev/null +++ b/cli/apple/screenshot-health.ts @@ -0,0 +1,147 @@ +// Screenshots that hold up a submission: App Store Connect answers 409 STATE_ERROR.ASSET_IN_POST_PROCESSING.APP_SCREENSHOT +// to a submit while any screenshot of the version is not COMPLETE. Seen live: a part upload answered with a non-2xx +// behind `Expect: 100-continue` was still committed, and the screenshot then sat in UPLOAD_COMPLETE for hours (never +// processed), blocking the submit. This module names every such screenshot (locale, display type, position, file), +// tells stuck ones (UPLOAD_COMPLETE longer than STUCK_MS) from ones still processing, and replaces only those in +// place (`apple screenshots --repair-stuck`). +// +// Apple gives no timestamp on a screenshot, so "how long in UPLOAD_COMPLETE" comes from a local ledger +// (.storebound/screenshot-states.json: screenshot id -> first time this machine saw it UPLOAD_COMPLETE, or committed it). +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { basename, dirname, join } from 'node:path'; +import type { J } from './asc'; + +/** UPLOAD_COMPLETE longer than this is stuck, not processing (Apple normally finishes in well under a minute). */ +export const STUCK_MS = 5 * 60_000; + +export interface ShotRow { id: string; locale: string; displayType: string; position: number; fileName: string; state: string; checksum?: string | null } +export type PendingKind = 'processing' | 'stuck' | 'failed' | 'awaiting-upload'; +export interface Pending extends ShotRow { kind: PendingKind; ageMs?: number } + +/** The submit / validate error this module explains. Pure. */ +export const isScreenshotProcessing409 = (e: unknown): boolean => + /-> 409\b/.test(String((e as Error)?.message ?? e)) && /ASSET_IN_POST_PROCESSING(\.APP_SCREENSHOT)?/.test(String((e as Error)?.message ?? e)); + +const ledgerFile = (root: string): string => join(root, '.storebound', 'screenshot-states.json'); + +export function readLedger(root: string): Record { + try { return JSON.parse(readFileSync(ledgerFile(root), 'utf8')) as Record; } catch { return {}; } +} + +/** Notes the first time each UPLOAD_COMPLETE screenshot of `rows` was seen (a known one keeps its time; one in another + * state is dropped; screenshots not in `rows` are left as they are). */ +export function updateLedger(root: string, rows: { id: string; state: string }[], now = Date.now()): Record { + const next: Record = { ...readLedger(root) }; + for (const r of rows) { if (r.state === 'UPLOAD_COMPLETE') next[r.id] = next[r.id] ?? now; else delete next[r.id]; } + try { mkdirSync(dirname(ledgerFile(root)), { recursive: true }); writeFileSync(ledgerFile(root), JSON.stringify(next, null, 2) + '\n'); } catch { /* read-only project: ages stay unknown */ } + return next; +} + +/** Records a screenshot this run just committed (its UPLOAD_COMPLETE clock starts now). */ +export function noteCommitted(root: string, id: string, now = Date.now()): void { + const l = readLedger(root); + l[id] = l[id] ?? now; + try { mkdirSync(dirname(ledgerFile(root)), { recursive: true }); writeFileSync(ledgerFile(root), JSON.stringify(l, null, 2) + '\n'); } catch { /* ignore */ } +} + +/** Every screenshot that is not COMPLETE, classified. A screenshot with no known first-seen time counts as processing + * (the next look starts its clock). Pure. */ +export function pendingScreenshots(rows: ShotRow[], seen: Record, now: number, stuckMs = STUCK_MS): Pending[] { + const out: Pending[] = []; + for (const r of rows) { + if (r.state === 'COMPLETE') continue; + if (r.state === 'FAILED') { out.push({ ...r, kind: 'failed' }); continue; } + if (r.state === 'AWAITING_UPLOAD') { out.push({ ...r, kind: 'awaiting-upload' }); continue; } + const at = seen[r.id]; + const ageMs = at === undefined ? undefined : now - at; + out.push({ ...r, kind: r.state === 'UPLOAD_COMPLETE' && ageMs !== undefined && ageMs > stuckMs ? 'stuck' : 'processing', ...(ageMs !== undefined ? { ageMs } : {}) }); + } + return out; +} + +/** Can --repair-stuck replace it (stuck, failed or a stranded reservation)? Processing ones are left to finish. */ +export const repairable = (p: Pending): boolean => p.kind !== 'processing'; + +const mins = (ms: number): string => `${Math.round(ms / 60_000)} min`; + +/** One line per pending screenshot. Pure. */ +export function describePending(list: Pending[]): string[] { + return list.map(p => `${p.locale} ${p.displayType} #${p.position} ${p.fileName}: ${p.state}${p.ageMs !== undefined ? ` for ${mins(p.ageMs)}` : ''} -> ${ + p.kind === 'stuck' ? 'STUCK (not processing)' : p.kind === 'failed' ? 'FAILED' : p.kind === 'awaiting-upload' ? 'stranded reservation (never uploaded)' : 'still processing'}`); +} + +/** The explanation for a 409 ASSET_IN_POST_PROCESSING: what holds the submit and what to do. Pure. */ +export function explain409(list: Pending[]): string { + if (!list.length) return 'App Store Connect says a screenshot is still processing, but every screenshot of the version now reads COMPLETE: run the same command again.'; + const bad = list.filter(repairable); + return `App Store Connect refuses the submit while ${list.length} screenshot(s) are not COMPLETE:\n${describePending(list).map(l => ' ' + l).join('\n')}\n` + + (bad.length ? `${bad.length} will never finish on their own: storebound apple screenshots --repair-stuck --dry, then without --dry (replaces only these, at their positions), then submit again.` + : `They are still processing (under ${mins(STUCK_MS)}): run the same command again in a few minutes.`); +} + +/** Every screenshot of one version, with its locale, display type and 1-based position. */ +export async function versionScreenshotRows(c: { all: (p: string) => Promise }, versionId: string): Promise { + const rows: ShotRow[] = []; + for (const loc of await c.all(`/v1/appStoreVersions/${versionId}/appStoreVersionLocalizations?limit=50`)) + for (const set of await c.all(`/v1/appStoreVersionLocalizations/${loc.id}/appScreenshotSets?limit=50`)) + rows.push(...setRows(await c.all(`/v1/appScreenshotSets/${set.id}/appScreenshots?limit=50`), loc.attributes.locale, set.attributes.screenshotDisplayType)); + return rows; +} + +export const setRows = (shots: J[], locale: string, displayType: string): ShotRow[] => shots.map((s, i) => ({ + id: s.id, locale, displayType, position: i + 1, fileName: s.attributes?.fileName ?? '?', state: s.attributes?.assetDeliveryState?.state ?? 'UNKNOWN', checksum: s.attributes?.sourceFileChecksum, +})); + +/** Request headers of one upload part, without `Expect` (100-continue): seen live, a part sent with it got a non-2xx + * that looked like progress and the asset never processed. Pure. */ +export function partHeaders(op: { requestHeaders?: { name: string; value: string }[] }): Record { + const h: Record = {}; + for (const x of op.requestHeaders ?? []) if (x.name.toLowerCase() !== 'expect') h[x.name] = x.value; + return h; +} + +export interface RepairStep { id: string; position: number; fileName: string; file: string | null; kind: PendingKind } + +/** What --repair-stuck does in one set: each repairable screenshot with the local file of the same name (else the file + * at its position). Pure. */ +export function repairPlan(shots: ShotRow[], pending: Pending[], files: string[]): RepairStep[] { + const ids = new Set(pending.filter(repairable).map(p => p.id)); + return shots.filter(s => ids.has(s.id)).map(s => ({ + id: s.id, position: s.position, fileName: s.fileName, kind: pending.find(p => p.id === s.id)!.kind, + file: files.find(f => basename(f) === s.fileName) ?? files[s.position - 1] ?? null, + })); +} + +export interface RepairClient { + asc: (method: string, path: string, body?: unknown) => Promise; + all: (path: string) => Promise; + uploadAsset: (type: string, rel: Record, file: string) => Promise; +} + +/** Replaces the planned screenshots of one set at their own positions: delete, upload the same file, put the order + * back, then read the set again and check the count did not change. Re-runnable: a step whose screenshot is gone + * already is skipped, and a set that still holds the same count afterwards is left as it is. */ +export async function repairSet(c: RepairClient, setId: string, steps: RepairStep[], say: (m: string) => void = () => {}): Promise<{ replaced: number }> { + const before = (await c.all(`/v1/appScreenshotSets/${setId}/appScreenshots?limit=50`)).map(x => x.id as string); + const order = [...before]; + let replaced = 0; + for (const s of steps) { + const at = order.indexOf(s.id); + if (at < 0) continue; // replaced by an earlier run + if (!s.file || !existsSync(s.file)) throw new Error(`#${s.position} ${s.fileName}: no local file to re-upload (looked for the same name in the renders); nothing changed for it`); + await c.asc('DELETE', `/v1/appScreenshots/${s.id}`); + const id = await c.uploadAsset('appScreenshots', { appScreenshotSet: { data: { type: 'appScreenshotSets', id: setId } } }, s.file); + order[at] = id; + replaced++; + say(`#${s.position} ${s.fileName}: replaced (${s.kind})`); + } + if (replaced) { + const now = (await c.all(`/v1/appScreenshotSets/${setId}/appScreenshots?limit=50`)).map(x => x.id as string); + if (now.join() !== order.join() && order.every(id => now.includes(id))) + await c.asc('PATCH', `/v1/appScreenshotSets/${setId}/relationships/appScreenshots`, { data: order.map(id => ({ type: 'appScreenshots', id })) }); + const after = (await c.all(`/v1/appScreenshotSets/${setId}/appScreenshots?limit=50`)).map(x => x.id as string); + if (after.length !== before.length) throw new Error(`set ${setId}: ${before.length} screenshots before the repair, ${after.length} after: re-run storebound apple screenshots to restore the set`); + if (after.join() !== order.join()) throw new Error(`set ${setId}: order after the repair differs from the original positions: re-run storebound apple screenshots`); + } + return { replaced }; +} diff --git a/cli/apple/screenshots.ts b/cli/apple/screenshots.ts index 3d45e1f..afcc0d5 100644 --- a/cli/apple/screenshots.ts +++ b/cli/apple/screenshots.ts @@ -1,6 +1,7 @@ // Store screenshots of every locale on the editable App Store version (idempotent: a set whose files already match // by MD5 and order is left alone, otherwise it is emptied and re-uploaded). // storebound apple screenshots [--src store/renders] [--only en-US,tr] [--jobs 4] [--variant b] [--dry] +// storebound apple screenshots --repair-stuck [--dry] (only the screenshots stuck outside COMPLETE, in place) // Source per language: //ios69/NN.png (6.9", 1320 x 2868 -> APP_IPHONE_67), // ios65/NN.png (6.5", 1284 x 2778 -> APP_IPHONE_65) and, only with apple.ipad, ipad13/NN.png (13" iPad, 2064 x 2752 -> // APP_IPAD_PRO_3GEN_129: the API has no "13 inch" value, the 13" display set keeps the 3rd gen 12.9" name). With @@ -21,6 +22,7 @@ import { pulledChecksum } from '../lib/art-pull'; import { consoleLink } from '../lib/console-links'; import { IPHONE_DUO_DISPLAY, IPHONE_DUO_NOT_IN_API } from '../shots/spec'; import { type Asc, ascClient, EDITABLE, keptPrefix, md5, setUpToDate, type J } from './asc'; +import { pendingScreenshots, repairPlan, repairSet, setRows, updateLedger } from './screenshot-health'; import { allVersions, parsePlatform, pickPlatform, platformLabel, stateOf, versionLabel } from './platform'; /** Render size key -> ASC screenshotDisplayType (iPhone sets). */ @@ -104,6 +106,8 @@ export async function run(ctx: Ctx): Promise { const syncSet = (locId: string, sets: J[], type: string, files: string[], tag: string) => syncScreenshotSet(c, { rel: 'appStoreVersionLocalization', type: 'appStoreVersionLocalizations', id: locId }, sets, type, files, tag, ctx.args.has('dry')); + if (ctx.args.has('repair-stuck')) { await repairStuck(ctx, c, root, locs, src, platform, only); return; } + const tasks: (() => Promise)[] = []; for (const loc of locs) { const locale: string = loc.attributes.locale; @@ -132,3 +136,35 @@ export async function run(ctx: Ctx): Promise { } done('apple', bad ? `${bad} screenshots failed processing (re-run to retry)` : 'screenshots done'); } + +/** --repair-stuck: only the screenshots that are not COMPLETE and will not finish on their own (UPLOAD_COMPLETE for + * over 5 min, FAILED, or a stranded AWAITING_UPLOAD reservation) are replaced at their own positions with the same + * local file (same name in the renders). Everything else stays; still-processing ones are left to finish. --dry lists + * the plan. Re-runnable: a run cut midway leaves the rest for the next run, which skips what is already COMPLETE. */ +async function repairStuck(ctx: Ctx, c: Asc, root: string, locs: J[], src: string, platform: string, only: string[]): Promise { + const dry = ctx.args.has('dry'); + const langOf = byAppleLocale(ctx.loaded.config.languages); + const dirOf = Object.fromEntries(Object.entries(displaySets(ctx.loaded.config.apple, platform)).map(([d, t]) => [t, d] as const)); + let total = 0, held = 0; + for (const loc of locs) { + const locale: string = loc.attributes.locale; + if (only.length && !only.includes(locale)) continue; + for (const set of await c.all(`/v1/appStoreVersionLocalizations/${loc.id}/appScreenshotSets?limit=50`)) { + const type: string = set.attributes.screenshotDisplayType; + const rows = setRows(await c.all(`/v1/appScreenshotSets/${set.id}/appScreenshots?limit=50`), locale, type); + const pending = pendingScreenshots(rows, updateLedger(root, rows), Date.now()); + held += pending.filter(p => p.kind === 'processing').length; + const lang = langOf.get(locale); + const dir = dirOf[type]; + const files = lang && dir ? numberedImages(join(src, lang.id, dir)).filter(f => f.endsWith('.png')) : []; + const steps = repairPlan(rows, pending, files); + if (!steps.length) continue; + total += steps.length; + const tag = `${locale} ${type}`; + if (dry) { for (const st of steps) log('apple', `${tag}: would replace #${st.position} ${st.fileName} (${st.kind}) with ${st.file ?? 'NO LOCAL FILE'}`); continue; } + await repairSet(c, set.id, steps, m => log('apple', `${tag} ${m}`)); + } + } + if (held) log('apple', `${held} screenshot(s) still processing (under 5 min): left alone; run validate again in a few minutes`); + done('apple', total ? `${dry ? 'dry run: would replace' : 'replaced'} ${total} stuck screenshot(s)` : 'no stuck screenshots'); +} diff --git a/cli/apple/upload.ts b/cli/apple/upload.ts index 661cc4d..cc38e77 100644 --- a/cli/apple/upload.ts +++ b/cli/apple/upload.ts @@ -32,6 +32,7 @@ import { createOnce } from '../lib/upsert'; import { elapsed, heartbeat, type HeartbeatOptions, mb, share, withHeartbeat } from '../lib/progress'; import { pump } from '../lib/runner'; import * as rt from '../lib/rt'; +import { partHeaders } from './screenshot-health'; const TAG = 'upload'; @@ -94,8 +95,7 @@ export async function sendParts(o: SendPartsOptions): Promise { try { for (const [i, op] of o.ops.entries()) { current = i + 1; - const headers: Record = {}; - for (const h of op.requestHeaders ?? []) headers[h.name] = h.value; + const headers = partHeaders(op); const body = new Uint8Array(slice(o.file, op.offset, op.length)); for (let attempt = 1; ; attempt++) { const left = o.deadline - now(); diff --git a/cli/commands.ts b/cli/commands.ts index d851e4c..b58f9e6 100644 --- a/cli/commands.ts +++ b/cli/commands.ts @@ -78,7 +78,7 @@ export const COMMANDS: Record Promise, string]> = { 'apple cpp': [() => import('./apple/cpp'), 'custom product pages: list | create | upload --name | submit --name | visible --name (submit / visible ask first)'], 'apple events': [() => import('./apple/events'), 'in-app events: list | create | upload --name | submit --name (submit asks first)'], 'apple listing': [() => import('./apple/listing'), 'version, build, name / subtitle / description / keywords per locale; pull [--write]: live texts back into the listing file (diff first); --platform ios|macos|tvos|visionos (default: the platform that has the version this needs; asks when several do)'], - 'apple screenshots': [() => import('./apple/screenshots'), '6.9" + 6.5" (+ 13" iPad) screenshots per locale; --variant ; --platform ios|macos|tvos|visionos (default: the platform that has the version this needs; asks when several do)'], + 'apple screenshots': [() => import('./apple/screenshots'), '6.9" + 6.5" (+ 13" iPad) screenshots per locale; --variant ; --repair-stuck [--dry] (replace only screenshots not COMPLETE, at their positions); --platform ios|macos|tvos|visionos (default: the platform that has the version this needs; asks when several do)'], 'apple appinfo': [() => import('./apple/appinfo'), 'categories, age rating, content rights, Free price, territories'], 'apple review-details': [() => import('./apple/review-details'), 'App Review contact, demo account (from .storebound/, masked) + notes'], 'apple status': [() => import('./apple/status'), 'versions, builds, IAPs, review submissions (--wait-review, --cancel-submission ); --platform ios|macos|tvos|visionos (default: the platform that has the version this needs; asks when several do)'], diff --git a/cli/data/flags.json b/cli/data/flags.json index 938d845..9c2cd6a 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -43,6 +43,7 @@ "api": [ "all-pages", "body", + "confirm", "out", "param", "search", @@ -84,6 +85,7 @@ "off", "platform", "prune", + "repair-stuck", "src", "variant", "write" @@ -151,6 +153,7 @@ "not-sent-for-review", "platform", "prune", + "repair-stuck", "src", "traffic", "variant", @@ -198,6 +201,7 @@ "not-sent-for-review", "platform", "prune", + "repair-stuck", "src", "variant", "write" @@ -895,6 +899,7 @@ "play", "prune", "react-native", + "repair-stuck", "signature", "src", "unity", @@ -968,6 +973,7 @@ "complete", "concurrency", "configuration", + "confirm", "contact-from", "cordova", "cordova-android", @@ -1099,6 +1105,7 @@ "release-date", "remove", "render", + "repair-stuck", "resolve-iaps", "resume", "review-sent", @@ -1281,7 +1288,8 @@ "storebound apple review-details [--contact-from ] [--dry]" ], "apple screenshots": [ - "storebound apple screenshots [--src store/renders] [--only en-US,tr] [--jobs 4] [--variant b] [--dry]" + "storebound apple screenshots [--src store/renders] [--only en-US,tr] [--jobs 4] [--variant b] [--dry]", + "storebound apple screenshots --repair-stuck [--dry] (only the screenshots stuck outside COMPLETE, in place)" ], "apple signing": [ "storebound apple signing status [--json] read-only: capabilities, certificates (with / without a", diff --git a/cli/lib/validate-rules.ts b/cli/lib/validate-rules.ts index 491fb2a..8470651 100644 --- a/cli/lib/validate-rules.ts +++ b/cli/lib/validate-rules.ts @@ -2,6 +2,7 @@ // these functions turn it into an ordered list of findings. Order = the order you would fix things in. import { consoleLink, consoleUrl } from './console-links'; +import { describePending, type Pending, repairable } from '../apple/screenshot-health'; import { type FixAction, fixAppleListing, fixPlayListing, fixReviewDetails } from './fix-actions'; import { iphoneDuoNote, macNote } from '../shots/spec'; @@ -59,6 +60,9 @@ export interface AppleSnapshot { version: { versionString: string; state: string; copyright?: string | null; platform?: string } | null; /** Header and Search Results files uploaded but not approved yet, per locale and placement (apple creative-assets). */ creativeWaiting?: { locale: string; placement: string; file: string; text: string }[]; + /** Screenshots of the version that are not COMPLETE (cli/apple/screenshot-health.ts): a submit answers 409 + * ASSET_IN_POST_PROCESSING while any is left. */ + screenshotsPending?: Pending[]; /** Editable or rejected versions of the app's other platforms (an app's macOS version has its own state). */ otherPlatformVersions?: { versionString: string; state: string; platform: string }[]; /** app.copyright from the config (undefined: not set). */ @@ -211,6 +215,13 @@ export function appleRules(s: AppleSnapshot): Finding[] { else if (EDITABLE.includes(s.version.state)) add('ok', 'version', `version ${vl}: ${s.version.state}`); else if (IN_FLIGHT.includes(s.version.state)) add('warn', 'version', `version ${vl} is ${s.version.state} (nothing to prepare)`); else add('warn', 'version', `version ${vl}: ${s.version.state}`); + { + const pend = s.screenshotsPending ?? []; + const lines = describePending(pend); + pend.forEach((p, i) => repairable(p) + ? add('blocker', 'screenshot-stuck', lines[i]!, 'storebound apple screenshots --repair-stuck --dry, then without --dry (replaces only this screenshot at its position)') + : add('warn', 'screenshot-processing', lines[i]!, 'wait a few minutes: a submit answers 409 ASSET_IN_POST_PROCESSING until it is COMPLETE')); + } for (const w of s.creativeWaiting ?? []) add('warn', 'creative-waiting', `${w.locale} ${w.placement}: ${w.file} ${w.text}`, 'storebound apple creative-assets (a re-run places it once approved; --add-for-review sends it to review)'); for (const o of s.otherPlatformVersions ?? []) { const name = PLATFORM_NAMES[o.platform] ?? o.platform; diff --git a/cli/validate.ts b/cli/validate.ts index 7819d81..4d43db3 100644 --- a/cli/validate.ts +++ b/cli/validate.ts @@ -20,6 +20,7 @@ import { allVersions, type AscPlatform, parsePlatform, platformOf, stateOf, vers import { capabilityReport } from './apple/signing'; import { firstProductReport } from './apple/first-products'; import { requiredDisplayTypes } from './apple/screenshots'; +import { pendingScreenshots, setRows, type ShotRow, updateLedger } from './apple/screenshot-health'; import { type Loaded, playCategoryOf, playCodes, profileOf, sellsOn } from './lib/config'; import { reviewDemoAccount } from './lib/credentials'; import { allSubscriptions, basePlanId } from './lib/subscriptions'; @@ -80,6 +81,7 @@ export async function collectApple(ctx: Ctx): Promise { let build: AppleSnapshot['build'] = null; const locales: AppleSnapshot['locales'] = []; let reviewDetail: AppleSnapshot['reviewDetail'] = null; + const shotRows: ShotRow[] = []; if (v) { const b = (await c.maybe(`/v1/appStoreVersions/${v.id}/build`))?.data; if (b) { @@ -92,7 +94,11 @@ export async function collectApple(ctx: Ctx): Promise { for (const l of await c.all(`/v1/appStoreVersions/${v.id}/appStoreVersionLocalizations?limit=50`)) { const sets = await c.all(`/v1/appStoreVersionLocalizations/${l.id}/appScreenshotSets?limit=50`); const screenshots: Record = {}; - for (const s of sets) screenshots[s.attributes.screenshotDisplayType] = (await c.all(`/v1/appScreenshotSets/${s.id}/appScreenshots?limit=50`)).length; + for (const s of sets) { + const shots = await c.all(`/v1/appScreenshotSets/${s.id}/appScreenshots?limit=50`); + screenshots[s.attributes.screenshotDisplayType] = shots.length; + shotRows.push(...setRows(shots, l.attributes.locale, s.attributes.screenshotDisplayType)); + } const ia = infoLocs.get(l.attributes.locale) ?? {}; locales.push({ locale: l.attributes.locale, name: ia.name, subtitle: ia.subtitle, description: l.attributes.description, keywords: l.attributes.keywords, screenshots }); } @@ -132,6 +138,7 @@ export async function collectApple(ctx: Ctx): Promise { version: v ? { versionString: v.attributes.versionString, state: v.attributes.appVersionState ?? v.attributes.appStoreState, copyright: v.attributes.copyright ?? null, platform } : null, otherPlatformVersions, creativeWaiting: await creativeWaitingOf(ctx, c, appId), + screenshotsPending: pendingScreenshots(shotRows, updateLedger(root, shotRows), Date.now()), configCopyright: config.app.copyright, build, locales, reviewDetail, ageRating, expectedLocales: config.languages.map(l => l.apple).filter((x): x is string => !!x), diff --git a/docs/api-coverage.md b/docs/api-coverage.md index 22354bd..b257ca2 100644 --- a/docs/api-coverage.md +++ b/docs/api-coverage.md @@ -12,7 +12,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | API | operations | GET | other | wrapped by a command | owner only | |---|---:|---:|---:|---:|---:| -| App Store Connect API 4.5.1 | 1303 | 826 | 477 | 218 | 166 | +| App Store Connect API 4.5.1 | 1303 | 826 | 477 | 222 | 166 | | Google Play Android Developer API v3 (revision 20261008) | 145 | 45 | 100 | 35 | 49 | | Google Play Developer Reporting API v1beta1 (revision 20261008) | 25 | 15 | 10 | 6 | 0 | @@ -282,17 +282,17 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | `appPriceSchedules_manualPrices_getToManyRelated` | GET | `/v1/appPriceSchedules/{id}/manualPrices` | read | | | `appPriceSchedules_manualPrices_getToManyRelationship` | GET | `/v1/appPriceSchedules/{id}/relationships/manualPrices` | read | | | **appScreenshotSets** (6) | | | | | -| `appScreenshotSets_appScreenshots_getToManyRelated` | GET | `/v1/appScreenshotSets/{id}/appScreenshots` | read | apple/ppo, apple/screenshots, art, validate | +| `appScreenshotSets_appScreenshots_getToManyRelated` | GET | `/v1/appScreenshotSets/{id}/appScreenshots` | read | apple/ppo, apple/screenshot-health, apple/screenshots, art, validate | | `appScreenshotSets_appScreenshots_getToManyRelationship` | GET | `/v1/appScreenshotSets/{id}/relationships/appScreenshots` | read | | -| `appScreenshotSets_appScreenshots_replaceToManyRelationship` | PATCH | `/v1/appScreenshotSets/{id}/relationships/appScreenshots` | write (dry by default) | | +| `appScreenshotSets_appScreenshots_replaceToManyRelationship` | PATCH | `/v1/appScreenshotSets/{id}/relationships/appScreenshots` | write (dry by default) | apple/screenshot-health | | `appScreenshotSets_createInstance` | POST | `/v1/appScreenshotSets` | write (dry by default) | apple/screenshots | | `appScreenshotSets_deleteInstance` | DELETE | `/v1/appScreenshotSets/{id}` | owner only (typed confirm) | | | `appScreenshotSets_getInstance` | GET | `/v1/appScreenshotSets/{id}` | read | | | **appScreenshots** (4) | | | | | -| `appScreenshots_createInstance` | POST | `/v1/appScreenshots` | write (dry by default) | | -| `appScreenshots_deleteInstance` | DELETE | `/v1/appScreenshots/{id}` | owner only (typed confirm) | | +| `appScreenshots_createInstance` | POST | `/v1/appScreenshots` | write (dry by default) | apple/screenshot-health | +| `appScreenshots_deleteInstance` | DELETE | `/v1/appScreenshots/{id}` | owner only (typed confirm) | apple/screenshot-health | | `appScreenshots_getInstance` | GET | `/v1/appScreenshots/{id}` | read | | -| `appScreenshots_updateInstance` | PATCH | `/v1/appScreenshots/{id}` | write (dry by default) | | +| `appScreenshots_updateInstance` | PATCH | `/v1/appScreenshots/{id}` | write (dry by default) | apple/screenshot-health | | **appStoreReviewAttachments** (4) | | | | | | `appStoreReviewAttachments_createInstance` | POST | `/v1/appStoreReviewAttachments` | write (dry by default) | | | `appStoreReviewAttachments_deleteInstance` | DELETE | `/v1/appStoreReviewAttachments/{id}` | owner only (typed confirm) | | @@ -337,7 +337,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | **appStoreVersionLocalizations** (14) | | | | | | `appStoreVersionLocalizations_appPreviewSets_getToManyRelated` | GET | `/v1/appStoreVersionLocalizations/{id}/appPreviewSets` | read | apple/previews, art | | `appStoreVersionLocalizations_appPreviewSets_getToManyRelationship` | GET | `/v1/appStoreVersionLocalizations/{id}/relationships/appPreviewSets` | read | | -| `appStoreVersionLocalizations_appScreenshotSets_getToManyRelated` | GET | `/v1/appStoreVersionLocalizations/{id}/appScreenshotSets` | read | apple/screenshots, art, validate | +| `appStoreVersionLocalizations_appScreenshotSets_getToManyRelated` | GET | `/v1/appStoreVersionLocalizations/{id}/appScreenshotSets` | read | apple/screenshot-health, apple/screenshots, art, validate | | `appStoreVersionLocalizations_appScreenshotSets_getToManyRelationship` | GET | `/v1/appStoreVersionLocalizations/{id}/relationships/appScreenshotSets` | read | | | `appStoreVersionLocalizations_createInstance` | POST | `/v1/appStoreVersionLocalizations` | write (dry by default) | listing-store | | `appStoreVersionLocalizations_deleteInstance` | DELETE | `/v1/appStoreVersionLocalizations/{id}` | owner only (typed confirm) | | @@ -371,7 +371,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | `appStoreVersions_appStoreVersionExperimentsV2_getToManyRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/appStoreVersionExperimentsV2` | read | | | `appStoreVersions_appStoreVersionExperiments_getToManyRelated` | GET | `/v1/appStoreVersions/{id}/appStoreVersionExperiments` | read | | | `appStoreVersions_appStoreVersionExperiments_getToManyRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/appStoreVersionExperiments` | read | | -| `appStoreVersions_appStoreVersionLocalizations_getToManyRelated` | GET | `/v1/appStoreVersions/{id}/appStoreVersionLocalizations` | read | apple/creative-assets, apple/listing, apple/previews, apple/screenshots, art, listing-store, onboard, validate | +| `appStoreVersions_appStoreVersionLocalizations_getToManyRelated` | GET | `/v1/appStoreVersions/{id}/appStoreVersionLocalizations` | read | apple/creative-assets, apple/listing, apple/previews, apple/screenshot-health, apple/screenshots, art, listing-store, onboard, validate | | `appStoreVersions_appStoreVersionLocalizations_getToManyRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/appStoreVersionLocalizations` | read | | | `appStoreVersions_appStoreVersionPhasedRelease_getToOneRelated` | GET | `/v1/appStoreVersions/{id}/appStoreVersionPhasedRelease` | read | apple/release, apple/status | | `appStoreVersions_appStoreVersionPhasedRelease_getToOneRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/appStoreVersionPhasedRelease` | read | | diff --git a/skills/store-api/SKILL.md b/skills/store-api/SKILL.md index 485ab59..dae8e94 100644 --- a/skills/store-api/SKILL.md +++ b/skills/store-api/SKILL.md @@ -40,6 +40,9 @@ storebound api apple salesReports_getCollection --param ... --out report.gz # whatever the flags. `--yes` with stdout not a TTY (piped `| tail`, redirected `> out.json`, an agent's shell) is refused: exit 1 and "refused: writes through `storebound api` need an interactive terminal ... Nothing was sent." on stderr (store-pitfalls 78). Never pipe or redirect a write; use the dedicated command the message names. + An agent without a terminal sends a plain (non-owner) write with `--yes --confirm `, the id equal + to the one the call resolved to (store-pitfalls 92), after showing the dry run. `--confirm` never applies to + owner-only operations. 3. Owner-only operations (cli/api/gate.ts: every DELETE, submissions and their cancel, release requests, phased release changes, product page test start / stop, price schedules and price migrations, review replies, tester and user invitations, Play `edits.commit`, product activation, refunds, revokes and cancels, app signing) also ask for diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index b9b143d..cc5b7da 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1113,3 +1113,26 @@ that fails without the fix (see CONTRIBUTING.md). check `apple status` for the draft's state before re-running anything else. - **Guard:** `willSubmit` in `cli/lib/review-submit.ts` (a non-empty READY_FOR_REVIEW draft that holds the named app version, or for `iap-submit` an asked-for item, is submitted); `tests/resubmit.test.ts`. + +## 91. Submit refused: 409 STATE_ERROR.ASSET_IN_POST_PROCESSING.APP_SCREENSHOT (screenshots stuck in UPLOAD_COMPLETE) +- **Symptom:** `apple submit` answered 409 `ASSET_IN_POST_PROCESSING.APP_SCREENSHOT` for hours. A few screenshots + sat in UPLOAD_COMPLETE and never became COMPLETE: their part upload had gone out with `Expect: 100-continue`, got + a non-2xx answer, and the upload was committed anyway. +- **Do:** `storebound validate` (or the failed submit) now lists every screenshot that is not COMPLETE: locale, + display type, position, file name, state and age. UPLOAD_COMPLETE for over 5 minutes is **stuck**, not processing + (a blocker); younger ones are a warning, wait. Then `storebound apple screenshots --repair-stuck --dry`, then + without `--dry`: only the stuck / FAILED / AWAITING_UPLOAD ones are deleted, the same local file (same name in the + renders) uploaded again and put back at its position; the set count is checked afterwards. Re-runnable. +- **Guard:** `cli/apple/screenshot-health.ts` (`pendingScreenshots`, `explain409`, `repairPlan`, `repairSet`, + ledger `.storebound/screenshot-states.json` for the UPLOAD_COMPLETE age), `uploadAssetVia` in `cli/apple/asc.ts` + (parts without `Expect`, any non-2xx part is a failure, the AWAITING_UPLOAD reservation is deleted and the upload + tried once more, never committed after a failed part), `tests/screenshot-health.test.ts`. + +## 92. Agents could not send any `storebound api` write (no TTY) +- **Symptom:** an agent's shell has no TTY, so every write through `storebound api` was refused (pitfall 78), even + a harmless one the owner had already agreed to, and the owner was asked to run it by hand. +- **Do:** show the dry run, then `storebound api apple|play ... --yes --confirm `. The + `--confirm` value must equal the operation id the call resolved to (also with `METHOD path`), or nothing is sent. + Owner-only operations (submit, release, delete, prices, testers, replies, ...) refuse `--confirm`: the owner + still types the id in a terminal. MCP and the desktop app still never send writes. +- **Guard:** `decide` / `OWNER_NO_CONFIRM` in `cli/api/gate.ts`, `tests/api.test.ts`. diff --git a/tests/api.test.ts b/tests/api.test.ts index ac4bf1b..41bd5b4 100644 --- a/tests/api.test.ts +++ b/tests/api.test.ts @@ -5,7 +5,7 @@ import { appleRows, generate, playRows, scanSource, templateRegex, wrappedOps } import { APPLE_OPS } from '../cli/api/apple.gen'; import { PLAY_APIS, PLAY_OPS } from '../cli/api/play.gen'; import { allOps, appleApi, backoffMs, buildRequest, getOp, mergePages, nextRequest, type Op, playApi, resolveOp, send, sendAll } from '../cli/api/client'; -import { decide, gateOf, type GateInput, OWNER_ONLY, ownerReason } from '../cli/api/gate'; +import { decide, gateOf, type GateInput, OWNER_NO_CONFIRM, OWNER_ONLY, ownerReason } from '../cli/api/gate'; import { coverage, describeRequest, parseParams, rows, search } from '../cli/api'; import { parseArgs } from '../cli/lib/args'; import { TOOLS, toArgv, validateInput } from '../cli/mcp-tools'; @@ -180,6 +180,20 @@ describe('write gating', () => { expect(decide({ ...base, getOnly: true, method: 'POST' }).action).toBe('refuse'); expect(decide({ ...base, getOnly: true })).toEqual({ action: 'send' }); }); + test('--confirm : an agent without a terminal sends a plain write, never an owner-only one', () => { + const w = { ...base, kind: 'write' as const, method: 'PATCH', yes: true, tty: false, opId: 'appStoreVersions_updateInstance' }; + expect(decide({ ...w, confirm: 'appStoreVersions_updateInstance' })).toEqual({ action: 'send' }); + expect(decide({ ...w, confirm: 'appInfos_updateInstance' })).toMatchObject({ action: 'refuse', why: expect.stringContaining('does not equal') }); + expect(decide({ ...w, confirm: 'x', opId: undefined }).action).toBe('refuse'); + // still dry without --yes, still nothing under MCP / desktop + expect(decide({ ...w, yes: false, confirm: w.opId }).action).toBe('dry'); + expect(decide({ ...w, agent: true, confirm: w.opId }).action).toBe('refuse'); + // owner-only: --confirm never replaces the owner's typed id, with or without a terminal + const o = { ...w, kind: 'owner' as const, method: 'DELETE', opId: 'appScreenshots_deleteInstance' }; + expect(decide({ ...o, confirm: o.opId })).toMatchObject({ action: 'refuse', why: OWNER_NO_CONFIRM }); + expect(decide({ ...o, tty: true, confirm: o.opId })).toMatchObject({ action: 'refuse', why: OWNER_NO_CONFIRM }); + expect(decide({ ...o, tty: true })).toEqual({ action: 'confirm', typed: true }); + }); test('the dry run shows the exact request without the credential', () => { const r = buildRequest(op('apple', 'appStoreVersions_updateInstance'), { id: '1' }, { data: { type: 'appStoreVersions', id: '1' } }); const text = describeRequest(r); diff --git a/tests/idempotency.test.ts b/tests/idempotency.test.ts index 26d6ae3..bef1580 100644 --- a/tests/idempotency.test.ts +++ b/tests/idempotency.test.ts @@ -529,9 +529,12 @@ describe('crash midway and unclear answers', () => { const md5 = (b: Uint8Array) => new Bun.CryptoHasher('md5').update(b).digest('hex'); s.asc.put({ type: 'appScreenshots', id: 'shot-a', attributes: { sourceFileChecksum: md5(png(1)), assetDeliveryState: { state: 'COMPLETE' }, fileName: '01.png' }, rels: { appScreenshotSet: set.id } }); s.asc.put({ type: 'appScreenshots', id: 'shot-x', attributes: { sourceFileChecksum: 'stale', assetDeliveryState: { state: 'COMPLETE' }, fileName: 'old.png' }, rels: { appScreenshotSet: set.id } }); - s.failPart = n => n === 2; // the 2nd uploaded part (03.png) fails + s.failPart = n => n === 2 || n === 3; // 03.png fails, and its one retry too const r1 = await capture(() => appleScreenshots(p.ctx(['--only', 'en-US']))).catch(e => ({ out: String(e), err: '', exit: 1 })); expect(r1.out + r1.err).toContain('03.png part 0 -> 400'); + expect(r1.out + r1.err).toContain('nothing committed'); + // the failed reservations were deleted, not left AWAITING_UPLOAD + expect(s.asc.children(set.id, 'appScreenshots').filter(x => (x.attributes.assetDeliveryState as { state: string } | undefined)?.state !== 'COMPLETE')).toEqual([]); expect(s.asc.children(set.id, 'appScreenshots').map(x => x.id)).toContain('shot-a'); s.failPart = undefined; const r2 = await capture(() => appleScreenshots(p.ctx(['--only', 'en-US']))); diff --git a/tests/screenshot-health.test.ts b/tests/screenshot-health.test.ts new file mode 100644 index 0000000..a0dc24d --- /dev/null +++ b/tests/screenshot-health.test.ts @@ -0,0 +1,127 @@ +// Screenshots that hold up a submit (409 ASSET_IN_POST_PROCESSING.APP_SCREENSHOT): classification (stuck vs still +// processing), the 409 explanation, validate findings, --repair-stuck in place, and the part upload rules (no +// `Expect: 100-continue`, a failed part deletes the reservation and is retried once, never committed). No network. +import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { uploadAssetVia } from '../cli/apple/asc'; +import { describePending, explain409, isScreenshotProcessing409, partHeaders, pendingScreenshots, readLedger, repairPlan, repairSet, setRows, STUCK_MS, updateLedger, type ShotRow } from '../cli/apple/screenshot-health'; +import { appleRules } from '../cli/lib/validate-rules'; + +let dir = ''; +beforeAll(() => { dir = mkdtempSync(join(tmpdir(), 'sb-shots-')); for (const n of ['01.png', '02.png', '03.png']) writeFileSync(join(dir, n), `png ${n}`); }); +afterAll(() => rmSync(dir, { recursive: true, force: true })); + +const shot = (id: string, fileName: string, state: string) => ({ id, type: 'appScreenshots', attributes: { fileName, assetDeliveryState: { state }, sourceFileChecksum: 'x' } }); +const NOW = 10_000_000; + +describe('classification', () => { + const rows: ShotRow[] = setRows([shot('a', '01.png', 'COMPLETE'), shot('b', '02.png', 'UPLOAD_COMPLETE'), shot('c', '03.png', 'UPLOAD_COMPLETE'), shot('d', '04.png', 'FAILED'), shot('e', '05.png', 'AWAITING_UPLOAD')], 'en-US', 'APP_IPHONE_67'); + test('only non-COMPLETE rows; UPLOAD_COMPLETE over 5 min is stuck, younger or unknown is processing', () => { + const p = pendingScreenshots(rows, { b: NOW - STUCK_MS - 1, c: NOW - 60_000 }, NOW); + expect(p.map(x => [x.id, x.kind, x.position])).toEqual([['b', 'stuck', 2], ['c', 'processing', 3], ['d', 'failed', 4], ['e', 'awaiting-upload', 5]]); + expect(pendingScreenshots(rows, {}, NOW).find(x => x.id === 'b')!.kind).toBe('processing'); + const lines = describePending(p); + expect(lines[0]).toBe('en-US APP_IPHONE_67 #2 02.png: UPLOAD_COMPLETE for 5 min -> STUCK (not processing)'); + expect(lines[1]).toContain('still processing'); + }); + test('the 409 is recognised and explained with the repair command', () => { + const e = new Error('PATCH /v1/reviewSubmissions/1 -> 409 STATE_ERROR.ASSET_IN_POST_PROCESSING.APP_SCREENSHOT: screenshots are processing'); + expect(isScreenshotProcessing409(e)).toBe(true); + expect(isScreenshotProcessing409(new Error('-> 409 not ready to be submitted'))).toBe(false); + const p = pendingScreenshots(rows, { b: NOW - STUCK_MS - 1 }, NOW); + expect(explain409(p)).toContain('--repair-stuck'); + expect(explain409(p)).toContain('#2 02.png'); + expect(explain409(pendingScreenshots(rows.slice(0, 3), {}, NOW))).toContain('still processing'); + }); + test('validate: stuck is a blocker, processing a warning', () => { + const p = pendingScreenshots(rows.slice(0, 3), { b: NOW - STUCK_MS - 1 }, NOW); + const f = appleRules({ version: null, build: null, expectedLocales: [], locales: [], requiredDisplayTypes: [], reviewDetail: null, ageRating: null, priceSchedule: true, availability: true, + iaps: [], expectedProducts: [], privacyUrl: { url: 'https://example.com/privacy', status: 200 }, screenshotsPending: p }).filter(x => x.code.startsWith('screenshot-')); + expect(f.map(x => [x.code, x.level])).toEqual([['screenshot-stuck', 'blocker'], ['screenshot-processing', 'warn']]); + expect(f[0]!.fix).toContain('--repair-stuck'); + }); + test('ledger keeps the first-seen time and drops screenshots that left UPLOAD_COMPLETE', () => { + updateLedger(dir, [{ id: 'b', state: 'UPLOAD_COMPLETE' }, { id: 'z', state: 'UPLOAD_COMPLETE' }], 100); + updateLedger(dir, [{ id: 'b', state: 'UPLOAD_COMPLETE' }, { id: 'z', state: 'COMPLETE' }], 900); + expect(readLedger(dir)).toEqual({ b: 100 }); + }); +}); + +/** A fake screenshot set: list, delete, upload (append), reorder. */ +function fakeSet(start: ReturnType[]) { + let items = [...start]; + let n = 0; + const calls: string[] = []; + return { + calls, get items() { return items; }, + all: async (_p: string) => items.map(x => ({ ...x })), + asc: async (method: string, path: string, b?: unknown) => { + const body = b as { data: { id: string }[] } | undefined; + calls.push(`${method} ${path}`); + if (method === 'DELETE') items = items.filter(x => !path.endsWith('/' + x.id)); + if (method === 'PATCH') items = body!.data.map(d => items.find(x => x.id === d.id)!); + return {}; + }, + uploadAsset: async (_t: string, _r: unknown, file: string) => { const id = `new${++n}`; calls.push(`UPLOAD ${file.split('/').pop()}`); items.push(shot(id, file.split('/').pop()!, 'COMPLETE')); return id; }, + }; +} + +describe('--repair-stuck', () => { + test('replaces only the stuck one, same file, same position, count unchanged; a re-run does nothing', async () => { + const set = fakeSet([shot('a', '01.png', 'COMPLETE'), shot('b', '02.png', 'UPLOAD_COMPLETE'), shot('c', '03.png', 'UPLOAD_COMPLETE')]); + const rows = setRows(set.items, 'en-US', 'APP_IPHONE_67'); + const pending = pendingScreenshots(rows, { b: NOW - STUCK_MS - 1, c: NOW - 1000 }, NOW); + const files = ['01.png', '02.png', '03.png'].map(f => join(dir, f)); + const steps = repairPlan(rows, pending, files); + expect(steps.map(s => [s.id, s.position, s.file])).toEqual([['b', 2, join(dir, '02.png')]]); + expect(await repairSet(set, 'S', steps)).toEqual({ replaced: 1 }); + expect(set.items.map(x => [x.id, x.attributes.fileName])).toEqual([['a', '01.png'], ['new1', '02.png'], ['c', '03.png']]); + expect(set.calls.filter(c => !c.startsWith('PATCH'))).toEqual(['DELETE /v1/appScreenshots/b', 'UPLOAD 02.png']); + // re-run with the same (now stale) plan: the stuck id is gone, nothing is touched + const before = set.calls.length; + expect(await repairSet(set, 'S', steps)).toEqual({ replaced: 0 }); + expect(set.calls.length).toBe(before); + }); + test('no local file: nothing deleted', async () => { + const set = fakeSet([shot('b', 'gone.png', 'FAILED')]); + const rows = setRows(set.items, 'en-US', 'APP_IPHONE_67'); + const steps = repairPlan(rows, pendingScreenshots(rows, {}, NOW), []); + await expect(repairSet(set, 'S', steps)).rejects.toThrow('no local file'); + expect(set.calls).toEqual([]); + }); +}); + +describe('part uploads', () => { + test('Expect is never sent', () => { + expect(partHeaders({ requestHeaders: [{ name: 'Content-Type', value: 'image/png' }, { name: 'Expect', value: '100-continue' }, { name: 'expect', value: '100-continue' }] })).toEqual({ 'Content-Type': 'image/png' }); + }); + function store(partStatuses: number[]) { + const calls: string[] = []; + let r = 0; + return { + calls, + asc: async (method: string, path: string) => { + calls.push(`${method} ${path}`); + return method === 'POST' ? { data: { id: `r${++r}`, attributes: { uploadOperations: [{ method: 'PUT', url: 'https://upload.example.com/p', offset: 0, length: 4, requestHeaders: [{ name: 'Expect', value: '100-continue' }] }] } } } : {}; + }, + fetch: async (_u: string, i: RequestInit) => { + expect(Object.keys(i.headers as Record).map(k => k.toLowerCase())).not.toContain('expect'); + const s = partStatuses.shift()!; calls.push(`PART ${s}`); return new Response(null, { status: s }); + }, + }; + } + const rel = { appScreenshotSet: { data: { type: 'appScreenshotSets', id: 'S' } } }; + test('a non-2xx part (also 100 / 3xx): the reservation is deleted, retried once, committed only after a good part', async () => { + const s = store([302, 200]); + expect(await uploadAssetVia(s, 'appScreenshots', rel, join(dir, '01.png'))).toBe('r2'); + expect(s.calls).toEqual(['POST /v1/appScreenshots', 'PART 302', 'DELETE /v1/appScreenshots/r1', 'POST /v1/appScreenshots', 'PART 200', 'PATCH /v1/appScreenshots/r2']); + }); + test('two failed parts: throws, never commits', async () => { + const s = store([500, 403]); + await expect(uploadAssetVia(s, 'appScreenshots', rel, join(dir, '01.png'))).rejects.toThrow('nothing committed'); + expect(s.calls.some(c => c.startsWith('PATCH'))).toBe(false); + expect(s.calls.filter(c => c.startsWith('DELETE'))).toEqual(['DELETE /v1/appScreenshots/r1', 'DELETE /v1/appScreenshots/r2']); + }); +}); From 88d1b58f1fa2529a3e6f3d017046f3771154d2b1 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 18:09:06 +0700 Subject: [PATCH 082/344] shots: render refuses missing frames and fails on load errors; shots check errors on renders with failed loads (pitfall 93) --- cli/shots/lib.ts | 17 ++++++++++++++ cli/shots/render.ts | 10 +++++++- cli/shots/report.ts | 1 + cli/shots/spec.ts | 2 +- docs/pitfalls.md | 1 + skills/store-pitfalls/SKILL.md | 12 ++++++++++ tests/shots-missing-frames.test.ts | 37 ++++++++++++++++++++++++++++++ 7 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 tests/shots-missing-frames.test.ts diff --git a/cli/shots/lib.ts b/cli/shots/lib.ts index b440186..8f56cde 100644 --- a/cli/shots/lib.ts +++ b/cli/shots/lib.ts @@ -305,3 +305,20 @@ export function boxOutside(b: DeviceBox, W: number, H: number, tol = 1): string[ if (b.x + b.w > W + tol) out.push(`right ${Math.round(b.x + b.w - W)} px`); return out; } + +/** Frame files (relative to shots.frames: //) a render of these scenes and sizes + * loads. A missing one renders an image with no app or game content (only a 404 in the page), so `shots render` + * refuses to start without them. Landscape layouts use each scene's first frame; the feature graphic a phone frame. */ +export function framesForRender(scenes: { frames: { src: string }[] }[], sizes: string[], langs: string[], + shots: Pick & { feature?: { frame?: string } }): string[] { + const out = new Set(); + for (const lang of langs) for (const size of sizes) { + const s = SIZES[size]; + if (!s) continue; + if (s.feature) { const f = shots.feature?.frame ?? scenes[0]?.frames[0]?.src; if (f) out.add(`${lang}/phone/${f}`); continue; } + const d = renderDims(size, shots); + const kind = d.landscape ? 'landscape' : s.device ? 'tablet' : 'phone'; + for (const sc of scenes) for (const f of d.landscape ? sc.frames.slice(0, 1) : sc.frames) out.add(`${lang}/${kind}/${f.src}`); + } + return [...out].sort(); +} diff --git a/cli/shots/render.ts b/cli/shots/render.ts index 4aa751d..fff6517 100644 --- a/cli/shots/render.ts +++ b/cli/shots/render.ts @@ -25,7 +25,7 @@ import { done, log, warn } from '../lib/log'; import { closeBrowser, launch } from './browser'; import { defaultConcurrency, pool, progressLine } from './capture-web'; import { shotsStyle } from '../lib/config'; -import { type CopyFile, type DeviceBox, type TextBox, SIZES, renderDims, sheetTimeoutMs, featureLayout, copyText, defaultSizes, frameDims, mergeCopy, palette, renderDir, scriptFont, sheetLayout, validateCopy, variantScenes } from './lib'; +import { type CopyFile, type DeviceBox, type TextBox, SIZES, renderDims, sheetTimeoutMs, featureLayout, copyText, defaultSizes, frameDims, framesForRender, mergeCopy, palette, renderDir, scriptFont, sheetLayout, validateCopy, variantScenes } from './lib'; import { bgCss, bgTone, type ContrastSample, contrastIssues, parseColour, photoBackground, photoCss, type RGB, worstContrast } from './palette'; import { type WeightSample, weightIssues } from './weights'; import type { Palette } from '../lib/config'; @@ -70,6 +70,12 @@ export async function run(ctx: Ctx): Promise { if (bad.length) throw new Error(`--scenes: unknown scene id${bad.length > 1 ? 's' : ''} ${bad.join(', ')}${v ? ` (variant ${v})` : ''}; scene ids: ${job.scenes.map(s => s.id).join(', ')}`); } const framesDir = resolve(shots.frames), outDir = resolve(shots.out); + // every frame the scenes load must exist: a missing one renders a store image with no app or game in it + const gone = [...jobs.values()].flatMap(job => { + const sel = a.list('scenes').length ? job.scenes.filter(s => a.list('scenes').includes(s.id)) : job.scenes; + return framesForRender(sel, sizes, langs, shots); + }).filter((f, i, all) => all.indexOf(f) === i && !existsSync(join(framesDir, f))); + if (gone.length) throw new Error(`shots render: ${gone.length} frame file${gone.length > 1 ? 's' : ''} missing under ${relative(root, framesDir) || '.'} (run \`storebound shots capture\` first, or restore the frames folder; it is often git-ignored):\n ${gone.slice(0, 20).join('\n ')}${gone.length > 20 ? `\n ... ${gone.length - 20} more` : ''}`); if (a.has('dry')) { let n = 0; for (const [v, job] of jobs) for (const lang of langs) { @@ -290,6 +296,8 @@ export async function run(ctx: Ctx): Promise { server.stop(true); if (Object.keys(report).length) writeFileSync(join(outDir, 'report.json'), JSON.stringify(mergeReport(readReport(outDir), report), null, 1) + '\n'); } + const broken = Object.entries(report).filter(([, r]) => r.missing?.length); + if (broken.length) throw new Error(`shots render: ${broken.length} image${broken.length > 1 ? 's' : ''} rendered with files that failed to load (frame, logo or background; the image has holes): ${broken.slice(0, 5).map(([k, r]) => `${k} (${r.missing!.join(', ')})`).join('; ')}${broken.length > 5 ? ' ...' : ''}`); const flagged = Object.values(report).filter(r => r.overflow.length).length; if (flagged) warn('shots', `${flagged} images with text overflow flags: storebound shots check / shots gallery`); done('shots', `render done${warnings ? `, ${warnings} with warnings (missing frames or fonts?)` : ''}`); diff --git a/cli/shots/report.ts b/cli/shots/report.ts index f197ada..04d6c18 100644 --- a/cli/shots/report.ts +++ b/cli/shots/report.ts @@ -88,6 +88,7 @@ export function scanRenders(dir: string, o: { langs: string[]; variants?: string const fromStore = !variant && !!pulledEntry(pulled, dir, file, bytes); const issues = fromStore ? [] : checkImage(info, size); const entry = report[rel.replace(/\.jpe?g$/i, '.png')]; + if (entry?.missing?.length) issues.push({ level: 'error', code: 'frame-missing', msg: `rendered while ${entry.missing.length} file${entry.missing.length > 1 ? 's' : ''} failed to load (${entry.missing.join(', ')}): the image lacks its frame / logo / background; restore the frames (shots capture) and render again` }); for (const msg of entry?.overflow ?? []) issues.push({ level: 'warn', code: 'overflow', msg }); issues.push(...fontIssues(entry?.fonts)); issues.push(...deviceIssues(entry, size, info.w, info.h)); diff --git a/cli/shots/spec.ts b/cli/shots/spec.ts index 10d9bd1..40ae395 100644 --- a/cli/shots/spec.ts +++ b/cli/shots/spec.ts @@ -122,7 +122,7 @@ export function imageInfo(b: Uint8Array): ImageInfo { } export type IssueLevel = 'error' | 'warn'; -export interface Issue { level: IssueLevel; code: 'size' | 'alpha' | 'format' | 'bytes' | 'count' | 'overflow' | 'video' | 'font-fallback' | 'glyph-missing' | 'device-crop' | 'fonts' | 'margin' | 'font-weight' | 'contrast' | 'background'; msg: string } +export interface Issue { level: IssueLevel; code: 'size' | 'alpha' | 'format' | 'bytes' | 'count' | 'overflow' | 'video' | 'font-fallback' | 'glyph-missing' | 'device-crop' | 'fonts' | 'margin' | 'font-weight' | 'contrast' | 'background' | 'frame-missing'; msg: string } /** Problems with one image for a size key. */ export function checkImage(info: ImageInfo, sizeKey: string): Issue[] { diff --git a/docs/pitfalls.md b/docs/pitfalls.md index b1248cc..8056ceb 100644 --- a/docs/pitfalls.md +++ b/docs/pitfalls.md @@ -9,6 +9,7 @@ fails without the fix. | # | date | lesson | guard | |---|---|---|---| +| 93 | 2026-10 | A git-ignored, never-captured frames folder rendered store images with no app or game in them; render only logged 404s and `shots check` said 0 errors. | `shots render` refuses to start while a scene frame is missing (`framesForRender` in `cli/shots/lib.ts`) and fails when any load failed; report.json `missing` is a `frame-missing` error in `shots check` / `validate` (`cli/shots/report.ts`, `tests/shots-missing-frames.test.ts`). | | 90 | 2026-10 | `apple submit --build N --version X --yes` after `apple submit --no-submit --yes` (the documented two-step flow) printed the plan (every item "in it already", then "submit PATCH submitted: true"), logged "not added ...: already in the draft submission" and ended with "nothing to submit" without the PATCH: the submit only ran for new items or an UNRESOLVED_ISSUES submission. | `willSubmit` (cli/lib/review-submit.ts) also submits a READY_FOR_REVIEW draft that already holds the named app version (iap-submit: one of the asked-for items), with the same "not ready yet" retry. `tests/resubmit.test.ts` ("the second step submits the prepared draft"). | | 85 | 2026-10 | `shots record --source web` filmed at the page's CSS size: Chromium's screencast ignores the deviceScaleFactor (maxWidth only shrinks), so a 1080x1920 preview of a 430x932 @2x page was a 2.5x upscale. | `Page.captureScreenshot` with `clip.scale` = dpr (long side capped at 1920), 3 requests in flight, timestamped frames joined by ffmpeg; a warning when the first frame is smaller than asked or the rate is under 20 frames/s. `recordSize` / `captureShortfall` in `cli/shots/devices.ts`, `tests/video.test.ts`. | | 80 | 2026-10 | A game's hero logo and titles sat against the screenshot edges, a game with a macOS version had no Mac screenshots, and the contact sheet timed out at a flat 30 s with 9 sizes. | Templates keep 7 % / 5 % safe margins and `shots check` fails text or logo boxes under 6 % / 4 % (`marginViolations`, report.json `boxes`); `apple.mac` adds the `mac` size (APP_DESKTOP, macOS version); `sheetTimeoutMs` scales with images, sizes and load. `tests/mac-landscape.test.ts`, `tests/browser/landscape.browser.ts`. | diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index cc5b7da..f6131d3 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1136,3 +1136,15 @@ that fails without the fix (see CONTRIBUTING.md). Owner-only operations (submit, release, delete, prices, testers, replies, ...) refuse `--confirm`: the owner still types the id in a terminal. MCP and the desktop app still never send writes. - **Guard:** `decide` / `OWNER_NO_CONFIRM` in `cli/api/gate.ts`, `tests/api.test.ts`. + +## 93. Screenshots rendered without their frames (empty store images, check said 0 errors) +- **Symptom:** `shots render` finished and `shots check` reported 0 errors / 0 warnings, but the images showed only + captions and backgrounds: no app or game. The render log had only `404 .../frames/...` warnings. +- **Cause:** the raw frames folder (`shots.frames`) is usually git-ignored; in a fresh checkout it was never captured, + and the 404s were recorded in report.json `missing` but never checked. +- **Do:** run `storebound shots capture` (or restore the frames folder) before rendering. Never ship renders whose + log has 404 lines. +- **Guard:** `shots render` refuses to start while any frame a selected scene uses is missing (`framesForRender` in + `cli/shots/lib.ts`) and exits 1 if any file failed to load while rendering; `shots check` and `validate` raise a + `frame-missing` error for every render whose report entry has failed loads (`cli/shots/report.ts`, + `tests/shots-missing-frames.test.ts`). diff --git a/tests/shots-missing-frames.test.ts b/tests/shots-missing-frames.test.ts new file mode 100644 index 0000000..32ce4e6 --- /dev/null +++ b/tests/shots-missing-frames.test.ts @@ -0,0 +1,37 @@ +// Guardrail from real use: the raw frames folder was git-ignored and never captured, `shots render` produced store +// images with no app or game in them (only 404 lines in the log) and `shots check` still said 0 errors. Now render +// refuses to start without every frame, and report.json `missing` entries are check errors. +import { describe, expect, test } from 'bun:test'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { framesForRender } from '../cli/shots/lib'; +import { allIssues, scanRenders } from '../cli/shots/report'; +import { png } from './fixtures'; + +const scenes = [{ frames: [{ src: 'home.png' }, { src: 'back.png' }] }, { frames: [{ src: 'level.png' }] }]; + +describe('missing frames', () => { + test('framesForRender lists every frame per language and device class', () => { + expect(framesForRender(scenes, ['ios69', 'ipad13', 'feature'], ['en'], {})).toEqual([ + 'en/phone/back.png', 'en/phone/home.png', 'en/phone/level.png', 'en/tablet/back.png', 'en/tablet/home.png', 'en/tablet/level.png']); + expect(framesForRender(scenes, ['mac'], ['en', 'tr'], {})).toEqual(['en/landscape/home.png', 'en/landscape/level.png', 'tr/landscape/home.png', 'tr/landscape/level.png']); + expect(framesForRender(scenes, ['feature'], ['en'], { feature: { frame: 'promo.png' } })).toEqual(['en/phone/promo.png']); + }); + + test('a render recorded with failed loads is a shots check error', () => { + const dir = mkdtempSync(join(tmpdir(), 'sb-missing-')); + try { + mkdirSync(join(dir, 'en', 'ios69'), { recursive: true }); + writeFileSync(join(dir, 'en', 'ios69', '01.png'), png(1320, 2868)); + writeFileSync(join(dir, 'en', 'ios69', '02.png'), png(1320, 2868)); + writeFileSync(join(dir, 'report.json'), JSON.stringify({ + 'en/ios69/01.png': { overflow: [], missing: ['404 http://127.0.0.1:8792/frames/en/phone/home.png'], fonts: { fallback: [], missing: [] } }, + 'en/ios69/02.png': { overflow: [], missing: [], fonts: { fallback: [], missing: [] } }, + })); + const issues = allIssues(scanRenders(dir, { langs: ['en'], sizes: ['ios69'], probe: () => null })).filter(x => x.issue.code === 'frame-missing'); + expect(issues.map(x => `${x.where} ${x.issue.level}`)).toEqual(['en/ios69/01.png error']); + expect(issues[0]!.issue.msg).toContain('/frames/en/phone/home.png'); + } finally { rmSync(dir, { recursive: true, force: true }); } + }); +}); From e5dffb5533726b427a231c374fa5d57866818a67 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 18:10:58 +0700 Subject: [PATCH 083/344] docs/HANDOFF.md: what is released, the open work (desktop report view in a stash, two worktrees of other sessions, things not verified live), and the rules that matter --- docs/HANDOFF.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 docs/HANDOFF.md diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md new file mode 100644 index 0000000..a4a4abd --- /dev/null +++ b/docs/HANDOFF.md @@ -0,0 +1,36 @@ +# Handoff + +State of storebound for whoever picks it up next. Public-safe: no project, app or account names. + +## Released + +- npm, storebound.dev and the desktop app carry the latest tag (see `CHANGELOG.md`). +- Releases: `bun tools/release.ts --yes` runs everything in one command, npm included (docs/desktop-release.md). + - Background tests run on Forgejo and never gate a release. `bun tools/ci-status.ts` shows the newest result. + - The Linux and Windows updater signatures are made on the release server: `bun tools/desktop-release.ts vds-key` + rotates its key, and `--sign-local` is the fallback. + +## Open work + +- **Desktop report view + design v2** (paused by the owner). + - What it is: the readiness report inside the desktop app as its own screen, not only in the browser. Also a + stronger design (a hero per store, "what to fix first", passed checks shown, a 1200x630 summary image). + - Where it is: half done, kept in a local git stash named "paused: report in desktop + design v2" (not pushed). + - How to resume: `git stash list`, then `git stash apply`, then finish the view and run the desktop typecheck and the + fixture UI. +- **Two worktrees with uncommitted changes from other sessions:** + - `guardrail-2310-macos`: Apple platform commands (iap-submit, release, resubmit, status); + - `shots-bleed-landscape`: landscape screenshots and uploads. + Their owners decide; don't delete them without asking. +- **Not verified live yet:** + - The IARC exact-label helper in the console plans (tested on a fake page only). + - The Play Games Services console page paths. + - The Games Configuration API bodies (no pinned spec). + - Placing a Header and Search Results asset on a live App Store version. +- **iPhone Duo:** App Store Connect's API has no Duo screenshot type yet. Uploads skip with a console link; wire it + when the spec gains the type (`IPHONE_DUO_DISPLAY` in `cli/shots/spec.ts`). + +## Rules that matter here + +- Every check, message and screen covers both stores and every surface (AGENTS.md, "Working on storebound itself"). +- Real projects reported most guardrails. They stay anonymous in the repo: neutral names and com.example.* only. From 0ac3cd02b0be16bab45c661bd230c385211b8d5b Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 22:21:49 +0800 Subject: [PATCH 084/344] Windows: MCP entries start through cmd /c npx or bun cli/index.ts (npx.cmd and the sh launcher cannot be spawned, pitfall 94); desktop download streams with progress and fails after 60 s without data (pitfall 95); getting-started Windows note --- cli/desktop.ts | 34 +++++++++++++++++++++++++++++++--- cli/install.ts | 14 +++++++++++++- docs/getting-started.md | 4 ++++ skills/store-pitfalls/SKILL.md | 18 ++++++++++++++++++ tests/desktop-dist.test.ts | 3 +++ tests/wave1.test.ts | 13 ++++++++----- 6 files changed, 77 insertions(+), 9 deletions(-) diff --git a/cli/desktop.ts b/cli/desktop.ts index 256ca56..8089388 100644 --- a/cli/desktop.ts +++ b/cli/desktop.ts @@ -58,10 +58,10 @@ export function pick(m: Manifest, keys: DownloadKey[], format?: string): [Downlo } /** Downloads one installer and keeps it only when its size, SHA-256 and minisign signature are right. */ -export async function download(d: Download, dir: string, get: Fetch = fetch, publicKey = PUBLIC_KEY): Promise { - const r = await get(d.url); +export async function download(d: Download, dir: string, get: Fetch = fetch, publicKey = PUBLIC_KEY, stallMs = 60_000, say: (s: string) => void = s => console.log(s)): Promise { + const r = await withStall(get(d.url), stallMs, d.url); if (!r.ok) throw new Error(`${d.url}: HTTP ${r.status}`); - const data = new Uint8Array(await r.arrayBuffer()); + const data = await readBody(r, d, stallMs, say); if (data.length !== d.size) throw new Error(`${d.file}: ${data.length} bytes, latest.json says ${d.size}; not kept`); const sha = createHash('sha256').update(data).digest('hex'); if (sha !== d.sha256) throw new Error(`${d.file}: SHA-256 ${sha} does not match latest.json; not kept`); @@ -75,6 +75,34 @@ export async function download(d: Download, dir: string, get: Fetch = fetch, pub return out; } +function withStall(p: Promise, ms: number, url: string): Promise { + let t: ReturnType | undefined; + const stall = new Promise((_, no) => { t = setTimeout(() => no(new Error(`${url}: no data for ${ms / 1000} s; the download stalled (try again; pitfall 95)`)), ms); }); + return Promise.race([p, stall]).finally(() => clearTimeout(t)); +} + +/** Reads the body in chunks: a progress line every 10 % and a stall error when no byte arrives for `stallMs` + * (a cold CDN cache once sent nothing for minutes and the CLI waited forever, pitfall 95). */ +async function readBody(r: Response, d: Download, stallMs: number, say: (s: string) => void): Promise { + if (!r.body) return new Uint8Array(await r.arrayBuffer()); + const reader = r.body.getReader(); + const parts: Uint8Array[] = []; + let n = 0, shown = 0; + try { + for (;;) { + const { done, value } = await withStall(reader.read(), stallMs, d.url); + if (done) break; + parts.push(value); n += value.length; + const pct = d.size ? Math.floor((n / d.size) * 10) * 10 : 0; + if (pct > shown && pct < 100) { shown = pct; say(` ${pct}% (${(n / 1e6).toFixed(1)} MB)`); } + } + } catch (e) { void reader.cancel().catch(() => {}); throw e; } + const out = new Uint8Array(n); + let o = 0; + for (const p of parts) { out.set(p, o); o += p.length; } + return out; +} + const VERSION_RE = /\b(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\b/; /** The version of an installed app: Info.plist on macOS, `storebound-desktop --version` elsewhere (15 s at most). */ diff --git a/cli/install.ts b/cli/install.ts index 3ad841a..72c9e29 100644 --- a/cli/install.ts +++ b/cli/install.ts @@ -29,7 +29,19 @@ function snapshot(dir: string, base = dir, out = new Map()): Map } const same = (a: Map, b: Map) => a.size === b.size && [...a].every(([k, v]) => b.get(k) === v); -export function mcpCommand(project: string, override?: string, runtime: 'bun' | 'node' = rt.runtime.name, version = pkg.version): McpCommand { +/** Windows cannot start `npx` (a .cmd shim) or the /bin/sh launcher as a stdio command (pitfall 94). */ +export function winWrap(c: McpCommand, platform: string = process.platform): McpCommand { + if (platform !== 'win32') return c; + if (c.command === 'npx') return { command: 'cmd', args: ['/c', 'npx', ...c.args] }; + if (c.command === join(TOOLCHAIN, 'bin', 'storebound')) return { command: 'bun', args: [join(TOOLCHAIN, 'cli', 'index.ts'), ...c.args] }; + return c; +} + +export function mcpCommand(project: string, override?: string, runtime: 'bun' | 'node' = rt.runtime.name, version = pkg.version, platform: string = process.platform): McpCommand { + return winWrap(mcpCommand0(project, override, runtime, version), platform); +} + +function mcpCommand0(project: string, override?: string, runtime: 'bun' | 'node' = rt.runtime.name, version = pkg.version): McpCommand { if (override) { const [command, ...args] = override.split(/\s+/).filter(Boolean); return { command: command!, args: [...args, 'mcp'] }; } if (existsSync(join(project, 'node_modules', 'storebound', 'package.json'))) return { command: runtime === 'bun' ? 'bunx' : 'npx', args: ['storebound', 'mcp'] }; if (runtime === 'node') return { command: 'npx', args: ['-y', `storebound@${version}`, 'mcp'] }; diff --git a/docs/getting-started.md b/docs/getting-started.md index 5b6177d..02f2c56 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -152,6 +152,10 @@ plain Markdown and the CLI is a normal command. and `--command ""` to choose how the MCP server starts. It only adds or updates the `storebound` entry and its own skill folders; everything else in those files stays as it is, and re-running it is safe. +**Windows:** an MCP client cannot start `npx` directly (it is `npx.cmd`). `install` writes the working form for you; +by hand use `"command": "cmd", "args": ["/c", "npx", "-y", "storebound@", "mcp"]` (or `bunx storebound mcp` +with Bun). If the server shows "connection closed", check this first ([pitfall 94](../skills/store-pitfalls/SKILL.md)). + --- [All docs](README.md) · [README](../README.md) diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index f6131d3..68af0d1 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1148,3 +1148,21 @@ that fails without the fix (see CONTRIBUTING.md). `cli/shots/lib.ts`) and exits 1 if any file failed to load while rendering; `shots check` and `validate` raise a `frame-missing` error for every render whose report entry has failed loads (`cli/shots/report.ts`, `tests/shots-missing-frames.test.ts`). + +## 94. The MCP server never starts on Windows (`npx` as the stdio command) +- **Symptom:** the agent shows the `storebound` MCP server as "failed" / "connection closed" on Windows; the same + entry works on macOS and Linux. An old entry pinned to an old version (`storebound@0.8.2`) also hides new tools. +- **Cause:** on Windows `npx` is `npx.cmd`, which an MCP client cannot spawn directly as a stdio command; the + `bin/storebound` launcher is a /bin/sh script and cannot be spawned either. +- **Do:** use `{"command": "cmd", "args": ["/c", "npx", "-y", "storebound@", "mcp"]}`, or re-run + `storebound install --agent `, which writes that form (or `bun /cli/index.ts mcp`) on Windows. Keep the version current. +- **Guard:** `winWrap` / `mcpCommand` in `cli/install.ts`, `tests/wave1.test.ts`. + +## 95. `storebound desktop` stayed on "downloading ..." forever +- **Symptom:** `npx storebound desktop` printed `downloading storebound__x64-setup-unsigned.exe (37.0 MB)` and + then nothing, for many minutes. +- **Cause:** the installer was not in the CDN cache yet (`cf-cache-status: MISS`) and the origin sent no bytes; the + CLI read the whole body at once, with no progress and no timeout. +- **Do:** run the command again later; after a release, warm the CDN cache by fetching every installer once. +- **Guard:** `download` in `cli/desktop.ts` reads in chunks, prints progress every 10 % and fails after 60 s without + data (`tests/desktop-dist.test.ts`). diff --git a/tests/desktop-dist.test.ts b/tests/desktop-dist.test.ts index ff2771d..53887b2 100644 --- a/tests/desktop-dist.test.ts +++ b/tests/desktop-dist.test.ts @@ -106,6 +106,9 @@ describe('latest.json and downloads', () => { await expect(download({ ...d, file: 'c.dmg', sha256: sha }, dir, serve(evil), k.pub)).rejects.toThrow(/signature/); await expect(download({ ...d, file: 'e.dmg' }, dir, serve(data.subarray(1)), k.pub)).rejects.toThrow(/bytes/); await expect(download({ ...d, file: 'f.dmg' }, dir, async () => new Response('', { status: 404 }), k.pub)).rejects.toThrow(/404/); + // a body that never sends a byte fails after the stall timeout instead of hanging forever (pitfall 95) + const silent = async () => new Response(new ReadableStream({ start() {} })); + await expect(download({ ...d, file: 'g.dmg' }, dir, silent, k.pub, 50, () => {})).rejects.toThrow(/stalled/); for (const f of ['b.dmg', 'c.dmg', 'e.dmg', 'f.dmg']) expect(existsSync(join(dir, f))).toBe(false); }); }); diff --git a/tests/wave1.test.ts b/tests/wave1.test.ts index 21faa86..894e88b 100644 --- a/tests/wave1.test.ts +++ b/tests/wave1.test.ts @@ -455,21 +455,24 @@ describe('install', () => { const vs = JSON.parse(readFileSync(join(dir, '.vscode/mcp.json'), 'utf8')); expect(Object.keys(vs.servers)).toEqual(['keep', 'storebound']); expect(readFileSync(join(dir, '.codex/config.toml'), 'utf8')).toContain('[mcp_servers.storebound]'); - expect(JSON.parse(readFileSync(join(home, '.config/devin/mcp_config.json'), 'utf8')).mcpServers.storebound.args).toEqual(['mcp']); + expect(JSON.parse(readFileSync(join(home, '.config/devin/mcp_config.json'), 'utf8')).mcpServers.storebound.args.at(-1)).toBe('mcp'); const before = readFileSync(join(dir, '.vscode/mcp.json'), 'utf8'); await install(parseArgs(['--agent', 'copilot', '--dir', dir, '--home', home])); expect(readFileSync(join(dir, '.vscode/mcp.json'), 'utf8')).toBe(before); }); test('mcp command choice', () => { const dir = tmp(); - expect(mcpCommand(dir).command).toMatch(/bin\/storebound$/); + expect(mcpCommand(dir, undefined, 'bun', undefined, 'linux').command).toMatch(/bin[\\/]storebound$/); + expect(mcpCommand(dir, undefined, 'bun', undefined, 'win32')).toEqual({ command: 'bun', args: [expect.stringMatching(/cli[\\/]index\.ts$/), 'mcp'] }); // run with Node (npx storebound install): the toolchain sits in npx's cache, so the pinned package instead - expect(mcpCommand(dir, undefined, 'node', '1.2.3')).toEqual({ command: 'npx', args: ['-y', 'storebound@1.2.3', 'mcp'] }); + expect(mcpCommand(dir, undefined, 'node', '1.2.3', 'linux')).toEqual({ command: 'npx', args: ['-y', 'storebound@1.2.3', 'mcp'] }); mkdirSync(join(dir, 'node_modules/storebound'), { recursive: true }); writeFileSync(join(dir, 'node_modules/storebound/package.json'), '{}'); expect(mcpCommand(dir)).toEqual({ command: 'bunx', args: ['storebound', 'mcp'] }); - expect(mcpCommand(dir, undefined, 'node')).toEqual({ command: 'npx', args: ['storebound', 'mcp'] }); - expect(mcpCommand(dir, 'npx -y storebound')).toEqual({ command: 'npx', args: ['-y', 'storebound', 'mcp'] }); + expect(mcpCommand(dir, undefined, 'node', undefined, 'linux')).toEqual({ command: 'npx', args: ['storebound', 'mcp'] }); + expect(mcpCommand(dir, 'npx -y storebound', undefined, undefined, 'linux')).toEqual({ command: 'npx', args: ['-y', 'storebound', 'mcp'] }); + expect(mcpCommand(dir, 'npx -y storebound', undefined, undefined, 'win32')).toEqual({ command: 'cmd', args: ['/c', 'npx', '-y', 'storebound', 'mcp'] }); + expect(mcpCommand(dir, undefined, 'bun', undefined, 'win32').command).not.toBe('cmd'); }); }); From 46f3e56c09cdfe4b033ccd851a35f9d69f2ef625 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 22:26:30 +0800 Subject: [PATCH 085/344] Windows checkouts: .gitattributes keeps text files LF (CRLF skills broke gen-adapters); findInstalled builds macOS/Linux paths with posix join; CONTRIBUTING Windows setup and desktop build --- .gitattributes | 13 +++++++++++++ CONTRIBUTING.md | 6 ++++++ cli/lib/desktop-dist.ts | 12 ++++++------ 3 files changed, 25 insertions(+), 6 deletions(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..714a3aa --- /dev/null +++ b/.gitattributes @@ -0,0 +1,13 @@ +* text=auto eol=lf +*.png binary +*.jpg binary +*.ico binary +*.icns binary +*.ttf binary +*.woff2 binary +*.mp4 binary +*.bat text eol=crlf +*.cmd text eol=crlf +# kept byte-for-byte as published upstream (CRLF) +cli/data/play-data-safety-form.csv -text +**/icons/LICENSE.txt -text diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a7d0abf..a6d34c2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -13,6 +13,12 @@ bun run ci # full gate before pushing: every check and test (ad bun run test:browser # only by hand: the suites that start Chrome / Chromium (tests/browser/*.browser.ts) ``` +**Windows.** `.gitattributes` keeps every text file LF in the working tree (with `core.autocrlf=true` the skills +came out CRLF and `bun tools/gen-adapters.ts` failed with "no frontmatter"). On a checkout made before that file +existed, run `git rm -r --cached -q . && git reset --hard` once on a clean tree. The desktop app builds with +`cd apps/desktop && bun run sidecar && bunx tauri build` (Rust via rustup; WiX and NSIS are downloaded by Tauri) into +`src-tauri/target/release/bundle/nsis/*-setup.exe` and `bundle/msi/*.msi`. + **Browser tests run only by hand.** The suites that launch a browser (console fill / flow / session / persist, web capture, glyphs and ligatures, local fonts, feature-graphic fit, site overflow) live in `tests/browser/` as `*.browser.ts`, which `bun test`, `ci`, `ci:quick` and the Forgejo workflows never pick up. Run `bun run test:browser` diff --git a/cli/lib/desktop-dist.ts b/cli/lib/desktop-dist.ts index 20f252e..552862a 100644 --- a/cli/lib/desktop-dist.ts +++ b/cli/lib/desktop-dist.ts @@ -9,7 +9,7 @@ // tests/desktop-dist.test.ts. import { existsSync, readdirSync } from 'node:fs'; import { homedir } from 'node:os'; -import { join } from 'node:path'; +import { join, posix } from 'node:path'; export const BUNDLE_ID = 'dev.storebound.desktop'; export const PAGE = 'https://storebound.dev/#download'; @@ -101,9 +101,9 @@ export function findInstalled(platform: NodeJS.Platform, env: Record /^storebound(?:[-_][A-Za-z0-9._-]*)?\.AppImage$/i.test(n)).sort().at(-1); - if (name) return { path: join(dir, name), how: 'appimage' }; + if (name) return { path: posix.join(dir, name), how: 'appimage' }; } return null; } From 5317230b087c17dd1b8e8c3ddec49d74c8020dec Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 22:37:51 +0800 Subject: [PATCH 086/344] README: drop the stale static version badge (npm badge is live), Agent Skills badge 39 with a test that keeps it in step; CHANGELOG Unreleased for the Windows fixes --- CHANGELOG.md | 6 ++++++ README.md | 3 +-- tests/readme-badges.test.ts | 19 +++++++++++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 tests/readme-badges.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 844b291..3bacc55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- **Windows: the MCP server starts.** `storebound install` writes `cmd /c npx -y storebound@ mcp` (or + `bun /cli/index.ts mcp`) on Windows, where `npx.cmd` and the sh launcher cannot be spawned. Pitfall 94. +- **`storebound desktop` no longer waits forever on a stalled download.** Progress every 10 %, and an error after + 60 s without data. Pitfall 95. +- Windows checkouts keep LF line endings (`.gitattributes`); README badges: live npm version, real skill count. + ## 0.8.23 · 2026-10-21 - **`apple submit --yes` submits a draft prepared with `--no-submit`.** The second step of the two-step flow diff --git a/README.md b/README.md index 3ff3849..c38d019 100644 --- a/README.md +++ b/README.md @@ -9,10 +9,9 @@ in-app products and prices, the compliance forms, even the consoles that have no [![npm](https://img.shields.io/npm/v/storebound?label=npm&color=cb3837)](https://www.npmjs.com/package/storebound) [![license: MIT](https://img.shields.io/badge/license-MIT-blue)](https://git.crt.fyi/CRT/storebound/src/branch/main/LICENSE) -[![version 0.6.0](https://img.shields.io/badge/version-0.6.0-informational)](https://git.crt.fyi/CRT/storebound/src/branch/main/CHANGELOG.md) [![runtime: Node 20+ or Bun 1.1+](https://img.shields.io/badge/runtime-Node%2020%2B%20%7C%20Bun%201.1%2B-f9f1e1)](#install-and-start) [![runtime dependencies: 0](https://img.shields.io/badge/runtime%20dependencies-0-brightgreen)](https://git.crt.fyi/CRT/storebound/src/branch/main/package.json) -[![Agent Skills: 25](https://img.shields.io/badge/Agent%20Skills-25-8a63d2)](https://git.crt.fyi/CRT/storebound/src/branch/main/skills) +[![Agent Skills: 39](https://img.shields.io/badge/Agent%20Skills-39-8a63d2)](https://git.crt.fyi/CRT/storebound/src/branch/main/skills) [![MCP: 2026-07-28](https://img.shields.io/badge/MCP-2026--07--28-black)](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/mcp.md) **Website: [storebound.dev](https://storebound.dev) · Docs: [docs/](https://git.crt.fyi/CRT/storebound/src/branch/main/docs/README.md) · `npx storebound init`** diff --git a/tests/readme-badges.test.ts b/tests/readme-badges.test.ts new file mode 100644 index 0000000..edabb1c --- /dev/null +++ b/tests/readme-badges.test.ts @@ -0,0 +1,19 @@ +// README badges never go stale: the version comes from npm (a static version badge once said 0.6.0 at 0.8.23) and the +// skill count must match skills/*/SKILL.md. +import { describe, expect, test } from 'bun:test'; +import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +const root = join(import.meta.dir, '..'); +const readme = readFileSync(join(root, 'README.md'), 'utf8'); + +describe('README badges', () => { + test('no hand-written version badge; the npm badge is live', () => { + expect(readme).not.toMatch(/img\.shields\.io\/badge\/version-/); + expect(readme).toContain('img.shields.io/npm/v/storebound'); + }); + test('the Agent Skills badge counts every skill', () => { + const n = readdirSync(join(root, 'skills')).filter(d => existsSync(join(root, 'skills', d, 'SKILL.md'))).length; + expect(/Agent%20Skills-(\d+)-/.exec(readme)?.[1]).toBe(String(n)); + }); +}); From e03cbbe8aa3324411e201c86d4c000f302c2b0e9 Mon Sep 17 00:00:00 2001 From: CRT Date: Wed, 21 Oct 2026 23:40:26 +0700 Subject: [PATCH 087/344] storebound 0.8.24: version in package.json and every copy, CHANGELOG 0.8.24 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index e978bf6..b8dfe47 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.23", + "version": "0.8.24", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index a05cceb..39866c9 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.23", + "version": "0.8.24", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 037b08f..841c6ac 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.23", + "version": "0.8.24", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bacc55..8bed5bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.24 · 2026-10-21 + - **Windows: the MCP server starts.** `storebound install` writes `cmd /c npx -y storebound@ mcp` (or `bun /cli/index.ts mcp`) on Windows, where `npx.cmd` and the sh launcher cannot be spawned. Pitfall 94. - **`storebound desktop` no longer waits forever on a stalled download.** Progress every 10 %, and an error after diff --git a/apps/desktop/package.json b/apps/desktop/package.json index af4ef39..d1be11a 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.23", + "version": "0.8.24", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 622bd1b..ec08b77 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4010,7 +4010,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.23" +version = "0.8.24" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 795c54a..f81a7e5 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.23" +version = "0.8.24" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index a0d4a78..122f7ad 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.23", + "version": "0.8.24", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index cea40a8..a6f0276 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.23", + "version": "0.8.24", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index ce1bffc..b327a24 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.23", + "version": "0.8.24", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From 4f993a906a5a780ec7a19ab8b249736a30cdfc7d Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 01:39:14 +0800 Subject: [PATCH 088/344] fastlane traces: check and release status warn, scan reports fastlane-upload when a Fastfile / Appfile or a CI file or script still runs fastlane supply, deliver or pilot (file:line, storebound import fastlane); test, pitfall 96 --- CHANGELOG.md | 4 +++ cli/check.ts | 3 ++ cli/lib/fastlane-traces.ts | 66 ++++++++++++++++++++++++++++++++++ cli/lib/scan/index.ts | 10 ++++++ cli/release.ts | 4 ++- skills/store-pitfalls/SKILL.md | 11 ++++++ tests/fastlane-traces.test.ts | 43 ++++++++++++++++++++++ 7 files changed, 140 insertions(+), 1 deletion(-) create mode 100644 cli/lib/fastlane-traces.ts create mode 100644 tests/fastlane-traces.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 8bed5bc..e306175 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- **fastlane left in a project is named.** `check` and `release status` warn and `scan` reports `fastlane-upload` + when a Fastfile / Appfile or a CI file or script still runs `fastlane supply`, `deliver` or `pilot`, with the + file:line and the way over (`storebound import fastlane`). Pitfall 96. + ## 0.8.24 · 2026-10-21 - **Windows: the MCP server starts.** `storebound install` writes `cmd /c npx -y storebound@ mcp` (or diff --git a/cli/check.ts b/cli/check.ts index 8b9368e..9147c00 100644 --- a/cli/check.ts +++ b/cli/check.ts @@ -34,6 +34,7 @@ import { creativeNote } from './shots/creative'; import { type CapProject, capacitorProject, prebuildFor, staleMessage, webState } from './lib/web-assets'; import { iphoneDuoNote } from './shots/spec'; import { hitLine } from './lib/cross-store'; +import { FASTLANE_FIX, findFastlaneTraces, traceLine } from './lib/fastlane-traces'; import { listingFileMentions } from './lib/listing-mentions'; /** The newest .ipa in a folder (apple build's export), or null. */ @@ -95,6 +96,8 @@ export async function run(ctx: Ctx): Promise { } return `${Object.keys(copy).length} locales`; }); + // fastlane uploads left next to storebound (pitfall 96) + try { const tr = findFastlaneTraces(dirname(path)); if (tr.length) for (const t of tr) note(`${traceLine(t)} · ${FASTLANE_FIX}`); } catch (e) { warn('check', `fastlane traces: ${(e as Error).message}`); } // other platforms named in a store's text: App Store 2.3.10 / Play Metadata, a blocker (pitfall 77) try { for (const h of listingFileMentions(ctx.loaded)) problems.push(`other platform in ${hitLine(h)}`); } catch (e) { warn('check', `platform mentions: ${(e as Error).message}`); } // listing translation drafts (storebound listing translate): fine to keep working on, not to push unreviewed diff --git a/cli/lib/fastlane-traces.ts b/cli/lib/fastlane-traces.ts new file mode 100644 index 0000000..0a666ba --- /dev/null +++ b/cli/lib/fastlane-traces.ts @@ -0,0 +1,66 @@ +// Fastlane left in a project storebound manages: a CI job or script that still uploads with `fastlane supply` +// (or deliver / pilot) bypasses storebound's checks and fights its writes, and nothing said so (pitfall 96). +// Offline and read-only: looks for Fastfile / Appfile, a fastlane/ folder and upload calls in CI files and scripts. +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; +import { join, relative, sep } from 'node:path'; + +export interface FastlaneTrace { + file: string; + line: number; + text: string; + /** play (supply, upload_to_play_store), apple (deliver, pilot, upload_to_app_store / testflight) or both (a file). */ + store: 'apple' | 'play' | 'both'; +} + +const UPLOAD = /\b(supply|upload_to_play_store|deliver|upload_to_app_store|pilot|upload_to_testflight)\b/; +/** A fastlane command line in CI / scripts: `fastlane supply`, `bundle exec fastlane run deliver`, `fastlane pilot upload`. */ +const CLI_CALL = /\bfastlane\s+(?:run\s+)?(supply|upload_to_play_store|deliver|upload_to_app_store|pilot|upload_to_testflight)\b/; +const PLAY = new Set(['supply', 'upload_to_play_store']); +const FASTLANE_DIRS = ['', 'ios', 'android', 'ios/App', 'android/app']; +const CI_FILES = ['Jenkinsfile', '.gitlab-ci.yml', 'bitrise.yml', 'codemagic.yaml', 'azure-pipelines.yml', 'Makefile', 'package.json', 'appcenter-post-build.sh']; +const CI_DIRS = ['.github/workflows', '.forgejo/workflows', '.gitea/workflows', '.circleci', 'scripts', 'ci', '.ci', 'tools']; +const SCRIPT_EXT = /\.(ya?ml|sh|bash|zsh|ps1|groovy|rb|mjs|js|ts|json)$/i; + +const storeOf = (m: string): 'apple' | 'play' => (PLAY.has(m) ? 'play' : 'apple'); + +function lines(file: string): string[] { + try { return statSync(file).size > 2_000_000 ? [] : readFileSync(file, 'utf8').split(/\r?\n/); } catch { return []; } +} + +export function findFastlaneTraces(root: string): FastlaneTrace[] { + const out: FastlaneTrace[] = []; + const rel = (p: string) => relative(root, p).split(sep).join('/'); + const seen = new Set(); + // Fastfile / Appfile (in fastlane/ or next to it): the file itself, plus each upload action it calls + for (const d of FASTLANE_DIRS) { + for (const f of [join(root, d, 'fastlane', 'Fastfile'), join(root, d, 'Fastfile'), join(root, d, 'fastlane', 'Appfile'), join(root, d, 'Appfile')]) { + if (seen.has(f) || !existsSync(f)) continue; + seen.add(f); + const ls = lines(f); + let calls = 0; + ls.forEach((l, i) => { + const m = UPLOAD.exec(l.replace(/#.*/, '')); + if (m && /Fastfile$/.test(f)) { out.push({ file: rel(f), line: i + 1, text: l.trim(), store: storeOf(m[1]!) }); calls++; } + }); + if (!calls) out.push({ file: rel(f), line: 1, text: ls.find(l => l.trim())?.trim() ?? '', store: 'both' }); + } + } + // CI files and scripts that run fastlane uploads + const files = CI_FILES.map(f => join(root, f)).filter(f => existsSync(f)); + for (const d of CI_DIRS) { + const dir = join(root, d); + try { for (const n of readdirSync(dir)) if (SCRIPT_EXT.test(n)) files.push(join(dir, n)); } catch { /* none */ } + } + try { for (const n of readdirSync(root)) if (/\.(sh|bash|ps1)$/i.test(n)) files.push(join(root, n)); } catch { /* unreadable */ } + for (const f of new Set(files)) { + lines(f).forEach((l, i) => { + const m = CLI_CALL.exec(l); + if (m) out.push({ file: rel(f), line: i + 1, text: l.trim().slice(0, 200), store: storeOf(m[1]!) }); + }); + } + return out; +} + +export const FASTLANE_FIX = 'uploads outside storebound skip its checks and overwrite its listing: run `storebound import fastlane` (MCP import_fastlane), then replace the call with the storebound command (play upload / apple upload) (pitfall 96)'; + +export const traceLine = (t: FastlaneTrace): string => `fastlane in ${t.file}:${t.line}${t.text ? `: ${t.text}` : ''}`; diff --git a/cli/lib/scan/index.ts b/cli/lib/scan/index.ts index 5b88cff..c692d81 100644 --- a/cli/lib/scan/index.ts +++ b/cli/lib/scan/index.ts @@ -10,6 +10,7 @@ import { AI_FIX_RULES, scanFixAction } from '../fix-actions'; import { proposeDeclarations, type Proposal } from './declare'; import { detectProject, ECO_LABEL, type ProjectFacts, type Stack, where } from './project'; import type { OriginalityReport } from '../originality'; +import { FASTLANE_FIX, findFastlaneTraces } from '../fastlane-traces'; import { APPLE_GUIDELINES, applyIgnore, type ScanFinding, scanRules, type Severity, sortScan, unusedIgnores } from './rules'; import type { SdkCategory } from './sdks'; @@ -73,6 +74,15 @@ export async function runScan(dir: string, o: { config?: string } = {}): Promise fix: g.fix ?? '', skill: 'game-services', ref: 'https://developer.android.com/games/pgs/android/android-start' }); } catch { /* unreadable Android project */ } } + // fastlane still uploading next to storebound (pitfall 96) + const traces = findFastlaneTraces(dir); + for (const store of ['apple', 'play'] as const) { + if (config && !config[store]) continue; + const ev = traces.filter(t => t.store === store || t.store === 'both'); + if (ev.length && !(config?.scan?.ignore ?? []).some(i => i.rule === 'fastlane-upload')) + findings.push({ rule: 'fastlane-upload', guideline: 'storebound workflow', store, severity: 'medium', title: `fastlane still in the project (${ev.length} place${ev.length > 1 ? 's' : ''}); uploads there bypass storebound`, + evidence: ev.map(t => ({ file: t.file, line: t.line, text: t.text })), fix: FASTLANE_FIX, skill: 'migrate-from-fastlane', ref: 'https://git.crt.fyi/CRT/storebound/src/branch/main/skills/migrate-from-fastlane/SKILL.md' }); + } for (const f of findings) { const action = f.accepted ? undefined : scanFixAction(f.rule, { configPath, declarationsChanged: declarations.changed }); if (action) f.action = action; diff --git a/cli/release.ts b/cli/release.ts index dfaf404..c31ef2f 100644 --- a/cli/release.ts +++ b/cli/release.ts @@ -21,6 +21,7 @@ import { laneOf, laneText, type PlanStep, releasePlan, type ReleasePlan, sameVer import type { Finding } from './lib/validate-rules'; import { findWorkspace, loadWorkspace, resolveApps, selectApps } from './lib/workspace'; import { appDir, appEnv, workspaceApps } from './workspace'; +import { FASTLANE_FIX, findFastlaneTraces, traceLine } from './lib/fastlane-traces'; interface Target { name: string; dir: string; virtual: boolean; env: Record; problems: string[] } @@ -94,7 +95,7 @@ async function status(args: Args): Promise { const read = await pool(list, concurrency, async t => ({ t, s: await readLive(t) })); if (args.has('json')) { printJson({ apps: read.map(({ t, s }) => ({ - app: t.name, folder: t.virtual ? null : t.dir, errors: [...t.problems, ...s.errors], warnings: s.warnings ?? [], storeErrors: s.storeErrors, + app: t.name, folder: t.virtual ? null : t.dir, errors: [...t.problems, ...s.errors], warnings: [...(s.warnings ?? []), ...(t.virtual ? [] : findFastlaneTraces(t.dir).map(f => `${traceLine(f)} · ${FASTLANE_FIX}`))], storeErrors: s.storeErrors, trains: trainsOf(s, all).map(({ which, train }) => ({ which, version: train.version, ios: train.ios, android: train.android, lanes: { ios: laneOf('ios', train.ios), android: laneOf('android', train.android) } })), })), at: new Date().toISOString() }); @@ -106,6 +107,7 @@ async function status(args: Args): Promise { if (!trains.length) rows.push([t.name, '', '', s.errors[0] ? `error: ${s.errors[0]}` : unread ? 'not read (see the warnings)' : 'no version on either store yet', '']); for (const { which, train } of trains) rows.push([t.name, train.version, which === 'other' ? '' : which, cell('ios', train, s), cell('android', train, s)]); for (const w of s.warnings ?? []) warn('release', `${t.name}: ${w}`); + if (!t.virtual) for (const f of findFastlaneTraces(t.dir)) warn('release', `${t.name}: ${traceLine(f)} · ${FASTLANE_FIX}`); for (const p of [...t.problems, ...s.errors.slice(trains.length ? 0 : 1), ...Object.entries(s.storeErrors).map(([k, v]) => `${k}: ${v}`)]) warn('release', `${t.name}: ${p}`); } console.log(textTable(['app', 'version', 'train', 'App Store', 'Google Play'], rows)); diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 68af0d1..322ab96 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1166,3 +1166,14 @@ that fails without the fix (see CONTRIBUTING.md). - **Do:** run the command again later; after a release, warm the CDN cache by fetching every installer once. - **Guard:** `download` in `cli/desktop.ts` reads in chunks, prints progress every 10 % and fails after 60 s without data (`tests/desktop-dist.test.ts`). + +## 96. A project still uploaded with fastlane and storebound never said so +- **Symptom:** the Play listing or build changed behind storebound's back; CI ran `fastlane supply` (or `deliver` / + `pilot`) next to the storebound config, and `check`, `scan` and `release status` were all quiet. +- **Cause:** storebound looked only at its own config; fastlane files and CI upload calls were never read. +- **Do:** run `storebound import fastlane` (MCP `import_fastlane`) to bring the metadata over, then replace each + upload call with the storebound command and remove the lane. Keep a lane only on purpose (`scan.ignore` + `fastlane-upload` with the reason). +- **Guard:** `findFastlaneTraces` in `cli/lib/fastlane-traces.ts` (Fastfile / Appfile, CI files and scripts with + `fastlane supply|deliver|pilot`); `check` warns, `scan` reports `fastlane-upload` with file:line, `release status` + warns per app (`tests/fastlane-traces.test.ts`). diff --git a/tests/fastlane-traces.test.ts b/tests/fastlane-traces.test.ts new file mode 100644 index 0000000..c0e30e9 --- /dev/null +++ b/tests/fastlane-traces.test.ts @@ -0,0 +1,43 @@ +// fastlane left in a project (Fastfile, CI calls to supply / deliver / pilot) is found and named (pitfall 96). +import { describe, expect, test } from 'bun:test'; +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { findFastlaneTraces, traceLine } from '../cli/lib/fastlane-traces'; +import { runScan } from '../cli/lib/scan'; + +function project(files: Record): string { + const dir = mkdtempSync(join(tmpdir(), 'sb-fl-')); + for (const [p, text] of Object.entries(files)) { mkdirSync(join(dir, p, '..'), { recursive: true }); writeFileSync(join(dir, p), text); } + return dir; +} + +describe('fastlane traces', () => { + test('Fastfile actions, Appfile, and CI / script calls with file:line', () => { + const dir = project({ + 'android/fastlane/Fastfile': 'lane :ship do\n # supply in a comment is not a call\n supply(track: "internal")\nend\n', + 'fastlane/Appfile': 'app_identifier("com.example.game")\n', + 'Jenkinsfile': 'stage("upload") {\n sh "bundle exec fastlane supply --aab app.aab"\n}\n', + '.github/workflows/ios.yml': 'steps:\n - run: fastlane pilot upload\n', + 'scripts/release.sh': 'echo fastlane is fine to mention\n', + }); + const t = findFastlaneTraces(dir); + expect(t).toContainEqual({ file: 'android/fastlane/Fastfile', line: 3, text: 'supply(track: "internal")', store: 'play' }); + expect(t).toContainEqual({ file: 'fastlane/Appfile', line: 1, text: 'app_identifier("com.example.game")', store: 'both' }); + expect(t).toContainEqual({ file: 'Jenkinsfile', line: 2, text: 'sh "bundle exec fastlane supply --aab app.aab"', store: 'play' }); + expect(t).toContainEqual({ file: '.github/workflows/ios.yml', line: 2, text: '- run: fastlane pilot upload', store: 'apple' }); + expect(t.some(x => x.file === 'scripts/release.sh')).toBe(false); + expect(t.filter(x => x.file === 'android/fastlane/Fastfile')).toHaveLength(1); + expect(traceLine(t.find(x => x.file === 'Jenkinsfile')!)).toBe('fastlane in Jenkinsfile:2: sh "bundle exec fastlane supply --aab app.aab"'); + }); + test('a project without fastlane has no traces', () => { + expect(findFastlaneTraces(project({ 'package.json': '{"scripts":{"build":"vite build"}}' }))).toEqual([]); + }); + test('scan reports fastlane-upload with the evidence lines', async () => { + const dir = project({ 'Jenkinsfile': 'sh "fastlane supply"\n' }); + const { report } = await runScan(dir, {}); + const f = report.findings.find(x => x.rule === 'fastlane-upload' && x.store === 'play'); + expect(f?.evidence[0]).toMatchObject({ file: 'Jenkinsfile', line: 1 }); + expect(f?.fix).toContain('storebound import fastlane'); + }); +}); From 62eb010998e173c15b3c58d5fade0fa76f70cf1e Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 00:59:03 +0700 Subject: [PATCH 089/344] storebound 0.8.25: version in package.json and every copy, CHANGELOG 0.8.25 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index b8dfe47..40ac3a9 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.24", + "version": "0.8.25", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 39866c9..6e1a9e5 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.24", + "version": "0.8.25", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 841c6ac..6821e9c 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.24", + "version": "0.8.25", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index e306175..1ae1e16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.25 · 2026-10-21 + - **fastlane left in a project is named.** `check` and `release status` warn and `scan` reports `fastlane-upload` when a Fastfile / Appfile or a CI file or script still runs `fastlane supply`, `deliver` or `pilot`, with the file:line and the way over (`storebound import fastlane`). Pitfall 96. diff --git a/apps/desktop/package.json b/apps/desktop/package.json index d1be11a..72b47c9 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.24", + "version": "0.8.25", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index ec08b77..368d239 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4010,7 +4010,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.24" +version = "0.8.25" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index f81a7e5..e1f9e34 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.24" +version = "0.8.25" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 122f7ad..1ff5db7 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.24", + "version": "0.8.25", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index a6f0276..9571d0f 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.24", + "version": "0.8.25", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index b327a24..e5f365b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.24", + "version": "0.8.25", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From 4fcee60ba66f4fa43bc82c9e7666e410d3092ab3 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 02:04:28 +0800 Subject: [PATCH 090/344] Direct store API calls in a project's scripts: androidpublisher.googleapis.com, the googleapis androidpublisher client, api.appstoreconnect.apple.com, altool / Transporter in CI files and scripts; scan rule direct-store-api, check and release status warnings with file:line and the storebound command; storebound's own checkout skipped; test, pitfall 97 --- CHANGELOG.md | 4 ++++ cli/check.ts | 4 ++-- cli/lib/fastlane-traces.ts | 29 ++++++++++++++++++++++++++--- cli/lib/scan/index.ts | 10 +++++++++- cli/release.ts | 6 +++--- skills/store-pitfalls/SKILL.md | 12 ++++++++++++ tests/fastlane-traces.test.ts | 17 ++++++++++++++++- 7 files changed, 72 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e306175..9d0b8bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- **Scripts that call the store APIs themselves are named.** `androidpublisher.googleapis.com`, the googleapis + androidpublisher client, `api.appstoreconnect.apple.com`, altool and Transporter in CI files and scripts: `check` and + `release status` warn, `scan` reports `direct-store-api`, each with file:line and the storebound command. Pitfall 97. + - **fastlane left in a project is named.** `check` and `release status` warn and `scan` reports `fastlane-upload` when a Fastfile / Appfile or a CI file or script still runs `fastlane supply`, `deliver` or `pilot`, with the file:line and the way over (`storebound import fastlane`). Pitfall 96. diff --git a/cli/check.ts b/cli/check.ts index 9147c00..2e2ebd0 100644 --- a/cli/check.ts +++ b/cli/check.ts @@ -34,7 +34,7 @@ import { creativeNote } from './shots/creative'; import { type CapProject, capacitorProject, prebuildFor, staleMessage, webState } from './lib/web-assets'; import { iphoneDuoNote } from './shots/spec'; import { hitLine } from './lib/cross-store'; -import { FASTLANE_FIX, findFastlaneTraces, traceLine } from './lib/fastlane-traces'; +import { findFastlaneTraces, traceMessage } from './lib/fastlane-traces'; import { listingFileMentions } from './lib/listing-mentions'; /** The newest .ipa in a folder (apple build's export), or null. */ @@ -97,7 +97,7 @@ export async function run(ctx: Ctx): Promise { return `${Object.keys(copy).length} locales`; }); // fastlane uploads left next to storebound (pitfall 96) - try { const tr = findFastlaneTraces(dirname(path)); if (tr.length) for (const t of tr) note(`${traceLine(t)} · ${FASTLANE_FIX}`); } catch (e) { warn('check', `fastlane traces: ${(e as Error).message}`); } + try { const tr = findFastlaneTraces(dirname(path)); if (tr.length) for (const t of tr) note(traceMessage(t)); } catch (e) { warn('check', `fastlane traces: ${(e as Error).message}`); } // other platforms named in a store's text: App Store 2.3.10 / Play Metadata, a blocker (pitfall 77) try { for (const h of listingFileMentions(ctx.loaded)) problems.push(`other platform in ${hitLine(h)}`); } catch (e) { warn('check', `platform mentions: ${(e as Error).message}`); } // listing translation drafts (storebound listing translate): fine to keep working on, not to push unreviewed diff --git a/cli/lib/fastlane-traces.ts b/cli/lib/fastlane-traces.ts index 0a666ba..ddc0668 100644 --- a/cli/lib/fastlane-traces.ts +++ b/cli/lib/fastlane-traces.ts @@ -10,16 +10,30 @@ export interface FastlaneTrace { text: string; /** play (supply, upload_to_play_store), apple (deliver, pilot, upload_to_app_store / testflight) or both (a file). */ store: 'apple' | 'play' | 'both'; + /** fastlane, or a script that calls a store API / upload tool itself (no fastlane, same bypass). */ + via?: 'api'; + /** The storebound command that replaces it (api traces). */ + fix?: string; } +/** Store APIs and upload tools called by a project's own scripts: each with its storebound replacement. */ +const DIRECT: { re: RegExp; store: 'apple' | 'play'; what: string; fix: string }[] = [ + { re: /androidpublisher\.googleapis\.com|\bandroidpublisher\s*\(|google\.androidpublisher|['"]androidpublisher['"]/, store: 'play', what: 'Google Play Developer API called directly', + fix: 'use storebound: play upload / play release (MCP play_release_testing), play images (play_images), play listing pull (play_listing_pull) (pitfall 97)' }, + { re: /api\.appstoreconnect\.apple\.com/, store: 'apple', what: 'App Store Connect API called directly', + fix: 'use storebound: apple upload / apple submit / apple listing / apple screenshots (MCP apple_* tools) (pitfall 97)' }, + { re: /\baltool\b|iTMSTransporter|\bTransporter\b/, store: 'apple', what: 'altool / Transporter upload', + fix: 'use storebound apple upload (MCP apple_upload) (pitfall 97)' }, +]; + const UPLOAD = /\b(supply|upload_to_play_store|deliver|upload_to_app_store|pilot|upload_to_testflight)\b/; /** A fastlane command line in CI / scripts: `fastlane supply`, `bundle exec fastlane run deliver`, `fastlane pilot upload`. */ const CLI_CALL = /\bfastlane\s+(?:run\s+)?(supply|upload_to_play_store|deliver|upload_to_app_store|pilot|upload_to_testflight)\b/; const PLAY = new Set(['supply', 'upload_to_play_store']); const FASTLANE_DIRS = ['', 'ios', 'android', 'ios/App', 'android/app']; const CI_FILES = ['Jenkinsfile', '.gitlab-ci.yml', 'bitrise.yml', 'codemagic.yaml', 'azure-pipelines.yml', 'Makefile', 'package.json', 'appcenter-post-build.sh']; -const CI_DIRS = ['.github/workflows', '.forgejo/workflows', '.gitea/workflows', '.circleci', 'scripts', 'ci', '.ci', 'tools']; -const SCRIPT_EXT = /\.(ya?ml|sh|bash|zsh|ps1|groovy|rb|mjs|js|ts|json)$/i; +const CI_DIRS = ['.github/workflows', '.forgejo/workflows', '.gitea/workflows', '.circleci', 'scripts', 'ci', '.ci', 'tools', 'bin', 'deploy', 'release', 'ops']; +const SCRIPT_EXT = /\.(ya?ml|sh|bash|zsh|ps1|groovy|rb|py|mjs|cjs|js|ts|json)$/i; const storeOf = (m: string): 'apple' | 'play' => (PLAY.has(m) ? 'play' : 'apple'); @@ -29,6 +43,8 @@ function lines(file: string): string[] { export function findFastlaneTraces(root: string): FastlaneTrace[] { const out: FastlaneTrace[] = []; + // storebound's own checkout calls the store APIs by design + try { if ((JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name?: string }).name === 'storebound') return out; } catch { /* no package.json */ } const rel = (p: string) => relative(root, p).split(sep).join('/'); const seen = new Set(); // Fastfile / Appfile (in fastlane/ or next to it): the file itself, plus each upload action it calls @@ -56,6 +72,10 @@ export function findFastlaneTraces(root: string): FastlaneTrace[] { lines(f).forEach((l, i) => { const m = CLI_CALL.exec(l); if (m) out.push({ file: rel(f), line: i + 1, text: l.trim().slice(0, 200), store: storeOf(m[1]!) }); + else if (!/package\.json$/.test(f) || /"[^"]*"\s*:\s*"/.test(l)) { + const d = DIRECT.find(x => x.re.test(l)); + if (d) out.push({ file: rel(f), line: i + 1, text: l.trim().slice(0, 200), store: d.store, via: 'api', fix: d.fix }); + } }); } return out; @@ -63,4 +83,7 @@ export function findFastlaneTraces(root: string): FastlaneTrace[] { export const FASTLANE_FIX = 'uploads outside storebound skip its checks and overwrite its listing: run `storebound import fastlane` (MCP import_fastlane), then replace the call with the storebound command (play upload / apple upload) (pitfall 96)'; -export const traceLine = (t: FastlaneTrace): string => `fastlane in ${t.file}:${t.line}${t.text ? `: ${t.text}` : ''}`; +export const traceLine = (t: FastlaneTrace): string => `${t.via === 'api' ? `${DIRECT.find(d => d.fix === t.fix)?.what ?? 'store API called directly'} in` : 'fastlane in'} ${t.file}:${t.line}${t.text ? `: ${t.text}` : ''}`; + +/** The warning for one trace: where, and the storebound way. */ +export const traceMessage = (t: FastlaneTrace): string => `${traceLine(t)} · ${t.fix ?? FASTLANE_FIX}`; diff --git a/cli/lib/scan/index.ts b/cli/lib/scan/index.ts index c692d81..81e3680 100644 --- a/cli/lib/scan/index.ts +++ b/cli/lib/scan/index.ts @@ -78,11 +78,19 @@ export async function runScan(dir: string, o: { config?: string } = {}): Promise const traces = findFastlaneTraces(dir); for (const store of ['apple', 'play'] as const) { if (config && !config[store]) continue; - const ev = traces.filter(t => t.store === store || t.store === 'both'); + const ev = traces.filter(t => !t.via && (t.store === store || t.store === 'both')); if (ev.length && !(config?.scan?.ignore ?? []).some(i => i.rule === 'fastlane-upload')) findings.push({ rule: 'fastlane-upload', guideline: 'storebound workflow', store, severity: 'medium', title: `fastlane still in the project (${ev.length} place${ev.length > 1 ? 's' : ''}); uploads there bypass storebound`, evidence: ev.map(t => ({ file: t.file, line: t.line, text: t.text })), fix: FASTLANE_FIX, skill: 'migrate-from-fastlane', ref: 'https://git.crt.fyi/CRT/storebound/src/branch/main/skills/migrate-from-fastlane/SKILL.md' }); } + // the project's own scripts call a store API or upload tool (pitfall 97) + for (const store of ['apple', 'play'] as const) { + if (config && !config[store]) continue; + const ev = traces.filter(t => t.via === 'api' && t.store === store); + if (ev.length && !(config?.scan?.ignore ?? []).some(i => i.rule === 'direct-store-api')) + findings.push({ rule: 'direct-store-api', guideline: 'storebound workflow', store, severity: 'medium', title: `scripts call the ${store === 'play' ? 'Google Play' : 'App Store Connect'} API or an upload tool directly (${ev.length} place${ev.length > 1 ? 's' : ''}); they bypass storebound`, + evidence: ev.map(t => ({ file: t.file, line: t.line, text: t.text })), fix: ev[0]!.fix!, skill: 'store-api', ref: 'https://git.crt.fyi/CRT/storebound/src/branch/main/skills/store-api/SKILL.md' }); + } for (const f of findings) { const action = f.accepted ? undefined : scanFixAction(f.rule, { configPath, declarationsChanged: declarations.changed }); if (action) f.action = action; diff --git a/cli/release.ts b/cli/release.ts index c31ef2f..fc217c1 100644 --- a/cli/release.ts +++ b/cli/release.ts @@ -21,7 +21,7 @@ import { laneOf, laneText, type PlanStep, releasePlan, type ReleasePlan, sameVer import type { Finding } from './lib/validate-rules'; import { findWorkspace, loadWorkspace, resolveApps, selectApps } from './lib/workspace'; import { appDir, appEnv, workspaceApps } from './workspace'; -import { FASTLANE_FIX, findFastlaneTraces, traceLine } from './lib/fastlane-traces'; +import { findFastlaneTraces, traceMessage } from './lib/fastlane-traces'; interface Target { name: string; dir: string; virtual: boolean; env: Record; problems: string[] } @@ -95,7 +95,7 @@ async function status(args: Args): Promise { const read = await pool(list, concurrency, async t => ({ t, s: await readLive(t) })); if (args.has('json')) { printJson({ apps: read.map(({ t, s }) => ({ - app: t.name, folder: t.virtual ? null : t.dir, errors: [...t.problems, ...s.errors], warnings: [...(s.warnings ?? []), ...(t.virtual ? [] : findFastlaneTraces(t.dir).map(f => `${traceLine(f)} · ${FASTLANE_FIX}`))], storeErrors: s.storeErrors, + app: t.name, folder: t.virtual ? null : t.dir, errors: [...t.problems, ...s.errors], warnings: [...(s.warnings ?? []), ...(t.virtual ? [] : findFastlaneTraces(t.dir).map(traceMessage))], storeErrors: s.storeErrors, trains: trainsOf(s, all).map(({ which, train }) => ({ which, version: train.version, ios: train.ios, android: train.android, lanes: { ios: laneOf('ios', train.ios), android: laneOf('android', train.android) } })), })), at: new Date().toISOString() }); @@ -107,7 +107,7 @@ async function status(args: Args): Promise { if (!trains.length) rows.push([t.name, '', '', s.errors[0] ? `error: ${s.errors[0]}` : unread ? 'not read (see the warnings)' : 'no version on either store yet', '']); for (const { which, train } of trains) rows.push([t.name, train.version, which === 'other' ? '' : which, cell('ios', train, s), cell('android', train, s)]); for (const w of s.warnings ?? []) warn('release', `${t.name}: ${w}`); - if (!t.virtual) for (const f of findFastlaneTraces(t.dir)) warn('release', `${t.name}: ${traceLine(f)} · ${FASTLANE_FIX}`); + if (!t.virtual) for (const f of findFastlaneTraces(t.dir)) warn('release', `${t.name}: ${traceMessage(f)}`); for (const p of [...t.problems, ...s.errors.slice(trains.length ? 0 : 1), ...Object.entries(s.storeErrors).map(([k, v]) => `${k}: ${v}`)]) warn('release', `${t.name}: ${p}`); } console.log(textTable(['app', 'version', 'train', 'App Store', 'Google Play'], rows)); diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 322ab96..3e3eb02 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1177,3 +1177,15 @@ that fails without the fix (see CONTRIBUTING.md). - **Guard:** `findFastlaneTraces` in `cli/lib/fastlane-traces.ts` (Fastfile / Appfile, CI files and scripts with `fastlane supply|deliver|pilot`); `check` warns, `scan` reports `fastlane-upload` with file:line, `release status` warns per app (`tests/fastlane-traces.test.ts`). + +## 97. The project's own scripts called the store APIs (no fastlane, same bypass) +- **Symptom:** an app uploaded AABs, set the track and rollout, pushed listing images and read the listing back with + three hand-written scripts (a self-signed JWT against `androidpublisher.googleapis.com`); storebound said nothing. +- **Cause:** pitfall 96 looked only for fastlane; direct API calls and upload tools (altool, Transporter) were not read. +- **Do:** replace each script with the storebound command: `play upload` / `play release` (MCP `play_release_testing`), + `play images` (`play_images`), `play listing pull` (`play_listing_pull`); for Apple `apple upload` and the other + `apple` commands (MCP `apple_*`). Keep one on purpose only with `scan.ignore` `direct-store-api` and the reason. +- **Guard:** `findFastlaneTraces` in `cli/lib/fastlane-traces.ts` also reports `androidpublisher.googleapis.com`, the + googleapis androidpublisher client, `api.appstoreconnect.apple.com`, `altool` / `iTMSTransporter` in CI files and + scripts (not storebound's own checkout, never node_modules); `scan` rule `direct-store-api`, `check` and + `release status` warnings with file:line and the storebound command (`tests/fastlane-traces.test.ts`). diff --git a/tests/fastlane-traces.test.ts b/tests/fastlane-traces.test.ts index c0e30e9..5b7a4df 100644 --- a/tests/fastlane-traces.test.ts +++ b/tests/fastlane-traces.test.ts @@ -3,7 +3,7 @@ import { describe, expect, test } from 'bun:test'; import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { findFastlaneTraces, traceLine } from '../cli/lib/fastlane-traces'; +import { findFastlaneTraces, traceLine, traceMessage } from '../cli/lib/fastlane-traces'; import { runScan } from '../cli/lib/scan'; function project(files: Record): string { @@ -30,6 +30,21 @@ describe('fastlane traces', () => { expect(t.filter(x => x.file === 'android/fastlane/Fastfile')).toHaveLength(1); expect(traceLine(t.find(x => x.file === 'Jenkinsfile')!)).toBe('fastlane in Jenkinsfile:2: sh "bundle exec fastlane supply --aab app.aab"'); }); + test('scripts that call the store APIs or upload tools themselves, with the storebound way', () => { + const dir = project({ + 'scripts/play-upload.mjs': "const url = 'https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/com.example.app/edits';\n", + 'tools/asc.py': "BASE = 'https://api.appstoreconnect.apple.com/v1'\n", + 'deploy/ios.sh': 'xcrun altool --upload-app -f app.ipa\n', + 'package.json': '{"name":"an-app","scripts":{"ship":"node scripts/play-upload.mjs"}}', + }); + const t = findFastlaneTraces(dir); + expect(t.map(x => `${x.file} ${x.store} ${x.via}`).sort()).toEqual(['deploy/ios.sh apple api', 'scripts/play-upload.mjs play api', 'tools/asc.py apple api']); + expect(traceMessage(t.find(x => x.store === 'play')!)).toContain('play_release_testing'); + expect(traceMessage(t.find(x => x.file === 'deploy/ios.sh')!)).toStartWith('altool / Transporter upload in deploy/ios.sh:1'); + }); + test("storebound's own checkout is not reported", () => { + expect(findFastlaneTraces(project({ 'package.json': '{"name":"storebound"}', 'scripts/x.ts': "fetch('https://api.appstoreconnect.apple.com/v1/apps')\n" }))).toEqual([]); + }); test('a project without fastlane has no traces', () => { expect(findFastlaneTraces(project({ 'package.json': '{"scripts":{"build":"vite build"}}' }))).toEqual([]); }); From 73d308164d2adb2658d9555964997570a643cbb7 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 02:10:52 +0800 Subject: [PATCH 091/344] Windows builds and moved credentials: play build runs gradlew.bat through cmd /c and takes C:/ keystore paths as absolute (pitfall 98); check names credential paths missing on this machine and a keystore the stored password / alias do not open (keytool) (pitfall 99); play / apple build write /latest.json for CI; CI install from a git clone documented --- CHANGELOG.md | 6 ++++++ cli/apple/build.ts | 2 ++ cli/check.ts | 4 +++- cli/lib/credentials.ts | 33 ++++++++++++++++++++++++++++++++- cli/lib/gradle.ts | 7 ++++--- cli/play/build.ts | 4 +++- docs/getting-started.md | 6 ++++++ skills/store-pitfalls/SKILL.md | 20 ++++++++++++++++++++ tests/build-sign.test.ts | 22 +++++++++++++++++++--- 9 files changed, 95 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d0b8bb..bb958cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- **Windows builds.** `play build` runs `gradlew.bat` through `cmd /c` (it was looked up on PATH only) and takes + `C:/...` keystore paths as absolute. Pitfall 98. +- **`check` verifies credential files.** Every credential path that does not exist on this machine and an upload keystore + the stored password / alias do not open (keytool) are named by field. Pitfall 99. +- `play build` / `apple build` write `/latest.json` with the AAB / IPA path for CI; CI install from a git clone documented. + - **Scripts that call the store APIs themselves are named.** `androidpublisher.googleapis.com`, the googleapis androidpublisher client, `api.appstoreconnect.apple.com`, altool and Transporter in CI files and scripts: `check` and `release status` warn, `scan` reports `direct-store-api`, each with file:line and the storebound command. Pitfall 97. diff --git a/cli/apple/build.ts b/cli/apple/build.ts index 62c5db4..dcb71dc 100644 --- a/cli/apple/build.ts +++ b/cli/apple/build.ts @@ -190,6 +190,8 @@ export async function run(ctx: Ctx): Promise { const privacy = bundleTrackingIssues(ipaManifests(join(exportPath, ipa))); if (privacy.length) throw new Error(`${relative(root, join(exportPath, ipa))} was built, but Apple would refuse it at upload:\n${privacy.map(x => ` ${x}`).join('\n')}\nFix the manifest and build again.`); const result = { ipa: join(exportPath, ipa), bundleId: info.bundleId, version: info.version, build: info.build, web: web.bundle }; + writeFileSync(join(out, 'latest.json'), `${JSON.stringify(result, null, 2)} +`); if (json) printJson(result); done(TAG, `${relative(root, result.ipa)}: ${info.bundleId} ${info.version} (${info.build}). Next: storebound apple upload ${relative(root, result.ipa)} --dry`); } diff --git a/cli/check.ts b/cli/check.ts index 2e2ebd0..df40330 100644 --- a/cli/check.ts +++ b/cli/check.ts @@ -21,7 +21,7 @@ import { playConsoleReminders } from './lib/console-plan'; import { APPLE_IAP_LIMITS, appleNameIssues, len, parseAppStoreListing, parsePlayListing } from './lib/copy'; import type { Ctx } from './lib/ctx'; import { dataSafetyIssues, dataSafetyRows } from './lib/data-safety'; -import { credentialStatus, reviewDemoAccount } from './lib/credentials'; +import { credentialFileIssues, credentialStatus, reviewDemoAccount } from './lib/credentials'; import { log, printJson, warn } from './lib/log'; import { profileIssues } from './lib/profile'; import { detectProject, grepOwn, where } from './lib/scan/project'; @@ -150,6 +150,8 @@ export async function run(ctx: Ctx): Promise { // template placeholders in the credentials ("YOUR_KEY_ID", "/absolute/path/to/...", "<...>"): missing, never a credential const ph = credentialStatus(ctx.loaded.root).filter(c => c.status === 'placeholder').map(c => c.key); if (ph.length) note(`credentials: ${ph.join(', ')} still hold template placeholders (env or .storebound/credentials.json): treated as missing; put the real value in or leave it empty`); + // credential files that are not on this machine, an upload keystore the stored password / alias do not open + try { for (const i of credentialFileIssues(ctx.loaded.root)) problems.push(`credentials: ${i}`); } catch (e) { warn('check', `credential files: ${(e as Error).message}`); } // scan.ignore entries that accept no finding (a typo, a title that changed, a fixed issue) are never silent if (config.scan?.ignore?.length) { const { runScan } = await import('./lib/scan'); diff --git a/cli/lib/credentials.ts b/cli/lib/credentials.ts index 34c890c..3b36e9d 100644 --- a/cli/lib/credentials.ts +++ b/cli/lib/credentials.ts @@ -26,6 +26,7 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { homedir, tmpdir } from 'node:os'; import { isAbsolute, join, resolve } from 'node:path'; +import * as rt from './rt'; export interface ServiceAccount { client_email: string; private_key: string; token_uri?: string } export interface AscKey { keyId: string; issuerId: string; pem: string } @@ -324,7 +325,7 @@ export function androidSigning(root: string): AndroidSigning | null { const storePassword = value(root, 'ANDROID_KEYSTORE_PASSWORD'), keyAlias = value(root, 'ANDROID_KEY_ALIAS'); if (!storePassword || !keyAlias) throw new Error('ANDROID_KEYSTORE is set but ANDROID_KEYSTORE_PASSWORD / ANDROID_KEY_ALIAS are not (env or .storebound/credentials.json)'); const abs = storeFile.replace(/^~(?=\/)/, homedir()); - return { storeFile: abs.startsWith('/') ? abs : join(root, abs), storePassword, keyAlias, keyPassword: value(root, 'ANDROID_KEY_PASSWORD') ?? storePassword }; + return { storeFile: isAbsolute(abs) ? abs : join(root, abs), storePassword, keyAlias, keyPassword: value(root, 'ANDROID_KEY_PASSWORD') ?? storePassword }; } /** App Store Connect vendor number for sales and finance reports (Payments and Financial Reports, top left): the @@ -334,3 +335,33 @@ export function ascVendorNumber(root: string): string | null { const v = value(root, 'ASC_VENDOR_NUMBER'); return v && /^\d{5,12}$/.test(v.trim()) ? v.trim() : null; } + +/** Credential paths that do not exist (a machine move left another computer's absolute paths) and an upload keystore + * the stored password / alias do not open: each names the field. `keytool` runs only when it is on PATH. */ +export function credentialFileIssues(root: string, run: (argv: string[]) => { ok: boolean; out: string } | null = keytool): string[] { + const issues: string[] = []; + const asPath = (v: string) => { const p = v.replace(/^~(?=[/\\])/, homedir()); return isAbsolute(p) ? p : join(root, p); }; + for (const k of ['PLAY_SERVICE_ACCOUNT', 'ASC_P8', 'ANDROID_KEYSTORE'] as const) { + let v: string | undefined; + try { v = value(root, k); } catch { continue; } + if (!v || /^\s*\{/.test(v) || /BEGIN [A-Z ]*PRIVATE KEY/.test(v)) continue; + if (!existsSync(asPath(v))) issues.push(`${k}: ${v} does not exist on this machine (moved from another computer?): point it at the file here`); + } + let s: AndroidSigning | null = null; + try { s = androidSigning(root); } catch (e) { issues.push((e as Error).message); } + if (s && existsSync(s.storeFile)) { + const r = run(['-list', '-keystore', s.storeFile, '-storepass', s.storePassword, '-alias', s.keyAlias]); + if (r && !r.ok) issues.push(/password|tampered|Keystore was tampered/i.test(r.out) + ? 'ANDROID_KEYSTORE_PASSWORD does not open the upload keystore (keytool -list failed): check the password (android/keystore.properties may hold the right one)' + : /alias|does not exist/i.test(r.out) ? `ANDROID_KEY_ALIAS "${s.keyAlias}" is not in the upload keystore` : `the upload keystore does not open with the stored password / alias: ${r.out.trim().split('\n')[0]}`); + } + return issues; +} + +function keytool(argv: string[]): { ok: boolean; out: string } | null { + const bin = process.env.JAVA_HOME ? join(process.env.JAVA_HOME, 'bin', process.platform === 'win32' ? 'keytool.exe' : 'keytool') : 'keytool'; + try { + const r = rt.spawnSync([bin, ...argv], { timeout: 20_000 }); + return { ok: r.success, out: `${r.stdout.toString()}${r.stderr.toString()}` }; + } catch { return null; } +} diff --git a/cli/lib/gradle.ts b/cli/lib/gradle.ts index 7ecfc8c..ddafbce 100644 --- a/cli/lib/gradle.ts +++ b/cli/lib/gradle.ts @@ -48,7 +48,7 @@ export function pickGradle(root: string, cfg: PlayBuildConfig = {}): GradleTarge if (fw === 'capacitor') notes.push('Capacitor: run npx cap sync android after the web build so the bundle has the current web assets'); if (fw === 'unity') notes.push('Unity: export the Gradle project from Unity (Build Settings > Android > Export Project) before each build'); if (fw === 'flutter') notes.push('Flutter: built with flutter build appbundle (build number = versionCode)'); - if (!existsSync(join(dir, process.platform === 'win32' ? 'gradlew.bat' : 'gradlew'))) notes.push('no Gradle wrapper (gradlew) in the project: using gradle from PATH'); + if (!existsSync(join(dir, 'gradlew')) && !existsSync(join(dir, 'gradlew.bat'))) notes.push('no Gradle wrapper (gradlew) in the project: using gradle from PATH'); return { framework: fw, dir, module, task: `:${module}:bundle${flavor}Release`, notes }; } @@ -57,10 +57,11 @@ export function pickGradle(root: string, cfg: PlayBuildConfig = {}): GradleTarge * override defaultConfig for bundleRelease: checked with AGP 8.13 (2026-10-12), `-Pandroid.injected.version.code=42` * on a build file with `versionCode 1` gives an AAB with versionCode 1; seen live the same day with a Capacitor app. * They stay on the command line for older plugins / IDE parity only; the AAB check after the build is the stop. */ -export function gradleArgs(t: GradleTarget, o: { versionCode?: number; versionName?: string; flavor?: string; hasWrapper: boolean }): string[] { +export function gradleArgs(t: GradleTarget, o: { versionCode?: number; versionName?: string; flavor?: string; hasWrapper: boolean }, platform: string = process.platform): string[] { if (t.framework === 'flutter') return ['flutter', 'build', 'appbundle', '--release', ...(o.flavor ? ['--flavor', o.flavor] : []), ...(o.versionCode ? ['--build-number', String(o.versionCode)] : []), ...(o.versionName ? ['--build-name', o.versionName] : [])]; - return [o.hasWrapper ? (process.platform === 'win32' ? 'gradlew.bat' : './gradlew') : 'gradle', t.task, '--no-daemon', '--console=plain', + // Windows: a bare `gradlew.bat` is searched on PATH only ("Executable not found in $PATH"); cmd /c finds it in the cwd + return [...(o.hasWrapper ? (platform === 'win32' ? ['cmd', '/c', 'gradlew.bat'] : ['./gradlew']) : platform === 'win32' ? ['cmd', '/c', 'gradle'] : ['gradle']), t.task, '--no-daemon', '--console=plain', ...(o.versionCode ? [`-Pandroid.injected.version.code=${o.versionCode}`, `-PversionCode=${o.versionCode}`] : []), ...(o.versionName ? [`-Pandroid.injected.version.name=${o.versionName}`, `-PversionName=${o.versionName}`] : [])]; } diff --git a/cli/play/build.ts b/cli/play/build.ts index a6a8ba5..91d12c9 100644 --- a/cli/play/build.ts +++ b/cli/play/build.ts @@ -59,7 +59,7 @@ export async function run(ctx: Ctx): Promise { } const versionName = a.get('version-name'); const signing = androidSigning(root); - const hasWrapper = existsSync(join(t.dir, 'gradlew')); + const hasWrapper = existsSync(join(t.dir, process.platform === 'win32' ? 'gradlew.bat' : 'gradlew')); const argv = gradleArgs(t, { versionCode: code || undefined, versionName, flavor, hasWrapper }); const cwd = t.framework === 'flutter' ? root : t.dir; // the SDK as Android Studio finds it (ANDROID_HOME is often unset in non-interactive shells and local.properties is @@ -117,6 +117,8 @@ export async function run(ctx: Ctx): Promise { const dest = join(out, `${info.packageName}-${info.versionCode}.aab`); copyFileSync(aab, dest); const result = { aab: dest, packageName: info.packageName, versionCode: info.versionCode, versionName: info.versionName ?? null, web: web.bundle }; + writeFileSync(join(out, 'latest.json'), `${JSON.stringify(result, null, 2)} +`); if (json) printJson(result); done(TAG, `${relative(root, dest)}: ${info.packageName} ${info.versionName ?? ''} (${info.versionCode}). Next: storebound play upload ${relative(root, dest)} --track internal --dry`); } diff --git a/docs/getting-started.md b/docs/getting-started.md index 02f2c56..ea6c825 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -152,6 +152,12 @@ plain Markdown and the CLI is a normal command. and `--command ""` to choose how the MCP server starts. It only adds or updates the `storebound` entry and its own skill folders; everything else in those files stays as it is, and re-running it is safe. +**CI servers (Jenkins, Forgejo / GitHub Actions):** use the npm package (`npx -y storebound@` or +`bunx storebound@`). From a git clone there is no `dist/` (it is built only for npm), so `node dist/storebound.mjs` +fails: run `bun install` in the clone and call `bin/storebound` (Bun runs `cli/index.ts`), e.g. symlink it onto PATH. +`storebound play build` and `apple build` write `/latest.json` (`aab` / `ipa` path, ids, version): read it instead of +globbing the output folder (or pass `--json`). + **Windows:** an MCP client cannot start `npx` directly (it is `npx.cmd`). `install` writes the working form for you; by hand use `"command": "cmd", "args": ["/c", "npx", "-y", "storebound@", "mcp"]` (or `bunx storebound mcp` with Bun). If the server shows "connection closed", check this first ([pitfall 94](../skills/store-pitfalls/SKILL.md)). diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 3e3eb02..061f84a 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1189,3 +1189,23 @@ that fails without the fix (see CONTRIBUTING.md). googleapis androidpublisher client, `api.appstoreconnect.apple.com`, `altool` / `iTMSTransporter` in CI files and scripts (not storebound's own checkout, never node_modules); `scan` rule `direct-store-api`, `check` and `release status` warnings with file:line and the storebound command (`tests/fastlane-traces.test.ts`). + +## 98. `play build` on Windows: "Executable not found in $PATH: gradlew.bat"; "C:/..." keystore "does not exist" +- **Symptom:** `storebound play build` stopped before Gradle on Windows although `android/gradlew.bat` exists; with + `ANDROID_KEYSTORE` set to an absolute `C:/...` path it said the keystore file does not exist. +- **Cause:** a bare `gradlew.bat` is searched on PATH only, never in the working folder; absolute paths were recognised + only when they started with `/`, so `C:/...` was joined onto the project folder. +- **Do:** update storebound. Until then run Gradle by hand and use a project-relative keystore path. +- **Guard:** `gradleArgs` in `cli/lib/gradle.ts` runs `cmd /c gradlew.bat` on Windows; `androidSigning` uses + `isAbsolute` (`tests/build-sign.test.ts`). + +## 99. Credentials still pointed at the old computer, and the keystore password did not open the keystore +- **Symptom:** after a machine move `ANDROID_KEYSTORE`, `PLAY_SERVICE_ACCOUNT` and `ASC_P8` held the old machine's + absolute paths, and `ANDROID_KEYSTORE_PASSWORD` / `ANDROID_KEY_ALIAS` did not open the upload keystore (keytool exit 1); + `check` passed and the build failed late. +- **Do:** point each path at the file on this machine; take the password and alias that open the keystore (an + `android/keystore.properties` often holds them). Verify with `keytool -list -keystore -alias `. +- **Guard:** `credentialFileIssues` in `cli/lib/credentials.ts`: `check` names every credential path that does not + exist and runs `keytool -list` with the stored password and alias (when keytool is on PATH or in JAVA_HOME), naming + the bad field (`tests/build-sign.test.ts`). `play build` / `apple build` also write `/latest.json` so CI + needs no glob for the AAB / IPA. diff --git a/tests/build-sign.test.ts b/tests/build-sign.test.ts index 3364713..83f1f1d 100644 --- a/tests/build-sign.test.ts +++ b/tests/build-sign.test.ts @@ -4,7 +4,7 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, ut import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { installedProfiles } from '../cli/apple/build'; -import { androidSigning, ascKeyFile } from '../cli/lib/credentials'; +import { androidSigning, ascKeyFile, credentialFileIssues } from '../cli/lib/credentials'; import { buildCsr, csrContent, newSigningKey, spkiOfKey } from '../cli/lib/csr'; import { aabInfo, appBuildFile, findBundles, gradleArgs, pickGradle, signingEnv, validatePlayBuild, versionSourceIssues, versionSourceMessage } from '../cli/lib/gradle'; import { parseBinaryPlist, parseMobileprovision, parsePlist, parseXmlPlist, toXmlPlist } from '../cli/lib/plist'; @@ -269,8 +269,10 @@ describe('gradle projects', () => { touch(rn, 'android/settings.gradle'); touch(rn, 'android/gradlew', '#!/bin/sh'); touch(rn, 'android/app/build.gradle'); const t = pickGradle(rn); expect(t).toMatchObject({ framework: 'react-native', module: 'app', task: ':app:bundleRelease' }); - expect(gradleArgs(t, { versionCode: 7, versionName: '1.2.0', hasWrapper: true })).toEqual(['./gradlew', ':app:bundleRelease', '--no-daemon', '--console=plain', + expect(gradleArgs(t, { versionCode: 7, versionName: '1.2.0', hasWrapper: true }, 'linux')).toEqual(['./gradlew', ':app:bundleRelease', '--no-daemon', '--console=plain', '-Pandroid.injected.version.code=7', '-PversionCode=7', '-Pandroid.injected.version.name=1.2.0', '-PversionName=1.2.0']); + // Windows: a bare gradlew.bat is looked up on PATH only; cmd /c runs the one in the project folder + expect(gradleArgs(t, { hasWrapper: true }, 'win32').slice(0, 4)).toEqual(['cmd', '/c', 'gradlew.bat', ':app:bundleRelease']); expect(pickGradle(rn, { flavor: 'prod' }).task).toBe(':app:bundleProdRelease'); const unity = dir('unity'); touch(unity, 'Export/settings.gradle'); touch(unity, 'Export/launcher/build.gradle'); touch(unity, 'Export/unityLibrary/build.gradle'); @@ -360,12 +362,26 @@ describe('credentials for builds', () => { delete process.env.ANDROID_KEYSTORE; expect(androidSigning(d)).toEqual({ storeFile: join(d, 'keys/upload.jks'), storePassword: 'pw', keyAlias: 'upload', keyPassword: 'pw' }); expect(androidSigning(dir('nocreds'))).toBeNull(); + // a Windows absolute path is used as it is, not joined onto the project folder + if (process.platform === 'win32') { + const w = dir('wincreds'); + touch(w, '.storebound/credentials.json', JSON.stringify({ ANDROID_KEYSTORE: 'C:/keys/upload.jks', ANDROID_KEYSTORE_PASSWORD: 'pw', ANDROID_KEY_ALIAS: 'upload' })); + expect(androidSigning(w)?.storeFile).toBe('C:/keys/upload.jks'); + } + // another machine's paths and a keystore the stored password does not open are named by field + const m = dir('moved'); + touch(m, 'keys/upload.jks', 'x'); + touch(m, '.storebound/credentials.json', JSON.stringify({ ANDROID_KEYSTORE: 'keys/upload.jks', ANDROID_KEYSTORE_PASSWORD: 'wrong', ANDROID_KEY_ALIAS: 'upload', PLAY_SERVICE_ACCOUNT: '/Users/someone/keys/play.json' })); + const issues = credentialFileIssues(m, () => ({ ok: false, out: 'keytool error: java.io.IOException: Keystore was tampered with, or password was incorrect' })); + expect(issues.some(i => i.startsWith('PLAY_SERVICE_ACCOUNT: /Users/someone/keys/play.json does not exist'))).toBe(true); + expect(issues.some(i => i.startsWith('ANDROID_KEYSTORE_PASSWORD does not open'))).toBe(true); + expect(credentialFileIssues(m, () => ({ ok: true, out: '' })).some(i => i.startsWith('ANDROID'))).toBe(false); const { pem } = newSigningKey(); const p8 = createPrivateKey(pem).export({ type: 'pkcs8', format: 'pem' }).toString(); Object.assign(process.env, { ASC_KEY_ID: 'KEYID00001', ASC_ISSUER_ID: '00000000-0000-0000-0000-000000000000', ASC_P8: p8 }); const k = ascKeyFile(d); expect(readFileSync(k.keyPath, 'utf8')).toBe(p8); - expect(k.keyPath.split('/').pop()).toBe(['AuthKey', 'KEYID00001.p8'].join('_')); + expect(k.keyPath.split(/[\\/]/).pop()).toBe(['AuthKey', 'KEYID00001.p8'].join('_')); k.cleanup(); expect(() => readFileSync(k.keyPath)).toThrow(); } finally { for (const key of ['ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8']) if (saved[key] === undefined) delete process.env[key]; else process.env[key] = saved[key]; } From e1634f6abe9a6edb1a0ddf2c8a961d71b5a1ff29 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 02:12:26 +0800 Subject: [PATCH 092/344] MCP: multi-line --text goes to the CLI as --from-text (console_verify kept only the first line on Windows); long JSON output keeps its start and names a file with the whole output (console_plan lost its start URL); test, pitfall 100 --- CHANGELOG.md | 3 +++ cli/mcp.ts | 30 ++++++++++++++++++++++++++++-- skills/store-pitfalls/SKILL.md | 11 +++++++++++ tests/mcp-text-file.test.ts | 24 ++++++++++++++++++++++++ 4 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 tests/mcp-text-file.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index bb958cb..28a0596 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- **MCP `console_verify` reads multi-line page text whole** (it kept only the first line on Windows), and long JSON + output such as `console_plan` keeps its start and names a file with the whole output. Pitfall 100. + - **Windows builds.** `play build` runs `gradlew.bat` through `cmd /c` (it was looked up on PATH only) and takes `C:/...` keystore paths as absolute. Pitfall 98. - **`check` verifies credential files.** Every credential path that does not exist on this machine and an upload keystore diff --git a/cli/mcp.ts b/cli/mcp.ts index 6abbfac..1bf1f64 100644 --- a/cli/mcp.ts +++ b/cli/mcp.ts @@ -20,6 +20,9 @@ // Every tool runs the CLI as a child process in the project directory (STOREBOUND_PROJECT or the server's cwd) and // returns its output. stdout of this process carries protocol messages only; logs go to stderr. // Tool list and safety rules: mcp-tools.ts (write tools default to dry_run, nothing public or irreversible exposed). +import { mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import pkg from '../package.json' with { type: 'json' }; import { runCommand, type Running } from './lib/runner'; import { listTools, TOOLS, toArgv, validateInput } from './mcp-tools'; @@ -107,9 +110,10 @@ export async function handle(m: Msg, run: (argv: string[], id: Id) => Promise<{ const input = (m.params?.arguments ?? {}) as Record; const problems = validateInput(tool, input); if (problems.length) return ok({ content: [{ type: 'text', text: `Invalid arguments: ${problems.join('; ')}` }], isError: true }); - const { argv, dryRun } = toArgv(tool, input); + const { argv: raw, dryRun } = toArgv(tool, input); + const argv = textToFile(raw); const r = await run(argv, m.id); - let out = r.out.length > MAX_OUTPUT ? `[... first ${r.out.length - MAX_OUTPUT} characters cut ...]\n` + r.out.slice(-MAX_OUTPUT) : r.out; + let out = clip(r.out, argv.includes('--json')); if (dryRun) out += '\n\n(dry run: nothing was changed. Ask the owner before calling again with dry_run: false.)'; const structured = { exitCode: r.code, dryRun, command: `storebound ${argv.join(' ')}`, output: out }; return ok({ content: [{ type: 'text', text: `$ storebound ${argv.join(' ')}\n${out}\n[exit ${r.code}]` }], structuredContent: structured, isError: r.code !== 0 }); @@ -118,6 +122,28 @@ export async function handle(m: Msg, run: (argv: string[], id: Id) => Promise<{ } } +/** A multi-line --text=... goes to the CLI as --from-text : on Windows the child starts through a shell and a + * multi-line argument kept only its first line (console_verify read every App Privacy type as missing). */ +export function textToFile(argv: string[]): string[] { + return argv.flatMap(a => { + if (!a.startsWith('--text=') || !/[\r\n]/.test(a)) return [a]; + const file = join(mkdtempSync(join(tmpdir(), 'storebound-mcp-')), 'page.txt'); + writeFileSync(file, a.slice('--text='.length)); + return ['--from-text', file]; + }); +} + +/** Long output: the whole text goes to a file whose path is named; JSON keeps its start (a plan's start URL and first + * steps were cut when the tail was kept), plain text its end (where errors are). */ +export function clip(out: string, json: boolean, max = MAX_OUTPUT): string { + if (out.length <= max) return out; + const file = join(mkdtempSync(join(tmpdir(), 'storebound-mcp-')), json ? 'output.json' : 'output.txt'); + writeFileSync(file, out); + return json + ? `${out.slice(0, max)}\n[... last ${out.length - max} characters cut; the whole output: ${file}]` + : `[... first ${out.length - max} characters cut; the whole output: ${file}]\n${out.slice(-max)}`; +} + const running = new Map(); function cancel(id: Id | undefined): void { if (id !== undefined) running.get(id)?.cancel(); } diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 061f84a..4de9ad2 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1209,3 +1209,14 @@ that fails without the fix (see CONTRIBUTING.md). exist and runs `keytool -list` with the stored password and alias (when keytool is on PATH or in JAVA_HOME), naming the bad field (`tests/build-sign.test.ts`). `play build` / `apple build` also write `/latest.json` so CI needs no glob for the AAB / IPA. + +## 100. `console_verify` reported every App Privacy type missing (multi-line page text over MCP on Windows) +- **Symptom:** MCP `console_verify` with the App Privacy page text said "not on the page" for every data type and "no + Published line"; the command line it echoed held only the text's first line. The same text from a file matched. +- **Cause:** the text went to the CLI as one `--text=...` argument; on Windows the child starts through a shell, which + kept only the first line. Separately, `console_plan` output over 60 KB was cut at the start, losing the start URL + and the first steps. +- **Do:** update storebound; meanwhile save the page text to a file and run `storebound console verify + --from-text `. +- **Guard:** `textToFile` in `cli/mcp.ts` sends multi-line text as `--from-text `; `clip` keeps the start of + long JSON output (the end of plain text) and names a file with the whole output (`tests/mcp-text-file.test.ts`). diff --git a/tests/mcp-text-file.test.ts b/tests/mcp-text-file.test.ts new file mode 100644 index 0000000..95dd166 --- /dev/null +++ b/tests/mcp-text-file.test.ts @@ -0,0 +1,24 @@ +// MCP calls: multi-line page text reaches the CLI whole (pitfall 100), long JSON output keeps its start. +import { describe, expect, test } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { clip, textToFile } from '../cli/mcp'; + +describe('mcp argv and output', () => { + test('a multi-line --text= becomes --from-text with the whole text', () => { + const page = 'App Privacy\nData Types\nCrash Data\r\nUsed for App Functionality\nPublished a few seconds ago'; + const argv = textToFile(['console', 'verify', 'apple-app-privacy', `--text=${page}`, '--json']); + expect(argv.slice(0, 4)).toEqual(['console', 'verify', 'apple-app-privacy', '--from-text']); + expect(argv.some(a => /[\r\n]/.test(a))).toBe(false); + expect(readFileSync(argv[4]!, 'utf8')).toBe(page); + expect(textToFile(['console', 'verify', 'x', '--text=one line'])).toEqual(['console', 'verify', 'x', '--text=one line']); + }); + test('long JSON keeps its start, long text its end; both name the full file', () => { + const json = `{"startUrl":"https://example.com/start",${'"x":1,'.repeat(50)}"end":true}`; + const j = clip(json, true, 40); + expect(j.startsWith('{"startUrl":"https://example.com/start"')).toBe(true); + const file = /the whole output: (.+)\]$/.exec(j)![1]!; + expect(readFileSync(file, 'utf8')).toBe(json); + expect(clip('a'.repeat(100) + 'ERROR at the end', false, 20).endsWith('ERROR at the end')).toBe(true); + expect(clip('short', true, 40)).toBe('short'); + }); +}); From f7dd646e570c311c6481d8ceda6a44ccd4cf01ab Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 02:15:03 +0800 Subject: [PATCH 093/344] Terminal: colors, status emoji and a live spinner line for waits at a TTY; plain lines unchanged when piped, in CI, with NO_COLOR, TERM=dumb, --json or MCP; desktop download progress through the log --- CHANGELOG.md | 4 +++ cli/desktop.ts | 4 +-- cli/lib/log.ts | 69 +++++++++++++++++++++++++++++++++++++++-- tests/log-fancy.test.ts | 26 ++++++++++++++++ 4 files changed, 98 insertions(+), 5 deletions(-) create mode 100644 tests/log-fancy.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 28a0596..939cbef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- **A livelier terminal.** At a terminal, lines get colors and status emoji (✅ ⚠️ ❌ 📦 🚀 🧪) and every wait ("waiting + for ...", uploads, downloads, progress) is one live spinner line with the elapsed time. Piped, CI, `NO_COLOR`, + `TERM=dumb`, `--json` and MCP keep the plain lines exactly as before. + - **MCP `console_verify` reads multi-line page text whole** (it kept only the first line on Windows), and long JSON output such as `console_plan` keeps its start and names a file with the whole output. Pitfall 100. diff --git a/cli/desktop.ts b/cli/desktop.ts index 8089388..5426361 100644 --- a/cli/desktop.ts +++ b/cli/desktop.ts @@ -26,7 +26,7 @@ import { verify } from './lib/minisign'; import { parsePlist } from './lib/plist'; import { addFolder } from './lib/registry'; import * as rt from './lib/rt'; -import { printJson, promptOut } from './lib/log'; +import { log, printJson, promptOut } from './lib/log'; import { stdinIsTTY } from './lib/tty'; type Fetch = (url: string) => Promise; @@ -58,7 +58,7 @@ export function pick(m: Manifest, keys: DownloadKey[], format?: string): [Downlo } /** Downloads one installer and keeps it only when its size, SHA-256 and minisign signature are right. */ -export async function download(d: Download, dir: string, get: Fetch = fetch, publicKey = PUBLIC_KEY, stallMs = 60_000, say: (s: string) => void = s => console.log(s)): Promise { +export async function download(d: Download, dir: string, get: Fetch = fetch, publicKey = PUBLIC_KEY, stallMs = 60_000, say: (s: string) => void = s => log('desktop', `downloading ${s.trim()}`)): Promise { const r = await withStall(get(d.url), stallMs, d.url); if (!r.ok) throw new Error(`${d.url}: HTTP ${r.status}`); const data = await readBody(r, d, stallMs, say); diff --git a/cli/lib/log.ts b/cli/lib/log.ts index 3790f6c..34bb78a 100644 --- a/cli/lib/log.ts +++ b/cli/lib/log.ts @@ -4,9 +4,72 @@ const t0 = Date.now(); const stamp = (): string => new Date().toISOString().slice(11, 19); const since = (): string => `${((Date.now() - t0) / 1000).toFixed(0)}s`; -export const log = (tag: string, msg: string): void => console.log(`${stamp()} [${tag}] ${msg}`); -export const warn = (tag: string, msg: string): void => console.warn(`${stamp()} [${tag}] WARN ${msg}`); -export const done = (tag: string, msg: string): void => console.log(`${stamp()} [${tag}] ${msg} (${since()})`); +/** + * Colors, status emoji and a spinner, only for a person at a terminal: stdout is a TTY and nothing asks for plain text + * (NO_COLOR, CI, TERM=dumb, a --json run, `storebound serve` / MCP children). Piped and logged output stays exactly + * the plain lines above, so `tail -f` and agents read the same text as before. + */ +export function fancy(env: Record = process.env, tty = !!process.stdout.isTTY): boolean { + return tty && !env.NO_COLOR && !env.CI && env.TERM !== 'dumb' && env.STOREBOUND_MACHINE !== '1' && env.STOREBOUND_MCP !== '1' && !jsonOutput(); +} + +const C = { dim: '\x1b[2m', cyan: '\x1b[36m', yellow: '\x1b[33m', green: '\x1b[32m', red: '\x1b[31m', bold: '\x1b[1m', off: '\x1b[0m' }; +const FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']; +/** A wait line ("waiting for ...", "still processing", "3/14 ..." progress) is drawn as one live spinner line. */ +const WAIT = /^(waiting|still |polling|processing|uploading|downloading|building|[ ]*\d+%|\d+\/\d+ )/i; + +/** Emoji for a line, by what it says. */ +export function emojiFor(msg: string, level: 'log' | 'warn' | 'done'): string { + if (level === 'warn') return '⚠️ '; + if (level === 'done') return '✅'; + if (/\b(fail|error|refus|rejected|not kept)/i.test(msg)) return '❌'; + if (/^(upload|uploading)/i.test(msg)) return '📦'; + if (/\b(submit(ted)?|released?|publish(ed)?|live)\b/i.test(msg)) return '🚀'; + if (/^(dry run|would )/i.test(msg)) return '🧪'; + return '•'; +} + +let spin: { text: string; start: number; frame: number; timer: ReturnType } | null = null; +const clearSpin = (): void => { if (spin) process.stdout.write('\r\x1b[2K'); }; +function stopSpin(): void { if (spin) { clearInterval(spin.timer); clearSpin(); spin = null; } } +function drawSpin(): void { + if (!spin) return; + const s = Math.round((Date.now() - spin.start) / 1000); + const cols = (process.stdout.columns || 100) - 12; + process.stdout.write(`\r\x1b[2K${C.cyan}${FRAMES[spin.frame++ % FRAMES.length]}${C.off} ${spin.text.slice(0, cols)} ${C.dim}${s}s${C.off}`); +} +function showSpin(text: string): void { + if (spin) { spin.text = text; drawSpin(); return; } + spin = { text, start: Date.now(), frame: 0, timer: setInterval(drawSpin, 100) }; + spin.timer.unref?.(); + drawSpin(); +} +let hooked = false; +/** Any other output first removes the live spinner line, so lines never mix. */ +function hook(): void { + if (hooked) return; + hooked = true; + for (const k of ['log', 'info', 'warn', 'error'] as const) { + const orig = console[k].bind(console); + console[k] = (...a: unknown[]) => { const was = spin?.text; stopSpin(); orig(...a); if (was !== undefined && k !== 'error') showSpin(was); }; + } + process.on('exit', stopSpin); +} + +function line(level: 'log' | 'warn' | 'done', tag: string, msg: string): void { + const plain = `${stamp()} [${tag}] ${level === 'warn' ? 'WARN ' : ''}${msg}${level === 'done' ? ` (${since()})` : ''}`; + if (!fancy()) { (level === 'warn' ? console.warn : console.log)(plain); return; } + hook(); + if (level === 'log' && WAIT.test(msg)) { showSpin(`${C.bold}${tag}${C.off} ${msg}`); return; } + stopSpin(); + const color = level === 'warn' ? C.yellow : level === 'done' ? C.green : emojiFor(msg, level) === '❌' ? C.red : ''; + const text = `${C.dim}${stamp()}${C.off} ${emojiFor(msg, level)} ${C.cyan}${tag}${C.off} ${color}${msg}${color ? C.off : ''}${level === 'done' ? ` ${C.dim}(${since()})${C.off}` : ''}`; + (level === 'warn' ? console.warn : console.log)(text); +} + +export const log = (tag: string, msg: string): void => line('log', tag, msg); +export const warn = (tag: string, msg: string): void => line('warn', tag, msg); +export const done = (tag: string, msg: string): void => line('done', tag, msg); // The count lives on globalThis: the Node bundle (tools/build-node.ts) can carry this module twice (once for the // static imports, once inside a lazily initialised chunk), and both copies must see the same --json run. diff --git a/tests/log-fancy.test.ts b/tests/log-fancy.test.ts new file mode 100644 index 0000000..c3f87a3 --- /dev/null +++ b/tests/log-fancy.test.ts @@ -0,0 +1,26 @@ +// Terminal styling is for people only: piped, CI, NO_COLOR, TERM=dumb, MCP and serve children get the plain lines. +import { describe, expect, test } from 'bun:test'; +import { emojiFor, fancy } from '../cli/lib/log'; + +describe('fancy terminal output', () => { + test('only on a TTY with nothing asking for plain text', () => { + expect(fancy({}, true)).toBe(true); + expect(fancy({}, false)).toBe(false); + for (const env of [{ NO_COLOR: '1' }, { CI: 'true' }, { TERM: 'dumb' }, { STOREBOUND_MCP: '1' }, { STOREBOUND_MACHINE: '1' }]) expect(fancy(env, true)).toBe(false); + }); + test('emoji by level and message', () => { + expect(emojiFor('anything', 'done')).toBe('✅'); + expect(emojiFor('anything', 'warn')).toBe('⚠️ '); + expect(emojiFor('upload failed: 409', 'log')).toBe('❌'); + expect(emojiFor('uploading 3 files', 'log')).toBe('📦'); + expect(emojiFor('submitted for review', 'log')).toBe('🚀'); + expect(emojiFor('dry run: nothing changed', 'log')).toBe('🧪'); + }); + test('a piped run prints the plain line, no ANSI', () => { + const r = Bun.spawnSync(['bun', '-e', "const { log, warn, done } = await import('./cli/lib/log.ts'); log('t', 'waiting for x'); warn('t', 'careful'); done('t', 'ok');"], { cwd: `${import.meta.dir}/..`, stdout: 'pipe', stderr: 'pipe' }); + const out = r.stdout.toString() + r.stderr.toString(); + expect(out).not.toMatch(/\x1b\[/); + expect(out).toMatch(/\[t\] waiting for x/); + expect(out).toMatch(/\[t\] WARN careful/); + }); +}); From a8a889fb3567586ee5c0b3f8908c47d863fad868 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 02:17:28 +0800 Subject: [PATCH 094/344] release: a staged npm publish found on the retry is reported as waiting for the maintainer's approval instead of failing after 5 minutes --- tools/release.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/release.ts b/tools/release.ts index 9d1a6d1..0565d00 100644 --- a/tools/release.ts +++ b/tools/release.ts @@ -481,6 +481,8 @@ async function npmRelease(version: string, token: string): Promise { again = true; say(`npm: ${version} is not on the registry yet: publishing once more`); const p2 = npmRun(['publish'], token); + // 0.8.25: the first publish was staged silently; the retry's 409 "previously staged" says so (no 5-minute wait) + if (/staged/i.test(p2.out)) { say(`npm: ${version} is staged and waits for the maintainer's approval: https://www.npmjs.com/package/storebound (approve it there; then deprecate runs with: bun tools/release.ts npm-publish)`); return; } if (p2.code !== 0 && !/previously published|cannot publish over/i.test(p2.out)) fail(`npm publish (second try) failed: ${p2.out.trim().split('\n').slice(-4).join(' ')}`); } } From 2598c4953aac91b3ab69ed67b940d0797406bfc7 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 02:21:26 +0800 Subject: [PATCH 095/344] doctor: build dependencies (JDK with the version the project needs, Android SDK command-line tools, CocoaPods, Node, Bun, bundletool), too-old status, doctor --install --yes runs the package-manager command (never sudo); desktop Dependencies shows too old; gen-flags works on Windows paths --- CHANGELOG.md | 5 +++ apps/desktop/src/i18n/en.ts | 1 + apps/desktop/src/i18n/tr.ts | 1 + apps/desktop/src/screens/Dependencies.tsx | 1 + cli/commands.ts | 2 +- cli/data/flags.json | 7 +++- cli/doctor.ts | 41 +++++++++++++++--- cli/lib/tools.ts | 51 ++++++++++++++++++++++- tests/deps.test.ts | 36 ++++++++++++++++ tools/gen-flags.ts | 6 +-- 10 files changed, 137 insertions(+), 14 deletions(-) create mode 100644 tests/deps.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 939cbef..14004de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- **Build dependencies in `doctor` and the desktop Dependencies screen.** JDK (with the version the project needs from + the Android Gradle plugin / jvmToolchain, "too old" when below it), Android SDK command-line tools, CocoaPods, Node.js, + Bun and bundletool join ffmpeg, Chrome, Xcode, adb and git. `storebound doctor --install --yes` runs this OS's + package-manager command (winget / brew); sudo and admin commands are printed, never run. + - **A livelier terminal.** At a terminal, lines get colors and status emoji (✅ ⚠️ ❌ 📦 🚀 🧪) and every wait ("waiting for ...", uploads, downloads, progress) is one live spinner line with the elapsed time. Piped, CI, `NO_COLOR`, `TERM=dumb`, `--json` and MCP keep the plain lines exactly as before. diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 3585c39..9e21009 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -543,6 +543,7 @@ export const en = { 'deps.tools': 'Tools on this computer', 'deps.found': '{found} of {total} found', 'deps.missing': 'Missing', + 'deps.outdated': 'Too old (needs {version})', 'deps.appCopy': 'App copy', 'deps.installed': 'Installed', 'deps.download': 'Download', diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index e4847bc..79f399c 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -545,6 +545,7 @@ export const tr: Record = { 'deps.tools': 'Bu bilgisayardaki araçlar', 'deps.found': '{total} araçtan {found} tanesi var', 'deps.missing': 'Eksik', + 'deps.outdated': 'Eski (gereken {version})', 'deps.appCopy': 'Uygulamanın kopyası', 'deps.installed': 'Kurulu', 'deps.download': 'İndir', diff --git a/apps/desktop/src/screens/Dependencies.tsx b/apps/desktop/src/screens/Dependencies.tsx index 3d7cc20..9c388e2 100644 --- a/apps/desktop/src/screens/Dependencies.tsx +++ b/apps/desktop/src/screens/Dependencies.tsx @@ -15,6 +15,7 @@ const TOOL_ICON: Record = { ffmpeg: 'image', ffprobe: 'search' /** Status chip of one tool. */ export function toolState(x: ToolStatus): { text: string; tone: 'ok' | 'warn' | 'accent' } { if (!x.found) return { text: t('deps.missing'), tone: 'warn' }; + if (x.status === 'outdated') return { text: t('deps.outdated', { version: x.required ?? '' }), tone: 'warn' }; return x.source === 'app' ? { text: t('deps.appCopy'), tone: 'accent' } : { text: t('deps.installed'), tone: 'ok' }; } diff --git a/cli/commands.ts b/cli/commands.ts index b58f9e6..7d1846f 100644 --- a/cli/commands.ts +++ b/cli/commands.ts @@ -15,7 +15,7 @@ export const PLAIN: Record Promise, string]> = { 'apps': [() => import('./apps'), 'list (every app the store keys can see: App Store Connect team, Play developer accounts; --icons) | check (key works / permission missing / revoked, with the fix); --store apple|play, --json; read-only | folders | add [] | remove : the app folders of this machine, the same list as the desktop app'], 'desktop': [() => import('./desktop'), 'open the storebound desktop app on this folder; not installed or another version: download it for this system (size, SHA-256, signature checked), install it for this user (asks once; --yes) and open it; --download only saves the installer, --dry / --json change nothing'], 'accounts': [() => import('./accounts'), 'the store accounts of this machine (credential profiles in ~/.storebound/credentials, shared with the desktop app): list | import (a project\'s store keys -> a profile; --dry first) | use | default (the machine default; --clear)'], - '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'], + 'doctor': [() => import('./doctor'), 'build and capture dependencies (JDK with the version the project needs, Android SDK, Xcode, CocoaPods, Node, Bun, ffmpeg, Chrome, adb, git, bundletool) and how to install what is missing; --install --yes; --json'], 'scan': [() => import('./scan'), 'offline, read-only rejection-risk scan of the project itself (stack, SDKs, Info.plist, manifest, listings) with guideline, evidence file:line, fix and skill, plus the Data safety / App Privacy / ATT / privacy manifest proposal; --write puts the detected answers into the config; --json; exit 1 on blockers'], 'api': [() => import('./api'), 'every App Store Connect / Google Play API operation: list | coverage | apple|play [--param k=v] [--body f.json] [--all-pages] (GET runs; writes dry unless --yes in a terminal; owner-only ones need the id typed)'], 'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios )'], diff --git a/cli/data/flags.json b/cli/data/flags.json index 9c2cd6a..be6a24c 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -459,7 +459,8 @@ "xdg-mime" ], "doctor": [ - "dir" + "dir", + "install" ], "edit": [ "ops", @@ -1019,6 +1020,7 @@ "identity", "include-drafts", "include-high-income", + "install", "internal", "internal-only", "invite", @@ -1370,7 +1372,8 @@ "storebound desktop --download only save the installer for this system into ~/Downloads (checked as above)" ], "doctor": [ - "storebound doctor [--dir .] [--json]" + "storebound doctor [--dir .] [--json]", + "storebound doctor --install [--yes] runs this OS's install command for one tool (winget / brew / apt);" ], "edit": [ "storebound edit --ops '' [--dry] [--json]", diff --git a/cli/doctor.ts b/cli/doctor.ts index 566a3e2..7b2de04 100644 --- a/cli/doctor.ts +++ b/cli/doctor.ts @@ -2,6 +2,8 @@ // 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] +// storebound doctor --install [--yes] runs this OS's install command for one tool (winget / brew / apt); +// without --yes only prints it. Never sudo, never an admin prompt. import { existsSync } from 'node:fs'; import { join, resolve } from 'node:path'; import pkg from '../package.json' with { type: 'json' }; @@ -22,6 +24,9 @@ export interface DoctorRow { path: string | null; source: ToolStatus['source']; usedFor: string; + /** The version the project needs and ok / missing / outdated. */ + required?: string | null; + status?: 'ok' | 'missing' | 'outdated'; /** Install commands for this OS (empty when found). */ install: string[]; url: string | null; @@ -38,30 +43,54 @@ export interface DoctorResult { } 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 tools: DoctorRow[] = detectTools(env, cwd).map(t => ({ id: t.id, name: t.name, found: t.found, version: t.version, path: t.path, source: t.source, usedFor: t.usedFor, + required: t.required ?? null, status: t.status, install: t.status === 'ok' ? [] : installCommands(t.id), url: t.install.url })); const pw = findPlaywright([cwd, rt.packageRoot()]); 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; const sdk = androidSdk([join(cwd, 'android'), cwd], env); - return { storebound: pkg.version, bun: rt.bunVersion, runtime: `${rt.runtime.name} ${rt.runtime.version}`, platform: `${process.platform}-${process.arch}`, project, tools, missing: tools.filter(t => !t.found).length, androidSdk: sdk, credentials: credentialStatus(cwd), + return { storebound: pkg.version, bun: rt.bunVersion, runtime: `${rt.runtime.name} ${rt.runtime.version}`, platform: `${process.platform}-${process.arch}`, project, tools, missing: tools.filter(t => !t.found || t.status === 'outdated').length, androidSdk: sdk, credentials: credentialStatus(cwd), foreignRsync: process.platform === 'darwin' ? foreignRsync(env.PATH) : null }; } +/** One install command of a tool, run only with --yes; sudo / admin commands are printed, never run. */ +export function installPlan(r: DoctorResult, id: string, platform: NodeJS.Platform = process.platform): { tool: DoctorRow; command: string | null; runnable: boolean } { + const tool = r.tools.find(t => t.id === id); + if (!tool) throw new Error(`doctor --install: no tool "${id}" (one of ${r.tools.map(t => t.id).join(', ')})`); + const command = installCommands(tool.id, platform)[0] ?? null; + return { tool, command, runnable: !!command && !/^sudo |\| *(ba)?sh|^Install /.test(command) }; +} + export async function run(args: Args): Promise { const r = doctor(resolve(args.str('dir', '.'))); + const want = args.get('install'); + if (want) { + const plan = installPlan(r, want); + if (plan.tool.status === 'ok') { log('doctor', `${plan.tool.name} ${plan.tool.version ?? ''} is already here${plan.tool.required ? ` (the project needs ${plan.tool.required})` : ''}`); return; } + if (!plan.command) throw new Error(`doctor --install: no install command for ${plan.tool.name} on this OS: ${plan.tool.url}`); + if (!plan.runnable || !args.has('yes')) { + log('doctor', `would run: ${plan.command}${plan.runnable ? ' (add --yes to run it)' : ' (needs admin rights: run it yourself)'}`); + return; + } + log('doctor', `installing ${plan.tool.name}: ${plan.command}`); + const p = rt.spawnSync(plan.command.split(/\s+/), { stdout: 'inherit', stderr: 'inherit', timeout: 20 * 60_000 }); + if (!p.success) throw new Error(`${plan.command} failed (exit ${p.exitCode}); open a new terminal if it installed but is not on PATH yet`); + const after = doctor(resolve(args.str('dir', '.'))).tools.find(t => t.id === plan.tool.id); + log('doctor', `${plan.tool.name}: ${after?.status ?? 'unknown'}${after?.version ? ` ${after.version}` : ''} (a new terminal may be needed for PATH)`); + return; + } if (args.has('json')) { printJson(r); return; } log('doctor', `storebound ${r.storebound} · ${r.runtime} · ${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]))); + console.log(textTable(['tool', 'status', 'version', 'needs', 'used for'], r.tools.map(t => [t.name, t.status === 'outdated' ? 'too old' : t.found ? (t.source === 'app' ? 'ok (app copy)' : 'ok') : 'missing', t.version ?? '', t.required ?? '', t.usedFor]))); log('doctor', r.androidSdk.path ? `Android SDK: ${r.androidSdk.path} (from ${r.androidSdk.source})` : `Android SDK: not found (play build needs it). Checked: ${r.androidSdk.checked.join('; ')}`); const set = r.credentials.filter(c => c.status === 'set').map(c => c.key), ph = r.credentials.filter(c => c.status === 'placeholder').map(c => c.key); log('doctor', `credentials: ${set.length ? set.join(', ') : 'none set'}${ph.length ? ` · placeholders (treated as missing): ${ph.join(', ')}` : ''}`); if (r.foreignRsync) log('doctor', `rsync: ${r.foreignRsync} is first on PATH and breaks Xcode exportArchive ("Copy failed") outside storebound; storebound apple build puts /usr/bin first. Fix for everything else: brew unlink rsync, or put /usr/bin before it`); - const missing = r.tools.filter(t => !t.found); + const missing = r.tools.filter(t => !t.found || t.status === 'outdated'); 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):'); + console.log('\nTo install what is missing (storebound doctor --install --yes runs the first one; sudo / admin ones you run yourself):'); for (const t of missing) { console.log(` ${t.name}`); for (const c of t.install) console.log(` ${c}`); diff --git a/cli/lib/tools.ts b/cli/lib/tools.ts index 3e7217e..db00065 100644 --- a/cli/lib/tools.ts +++ b/cli/lib/tools.ts @@ -8,7 +8,7 @@ import { existsSync, readFileSync } from 'node:fs'; import { delimiter, join } from 'node:path'; import * as rt from './rt'; -export type ToolId = 'ffmpeg' | 'ffprobe' | 'chrome' | 'xcode' | 'simctl' | 'adb' | 'git'; +export type ToolId = 'ffmpeg' | 'ffprobe' | 'chrome' | 'xcode' | 'simctl' | 'adb' | 'git' | 'java' | 'sdkmanager' | 'cocoapods' | 'node' | 'bun' | 'bundletool'; export interface ToolStatus { id: ToolId; @@ -22,6 +22,10 @@ export interface ToolStatus { usedFor: string; /** How to get it: the desktop app downloads ffmpeg and Chrome for Testing; Xcode and the Android SDK are link-out. */ install: { kind: 'download' | 'link'; url: string; note: string }; + /** The version the project needs (JDK from the Android Gradle plugin / jvmToolchain), when one is known. */ + required?: string | null; + /** ok, missing, or found but older than `required`. */ + status?: 'ok' | 'missing' | 'outdated'; } /** Folders where tools usually live but that are often missing from PATH (apps started from the Dock or Finder get @@ -57,6 +61,8 @@ function firstLine(cmd: string[], env: Record): string | null { /** "ffmpeg version 7.1.1 Copyright ..." -> "7.1.1"; "Google Chrome for Testing 131.0.6778.85" -> "131.0.6778.85". */ export function parseVersion(line: string | null): string | null { if (!line) return null; + const java = /version "(\d[^"]*)"/.exec(line)?.[1]; + if (java) return java; return line.match(/version\s+([^\s,]+)/i)?.[1] ?? line.match(/(\d+(?:\.\d+)+)/)?.[1] ?? null; } @@ -69,7 +75,7 @@ export function systemChrome(platform = process.platform, env: Record = process.env): ToolStatus[] { +export function detectTools(env: Record = process.env, project?: string): ToolStatus[] { const PATH = toolPath(env); const spawnEnv: Record = { ...Object.fromEntries(Object.entries(env).filter((e): e is [string, string] => e[1] !== undefined)), PATH }; const appDirs = (env.STOREBOUND_TOOL_PATH ?? '').split(delimiter).filter(Boolean); @@ -102,9 +108,44 @@ export function detectTools(env: Record = process.en } out.push(bin('adb', 'adb (Android platform tools)', 'Android emulator / device screenshots and recordings', { kind: 'link', url: 'https://developer.android.com/tools/releases/platform-tools', note: 'Install Android Studio or the SDK platform tools.' }, ['version'])); 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'])); + // build toolchain: what play build / apple build need + const javaBin = env.JAVA_HOME && existsSync(join(env.JAVA_HOME, 'bin')) ? join(env.JAVA_HOME, 'bin', process.platform === 'win32' ? 'java.exe' : 'java') : which('java'); + out.push({ id: 'java', name: 'JDK (Java)', found: !!javaBin, path: javaBin, version: javaBin ? parseVersion(firstLine([javaBin, '-version'], spawnEnv)) : null, source: javaBin ? 'system' : null, + usedFor: 'play build (Gradle), keystore checks (keytool)', required: project ? requiredJdk(project) : null, + install: { kind: 'link', url: 'https://adoptium.net/temurin/releases/', note: 'Temurin JDK; the version the Android Gradle plugin asks for.' } }); + const sdk = androidSdk(project ? [join(project, 'android'), project] : [], env); + const sdkm = sdk.path ? ['cmdline-tools/latest/bin', 'tools/bin'].map(d => join(sdk.path!, d, process.platform === 'win32' ? 'sdkmanager.bat' : 'sdkmanager')).find(f => existsSync(f)) ?? null : null; + out.push({ id: 'sdkmanager', name: 'Android SDK command-line tools', found: !!sdkm, path: sdkm ?? sdk.path, version: null, source: sdkm ? 'system' : null, + usedFor: 'play build: SDK platforms and build tools', install: { kind: 'link', url: 'https://developer.android.com/studio#command-tools', note: 'Android Studio, or the command-line tools alone.' } }); + if (process.platform === 'darwin') out.push(bin('pod' as ToolId, 'CocoaPods', 'iOS builds of Capacitor / React Native / Flutter apps with a Podfile', { kind: 'link', url: 'https://cocoapods.org', note: 'brew install cocoapods' }, ['--version'])); + out.push(bin('node', 'Node.js', 'web builds (npm scripts), npx storebound', { kind: 'link', url: 'https://nodejs.org', note: 'The LTS release.' }, ['--version'])); + out.push(bin('bun', 'Bun', 'storebound from a git clone, web builds', { kind: 'link', url: 'https://bun.sh', note: 'bun.sh installer or a package manager.' }, ['--version'])); + out.push(bin('bundletool', 'bundletool', 'checks of the AAB (sizes, APKs per device)', { kind: 'link', url: 'https://github.com/google/bundletool/releases', note: 'Optional.' }, ['version'])); + for (const t of out) { + if ((t.id as string) === 'pod') t.id = 'cocoapods'; + t.status = !t.found ? 'missing' : t.required && t.version && majorOf(t.version) < majorOf(t.required) ? 'outdated' : 'ok'; + } return out; } +/** "17.0.9" -> 17; "1.8.0_392" -> 8. */ +export const majorOf = (v: string): number => { const n = v.replace(/^1\.(?=\d+\.)/, '').match(/\d+/); return n ? Number(n[0]) : 0; }; + +/** + * The JDK major version an Android project needs: jvmToolchain(N) / JavaVersion.VERSION_N in its Gradle files, at + * least the Android Gradle plugin's minimum (AGP 8.x: 17, 7.x: 11). Null when the project has no Gradle files. + */ +export function requiredJdk(project: string): string | null { + const files = ['android/build.gradle', 'android/build.gradle.kts', 'android/app/build.gradle', 'android/app/build.gradle.kts', 'android/gradle/libs.versions.toml', + 'build.gradle', 'build.gradle.kts', 'app/build.gradle', 'app/build.gradle.kts', 'gradle/libs.versions.toml'].map(f => join(project, f)).filter(f => existsSync(f)); + if (!files.length) return null; + const text = files.map(f => { try { return readFileSync(f, 'utf8'); } catch { return ''; } }).join('\n'); + const toolchain = /jvmToolchain\s*\(\s*(\d+)/.exec(text)?.[1] ?? /JavaVersion\.VERSION_(\d+)/.exec(text)?.[1] ?? /JavaLanguageVersion\.of\(\s*(\d+)/.exec(text)?.[1]; + const agp = /com\.android\.tools\.build:gradle:(\d+)/.exec(text)?.[1] ?? /^\s*(?:agp|androidGradlePlugin|android-gradle-plugin)\s*=\s*"(\d+)/m.exec(text)?.[1]; + const fromAgp = agp ? (Number(agp) >= 8 ? 17 : Number(agp) >= 7 ? 11 : 8) : 17; + return String(Math.max(toolchain ? Number(toolchain) : 0, fromAgp)); +} + /** * 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. @@ -119,6 +160,12 @@ export function installCommands(id: ToolId | 'playwright', platform: NodeJS.Plat 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']; + case 'java': return mac ? ['brew install --cask temurin@17'] : win ? ['winget install --id EclipseAdoptium.Temurin.17.JDK'] : ['sudo apt install openjdk-17-jdk']; + case 'sdkmanager': return mac ? ['brew install --cask android-commandlinetools'] : win ? ['winget install --id Google.AndroidStudio'] : ['sudo snap install android-studio --classic']; + case 'cocoapods': return mac ? ['brew install cocoapods'] : []; + case 'node': return mac ? ['brew install node'] : win ? ['winget install --id OpenJS.NodeJS.LTS'] : ['sudo apt install nodejs npm']; + case 'bun': return mac ? ['brew install oven-sh/bun/bun'] : win ? ['winget install --id Oven-sh.Bun'] : ['curl -fsSL https://bun.sh/install | bash']; + case 'bundletool': return mac ? ['brew install bundletool'] : []; } } diff --git a/tests/deps.test.ts b/tests/deps.test.ts new file mode 100644 index 0000000..053ede4 --- /dev/null +++ b/tests/deps.test.ts @@ -0,0 +1,36 @@ +// Build dependencies: the JDK the project needs, version parsing, and doctor --install planning. +import { describe, expect, test } from 'bun:test'; +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { installPlan, type DoctorResult } from '../cli/doctor'; +import { installCommands, majorOf, parseVersion, requiredJdk } from '../cli/lib/tools'; + +function project(files: Record): string { + const dir = mkdtempSync(join(tmpdir(), 'sb-deps-')); + for (const [p, text] of Object.entries(files)) { mkdirSync(join(dir, p, '..'), { recursive: true }); writeFileSync(join(dir, p), text); } + return dir; +} + +describe('build dependencies', () => { + test('JDK version from java -version and majors', () => { + expect(parseVersion('openjdk version "17.0.9" 2023-10-17')).toBe('17.0.9'); + expect(parseVersion('java version "1.8.0_392"')).toBe('1.8.0_392'); + expect(majorOf('17.0.9')).toBe(17); + expect(majorOf('1.8.0_392')).toBe(8); + }); + test('the JDK a project needs: AGP minimum, jvmToolchain wins when higher', () => { + expect(requiredJdk(project({ 'android/build.gradle': "classpath 'com.android.tools.build:gradle:8.7.2'" }))).toBe('17'); + expect(requiredJdk(project({ 'android/build.gradle': "classpath 'com.android.tools.build:gradle:7.4.2'" }))).toBe('11'); + expect(requiredJdk(project({ 'android/gradle/libs.versions.toml': 'agp = "8.5.0"', 'android/app/build.gradle.kts': 'kotlin { jvmToolchain(21) }' }))).toBe('21'); + expect(requiredJdk(project({ 'package.json': '{}' }))).toBeNull(); + }); + test('install commands per OS; doctor --install runs only package-manager commands, never sudo', () => { + expect(installCommands('java', 'win32')[0]).toBe('winget install --id EclipseAdoptium.Temurin.17.JDK'); + expect(installCommands('sdkmanager', 'darwin')[0]).toBe('brew install --cask android-commandlinetools'); + const r = { tools: [{ id: 'java', name: 'JDK (Java)', found: false, version: null, path: null, source: null, usedFor: '', install: [], url: null, status: 'missing' }] } as unknown as DoctorResult; + expect(installPlan(r, 'java', 'win32')).toMatchObject({ command: 'winget install --id EclipseAdoptium.Temurin.17.JDK', runnable: true }); + expect(installPlan(r, 'java', 'linux').runnable).toBe(false); + expect(() => installPlan(r, 'nope', 'win32')).toThrow('no tool "nope"'); + }); +}); diff --git a/tools/gen-flags.ts b/tools/gen-flags.ts index c98884a..aaacd81 100644 --- a/tools/gen-flags.ts +++ b/tools/gen-flags.ts @@ -9,7 +9,7 @@ // bun tools/gen-flags.ts write cli/data/flags.json // bun tools/gen-flags.ts --check exit 1 when the file is stale (tests/cli-help.test.ts runs it) import { existsSync, readFileSync, writeFileSync } from 'node:fs'; -import { dirname, join, relative, resolve } from 'node:path'; +import { dirname, join, relative, resolve, sep } from 'node:path'; const ROOT = resolve(import.meta.dir, '..'); const CLI = join(ROOT, 'cli'); @@ -48,9 +48,9 @@ function scan(entry: string, errors: string[]): Set { const f = todo.pop()!; if (seen.has(f)) continue; seen.add(f); - const rel = relative(CLI, f); + const rel = relative(CLI, f).split(sep).join('/'); // lib/embedded.ts holds file texts (templates, shots pages: their own scripts read URL params), not flag reads - if (rel === 'index.ts' || rel === 'commands.ts' || rel === join('lib', 'embedded.ts')) continue; + if (rel === 'index.ts' || rel === 'commands.ts' || rel === 'lib/embedded.ts') continue; const src = readFileSync(f, 'utf8'); for (const m of src.matchAll(READ)) if (!NOT_ARGS.test(m[1]!)) flags.add(m[3]!); for (const fl of DYNAMIC[rel] ?? []) flags.add(fl); From 9bd17c401d987dea8cce54cd570ab625194d8b2b Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 02:27:34 +0800 Subject: [PATCH 096/344] Bypass mode (owner opt-in, default off): storebound settings bypass on|off|status and a one-time question in init; MCP owner_step (owner-only commands, dry run first), owner-only api operations with --yes --confirm, console plans may press buttons.final; every action logged to .storebound/owner-actions.log; docs/bypass.md, agent rules, tests --- .cursor/rules/storebound.mdc | 4 +++ .github/copilot-instructions.md | 4 +++ AGENTS.md | 4 +++ CHANGELOG.md | 6 ++++ GEMINI.md | 4 +++ cli/api.ts | 3 +- cli/api/gate.ts | 7 +++-- cli/commands.ts | 1 + cli/data/flags.json | 4 +++ cli/init.ts | 11 ++++++- cli/lib/bypass.ts | 54 +++++++++++++++++++++++++++++++++ cli/lib/console-plan.ts | 2 +- cli/lib/desktop-coverage.ts | 1 + cli/mcp-tools.ts | 14 +++++++-- cli/mcp.ts | 14 ++++++--- cli/settings.ts | 20 ++++++++++++ docs/agents-core.md | 4 +++ docs/bypass.md | 30 ++++++++++++++++++ docs/desktop-coverage.md | 3 +- tests/bypass.test.ts | 39 ++++++++++++++++++++++++ tests/desktop-coverage.test.ts | 2 +- 21 files changed, 218 insertions(+), 13 deletions(-) create mode 100644 cli/lib/bypass.ts create mode 100644 cli/settings.ts create mode 100644 docs/bypass.md create mode 100644 tests/bypass.test.ts diff --git a/.cursor/rules/storebound.mdc b/.cursor/rules/storebound.mdc index 8ba9940..18a30b6 100644 --- a/.cursor/rules/storebound.mdc +++ b/.cursor/rules/storebound.mdc @@ -20,6 +20,10 @@ storebound plus you, the AI agent, do the work. The owner is not your pair of ha testers. (Also the owner's: canceling a submission, starting or stopping a store experiment, a console form's final Submit / Create that a console plan lists in `buttons.final`, signing in and granting account permissions.) For these you prepare everything, show the dry run, and the owner presses one button or says yes. + **Bypass mode** (`storebound settings bypass status`): when the owner turned it on, you run these owner steps too: + MCP `owner_step` (dry run first, then `dry_run: false`), `storebound api ... --yes --confirm `, and + console plans' `buttons.final`. Say in one line what you pressed; every action is logged to + `.storebound/owner-actions.log`. Legal agreements, passwords and 2FA stay with the owner if your own rules say so. 3. **Ask the owner only for facts that no code, config or doc can prove:** compliance answers such as Data safety, App Privacy, age rating, export compliance, partial data deletion. Collect ALL of them in ONE batch at the start (`storebound check` and `storebound validate` list them), never one at a time during the run. Reuse answers that diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 5515c62..7ab0224 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -20,6 +20,10 @@ storebound plus you, the AI agent, do the work. The owner is not your pair of ha testers. (Also the owner's: canceling a submission, starting or stopping a store experiment, a console form's final Submit / Create that a console plan lists in `buttons.final`, signing in and granting account permissions.) For these you prepare everything, show the dry run, and the owner presses one button or says yes. + **Bypass mode** (`storebound settings bypass status`): when the owner turned it on, you run these owner steps too: + MCP `owner_step` (dry run first, then `dry_run: false`), `storebound api ... --yes --confirm `, and + console plans' `buttons.final`. Say in one line what you pressed; every action is logged to + `.storebound/owner-actions.log`. Legal agreements, passwords and 2FA stay with the owner if your own rules say so. 3. **Ask the owner only for facts that no code, config or doc can prove:** compliance answers such as Data safety, App Privacy, age rating, export compliance, partial data deletion. Collect ALL of them in ONE batch at the start (`storebound check` and `storebound validate` list them), never one at a time during the run. Reuse answers that diff --git a/AGENTS.md b/AGENTS.md index abbc502..ea2ee8f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,6 +21,10 @@ storebound plus you, the AI agent, do the work. The owner is not your pair of ha testers. (Also the owner's: canceling a submission, starting or stopping a store experiment, a console form's final Submit / Create that a console plan lists in `buttons.final`, signing in and granting account permissions.) For these you prepare everything, show the dry run, and the owner presses one button or says yes. + **Bypass mode** (`storebound settings bypass status`): when the owner turned it on, you run these owner steps too: + MCP `owner_step` (dry run first, then `dry_run: false`), `storebound api ... --yes --confirm `, and + console plans' `buttons.final`. Say in one line what you pressed; every action is logged to + `.storebound/owner-actions.log`. Legal agreements, passwords and 2FA stay with the owner if your own rules say so. 3. **Ask the owner only for facts that no code, config or doc can prove:** compliance answers such as Data safety, App Privacy, age rating, export compliance, partial data deletion. Collect ALL of them in ONE batch at the start (`storebound check` and `storebound validate` list them), never one at a time during the run. Reuse answers that diff --git a/CHANGELOG.md b/CHANGELOG.md index 14004de..89ac8d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- **Bypass mode (owner opt-in, default off).** `storebound settings bypass on` (or "y" in `storebound init`) lets the AI + agent press the owner-only buttons too: MCP `owner_step` (submit, release, rollout, testers, replies, prices, ...; + dry run first), owner-only `storebound api` operations with `--yes --confirm `, console plans' + `buttons.final`. Every action is logged to `.storebound/owner-actions.log`; `bypass off` restores the old behaviour. + docs/bypass.md. + - **Build dependencies in `doctor` and the desktop Dependencies screen.** JDK (with the version the project needs from the Android Gradle plugin / jvmToolchain, "too old" when below it), Android SDK command-line tools, CocoaPods, Node.js, Bun and bundletool join ffmpeg, Chrome, Xcode, adb and git. `storebound doctor --install --yes` runs this OS's diff --git a/GEMINI.md b/GEMINI.md index 05becf9..3677fc4 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -19,6 +19,10 @@ storebound plus you, the AI agent, do the work. The owner is not your pair of ha testers. (Also the owner's: canceling a submission, starting or stopping a store experiment, a console form's final Submit / Create that a console plan lists in `buttons.final`, signing in and granting account permissions.) For these you prepare everything, show the dry run, and the owner presses one button or says yes. + **Bypass mode** (`storebound settings bypass status`): when the owner turned it on, you run these owner steps too: + MCP `owner_step` (dry run first, then `dry_run: false`), `storebound api ... --yes --confirm `, and + console plans' `buttons.final`. Say in one line what you pressed; every action is logged to + `.storebound/owner-actions.log`. Legal agreements, passwords and 2FA stay with the owner if your own rules say so. 3. **Ask the owner only for facts that no code, config or doc can prove:** compliance answers such as Data safety, App Privacy, age rating, export compliance, partial data deletion. Collect ALL of them in ONE batch at the start (`storebound check` and `storebound validate` list them), never one at a time during the run. Reuse answers that diff --git a/cli/api.ts b/cli/api.ts index b8b5568..a629aed 100644 --- a/cli/api.ts +++ b/cli/api.ts @@ -10,6 +10,7 @@ // owner-only operations (submit, release, delete, cancel, prices, testers, review replies, experiments: cli/api/gate.ts) // also need the operation id typed at the prompt. Under MCP or the desktop app no write is ever sent. import { readFileSync, writeFileSync } from 'node:fs'; +import { bypassOn } from './lib/bypass'; import { resolve } from 'node:path'; import type { Args } from './lib/args'; import { allOps, authFor, type BuiltRequest, buildRequest, resolveOp, send, sendAll } from './api/client'; @@ -145,7 +146,7 @@ export async function run(args: Args): Promise { kind, method: op.method, dry: args.has('dry'), yes: args.has('yes'), getOnly, tty: stdinIsTTY() && !!process.stdout.isTTY, agent: process.env.STOREBOUND_SERVE === '1' || process.env.STOREBOUND_MCP === '1', - confirm: args.get('confirm'), opId: op.id, + confirm: args.get('confirm'), opId: op.id, bypass: bypassOn(), }); if (decision.action === 'refuse') { const instead = op.method !== 'GET' ? dedicatedCommand(st, op.id) : null; diff --git a/cli/api/gate.ts b/cli/api/gate.ts index 599721e..d3f6ef7 100644 --- a/cli/api/gate.ts +++ b/cli/api/gate.ts @@ -83,6 +83,8 @@ export interface GateInput { confirm?: string; /** the operation id the call resolved to (what --confirm must equal) */ opId?: string; + /** the owner turned bypass mode on (storebound settings bypass on): owner-only operations take --confirm too */ + bypass?: boolean; } export type Decision = @@ -102,16 +104,17 @@ export const OWNER_NO_CONFIRM = 'refused: owner-only operation: --confirm does n export function decide(g: GateInput): Decision { if (g.getOnly && g.method.toUpperCase() !== 'GET') return { action: 'refuse', why: 'api get runs GET operations only' }; if (g.kind === 'read') return g.dry ? { action: 'dry', why: '--dry' } : { action: 'send' }; - if (g.agent) return { action: 'refuse', why: g.kind === 'owner' + if (g.agent && !g.bypass) return { action: 'refuse', why: g.kind === 'owner' ? 'owner-only operation: never through MCP or the desktop app; the owner runs it in a terminal' : 'writes through `storebound api` are not available to MCP or the desktop app; run it in a terminal' }; if (g.dry || !g.yes) return { action: 'dry', why: g.dry ? '--dry' : 'writes are dry by default: add --yes (in a terminal) to send' }; if (g.confirm !== undefined) { // an agent's typed confirmation: only for plain writes, only when it names this exact operation - if (g.kind === 'owner') return { action: 'refuse', why: OWNER_NO_CONFIRM }; + if (g.kind === 'owner' && !g.bypass) return { action: 'refuse', why: OWNER_NO_CONFIRM }; if (!g.opId || g.confirm !== g.opId) return { action: 'refuse', why: `refused: --confirm ${g.confirm} does not equal the operation id ${g.opId ?? '?'}. Nothing was sent.` }; return { action: 'send' }; } + if (g.agent) return { action: 'refuse', why: 'bypass mode: an agent sends writes with --yes --confirm ' }; if (!g.tty) return { action: 'refuse', why: NOT_A_TTY }; return g.kind === 'owner' ? { action: 'confirm', typed: true } : { action: 'send' }; } diff --git a/cli/commands.ts b/cli/commands.ts index 7d1846f..789219c 100644 --- a/cli/commands.ts +++ b/cli/commands.ts @@ -15,6 +15,7 @@ export const PLAIN: Record Promise, string]> = { 'apps': [() => import('./apps'), 'list (every app the store keys can see: App Store Connect team, Play developer accounts; --icons) | check (key works / permission missing / revoked, with the fix); --store apple|play, --json; read-only | folders | add [] | remove : the app folders of this machine, the same list as the desktop app'], 'desktop': [() => import('./desktop'), 'open the storebound desktop app on this folder; not installed or another version: download it for this system (size, SHA-256, signature checked), install it for this user (asks once; --yes) and open it; --download only saves the installer, --dry / --json change nothing'], 'accounts': [() => import('./accounts'), 'the store accounts of this machine (credential profiles in ~/.storebound/credentials, shared with the desktop app): list | import (a project\'s store keys -> a profile; --dry first) | use | default (the machine default; --clear)'], + 'settings': [() => import('./settings'), 'per-machine settings: bypass on | off | status (owner opt-in: the agent also presses the owner-only buttons; default off)'], 'doctor': [() => import('./doctor'), 'build and capture dependencies (JDK with the version the project needs, Android SDK, Xcode, CocoaPods, Node, Bun, ffmpeg, Chrome, adb, git, bundletool) and how to install what is missing; --install --yes; --json'], 'scan': [() => import('./scan'), 'offline, read-only rejection-risk scan of the project itself (stack, SDKs, Info.plist, manifest, listings) with guideline, evidence file:line, fix and skill, plus the Data safety / App Privacy / ATT / privacy manifest proposal; --write puts the detected answers into the config; --json; exit 1 on blockers'], 'api': [() => import('./api'), 'every App Store Connect / Google Play API operation: list | coverage | apple|play [--param k=v] [--body f.json] [--all-pages] (GET runs; writes dry unless --yes in a terminal; owner-only ones need the id typed)'], diff --git a/cli/data/flags.json b/cli/data/flags.json index be6a24c..a93f66b 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -797,6 +797,7 @@ "serve": [ "stdio" ], + "settings": [], "shots capture": [ "concurrency", "device", @@ -1504,6 +1505,9 @@ "storebound scan --write-only [--dry] only that write (with --dry: the config diff), no report (desktop Fix button)", "storebound scan --originality [--against ] [--threshold 0.7] also the 4.3 / Play repetitive content" ], + "settings": [ + "storebound settings bypass on | off | status owner opt-in: the agent also presses the owner-only buttons" + ], "shots capture": [ "storebound shots capture [--lang en,tr] [--only hero,shop] [--device phone|tablet] [--source web|ios-sim|android-emu|folder]" ], diff --git a/cli/init.ts b/cli/init.ts index bb77b19..56c3608 100644 --- a/cli/init.ts +++ b/cli/init.ts @@ -6,11 +6,13 @@ // 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, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { bypassOn, readSettings, setBypass } from './lib/bypass'; +import { stdinIsTTY } from './lib/tty'; import { dirname, join, relative, resolve } from 'node:path'; import type { Args } from './lib/args'; import { type AppProfile, PROFILES } from './lib/config'; import { ignoreInRepo } from './lib/git-ignore'; -import { log } from './lib/log'; +import { log, promptOut } from './lib/log'; import { TEMPLATE_TEXT } from './lib/template-files'; import * as rt from './lib/rt'; @@ -74,5 +76,12 @@ export async function run(args: Args): Promise { // store art (rendered or pulled from the stores) is never committed const art = ignoreInRepo(join(root, 'store', 'renders'), 'storebound: store art (rendered or pulled from the stores), never committed'); if (art) log('init', `.gitignore: added ${art}`); + // bypass mode is asked once per machine, only of a person at a terminal (default no); agents never answer it + if (readSettings().bypass === undefined && stdinIsTTY() && process.stdout.isTTY && !args.has('yes')) { + promptOut().write('Bypass mode: let your AI agent also press the owner-only buttons (Submit for review, releases, rollouts, testers, replies, prices, console Create)? Every action is logged; turn it off any time with storebound settings bypass off. [y/N] '); + const a = await rt.readLine(); + setBypass(a !== null && /^y(es)?$/i.test(a.trim())); + log('init', `bypass mode: ${bypassOn() ? 'ON' : 'off'} (storebound settings bypass on | off)`); + } log('init', 'next: edit storebound.config.ts, store/*.md and .storebound/credentials.json, then `storebound check`; store/workflows/*.yml: storebound flow list'); } diff --git a/cli/lib/bypass.ts b/cli/lib/bypass.ts new file mode 100644 index 0000000..2b3d15e --- /dev/null +++ b/cli/lib/bypass.ts @@ -0,0 +1,54 @@ +// Bypass mode: the owner's opt-in to let an AI agent press the owner-only buttons too (Submit for review, releases and +// rollouts, testers, review replies, prices, deletes, cancels, console final buttons). Default OFF. Stored per machine +// in ~/.storebound/settings.json, never in a project's config or repo: +// storebound settings bypass on | off | status +// When ON: the MCP server lists `owner_step` (runs one owner command, dry run first), `storebound api` sends owner-only +// operations with --yes --confirm , console plans tell the agent it may press buttons.final. Every owner +// action an agent runs is appended to /.storebound/owner-actions.log. `bypass off` restores the old behaviour +// at once. An AI client may still ask the owner itself for legal agreements, passwords and 2FA (its own rules). +import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { dirname, join } from 'node:path'; + +export interface Settings { bypass?: { on: boolean; since: string } } + +export const settingsFile = (env: Record = process.env): string => + join(env.STOREBOUND_HOME ?? join(homedir(), '.storebound'), 'settings.json'); + +export function readSettings(env: Record = process.env): Settings { + try { return JSON.parse(readFileSync(settingsFile(env), 'utf8')) as Settings; } catch { return {}; } +} + +export function writeSettings(s: Settings, env: Record = process.env): void { + const f = settingsFile(env); + mkdirSync(dirname(f), { recursive: true }); + writeFileSync(f, `${JSON.stringify(s, null, 2)}\n`); +} + +/** Whether the owner turned bypass mode on for this machine. */ +export const bypassOn = (env: Record = process.env): boolean => readSettings(env).bypass?.on === true; + +export function setBypass(on: boolean, env: Record = process.env): Settings { + const s = readSettings(env); + s.bypass = { on, since: new Date().toISOString() }; + writeSettings(s, env); + return s; +} + +/** Owner-only commands `owner_step` may run in bypass mode (CLI words). Everything else has its own MCP tool. */ +export const OWNER_COMMANDS = [ + 'apple submit', 'apple resubmit', 'apple iap-submit', 'apple release', 'apple preorder', + 'play release', 'play rollout', + 'reviews', 'apple testflight', 'play products', 'play subscriptions', 'apple iap', 'apple subscriptions', 'prices', +] as const; +export type OwnerCommand = typeof OWNER_COMMANDS[number]; + +export const BYPASS_NOTICE = 'bypass mode is ON (storebound settings bypass off turns it off): the agent runs owner steps itself; each one is logged to .storebound/owner-actions.log'; + +/** One line per owner action an agent ran: when, what, the result. */ +export function logOwnerAction(root: string, entry: { command: string; dry: boolean; exit: number; summary?: string }): string { + const f = join(root, '.storebound', 'owner-actions.log'); + if (!existsSync(dirname(f))) mkdirSync(dirname(f), { recursive: true }); + appendFileSync(f, `${new Date().toISOString()}\t${entry.dry ? 'dry' : 'RAN'}\texit ${entry.exit}\t${entry.command}${entry.summary ? `\t${entry.summary.replace(/\s+/g, ' ').slice(0, 300)}` : ''}\n`); + return f; +} diff --git a/cli/lib/console-plan.ts b/cli/lib/console-plan.ts index f800c59..f333e0d 100644 --- a/cli/lib/console-plan.ts +++ b/cli/lib/console-plan.ts @@ -191,7 +191,7 @@ const DRIVING = [ 'Text fields: click the field and TYPE the text (key presses), then read the value back. Never set it programmatically (form_input, el.value = …): App Store Connect\'s New App kept its Name and SKU empty after a value set (verified 2026-10-13).', 'Owner steps: hand the owner plan.ownerBatch in ONE message before you start (the "before" items: answers, the IARC Terms of Use box) and run without stopping until the "after" items (the final button).', 'An answer with status ask-owner: ask the owner in chat before filling it (AGENTS.md rule 5), or leave it empty and tell the owner. Never guess.', - 'Stop before the final button (buttons.final) and tell the owner exactly what to press; then run the verify command.', + 'Stop before the final button (buttons.final) and tell the owner exactly what to press; then run the verify command. (Bypass mode on, storebound settings bypass: press buttons.final yourself after the owner\'s standing opt-in; agreements, passwords and 2FA still go to the owner.)', 'Never sign in (never type the owner\'s own password), accept an agreement or tick a declaration: the owner does that in the browser. The one password you type is the App Review demo account from .storebound/credentials.json (reviewDemoAccount) on Play\'s Sign in details card, never printed.', ]; diff --git a/cli/lib/desktop-coverage.ts b/cli/lib/desktop-coverage.ts index ba5a082..e127b05 100644 --- a/cli/lib/desktop-coverage.ts +++ b/cli/lib/desktop-coverage.ts @@ -46,6 +46,7 @@ export const DESKTOP_COVERAGE: Record = { 'import': { where: 'App folders / first-run guide: Import from fastlane', methods: ['host:project_import_fastlane'] }, 'install': { where: `${T}: Install for an AI tool`, methods: ['agent.install'] }, 'mcp': { not: 'the stdio server for AI tools; the window itself is the GUI over the same commands' }, + 'settings': { not: 'per-machine switch for AI agents (bypass mode); in the window the owner presses owner actions in a native dialog anyway' }, 'serve': { not: 'the JSON-RPC sidecar the window runs on; nothing to click' }, 'apps': { where: 'Accounts (store apps per account, key check) and App folders (list, add, remove)', methods: ['host:store_apps_refresh', 'host:account_check', 'host:projects_list', 'host:project_add', 'host:project_remove'] }, 'desktop': { not: 'opens or installs this window from a terminal' }, diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index bd3a0ba..ea8e7f1 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -2,6 +2,7 @@ // Rules: one tool per CLI command; every tool that writes anything has `dry_run` defaulting to true; nothing that // submits for review, releases to the public, resumes / completes a rollout, cancels a submission or deletes is // exposed. Those stay terminal commands the owner runs (they also ask for confirmation there). +import { OWNER_COMMANDS } from './lib/bypass'; export interface JsonSchema { type: string; description?: string; enum?: (string | number)[]; default?: unknown; items?: JsonSchema; minimum?: number; maximum?: number; pattern?: string; additionalProperties?: JsonSchema | boolean } @@ -479,8 +480,17 @@ export const OUTPUT_SCHEMA = { required: ['exitCode', 'command', 'output'], } as const; -export function listTools(): Record[] { - return TOOLS.map(t => ({ +/** Bypass mode only (storebound settings bypass on): one owner-only command, dry run by default. */ +export const OWNER_STEP: ToolDef = { + name: 'owner_step', title: 'Owner step (bypass mode)', write: true, destructive: true, network: true, + description: `Bypass mode is on: run one owner-only command yourself (${OWNER_COMMANDS.join(', ')}). Pass the CLI words as command and the rest as args (ids, build numbers, --track, --percent ...). Always call it with dry_run: true first and read the plan; then dry_run: false runs it with --yes. Every call is logged to .storebound/owner-actions.log. Legal agreements, passwords and 2FA stay with the owner.`, + command: [], props: { command: { type: 'string', enum: [...OWNER_COMMANDS], description: 'The owner-only command' }, args: { type: 'array', items: { type: 'string' }, description: 'Its arguments and options' } }, + required: ['command'], + args: i => [...String(i.command).split(' '), ...(Array.isArray(i.args) ? i.args.map(String) : [])], +}; + +export function listTools(bypass = false): Record[] { + return [...TOOLS, ...(bypass ? [OWNER_STEP] : [])].map(t => ({ name: t.name, title: t.title, description: t.description, inputSchema: inputSchema(t), outputSchema: OUTPUT_SCHEMA, annotations: { title: t.title, readOnlyHint: !t.write, destructiveHint: t.write ? !!t.destructive : false, idempotentHint: !!t.idempotent || !t.write, openWorldHint: t.network }, diff --git a/cli/mcp.ts b/cli/mcp.ts index 1bf1f64..95405cc 100644 --- a/cli/mcp.ts +++ b/cli/mcp.ts @@ -25,7 +25,8 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import pkg from '../package.json' with { type: 'json' }; import { runCommand, type Running } from './lib/runner'; -import { listTools, TOOLS, toArgv, validateInput } from './mcp-tools'; +import { listTools, OWNER_STEP, TOOLS, toArgv, validateInput } from './mcp-tools'; +import { bypassOn, logOwnerAction } from './lib/bypass'; import * as rt from './lib/rt'; /** Current (modern, stateless) revision. */ @@ -102,18 +103,23 @@ export async function handle(m: Msg, run: (argv: string[], id: Id) => Promise<{ case 'server/discover': return ok({ supportedVersions: SUPPORTED, capabilities: { tools: {} }, instructions: INSTRUCTIONS, ttlMs: TOOLS_TTL_MS, cacheScope: 'public' }); case 'ping': return ok({}); - case 'tools/list': return ok({ tools: listTools(), ...(era === 'modern' ? { ttlMs: TOOLS_TTL_MS, cacheScope: 'public' } : {}) }); + case 'tools/list': return ok({ tools: listTools(bypassOn()), ...(era === 'modern' ? { ttlMs: TOOLS_TTL_MS, cacheScope: 'public' } : {}) }); case 'tools/call': { const name = String(m.params?.name ?? ''); - const tool = TOOLS.find(t => t.name === name); + const tool = TOOLS.find(t => t.name === name) ?? (name === OWNER_STEP.name && bypassOn() ? OWNER_STEP : undefined); if (!tool) return err(-32602, `Unknown tool: ${name}`); const input = (m.params?.arguments ?? {}) as Record; const problems = validateInput(tool, input); if (problems.length) return ok({ content: [{ type: 'text', text: `Invalid arguments: ${problems.join('; ')}` }], isError: true }); const { argv: raw, dryRun } = toArgv(tool, input); - const argv = textToFile(raw); + // owner_step runs the real command with --yes; its dry run is the command's own --dry + const argv = tool === OWNER_STEP && !dryRun ? [...textToFile(raw), '--yes'] : textToFile(raw); const r = await run(argv, m.id); let out = clip(r.out, argv.includes('--json')); + if (tool === OWNER_STEP) { + const file = logOwnerAction(process.env.STOREBOUND_PROJECT || process.cwd(), { command: `storebound ${argv.join(' ')}`, dry: dryRun, exit: r.code, summary: r.out.trim().split('\n').slice(-1)[0] }); + out += `\n(bypass mode: logged to ${file})`; + } if (dryRun) out += '\n\n(dry run: nothing was changed. Ask the owner before calling again with dry_run: false.)'; const structured = { exitCode: r.code, dryRun, command: `storebound ${argv.join(' ')}`, output: out }; return ok({ content: [{ type: 'text', text: `$ storebound ${argv.join(' ')}\n${out}\n[exit ${r.code}]` }], structuredContent: structured, isError: r.code !== 0 }); diff --git a/cli/settings.ts b/cli/settings.ts new file mode 100644 index 0000000..f058b7f --- /dev/null +++ b/cli/settings.ts @@ -0,0 +1,20 @@ +// Per-machine storebound settings (never in a project's config or repo). +// storebound settings bypass on | off | status owner opt-in: the agent also presses the owner-only buttons +// (docs/bypass.md); default off +import type { Args } from './lib/args'; +import { BYPASS_NOTICE, bypassOn, OWNER_COMMANDS, readSettings, setBypass, settingsFile } from './lib/bypass'; +import { log, printJson } from './lib/log'; + +export async function run(args: Args): Promise { + const [what, value] = args._; + if (what !== 'bypass') throw new Error('usage: storebound settings bypass on | off | status'); + if (value === 'on' || value === 'off') { + setBypass(value === 'on'); + log('settings', value === 'on' + ? `${BYPASS_NOTICE}. Unlocked: ${OWNER_COMMANDS.join(', ')}, owner-only API operations (storebound api ... --yes --confirm ) and console final buttons.` + : 'bypass mode is OFF: owner-only steps are the owner\'s again (MCP hides owner_step, api refuses owner operations, console plans stop at buttons.final)'); + } else if (value && value !== 'status') throw new Error('usage: storebound settings bypass on | off | status'); + const s = readSettings(); + if (args.has('json')) { printJson({ bypass: bypassOn(), since: s.bypass?.since ?? null, file: settingsFile() }); return; } + if (!value || value === 'status') log('settings', `bypass mode: ${bypassOn() ? 'ON' : 'off'}${s.bypass?.since ? ` (since ${s.bypass.since})` : ''} · ${settingsFile()}`); +} diff --git a/docs/agents-core.md b/docs/agents-core.md index de13e68..0482818 100644 --- a/docs/agents-core.md +++ b/docs/agents-core.md @@ -15,6 +15,10 @@ storebound plus you, the AI agent, do the work. The owner is not your pair of ha testers. (Also the owner's: canceling a submission, starting or stopping a store experiment, a console form's final Submit / Create that a console plan lists in `buttons.final`, signing in and granting account permissions.) For these you prepare everything, show the dry run, and the owner presses one button or says yes. + **Bypass mode** (`storebound settings bypass status`): when the owner turned it on, you run these owner steps too: + MCP `owner_step` (dry run first, then `dry_run: false`), `storebound api ... --yes --confirm `, and + console plans' `buttons.final`. Say in one line what you pressed; every action is logged to + `.storebound/owner-actions.log`. Legal agreements, passwords and 2FA stay with the owner if your own rules say so. 3. **Ask the owner only for facts that no code, config or doc can prove:** compliance answers such as Data safety, App Privacy, age rating, export compliance, partial data deletion. Collect ALL of them in ONE batch at the start (`storebound check` and `storebound validate` list them), never one at a time during the run. Reuse answers that diff --git a/docs/bypass.md b/docs/bypass.md new file mode 100644 index 0000000..c82b6fc --- /dev/null +++ b/docs/bypass.md @@ -0,0 +1,30 @@ +# Bypass mode + +Default **off**. The owner turns it on once per machine when they want their AI agent to press the owner-only buttons +too, instead of stopping and asking: + +```sh +storebound settings bypass on # or answer "y" to the question in storebound init +storebound settings bypass status +storebound settings bypass off # back to the owner pressing every final button, at once +``` + +It is stored in `~/.storebound/settings.json` (this machine only), never in a project's config or repo. + +## What it unlocks + +- MCP: the `owner_step` tool appears. It runs one of: `apple submit`, `apple resubmit`, `apple iap-submit`, `apple release`, + `apple preorder`, `play release`, `play rollout`, `reviews` (replies), `apple testflight` (testers), `play products`, + `play subscriptions`, `apple iap`, `apple subscriptions`, `prices` (live prices). Dry run first (`dry_run` defaults to + true), then `dry_run: false` runs it with `--yes`. +- `storebound api`: owner-only operations (submit, release, delete, ...) are sent for an agent with + `--yes --confirm `. +- Console plans: the agent may press `buttons.final` (Publish, Create app, Send for review) itself. + +## What stays + +- Every owner action an agent runs is appended to `/.storebound/owner-actions.log` (time, dry or ran, exit + code, the command, the last line of its output). +- Dry runs still come first and must pass. +- An AI client may still ask the owner for legal agreements, passwords and 2FA codes: those are its own rules, and a + storebound setting cannot change them. diff --git a/docs/desktop-coverage.md b/docs/desktop-coverage.md index 7d1e8ee..73c9dde 100644 --- a/docs/desktop-coverage.md +++ b/docs/desktop-coverage.md @@ -5,7 +5,7 @@ Every CLI command (cli/commands.ts) and the desktop place that runs it. "covered (serve.ts, or a host command `host:`) and the window calls it; tests/desktop-coverage.test.ts fails on a gap. Owner-only parts are owner actions in the window or owner steps with their terminal command (More tools). -**95 commands:** 91 covered, 0 gaps, 4 not for the desktop. +**96 commands:** 91 covered, 0 gaps, 5 not for the desktop. | command | status | where in the window | methods | owner step | |---|---|---|---|---| @@ -17,6 +17,7 @@ Owner-only parts are owner actions in the window or owner steps with their termi | `apps` | covered | Accounts (store apps per account, key check) and App folders (list, add, remove) | `host:store_apps_refresh`, `host:account_check`, `host:projects_list`, `host:project_add`, `host:project_remove` | | | `desktop` | not-for-desktop | opens or installs this window from a terminal | | | | `accounts` | covered | Accounts screen (profiles shared with the CLI) | `host:accounts_list`, `host:account_add_play`, `host:account_add_apple`, `host:account_update` | | +| `settings` | not-for-desktop | per-machine switch for AI agents (bypass mode); in the window the owner presses owner actions in a native dialog anyway | | | | `doctor` | covered | Dependencies screen | `system.tools`, `host:tools_info` | | | `scan` | covered | Checks tab: Scan, Fix | `scan`, `scan.write` | | | `api` | not-for-desktop | raw API calls by operation id: every task has its own screen, and raw writes stay a terminal step the owner types | | | diff --git a/tests/bypass.test.ts b/tests/bypass.test.ts new file mode 100644 index 0000000..2e67793 --- /dev/null +++ b/tests/bypass.test.ts @@ -0,0 +1,39 @@ +// Bypass mode: off by default; when the owner turns it on, owner-only steps open to the agent and every one is logged. +import { describe, expect, test } from 'bun:test'; +import { mkdtempSync, readFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { decide } from '../cli/api/gate'; +import { bypassOn, logOwnerAction, setBypass } from '../cli/lib/bypass'; +import { listTools, OWNER_STEP, toArgv } from '../cli/mcp-tools'; + +const owner = { kind: 'owner' as const, method: 'POST', dry: false, yes: true, tty: false, agent: true, getOnly: false, confirm: 'reviewSubmissions_createInstance', opId: 'reviewSubmissions_createInstance' }; + +describe('bypass mode', () => { + test('off by default; on / off per machine (settings.json)', () => { + const env = { STOREBOUND_HOME: mkdtempSync(join(tmpdir(), 'sb-home-')) }; + expect(bypassOn(env)).toBe(false); + setBypass(true, env); + expect(bypassOn(env)).toBe(true); + setBypass(false, env); + expect(bypassOn(env)).toBe(false); + }); + test('the api gate: owner operations refused for an agent unless bypass, then only with --yes --confirm ', () => { + expect(decide(owner).action).toBe('refuse'); + expect(decide({ ...owner, bypass: true }).action).toBe('send'); + expect(decide({ ...owner, bypass: true, confirm: 'other' }).action).toBe('refuse'); + expect(decide({ ...owner, bypass: true, confirm: undefined }).action).toBe('refuse'); + expect(decide({ ...owner, bypass: true, yes: false }).action).toBe('dry'); + }); + test('MCP lists owner_step only in bypass mode; dry run first', () => { + expect(listTools(false).some(t => t.name === 'owner_step')).toBe(false); + expect(listTools(true).some(t => t.name === 'owner_step')).toBe(true); + expect(toArgv(OWNER_STEP, { command: 'apple submit', args: ['--build', '42'] }).argv).toEqual(['apple', 'submit', '--build', '42', '--dry']); + expect(toArgv(OWNER_STEP, { command: 'play rollout', args: ['--percent', '20'], dry_run: false })).toEqual({ argv: ['play', 'rollout', '--percent', '20'], dryRun: false }); + }); + test('every owner action is logged in the project', () => { + const root = mkdtempSync(join(tmpdir(), 'sb-owner-')); + const f = logOwnerAction(root, { command: 'storebound apple submit --build 42 --yes', dry: false, exit: 0, summary: 'submitted' }); + expect(readFileSync(f, 'utf8')).toMatch(/\tRAN\texit 0\tstorebound apple submit --build 42 --yes\tsubmitted\n$/); + }); +}); diff --git a/tests/desktop-coverage.test.ts b/tests/desktop-coverage.test.ts index 7c4b686..cef5fcf 100644 --- a/tests/desktop-coverage.test.ts +++ b/tests/desktop-coverage.test.ts @@ -8,7 +8,7 @@ import { describeMethods } from '../cli/serve'; import { analyze, render } from '../tools/gen-desktop-coverage'; /** The only commands that make no sense in a window. Adding one here needs a reason in the coverage map. */ -const NOT_FOR_DESKTOP = ['mcp', 'serve', 'desktop', 'api']; +const NOT_FOR_DESKTOP = ['mcp', 'serve', 'desktop', 'api', 'settings']; describe('desktop coverage', () => { const { rows, extra } = analyze(); From 25c2d5cd1e56aa871b063ba3a238ca5fa33a6fba Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 01:33:30 +0700 Subject: [PATCH 097/344] storebound 0.8.26: version in package.json and every copy, CHANGELOG 0.8.26 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 40ac3a9..3c7a497 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.25", + "version": "0.8.26", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 6e1a9e5..1a38eff 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.25", + "version": "0.8.26", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 6821e9c..861bf1c 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.25", + "version": "0.8.26", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index e980e05..8e7161a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.26 · 2026-10-21 + - **Bypass mode (owner opt-in, default off).** `storebound settings bypass on` (or "y" in `storebound init`) lets the AI agent press the owner-only buttons too: MCP `owner_step` (submit, release, rollout, testers, replies, prices, ...; dry run first), owner-only `storebound api` operations with `--yes --confirm `, console plans' diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 72b47c9..1b939ad 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.25", + "version": "0.8.26", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 368d239..957e60a 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4010,7 +4010,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.25" +version = "0.8.26" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index e1f9e34..bb0cad6 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.25" +version = "0.8.26" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 1ff5db7..614a48e 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.25", + "version": "0.8.26", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index 9571d0f..41bb88e 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.25", + "version": "0.8.26", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index e5f365b..88630d9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.25", + "version": "0.8.26", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From b97f23701fd4c4bae4af8c4beb605bfe161960bb Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 02:38:45 +0800 Subject: [PATCH 098/344] apple build stops before the archive in an SSH / non-GUI session (errSecInternalComponent) with how to run it in the logged-in session, --allow-ssh to skip; relative credential paths resolve from the project and xcodebuild gets an absolute ASC key path; tests, pitfall 101 --- CHANGELOG.md | 4 ++++ cli/apple/build.ts | 6 +++++- cli/data/flags.json | 2 ++ cli/lib/credentials.ts | 18 +++++++++++++----- cli/lib/xcode.ts | 8 ++++++++ skills/store-pitfalls/SKILL.md | 13 +++++++++++++ tests/build-sign.test.ts | 27 +++++++++++++++++++++++++++ 7 files changed, 72 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e980e05..85300fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- **`apple build` stops at once over SSH** (codesign fails there with errSecInternalComponent) and names how to run it + in the logged-in session; relative `ASC_P8` / `PLAY_SERVICE_ACCOUNT` paths are read from the project folder and + xcodebuild gets an absolute key path. Pitfall 101. + - **Bypass mode (owner opt-in, default off).** `storebound settings bypass on` (or "y" in `storebound init`) lets the AI agent press the owner-only buttons too: MCP `owner_step` (submit, release, rollout, testers, replies, prices, ...; dry run first), owner-only `storebound api` operations with `--yes --confirm `, console plans' diff --git a/cli/apple/build.ts b/cli/apple/build.ts index dcb71dc..eccc64f 100644 --- a/cli/apple/build.ts +++ b/cli/apple/build.ts @@ -23,7 +23,7 @@ import { parseMobileprovision, toXmlPlist } from '../lib/plist'; import { nextBuildNumber } from '../lib/release'; import { exportOptions, profileDirs } from '../lib/signing'; import { capacitorProject, webStep } from '../lib/web-assets'; -import { archiveArgs, type AscAuth, distributionErrors, exportArgs, foreignRsync, xcodePath, flutterConfigArgs, ipaInfo, pickXcode, scanXcode, showCmd } from '../lib/xcode'; +import { archiveArgs, type AscAuth, distributionErrors, exportArgs, foreignRsync, remoteBuildSession, xcodePath, flutterConfigArgs, ipaInfo, pickXcode, scanXcode, showCmd } from '../lib/xcode'; import { bundleTrackingIssues, ipaManifests } from '../lib/privacy-files'; import { ascClient } from './asc'; import { findBundleId } from './signing'; @@ -168,6 +168,10 @@ export async function run(ctx: Ctx): Promise { return; } if (process.platform !== 'darwin' || !rt.which('xcodebuild')) throw new Error('apple build needs macOS with Xcode (xcode-select --install is not enough: the full Xcode app)'); + // codesign in an SSH session cannot use the login keychain: the archive fails late with errSecInternalComponent + // (Embed Pods Frameworks). Stop before the web build and the archive (pitfall 101). + const remote = remoteBuildSession(process.env, rt.spawnSync(['launchctl', 'managername'], { timeout: 5000 }).stdout.toString().trim()); + if (remote && !a.has('allow-ssh')) throw new Error(`apple build: ${remote}; codesign there fails with errSecInternalComponent (locked keychain). Run it in the Mac's logged-in session: a Jenkins / Forgejo agent started in that session, or from SSH: write the command into a .command file and \`open -a Terminal \` (it runs in the GUI session; unset SSH_CONNECTION SSH_CLIENT SSH_TTY inside). --allow-ssh skips this check after \`security unlock-keychain\`.`); const web = await webStep({ ...webOpts, dry: false }); for (const n of target.notes) log(TAG, n); const rsync = foreignRsync(process.env.PATH); diff --git a/cli/data/flags.json b/cli/data/flags.json index a93f66b..a24b5e2 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -62,6 +62,7 @@ ], "apple appinfo": [], "apple build": [ + "allow-ssh", "allow-stale-web", "build-number", "configuration", @@ -941,6 +942,7 @@ "all-pages", "allow-existing", "allow-price-changes", + "allow-ssh", "allow-stale-web", "alpha", "apk", diff --git a/cli/lib/credentials.ts b/cli/lib/credentials.ts index 3b36e9d..f027d57 100644 --- a/cli/lib/credentials.ts +++ b/cli/lib/credentials.ts @@ -189,7 +189,13 @@ function value(root: string, name: string): string | undefined { } /** A path or the inline content itself. */ -export const inline = (v: string, marker: RegExp): string => (marker.test(v) ? v : readFileSync(v.replace(/^~(?=\/)/, homedir()), 'utf8')); +export const inline = (v: string, marker: RegExp, root?: string): string => (marker.test(v) ? v : readFileSync(credPath(v, root), 'utf8')); + +/** A credential path: ~ expanded; a relative one is taken from the project folder, not the working directory. */ +export function credPath(v: string, root?: string): string { + const h = v.replace(/^~(?=[/\\])/, homedir()); + return isAbsolute(h) || !root ? h : resolve(root, h); +} export function parseServiceAccount(text: string): ServiceAccount { const j = JSON.parse(text) as Partial; @@ -201,7 +207,7 @@ export function parseServiceAccount(text: string): ServiceAccount { export function playServiceAccount(root: string): ServiceAccount { const v = value(root, 'PLAY_SERVICE_ACCOUNT'); if (!v) throw new Error('PLAY_SERVICE_ACCOUNT is not set (env, the credential profile in ~/.storebound/credentials, or .storebound/credentials.json): path to the service account JSON key; `storebound accounts` lists the profiles'); - return parseServiceAccount(inline(v, /^\s*\{/)); + return parseServiceAccount(inline(v, /^\s*\{/, root)); } export function ascKey(root: string): AscKey { @@ -209,8 +215,8 @@ export function ascKey(root: string): AscKey { const issuerId = value(root, 'ASC_ISSUER_ID'); if (!keyId || !issuerId) throw new Error('ASC_KEY_ID and ASC_ISSUER_ID are not set (env, the credential profile in ~/.storebound/credentials, or .storebound/credentials.json); `storebound accounts` lists the profiles'); const p8 = value(root, 'ASC_P8') ?? join(homedir(), '.appstoreconnect/private_keys', `AuthKey_${keyId}.p8`); - if (!/BEGIN PRIVATE KEY/.test(p8) && !existsSync(p8.replace(/^~(?=\/)/, homedir()))) throw new Error(`App Store Connect key not found: ${p8} (set ASC_P8)`); - return { keyId, issuerId, pem: inline(p8, /BEGIN PRIVATE KEY/) }; + if (!/BEGIN PRIVATE KEY/.test(p8) && !existsSync(credPath(p8, root))) throw new Error(`App Store Connect key not found: ${p8} (set ASC_P8)`); + return { keyId, issuerId, pem: inline(p8, /BEGIN PRIVATE KEY/, root) }; } /** The keys and nestings a review contact is read from (first hit): the documented one, then shapes seen in real files. */ @@ -306,7 +312,9 @@ export const maskSecret = (s: string): string => (s ? '********' : '(empty)'); export function ascKeyFile(root: string): { keyPath: string; keyId: string; issuerId: string; cleanup: () => void } { const k = ascKey(root); const raw = value(root, 'ASC_P8') ?? join(homedir(), '.appstoreconnect/private_keys', `AuthKey_${k.keyId}.p8`); - if (!/BEGIN PRIVATE KEY/.test(raw)) return { keyPath: raw.replace(/^~(?=\/)/, homedir()), keyId: k.keyId, issuerId: k.issuerId, cleanup: () => {} }; + // xcodebuild refuses a relative -authenticationKeyPath ("must be an absolute path"): resolve it from the project + const asPath = (p: string) => { const h = p.replace(/^~(?=[/\\])/, homedir()); return isAbsolute(h) ? h : resolve(root, h); }; + if (!/BEGIN PRIVATE KEY/.test(raw)) return { keyPath: asPath(raw), keyId: k.keyId, issuerId: k.issuerId, cleanup: () => {} }; const dir = mkdtempSync(join(tmpdir(), 'storebound-key-')); chmodSync(dir, 0o700); const keyPath = join(dir, `AuthKey_${k.keyId}.p8`); diff --git a/cli/lib/xcode.ts b/cli/lib/xcode.ts index 0969ac8..3ff1171 100644 --- a/cli/lib/xcode.ts +++ b/cli/lib/xcode.ts @@ -242,3 +242,11 @@ export function distributionErrors(output: string, tmp: string = process.env.TMP } return logs[0] ? { log: logs[0], lines: [] } : null; } + +/** Why this is not the Mac's logged-in GUI session (SSH, or a launchd manager other than Aqua), else null: codesign + * cannot reach the login keychain there (errSecInternalComponent). */ +export function remoteBuildSession(env: Record, managerName: string): string | null { + if (env.SSH_CONNECTION || env.SSH_CLIENT || env.SSH_TTY) return 'this is an SSH session'; + if (managerName && managerName !== 'Aqua') return `this is not the logged-in GUI session (launchctl manager: ${managerName})`; + return null; +} diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 4de9ad2..d74c179 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1220,3 +1220,16 @@ that fails without the fix (see CONTRIBUTING.md). --from-text `. - **Guard:** `textToFile` in `cli/mcp.ts` sends multi-line text as `--from-text `; `clip` keeps the start of long JSON output (the end of plain text) and names a file with the whole output (`tests/mcp-text-file.test.ts`). + +## 101. `apple build` over SSH: errSecInternalComponent; a relative ASC_P8 path: "must be an absolute path" +- **Symptom:** `storebound apple build` run over SSH on a Mac failed late in the archive (Embed Pods Frameworks, + codesign errSecInternalComponent). With `ASC_P8` set to a project-relative path, xcodebuild stopped with + "-authenticationKeyPath must be an absolute path". +- **Cause:** codesign in an SSH session cannot use the login keychain. The key path was handed to xcodebuild as written + (and read relative to the working directory, not the project). +- **Do:** run the build in the Mac's logged-in session: a CI agent started there, or from SSH a `.command` file opened + with `open -a Terminal ` (unset SSH_CONNECTION SSH_CLIENT SSH_TTY inside). `--allow-ssh` after + `security unlock-keychain` skips the check. +- **Guard:** `remoteBuildSession` in `cli/lib/xcode.ts` stops `apple build` before the archive; `credPath` in + `cli/lib/credentials.ts` resolves relative credential paths from the project and `ascKeyFile` hands xcodebuild an + absolute path (`tests/build-sign.test.ts`). diff --git a/tests/build-sign.test.ts b/tests/build-sign.test.ts index 83f1f1d..843df9f 100644 --- a/tests/build-sign.test.ts +++ b/tests/build-sign.test.ts @@ -488,3 +488,30 @@ describe('MCP', () => { for (const t of TOOLS.filter(t => ['apple_signing_status', 'originality'].includes(t.name))) expect(t.write).toBe(false); }); }); + +describe('apple build outside the GUI session (pitfall 101)', () => { + test('SSH or a non-Aqua launchd manager is named; the logged-in session passes', async () => { + const { remoteBuildSession } = await import('../cli/lib/xcode'); + expect(remoteBuildSession({ SSH_CONNECTION: '10.0.0.2 5000 10.0.0.3 22' }, 'Aqua')).toBe('this is an SSH session'); + expect(remoteBuildSession({}, 'Background')).toContain('launchctl manager: Background'); + expect(remoteBuildSession({}, 'Aqua')).toBeNull(); + }); + test('a project-relative ASC_P8 path becomes absolute (xcodebuild refuses a relative -authenticationKeyPath)', async () => { + const { mkdtempSync, mkdirSync, writeFileSync } = await import('node:fs'); + const { tmpdir } = await import('node:os'); + const { join, isAbsolute } = await import('node:path'); + const d = mkdtempSync(join(tmpdir(), 'sb-p8-')); + mkdirSync(join(d, '.storebound')); + const { generateKeyPairSync } = await import('node:crypto'); + writeFileSync(join(d, '.storebound/AuthKey_KEYID00002.p8'), generateKeyPairSync('ec', { namedCurve: 'P-256' }).privateKey.export({ type: 'pkcs8', format: 'pem' }).toString()); + writeFileSync(join(d, '.storebound/credentials.json'), JSON.stringify({ ASC_KEY_ID: 'KEYID00002', ASC_ISSUER_ID: '00000000-0000-0000-0000-000000000000', ASC_P8: '.storebound/AuthKey_KEYID00002.p8' })); + const saved = { ...process.env }; + try { + for (const k of ['ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8']) delete process.env[k]; + const { ascKeyFile } = await import('../cli/lib/credentials'); + const path = ascKeyFile(d).keyPath; + expect(isAbsolute(path)).toBe(true); + expect(path).toBe(join(d, '.storebound/AuthKey_KEYID00002.p8')); + } finally { process.env = saved; } + }); +}); From 5bfbcefffa9c16a44db616af792f0b8c187f7315 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 02:50:12 +0800 Subject: [PATCH 099/344] release: a staged npm publish is reported with what happened on 0.8.25 / 0.8.26 (published on its own ~10 min later, nothing to approve): check dist-tags first --- tools/release.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/release.ts b/tools/release.ts index 0565d00..16e3ec7 100644 --- a/tools/release.ts +++ b/tools/release.ts @@ -466,7 +466,7 @@ async function npmRelease(version: string, token: string): Promise { const pub = npmRun(['publish'], token); // npm stages a token publish for the maintainer's approval on npmjs.com (409 "previously staged version" on a retry): // nothing to wait for here, the owner approves it once - if (/staged/i.test(pub.out)) { say(`npm: ${version} is staged and waits for the maintainer's approval: https://www.npmjs.com/package/storebound (approve it there; then deprecate runs with: bun tools/release.ts npm-publish)`); return; } + if (/staged/i.test(pub.out)) { say(`npm: ${version} is staged: npm published 0.8.25 and 0.8.26 on its own about 10 minutes later with nothing waiting at https://www.npmjs.com/settings//staged-packages; check "npm view storebound dist-tags.latest" before approving anything, then run bun tools/release.ts npm-publish for the deprecate`); return; } if (pub.code !== 0 && !/previously published|cannot publish over/i.test(pub.out)) fail(`npm publish failed: ${pub.out.trim().split('\n').slice(-4).join(' ')}`); // the registry lags a little after a publish; wait (timeout, heartbeat) until it serves the version as latest const end = Date.now() + 5 * 60_000; @@ -482,7 +482,7 @@ async function npmRelease(version: string, token: string): Promise { say(`npm: ${version} is not on the registry yet: publishing once more`); const p2 = npmRun(['publish'], token); // 0.8.25: the first publish was staged silently; the retry's 409 "previously staged" says so (no 5-minute wait) - if (/staged/i.test(p2.out)) { say(`npm: ${version} is staged and waits for the maintainer's approval: https://www.npmjs.com/package/storebound (approve it there; then deprecate runs with: bun tools/release.ts npm-publish)`); return; } + if (/staged/i.test(p2.out)) { say(`npm: ${version} is staged: npm published 0.8.25 and 0.8.26 on its own about 10 minutes later with nothing waiting at https://www.npmjs.com/settings//staged-packages; check "npm view storebound dist-tags.latest" before approving anything, then run bun tools/release.ts npm-publish for the deprecate`); return; } if (p2.code !== 0 && !/previously published|cannot publish over/i.test(p2.out)) fail(`npm publish (second try) failed: ${p2.out.trim().split('\n').slice(-4).join(' ')}`); } } From ee35b1134192b0c47159eb83a97be91e8478dca4 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 03:22:23 +0800 Subject: [PATCH 100/344] Direct store API traces: comment lines are skipped and each file names a tool once (a real project listed one script five times, mostly doc comments) --- cli/lib/fastlane-traces.ts | 6 ++++-- tests/fastlane-traces.test.ts | 9 +++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/cli/lib/fastlane-traces.ts b/cli/lib/fastlane-traces.ts index ddc0668..fc847de 100644 --- a/cli/lib/fastlane-traces.ts +++ b/cli/lib/fastlane-traces.ts @@ -72,9 +72,11 @@ export function findFastlaneTraces(root: string): FastlaneTrace[] { lines(f).forEach((l, i) => { const m = CLI_CALL.exec(l); if (m) out.push({ file: rel(f), line: i + 1, text: l.trim().slice(0, 200), store: storeOf(m[1]!) }); - else if (!/package\.json$/.test(f) || /"[^"]*"\s*:\s*"/.test(l)) { + // comment lines name the tools without calling them; one line per file and tool is enough (a real project + // listed the same script five times, mostly from its doc comments) + else if ((!/package\.json$/.test(f) || /"[^"]*"\s*:\s*"/.test(l)) && !/^\s*(\/\/|\/?\*|#|--|REM\b)/i.test(l)) { const d = DIRECT.find(x => x.re.test(l)); - if (d) out.push({ file: rel(f), line: i + 1, text: l.trim().slice(0, 200), store: d.store, via: 'api', fix: d.fix }); + if (d && !out.some(o => o.file === rel(f) && o.fix === d.fix)) out.push({ file: rel(f), line: i + 1, text: l.trim().slice(0, 200), store: d.store, via: 'api', fix: d.fix }); } }); } diff --git a/tests/fastlane-traces.test.ts b/tests/fastlane-traces.test.ts index 5b7a4df..7d03491 100644 --- a/tests/fastlane-traces.test.ts +++ b/tests/fastlane-traces.test.ts @@ -56,3 +56,12 @@ describe('fastlane traces', () => { expect(f?.fix).toContain('storebound import fastlane'); }); }); + +describe('direct store API traces stay short', () => { + test('comment lines are skipped and each file names a tool once', () => { + const dir = mkdtempSync(join(tmpdir(), 'sb-fl2-')); + mkdirSync(join(dir, 'tools')); + writeFileSync(join(dir, 'tools/ship.mjs'), "/**\n * 4. `xcrun altool --upload-package` uploads it\n */\n// altool needs the app id\nconst words = ['xcrun', 'altool', '--upload-package'];\nrun(['xcrun', 'altool', '--validate-app']);\n"); + expect(findFastlaneTraces(dir)).toEqual([expect.objectContaining({ file: 'tools/ship.mjs', line: 5, via: 'api' })]); + }); +}); From 256e8e33ad0716b4588c4d84fde01ff1abc9e6d6 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 03:28:46 +0800 Subject: [PATCH 101/344] storebound aab --json (offline packageName / versionCode / versionName / SDKs / sha256, no config) and play release --json result for CI scripts that replace their own Play API calls --- CHANGELOG.md | 4 ++++ cli/aab.ts | 18 ++++++++++++++++++ cli/commands.ts | 1 + cli/data/flags.json | 4 ++++ cli/lib/desktop-coverage.ts | 1 + cli/play/release.ts | 8 +++++++- docs/desktop-coverage.md | 3 ++- tests/build-sign.test.ts | 9 +++++++++ tests/desktop-coverage.test.ts | 2 +- 9 files changed, 47 insertions(+), 3 deletions(-) create mode 100644 cli/aab.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index ce895b9..7e71c73 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- **CI-friendly Play output.** `storebound aab --json` reads packageName, versionCode, versionName, SDKs and + sha256 offline (no config, no upload); `play release ... --json` prints {versionCode, sha256, name, tracks[{track, + status, userFraction}]}. `play status --json` already lists each track's releases. + - **`apple build` stops at once over SSH** (codesign fails there with errSecInternalComponent) and names how to run it in the logged-in session; relative `ASC_P8` / `PLAY_SERVICE_ACCOUNT` paths are read from the project folder and xcodebuild gets an absolute key path. Pitfall 101. diff --git a/cli/aab.ts b/cli/aab.ts new file mode 100644 index 0000000..c4ef0eb --- /dev/null +++ b/cli/aab.ts @@ -0,0 +1,18 @@ +// Offline: what an Android App Bundle says about itself, without a config or credentials (CI reads the version code +// before it uploads, instead of unzipping the AAB or asking the Play API). +// storebound aab [--json] +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import type { Args } from './lib/args'; +import { aabInfo } from './lib/gradle'; +import { log, printJson } from './lib/log'; + +export async function run(args: Args): Promise { + const file = args._.find(x => x.endsWith('.aab')); + if (!file) throw new Error('usage: storebound aab [--json]'); + const data = readFileSync(resolve(file)); + const info = { ...aabInfo(data), sha256: createHash('sha256').update(data).digest('hex'), bytes: data.length }; + if (args.has('json')) { printJson(info); return; } + log('aab', `${info.packageName} ${info.versionName ?? '?'} (${info.versionCode}) · minSdk ${info.minSdk ?? '?'} · targetSdk ${info.targetSdk ?? '?'} · ${(info.bytes / 1e6).toFixed(1)} MB`); +} diff --git a/cli/commands.ts b/cli/commands.ts index 789219c..5b0f6ae 100644 --- a/cli/commands.ts +++ b/cli/commands.ts @@ -16,6 +16,7 @@ export const PLAIN: Record Promise, string]> = { 'desktop': [() => import('./desktop'), 'open the storebound desktop app on this folder; not installed or another version: download it for this system (size, SHA-256, signature checked), install it for this user (asks once; --yes) and open it; --download only saves the installer, --dry / --json change nothing'], 'accounts': [() => import('./accounts'), 'the store accounts of this machine (credential profiles in ~/.storebound/credentials, shared with the desktop app): list | import (a project\'s store keys -> a profile; --dry first) | use | default (the machine default; --clear)'], 'settings': [() => import('./settings'), 'per-machine settings: bypass on | off | status (owner opt-in: the agent also presses the owner-only buttons; default off)'], + 'aab': [() => import('./aab'), 'offline: an AAB file: packageName, versionCode, versionName, min / target SDK, sha256 (no config, no upload); --json'], 'doctor': [() => import('./doctor'), 'build and capture dependencies (JDK with the version the project needs, Android SDK, Xcode, CocoaPods, Node, Bun, ffmpeg, Chrome, adb, git, bundletool) and how to install what is missing; --install --yes; --json'], 'scan': [() => import('./scan'), 'offline, read-only rejection-risk scan of the project itself (stack, SDKs, Info.plist, manifest, listings) with guideline, evidence file:line, fix and skill, plus the Data safety / App Privacy / ATT / privacy manifest proposal; --write puts the detected answers into the config; --json; exit 1 on blockers'], 'api': [() => import('./api'), 'every App Store Connect / Google Play API operation: list | coverage | apple|play [--param k=v] [--body f.json] [--all-pages] (GET runs; writes dry unless --yes in a terminal; owner-only ones need the id typed)'], diff --git a/cli/data/flags.json b/cli/data/flags.json index a24b5e2..e27b0da 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -11,6 +11,7 @@ "yes" ], "commands": { + "aab": [], "accounts": [ "clear", "dir", @@ -1178,6 +1179,9 @@ ] }, "usage": { + "aab": [ + "storebound aab [--json]" + ], "accounts": [ "storebound accounts [list] [--json] every profile: Apple key, Play account (masked), which", "storebound accounts import [--dir ] [--name ] [--dry] [--yes]", diff --git a/cli/lib/desktop-coverage.ts b/cli/lib/desktop-coverage.ts index e127b05..8628439 100644 --- a/cli/lib/desktop-coverage.ts +++ b/cli/lib/desktop-coverage.ts @@ -46,6 +46,7 @@ export const DESKTOP_COVERAGE: Record = { 'import': { where: 'App folders / first-run guide: Import from fastlane', methods: ['host:project_import_fastlane'] }, 'install': { where: `${T}: Install for an AI tool`, methods: ['agent.install'] }, 'mcp': { not: 'the stdio server for AI tools; the window itself is the GUI over the same commands' }, + 'aab': { not: 'a CI helper that reads one AAB file; the window shows the builds each store has' }, 'settings': { not: 'per-machine switch for AI agents (bypass mode); in the window the owner presses owner actions in a native dialog anyway' }, 'serve': { not: 'the JSON-RPC sidecar the window runs on; nothing to click' }, 'apps': { where: 'Accounts (store apps per account, key check) and App folders (list, add, remove)', methods: ['host:store_apps_refresh', 'host:account_check', 'host:projects_list', 'host:project_add', 'host:project_remove'] }, diff --git a/cli/play/release.ts b/cli/play/release.ts index 808214a..24c3d8f 100644 --- a/cli/play/release.ts +++ b/cli/play/release.ts @@ -8,9 +8,10 @@ // 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 { createHash } from 'node:crypto'; import type { Ctx } from '../lib/ctx'; import { confirm, need } from '../lib/ctx'; -import { done, log, warn } from '../lib/log'; +import { done, log, warn, printJson } from '../lib/log'; import { aabInfo } from '../lib/gradle'; import { playTargetSdkProblem, targetSdkFile } from '../lib/store-minimums'; import { playClient } from './client'; @@ -55,6 +56,7 @@ export async function run(ctx: Ctx): Promise { if (sdkWhy) throw new Error(`${aab}: not released, ${sdkWhy}`); } const play = await playClient(root, pkg); + let released = fixed ?? ''; try { await play.edit(async (id, ctl) => { let code = fixed ?? ''; @@ -74,6 +76,7 @@ export async function run(ctx: Ctx): Promise { log('play', `uploaded versionCode ${code}`); } } + released = code; let changed = 0; for (const t of tracks) { const release: PlayTrackRelease = { versionCodes: [code], status: t.status }; @@ -100,5 +103,8 @@ export async function run(ctx: Ctx): Promise { if (config.play?.managedPublishing !== true) warn('play', `managed publishing is ${config.play?.managedPublishing === false ? 'off' : 'off by default (play.managedPublishing not set)'}: the release goes live automatically once Google approves it`); if (prod.status === 'draft') log('play', 'next: `storebound console plan play-production-countries` (the API cannot set countries), then `storebound console plan play-production-release` (its final "Send changes for review" is the owner\'s)'); } + // machine-readable result for CI scripts (a Jenkins stage reads it instead of calling the Play API itself) + if (a.has('json')) printJson({ versionCode: released ? Number(released) : null, sha256: aab ? createHash('sha256').update(readFileSync(aab)).digest('hex') : null, name: a.get('name') ?? null, + tracks: tracks.map(t => ({ track: t.track, status: t.status, userFraction: t.status === 'inProgress' ? Number(fraction ?? 0.1) : null })), dry: a.has('dry') }); done('play', 'release done'); } diff --git a/docs/desktop-coverage.md b/docs/desktop-coverage.md index 73c9dde..ae4a1af 100644 --- a/docs/desktop-coverage.md +++ b/docs/desktop-coverage.md @@ -5,7 +5,7 @@ Every CLI command (cli/commands.ts) and the desktop place that runs it. "covered (serve.ts, or a host command `host:`) and the window calls it; tests/desktop-coverage.test.ts fails on a gap. Owner-only parts are owner actions in the window or owner steps with their terminal command (More tools). -**96 commands:** 91 covered, 0 gaps, 5 not for the desktop. +**97 commands:** 91 covered, 0 gaps, 6 not for the desktop. | command | status | where in the window | methods | owner step | |---|---|---|---|---| @@ -18,6 +18,7 @@ Owner-only parts are owner actions in the window or owner steps with their termi | `desktop` | not-for-desktop | opens or installs this window from a terminal | | | | `accounts` | covered | Accounts screen (profiles shared with the CLI) | `host:accounts_list`, `host:account_add_play`, `host:account_add_apple`, `host:account_update` | | | `settings` | not-for-desktop | per-machine switch for AI agents (bypass mode); in the window the owner presses owner actions in a native dialog anyway | | | +| `aab` | not-for-desktop | a CI helper that reads one AAB file; the window shows the builds each store has | | | | `doctor` | covered | Dependencies screen | `system.tools`, `host:tools_info` | | | `scan` | covered | Checks tab: Scan, Fix | `scan`, `scan.write` | | | `api` | not-for-desktop | raw API calls by operation id: every task has its own screen, and raw writes stay a terminal step the owner types | | | diff --git a/tests/build-sign.test.ts b/tests/build-sign.test.ts index 843df9f..a397a99 100644 --- a/tests/build-sign.test.ts +++ b/tests/build-sign.test.ts @@ -515,3 +515,12 @@ describe('apple build outside the GUI session (pitfall 101)', () => { } finally { process.env = saved; } }); }); + +describe('storebound aab (CI reads the version code without uploading)', () => { + test('prints packageName, versionCode, versionName as JSON', () => { + const d = dir('inspect-aab'); + writeFileSync(join(d, 'app.aab'), makeAab('com.example.game', 4321, '3.1.0')); + const r = Bun.spawnSync(['bun', join(import.meta.dir, '..', 'cli', 'index.ts'), 'aab', 'app.aab', '--json'], { cwd: d, stdout: 'pipe', stderr: 'pipe' }); + expect(JSON.parse(r.stdout.toString())).toMatchObject({ packageName: 'com.example.game', versionCode: 4321, versionName: '3.1.0' }); + }); +}); diff --git a/tests/desktop-coverage.test.ts b/tests/desktop-coverage.test.ts index cef5fcf..c12236b 100644 --- a/tests/desktop-coverage.test.ts +++ b/tests/desktop-coverage.test.ts @@ -8,7 +8,7 @@ import { describeMethods } from '../cli/serve'; import { analyze, render } from '../tools/gen-desktop-coverage'; /** The only commands that make no sense in a window. Adding one here needs a reason in the coverage map. */ -const NOT_FOR_DESKTOP = ['mcp', 'serve', 'desktop', 'api', 'settings']; +const NOT_FOR_DESKTOP = ['mcp', 'serve', 'desktop', 'api', 'settings', 'aab']; describe('desktop coverage', () => { const { rows, extra } = analyze(); From 600b6893e5c7d92f77ce96753135cd0974fd945a Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 03:33:30 +0800 Subject: [PATCH 102/344] play listing uploads the hi-res icon (and the feature graphic) for a new Play language in the same edit (403 no high resolution icon set; play images skipped it), pitfall 102; script traces skip test files --- CHANGELOG.md | 4 ++++ cli/lib/fastlane-traces.ts | 3 ++- cli/play/images.ts | 12 ++++++++++++ cli/play/listing.ts | 10 ++++++++++ skills/store-pitfalls/SKILL.md | 10 ++++++++++ tests/fastlane-traces.test.ts | 9 +++++++++ 6 files changed, 47 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e71c73..24629af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- **A new Play language in one run.** `play listing` uploads the hi-res icon (and the feature graphic when rendered) for a + language Play does not have yet, in the same edit (Play refused the commit with 403 otherwise). Pitfall 102. +- Script traces skip test files (`*.test.*`, `*.spec.*`). + - **CI-friendly Play output.** `storebound aab --json` reads packageName, versionCode, versionName, SDKs and sha256 offline (no config, no upload); `play release ... --json` prints {versionCode, sha256, name, tracks[{track, status, userFraction}]}. `play status --json` already lists each track's releases. diff --git a/cli/lib/fastlane-traces.ts b/cli/lib/fastlane-traces.ts index fc847de..2a80a8f 100644 --- a/cli/lib/fastlane-traces.ts +++ b/cli/lib/fastlane-traces.ts @@ -68,7 +68,8 @@ export function findFastlaneTraces(root: string): FastlaneTrace[] { try { for (const n of readdirSync(dir)) if (SCRIPT_EXT.test(n)) files.push(join(dir, n)); } catch { /* none */ } } try { for (const n of readdirSync(root)) if (/\.(sh|bash|ps1)$/i.test(n)) files.push(join(root, n)); } catch { /* unreadable */ } - for (const f of new Set(files)) { + // test files quote the tools in their assertions; they upload nothing + for (const f of [...new Set(files)].filter(x => !/\.(test|spec)\.[cm]?[jt]sx?$/i.test(x))) { lines(f).forEach((l, i) => { const m = CLI_CALL.exec(l); if (m) out.push({ file: rel(f), line: i + 1, text: l.trim().slice(0, 200), store: storeOf(m[1]!) }); diff --git a/cli/play/images.ts b/cli/play/images.ts index 8ee5940..de181b2 100644 --- a/cli/play/images.ts +++ b/cli/play/images.ts @@ -72,6 +72,18 @@ export function missingChange(type: string, remote: number, prune: boolean): Ima /** What one language uploads: the sets with files, the optional types without, and errors (missing required sets). */ export interface LangImages { sets: [string, string[]][]; missing: string[]; errors: string[] } +/** The graphics a NEW Play language needs before its edit can commit (403 "no high resolution icon set for language"): + * the hi-res icon and, when rendered, the feature graphic. `play listing` uploads them in the same edit as the text, + * so listing and images never wait for each other (pitfall 102). */ +export function firstGraphics(ctx: Ctx, code: string): [string, string][] { + const { config, resolve } = ctx.loaded; + const icon = resolve(config.play?.icon ?? join(config.icons?.out ?? 'store/icons', 'play-512.png')); + const l = byPlayCode(config.languages).get(code); + const src = resolve(config.renders ?? config.shots?.out ?? 'store/renders'); + const li = langImages(code, l ? join(src, l.id) : join(src, '__none__'), icon, false); + return li.sets.filter(([t]) => t === 'icon' || t === 'featureGraphic').map(([t, files]) => [t, files[0]!] as [string, string]); +} + /** The image sets of one language folder (`tablets` = resolved play.tablets). Reads the folder only. */ export function langImages(code: string, dir: string, icon: string, tablets: boolean): LangImages { const out: LangImages = { sets: [], missing: [], errors: [] }; diff --git a/cli/play/listing.ts b/cli/play/listing.ts index 2d86894..fc0ded4 100644 --- a/cli/play/listing.ts +++ b/cli/play/listing.ts @@ -20,6 +20,7 @@ import type { Ctx } from '../lib/ctx'; import { confirm, need } from '../lib/ctx'; import { done, log, printJson, step, warn } from '../lib/log'; import { playClient } from './client'; +import { firstGraphics } from './images'; import { stdinIsTTY } from '../lib/tty'; /** Play release notes that name iOS, iPhone, App Store, ... are refused before any edit, dry runs included (pitfall 77). */ @@ -167,6 +168,15 @@ export async function run(ctx: Ctx): Promise { for (const [i, b] of todo.entries()) { await play.call('PUT', `${play.API}/edits/${id}/listings/${b.language}`, b); log('play', step(i + 1, todo.length, b.language!)); + // a language Play does not have yet: its edit only commits with a hi-res icon (pitfall 102) + if (!now.some(n => n.language === b.language)) { + const graphics = firstGraphics(ctx, b.language!); + if (!graphics.some(([t]) => t === 'icon')) throw new Error(`${b.language}: a new Play language needs the 512x512 icon in the same edit (play.icon or store/icons/play-512.png): storebound icons makes it`); + for (const [type, f] of graphics) { + await play.call('POST', `${play.UPLOAD}/edits/${id}/listings/${b.language}/${type}?uploadType=media`, new Uint8Array(readFileSync(f)), { 'Content-Type': /\.png$/i.test(f) ? 'image/png' : 'image/jpeg' }); + log('play', `${b.language}: ${type} uploaded with the new listing`); + } + } } }, { notSentForReview: ctx.args.has('not-sent-for-review'), summary: 'listing text' }); done('play', sent ? 'listing done' : 'listing already up to date (the edit was deleted, nothing committed)'); diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index d74c179..ec8c872 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1233,3 +1233,13 @@ that fails without the fix (see CONTRIBUTING.md). - **Guard:** `remoteBuildSession` in `cli/lib/xcode.ts` stops `apple build` before the archive; `credPath` in `cli/lib/credentials.ts` resolves relative credential paths from the project and `ascKeyFile` hands xcodebuild an absolute path (`tests/build-sign.test.ts`). + +## 102. A new Play language: `play listing` 403 "no high resolution icon set for language", `play images` skips it +- **Symptom:** adding a language (tr-TR) to an existing app, `play listing --yes` failed at the edit commit with 403 + "This app has no high resolution icon set for language tr-TR", while `play images` said "skipped tr-TR: no Play + listing yet": each waited for the other. +- **Cause:** Play commits a new language only when its hi-res icon is in the same edit. +- **Do:** update storebound; `play listing` now uploads the icon (and the feature graphic when rendered) for a new + language in the same edit. Then run `play images` for the screenshots. +- **Guard:** `firstGraphics` in `cli/play/images.ts`, used by `cli/play/listing.ts` for languages Play does not have yet; + it stops with the fix when the 512x512 icon is missing. diff --git a/tests/fastlane-traces.test.ts b/tests/fastlane-traces.test.ts index 7d03491..1879ed5 100644 --- a/tests/fastlane-traces.test.ts +++ b/tests/fastlane-traces.test.ts @@ -65,3 +65,12 @@ describe('direct store API traces stay short', () => { expect(findFastlaneTraces(dir)).toEqual([expect.objectContaining({ file: 'tools/ship.mjs', line: 5, via: 'api' })]); }); }); + +describe('test files are not traces', () => { + test('a test that quotes altool is skipped', () => { + const dir = mkdtempSync(join(tmpdir(), 'sb-fl3-')); + mkdirSync(join(dir, 'tools')); + writeFileSync(join(dir, 'tools/ship.test.mjs'), "test('calls altool', () => { run(['xcrun', 'altool']); });\n"); + expect(findFastlaneTraces(dir)).toEqual([]); + }); +}); From aae3a6c62d10c37886b2832f4932e6dbd20f816a Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 03:45:25 +0800 Subject: [PATCH 103/344] doctor: at a terminal the used-for column is cut to the window width so rows never wrap; piped output stays whole --- cli/doctor.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/cli/doctor.ts b/cli/doctor.ts index 7b2de04..612d04f 100644 --- a/cli/doctor.ts +++ b/cli/doctor.ts @@ -82,7 +82,15 @@ export async function run(args: Args): Promise { } if (args.has('json')) { printJson(r); return; } log('doctor', `storebound ${r.storebound} · ${r.runtime} · ${r.platform}${r.project ? ' · project config found' : ''}`); - console.log(textTable(['tool', 'status', 'version', 'needs', 'used for'], r.tools.map(t => [t.name, t.status === 'outdated' ? 'too old' : t.found ? (t.source === 'app' ? 'ok (app copy)' : 'ok') : 'missing', t.version ?? '', t.required ?? '', t.usedFor]))); + const rows = r.tools.map(t => [t.name, t.status === 'outdated' ? 'too old' : t.found ? (t.source === 'app' ? 'ok (app copy)' : 'ok') : 'missing', (t.version ?? '').slice(0, 16), t.required ?? '', t.usedFor]); + // at a terminal the last column is cut to the window width, so rows never wrap (piped output stays whole) + const cols = process.stdout.isTTY ? process.stdout.columns : 0; + if (cols) { + const w = (i: number) => Math.max(...[['tool', 'status', 'version', 'needs'][i]!, ...rows.map(x => x[i]!)].map(s => s.length)); + const room = cols - [0, 1, 2, 3].reduce((n, i) => n + w(i) + 2, 0) - 1; + for (const x of rows) if (x[4]!.length > room) x[4] = room > 8 ? `${x[4]!.slice(0, room - 1)}…` : ''; + } + console.log(textTable(['tool', 'status', 'version', 'needs', 'used for'], rows)); log('doctor', r.androidSdk.path ? `Android SDK: ${r.androidSdk.path} (from ${r.androidSdk.source})` : `Android SDK: not found (play build needs it). Checked: ${r.androidSdk.checked.join('; ')}`); const set = r.credentials.filter(c => c.status === 'set').map(c => c.key), ph = r.credentials.filter(c => c.status === 'placeholder').map(c => c.key); From 9f40a9ea1458c847775cde185806d3e9326a1b90 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 05:24:58 +0800 Subject: [PATCH 104/344] Console plan apple-app-privacy: Edit opens Data Collection first on a published app (type list ends in Continue), each type's last step is Publish (live, no draft); Publish is the owner's unless bypass mode is on (verified 2026-10-22) --- CHANGELOG.md | 4 ++++ cli/lib/console-plan.ts | 8 ++++---- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 24629af..a7816ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- **App Privacy console plan follows today's page** (verified 2026-10-22): on an app published before, Edit opens the + Data Collection question first and the type list ends in Continue; each type's last step is Publish (it goes live, + no draft). Publish stays the owner's unless bypass mode is on. + - **A new Play language in one run.** `play listing` uploads the hi-res icon (and the feature graphic when rendered) for a language Play does not have yet, in the same edit (Play refused the commit with 403 otherwise). Pitfall 102. - Script traces skip test files (`*.test.*`, `*.spec.*`). diff --git a/cli/lib/console-plan.ts b/cli/lib/console-plan.ts index f333e0d..7eeac67 100644 --- a/cli/lib/console-plan.ts +++ b/cli/lib/console-plan.ts @@ -273,7 +273,7 @@ function appPrivacyPlan(answers: PlanAnswer[], appId: string | null | undefined) const add = (s: Omit) => steps.push({ n: steps.length + 1, ...s }); add({ text: appId ? 'Open the App Privacy page of the app (deep link).' : `Open App Store Connect > Apps > the app > App Privacy (sidebar): ${consoleUrl('asc.apps')}` }); add({ text: 'First time: click "Get Started" and answer the Data Collection question; then Next.', click: ['Get Started'], answers: ['collects'] }); - add({ text: 'Data types: when the Data Types section does not list exactly the collected types below, click the "Edit" next to the "Data Types" heading (never the Privacy Policy Edit), tick exactly these types and untick the rest, then Save (a draft: nothing is public before Publish). Console labels: Purchase History shows as "Purchases", Other Data Types as "Other Data".', click: ['Edit', 'Save'], answers: ids(answers, a => a.id.startsWith('type:')) }); + add({ text: 'Data types: when the Data Types section does not list exactly the collected types below, click the "Edit" next to the "Data Types" heading (never the Privacy Policy Edit), tick exactly these types and untick the rest, then Save. On an app whose answers were published before (verified 2026-10-22), Edit first opens the "Data Collection" question (Yes / No, then Next); the type list is step 2 and ends in "Continue", not "Save". Console labels: Purchase History shows as "Purchases", Other Data Types as "Other Data".', click: ['Edit', 'Next', 'Save', 'Continue'], answers: ids(answers, a => a.id.startsWith('type:')) }); add({ text: `${APPLE_ADDITIONAL_SETUP}`, click: ['OK'] }); for (const t of collected) { const set = setUpTexts(t).filter(x => !/ ayarla$/.test(x)); @@ -281,9 +281,9 @@ function appPrivacyPlan(answers: PlanAnswer[], appId: string | null | undefined) add({ type: t, text: `"${t}" step 1, purposes: tick and untick the 6 checkboxes as answered, then Next.`, click: ['Next'], answers: ids(answers, a => a.id.startsWith(`purpose:${t}:`)) }); add({ type: t, text: `"${t}" step 2, linked to the user: pick the radio, then Next.`, click: ['Next'], answers: [`linked:${t}`] }); add({ type: t, text: `"${t}" steps 3 and 4: two information pages ("Let’s define two important terms…", then "To help put tracking into context, here are a few examples:"), no inputs: press Next on each.`, click: ['Next', 'Next'] }); - add({ type: t, text: `"${t}" step 5, tracking: pick the radio, then Save (a draft). Never "Definitions and Examples". The dialog closes; the row shows Edit and the summary.`, click: ['Save'], answers: [`tracking:${t}`] }); + add({ type: t, text: `"${t}" step 5, tracking: pick the radio, then the last button: "Save" (first setup: a draft) or "Publish" (answers published before: this type goes live at once, verified 2026-10-22). Publish is the owner's button unless bypass mode is on (storebound settings bypass status). Never "Definitions and Examples". The dialog closes; the row shows Edit and the summary.`, click: ['Save'], answers: [`tracking:${t}`] }); } - add({ text: 'Stop. Do NOT press Publish: tell the owner to review the summary on the App Privacy page and press Publish, then Publish again in the "Publish Your App Privacy Responses?" dialog (it puts the answers on the App Store product page). Afterwards the page shows "Published … ago by …".' }); + add({ text: 'First setup only: the page then has a Publish button (top right) and the dialog "Publish Your App Privacy Responses?". That Publish is the owner’s unless bypass mode is on; then press it yourself. Afterwards the page shows "Published … ago by …". (Answers published before: each type was already published by its own last step.)' }); add({ text: 'Verify: read the Data Types section as text (document.querySelector("main").innerText) and pipe it to `storebound console verify apple-app-privacy --from-text -`.' }); return { start: appId ? { url: `${ASC}/apps/${appId}/distribution/privacy`, deepLink: true, reach: [] } @@ -297,7 +297,7 @@ function appPrivacyPlan(answers: PlanAnswer[], appId: string | null | undefined) 'Step 2, linked: 2 radios, "Yes, data collected from this app is linked to the user’s identity" / "No, …" (curly ’). Buttons: Back, Cancel, Next.', 'Step 3: an information page "Let’s define two important terms…" (Tracking / Third-Party Data). No inputs: press Next.', 'Step 4: an information page "To help put tracking into context, here are a few examples:". No inputs: press Next. (Two information steps in a row: keep pressing Next while the dialog shows no inputs.)', - 'Step 5, tracking: 2 radios, "Yes, we use data for tracking purposes" / "No, we do not …". Buttons: "Definitions and Examples" (help: never press), Back, Cancel, Save.', + 'Step 5, tracking: 2 radios, "Yes, we use data for tracking purposes" / "No, we do not …". Buttons: "Definitions and Examples" (help: never press), Back, Cancel, and Save (first setup) or Publish (answers published before: no draft, the type goes live; verified 2026-10-22).', 'Save closes the dialog. The type then shows "Edit" and a summary: "Used for ", "Linked to the user’s identity" (or not), "Used for tracking purposes" (or not). That summary is what `console verify` reads.', 'Labels use typographic quotes (’): match straight and curly quotes alike.', 'The "?" buttons ("More information") are help only. Publish (top right) is the owner\'s: it opens a "Publish Your App Privacy Responses?" with Cancel / Publish (the owner\'s final button); after it the page shows "Published a few seconds ago by …" (verified 2026-10-12), which `console verify` reads as the published signal.', From 9a907d87e59ce4c4d5406ba7fd02a58a4f94de60 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 05:59:41 +0800 Subject: [PATCH 105/344] Desktop: tray icon, start at logon hidden (autostart --hidden, window state never restores visible), closing hides to the tray, background signed auto-update at start and every 30 min with restart --- CHANGELOG.md | 4 + apps/desktop/src-tauri/Cargo.lock | 113 +++++++++++++++++++++++-- apps/desktop/src-tauri/Cargo.toml | 3 +- apps/desktop/src-tauri/src/lib.rs | 82 +++++++++++++++++- apps/desktop/src-tauri/tauri.conf.json | 3 +- docs/desktop.md | 8 +- 6 files changed, 200 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a7816ee..4687765 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- **Desktop: tray app that starts at logon and updates itself.** First run registers a logon entry (`--hidden`): the app + starts silently in the tray; closing the window keeps it there, the tray menu quits. A signed update is checked a + minute after start and every 30 minutes, installed silently, and the app restarts as it was. + - **App Privacy console plan follows today's page** (verified 2026-10-22): on an app published before, Edit opens the Data Collection question first and the type list ends in Continue; each type's last step is Publish (it goes live, no draft). Publish stays the owner's unless bypass mode is on. diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 957e60a..4b7b3f9 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -227,6 +227,20 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "auto-launch" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17918dba7ecf78b9a14507ec9f984e7977d13fad87dc86d61038980a45d128cf" +dependencies = [ + "dirs 6.0.0", + "os_info", + "smappservice-rs", + "thiserror 2.0.21", + "windows-registry", + "windows-result", +] + [[package]] name = "autocfg" version = "1.5.1" @@ -855,6 +869,15 @@ dependencies = [ "subtle", ] +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", +] + [[package]] name = "dirs" version = "7.0.0" @@ -2446,6 +2469,18 @@ dependencies = [ "memoffset", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "notify-rust" version = "4.18.2" @@ -2724,6 +2759,30 @@ dependencies = [ "objc2-foundation", ] +[[package]] +name = "objc2-security" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe137109bd1e8b5a99390f77a7d8b2961dafc1a1c5db8f2e60329ad6d895a" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-service-management" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b213642d6959cc6023ceb1217aa595eaaf09b8094ce95127c103cab611fe65e8" +dependencies = [ + "block2", + "objc2", + "objc2-core-foundation", + "objc2-foundation", + "objc2-security", +] + [[package]] name = "objc2-ui-kit" version = "0.3.2" @@ -2818,6 +2877,21 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "os_info" +version = "3.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cf20a545b305cf1da722b236b5155c9bb35f1d5ceb28c048bd96ca842f41b5b" +dependencies = [ + "android_system_properties", + "log", + "nix 0.31.3", + "objc2", + "objc2-foundation", + "objc2-ui-kit", + "windows-sys 0.61.2", +] + [[package]] name = "os_pipe" version = "1.2.3" @@ -3926,6 +4000,18 @@ version = "1.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +[[package]] +name = "smappservice-rs" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52703b97a53101cf5d4580e0737aaa634ce1fdcfc123c16b2a9658e358013488" +dependencies = [ + "objc2", + "objc2-foundation", + "objc2-service-management", + "thiserror 2.0.21", +] + [[package]] name = "socket2" version = "0.6.5" @@ -4025,6 +4111,7 @@ dependencies = [ "sha2", "tauri", "tauri-build", + "tauri-plugin-autostart", "tauri-plugin-deep-link", "tauri-plugin-dialog", "tauri-plugin-notification", @@ -4250,7 +4337,7 @@ dependencies = [ "anyhow", "bytes", "cookie", - "dirs", + "dirs 7.0.0", "dunce", "embed_plist", "getrandom 0.3.4", @@ -4300,7 +4387,7 @@ checksum = "59563ca5b331fd97f27ee9672ec8d36d33bb3c9e2c9f6710a1a5687256052e45" dependencies = [ "anyhow", "cargo_toml", - "dirs", + "dirs 7.0.0", "glob", "heck 0.5.0", "json-patch", @@ -4370,6 +4457,20 @@ dependencies = [ "walkdir", ] +[[package]] +name = "tauri-plugin-autostart" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bce56ceb0a99b8ab5eebc977ba9ffc62391b862648cb9ab76fc8bc7231b8f7e2" +dependencies = [ + "auto-launch", + "serde", + "serde_json", + "tauri", + "tauri-plugin", + "thiserror 2.0.21", +] + [[package]] name = "tauri-plugin-deep-link" version = "2.6.1" @@ -4532,7 +4633,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "855a336eb389d2c1502244fd48fa2d8cb487a430f691bbaed025195f99a04489" dependencies = [ "base64 0.22.1", - "dirs", + "dirs 7.0.0", "flate2", "futures-util", "http", @@ -5018,7 +5119,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72" dependencies = [ "crossbeam-channel", - "dirs", + "dirs 7.0.0", "libappindicator", "muda", "objc2", @@ -5841,7 +5942,7 @@ dependencies = [ "block2", "cookie", "crossbeam-channel", - "dirs", + "dirs 7.0.0", "dom_query", "dpi", "dunce", @@ -5955,7 +6056,7 @@ dependencies = [ "futures-sink", "futures-util", "hex", - "nix", + "nix 0.29.0", "ordered-stream", "rand 0.8.8", "serde", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index bb0cad6..6ef6990 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -19,7 +19,7 @@ path = "src/main.rs" tauri-build = { version = "2", features = [] } [dependencies] -tauri = { version = "2.12", features = [] } +tauri = { version = "2.12", features = ["tray-icon"] } # Spawns the storebound sidecar from Rust only; no capability grants the plugin's JS API. tauri-plugin-shell = "2" tauri-plugin-single-instance = { version = "2", features = ["deep-link"] } @@ -31,6 +31,7 @@ tauri-plugin-dialog = "2" tauri-plugin-notification = "2" tauri-plugin-updater = "2" tauri-plugin-process = "2" +tauri-plugin-autostart = "2" # Store credentials: macOS Keychain, Windows Credential Manager, Secret Service on Linux. keyring = { version = "3", features = ["apple-native", "windows-native", "sync-secret-service", "crypto-rust"] } serde = { version = "1", features = ["derive"] } diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index c16ea24..dd9272d 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -21,7 +21,10 @@ include!("commands_list.rs"); use std::sync::Mutex; use tauri::menu::{Menu, MenuItem, PredefinedMenuItem, Submenu, WINDOW_SUBMENU_ID}; +use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}; use tauri::{AppHandle, Emitter, Manager, RunEvent, Runtime, WindowEvent}; +use tauri_plugin_autostart::{MacosLauncher, ManagerExt}; +use tauri_plugin_updater::UpdaterExt; use tauri_plugin_deep_link::DeepLinkExt; /// WebKitGTK's DMABUF renderer leaves the window blank on some Linux GPU / driver / VM combinations. Turn it off unless @@ -34,6 +37,60 @@ pub fn linux_webkit_env() { } } +/// Started by the logon entry (`--hidden`): the app runs in the tray and shows no window. +fn started_hidden() -> bool { + std::env::args().any(|a| a == "--hidden") +} + +/// Tray icon: a click shows the window; the menu has Open and Quit (the only real quit on Windows and Linux, where +/// closing the window keeps the app running in the tray). +fn tray(app: &tauri::App) -> tauri::Result<()> { + let open = MenuItem::with_id(app, "tray-open", "Open storebound", true, None::<&str>)?; + let quit = MenuItem::with_id(app, "tray-quit", "Quit storebound", true, None::<&str>)?; + let menu = Menu::with_items(app, &[&open, &PredefinedMenuItem::separator(app)?, &quit])?; + let mut b = TrayIconBuilder::with_id("main").tooltip("storebound").menu(&menu).show_menu_on_left_click(false); + if let Some(icon) = app.default_window_icon() { + b = b.icon(icon.clone()); + } + b.on_menu_event(|app, e| match e.id().as_ref() { + "tray-open" => show_main(app), + "tray-quit" => app.exit(0), + _ => {} + }) + .on_tray_icon_event(|t, e| { + if let TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. } = e { + show_main(t.app_handle()); + } + }) + .build(app)?; + Ok(()) +} + +/// Silent self-update: at start (after a minute) and every 30 minutes, a signed update from storebound.dev is +/// downloaded, installed and the app restarts with the same arguments (`--hidden` stays hidden). Errors are logged. +fn auto_update(app: AppHandle) { + tauri::async_runtime::spawn(async move { + tokio::time::sleep(std::time::Duration::from_secs(60)).await; + loop { + match app.updater() { + Ok(u) => match u.check().await { + Ok(Some(update)) => { + logs::host("info", &format!("auto-update: {} available, installing", update.version)); + match update.download_and_install(|_, _| {}, || {}).await { + Ok(()) => app.restart(), + Err(e) => logs::host("warn", &format!("auto-update: install failed: {e}")), + } + } + Ok(None) => {} + Err(e) => logs::host("warn", &format!("auto-update: check failed: {e}")), + }, + Err(e) => logs::host("warn", &format!("auto-update: no updater: {e}")), + } + tokio::time::sleep(std::time::Duration::from_secs(30 * 60)).await; + } + }); +} + fn show_main(app: &AppHandle) { if let Some(w) = app.get_webview_window(policy::MAIN) { let _ = w.unminimize(); @@ -135,7 +192,9 @@ pub fn run() { // single-instance first: a second start (or a storebound:// link) focuses the running app instead .plugin(tauri_plugin_single_instance::init(|app, _argv, _cwd| show_main(app))) .plugin(tauri_plugin_deep_link::init()) - .plugin(tauri_plugin_window_state::Builder::new().build()) + // never restore "visible": a --hidden start would otherwise pop the window up + .plugin(tauri_plugin_window_state::Builder::new().with_state_flags(tauri_plugin_window_state::StateFlags::all() & !tauri_plugin_window_state::StateFlags::VISIBLE).build()) + .plugin(tauri_plugin_autostart::init(MacosLauncher::LaunchAgent, Some(vec!["--hidden"]))) .plugin(tauri_plugin_shell::init()) .plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_dialog::init()) @@ -178,7 +237,20 @@ pub fn run() { if let Err(e) = commands::sync_machine(&state) { logs::host("warn", &format!("accounts / app folders not synced at start: {}", e.message)); } + // start at logon, in the tray: set once (first run); the owner can turn it off in the OS afterwards + let marker = state.data_dir.join("autostart-set"); + if !marker.exists() { + match app.autolaunch().enable() { + Ok(()) => { let _ = std::fs::write(&marker, "1"); logs::host("info", "autostart at logon enabled (--hidden, tray)"); } + Err(e) => logs::host("warn", &format!("autostart not enabled: {e}")), + } + } app.manage(state); + tray(app)?; + if !started_hidden() { + show_main(app.handle()); + } + auto_update(app.handle().clone()); #[cfg(target_os = "macos")] app.set_menu(menu(app.handle())?)?; #[cfg(not(target_os = "macos"))] @@ -202,9 +274,9 @@ pub fn run() { Ok(()) }) .on_window_event(|w, e| { - // macOS: the close button hides the window (the app stays in the Dock and the Window menu); - // Cmd+Q and the app menu's Quit still quit. Elsewhere closing the window quits. - if cfg!(target_os = "macos") && w.label() == policy::MAIN { + // the close button hides the window: the app keeps running in the tray (macOS: also the Dock); the tray's + // Quit (macOS: Cmd+Q) really quits + if w.label() == policy::MAIN { if let WindowEvent::CloseRequested { api, .. } = e { api.prevent_close(); let _ = w.hide(); @@ -267,6 +339,8 @@ pub fn run() { app.run(|app, e| match e { #[cfg(target_os = "macos")] RunEvent::Reopen { .. } => show_main(app), + // no window left is not a reason to quit (tray app); an explicit exit or the updater's restart carries a code + RunEvent::ExitRequested { code: None, api, .. } => api.prevent_exit(), RunEvent::Exit => { if let Some(s) = app.try_state::() { s.sidecar.shutdown_now(); diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 614a48e..51f3128 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -20,7 +20,8 @@ "minWidth": 880, "minHeight": 560, "resizable": true, - "center": true + "center": true, + "visible": false } ], "security": { diff --git a/docs/desktop.md b/docs/desktop.md index 795c2c3..9de0347 100644 --- a/docs/desktop.md +++ b/docs/desktop.md @@ -482,8 +482,14 @@ The CLI and the app are one product: one version number, one set of store accoun - Releases: [desktop-release.md](desktop-release.md) (version authority, privacy gate, macOS signing and notarization, Forgejo builds for Linux and Windows, storebound.dev hosting, publish). - **Updates**: Settings > Updates checks storebound.dev (stable `/desktop/latest.json` or beta - `/desktop/beta/latest.json`) only when asked; Install shows a native dialog, then the updater downloads the bundle, + `/desktop/beta/latest.json`) when asked; Install shows a native dialog, then the updater downloads the bundle, checks its minisign signature against `plugins.updater.pubkey` and restarts (`update_check`, `update_install`). + In the background the app also checks the stable channel a minute after start and every 30 minutes, installs a + signed update silently and restarts with the same arguments (`auto_update` in `src-tauri/src/lib.rs`). +- **Tray and start at logon**: the first run registers a logon entry (`tauri-plugin-autostart`, `--hidden`): the app + starts silently in the tray, without a window. Closing the window keeps it running in the tray; the tray icon + opens it, the tray menu's Quit (macOS: Cmd+Q) quits. Turn the logon entry off in the OS (Windows: Settings > Apps > + Startup). Window state never restores "visible", so a `--hidden` start stays hidden. - **`storebound://open?path=`** (sent by `storebound desktop` in an app folder, which first puts the folder on the machine's list): the host accepts one plain absolute path (`policy::deep_link_open_path`), syncs the list, selects that app folder when it is on it, otherwise asks in a native dialog and adds it From 17535d4b7a023fe2526ca1c7100269ce4f4f1d39 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 05:05:48 +0700 Subject: [PATCH 106/344] storebound 0.8.27: version in package.json and every copy, CHANGELOG 0.8.27 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 3c7a497..6c2381f 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.26", + "version": "0.8.27", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 1a38eff..c750978 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.26", + "version": "0.8.27", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 861bf1c..c444524 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.26", + "version": "0.8.27", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index 4687765..1982ddf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.27 · 2026-10-21 + - **Desktop: tray app that starts at logon and updates itself.** First run registers a logon entry (`--hidden`): the app starts silently in the tray; closing the window keeps it there, the tray menu quits. A signed update is checked a minute after start and every 30 minutes, installed silently, and the app restarts as it was. diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 1b939ad..4c959fa 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.26", + "version": "0.8.27", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 4b7b3f9..f528243 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4096,7 +4096,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.26" +version = "0.8.27" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 6ef6990..1a55690 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.26" +version = "0.8.27" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 51f3128..6cba48d 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.26", + "version": "0.8.27", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index 41bb88e..a727731 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.26", + "version": "0.8.27", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index 88630d9..220d0c1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.26", + "version": "0.8.27", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From cd0110527ce1a39214c83c30110ff33839e4a24c Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 06:22:08 +0800 Subject: [PATCH 107/344] apps relink: after a machine move, missing app folders are pointed at the same app here (last path parts, else the config's app name), ids kept; apps folders hints it; apps add names an app after its config app name --- CHANGELOG.md | 4 +++ cli/apps.ts | 23 +++++++++++-- cli/data/flags.json | 14 +++++++- cli/lib/registry.ts | 65 +++++++++++++++++++++++++++++++++-- tests/registry-relink.test.ts | 33 ++++++++++++++++++ 5 files changed, 134 insertions(+), 5 deletions(-) create mode 100644 tests/registry-relink.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 4687765..425884f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- **`storebound apps relink`** after a machine move: every "folder not found" entry of the app folder list is pointed at + the same app on this machine (by its path or its app name), ids kept so the desktop keeps its accounts and settings; + `apps folders` says so when entries are missing. `apps add` names an app after its config's app name. + - **Desktop: tray app that starts at logon and updates itself.** First run registers a logon entry (`--hidden`): the app starts silently in the tray; closing the window keeps it there, the tray menu quits. A signed update is checked a minute after start and every 30 minutes, installed silently, and the app restarts as it was. diff --git a/cli/apps.ts b/cli/apps.ts index 1200151..e28de41 100644 --- a/cli/apps.ts +++ b/cli/apps.ts @@ -9,6 +9,7 @@ // the same list as the desktop app's App folders) // storebound apps add [] | apps remove add / remove a folder in that list (the folder itself stays) // storebound apps add --store apple|play --app-id [--account ] [--name ] [--bundle-id ] +// storebound apps relink [--root ]... [--dry] after a move: "folder not found" entries -> the same app here // a store app with no project on this machine: the // desktop shows it read-only ("no local project"); // apps remove apple: | takes it out @@ -17,7 +18,7 @@ import { ascKey, playServiceAccount } from './lib/credentials'; import type { AccountCheck, AppsListResult } from './lib/desktop-protocol'; import { PLAY_SCOPE, REPORTING_SCOPE, tokenSource } from './lib/google-auth'; import { errorBody } from './lib/http'; -import { log, printJson, warn } from './lib/log'; +import { done, log, printJson, warn } from './lib/log'; import { appleCheck, type Bytes, dataUrl, type Get, isServiceDisabled, listAppleApps, listPlayApps, localPlayApps, MAX_ICON_BYTES, playCheck } from './lib/store-apps'; import { textTable } from './lib/table'; import { ascClient } from './apple/asc'; @@ -26,7 +27,8 @@ import * as rt from './lib/rt'; import { existsSync, readFileSync } from 'node:fs'; import { basename, join, resolve } from 'node:path'; import { CONFIG_NAMES } from './lib/config'; -import { addFolder, addStoreApp, readRegistry, registryFile, removeFolder, removeStoreApp } from './lib/registry'; +import { addFolder, addStoreApp, applyRelink, configAppName, configFolders, readRegistry, registryFile, relinkPlan, removeFolder, removeStoreApp } from './lib/registry'; +import { homedir } from 'node:os'; type Store = 'apple' | 'play'; @@ -175,6 +177,8 @@ async function folders(sub: string, args: Args): Promise { } if (!r.projects.length) { console.log(`no app folders yet (${tilde(registryFile())}): storebound apps add, in an app folder (or storebound desktop there)`); return; } console.log(textTable(['app', 'folder', ''], r.projects.map(p => [p.name, tilde(p.path), existsSync(p.path) ? '' : 'folder not found']))); + const missing = r.projects.filter(p => !existsSync(p.path)).length; + if (missing) console.log(`\n${missing} folder(s) not found (moved to another computer or folder?): storebound apps relink --dry finds them by path and app name`); console.log(` ${tilde(registryFile())}: the same list as the desktop app's App folders`); return; @@ -218,10 +222,25 @@ ${tilde(registryFile())}: the same list as the desktop app's App folders`); log('apps', removed ? `removed ${tilde(removed.path)} from the list (the folder and its files stay)` : `${tilde(dir)} is not in the list`); } +/** apps relink: point "folder not found" entries at the same app on this machine (after a move); ids stay. */ +function relink(args: Args): void { + const home = homedir(); + const roots = args.list('root').length ? args.list('root').map(r => resolve(r)) + : [join(home, 'Documents', 'Visual Studio Workspaces'), join(home, 'Documents'), join(home, 'Desktop'), join(home, 'Projects'), join(home, 'code')].filter(d => existsSync(d)); + const plan = relinkPlan(readRegistry(), configFolders(roots), existsSync, configAppName); + if (args.has('json')) { printJson({ roots, plan, dry: args.has('dry') }); } + else if (!plan.length) log('apps', `nothing to relink (looked under ${roots.map(tilde).join(', ')}; --root to look elsewhere)`); + else for (const s of plan) log('apps', `${s.name}: ${s.from} -> ${tilde(s.to)}`); + if (!plan.length || args.has('dry')) { if (plan.length) done('apps', `dry run: ${plan.length} folder(s) would be relinked`); return; } + applyRelink(plan); + done('apps', `${plan.length} folder(s) relinked (the desktop app picks them up on its next start)`); +} + export async function run(args: Args): Promise { const sub = args._[0]; const root = process.cwd(); const json = args.has('json'); + if (sub === 'relink') return relink(args); if (sub === 'folders' || sub === 'add' || sub === 'remove') return folders(sub, args); if (sub === 'list') { const out: AppsListResult[] = []; diff --git a/cli/data/flags.json b/cli/data/flags.json index e27b0da..6c48e61 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -317,6 +317,7 @@ "bundle-id", "icons", "name", + "root", "store" ], "art": [ @@ -621,6 +622,9 @@ "play listing": [ "include-drafts", "not-sent-for-review", + "prune", + "src", + "variant", "write" ], "play next-version-code": [], @@ -636,6 +640,9 @@ "name", "not-sent-for-review", "production", + "prune", + "src", + "variant", "version-code", "write" ], @@ -683,8 +690,11 @@ "include-drafts", "name", "not-sent-for-review", + "prune", + "src", "status", "track", + "variant", "write" ], "prices": [ @@ -1115,6 +1125,7 @@ "resolve-iaps", "resume", "review-sent", + "root", "scenes", "scheme", "sdk-dirs", @@ -1337,7 +1348,8 @@ "storebound apps check [--store apple|play] [--json] auth OK / permission missing / key revoked, with the fix", "storebound apps folders [--json] the app folders of this machine (~/.storebound/projects.json,", "storebound apps add [] | apps remove add / remove a folder in that list (the folder itself stays)", - "storebound apps add --store apple|play --app-id [--account ] [--name ] [--bundle-id ]" + "storebound apps add --store apple|play --app-id [--account ] [--name ] [--bundle-id ]", + "storebound apps relink [--root ]... [--dry] after a move: \"folder not found\" entries -> the same app here" ], "art": [ "storebound art pull [--store apple|play] [--write] [--force] [--dry] [--json]", diff --git a/cli/lib/registry.ts b/cli/lib/registry.ts index e16a6ee..81dc840 100644 --- a/cli/lib/registry.ts +++ b/cli/lib/registry.ts @@ -12,7 +12,7 @@ // Written atomically (temp file, rename); a missing or unreadable file reads as empty (an unreadable one is kept). import { consoleLink } from './console-links'; import { createHash } from 'node:crypto'; -import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; +import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'; import { homedir } from 'node:os'; import { basename, dirname, join, resolve } from 'node:path'; @@ -87,7 +87,7 @@ export function withFolder(r: Registry, path: string, name: string | undefined, const abs = resolve(path); const have = r.projects.find(p => p.path === abs); if (have) return { registry: r, project: have, added: false }; - const project = { id: folderId(abs), path: abs, name: name?.trim() || basename(abs), added: now }; + const project = { id: folderId(abs), path: abs, name: name?.trim() || configAppName(abs) || basename(abs), added: now }; return { registry: { ...r, version: 1, projects: [...r.projects, project] }, project, added: true }; } @@ -144,3 +144,64 @@ export function removeFolder(pathOrId: string, file = registryFile()): RegistryP if (removed) writeRegistry(registry, file); return removed; } + +/** The app name a storebound config gives (`app: { name: '...' }`), read as text (no config load), else null. */ +export function configAppName(dir: string): string | null { + for (const n of ['storebound.config.ts', 'storebound.config.mts', 'storebound.config.js', 'storebound.config.mjs']) { + try { + const text = readFileSync(join(dir, n), 'utf8'); + const m = /\bapp\s*:\s*\{[^}]*?\bname\s*:\s*(['"`])([^'"`]+)\1/s.exec(text); + if (m) return m[2]!.trim(); + } catch { /* not this one */ } + } + return null; +} + +/** Folders with a storebound config under the roots (depth 4; node_modules, .git and _arsiv skipped). */ +export function configFolders(roots: string[], depth = 4): string[] { + const out: string[] = []; + const walk = (d: string, left: number) => { + let names: string[] = []; + try { names = readdirSync(d); } catch { return; } + if (names.some(n => /^storebound\.config\.(ts|mts|js|mjs)$/.test(n))) out.push(d); + if (left <= 0) return; + for (const n of names) { + if (n === 'node_modules' || n.startsWith('.') || n === '_arsiv') continue; + const p = join(d, n); + try { if (statSync(p).isDirectory()) walk(p, left - 1); } catch { /* unreadable */ } + } + }; + for (const r of roots) walk(r, depth); + return [...new Set(out)]; +} + +/** + * After a machine move the list keeps the old computer's paths ("folder not found"). For each missing folder: a + * config folder under the roots whose last path parts match (some-game, Acme/frontend), else one whose app name is + * the same as the entry's name. The id stays, so the desktop's per-app accounts and settings stay linked. Pure. + */ +export function relinkPlan(r: Registry, candidates: string[], exists: (p: string) => boolean, nameOf: (dir: string) => string | null): { id: string; name: string; from: string; to: string }[] { + const parts = (p: string) => p.split(/[\\/]+/).filter(Boolean).map(x => x.toLowerCase()); + const taken = new Set(r.projects.filter(p => exists(p.path)).map(p => resolve(p.path).toLowerCase())); + const plan: { id: string; name: string; from: string; to: string }[] = []; + for (const p of r.projects) { + if (exists(p.path)) continue; + const want = parts(p.path); + const free = candidates.filter(c => !taken.has(resolve(c).toLowerCase())); + let best: string | undefined; + for (const k of [3, 2, 1]) { + const tail = want.slice(-k).join('/'); + best = free.find(c => parts(c).slice(-k).join('/') === tail); + if (best) break; + } + best ??= free.find(c => nameOf(c)?.toLowerCase() === p.name.toLowerCase()); + if (best) { plan.push({ id: p.id, name: p.name, from: p.path, to: resolve(best) }); taken.add(resolve(best).toLowerCase()); } + } + return plan; +} + +export function applyRelink(plan: { id: string; to: string }[], file = registryFile()): void { + const r = readRegistry(file); + for (const s of plan) { const p = r.projects.find(x => x.id === s.id); if (p) p.path = s.to; } + writeRegistry(r, file); +} diff --git a/tests/registry-relink.test.ts b/tests/registry-relink.test.ts new file mode 100644 index 0000000..31d1cb6 --- /dev/null +++ b/tests/registry-relink.test.ts @@ -0,0 +1,33 @@ +// After a machine move the app folder list points at the old computer; relink finds each app here and keeps its id. +import { describe, expect, test } from 'bun:test'; +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { configAppName, configFolders, relinkPlan } from '../cli/lib/registry'; + +function app(root: string, rel: string, name: string): string { + const d = join(root, rel); mkdirSync(d, { recursive: true }); + writeFileSync(join(d, 'storebound.config.ts'), `export default { app: { name: '${name}' } };\n`); + return d; +} + +describe('apps relink', () => { + test('by the last path parts, else by the app name; ids stay; a taken folder is not reused', () => { + const root = mkdtempSync(join(tmpdir(), 'sb-relink-')); + const game = app(root, 'game-one', 'Game One'); + const front = app(root, 'Studio/frontend', 'Studio'); + const renamed = app(root, 'NewName/app', 'Old App'); + mkdirSync(join(root, 'node_modules/x'), { recursive: true }); writeFileSync(join(root, 'node_modules/x/storebound.config.ts'), ''); + const found = configFolders([root]); + expect(found.sort()).toEqual([game, front, renamed].sort()); + expect(configAppName(front)).toBe('Studio'); + const r = { version: 1 as const, projects: [ + { id: 'a', path: '/Users/old/Desktop/game-one', name: 'Game One', added: '' }, + { id: 'b', path: '/Users/old/Work/Studio/frontend', name: 'frontend', added: '' }, + { id: 'c', path: '/Users/old/Work/OldName/app', name: 'Old App', added: '' }, + { id: 'd', path: '/Users/old/gone', name: 'Gone', added: '' }, + ] }; + const plan = relinkPlan(r, found, () => false, configAppName); + expect(plan.map(p => [p.id, p.to])).toEqual([['a', game], ['b', front], ['c', renamed]]); + }); +}); From cbba936ed801ddcd48a72f3ee54df0ece3b28823 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 16:03:07 +0800 Subject: [PATCH 108/344] Entitlements reference check compares forward-slash paths on every OS (false 'not referenced by CODE_SIGN_ENTITLEMENTS' on Windows); test, pitfall 103 --- CHANGELOG.md | 2 ++ cli/apple/signing.ts | 8 +++++--- skills/store-pitfalls/SKILL.md | 8 ++++++++ tests/entitlements-ref.test.ts | 18 ++++++++++++++++++ 4 files changed, 33 insertions(+), 3 deletions(-) create mode 100644 tests/entitlements-ref.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index ac553e3..d222a34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- Windows: no false "entitlements not referenced by CODE_SIGN_ENTITLEMENTS" warning (paths compared with forward slashes). Pitfall 103. + - **`storebound apps relink`** after a machine move: every "folder not found" entry of the app folder list is pointed at the same app on this machine (by its path or its app name), ids kept so the desktop keeps its accounts and settings; `apps folders` says so when entries are missing. `apps add` names an app after its config's app name. diff --git a/cli/apple/signing.ts b/cli/apple/signing.ts index 724e56c..30ce943 100644 --- a/cli/apple/signing.ts +++ b/cli/apple/signing.ts @@ -14,7 +14,7 @@ import { ensureGcSwitch, gcSwitchPlan, readGcSwitch } from './game-center'; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'; import { homedir, tmpdir } from 'node:os'; -import { basename, dirname, join, relative, resolve as resolvePath } from 'node:path'; +import { basename, dirname, join, relative, resolve as resolvePath, sep } from 'node:path'; import type { Ctx } from '../lib/ctx'; import { confirm, need } from '../lib/ctx'; import { buildCsr, csrContent, newSigningKey, spkiOfKey } from '../lib/csr'; @@ -83,9 +83,11 @@ export function readProjectEntitlements(root: string): ProjectEntitlements[] | n for (const n of names) { const f = join(dir, n); if (n.endsWith('.entitlements')) { - const rel = relative(root, f); + // forward slashes on every OS: the pbxproj writes App/App.entitlements, Windows paths use backslashes + const rel = relative(root, f).split(sep).join('/'); + const fwd = f.split(sep).join('/'); if (isBuildCopyPath(rel) || out.some(o => o.file === rel)) continue; - out.push(projectEntitlements(rel, readFileSync(f, 'utf8'), pbx ? refs.some(r => f.endsWith('/' + r)) : null)); + out.push(projectEntitlements(rel, readFileSync(f, 'utf8'), pbx ? refs.some(r => fwd.endsWith('/' + r.replace(/\\/g, '/'))) : null)); } else if (d > 0 && !n.startsWith('.') && !['node_modules', 'Pods', 'build', 'DerivedData'].includes(n) && !n.endsWith('.xcodeproj')) { try { if (statSync(f).isDirectory()) walk(f, d - 1); } catch { /* unreadable */ } } diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index ec8c872..6f89dc2 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1243,3 +1243,11 @@ that fails without the fix (see CONTRIBUTING.md). language in the same edit. Then run `play images` for the screenshots. - **Guard:** `firstGraphics` in `cli/play/images.ts`, used by `cli/play/listing.ts` for languages Play does not have yet; it stops with the fix when the 512x512 icon is missing. + +## 103. "App.entitlements is not referenced by CODE_SIGN_ENTITLEMENTS" on Windows although it is +- **Symptom:** on Windows, `apple status` / `apple signing` warned that `ios\App\App\App.entitlements` is not + referenced, while project.pbxproj sets `CODE_SIGN_ENTITLEMENTS = App/App.entitlements` for both configurations. +- **Cause:** the check compared the Windows path (backslashes) with the pbxproj's forward-slash path. +- **Do:** update storebound; the warning was false. +- **Guard:** `readProjectEntitlements` in `cli/apple/signing.ts` compares forward-slash paths on every OS + (`tests/entitlements-ref.test.ts`). diff --git a/tests/entitlements-ref.test.ts b/tests/entitlements-ref.test.ts new file mode 100644 index 0000000..8d1c56c --- /dev/null +++ b/tests/entitlements-ref.test.ts @@ -0,0 +1,18 @@ +// The entitlements file the pbxproj names is "referenced" on every OS (Windows paths use backslashes; pitfall 103). +import { expect, test } from 'bun:test'; +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { readProjectEntitlements } from '../cli/apple/signing'; + +test('CODE_SIGN_ENTITLEMENTS = App/App.entitlements matches ios/App/App/App.entitlements', () => { + const root = mkdtempSync(join(tmpdir(), 'sb-ent-')); + mkdirSync(join(root, 'ios/App/App.xcodeproj'), { recursive: true }); + mkdirSync(join(root, 'ios/App/App'), { recursive: true }); + writeFileSync(join(root, 'ios/App/App.xcodeproj/project.pbxproj'), 'buildSettings = { CODE_SIGN_ENTITLEMENTS = App/App.entitlements; };\n'); + writeFileSync(join(root, 'ios/App/App/App.entitlements'), 'com.apple.developer.game-center'); + const r = readProjectEntitlements(root)!; + expect(r).toHaveLength(1); + expect(r[0]!.file).toBe('ios/App/App/App.entitlements'); + expect(r[0]!.referenced).toBe(true); +}); From 294fa322e2cbd8bd0b737853294f375b52052b88 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 15:03:45 +0700 Subject: [PATCH 109/344] storebound 0.8.28: version in package.json and every copy, CHANGELOG 0.8.28 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 6c2381f..7000a74 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.27", + "version": "0.8.28", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index c750978..7535e7a 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.27", + "version": "0.8.28", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index c444524..e0abd17 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.27", + "version": "0.8.28", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index d222a34..1781c80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.28 · 2026-10-22 + - Windows: no false "entitlements not referenced by CODE_SIGN_ENTITLEMENTS" warning (paths compared with forward slashes). Pitfall 103. - **`storebound apps relink`** after a machine move: every "folder not found" entry of the app folder list is pointed at diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 4c959fa..4ed3263 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.27", + "version": "0.8.28", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index f528243..4dc267b 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4096,7 +4096,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.27" +version = "0.8.28" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 1a55690..1ad40b3 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.27" +version = "0.8.28" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 6cba48d..33afde1 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.27", + "version": "0.8.28", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index a727731..90ed811 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.27", + "version": "0.8.28", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index 220d0c1..e3dcb1f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.27", + "version": "0.8.28", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From 4b0f9cd5b8a62ba09a2b7086076e797776899721 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 20:28:16 +0800 Subject: [PATCH 110/344] apple iap: the dry run shows a live price that differs from the config (USA base and overrides) and --allow-price-changes replaces the price schedule; prices diff (the catalog diff report) --- cli/apple/iap.ts | 44 +++++++++++++++++++++++++++++------------ cli/data/flags.json | 48 ++++++++++++++++++++++++++++++++++++++------- cli/prices.ts | 4 +++- 3 files changed, 75 insertions(+), 21 deletions(-) diff --git a/cli/apple/iap.ts b/cli/apple/iap.ts index 6a580f6..0536a44 100644 --- a/cli/apple/iap.ts +++ b/cli/apple/iap.ts @@ -1,7 +1,8 @@ // In-app purchases on App Store Connect: create missing products, localizations, price schedule (USA base + your // overrides; Apple equalizes every other storefront) and availability (every territory + new ones). Idempotent: -// existing products and schedules are left alone (prices of an existing schedule are not changed; do that in the UI). -// storebound apple iap [--dry] [--only id1,id2] +// existing products are left alone; a price that differs from the config (USA base and overrides) is shown in the plan +// and changed only with --allow-price-changes (live prices are the owner's call; Acme 2026-10-22: the plan was silent). +// storebound apple iap [--dry] [--only id1,id2] [--allow-price-changes] // Then `apple iap-review` for the review screenshots. First IAPs can only be submitted together with an app version, // from the IAP page in the web UI (see the store-iap-setup skill). // --dry reads everything (read-only) and prints one plan row per product. After a real run the store's product list @@ -18,6 +19,7 @@ import { appleTerritory, nearestPrices, samePrice } from '../lib/money'; import { createOnce, findOrCreate, getById } from '../lib/upsert'; import { ascClient, type J } from './asc'; import * as rt from '../lib/rt'; +import { appleCurrent } from '../prices'; /** Product type -> InAppPurchaseType (POST /v2/inAppPurchases). */ export const APPLE_IAP_TYPE = { consumable: 'CONSUMABLE', non_consumable: 'NON_CONSUMABLE', non_renewing: 'NON_RENEWING_SUBSCRIPTION' } as const; @@ -42,6 +44,24 @@ export async function run(ctx: Ctx): Promise { throw new Error(`${territory} has no ${price} price point (nearest ${nearestPrices(seen, price).join(', ')})`); } + const wanted = (p: (typeof products)[number]) => [{ territory: 'USA', price: p.usd }, ...(p.overrides ?? []).map(o => ({ territory: appleTerritory(o), price: o.price }))]; + /** "USA 9.99 -> 12.99" per territory whose live (current, not scheduled) manual price differs from the config. */ + async function priceDiffs(id: string, p: (typeof products)[number]): Promise { + const live = (await appleCurrent(c, id, p.id, false)).rows.filter(x => !x.startDate || x.startDate <= new Date().toISOString().slice(0, 10)); + return wanted(p).flatMap(w => { const cur = live.find(x => x.territory === w.territory); return cur && !samePrice(cur.price, w.price) ? [`${w.territory} ${cur.price} -> ${w.price}`] : []; }); + } + async function writeSchedule(id: string, manual: { territory: string; price: number }[]): Promise { + const points = await Promise.all(manual.map(m => pricePoint(id, m.territory, m.price))); + await c.asc('POST', '/v1/inAppPurchasePriceSchedules', { + data: { type: 'inAppPurchasePriceSchedules', relationships: { + inAppPurchase: { data: { type: 'inAppPurchases', id } }, + baseTerritory: { data: { type: 'territories', id: 'USA' } }, + manualPrices: { data: manual.map(m => ({ type: 'inAppPurchasePrices', id: '${' + m.territory + '}' })) } } }, + included: manual.map((m, k) => ({ type: 'inAppPurchasePrices', id: '${' + m.territory + '}', attributes: { startDate: null }, + relationships: { inAppPurchasePricePoint: { data: { type: 'inAppPurchasePricePoints', id: points[k] } } } })), + }); + } + const allowPrices = ctx.args.has('allow-price-changes'); const rows: PlanRow[] = []; const created: string[] = []; for (const [i, p] of products.entries()) { @@ -76,17 +96,13 @@ export async function run(ctx: Ctx): Promise { const sched = await c.maybe(`/v2/inAppPurchases/${id}/iapPriceSchedule?include=manualPrices`); if (!sched?.included?.length) { - const manual = [{ territory: 'USA', price: p.usd }, ...(p.overrides ?? []).map(o => ({ territory: appleTerritory(o), price: o.price }))]; - const points = await Promise.all(manual.map(m => pricePoint(id, m.territory, m.price))); - await c.asc('POST', '/v1/inAppPurchasePriceSchedules', { - data: { type: 'inAppPurchasePriceSchedules', relationships: { - inAppPurchase: { data: { type: 'inAppPurchases', id } }, - baseTerritory: { data: { type: 'territories', id: 'USA' } }, - manualPrices: { data: manual.map(m => ({ type: 'inAppPurchasePrices', id: '${' + m.territory + '}' })) } } }, - included: manual.map((m, k) => ({ type: 'inAppPurchasePrices', id: '${' + m.territory + '}', attributes: { startDate: null }, - relationships: { inAppPurchasePricePoint: { data: { type: 'inAppPurchasePricePoints', id: points[k] } } } })), - }); + const manual = wanted(p); + await writeSchedule(id, manual); log('apple', ` prices ${manual.map(m => `${m.territory} ${m.price}`).join(', ')}`); + } else { + const diff = await priceDiffs(id, p); + if (diff.length && allowPrices) { await writeSchedule(id, wanted(p)); log('apple', ` prices changed: ${diff.join(', ')} (takes effect today; Apple equalizes the other storefronts)`); } + else if (diff.length) log('apple', ` prices differ from the config, NOT changed: ${diff.join(', ')} (live prices: re-run with --allow-price-changes after the owner's yes)`); } const avail = await c.maybe(`/v2/inAppPurchases/${id}/inAppPurchaseAvailability`); @@ -120,7 +136,9 @@ export async function run(ctx: Ctx): Promise { const add = locales.filter(l => !have.has(l)); const sched = await c.maybe(`/v2/inAppPurchases/${id}/iapPriceSchedule?include=manualPrices`); const avail = await c.maybe(`/v2/inAppPurchases/${id}/inAppPurchaseAvailability`); - const parts = [add.length ? `localizations ${add.join(', ')}` : '', sched?.included?.length ? '' : `prices ${prices}`, avail?.data ? '' : `availability ${territories.length} territories + new ones`].filter(Boolean); + const diff = sched?.included?.length ? await priceDiffs(id, p) : []; + const priceNote = !sched?.included?.length ? `prices ${prices}` : diff.length ? `PRICE CHANGE ${diff.join(', ')}${allowPrices ? '' : ' (only with --allow-price-changes)'}` : ''; + const parts = [add.length ? `localizations ${add.join(', ')}` : '', priceNote, avail?.data ? '' : `availability ${territories.length} territories + new ones`].filter(Boolean); return parts.length ? { item: p.id, action: 'update', detail: `${parts.join('; ')} (state ${state ?? '?'})` } : { item: p.id, action: 'keep' }; } } diff --git a/cli/data/flags.json b/cli/data/flags.json index 6c48e61..fe63096 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -107,7 +107,31 @@ "keychain", "no-install" ], - "apple iap": [], + "apple iap": [ + "all", + "allow-price-changes", + "base", + "ceiling", + "csv", + "file", + "floor", + "include-high-income", + "max-level", + "max-ratio", + "min-ratio", + "no-only-decreases", + "no-subscriptions", + "offline", + "only-decreases", + "out", + "reconvert", + "source", + "store", + "threshold", + "update-bigmac", + "with-automatic", + "write" + ], "apple iap-review": [], "apple iap-submit": [ "new-version", @@ -144,8 +168,10 @@ "reconvert", "source", "store", + "threshold", "update-bigmac", - "with-automatic" + "with-automatic", + "write" ], "apple ppo": [ "experiment", @@ -253,8 +279,10 @@ "reconvert", "source", "store", + "threshold", "update-bigmac", - "with-automatic" + "with-automatic", + "write" ], "apple testflight": [ "build", @@ -309,8 +337,10 @@ "reconvert", "source", "store", + "threshold", "update-bigmac", - "with-automatic" + "with-automatic", + "write" ], "apps": [ "app-id", @@ -683,8 +713,10 @@ "reconvert", "source", "store", + "threshold", "update-bigmac", - "with-automatic" + "with-automatic", + "write" ], "play upload": [ "include-drafts", @@ -717,8 +749,10 @@ "reconvert", "source", "store", + "threshold", "update-bigmac", - "with-automatic" + "with-automatic", + "write" ], "privacy-manifest": [ "ios", @@ -1262,7 +1296,7 @@ "storebound apple game-center [status] [--dry] [--yes] [--json]" ], "apple iap": [ - "storebound apple iap [--dry] [--only id1,id2]" + "storebound apple iap [--dry] [--only id1,id2] [--allow-price-changes]" ], "apple iap-review": [ "storebound apple iap-review [--dry]" diff --git a/cli/prices.ts b/cli/prices.ts index 18a7d71..2964f8e 100644 --- a/cli/prices.ts +++ b/cli/prices.ts @@ -64,7 +64,9 @@ export async function run(ctx: Ctx): Promise { const a = ctx.args; const sub = a._[0]; if (sub === 'ppp') return (await import('./prices-ppp')).run(ctx); - if (sub !== 'export' && sub !== 'import') throw new Error('usage: storebound prices export | import [--csv store/prices.csv] [--dry] | ppp [--base ] [--dry]'); + // `prices diff`: the config's prices against both stores (the same read-only report as `catalog diff`) + if (sub === 'diff') { ctx.args._.splice(0, 1, 'diff'); return (await import('./catalog')).run(ctx); } + if (sub !== 'export' && sub !== 'import') throw new Error('usage: storebound prices export | import [--csv store/prices.csv] [--dry] | diff | ppp [--base ] [--dry]'); const store = a.get('store'); if (store && store !== 'apple' && store !== 'play') throw new Error('--store apple | play'); const useApple = (!store || store === 'apple') && !!config.apple; From f7ff52dfddc0e47f9fe0a3c10f047a4b45af3fbb Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 20:32:52 +0800 Subject: [PATCH 111/344] apple iap: existing products are compared with the config: localization name / description, reference name, review note (patched), family sharing (reported; on only), availability territories; all shown in the dry plan, one line each --- cli/apple/iap.ts | 86 ++++++++++++++++++++++++++++++++--- tests/apple-iap-drift.test.ts | 64 ++++++++++++++++++++++++++ 2 files changed, 144 insertions(+), 6 deletions(-) create mode 100644 tests/apple-iap-drift.test.ts diff --git a/cli/apple/iap.ts b/cli/apple/iap.ts index 0536a44..39cc4f7 100644 --- a/cli/apple/iap.ts +++ b/cli/apple/iap.ts @@ -24,6 +24,50 @@ import { appleCurrent } from '../prices'; /** Product type -> InAppPurchaseType (POST /v2/inAppPurchases). */ export const APPLE_IAP_TYPE = { consumable: 'CONSUMABLE', non_consumable: 'NON_CONSUMABLE', non_renewing: 'NON_RENEWING_SUBSCRIPTION' } as const; +// one plan line per change: store texts carry line breaks, which broke the dry-run table +const clip = (s: string, n = 40): string => { const a = [...s.replace(/\s+/g, ' ').trim()]; return a.length > n ? `${a.slice(0, n - 1).join('')}…` : a.join(''); }; + +export type IapLocalization = { locale: string; id?: string; name: string; description: string }; +export type IapLocalizationChange = { locale: string; id: string; attrs: { name?: string; description?: string }; note: string }; +/** Existing locales whose name/description differ from the config: the attributes to PATCH and a short plan note. */ +export function iapLocalizationChanges(store: IapLocalization[], wanted: IapLocalization[]): IapLocalizationChange[] { + const out: IapLocalizationChange[] = []; + for (const w of wanted) { + const s = store.find(x => x.locale === w.locale); + if (!s?.id) continue; + const attrs: { name?: string; description?: string } = {}; + const parts: string[] = []; + if ((s.name ?? '') !== w.name) { attrs.name = w.name; parts.push(`name "${clip(s.name ?? '')}" -> "${clip(w.name)}"`); } + if ((s.description ?? '') !== w.description) { attrs.description = w.description; parts.push(`description "${clip(s.description ?? '')}" -> "${clip(w.description)}"`); } + if (parts.length) out.push({ locale: w.locale, id: s.id, attrs, note: `localization ${w.locale}: ${parts.join(', ')}` }); + } + return out; +} + +export type IapAttributes = { name?: string; reviewNote?: string; familySharable?: boolean }; +export type IapAttributeChanges = { patch: { name?: string; reviewNote?: string; familySharable?: true }; notes: string[]; familyMismatch: string | null }; +/** Product attributes: referenceName (`name`), reviewNote (only when the config sets one), familySharable (on only; Apple cannot turn it off). */ +export function iapAttributeChanges(store: IapAttributes, wanted: IapAttributes): IapAttributeChanges { + const patch: IapAttributeChanges['patch'] = {}; + const notes: string[] = []; + let familyMismatch: string | null = null; + if (wanted.name !== undefined && (store.name ?? '') !== wanted.name) { patch.name = wanted.name; notes.push(`referenceName "${clip(store.name ?? '')}" -> "${clip(wanted.name)}"`); } + if (wanted.reviewNote !== undefined && (store.reviewNote ?? '') !== wanted.reviewNote) { patch.reviewNote = wanted.reviewNote; notes.push(`reviewNote "${clip(store.reviewNote ?? '')}" -> "${clip(wanted.reviewNote)}"`); } + const wantFam = wanted.familySharable ?? false, haveFam = store.familySharable ?? false; + if (wantFam && !haveFam) { patch.familySharable = true; notes.push('familySharable false -> true (Apple cannot turn it off again)'); } + else if (!wantFam && haveFam) familyMismatch = 'familySharable is on in the store but off in the config (Apple cannot turn it off; not changed)'; + return { patch, notes, familyMismatch }; +} + +/** Availability: null when the store covers every wanted territory and new ones; else "N -> M" (a POST replaces it). */ +export function availabilityChange(store: { territories: string[]; newTerritories: boolean } | null, territories: string[]): { from: number; to: number; note: string } | null { + const have = new Set(store?.territories ?? []); + const missing = territories.filter(t => !have.has(t)); + if (store && !missing.length && store.newTerritories) return null; + const from = store ? have.size : 0; + return { from, to: territories.length, note: `availability: ${from} -> ${territories.length} territories${store && !store.newTerritories ? ' (+ new territories on)' : ''}` }; +} + export async function run(ctx: Ctx): Promise { const { config, root } = ctx.loaded; const bundleId = need(config.apple?.bundleId, 'apple.bundleId'); @@ -50,6 +94,15 @@ export async function run(ctx: Ctx): Promise { const live = (await appleCurrent(c, id, p.id, false)).rows.filter(x => !x.startDate || x.startDate <= new Date().toISOString().slice(0, 10)); return wanted(p).flatMap(w => { const cur = live.find(x => x.territory === w.territory); return cur && !samePrice(cur.price, w.price) ? [`${w.territory} ${cur.price} -> ${w.price}`] : []; }); } + const locOf = (x: J) => ({ locale: x.attributes.locale as string, name: (x.attributes.name ?? '') as string, description: (x.attributes.description ?? '') as string }); + const wantedLocs = (p: (typeof products)[number]) => Object.entries(p.listings).flatMap(([k, l]) => { const locale = langs.get(k)?.apple; return locale ? [{ locale, name: l.title, description: l.description }] : []; }); + const wantedAttrs = (p: (typeof products)[number]): IapAttributes => ({ name: p.referenceName ?? Object.values(p.listings)[0]!.title, reviewNote: p.reviewNote, familySharable: p.familySharable }); + /** The store's availability as territory ids + the new-territories flag (null when there is none). */ + async function readAvail(avail: J | null | undefined): Promise<{ territories: string[]; newTerritories: boolean } | null> { + if (!avail?.data) return null; + const ts = (await c.all(`/v1/inAppPurchaseAvailabilities/${avail.data.id}/availableTerritories?limit=200`)).map((t: J) => t.id as string); + return { territories: ts, newTerritories: avail.data.attributes?.availableInNewTerritories === true }; + } async function writeSchedule(id: string, manual: { territory: string; price: number }[]): Promise { const points = await Promise.all(manual.map(m => pricePoint(id, m.territory, m.price))); await c.asc('POST', '/v1/inAppPurchasePriceSchedules', { @@ -82,7 +135,8 @@ export async function run(ctx: Ctx): Promise { log('apple', `${tag}: ${made.created ? 'created' : 'exists'}`); const locsOf = async () => await c.all(`/v2/inAppPurchases/${id}/inAppPurchaseLocalizations`); - const have = new Set((await locsOf()).map((l: J) => l.attributes.locale)); + const storeLocs = await locsOf(); + const have = new Set(storeLocs.map((l: J) => l.attributes.locale)); for (const [langId, l] of Object.entries(p.listings)) { const locale = langs.get(langId)?.apple; if (!locale || have.has(locale)) continue; @@ -93,6 +147,22 @@ export async function run(ctx: Ctx): Promise { relationships: { inAppPurchaseV2: { data: { type: 'inAppPurchases', id } } } } })).data }); log('apple', ` localization ${locale}`); } + for (const ch of iapLocalizationChanges(storeLocs.map((x: J) => ({ id: x.id, ...locOf(x) })), wantedLocs(p))) { + const l = Object.entries(p.listings).find(([k]) => langs.get(k)?.apple === ch.locale)![1]; + if ([...l.description].length > APPLE_IAP_LIMITS.description) throw new Error(`${p.id} ${ch.locale}: description over ${APPLE_IAP_LIMITS.description} characters (Apple limit)`); + if ([...l.title].length > APPLE_IAP_LIMITS.name) throw new Error(`${p.id} ${ch.locale}: name over ${APPLE_IAP_LIMITS.name} characters (Apple limit)`); + await c.asc('PATCH', `/v1/inAppPurchaseLocalizations/${ch.id}`, { data: { type: 'inAppPurchaseLocalizations', id: ch.id, attributes: ch.attrs } }); + log('apple', ` ${ch.note}`); + } + if (!made.created) { + const cur = (await c.asc('GET', `/v2/inAppPurchases/${id}`)).data?.attributes ?? {}; + const ac = iapAttributeChanges(cur, wantedAttrs(p)); + if (Object.keys(ac.patch).length) { + await c.asc('PATCH', `/v2/inAppPurchases/${id}`, { data: { type: 'inAppPurchases', id, attributes: ac.patch } }); + log('apple', ` product updated: ${ac.notes.join(', ')}`); + } + if (ac.familyMismatch) log('apple', ` ${ac.familyMismatch}`); + } const sched = await c.maybe(`/v2/inAppPurchases/${id}/iapPriceSchedule?include=manualPrices`); if (!sched?.included?.length) { @@ -106,11 +176,12 @@ export async function run(ctx: Ctx): Promise { } const avail = await c.maybe(`/v2/inAppPurchases/${id}/inAppPurchaseAvailability`); - if (!avail?.data) { + const availDiff = availabilityChange(await readAvail(avail), territories); + if (availDiff) { await c.asc('POST', '/v1/inAppPurchaseAvailabilities', { data: { type: 'inAppPurchaseAvailabilities', attributes: { availableInNewTerritories: true }, relationships: { inAppPurchase: { data: { type: 'inAppPurchases', id } }, availableTerritories: { data: territories.map(t => ({ type: 'territories', id: t })) } } } }); - log('apple', ` available in ${territories.length} territories + new ones`); + log('apple', ` ${avail?.data ? availDiff.note : `available in ${territories.length} territories + new ones`}`); } } if (dry) { @@ -132,13 +203,16 @@ export async function run(ctx: Ctx): Promise { const locales = Object.keys(p.listings).map(l => langs.get(l)?.apple).filter((l): l is string => !!l); const prices = [`USA ${p.usd}`, ...(p.overrides ?? []).map(o => `${appleTerritory(o)} ${o.price}`)].join(', '); if (!id) return { item: p.id, action: 'create', detail: `${APPLE_IAP_TYPE[p.type]}; localizations ${locales.join(', ')}; prices ${prices}; ${territories.length} territories + new ones` }; - const have = new Set((await c.all(`/v2/inAppPurchases/${id}/inAppPurchaseLocalizations`)).map((l: J) => l.attributes.locale)); + const storeLocs = await c.all(`/v2/inAppPurchases/${id}/inAppPurchaseLocalizations`); + const have = new Set(storeLocs.map((l: J) => l.attributes.locale)); + const locChanges = iapLocalizationChanges(storeLocs.map((x: J) => ({ id: x.id, ...locOf(x) })), wantedLocs(p)); + const ac = iapAttributeChanges((await c.asc('GET', `/v2/inAppPurchases/${id}`)).data?.attributes ?? {}, wantedAttrs(p)); + const availDiff = availabilityChange(await readAvail(await c.maybe(`/v2/inAppPurchases/${id}/inAppPurchaseAvailability`)), territories); const add = locales.filter(l => !have.has(l)); const sched = await c.maybe(`/v2/inAppPurchases/${id}/iapPriceSchedule?include=manualPrices`); - const avail = await c.maybe(`/v2/inAppPurchases/${id}/inAppPurchaseAvailability`); const diff = sched?.included?.length ? await priceDiffs(id, p) : []; const priceNote = !sched?.included?.length ? `prices ${prices}` : diff.length ? `PRICE CHANGE ${diff.join(', ')}${allowPrices ? '' : ' (only with --allow-price-changes)'}` : ''; - const parts = [add.length ? `localizations ${add.join(', ')}` : '', priceNote, avail?.data ? '' : `availability ${territories.length} territories + new ones`].filter(Boolean); + const parts = [add.length ? `localizations ${add.join(', ')}` : '', priceNote, ...locChanges.map(x => x.note), ...ac.notes, ac.familyMismatch ? `MISMATCH ${ac.familyMismatch}` : '', availDiff?.note ?? ''].filter(Boolean); return parts.length ? { item: p.id, action: 'update', detail: `${parts.join('; ')} (state ${state ?? '?'})` } : { item: p.id, action: 'keep' }; } } diff --git a/tests/apple-iap-drift.test.ts b/tests/apple-iap-drift.test.ts new file mode 100644 index 0000000..cd10d4b --- /dev/null +++ b/tests/apple-iap-drift.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, test } from 'bun:test'; +import { availabilityChange, iapAttributeChanges, iapLocalizationChanges } from '../cli/apple/iap'; + +describe('iapLocalizationChanges', () => { + const store = [{ id: 'l1', locale: 'en-US', name: 'Coins', description: 'A pile of coins' }, { id: 'l2', locale: 'de-DE', name: 'Muenzen', description: 'Viele' }]; + test('no difference means no change', () => { + expect(iapLocalizationChanges(store, [{ locale: 'en-US', name: 'Coins', description: 'A pile of coins' }])).toEqual([]); + }); + test('only the changed attribute is patched', () => { + const r = iapLocalizationChanges(store, [{ locale: 'en-US', name: 'Coins', description: 'More coins' }]); + expect(r).toHaveLength(1); + expect(r[0]!.id).toBe('l1'); + expect(r[0]!.attrs).toEqual({ description: 'More coins' }); + expect(r[0]!.note).toBe('localization en-US: description "A pile of coins" -> "More coins"'); + }); + test('name and description, long text truncated, missing locales skipped', () => { + const long = 'x'.repeat(100); + const r = iapLocalizationChanges(store, [{ locale: 'de-DE', name: 'Gold', description: long }, { locale: 'fr-FR', name: 'a', description: 'b' }]); + expect(r).toHaveLength(1); + expect(r[0]!.attrs).toEqual({ name: 'Gold', description: long }); + expect(r[0]!.note).toContain('name "Muenzen" -> "Gold"'); + expect(r[0]!.note.length).toBeLessThan(120); + }); +}); + +describe('iapAttributeChanges', () => { + test('equal attributes: nothing', () => { + const r = iapAttributeChanges({ name: 'com.example.coins', reviewNote: 'n', familySharable: false }, { name: 'com.example.coins', reviewNote: 'n', familySharable: false }); + expect(r.patch).toEqual({}); + expect(r.notes).toEqual([]); + expect(r.familyMismatch).toBeNull(); + }); + test('referenceName and reviewNote differ', () => { + const r = iapAttributeChanges({ name: 'Old', reviewNote: 'a' }, { name: 'New', reviewNote: 'b' }); + expect(r.patch).toEqual({ name: 'New', reviewNote: 'b' }); + expect(r.notes).toHaveLength(2); + }); + test('reviewNote not set in the config is not compared', () => { + expect(iapAttributeChanges({ name: 'A', reviewNote: 'kept' }, { name: 'A' }).patch).toEqual({}); + }); + test('familySharable can be turned on, never off', () => { + expect(iapAttributeChanges({ name: 'A', familySharable: false }, { name: 'A', familySharable: true }).patch).toEqual({ familySharable: true }); + const off = iapAttributeChanges({ name: 'A', familySharable: true }, { name: 'A', familySharable: false }); + expect(off.patch).toEqual({}); + expect(off.familyMismatch).toContain('familySharable'); + }); +}); + +describe('availabilityChange', () => { + const all = ['USA', 'DEU', 'FRA']; + test('complete availability with new territories: no change', () => { + expect(availabilityChange({ territories: ['USA', 'DEU', 'FRA', 'ITA'], newTerritories: true }, all)).toBeNull(); + }); + test('fewer territories', () => { + const r = availabilityChange({ territories: ['USA'], newTerritories: true }, all); + expect(r?.note).toBe('availability: 1 -> 3 territories'); + }); + test('new territories off', () => { + expect(availabilityChange({ territories: all, newTerritories: false }, all)?.note).toContain('new territories on'); + }); + test('no availability at all', () => { + expect(availabilityChange(null, all)).toMatchObject({ from: 0, to: 3 }); + }); +}); From f2b841d73576195b19ad18ee2dc1c416141bbe72 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 20:33:46 +0800 Subject: [PATCH 112/344] apple appinfo: live app price and availability compared with the config (price change needs --allow-price-changes, territory removals --allow-availability-changes); review-details --dry reads the store and shows old -> new (masked) --- cli/apple/appinfo.ts | 86 ++++++++++++++++++++++++++++++++----- cli/apple/review-details.ts | 27 +++++++++++- tests/appinfo-drift.test.ts | 68 +++++++++++++++++++++++++++++ 3 files changed, 168 insertions(+), 13 deletions(-) create mode 100644 tests/appinfo-drift.test.ts diff --git a/cli/apple/appinfo.ts b/cli/apple/appinfo.ts index 7eb176f..d99b83b 100644 --- a/cli/apple/appinfo.ts +++ b/cli/apple/appinfo.ts @@ -1,5 +1,5 @@ // App-level App Store settings (idempotent), from apple.info in storebound.config.ts: -// storebound apple appinfo [--dry] [--json] +// storebound apple appinfo [--dry] [--json] [--allow-price-changes] [--allow-availability-changes] // Every run first reads the current values and prints the plan (old -> new per field); --dry stops there, the real run // asks in a terminal and changes only what differs. // - categories (primary + up to two subcategories for games, secondary) @@ -22,14 +22,52 @@ const CATEGORY_RELS = ['primaryCategory', 'primarySubcategoryOne', 'primarySubca const str = (v: unknown): string => (v === null || v === undefined ? '' : String(v)); /** The plan of one `apple appinfo` run, from read-only GETs. */ -export interface AppInfoPlan { appInfoId: string; items: ItemPlan[]; freePricePointId: string | null; territories: string[]; changes: number } +export interface AppInfoPlan { appInfoId: string; items: ItemPlan[]; freePricePointId: string | null; territories: string[]; changes: number; + /** Item keys that differ but are NOT applied (price without --allow-price-changes, territory removal without --allow-availability-changes). */ + blocked: string[] } + +type J = any; // eslint-disable-line @typescript-eslint/no-explicit-any + +/** The manual base price of an app price schedule as a label ('Free' or '4.99'), from GET appPriceSchedule/manualPrices + * ?include=appPricePoint. The current price is the one without a start date or the latest one already started. Pure. */ +export function currentBasePrice(page: { data?: J[]; included?: J[] } | null | undefined, today: string = new Date().toISOString().slice(0, 10)): string | null { + const points = new Map(); + for (const x of Array.isArray(page?.included) ? page!.included! : []) if (x.type === 'appPricePoints') points.set(x.id, String(x.attributes?.customerPrice ?? '')); + const started = (Array.isArray(page?.data) ? page!.data! : []).filter(p => !p.attributes?.startDate || String(p.attributes.startDate) <= today) + .sort((a, b) => String(a.attributes?.startDate ?? '').localeCompare(String(b.attributes?.startDate ?? ''))); + const cur = started[started.length - 1]; + const raw = cur ? points.get(cur.relationships?.appPricePoint?.data?.id) : undefined; + if (raw === undefined || raw === '' || Number.isNaN(Number(raw))) return null; + return Number(raw) === 0 ? 'Free' : String(Number(raw)); +} + +export interface AvailabilityNow { availableInNewTerritories: boolean; available: string[] } +export interface AvailabilityPlan { add: string[]; remove: string[]; newFlagChange: boolean; differs: boolean; from: string; to: string } + +/** Territory ids that are available now, from the pages of /v2/appAvailabilities/{id}/territoryAvailabilities. Pure. */ +export function availableTerritories(pages: { data?: J[] }[]): string[] { + return pages.flatMap(p => p.data ?? []).filter(t => t.attributes?.available === true).map(t => String(t.relationships?.territory?.data?.id ?? '')).filter(Boolean); +} + +/** Current availability against the wanted one (the listed territories, availableInNewTerritories true). Pure. */ +export function planAvailability(cur: AvailabilityNow, wanted: string[]): AvailabilityPlan { + const have = new Set(cur.available), want = new Set(wanted); + const add = wanted.filter(t => !have.has(t)), remove = cur.available.filter(t => !want.has(t)); + const newFlagChange = !cur.availableInNewTerritories; + return { add, remove, newFlagChange, differs: !!(add.length || remove.length || newFlagChange), from: `${cur.available.length} territories`, to: `${wanted.length} territories` }; +} + +/** Differing items that are held back: money needs --allow-price-changes, territory removal --allow-availability-changes. Pure. */ +export function blockedItems(o: { priceDiffers: boolean; removes: boolean; allowPrice: boolean; allowAvailability: boolean }): string[] { + return [...(o.priceDiffers && !o.allowPrice ? ['price'] : []), ...(o.removes && !o.allowAvailability ? ['availability removal'] : [])]; +} /** The plan as text lines. Pure. */ export function appInfoPlanLines(p: AppInfoPlan): string[] { return p.items.flatMap(i => itemLines(i.key, i, '')); } -async function planAppInfo(ctx: Ctx, c: Awaited>, appId: string): Promise { +export async function planAppInfo(ctx: Ctx, c: Awaited>, appId: string, opts: { allowPrice?: boolean; allowAvailability?: boolean } = {}): Promise { const info = ctx.loaded.config.apple?.info ?? {}; const appInfo = await c.editableAppInfo(); const items: ItemPlan[] = []; @@ -48,22 +86,47 @@ async function planAppInfo(ctx: Ctx, c: Awaited>, a const app = await c.maybe(`/v1/apps/${appId}`); items.push(planItem('content rights', { attributes: { contentRightsDeclaration: str(app?.data?.attributes?.contentRightsDeclaration) } }, { contentRightsDeclaration: info.contentRights })); } - let freePricePointId: string | null = null, territories: string[] = []; + let freePricePointId: string | null = null, territories: string[] = [], priceDiffers = false, removes = false; if (info.free !== false) { const sched = await c.maybe(`/v1/apps/${appId}/appPriceSchedule?include=manualPrices`); - if (!sched?.included?.some((x: { type: string }) => x.type === 'appPrices')) { + const findFree = async (): Promise => { const free = (await c.all(`/v1/apps/${appId}/appPricePoints?filter[territory]=USA&limit=200`)).find(p => Number(p.attributes.customerPrice) === 0); if (!free) throw new Error('no free price point for USA'); - freePricePointId = free.id; + return free.id as string; + }; + if (!sched?.included?.some((x: { type: string }) => x.type === 'appPrices')) { + freePricePointId = await findFree(); items.push(planItem('price', null, { price: 'Free', baseTerritory: 'USA' })); - } else items.push(planItem('price', { attributes: { schedule: 'exists' } }, { schedule: 'exists' })); + } else { + const now = currentBasePrice(await c.maybe(`/v1/apps/${appId}/appPriceSchedule/manualPrices?include=appPricePoint&limit=50`)); + if (now === null) items.push(planItem('price', { attributes: { schedule: 'exists' } }, { schedule: 'exists' })); + else { + const it = planItem('price', { attributes: { price: now } }, { price: 'Free' }); + items.push(it); + if (it.action !== 'same') { priceDiffers = true; if (opts.allowPrice) freePricePointId = await findFree(); } + } + } const avail = await c.maybe(`/v1/apps/${appId}/appAvailabilityV2`); + const all = (await c.all('/v1/territories?limit=200')).map(t => t.id as string); if (!avail?.data) { - territories = (await c.all('/v1/territories?limit=200')).map(t => t.id); + territories = all; items.push(planItem('availability', null, { territories: `${territories.length} (all)`, availableInNewTerritories: 'true' })); - } else items.push(planItem('availability', { attributes: { availability: 'exists' } }, { availability: 'exists' })); + } else { + const pages: J[] = []; + for (let url: string | null = `/v2/appAvailabilities/${avail.data.id}/territoryAvailabilities?include=territory&limit=200`; url;) { const pg: J = await c.asc('GET', url); pages.push(pg); url = pg.links?.next ?? null; } + const have = availableTerritories(pages); + const ap = planAvailability({ availableInNewTerritories: avail.data.attributes?.availableInNewTerritories === true, available: have }, all); + items.push(planItem('availability', { attributes: { availability: ap.from, availableInNewTerritories: String(!ap.newFlagChange) } }, { availability: ap.differs ? ap.to : ap.from, availableInNewTerritories: 'true' })); + if (ap.differs) { + removes = ap.remove.length > 0; + // additions go ahead; removals only with the flag (otherwise today's set plus the additions is sent) + territories = opts.allowAvailability || !removes ? all : [...new Set([...have, ...all])]; + } + } } - return { appInfoId: appInfo.id, items, freePricePointId, territories, changes: items.filter(i => i.action !== 'same').length }; + const blocked = blockedItems({ priceDiffers, removes, allowPrice: !!opts.allowPrice, allowAvailability: !!opts.allowAvailability }); + const held = (i: ItemPlan) => i.key === 'price' && blocked.includes('price'); + return { appInfoId: appInfo.id, items, freePricePointId, territories, blocked, changes: items.filter(i => i.action !== 'same' && !held(i)).length }; } export async function run(ctx: Ctx): Promise { @@ -73,9 +136,10 @@ export async function run(ctx: Ctx): Promise { refuseTemplate(config, ['ageRating'], 'apple appinfo (age rating declaration)'); const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId); const appId = await c.app(); - const p = await planAppInfo(ctx, c, appId); + const p = await planAppInfo(ctx, c, appId, { allowPrice: ctx.args.has('allow-price-changes'), allowAvailability: ctx.args.has('allow-availability-changes') }); if (ctx.args.has('json')) printJson({ dry, ...p }); else for (const line of appInfoPlanLines(p)) console.log(line); + for (const b of p.blocked) warn('apple', b === 'price' ? "price differs from the config: not changed (live price; re-run with --allow-price-changes after the owner's yes)" : "availability would remove territories: not removed (re-run with --allow-availability-changes after the owner's yes)"); if (dry) { done('apple', `dry run: ${p.changes ? `${p.changes} change(s)` : 'nothing to change'}; read-only, nothing written`); return; } if (!p.changes) { done('apple', 'appinfo already up to date (App Privacy is UI-only: store-declarations skill)'); return; } if (stdinIsTTY() && !(await confirm(ctx, `Apply these ${p.changes} change(s) to App Store Connect?`))) { warn('apple', 'nothing written'); return; } diff --git a/cli/apple/review-details.ts b/cli/apple/review-details.ts index ab9404b..123cc50 100644 --- a/cli/apple/review-details.ts +++ b/cli/apple/review-details.ts @@ -8,12 +8,30 @@ import { refuseTemplate } from '../lib/template-answers'; import type { Ctx } from '../lib/ctx'; import { need } from '../lib/ctx'; -import { findReviewContact, noContactMessage, reviewDemoAccount } from '../lib/credentials'; +import { findReviewContact, maskSecret, maskUser, noContactMessage, reviewDemoAccount } from '../lib/credentials'; import { reviewDetailPlan } from '../lib/review-details'; import { done, log } from '../lib/log'; import { createOnce } from '../lib/upsert'; import { ascClient } from './asc'; +type Attrs = Record; +const shown = (k: string, v: unknown): string => { + if (v === null || v === undefined || v === '') return '(empty)'; + const t = String(v); + if (k === 'demoAccountPassword') return maskSecret(t); + if (k === 'demoAccountName' || k === 'contactEmail') return maskUser(t); + if (k === 'contactPhone') return `${t.slice(0, 3)}***`; + if (k === 'notes') return `${new TextEncoder().encode(t).length} bytes`; + return t; +}; + +/** Changed review-detail keys as `key: old -> new` lines (secrets, phone, email masked; notes as byte counts). A missing + * detail (cur null) lists every key as new. Pure. */ +export function reviewDetailDiff(cur: Attrs | null, want: Attrs): string[] { + return Object.entries(want).filter(([k, v]) => !cur || (cur[k] ?? null) !== (v ?? null)) + .map(([k, v]) => `${k}: ${cur ? shown(k, cur[k]) : '(none)'} -> ${shown(k, v)}`); +} + export async function run(ctx: Ctx): Promise { const { config, root } = ctx.loaded; refuseTemplate(config, ['reviewNotes', 'reviewAccess', 'accounts'], 'apple review-details (App Review notes, demo account requirement)'); @@ -40,9 +58,14 @@ export async function run(ctx: Ctx): Promise { if (!contact) throw new Error(noContactMessage(root, checked)); const { attributes, summary } = reviewDetailPlan(config, contact, reviewDemoAccount(root)); - if (ctx.args.has('dry')) { log('apple', `would set review details (contact ${from ? 'copied from ' + from : 'from credentials'}, ${summary})`); return; } const read = async () => (await c.maybe(`/v1/appStoreVersions/${version.id}/appStoreReviewDetail`))?.data ?? null; const cur = await read(); + if (ctx.args.has('dry')) { + const lines = reviewDetailDiff(cur?.attributes ?? null, attributes); + log('apple', `would ${cur ? (lines.length ? 'update' : 'keep') : 'create'} review details (contact ${from ? 'copied from ' + from : 'from credentials'}, ${summary})`); + for (const l of lines) console.log(` ${l}`); + return; + } // one review detail per version: only changed fields are sent; a new one is created once (a 409 finds it) const changed = cur ? Object.fromEntries(Object.entries(attributes).filter(([k, v]) => (cur.attributes?.[k] ?? null) !== (v ?? null))) : attributes; if (cur && !Object.keys(changed).length) { done('apple', `review details on ${version.attributes.versionString} up to date (${summary})`); return; } diff --git a/tests/appinfo-drift.test.ts b/tests/appinfo-drift.test.ts new file mode 100644 index 0000000..8eaaee6 --- /dev/null +++ b/tests/appinfo-drift.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, test } from 'bun:test'; +import { availableTerritories, blockedItems, currentBasePrice, planAvailability } from '../cli/apple/appinfo'; +import { reviewDetailDiff } from '../cli/apple/review-details'; + +const price = (id: string, startDate: string | null, point: string) => ({ type: 'appPrices', id, attributes: { startDate }, relationships: { appPricePoint: { data: { type: 'appPricePoints', id: point } } } }); +const point = (id: string, customerPrice: string) => ({ type: 'appPricePoints', id, attributes: { customerPrice } }); + +describe('currentBasePrice', () => { + test('paid price is shown as a number', () => { + expect(currentBasePrice({ data: [price('a', null, 'p1')], included: [point('p1', '4.99')] })).toBe('4.99'); + }); + test('zero is Free', () => { + expect(currentBasePrice({ data: [price('a', null, 'p1')], included: [point('p1', '0.0')] })).toBe('Free'); + }); + test('latest started price wins, future ones are ignored', () => { + const page = { data: [price('a', null, 'p1'), price('b', '2026-01-01', 'p2'), price('c', '2099-01-01', 'p3')], included: [point('p1', '0'), point('p2', '1.99'), point('p3', '9.99')] }; + expect(currentBasePrice(page, '2026-06-01')).toBe('1.99'); + }); + test('unreadable gives null', () => { + expect(currentBasePrice(null)).toBeNull(); + expect(currentBasePrice({ data: [price('a', null, 'zz')], included: [] })).toBeNull(); + }); +}); + +describe('availability', () => { + const ta = (t: string, available: boolean) => ({ attributes: { available }, relationships: { territory: { data: { id: t } } } }); + test('availableTerritories lists only available ones across pages', () => { + expect(availableTerritories([{ data: [ta('AAA', true), ta('BBB', false)] }, { data: [ta('CCC', true)] }])).toEqual(['AAA', 'CCC']); + }); + test('same set and flag: no difference', () => { + expect(planAvailability({ availableInNewTerritories: true, available: ['A', 'B'] }, ['A', 'B']).differs).toBe(false); + }); + test('missing territories are additions', () => { + const p = planAvailability({ availableInNewTerritories: true, available: ['A'] }, ['A', 'B', 'C']); + expect(p).toMatchObject({ add: ['B', 'C'], remove: [], differs: true, from: '1 territories', to: '3 territories' }); + }); + test('extra territories are removals; flag off is a change', () => { + const p = planAvailability({ availableInNewTerritories: false, available: ['A', 'X'] }, ['A']); + expect(p.remove).toEqual(['X']); + expect(p.newFlagChange).toBe(true); + }); + test('blockedItems', () => { + expect(blockedItems({ priceDiffers: true, removes: true, allowPrice: false, allowAvailability: false })).toEqual(['price', 'availability removal']); + expect(blockedItems({ priceDiffers: true, removes: true, allowPrice: true, allowAvailability: true })).toEqual([]); + expect(blockedItems({ priceDiffers: false, removes: false, allowPrice: false, allowAvailability: false })).toEqual([]); + }); +}); + +describe('reviewDetailDiff', () => { + const want = { contactPhone: '+15550001111', contactEmail: 'someone@example.com', demoAccountRequired: true, demoAccountName: 'demo-user', demoAccountPassword: 'hunter2', notes: 'Hello' }; + test('lists only changed keys and masks secrets', () => { + const lines = reviewDetailDiff({ ...want, demoAccountPassword: 'old-secret', notes: 'Hi' }, want); + expect(lines).toHaveLength(2); + expect(lines.join('\n')).not.toContain('hunter2'); + expect(lines.join('\n')).not.toContain('old-secret'); + expect(lines[0]).toBe('demoAccountPassword: ******** -> ********'); + expect(lines[1]).toBe('notes: 2 bytes -> 5 bytes'); + }); + test('nothing changed gives no lines', () => { + expect(reviewDetailDiff({ ...want }, want)).toEqual([]); + }); + test('new detail lists everything, phone and email masked', () => { + const lines = reviewDetailDiff(null, want); + expect(lines).toHaveLength(6); + expect(lines.join('\n')).not.toContain('5550001111'); + expect(lines.join('\n')).not.toContain('someone@example.com'); + }); +}); From e381bc2256f700346fa1fb28cc5e7a08899a2035 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 20:38:54 +0800 Subject: [PATCH 113/344] Drift on existing items: offer-code and win-back campaigns that differ are named (Apple cannot edit them), in-app event attributes patched on drafts, a removed custom page deep link cleared, config languages without a version localization named, data safety dry run says Play has no read API; appinfo reads /v1/appPriceSchedules/{id}/manualPrices; a new Play language without an icon warns instead of stopping; fake store lists for the new reads --- cli/apple/appinfo.ts | 2 +- cli/apple/cpp.ts | 8 ++-- cli/apple/events.ts | 11 +++++- cli/apple/offer-codes.ts | 28 +++++++++++++- cli/apple/screenshots.ts | 7 ++++ cli/apple/win-back.ts | 30 ++++++++++++++- cli/lib/cpp-events.ts | 38 ++++++++++++++++++ cli/play/data-safety.ts | 5 +++ cli/play/listing.ts | 2 +- tests/helpers/fake-stores.ts | 11 ++++++ tests/misc-drift.test.ts | 74 ++++++++++++++++++++++++++++++++++++ 11 files changed, 206 insertions(+), 10 deletions(-) create mode 100644 tests/misc-drift.test.ts diff --git a/cli/apple/appinfo.ts b/cli/apple/appinfo.ts index d99b83b..9dc2360 100644 --- a/cli/apple/appinfo.ts +++ b/cli/apple/appinfo.ts @@ -98,7 +98,7 @@ export async function planAppInfo(ctx: Ctx, c: Awaited { if (!page.version || !CPP_EDITABLE.has(page.version.state)) { log(TAG, `"${d.name}": version ${page.version?.state ?? 'missing'}, not editable (a new version: App Store Connect)`); continue; } const have = (await c.all(`/v1/appCustomProductPageVersions/${page.version.id}/appCustomProductPageLocalizations?limit=200`)).map((l: J) => ({ id: l.id, locale: l.attributes.locale, promotionalText: l.attributes.promotionalText })); reqs.push(...planCppLocales(page.version.id, have, locs)); - if ((d.deepLink ?? null) !== (page.version.deepLink ?? null) && d.deepLink) reqs.push({ method: 'PATCH', path: `/v1/appCustomProductPageVersions/${page.version.id}`, note: `"${d.name}" deep link`, - body: { data: { type: 'appCustomProductPageVersions', id: page.version.id, attributes: { deepLink: d.deepLink } } } }); + const extra = extraCppLocales(have.map(h => h.locale), locs.map(l => l.locale)); + if (extra.length) warn(TAG, `"${d.name}": locale(s) ${extra.join(', ')} are on the page but not in the config languages (not removed)`); + const dl = cppDeepLinkReq(page.version.id, d.name, d.deepLink, page.version.deepLink); + if (dl) reqs.push(dl); } if (pages.length + reqs.filter(r => r.path === '/v1/appCustomProductPages').length > CPP_LIMITS.pages) throw new Error(`more than ${CPP_LIMITS.pages} custom product pages`); if (a.has('json')) printJson({ dryRun: dry, requests: reqs.map(r => describeReq(r)) }); diff --git a/cli/apple/events.ts b/cli/apple/events.ts index 6bde356..5691256 100644 --- a/cli/apple/events.ts +++ b/cli/apple/events.ts @@ -9,7 +9,7 @@ import { existsSync, readFileSync } from 'node:fs'; import type { Ctx } from '../lib/ctx'; import { confirm, need } from '../lib/ctx'; -import { type AppEventDef, checkEventMedia, EVENT_EDITABLE, EVENT_LIMITS, eventCreateBody, planEventLocales, reviewItemReq } from '../lib/cpp-events'; +import { type AppEventDef, checkEventMedia, EVENT_EDITABLE, EVENT_LIMITS, eventAttrDiff, eventCreateBody, eventPatchReq, planEventLocales, reviewItemReq } from '../lib/cpp-events'; import { done, log, printJson, warn } from '../lib/log'; import { textTable } from '../lib/table'; import { imageInfo } from '../shots/spec'; @@ -59,7 +59,14 @@ export async function run(ctx: Ctx): Promise { const primary = localeOf(d.primaryLanguage ?? '') ?? want[0]?.locale ?? 'en-US'; const ev = events.find((e: J) => e.attributes.referenceName === d.referenceName); if (!ev) { created.push({ def: d, index: reqs.length }); reqs.push({ method: 'POST', path: '/v1/appEvents', note: `event "${d.referenceName}" (${d.badge}, ${d.schedule.eventStart} to ${d.schedule.eventEnd})`, body: eventCreateBody(appId, d, primary, d.schedule.territories ?? territories) }); continue; } - if (!EVENT_EDITABLE.has(ev.attributes.eventState)) { log(TAG, `"${d.referenceName}": ${ev.attributes.eventState}, not editable`); continue; } + const drift = eventAttrDiff(d, ev.attributes); + if (!EVENT_EDITABLE.has(ev.attributes.eventState)) { + if (drift.lines.length) warn(TAG, `"${d.referenceName}" is ${ev.attributes.eventState} and differs from the config: ${drift.lines.join('; ')} (not editable: change it in App Store Connect)`); + else log(TAG, `"${d.referenceName}": ${ev.attributes.eventState}, not editable`); + continue; + } + const patch = eventPatchReq(ev.id, d.referenceName, drift.attrs, drift.lines); + if (patch) reqs.push(patch); const have = (await c.all(`/v1/appEvents/${ev.id}/localizations?limit=200`)).map((l: J) => ({ id: l.id, ...l.attributes })); reqs.push(...planEventLocales(ev.id, have, want)); } diff --git a/cli/apple/offer-codes.ts b/cli/apple/offer-codes.ts index ce300f3..30ccc4d 100644 --- a/cli/apple/offer-codes.ts +++ b/cli/apple/offer-codes.ts @@ -21,6 +21,26 @@ import { findOrCreate, getById } from '../lib/upsert'; const TAG = 'offer-codes'; +/** Differences between an existing offer code campaign and the config (Apple does not allow editing a campaign). Pure. */ +export function campaignDiff(cur: { eligibility: string[]; prices: { territory: string; pointId?: string }[] }, + want: { eligibility: string[]; free: boolean; prices: { territory: string; pointId?: string }[] }): string[] { + const out: string[] = []; + const set = (x: string[]) => [...new Set(x)].sort(); + const a = set(cur.eligibility), b = set(want.eligibility); + if (a.join() !== b.join()) out.push(`eligibility ${a.join('+') || '(none)'} -> ${b.join('+') || '(none)'}`); + const curFree = cur.prices.length > 0 && cur.prices.every(x => !x.pointId); + if (cur.prices.length && curFree !== want.free) out.push(`mode ${curFree ? 'free' : 'paid'} -> ${want.free ? 'free' : 'paid'}`); + const ct = set(cur.prices.map(x => x.territory)), wt = set(want.prices.map(x => x.territory)); + const gone = ct.filter(t => !wt.includes(t)), added = wt.filter(t => !ct.includes(t)); + if (gone.length || added.length) out.push(`territories ${added.length ? `+${added.length} (${added.slice(0, 5).join(',')}${added.length > 5 ? ',...' : ''})` : ''}${gone.length ? ` -${gone.length} (${gone.slice(0, 5).join(',')}${gone.length > 5 ? ',...' : ''})` : ''}`.replace('territories ', 'territories ')); + if (!want.free && !curFree) { + const have = new Map(cur.prices.map(x => [x.territory, x.pointId] as const)); + const diff = want.prices.filter(x => have.has(x.territory) && have.get(x.territory) !== x.pointId).map(x => x.territory); + if (diff.length) out.push(`prices differ in ${diff.length} territor${diff.length === 1 ? 'y' : 'ies'} (${diff.slice(0, 5).join(',')}${diff.length > 5 ? ',...' : ''})`); + } + return out; +} + export async function run(ctx: Ctx): Promise { const { config, root, resolve } = ctx.loaded; const a = ctx.args; @@ -71,7 +91,13 @@ export async function run(ctx: Ctx): Promise { log(TAG, `${describeReq(req)}: ${made.created ? 'done' : 'exists already'}`); if (made.created) active++; } - } else log(TAG, `${p.id}: campaign "${oc.name}" exists (${cur.attributes.active ? 'active' : 'inactive'}, ${cur.attributes.productionCodeCount ?? 0} production codes)`); + } else { + log(TAG, `${p.id}: campaign "${oc.name}" exists (${cur.attributes.active ? 'active' : 'inactive'}, ${cur.attributes.productionCodeCount ?? 0} production codes)`); + const curPrices = (await c.all(`/v1/inAppPurchaseOfferCodes/${cur.id}/prices?include=territory,pricePoint&limit=200`)) + .map((x: J) => ({ territory: x.relationships?.territory?.data?.id as string, pointId: x.relationships?.pricePoint?.data?.id as string | undefined })).filter((x: { territory?: string }) => !!x.territory); + const diffs = campaignDiff({ eligibility: cur.attributes.customerEligibilities ?? [], prices: curPrices }, { eligibility: oc.eligibility, free: !!oc.free, prices: await prices(oc) }); + if (diffs.length) warn(TAG, `${p.id}: campaign ${oc.name} differs from the config: ${diffs.join('; ')} (Apple does not allow editing: create a new campaign with another name)`); + } const haveCustom = new Set(cur ? (await c.all(`/v1/inAppPurchaseOfferCodes/${cur.id}/customCodes?limit=200`)).map((x: J) => x.attributes.customCode) : []); for (const cc of oc.customCodes ?? []) if (!haveCustom.has(cc.code)) codeReqs.push({ req: iapCustomCodeReq(id ?? '${new campaign}', cc), product: p.id, campaign: oc.name, oneTime: false }); // one-time batches are not matched one by one: a batch is created when the campaign has fewer batches than configured diff --git a/cli/apple/screenshots.ts b/cli/apple/screenshots.ts index afcc0d5..fbb353f 100644 --- a/cli/apple/screenshots.ts +++ b/cli/apple/screenshots.ts @@ -103,6 +103,9 @@ export async function run(ctx: Ctx): Promise { const langOf = byAppleLocale(config.languages); const locs = await c.all(`/v1/appStoreVersions/${version.id}/appStoreVersionLocalizations?limit=50`); + const noLoc = missingVersionLocales(config.languages, locs.map((l: J) => l.attributes.locale as string)).filter(l => !only.length || only.includes(l)); + for (const l of noLoc) warn('apple', `${l}: in the config languages but the version has no localization (run apple listing first)`); + const syncSet = (locId: string, sets: J[], type: string, files: string[], tag: string) => syncScreenshotSet(c, { rel: 'appStoreVersionLocalization', type: 'appStoreVersionLocalizations', id: locId }, sets, type, files, tag, ctx.args.has('dry')); @@ -168,3 +171,7 @@ async function repairStuck(ctx: Ctx, c: Asc, root: string, locs: J[], src: strin if (held) log('apple', `${held} screenshot(s) still processing (under 5 min): left alone; run validate again in a few minutes`); done('apple', total ? `${dry ? 'dry run: would replace' : 'replaced'} ${total} stuck screenshot(s)` : 'no stuck screenshots'); } + +/** App Store locales of the config languages that the version has no localization for. Pure. */ +export const missingVersionLocales = (langs: { apple?: string }[], have: string[]): string[] => + [...new Set(langs.flatMap(l => (l.apple ? [l.apple] : [])))].filter(l => !have.includes(l)); diff --git a/cli/apple/win-back.ts b/cli/apple/win-back.ts index 9631dda..2ef5836 100644 --- a/cli/apple/win-back.ts +++ b/cli/apple/win-back.ts @@ -8,8 +8,8 @@ import type { Ctx } from '../lib/ctx'; import { confirm, need } from '../lib/ctx'; import { done, log, printJson, warn } from '../lib/log'; -import { type TerritoryPoint, validateWinBack, winBackBody } from '../lib/offers'; -import { allSubscriptions, applePoints, pickPoint } from '../lib/subscriptions'; +import { type TerritoryPoint, validateWinBack, type WinBackDef, winBackBody } from '../lib/offers'; +import { allSubscriptions, APPLE_OFFER_MODE, applePoints, pickPoint } from '../lib/subscriptions'; import { textTable } from '../lib/table'; import { pages } from '../prices'; import { ascClient, type J } from './asc'; @@ -17,6 +17,17 @@ import { describeReq, execute, type Req } from './jsonapi'; const TAG = 'win-back'; +/** Differences between an existing win-back offer and the config (mode, price, dates). No PATCH exists for them. `usaPrice` = the offer's USA customer price (undefined: not read, not compared). Pure. */ +export function winBackDiff(have: { offerMode?: string; startDate?: string | null; endDate?: string | null }, usaPrice: number | undefined, want: WinBackDef): string[] { + const out: string[] = []; + const mode = APPLE_OFFER_MODE[want.type]; + if (have.offerMode && have.offerMode !== mode) out.push(`mode ${have.offerMode} -> ${mode}`); + if (want.type !== 'free' && usaPrice !== undefined && want.usd !== undefined && Math.abs(usaPrice - want.usd) > 0.005) out.push(`USA price ${usaPrice} -> ${want.usd}`); + if ((have.startDate ?? '').slice(0, 10) !== want.start) out.push(`start ${have.startDate ?? '(none)'} -> ${want.start}`); + if ((have.endDate ?? '').slice(0, 10) !== (want.end ?? '')) out.push(`end ${have.endDate ?? '(none)'} -> ${want.end ?? '(none)'}`); + return out; +} + export async function run(ctx: Ctx): Promise { const { config, root } = ctx.loaded; const a = ctx.args; @@ -39,6 +50,21 @@ export async function run(ctx: Ctx): Promise { if (!remote) { skipped.push({ id: s.id, why: 'not on App Store Connect (storebound apple subscriptions)' }); continue; } const existing = await c.all(`/v1/subscriptions/${remote.id}/winBackOffers?limit=200`); for (const o of existing) rows.push([s.id, o.attributes.offerId, o.attributes.offerMode, o.attributes.startDate ?? '', o.attributes.endDate ?? '', o.attributes.priority ?? '']); + for (const o of s.winBack!) { + const x = existing.find((e: J) => e.attributes.offerId === o.id); + if (!x) continue; + let usaPrice: number | undefined; + if (o.type !== 'free') { + const pr = await pages(c, `/v1/winBackOffers/${x.id}/prices?include=territory,subscriptionPricePoint&limit=200`); + const usa = pr.data.find((r: J) => r.relationships?.territory?.data?.id === 'USA'); + const pid = usa?.relationships?.subscriptionPricePoint?.data?.id; + const inc = pid ? pr.included.find((i: J) => i.id === pid) : undefined; + const cp = Number(inc?.attributes?.customerPrice); + if (Number.isFinite(cp)) usaPrice = cp; + } + const diffs = winBackDiff(x.attributes, usaPrice, o); + if (diffs.length) warn(TAG, `${s.id}: win-back "${o.id}" differs from the config: ${diffs.join('; ')} (Apple does not allow editing: create a new offer with another id)`); + } const missing = s.winBack!.filter(o => !existing.some((x: J) => x.attributes.offerId === o.id)); if (!missing.length) continue; if (remote.attributes.state !== 'APPROVED') { skipped.push({ id: s.id, why: `subscription is ${remote.attributes.state}: win-back offers need an approved subscription` }); continue; } diff --git a/cli/lib/cpp-events.ts b/cli/lib/cpp-events.ts index e85e6ad..630fca9 100644 --- a/cli/lib/cpp-events.ts +++ b/cli/lib/cpp-events.ts @@ -200,3 +200,41 @@ export const reviewItemReq = (submissionId: string, kind: 'appCustomProductPageV method: 'POST', path: '/v1/reviewSubmissionItems', note: label, body: { data: { type: 'reviewSubmissionItems', relationships: { reviewSubmission: one('reviewSubmissions', submissionId), [kind]: one(kind === 'appEvent' ? 'appEvents' : 'appCustomProductPageVersions', id) } } }, }); + +/** Event attributes that differ from the config: `attrs` = the PATCH attributes (empty when nothing differs), `lines` = readable. Pure. */ +export function eventAttrDiff(ev: AppEventDef, now: { badge?: string; priority?: string; purpose?: string; deepLink?: string | null; territorySchedules?: { territories?: string[]; publishStart?: string; eventStart?: string; eventEnd?: string }[] }): { attrs: Record; lines: string[] } { + const attrs: Record = {}; + const lines: string[] = []; + const same = (a?: string, b?: string) => (a && b ? Date.parse(a) === Date.parse(b) : a === b); + if (now.badge !== undefined && now.badge !== ev.badge) { attrs.badge = ev.badge; lines.push(`badge ${now.badge} -> ${ev.badge}`); } + const pri = (ev.priority ?? 'normal').toUpperCase(); + if (now.priority !== undefined && now.priority !== pri) { attrs.priority = pri; lines.push(`priority ${now.priority} -> ${pri}`); } + const purpose = ev.purpose ?? 'APPROPRIATE_FOR_ALL_USERS'; + if (now.purpose !== undefined && now.purpose !== purpose) { attrs.purpose = purpose; lines.push(`purpose ${now.purpose} -> ${purpose}`); } + const s = now.territorySchedules?.[0]; + const sch: string[] = []; + if (!same(s?.publishStart, ev.schedule.publishStart)) sch.push(`publishStart ${s?.publishStart ?? '(none)'} -> ${ev.schedule.publishStart}`); + if (!same(s?.eventStart, ev.schedule.eventStart)) sch.push(`eventStart ${s?.eventStart ?? '(none)'} -> ${ev.schedule.eventStart}`); + if (!same(s?.eventEnd, ev.schedule.eventEnd)) sch.push(`eventEnd ${s?.eventEnd ?? '(none)'} -> ${ev.schedule.eventEnd}`); + const wt = ev.schedule.territories; + if (wt && [...new Set(s?.territories ?? [])].sort().join() !== [...new Set(wt)].sort().join()) sch.push(`territories ${(s?.territories ?? []).length} -> ${wt.length}`); + if (sch.length) { + attrs.territorySchedules = [{ territories: wt ?? s?.territories ?? [], publishStart: ev.schedule.publishStart, eventStart: ev.schedule.eventStart, eventEnd: ev.schedule.eventEnd }]; + lines.push(...sch); + } + return { attrs, lines }; +} + +/** PATCH /v1/appEvents/{id} with the changed attributes, null when none. */ +export const eventPatchReq = (eventId: string, name: string, attrs: Record, lines: string[]): Req | null => + Object.keys(attrs).length ? { method: 'PATCH', path: `/v1/appEvents/${eventId}`, note: `event "${name}": ${lines.join('; ')}`, body: { data: { type: 'appEvents', id: eventId, attributes: attrs } } } : null; + +/** PATCH of a page version's deep link: set, change, or clear (config has none, the page has one). Null when equal. Pure. */ +export function cppDeepLinkReq(versionId: string, name: string, want: string | undefined, have: string | null | undefined): Req | null { + if ((want ?? null) === (have ?? null)) return null; + return { method: 'PATCH', path: `/v1/appCustomProductPageVersions/${versionId}`, note: want ? `"${name}" deep link` : `"${name}" deep link removed`, + body: { data: { type: 'appCustomProductPageVersions', id: versionId, attributes: { deepLink: want ?? null } } } }; +} + +/** Locales on a page version that the config has no language for. Pure. */ +export const extraCppLocales = (have: string[], want: string[]): string[] => have.filter(l => !want.includes(l)); diff --git a/cli/play/data-safety.ts b/cli/play/data-safety.ts index 7610e43..c95eef3 100644 --- a/cli/play/data-safety.ts +++ b/cli/play/data-safety.ts @@ -50,6 +50,10 @@ export function changeLines(changes: DataSafetyChange[]): string[] { return [...(acc.length ? [' account and deletion answers:', ...acc.map(line)] : []), ...(rest.length ? [' data types and other answers:', ...rest.map(line)] : [])]; } +/** The dry-run line about the state it compares with. Pure. */ +export const dataSafetyDryNote = (last: { at: string } | null): string => + `Play has no read API for the Data safety form: this compares with the last upload from this project (${DATA_SAFETY_HASH} sha256${last ? `, uploaded ${last.at.slice(0, 16).replace('T', ' ')} UTC` : ', none recorded'}), not with the live form; --force re-sends the CSV`; + export async function run(ctx: Ctx): Promise { const { config, root, resolve } = ctx.loaded; const ds = need(config.dataSafety, 'dataSafety'); @@ -69,6 +73,7 @@ export async function run(ctx: Ctx): Promise { if (ctx.args.has('dry')) { const upFile = join(root, DATA_SAFETY_UPLOADED); const before = existsSync(upFile) ? readFileSync(upFile, 'utf8') : null; + log('play', dataSafetyDryNote(last)); const changes = dataSafetyDiff(before, rows); log('play', `changes against ${before ? `the last uploaded CSV (${DATA_SAFETY_UPLOADED}; Play cannot read the form back)` : 'nothing (no upload recorded: every answer is new)'}: ${changes.length} answer(s)`); for (const l of changeLines(changes)) console.log(l); diff --git a/cli/play/listing.ts b/cli/play/listing.ts index fc0ded4..f0dce56 100644 --- a/cli/play/listing.ts +++ b/cli/play/listing.ts @@ -171,7 +171,7 @@ export async function run(ctx: Ctx): Promise { // a language Play does not have yet: its edit only commits with a hi-res icon (pitfall 102) if (!now.some(n => n.language === b.language)) { const graphics = firstGraphics(ctx, b.language!); - if (!graphics.some(([t]) => t === 'icon')) throw new Error(`${b.language}: a new Play language needs the 512x512 icon in the same edit (play.icon or store/icons/play-512.png): storebound icons makes it`); + if (!graphics.some(([t]) => t === 'icon')) warn('play', `${b.language}: no 512x512 icon to send with this new language (play.icon or store/icons/play-512.png; storebound icons makes it): Play may refuse the commit with 403 "no high resolution icon"`); for (const [type, f] of graphics) { await play.call('POST', `${play.UPLOAD}/edits/${id}/listings/${b.language}/${type}?uploadType=media`, new Uint8Array(readFileSync(f)), { 'Content-Type': /\.png$/i.test(f) ? 'image/png' : 'image/jpeg' }); log('play', `${b.language}: ${type} uploaded with the new listing`); diff --git a/tests/helpers/fake-stores.ts b/tests/helpers/fake-stores.ts index 0a1e00d..756ebfc 100644 --- a/tests/helpers/fake-stores.ts +++ b/tests/helpers/fake-stores.ts @@ -23,6 +23,12 @@ const LISTS: Record = { 'inAppPurchases/offerCodes': { type: 'inAppPurchaseOfferCodes' }, 'inAppPurchaseOfferCodes/customCodes': { type: 'inAppPurchaseOfferCodeCustomCodes' }, 'inAppPurchaseOfferCodes/oneTimeUseCodes': { type: 'inAppPurchaseOfferCodeOneTimeUseCodes' }, + 'inAppPurchaseOfferCodes/prices': { type: 'inAppPurchaseOfferPrices' }, + 'inAppPurchasePriceSchedules/manualPrices': { type: 'inAppPurchasePrices' }, + 'inAppPurchasePriceSchedules/baseTerritory': { type: 'territories', one: true }, + 'appPriceSchedules/manualPrices': { type: 'appPrices' }, + 'inAppPurchaseAvailabilities/availableTerritories': { type: 'territories' }, + 'winBackOffers/prices': { type: 'winBackOfferPrices' }, 'apps/appStoreVersions': { type: 'appStoreVersions' }, 'appStoreVersions/appStoreVersionLocalizations': { type: 'appStoreVersionLocalizations' }, 'appStoreVersions/appStoreReviewDetail': { type: 'appStoreReviewDetails', one: true }, @@ -259,6 +265,11 @@ export class FakeAsc { const self = this.res.get(id); if (!rel) return self && self.type === type ? json({ data: this.view(self) }) : json({ errors: [{ status: '404' }] }, 404); if (rel === 'relationships') return json({ data: this.children(id, rel2!).map(r => ({ type: r.type, id: r.id })) }); + // an availability's territories are the ids its create named (a to-many relationship, not child resources) + if (rel === 'availableTerritories' && self) { + const ids = self.rels.availableTerritories; + return json({ data: (Array.isArray(ids) ? ids : ids ? [ids] : []).map(t => ({ type: 'territories', id: t })), links: {} }); + } const l = LISTS[`${type}/${rel}`]; if (!l) return json({ errors: [{ status: '599', detail: `fake: no list ${type}/${rel}` }] }, 599); const kids = this.filtered(this.children(id, l.type), u.searchParams); diff --git a/tests/misc-drift.test.ts b/tests/misc-drift.test.ts new file mode 100644 index 0000000..82cfe30 --- /dev/null +++ b/tests/misc-drift.test.ts @@ -0,0 +1,74 @@ +import { describe, expect, test } from 'bun:test'; +import { campaignDiff } from '../cli/apple/offer-codes'; +import { winBackDiff } from '../cli/apple/win-back'; +import { cppDeepLinkReq, type AppEventDef, eventAttrDiff, eventPatchReq, extraCppLocales } from '../cli/lib/cpp-events'; +import { missingVersionLocales } from '../cli/apple/screenshots'; +import { dataSafetyDryNote } from '../cli/play/data-safety'; + +describe('offer code campaign drift', () => { + const cur = { eligibility: ['NON_SPENDER'], prices: [{ territory: 'USA', pointId: 'p1' }, { territory: 'DEU', pointId: 'p2' }] }; + test('equal: no differences', () => { + expect(campaignDiff(cur, { eligibility: ['NON_SPENDER'], free: false, prices: cur.prices })).toEqual([]); + }); + test('eligibility, territories, price and mode differ', () => { + const d = campaignDiff(cur, { eligibility: ['NON_SPENDER', 'CHURNED_SPENDER'], free: false, prices: [{ territory: 'USA', pointId: 'p9' }, { territory: 'FRA', pointId: 'p3' }] }); + expect(d.join('|')).toContain('eligibility'); + expect(d.join('|')).toContain('+1 (FRA)'); + expect(d.join('|')).toContain('-1 (DEU)'); + expect(d.join('|')).toContain('prices differ in 1 territory'); + expect(campaignDiff(cur, { eligibility: ['NON_SPENDER'], free: true, prices: cur.prices }).join()).toContain('mode paid -> free'); + }); +}); + +describe('win-back drift', () => { + const want = { id: 'wb', type: 'pay-as-you-go', usd: 2.99, paidMonths: 3, lapsedMonths: { min: 1, max: 12 }, start: '2027-01-01', end: '2027-02-01' } as const; + test('equal', () => expect(winBackDiff({ offerMode: 'PAY_AS_YOU_GO', startDate: '2027-01-01', endDate: '2027-02-01' }, 2.99, want)).toEqual([])); + test('mode, price, dates', () => { + const d = winBackDiff({ offerMode: 'FREE_TRIAL', startDate: '2027-01-05', endDate: null }, 1.99, want); + expect(d.length).toBe(4); + expect(winBackDiff({ offerMode: 'PAY_AS_YOU_GO', startDate: '2027-01-01', endDate: '2027-02-01' }, undefined, want)).toEqual([]); + }); +}); + +describe('event attribute drift', () => { + const ev: AppEventDef = { referenceName: 'Spring', badge: 'CHALLENGE', priority: 'high', schedule: { publishStart: '2027-03-01T00:00:00Z', eventStart: '2027-03-05T00:00:00Z', eventEnd: '2027-03-10T00:00:00Z' }, listings: {} }; + const now = { badge: 'CHALLENGE', priority: 'HIGH', purpose: 'APPROPRIATE_FOR_ALL_USERS', territorySchedules: [{ territories: ['USA'], publishStart: '2027-03-01T00:00:00.000Z', eventStart: '2027-03-05T00:00:00.000Z', eventEnd: '2027-03-10T00:00:00.000Z' }] }; + test('same instants in another format: no drift', () => { + const d = eventAttrDiff(ev, now); + expect(d.lines).toEqual([]); + expect(eventPatchReq('e1', 'Spring', d.attrs, d.lines)).toBeNull(); + }); + test('badge, priority and end differ: one PATCH', () => { + const d = eventAttrDiff({ ...ev, badge: 'MAJOR_UPDATE', priority: 'normal', schedule: { ...ev.schedule, eventEnd: '2027-03-12T00:00:00Z' } }, now); + expect(d.lines.length).toBe(3); + const r = eventPatchReq('e1', 'Spring', d.attrs, d.lines)!; + expect(r.method).toBe('PATCH'); + expect(r.path).toBe('/v1/appEvents/e1'); + expect((r.body as { data: { attributes: Record } }).data.attributes.territorySchedules).toHaveLength(1); + }); +}); + +describe('custom product page drift', () => { + test('deep link removed is cleared', () => { + const r = cppDeepLinkReq('v1', 'Page', undefined, 'example://old')!; + expect(r.note).toContain('removed'); + expect((r.body as { data: { attributes: { deepLink: unknown } } }).data.attributes.deepLink).toBeNull(); + }); + test('equal or both empty: nothing', () => { + expect(cppDeepLinkReq('v1', 'Page', 'example://a', 'example://a')).toBeNull(); + expect(cppDeepLinkReq('v1', 'Page', undefined, null)).toBeNull(); + }); + test('extra locales on the page', () => expect(extraCppLocales(['en-US', 'fr-FR'], ['en-US'])).toEqual(['fr-FR'])); +}); + +describe('screenshots and data safety notes', () => { + test('version without a localization for a config language', () => { + expect(missingVersionLocales([{ apple: 'en-US' }, { apple: 'tr' }, {}], ['en-US'])).toEqual(['tr']); + }); + test('data safety dry note says Play cannot be read and --force re-sends', () => { + const n = dataSafetyDryNote({ at: '2027-01-01T10:00:00Z' }); + expect(n).toContain('no read API'); + expect(n).toContain('--force'); + expect(dataSafetyDryNote(null)).toContain('none recorded'); + }); +}); From abc195aee60c43eef402833e463437339065b358 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 20:49:43 +0800 Subject: [PATCH 114/344] Subscriptions drift on both stores (Apple prices in the dry run, localizations, group names, attributes, territories, intro offers reported; Play offer phases and prices, other-regions price, dropped regions gated, grace period, --prune-languages); pitfall 104, CHANGELOG; test fixtures for the new reads --- CHANGELOG.md | 14 +++ cli/apple/subscriptions.ts | 122 +++++++++++++++++-- cli/data/flags.json | 28 +++-- cli/lib/subscriptions.ts | 189 ++++++++++++++++++++++++++++-- cli/play/subscriptions.ts | 97 ++++++++++----- skills/store-pitfalls/SKILL.md | 14 +++ tests/pitfalls.test.ts | 5 +- tests/subscriptions-drift.test.ts | 148 +++++++++++++++++++++++ 8 files changed, 558 insertions(+), 59 deletions(-) create mode 100644 tests/subscriptions-drift.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index d222a34..61b6a28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ ## Unreleased +- **Existing store items are compared with the config, field by field** (pitfall 104). The dry run shows every + difference (old -> new); texts are sent, money and availability need a flag, fields Apple cannot edit are named. + - `apple iap`: price (`--allow-price-changes`), localization names and descriptions, reference name, review note, + family sharing (reported), territories. + - `apple subscriptions`: prices in the dry run, localizations, group names, reference name, review note, level, + territories; intro offers, period and family sharing reported. + - `play subscriptions`: offer phases and prices, other-regions price, regions no longer sold (all price-gated), + grace period, languages missing from the config kept unless `--prune-languages`. + - `apple appinfo`: app price (`--allow-price-changes`) and territories (removals `--allow-availability-changes`); + `apple review-details --dry` shows old -> new. + - Offer-code and win-back campaigns that differ are named; in-app event attributes patched on drafts; a removed + custom page deep link cleared; config languages without a version localization named. +- `prices diff` (the `catalog diff` report). + - Windows: no false "entitlements not referenced by CODE_SIGN_ENTITLEMENTS" warning (paths compared with forward slashes). Pitfall 103. - **`storebound apps relink`** after a machine move: every "folder not found" entry of the app folder list is pointed at diff --git a/cli/apple/subscriptions.ts b/cli/apple/subscriptions.ts index b9250da..d892670 100644 --- a/cli/apple/subscriptions.ts +++ b/cli/apple/subscriptions.ts @@ -20,10 +20,11 @@ import { type OfferCodeDef, sellsOn, type Subscription, type SubscriptionGroup } import type { Ctx } from '../lib/ctx'; import { confirm, need } from '../lib/ctx'; import { done, log, step, warn } from '../lib/log'; -import { allowPriceChanges, type HeldPrice, holdPriceChanges, withoutYes } from '../lib/price-gate'; +import { allowPriceChanges, type HeldPrice, heldSection, holdPriceChanges, withoutYes } from '../lib/price-gate'; import { parsePriceCsv, type PriceRow } from '../lib/prices'; import { - allSubscriptions, appleAvailabilityBody, appleCustomCodeBody, appleOfferCodeBody, applePromoOfferBody, appleGroupBody, appleGroupLocBody, appleIntroPatch, applePoints, applePriceChanges, + allSubscriptions, appleAvailabilityBody, appleAvailabilityDiff, appleGroupLocDiff, appleGroupLocPatchBody, appleIntroDiff, appleIntroOffers, appleLocDiff, appleLocPatchBody, + type AppleAttrDiff, appleSubAttrDiff, appleSubPatchBody, appleCustomCodeBody, appleOfferCodeBody, applePromoOfferBody, appleGroupBody, appleGroupLocBody, appleIntroPatch, applePoints, applePriceChanges, applePricesPatch, appleSubLocBody, appleSubPrices, appleSubscriptionBody, appleSubscriptionPlan, type AppleSubState, appleWantedPrices, type ApplePoint, pickPoint, } from '../lib/subscriptions'; @@ -69,6 +70,75 @@ async function readState(c: Asc, appId: string): Promise { const heldOf = (id: string, changes: { territory: string; from: number | null; to: number; startDate?: string | null }[]): HeldPrice => ({ id, changes: changes.map(ch => ({ region: ch.territory, from: ch.from === null ? '-' : String(ch.from), to: `${ch.to}${ch.startDate ? ` from ${ch.startDate}` : ''}` })) }); +/** Everything an existing subscription has that differs from the config (pure data; the run prints and applies it). */ +export interface SubDrift { + attrs: AppleAttrDiff; + locs: { id: string; loc: string; patch: Record }[]; + availability: { missing: string[]; newTerritories: boolean } | null; + intro: string[]; +} + +/** Reads the live subscription (attributes, localizations, availability, introductory offers) and diffs it with the config. Read-only. */ +export async function readSubDrift(c: Asc, s: Subscription, id: string, locale: Map, territories: string[]): Promise { + const live = (await c.maybe(`/v1/subscriptions/${id}`))?.data?.attributes ?? {}; + const attrs = appleSubAttrDiff(s, { name: live.name, subscriptionPeriod: live.subscriptionPeriod, familySharable: live.familySharable, reviewNote: live.reviewNote, groupLevel: live.groupLevel }); + const locs: SubDrift['locs'] = []; + const haveLocs = await c.all(`/v1/subscriptions/${id}/subscriptionLocalizations?limit=200`); + for (const [lang, l] of Object.entries(s.listings)) { + const loc = locale.get(lang); + const h = loc ? haveLocs.find((x: J) => x.attributes.locale === loc) : undefined; + const patch = h ? appleLocDiff(l, { name: h.attributes.name, description: h.attributes.description }) : null; + if (h && patch && loc) locs.push({ id: h.id, loc, patch }); + } + let availability: SubDrift['availability'] = null; + const av = (await c.maybe(`/v1/subscriptions/${id}/subscriptionAvailability`))?.data; + if (av?.id) { + let haveT: string[] | null = null; + try { haveT = (await c.all(`/v1/subscriptionAvailabilities/${av.id}/availableTerritories?limit=200`)).map((t: J) => t.id as string); } catch { /* unreadable: left alone */ } + if (haveT) availability = appleAvailabilityDiff({ territories: haveT, availableInNewTerritories: av.attributes?.availableInNewTerritories }, territories); + } + const hasIntro = !!(await c.asc('GET', `/v1/subscriptions/${id}/introductoryOffers?limit=1`)).data?.length; + const intro = hasIntro ? appleIntroDiff(s, appleIntroOffers(await pages(c, `/v1/subscriptions/${id}/introductoryOffers?include=subscriptionPricePoint,territory&limit=200`))) : []; + return { attrs, locs, availability, intro }; +} + +/** Group localizations whose name / customAppName differ from the config. Read-only. */ +export async function readGroupLocDrift(c: Asc, g: SubscriptionGroup, groupId: string, locale: Map): Promise<{ id: string; loc: string; patch: Record }[]> { + const have = await c.all(`/v1/subscriptionGroups/${groupId}/subscriptionGroupLocalizations?limit=200`); + const out: { id: string; loc: string; patch: Record }[] = []; + for (const [lang, l] of Object.entries(g.listings)) { + const loc = locale.get(lang); + const h = loc ? have.find((x: J) => x.attributes.locale === loc) : undefined; + const patch = h ? appleGroupLocDiff(l, { name: h.attributes.name, customAppName: h.attributes.customAppName }) : null; + if (h && patch && loc) out.push({ id: h.id, loc, patch }); + } + return out; +} + +/** The lines the dry run prints for one subscription's drift. Pure. */ +export function driftLines(id: string, d: SubDrift): string[] { + const av = d.availability; + return [ + ...d.attrs.text.map(x => `${id}: ${x}`), ...d.attrs.report, + ...d.locs.map(l => `${id} ${l.loc}: ${Object.keys(l.patch).join(' + ')} differ from the config`), + ...(av ? [`${id}: availability${av.missing.length ? ` ${av.missing.length} territories missing (${av.missing.slice(0, 5).join(', ')})` : ''}${av.newTerritories ? ' new territories off' : ''}`] : []), + ...d.intro, + ]; +} + +/** Today's prices vs the config for one existing subscription (read-only). */ +async function priceState(c: Asc, s: Subscription, id: string, cur: { hasPrices: boolean } | undefined, csv: PriceRow[]) { + const usaPoints = applePoints(await pages(c, `/v1/subscriptions/${id}/pricePoints?filter[territory]=USA&include=territory&limit=200`)); + const usa = pickPoint(usaPoints, 'USA', s.usd); + const equalized = applePoints(await pages(c, `/v1/subscriptionPricePoints/${usa.id}/equalizations?include=territory&limit=200`)); + const known: ApplePoint[] = [usa, ...equalized]; + // a subscription the first read missed (list lag) is read live, so nothing is sent twice + const hasPrices = cur ? cur.hasPrices : !!(await c.asc('GET', `/v1/subscriptions/${id}/prices?limit=1`)).data?.length; + const current = hasPrices ? appleSubPrices(await pages(c, `/v1/subscriptions/${id}/prices?include=subscriptionPricePoint,territory&limit=200`)) : []; + const changes = applePriceChanges(current, appleWantedPrices(s, equalized, csv), csv.filter(r => r.product === s.id)); + return { usaPoints, known, current, changes }; +} + export async function run(ctx: Ctx): Promise { const { config, root, resolve } = ctx.loaded; const only = ctx.args.list('only'); @@ -83,7 +153,29 @@ export async function run(ctx: Ctx): Promise { const state = await readState(c, appId); const plan = appleSubscriptionPlan(groups, config.languages, state); for (const [i, s] of plan.entries()) log(TAG, `${step(i + 1, plan.length, s.what)}`); - if (dry) { done(TAG, `subscriptions planned (dry run, nothing written; prices are compared per territory on a real run${csv.length ? `, ${csv.length} CSV rows` : ''})`); return; } + if (dry) { + // read-only comparison of everything that exists: text, attributes, availability, intro offers and prices (old -> new) + const locale = new Map(config.languages.map(l => [l.id, l.apple] as const)); + const territories: string[] = (await c.all('/v1/territories?limit=200')).map((t: J) => t.id); + const heldDry: HeldPrice[] = []; + for (const g of groups) { + const sg = state.groups.find(x => x.referenceName === g.name); + if (sg) for (const d of await readGroupLocDrift(c, g, sg.id, locale)) log(TAG, `group "${g.name}" ${d.loc}: ${Object.keys(d.patch).join(' + ')} differ from the config`); + for (const s of g.subscriptions) { + const cur = state.subscriptions.find(x => x.productId === s.id); + if (!cur) continue; + for (const l of driftLines(s.id, await readSubDrift(c, s, cur.id, locale, territories))) log(TAG, l); + try { + const { changes } = await priceState(c, s, cur.id, cur, csv); + if (changes.length) { log(TAG, `${s.id}: ${changes.length} price change(s)`); heldDry.push(heldOf(s.id, changes)); } + } catch (e) { warn(TAG, `${s.id}: prices not compared (${String((e as Error).message ?? e).slice(0, 160)})`); } + } + } + const h = heldSection(heldDry, ctx.args.has('allow-price-changes')); + if (h) console.log(h); + done(TAG, `subscriptions planned (dry run, nothing written${csv.length ? `, ${csv.length} CSV rows` : ''})`); + return; + } const yes = ctx.args.has('yes'); // price changes of existing subscriptions: only with --allow-price-changes, their own question per subscription @@ -115,6 +207,12 @@ export async function run(ctx: Ctx): Promise { create: async () => (await c.asc('POST', '/v1/subscriptionGroupLocalizations', appleGroupLocBody(groupId, loc, l))).data }); log(TAG, ` group ${loc}`); } + if (state.groups.some(x => x.id === groupId)) { + for (const d of await readGroupLocDrift(c, g, groupId, locale)) { + await c.asc('PATCH', `/v1/subscriptionGroupLocalizations/${d.id}`, appleGroupLocPatchBody(d.id, d.patch)); + log(TAG, ` group ${d.loc}: ${Object.keys(d.patch).join(' + ')} updated`); + } + } for (const [i, s] of g.subscriptions.entries()) { const tag = step(i + 1, g.subscriptions.length, s.id); const cur = state.subscriptions.find(x => x.productId === s.id); @@ -139,16 +237,18 @@ export async function run(ctx: Ctx): Promise { log(TAG, ` ${loc}`); } if (!cur?.availability && !(await c.maybe(`/v1/subscriptions/${id}/subscriptionAvailability`))?.data) { await c.asc('POST', '/v1/subscriptionAvailabilities', appleAvailabilityBody(id, territories)); log(TAG, ` available in ${territories.length} territories + new ones`); } + if (cur) { + // what exists but differs from the config: text and attributes are patched, availability is set again, intro offers + // and the period / family sharing are only reported (Apple cannot change them) + const d = await readSubDrift(c, s, subId, locale, territories); + if (Object.keys(d.attrs.patch).length) { await c.asc('PATCH', `/v1/subscriptions/${subId}`, appleSubPatchBody(subId, d.attrs.patch)); log(TAG, ` attributes updated: ${d.attrs.text.join(', ')}`); } + for (const l of d.locs) { await c.asc('PATCH', `/v1/subscriptionLocalizations/${l.id}`, appleLocPatchBody(l.id, l.patch)); log(TAG, ` ${l.loc}: ${Object.keys(l.patch).join(' + ')} updated`); } + if (d.availability) { await c.asc('POST', '/v1/subscriptionAvailabilities', appleAvailabilityBody(subId, territories)); log(TAG, ` availability set again: ${territories.length} territories + new ones`); } + for (const x of [...d.attrs.report, ...d.intro]) warn(TAG, x); + } // prices: USA point -> equalizations -> overrides / CSV; only what differs from today's prices - const usaPoints = applePoints(await pages(c, `/v1/subscriptions/${id}/pricePoints?filter[territory]=USA&include=territory&limit=200`)); - const usa = pickPoint(usaPoints, 'USA', s.usd); - const equalized = applePoints(await pages(c, `/v1/subscriptionPricePoints/${usa.id}/equalizations?include=territory&limit=200`)); - const known: ApplePoint[] = [usa, ...equalized]; - // a subscription the first read missed (list lag) is read live, so nothing is sent twice - const hasPrices = cur ? cur.hasPrices : !!(await c.asc('GET', `/v1/subscriptions/${id}/prices?limit=1`)).data?.length; - const current = hasPrices ? appleSubPrices(await pages(c, `/v1/subscriptions/${id}/prices?include=subscriptionPricePoint,territory&limit=200`)) : []; - const changes = applePriceChanges(current, appleWantedPrices(s, equalized, csv), csv.filter(r => r.product === s.id)); + const { usaPoints, known, current, changes } = await priceState(c, s, id, cur, csv); if (!changes.length) log(TAG, ' prices up to date'); else if (current.length && !(await allowPriceChanges(ctx, [heldOf(s.id, changes)], `Change the prices of the existing subscription ${s.id} on App Store Connect (${changes.length} territories)? New subscribers pay the new price.`))) { log(TAG, ' owner: price change of an existing subscription (--allow-price-changes)'); diff --git a/cli/data/flags.json b/cli/data/flags.json index fe63096..f581df0 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -61,7 +61,10 @@ "plist", "udid" ], - "apple appinfo": [], + "apple appinfo": [ + "allow-availability-changes", + "allow-price-changes" + ], "apple build": [ "allow-ssh", "allow-stale-web", @@ -403,6 +406,8 @@ "write" ], "check": [ + "allow-availability-changes", + "allow-price-changes", "aso", "capacitor", "cordova", @@ -420,6 +425,8 @@ "unity" ], "console fill": [ + "allow-availability-changes", + "allow-price-changes", "capacitor", "cdp", "chrome-profile", @@ -441,6 +448,8 @@ ], "console plan": [ "all", + "allow-availability-changes", + "allow-price-changes", "capacitor", "cdp", "chrome-profile", @@ -464,6 +473,8 @@ "use-chrome-session" ], "console verify": [ + "allow-availability-changes", + "allow-price-changes", "capacitor", "cordova", "cordova-android", @@ -605,6 +616,8 @@ "threshold" ], "play app-id": [ + "allow-availability-changes", + "allow-price-changes", "capacitor", "cdp", "chrome-profile", @@ -710,6 +723,7 @@ "offline", "only-decreases", "out", + "prune-languages", "reconvert", "source", "store", @@ -780,6 +794,8 @@ "workspace" ], "report": [ + "allow-availability-changes", + "allow-price-changes", "capacitor", "cordova", "cordova-android", @@ -985,6 +1001,7 @@ "agent", "all", "all-pages", + "allow-availability-changes", "allow-existing", "allow-price-changes", "allow-ssh", @@ -1146,6 +1163,7 @@ "project", "propose", "prune", + "prune-languages", "q", "rating", "react-native", @@ -1263,7 +1281,7 @@ "storebound apple adhoc export --archive [--plist build/ExportOptions.plist] [--out build/adhoc] [--dry]" ], "apple appinfo": [ - "storebound apple appinfo [--dry] [--json]" + "storebound apple appinfo [--dry] [--json] [--allow-price-changes] [--allow-availability-changes]" ], "apple build": [ "storebound apple build [--version 1.2.0] [--build-number N] [--scheme S] [--workspace W | --project P]" @@ -1311,9 +1329,6 @@ "apple next-build": [ "storebound apple next-build -> 42" ], - "apple offer-codes": [ - "storebound apple offer-codes [--only id1,id2] [--codes] [--dry] [--yes] [--json]" - ], "apple ppo": [ "storebound apple ppo status [--json]", "storebound apple ppo create --variant b[,c] [--name \"...\"] [--traffic 30] [--dry]", @@ -1338,9 +1353,6 @@ "apple resubmit": [ "storebound apple resubmit --build [--version 1.0.0] [--platform ios|macos|tvos|visionos] [--resolve-iaps] [--dry] [--yes] [--json]" ], - "apple review-details": [ - "storebound apple review-details [--contact-from ] [--dry]" - ], "apple screenshots": [ "storebound apple screenshots [--src store/renders] [--only en-US,tr] [--jobs 4] [--variant b] [--dry]", "storebound apple screenshots --repair-stuck [--dry] (only the screenshots stuck outside COMPLETE, in place)" diff --git a/cli/lib/subscriptions.ts b/cli/lib/subscriptions.ts index 70ac790..08ffdec 100644 --- a/cli/lib/subscriptions.ts +++ b/cli/lib/subscriptions.ts @@ -297,6 +297,92 @@ export function applePriceChanges(current: { territory: string; price: number; s return out; } +// ---- Apple: what exists vs the config (drift) ---- + +export interface AppleSubAttrs { name?: string; subscriptionPeriod?: string; familySharable?: boolean; reviewNote?: string | null; groupLevel?: number } +/** `patch` = attributes PATCH /v1/subscriptions/{id} can change, `text` = lines for those, `report` = differences Apple cannot change. */ +export interface AppleAttrDiff { patch: Record; text: string[]; report: string[] } + +/** Subscription attributes on App Store Connect vs the config. Name (reference name), review note and group level are + * patched; the period and family sharing cannot change after creation and are only reported. An attribute the read + * did not return is left alone. Pure. */ +export function appleSubAttrDiff(s: Subscription, cur: AppleSubAttrs): AppleAttrDiff { + const out: AppleAttrDiff = { patch: {}, text: [], report: [] }; + const want = APPLE_PERIOD[s.period]; + if (cur.subscriptionPeriod !== undefined && cur.subscriptionPeriod !== want) out.report.push(`${s.id}: period is ${cur.subscriptionPeriod} on App Store Connect, the config says ${want} (a period cannot change; use a new product id)`); + const fam = s.familySharable ?? false; + if (cur.familySharable !== undefined && cur.familySharable !== fam) out.report.push(`${s.id}: familySharable is ${cur.familySharable} on App Store Connect, the config says ${fam} (cannot be changed through the API)`); + const name = s.referenceName ?? Object.values(s.listings)[0]?.title; + if (name !== undefined && cur.name !== undefined && cur.name !== name) { out.patch.name = name; out.text.push(`reference name "${cur.name}" -> "${name}"`); } + if (s.reviewNote !== undefined && cur.reviewNote !== undefined && (cur.reviewNote ?? '') !== s.reviewNote) { out.patch.reviewNote = s.reviewNote; out.text.push('review note changed'); } + if (cur.groupLevel !== undefined && cur.groupLevel !== s.level) { out.patch.groupLevel = s.level; out.text.push(`level ${cur.groupLevel} -> ${s.level}`); } + return out; +} + +export const appleSubPatchBody = (subId: string, attributes: Record) => ({ data: { type: 'subscriptions', id: subId, attributes } }); + +/** Subscription localization text vs the config: the attributes to PATCH, or null when equal (or not returned). Pure. */ +export function appleLocDiff(want: { title: string; description: string }, cur: { name?: string; description?: string }): Record | null { + const patch: Record = {}; + if (cur.name !== undefined && cur.name !== want.title) patch.name = want.title; + if (cur.description !== undefined && cur.description !== want.description) patch.description = want.description; + return Object.keys(patch).length ? patch : null; +} +export const appleLocPatchBody = (locId: string, attributes: Record) => ({ data: { type: 'subscriptionLocalizations', id: locId, attributes } }); + +/** Subscription group localization (name, customAppName when configured) vs the config. Pure. */ +export function appleGroupLocDiff(want: { name: string; customAppName?: string }, cur: { name?: string; customAppName?: string | null }): Record | null { + const patch: Record = {}; + if (cur.name !== undefined && cur.name !== want.name) patch.name = want.name; + if (want.customAppName !== undefined && (cur.customAppName ?? '') !== want.customAppName) patch.customAppName = want.customAppName; + return Object.keys(patch).length ? patch : null; +} +export const appleGroupLocPatchBody = (locId: string, attributes: Record) => ({ data: { type: 'subscriptionGroupLocalizations', id: locId, attributes } }); + +/** Subscription availability vs "every territory + new ones": territories missing, availableInNewTerritories off. null = same. Pure. */ +export function appleAvailabilityDiff(cur: { territories: string[]; availableInNewTerritories?: boolean }, wanted: string[]): { missing: string[]; newTerritories: boolean } | null { + const have = new Set(cur.territories); + const missing = wanted.filter(t => !have.has(t)); + const newTerritories = cur.availableInNewTerritories === false; + return missing.length || newTerritories ? { missing, newTerritories } : null; +} + +export interface AppleIntroOffer { territory: string; mode?: string; duration?: string; periods?: number; price?: number } + +/** GET /v1/subscriptions/{id}/introductoryOffers?include=subscriptionPricePoint,territory -> offers per territory. */ +export function appleIntroOffers(resp: JsonApi): AppleIntroOffer[] { + const points = new Map((resp.included ?? []).filter(x => x.type === 'subscriptionPricePoints').map(x => [x.id, Number(x.attributes?.customerPrice)] as const)); + return (resp.data ?? []).map(o => { + const pid = o.relationships?.subscriptionPricePoint?.data?.id; + const price = pid ? points.get(pid) : undefined; + return { + territory: o.relationships?.territory?.data?.id ?? '', mode: o.attributes?.offerMode as string | undefined, duration: o.attributes?.duration as string | undefined, + periods: o.attributes?.numberOfPeriods as number | undefined, ...(price !== undefined && !Number.isNaN(price) ? { price } : {}), + }; + }); +} + +/** Introductory offers on App Store Connect vs the config (Apple cannot PATCH them: report only), as `intro differs: ...` + * lines. A subscription without any offer yet is created by the run, not a difference. Pure. */ +export function appleIntroDiff(s: Subscription, cur: AppleIntroOffer[]): string[] { + if (!cur.length) return []; + if (!s.intro) return [`intro differs: ${s.id} has an introductory offer on App Store Connect, the config has none`]; + const o = s.intro; + const out: string[] = []; + const distinct = (f: (x: AppleIntroOffer) => T | undefined): T[] => [...new Set(cur.map(f).filter((x): x is T => x !== undefined))]; + const check = (what: string, have: (string | number)[], want: string | number) => { + if (have.some(h => h !== want)) out.push(`intro differs: ${s.id} ${what} ${have.join('/')} on App Store Connect, ${want} in the config`); + }; + check('mode', distinct(x => x.mode), APPLE_OFFER_MODE[o.type]); + check('duration', distinct(x => x.duration), APPLE_OFFER_DURATION[introDuration(s)] ?? introDuration(s)); + check('periods', distinct(x => x.periods), o.type === 'pay-as-you-go' ? o.periods ?? 1 : 1); + if (o.type !== 'free' && o.usd !== undefined) { + const usa = cur.find(x => x.territory === 'USA')?.price; + if (usa !== undefined && cents(usa) !== cents(o.usd)) out.push(`intro differs: ${s.id} price USA ${usa} on App Store Connect, ${o.usd} in the config`); + } + return out; +} + // ---- Apple: plan ---- export interface AppleSubState { @@ -430,10 +516,20 @@ export function playOfferBody(pkg: string, s: Subscription, regions: PlayRegionP const moneyKey = (m?: Money): string => (m ? `${m.currencyCode} ${cents(fromMoney(m))}` : '-'); -export interface PlaySubDiff { create: boolean; listings: string[]; basePlan: 'new' | 'same' | 'changed'; priceChanges: { regionCode: string; from: string; to: string }[]; activate: boolean } +export interface PlaySubDiff { + create: boolean; listings: string[]; basePlan: 'new' | 'same' | 'changed'; priceChanges: { regionCode: string; from: string; to: string }[]; activate: boolean; + /** Languages on Play that the config does not list (a PATCH drops them only with --prune-languages). Set only when there are some. */ + listingsRemoved?: string[]; + /** Grace period on Play vs the config. Set only when it differs. */ + grace?: { from: string; to: string }; + /** Regions sold on Play that the config no longer lists (also one "not sold" row in priceChanges, owner-gated). */ + droppedRegions?: string[]; +} /** Current Play subscription (or null) vs the wanted body: what a patch would change. Price changes on an existing - * base plan apply to new subscribers; existing ones keep their price until you run a price migration in the Console. */ + * base plan apply to new subscribers; existing ones keep their price until you run a price migration in the Console. + * Money (regional prices, the other-regions USD / EUR price, regions no longer sold) all land in `priceChanges`, so + * the price gate holds them; text (listings, grace period) is its own field. */ export function playSubDiff(cur: PlaySubscription | null, want: PlaySubscription): PlaySubDiff { const wb = want.basePlans![0]!; if (!cur) return { create: true, listings: (want.listings ?? []).map(l => l.languageCode), basePlan: 'new', priceChanges: [], activate: true }; @@ -442,25 +538,100 @@ export function playSubDiff(cur: PlaySubscription | null, want: PlaySubscription const c = curL.get(l.languageCode); return !c || c.title !== l.title || (c.description ?? '') !== (l.description ?? '') || JSON.stringify(c.benefits ?? []) !== JSON.stringify(l.benefits ?? []); }).map(l => l.languageCode); + const wantCodes = new Set((want.listings ?? []).map(l => l.languageCode)); + const removed = [...curL.keys()].filter(c => !wantCodes.has(c)); + const extras = removed.length ? { listingsRemoved: removed } : {}; const cb = cur.basePlans?.find(b => b.basePlanId === wb.basePlanId); - if (!cb) return { create: false, listings, basePlan: 'new', priceChanges: [], activate: true }; + if (!cb) return { create: false, listings, basePlan: 'new', priceChanges: [], activate: true, ...extras }; const cr = new Map((cb.regionalConfigs ?? []).map(r => [r.regionCode, r.price] as const)); const priceChanges = (wb.regionalConfigs ?? []).filter(r => moneyKey(cr.get(r.regionCode)) !== moneyKey(r.price)) .map(r => ({ regionCode: r.regionCode, from: moneyKey(cr.get(r.regionCode)), to: moneyKey(r.price) })); - const typeSame = cb.autoRenewingBasePlanType?.billingPeriodDuration === wb.autoRenewingBasePlanType?.billingPeriodDuration - && (cb.autoRenewingBasePlanType?.gracePeriodDuration ?? '') === (wb.autoRenewingBasePlanType?.gracePeriodDuration ?? cb.autoRenewingBasePlanType?.gracePeriodDuration ?? ''); + const wantRegions = new Set((wb.regionalConfigs ?? []).map(r => r.regionCode)); + const gone = [...cr.keys()].filter(c => !wantRegions.has(c)); + for (const c of gone) priceChanges.push({ regionCode: c, from: moneyKey(cr.get(c)), to: 'not sold' }); + const co = cb.otherRegionsConfig, wo = wb.otherRegionsConfig; + if (wo && (moneyKey(co?.usdPrice) !== moneyKey(wo.usdPrice) || moneyKey(co?.eurPrice) !== moneyKey(wo.eurPrice))) + priceChanges.push({ regionCode: 'other regions', from: `${moneyKey(co?.usdPrice)} / ${moneyKey(co?.eurPrice)}`, to: `${moneyKey(wo.usdPrice)} / ${moneyKey(wo.eurPrice)}` }); + const curGrace = cb.autoRenewingBasePlanType?.gracePeriodDuration ?? ''; + const wantGrace = wb.autoRenewingBasePlanType?.gracePeriodDuration ?? ''; + // a config without a grace period leaves the one on Play alone + const graceChanged = wantGrace !== '' && wantGrace !== curGrace; if (cb.autoRenewingBasePlanType && cb.autoRenewingBasePlanType.billingPeriodDuration !== wb.autoRenewingBasePlanType?.billingPeriodDuration) throw new Error(`${want.productId}: base plan ${wb.basePlanId} bills every ${cb.autoRenewingBasePlanType.billingPeriodDuration} on Play, the config says ${wb.autoRenewingBasePlanType?.billingPeriodDuration} (a billing period cannot change; use a new basePlanId)`); - return { create: false, listings, basePlan: priceChanges.length || !typeSame ? 'changed' : 'same', priceChanges, activate: cb.state !== 'ACTIVE' }; + return { + create: false, listings, basePlan: priceChanges.length || graceChanged ? 'changed' : 'same', priceChanges, activate: cb.state !== 'ACTIVE', ...extras, + ...(graceChanged ? { grace: { from: curGrace || '-', to: wantGrace } } : {}), ...(gone.length ? { droppedRegions: gone } : {}), + }; } -/** The patch body keeps base plans the config does not manage (Play would otherwise drop them) and output-only fields out. */ -export function playPatchSubscription(cur: PlaySubscription, want: PlaySubscription): PlaySubscription { +/** The patch body keeps base plans the config does not manage (Play would otherwise drop them) and output-only fields out. + * Languages on Play that the config does not list stay in the body unless `pruneLanguages`. */ +export function playPatchSubscription(cur: PlaySubscription, want: PlaySubscription, o: { pruneLanguages?: boolean } = {}): PlaySubscription { const wb = want.basePlans![0]!; const keep = (cur.basePlans ?? []).filter(b => b.basePlanId !== wb.basePlanId).map(({ state: _s, ...b }) => b); const curMine = cur.basePlans?.find(b => b.basePlanId === wb.basePlanId); const { state: _st, ...mine } = { ...(curMine ?? {}), ...wb, autoRenewingBasePlanType: { ...(curMine?.autoRenewingBasePlanType ?? {}), ...wb.autoRenewingBasePlanType! } }; - return { ...want, basePlans: [...keep, mine as NonNullable[number]] }; + const wantCodes = new Set((want.listings ?? []).map(l => l.languageCode)); + const kept = o.pruneLanguages ? [] : (cur.listings ?? []).filter(l => !wantCodes.has(l.languageCode)); + return { ...want, ...(kept.length ? { listings: [...(want.listings ?? []), ...kept] } : {}), basePlans: [...keep, mine as NonNullable[number]] }; +} + +/** The text side of a Play subscription diff (no money; empty = nothing). Pure. */ +export function playSubTextChanges(d: PlaySubDiff, prune = false): string[] { + return [ + d.listings.length ? `listings ${d.listings.join(', ')}` : '', + d.listingsRemoved?.length ? (prune ? `listings removed: ${d.listingsRemoved.join(', ')}` : `listings removed from the config: ${d.listingsRemoved.join(', ')} (kept on Play; --prune-languages removes them)`) : '', + d.grace ? `grace ${d.grace.from} -> ${d.grace.to}` : '', + ].filter(Boolean); +} + +// ---- Play: offers already on the base plan ---- + +export interface PlayOfferLike { + offerId?: string; state?: string; + phases?: { recurrenceCount?: number; duration?: string; regionalConfigs?: { regionCode: string; free?: unknown; relativeDiscount?: number; absoluteDiscount?: Money; price?: Money }[]; + otherRegionsConfig?: { free?: unknown; relativeDiscount?: number; absoluteDiscount?: unknown; otherRegionsPrices?: { usdPrice?: Money; eurPrice?: Money } } }[]; + [k: string]: unknown; +} + +type Entry = Record | undefined; +/** "free", "-50%", "-USD 100" or "USD 299": the kind (free / discount / price) and the shown value of one phase entry. */ +function phaseEntry(c: Entry): { kind: string; text: string } { + if (!c) return { kind: '-', text: '-' }; + if (c.free !== undefined) return { kind: 'free', text: 'free' }; + if (typeof c.relativeDiscount === 'number') return { kind: 'discount', text: `-${Math.round(c.relativeDiscount * 100)}%` }; + if (c.absoluteDiscount) return { kind: 'absolute', text: `-${moneyKey(c.absoluteDiscount as Money)}` }; + if (c.price) return { kind: 'price', text: moneyKey(c.price as Money) }; + const o = c.otherRegionsPrices as { usdPrice?: Money; eurPrice?: Money } | undefined; + if (o) return { kind: 'price', text: `${moneyKey(o.usdPrice)} / ${moneyKey(o.eurPrice)}` }; + return { kind: '-', text: '-' }; +} + +export interface PlayOfferDrift { phase: string[]; prices: { region: string; from: string; to: string }[] } + +/** Offer on Play vs the offer the config would create: `phase` = free / paid kind, duration, periods (text), `prices` = + * per region the discount, price or other-regions price (money: only behind the price gate). Pure. */ +export function playOfferDiff(cur: PlayOfferLike, want: PlayOfferLike): PlayOfferDrift { + const out: PlayOfferDrift = { phase: [], prices: [] }; + const cp = cur.phases ?? [], wp = want.phases ?? []; + if (cp.length !== wp.length) out.phase.push(`${cp.length} phase(s) -> ${wp.length}`); + for (const [i, w] of wp.entries()) { + const c = cp[i]; + if (!c) continue; + const at = wp.length > 1 ? `phase ${i + 1} ` : ''; + if ((c.duration ?? '') !== (w.duration ?? '')) out.phase.push(`${at}duration ${c.duration ?? '-'} -> ${w.duration ?? '-'}`); + if ((c.recurrenceCount ?? 1) !== (w.recurrenceCount ?? 1)) out.phase.push(`${at}periods ${c.recurrenceCount ?? 1} -> ${w.recurrenceCount ?? 1}`); + const cm = new Map((c.regionalConfigs ?? []).map(r => [r.regionCode, r as Entry] as const)); + const rows: [string, Entry, Entry][] = (w.regionalConfigs ?? []).map(r => [r.regionCode, cm.get(r.regionCode), r as Entry]); + rows.push(['other regions', c.otherRegionsConfig as Entry, w.otherRegionsConfig as Entry]); + for (const [region, cc, wc] of rows) { + const a = phaseEntry(cc), b = phaseEntry(wc); + if (a.text === b.text) continue; + if (a.kind !== b.kind && a.kind !== '-') out.phase.push(`${at}${region} ${a.text} -> ${b.text}`); + else out.prices.push({ region, from: a.text, to: b.text }); + } + } + return out; } // ---- Apple: reading responses ---- diff --git a/cli/play/subscriptions.ts b/cli/play/subscriptions.ts index 65f7d85..ab037b0 100644 --- a/cli/play/subscriptions.ts +++ b/cli/play/subscriptions.ts @@ -20,8 +20,8 @@ import { done, log, step, warn } from '../lib/log'; import { allowPriceChanges, type HeldPrice, heldSection, holdPriceChanges } from '../lib/price-gate'; import { type Money, toMoney } from '../lib/money'; import { - allSubscriptions, basePlanId, offerId, playOfferBody, playPatchSubscription, type PlaySubscription, playSubDiff, playSubRegions, - playSubscriptionBody, + allSubscriptions, basePlanId, offerId, type PlayOfferLike, playOfferBody, playOfferDiff, playPatchSubscription, type PlaySubscription, playSubDiff, playSubRegions, + playSubscriptionBody, playSubTextChanges, } from '../lib/subscriptions'; import { subscriptionCsv } from '../apple/subscriptions'; import { createOnce } from '../lib/upsert'; @@ -58,7 +58,19 @@ export async function run(ctx: Ctx): Promise { return { convertedRegionPrices: conv.convertedRegionPrices, convertedOtherRegionsPrice: conv.convertedOtherRegionsPrice, regionVersion: conv.regionVersion ?? { version: '2022/02' } }; }; - const work: { s: typeof subs[number]; body: PlaySubscription; diff: ReturnType; version: string; offerMissing: boolean; extraMissing: string[] }[] = []; + const prune = ctx.args.has('prune-languages'); + // the offer the config would create (pay-up-front prices come from convertRegionPrices of the offer price) + const buildOffer = async (s: typeof subs[number], regions: { regionCode: string; price: Money }[], o: { type: string; usd?: number }, extra?: NonNullable[number]) => { + let offerRegions; + if (o.type === 'pay-up-front') { + const oc = await convert(o.usd!); + offerRegions = { regions: Object.values(oc.convertedRegionPrices).map(r => ({ regionCode: r.regionCode, price: r.price })), other: oc.convertedOtherRegionsPrice }; + } + return playOfferBody(pkg, s, regions, offerRegions, extra); + }; + + interface OfferDrift { offerId: string; phase: string[]; prices: HeldPrice['changes']; body: ReturnType } + const work: { s: typeof subs[number]; body: PlaySubscription; diff: ReturnType; version: string; offerMissing: boolean; extraMissing: string[]; offerDrift: OfferDrift[] }[] = []; for (const [i, s] of subs.entries()) { const conv = await convert(s.usd); const regions = playSubRegions(s, conv.convertedRegionPrices, csv); @@ -67,42 +79,63 @@ export async function run(ctx: Ctx): Promise { const diff = playSubDiff(cur, body); let offerMissing = !!s.intro; let extraMissing = (s.offers ?? []).map(o => o.id); + const offerDrift: OfferDrift[] = []; if ((s.intro || s.offers?.length) && cur?.basePlans?.some(b => b.basePlanId === basePlanId(s))) { - const offers = await play.call<{ subscriptionOffers?: { offerId: string }[] }>('GET', `${play.API}/subscriptions/${encodeURIComponent(s.id)}/basePlans/${basePlanId(s)}/offers`); - const have = new Set((offers.subscriptionOffers ?? []).map(o => o.offerId)); - offerMissing = !!s.intro && !have.has(offerId(s)); - extraMissing = extraMissing.filter(x => !have.has(x)); + const offers = await play.call<{ subscriptionOffers?: PlayOfferLike[] }>('GET', `${play.API}/subscriptions/${encodeURIComponent(s.id)}/basePlans/${basePlanId(s)}/offers`); + const haveOffers = new Map((offers.subscriptionOffers ?? []).map(o => [o.offerId ?? '', o] as const)); + offerMissing = !!s.intro && !haveOffers.has(offerId(s)); + extraMissing = extraMissing.filter(x => !haveOffers.has(x)); + // offers that exist: phases (free / paid, duration, periods) and prices per region vs what the config would create + const regionPrices = body.basePlans![0]!.regionalConfigs!.map(r => ({ regionCode: r.regionCode, price: r.price! })); + const check: [string, { type: string; usd?: number }, NonNullable[number] | undefined][] = []; + if (s.intro && haveOffers.has(offerId(s))) check.push([offerId(s), s.intro, undefined]); + for (const o of s.offers ?? []) if (haveOffers.has(o.id)) check.push([o.id, o, o]); + for (const [oid, o, extra] of check) { + const want = await buildOffer(s, regionPrices, o, extra); + const d = playOfferDiff(haveOffers.get(oid)!, want as unknown as PlayOfferLike); + if (d.phase.length || d.prices.length) offerDrift.push({ offerId: oid, phase: d.phase, prices: d.prices, body: want }); + } } + const text = playSubTextChanges(diff, prune); const what = diff.create ? `create, base plan ${basePlanId(s)} (${s.period}) in ${regions.length} regions` - : [diff.listings.length ? `listings ${diff.listings.join(', ')}` : '', diff.basePlan === 'new' ? `new base plan ${basePlanId(s)}` : diff.basePlan === 'changed' ? `base plan ${basePlanId(s)}: ${diff.priceChanges.length} regional price change(s)` : '', - diff.activate ? 'activate base plan' : ''].filter(Boolean).join(' · ') || 'up to date'; + : [...text.filter(x => !x.startsWith('grace')), diff.basePlan === 'new' ? `new base plan ${basePlanId(s)}` : diff.basePlan === 'changed' && diff.priceChanges.length ? `base plan ${basePlanId(s)}: ${diff.priceChanges.length} regional price change(s)` : '', + ...text.filter(x => x.startsWith('grace')), diff.activate ? 'activate base plan' : ''].filter(Boolean).join(' · ') || 'up to date'; log(TAG, `${step(i + 1, subs.length, s.id)}: ${what}${offerMissing ? ` · intro offer ${offerId(s)} (${s.intro!.type})` : ''}${extraMissing.length ? ` · offers ${extraMissing.join(', ')}` : ''}`); if (diff.priceChanges.length) log(TAG, ' owner: price change of an existing base plan (--allow-price-changes)'); for (const p of diff.priceChanges.slice(0, 5)) log(TAG, ` ${p.regionCode}: ${p.from} -> ${p.to}`); if (diff.priceChanges.length > 5) log(TAG, ` ... ${diff.priceChanges.length - 5} more`); - work.push({ s, body, diff, version: conv.regionVersion.version, offerMissing, extraMissing }); + for (const d of offerDrift) { + log(TAG, ` offer ${d.offerId} differs${d.phase.length ? `: ${d.phase.join('; ')}` : ''}${d.prices.length ? ` · ${d.prices.length} price(s), owner (--allow-price-changes)` : ''}`); + for (const p of d.prices.slice(0, 5)) log(TAG, ` ${p.region}: ${p.from} -> ${p.to}`); + } + work.push({ s, body, diff, version: conv.regionVersion.version, offerMissing, extraMissing, offerDrift }); } + // money held behind --allow-price-changes: base plan prices (incl. other regions and regions dropped) and offer prices + const moneyOf = (w: typeof work[number]): HeldPrice[] => [ + ...(w.diff.basePlan === 'changed' && w.diff.priceChanges.length ? [{ id: w.s.id, changes: w.diff.priceChanges.map(p => ({ region: p.regionCode, from: p.from, to: p.to })) }] : []), + ...w.offerDrift.filter(d => d.prices.length).map(d => ({ id: `${w.s.id} offer ${d.offerId}`, changes: d.prices })), + ]; if (dry) { - const h = heldSection(work.filter(w => w.diff.basePlan === 'changed' && w.diff.priceChanges.length).map(w => ({ id: w.s.id, changes: w.diff.priceChanges.map(p => ({ region: p.regionCode, from: p.from, to: p.to })) })), ctx.args.has('allow-price-changes')); + const h = heldSection(work.flatMap(moneyOf), ctx.args.has('allow-price-changes')); if (h) console.log(h); done(TAG, 'subscriptions planned (dry run, nothing written)'); return; } - const todo = work.filter(w => w.diff.create || w.diff.listings.length || w.diff.basePlan !== 'same' || w.diff.activate || w.offerMissing || w.extraMissing.length); + const todo = work.filter(w => w.diff.create || w.diff.listings.length || w.diff.basePlan !== 'same' || w.diff.activate || w.offerMissing || w.extraMissing.length || w.offerDrift.length || (prune && w.diff.listingsRemoved?.length)); if (!todo.length) { done(TAG, 'subscriptions up to date'); return; } const yes = ctx.args.has('yes'); - const priced = todo.filter(w => w.diff.basePlan === 'changed' && w.diff.priceChanges.length); + const priced = todo.filter(w => moneyOf(w).length); // the terminal question covers creates and other updates; price changes of existing base plans need // --allow-price-changes and their own question listing each old -> new (lib/price-gate.ts) if (stdinIsTTY() && !yes && process.env.STOREBOUND_SERVE !== '1') { if (!(await confirm(ctx, `Write ${todo.length} subscription(s) to Google Play? Activated base plans and offers can be bought as soon as the app is published. Price changes of existing base plans are not part of this answer (--allow-price-changes).`))) return; } - const liveOk = await allowPriceChanges(ctx, priced.map(w => ({ id: w.s.id, changes: w.diff.priceChanges.map(p => ({ region: p.regionCode, from: p.from, to: p.to })) })), - `Change the base plan prices of ${priced.length} existing subscription(s) on Google Play? New subscribers pay the new price.`); - if (!liveOk && priced.length) log(TAG, 'writing what is new; price changes of existing base plans wait for the owner (--allow-price-changes)'); + const liveOk = await allowPriceChanges(ctx, priced.flatMap(moneyOf), + `Change the prices (base plan, other regions, regions sold, offers) of ${priced.length} existing subscription(s) on Google Play? New subscribers pay the new price.`); + if (!liveOk && priced.length) log(TAG, 'writing what is new; price changes of existing base plans and offers wait for the owner (--allow-price-changes)'); const held: HeldPrice[] = []; - for (const { s, body, diff, version, offerMissing, extraMissing } of todo) { + for (const { s, body, diff, version, offerMissing, extraMissing, offerDrift } of todo) { const v = encodeURIComponent(version); const id = encodeURIComponent(s.id); const cur = existing.get(s.id); @@ -113,16 +146,19 @@ export async function run(ctx: Ctx): Promise { create: () => play.call('POST', `${play.API}/subscriptions?productId=${id}®ionsVersion.version=${v}`, body) }); log(TAG, `${s.id}: ${r.created ? 'created' : 'exists already (made by an earlier run); run again to compare it with the config'}`); if (!r.created) continue; - } else if (diff.listings.length || diff.basePlan !== 'same') { + } else if (diff.listings.length || diff.basePlan !== 'same' || (prune && diff.listingsRemoved?.length)) { + const pruneLanguages = prune; if (diff.basePlan === 'changed' && diff.priceChanges.length && !liveOk) { held.push({ id: s.id, changes: diff.priceChanges.map(p => ({ region: p.regionCode, from: p.from, to: p.to })) }); - if (diff.listings.length) { - // the listings only; the base plans as Play has them - await play.call('PATCH', `${play.API}/subscriptions/${id}?updateMask=listings®ionsVersion.version=${v}`, { ...playPatchSubscription(cur!, body), basePlans: cur!.basePlans?.map(({ state: _s, ...b }) => b) }); - log(TAG, `${s.id}: listings updated (prices unchanged)`); + if (diff.listings.length || diff.grace || (prune && diff.listingsRemoved?.length)) { + // the text only (listings, grace period); the base plans as Play has them + const plans = cur!.basePlans?.map(({ state: _s, ...b }) => (diff.grace && b.basePlanId === basePlanId(s) + ? { ...b, autoRenewingBasePlanType: { ...b.autoRenewingBasePlanType!, gracePeriodDuration: diff.grace.to } } : b)); + await play.call('PATCH', `${play.API}/subscriptions/${id}?updateMask=listings${diff.grace ? ',basePlans' : ''}®ionsVersion.version=${v}`, { ...playPatchSubscription(cur!, body, { pruneLanguages }), basePlans: plans }); + log(TAG, `${s.id}: ${playSubTextChanges(diff, prune).join(' · ')} updated (prices unchanged)`); } } else { - await play.call('PATCH', `${play.API}/subscriptions/${id}?updateMask=listings,basePlans®ionsVersion.version=${v}`, playPatchSubscription(cur!, body)); + await play.call('PATCH', `${play.API}/subscriptions/${id}?updateMask=listings,basePlans®ionsVersion.version=${v}`, playPatchSubscription(cur!, body, { pruneLanguages })); log(TAG, `${s.id}: updated`); } } @@ -131,14 +167,9 @@ export async function run(ctx: Ctx): Promise { log(TAG, `${s.id}: base plan ${basePlanId(s)} activated`); } const regions = body.basePlans![0]!.regionalConfigs!.map(r => ({ regionCode: r.regionCode, price: r.price! })); + const offerUrl = `${play.API}/subscriptions/${id}/basePlans/${basePlanId(s)}/offers`; const createOffer = async (o: { type: string; usd?: number }, extra?: NonNullable[number]) => { - let offerRegions; - if (o.type === 'pay-up-front') { - const oc = await convert(o.usd!); - offerRegions = { regions: Object.values(oc.convertedRegionPrices).map(r => ({ regionCode: r.regionCode, price: r.price })), other: oc.convertedOtherRegionsPrice }; - } - const ob = playOfferBody(pkg, s, regions, offerRegions, extra); - const offerUrl = `${play.API}/subscriptions/${id}/basePlans/${basePlanId(s)}/offers`; + const ob = await buildOffer(s, regions, o, extra); // offer ids are unique per base plan: a 409 or an unclear answer finds the existing offer, never a second one const r = await createOnce({ what: `${s.id} offer ${ob.offerId}`, tag: TAG, unique: true, find: () => getOrNull<{ state?: string }>(play, `${offerUrl}/${encodeURIComponent(ob.offerId)}`), @@ -149,6 +180,12 @@ export async function run(ctx: Ctx): Promise { }; if (s.intro && offerMissing) await createOffer(s.intro); for (const o of (s.offers ?? []).filter(x => extraMissing.includes(x.id))) await createOffer(o, o); + // offers that exist but differ: phases (text) are updated; their prices only behind the price gate + for (const d of offerDrift) { + if (d.prices.length && !liveOk) { held.push({ id: `${s.id} offer ${d.offerId}`, changes: d.prices }); continue; } + await play.call('PATCH', `${offerUrl}/${encodeURIComponent(d.offerId)}?updateMask=phases®ionsVersion.version=${v}`, d.body); + log(TAG, `${s.id}: offer ${d.offerId} updated (${[...d.phase, ...(d.prices.length ? [`${d.prices.length} price(s)`] : [])].join('; ')})`); + } } holdPriceChanges(held); done(TAG, held.length ? 'subscriptions done, price changes left for the owner' : 'subscriptions done'); diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 6f89dc2..c44253a 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1251,3 +1251,17 @@ that fails without the fix (see CONTRIBUTING.md). - **Do:** update storebound; the warning was false. - **Guard:** `readProjectEntitlements` in `cli/apple/signing.ts` compares forward-slash paths on every OS (`tests/entitlements-ref.test.ts`). + +## 104. An existing store item differs from the config and the run said nothing +- **Symptom:** `apple iap --yes` updated only missing localizations of live consumables while the config's USD prices + (12.99 / 129.99 / 649.99) differed from the store (9.99 / 99.99 / 500.00); the dry run showed no price, and changed + names and descriptions were never sent. An audit found the same class in 24 places (subscriptions, offers, app + price and availability, events, custom pages, review details). +- **Cause:** existing items were checked for existence only, not compared field by field. +- **Do:** read the dry run: every difference of an existing item is a row (old -> new). Text changes are sent; + prices, dropped regions and removed territories need `--allow-price-changes` / `--allow-availability-changes` + (the owner's call); fields Apple cannot edit (family sharing on, offer-code and win-back campaigns, intro offers, + subscription period) are named, never changed. +- **Guard:** `iapLocalizationChanges` / `iapAttributeChanges` / `availabilityChange` (`cli/apple/iap.ts`), the + subscription helpers in `cli/lib/subscriptions.ts`, `planAppInfo` / `reviewDetailDiff`, `campaignDiff`, + `winBackDiff`, `eventAttrDiff`; tests `apple-iap-drift`, `subscriptions-drift`, `appinfo-drift`, `misc-drift`. diff --git a/tests/pitfalls.test.ts b/tests/pitfalls.test.ts index 1d2ba3e..a75c6c6 100644 --- a/tests/pitfalls.test.ts +++ b/tests/pitfalls.test.ts @@ -66,7 +66,10 @@ describe('store list lag after create', () => { { match: new RegExp(`^/v1/apps/6400000101/inAppPurchasesV2\\?filter\\[productId\\]=${GEMS}`), answer: page([]) }, { match: /^\/v2\/inAppPurchases\/i-pro\/inAppPurchaseLocalizations/, answer: page([]) }, { match: /^\/v2\/inAppPurchases\/i-pro\/iapPriceSchedule/, answer: notFound() }, - { match: /^\/v2\/inAppPurchases\/i-pro\/inAppPurchaseAvailability/, answer: { data: { type: 'inAppPurchaseAvailabilities', id: 'av' } } }, + { match: /^\/v2\/inAppPurchases\/i-pro\/inAppPurchaseAvailability/, answer: { data: { type: 'inAppPurchaseAvailabilities', id: 'av', attributes: { availableInNewTerritories: true } } } }, + { match: /^\/v1\/inAppPurchaseAvailabilities\/av\/availableTerritories/, answer: page([{ type: 'territories', id: 'USA' }, { type: 'territories', id: 'TUR' }]) }, + // the product as the store has it: the same reference name as the config, so only localizations and prices change + { match: /^\/v2\/inAppPurchases\/i-pro(\?|$)/, answer: { data: { type: 'inAppPurchases', id: 'i-pro', attributes: { productId: PRO, name: 'No Ads', familySharable: false, state: 'MISSING_METADATA' } } } }, ]); const r = await capture(() => iap(p.ctx(['--dry']))); expect(r.out).toContain('dry run: apple iap: 2 change(s); nothing written'); diff --git a/tests/subscriptions-drift.test.ts b/tests/subscriptions-drift.test.ts new file mode 100644 index 0000000..0145cb2 --- /dev/null +++ b/tests/subscriptions-drift.test.ts @@ -0,0 +1,148 @@ +// Existing subscription items that differ from the config are shown in the dry run and updated (text) or held behind the +// price gate (money). Pure helpers of cli/lib/subscriptions.ts with neutral data. +import { describe, expect, test } from 'bun:test'; +import type { Subscription } from '../cli/lib/config'; +import { toMoney } from '../cli/lib/money'; +import { + appleAvailabilityDiff, appleGroupLocDiff, appleIntroDiff, appleIntroOffers, appleLocDiff, appleSubAttrDiff, appleSubscriptionBody, + type PlayOfferLike, playOfferBody, playOfferDiff, playPatchSubscription, type PlaySubscription, playSubDiff, playSubRegions, playSubscriptionBody, playSubTextChanges, +} from '../cli/lib/subscriptions'; + +const LANGS = [{ id: 'en', apple: 'en-US', play: 'en-US' }, { id: 'de', apple: 'de-DE', play: 'de-DE' }] as never; +const s: Subscription = { + id: 'com.example.app.pro_monthly', period: 'P1M', level: 1, usd: 4.99, gracePeriod: 'P7D', familySharable: false, reviewNote: 'Sign in with the demo account', + listings: { en: { title: 'Pro', description: 'All features', benefits: ['A'] }, de: { title: 'Pro', description: 'Alle Funktionen' } }, + intro: { type: 'free', duration: 'P1W' }, +}; +const conv = { US: { regionCode: 'US', price: toMoney('USD', 4.99) }, TR: { regionCode: 'TR', price: toMoney('TRY', 99.99) } }; +const other = { usdPrice: toMoney('USD', 4.99), eurPrice: toMoney('EUR', 4.99) }; +const want = (): PlaySubscription => playSubscriptionBody('com.example.app', s, LANGS, playSubRegions(s, conv), other); +const live = (): PlaySubscription => { const c = JSON.parse(JSON.stringify(want())) as PlaySubscription; c.basePlans![0]!.state = 'ACTIVE'; return c; }; + +describe('apple subscription attributes', () => { + const ok = { name: 'Pro', subscriptionPeriod: 'ONE_MONTH', familySharable: false, reviewNote: 'Sign in with the demo account', groupLevel: 1 }; + test('equal: nothing', () => { + expect(appleSubAttrDiff(s, ok)).toEqual({ patch: {}, text: [], report: [] }); + expect(appleSubAttrDiff(s, {})).toEqual({ patch: {}, text: [], report: [] }); + }); + test('name, review note and level are patched; period and family sharing only reported', () => { + const d = appleSubAttrDiff(s, { ...ok, name: 'Old', reviewNote: null, groupLevel: 2, subscriptionPeriod: 'ONE_YEAR', familySharable: true }); + expect(d.patch).toEqual({ name: 'Pro', reviewNote: 'Sign in with the demo account', groupLevel: 1 }); + expect(d.report.length).toBe(2); + expect(d.report[0]).toContain('ONE_YEAR'); + expect(d.report[1]).toContain('familySharable'); + expect(Object.keys(appleSubscriptionBody('g', s).data.attributes)).toContain('reviewNote'); + }); + test('a config without referenceName compares with the first listing title', () => { + expect(appleSubAttrDiff(s, { name: 'Pro' }).patch).toEqual({}); + expect(appleSubAttrDiff({ ...s, referenceName: 'Pro monthly' }, { name: 'Pro' }).patch).toEqual({ name: 'Pro monthly' }); + }); +}); + +describe('apple localizations', () => { + test('subscription text', () => { + expect(appleLocDiff({ title: 'Pro', description: 'All features' }, { name: 'Pro', description: 'All features' })).toBeNull(); + expect(appleLocDiff({ title: 'Pro', description: 'All features' }, { name: 'Pro', description: 'Old' })).toEqual({ description: 'All features' }); + expect(appleLocDiff({ title: 'Pro', description: 'x' }, {})).toBeNull(); + }); + test('group name and customAppName (only when configured)', () => { + expect(appleGroupLocDiff({ name: 'Pro' }, { name: 'Pro', customAppName: 'Anything' })).toBeNull(); + expect(appleGroupLocDiff({ name: 'Pro', customAppName: 'Example' }, { name: 'Old', customAppName: null })).toEqual({ name: 'Pro', customAppName: 'Example' }); + }); +}); + +describe('apple availability', () => { + test('missing territories and new territories off', () => { + expect(appleAvailabilityDiff({ territories: ['USA', 'TUR'], availableInNewTerritories: true }, ['USA', 'TUR'])).toBeNull(); + expect(appleAvailabilityDiff({ territories: ['USA'], availableInNewTerritories: true }, ['USA', 'TUR', 'DEU'])).toEqual({ missing: ['TUR', 'DEU'], newTerritories: false }); + expect(appleAvailabilityDiff({ territories: ['USA'], availableInNewTerritories: false }, ['USA'])).toEqual({ missing: [], newTerritories: true }); + }); +}); + +describe('apple intro offers', () => { + const resp = (mode: string, duration: string, periods: number, price?: string) => ({ + data: [{ id: 'i1', attributes: { offerMode: mode, duration, numberOfPeriods: periods }, + relationships: { territory: { data: { id: 'USA' } }, ...(price ? { subscriptionPricePoint: { data: { id: 'pp1' } } } : {}) } }], + included: price ? [{ id: 'pp1', type: 'subscriptionPricePoints', attributes: { customerPrice: price } }] : [], + }); + test('equal or no offer yet: nothing', () => { + expect(appleIntroDiff(s, appleIntroOffers(resp('FREE_TRIAL', 'ONE_WEEK', 1)))).toEqual([]); + expect(appleIntroDiff(s, [])).toEqual([]); + }); + test('differences are reported as "intro differs"', () => { + const d = appleIntroDiff(s, appleIntroOffers(resp('PAY_UP_FRONT', 'ONE_MONTH', 1))); + expect(d.length).toBe(2); + expect(d.every(x => x.startsWith('intro differs: '))).toBe(true); + const paid: Subscription = { ...s, intro: { type: 'pay-as-you-go', periods: 3, usd: 1.99 } }; + expect(appleIntroDiff(paid, appleIntroOffers(resp('PAY_AS_YOU_GO', 'ONE_MONTH', 3, '0.99')))).toEqual([expect.stringContaining('price USA 0.99')]); + expect(appleIntroDiff({ ...s, intro: undefined }, appleIntroOffers(resp('FREE_TRIAL', 'ONE_WEEK', 1)))[0]).toContain('config has none'); + }); +}); + +describe('play subscription diff', () => { + test('equal: the old shape, no extra fields', () => { + expect(playSubDiff(live(), want())).toEqual({ create: false, listings: [], basePlan: 'same', priceChanges: [], activate: false }); + }); + test('other regions USD / EUR price is a gated price change', () => { + const cur = live(); + cur.basePlans![0]!.otherRegionsConfig = { usdPrice: toMoney('USD', 3.99), eurPrice: toMoney('EUR', 4.99) }; + const d = playSubDiff(cur, want()); + expect(d.basePlan).toBe('changed'); + expect(d.priceChanges).toEqual([{ regionCode: 'other regions', from: 'USD 399 / EUR 499', to: 'USD 499 / EUR 499' }]); + }); + test('a region sold on Play but not in the config is an owner-gated "not sold" row', () => { + const cur = live(); + cur.basePlans![0]!.regionalConfigs!.push({ regionCode: 'JP', newSubscriberAvailability: true, price: toMoney('JPY', 750) }); + const d = playSubDiff(cur, want()); + expect(d.droppedRegions).toEqual(['JP']); + expect(d.priceChanges).toEqual([{ regionCode: 'JP', from: 'JPY 75000', to: 'not sold' }]); + expect(d.basePlan).toBe('changed'); + }); + test('grace period is its own line and needs no price gate', () => { + const cur = live(); + cur.basePlans![0]!.autoRenewingBasePlanType!.gracePeriodDuration = 'P3D'; + const d = playSubDiff(cur, want()); + expect(d.grace).toEqual({ from: 'P3D', to: 'P7D' }); + expect(d.priceChanges).toEqual([]); + expect(playSubTextChanges(d)).toEqual(['grace P3D -> P7D']); + // a config without a grace period leaves Play's alone + const noGrace = want(); + delete noGrace.basePlans![0]!.autoRenewingBasePlanType!.gracePeriodDuration; + expect(playSubDiff(cur, noGrace).grace).toBeUndefined(); + }); + test('languages on Play but not in the config are reported and kept unless pruned', () => { + const cur = live(); + cur.listings!.push({ languageCode: 'fr-FR', title: 'Pro', description: 'Tout' }); + const d = playSubDiff(cur, want()); + expect(d.listingsRemoved).toEqual(['fr-FR']); + expect(d.listings).toEqual([]); + expect(playSubTextChanges(d, true)).toEqual(['listings removed: fr-FR']); + expect(playSubTextChanges(d)[0]).toContain('kept on Play'); + expect(playPatchSubscription(cur, want()).listings!.map(l => l.languageCode)).toContain('fr-FR'); + expect(playPatchSubscription(cur, want(), { pruneLanguages: true }).listings!.map(l => l.languageCode)).not.toContain('fr-FR'); + }); +}); + +describe('play offers that exist', () => { + const regions = [{ regionCode: 'US', price: toMoney('USD', 4.99) }, { regionCode: 'TR', price: toMoney('TRY', 99.99) }]; + const body = (sub: Subscription) => playOfferBody('com.example.app', sub, regions) as unknown as PlayOfferLike; + test('equal: nothing', () => { + expect(playOfferDiff(JSON.parse(JSON.stringify(body(s))), body(s))).toEqual({ phase: [], prices: [] }); + }); + test('duration and periods are phase (text) changes', () => { + const cur = body({ ...s, intro: { type: 'free', duration: 'P1M' } }); + const d = playOfferDiff(cur, body(s)); + expect(d.phase).toEqual(['duration P1M -> P1W']); + expect(d.prices).toEqual([]); + }); + test('free to discounted is a phase change, a new discount percentage is money', () => { + const payg: Subscription = { ...s, intro: { type: 'pay-as-you-go', periods: 2, usd: 2.49 } }; + const cur = body(s); + const d = playOfferDiff(cur, body(payg)); + expect(d.phase.some(x => x.includes('free -> -50%'))).toBe(true); + expect(d.phase.some(x => x.startsWith('periods 1 -> 2'))).toBe(true); + const cheaper = playOfferDiff(body(payg), body({ ...payg, intro: { type: 'pay-as-you-go', periods: 2, usd: 1.99 } })); + expect(cheaper.phase).toEqual([]); + expect(cheaper.prices.map(p => `${p.region} ${p.from} -> ${p.to}`)).toContain('US -50% -> -60%'); + }); +}); From e77f2b68f573c01cafa18e411d80a03c3fe93ada Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 19:51:07 +0700 Subject: [PATCH 115/344] storebound 0.8.29: version in package.json and every copy, CHANGELOG 0.8.29 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 7000a74..010f08d 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.28", + "version": "0.8.29", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 7535e7a..6b3d13b 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.28", + "version": "0.8.29", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index e0abd17..2a01cf5 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.28", + "version": "0.8.29", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index c5f90f7..6b71f5c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.29 · 2026-10-22 + - **Existing store items are compared with the config, field by field** (pitfall 104). The dry run shows every difference (old -> new); texts are sent, money and availability need a flag, fields Apple cannot edit are named. - `apple iap`: price (`--allow-price-changes`), localization names and descriptions, reference name, review note, diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 4ed3263..e942f78 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.28", + "version": "0.8.29", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 4dc267b..a701c60 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4096,7 +4096,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.28" +version = "0.8.29" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 1ad40b3..a015e93 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.28" +version = "0.8.29" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 33afde1..de6c1e0 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.28", + "version": "0.8.29", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index 90ed811..b878a45 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.28", + "version": "0.8.29", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index e3dcb1f..d3e6370 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.28", + "version": "0.8.29", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From 27db41c3f0ad3d39cc8274f85944c1e2a35e4a3f Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 21:24:24 +0800 Subject: [PATCH 116/344] Desktop portfolio v2: greeting with what is moving, store-style app cards (rendered screenshots or the icon on its tint), two-store release pipeline, crash sparkline, one next-step button; What changed feed and Fix first queue; Cards / Table switch keeps the old table --- apps/desktop/src/i18n/en.ts | 47 ++++ apps/desktop/src/i18n/tr.ts | 47 ++++ apps/desktop/src/screens/Portfolio.tsx | 369 ++++++++++++++++++++++--- apps/desktop/src/styles.css | 91 ++++++ 4 files changed, 519 insertions(+), 35 deletions(-) diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 9e21009..c400f03 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -1865,4 +1865,51 @@ export const en = { 'gs.syncHint': 'Dry run first, then you confirm; nothing is submitted or published.', 'gs.synced': 'Game services in step', 'gs.setup': 'Setup plan', + 'pf.morning': "Good morning.", + 'pf.afternoon': "Good afternoon.", + 'pf.evening': "Good evening.", + 'pf.moving': "{count} releases are moving", + 'pf.moving_one': "1 release is moving", + 'pf.movingNone': "Nothing is moving right now", + 'pf.notMovingUnknown': "Read the stores to see what is moving", + 'pf.readAgo': "stores read {when}", + 'pf.layout': "Layout", + 'pf.cards': "Cards", + 'pf.table': "Table", + 'pf.next': "next", + 'pf.crash': "crash", + 'pf.ctaFix': "Fix {count} blockers", + 'pf.ctaFix_one': "Fix 1 blocker", + 'pf.ctaRollout': "Roll out (now {share})", + 'pf.ctaRelease': "Release {version}", + 'pf.ctaSubmit': "Submit {version}", + 'pf.ctaReview': "Follow review of {version}", + 'pf.ctaWarnings': "Look at {count} warnings", + 'pf.ctaWarnings_one': "Look at 1 warning", + 'pf.ctaUpload': "Upload a build", + 'pf.ctaOpen': "Open releases", + 'pf.feed': "What changed", + 'pf.feedSub': "Releases, health and folders, newest first", + 'pf.feedEmpty': "Nothing changed yet", + 'pf.feedEmptyText': "Read the stores to see releases and health here.", + 'pf.evLive': "{version} is live on {store}", + 'pf.evRollout': "{version} is rolling out to {share} on {store}", + 'pf.evReview': "{version} went into review on {store}", + 'pf.evApproved': "{version} was approved on {store}", + 'pf.evRejected': "{version} was rejected on {store}", + 'pf.evHalted': "{version} rollout halted on {store}", + 'pf.evTesting': "{version} is in testing on {store}", + 'pf.evDraft': "{version} draft on {store}", + 'pf.evCrash': "crash rate {rate} on Google Play", + 'pf.evAdded': "folder added to the workspace", + 'pf.more': "Show {count} more", + 'pf.less': "Show less", + 'pf.fixFirst': "Fix first", + 'pf.fixFirstSub': "{count} items, blockers first", + 'pf.fixFirstSub_one': "1 item", + 'pf.blocker': "Blocker", + 'pf.warning': "Warning", + 'pf.note': "Note", + 'pf.fixIn': "Fix in {tab}", + 'pf.openTab': "Open {tab}", } as const; diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index 79f399c..afc278c 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -1867,4 +1867,51 @@ export const tr: Record = { 'gs.syncHint': 'Önce deneme çalıştırması, sonra sen onaylarsın; hiçbir şey gönderilmez ya da yayınlanmaz.', 'gs.synced': 'Oyun hizmetleri eşit', 'gs.setup': 'Kurulum planı', + 'pf.morning': "Günaydın.", + 'pf.afternoon': "İyi günler.", + 'pf.evening': "İyi akşamlar.", + 'pf.moving': "{count} sürüm ilerliyor", + 'pf.moving_one': "1 sürüm ilerliyor", + 'pf.movingNone': "Şu an ilerleyen sürüm yok", + 'pf.notMovingUnknown': "Neyin ilerlediğini görmek için mağazaları oku", + 'pf.readAgo': "mağazalar {when} okundu", + 'pf.layout': "Görünüm", + 'pf.cards': "Kartlar", + 'pf.table': "Tablo", + 'pf.next': "sıradaki", + 'pf.crash': "çökme", + 'pf.ctaFix': "{count} engeli düzelt", + 'pf.ctaFix_one': "1 engeli düzelt", + 'pf.ctaRollout': "Dağıtımı sürdür (şu an {share})", + 'pf.ctaRelease': "{version} sürümünü yayınla", + 'pf.ctaSubmit': "{version} sürümünü gönder", + 'pf.ctaReview': "{version} incelemesini izle", + 'pf.ctaWarnings': "{count} uyarıya bak", + 'pf.ctaWarnings_one': "1 uyarıya bak", + 'pf.ctaUpload': "Derleme yükle", + 'pf.ctaOpen': "Sürümleri aç", + 'pf.feed': "Neler değişti", + 'pf.feedSub': "Sürümler, sağlık ve klasörler, en yenisi üstte", + 'pf.feedEmpty': "Henüz değişiklik yok", + 'pf.feedEmptyText': "Sürümleri ve sağlığı burada görmek için mağazaları oku.", + 'pf.evLive': "{version}, {store} üzerinde yayında", + 'pf.evRollout': "{version}, {store} üzerinde {share} kullanıcıya dağıtılıyor", + 'pf.evReview': "{version}, {store} incelemesine girdi", + 'pf.evApproved': "{version}, {store} tarafından onaylandı", + 'pf.evRejected': "{version}, {store} tarafından reddedildi", + 'pf.evHalted': "{version} dağıtımı {store} üzerinde durduruldu", + 'pf.evTesting': "{version}, {store} üzerinde testte", + 'pf.evDraft': "{version}, {store} üzerinde taslak", + 'pf.evCrash': "Google Play çökme oranı {rate}", + 'pf.evAdded': "klasör çalışma alanına eklendi", + 'pf.more': "{count} tane daha göster", + 'pf.less': "Daha az göster", + 'pf.fixFirst': "Önce bunları düzelt", + 'pf.fixFirstSub': "{count} madde, önce engeller", + 'pf.fixFirstSub_one': "1 madde", + 'pf.blocker': "Engel", + 'pf.warning': "Uyarı", + 'pf.note': "Not", + 'pf.fixIn': "{tab} sekmesinde düzelt", + 'pf.openTab': "{tab} sekmesini aç", }; diff --git a/apps/desktop/src/screens/Portfolio.tsx b/apps/desktop/src/screens/Portfolio.tsx index 91dc8d1..b6e1a9e 100644 --- a/apps/desktop/src/screens/Portfolio.tsx +++ b/apps/desktop/src/screens/Portfolio.tsx @@ -1,15 +1,17 @@ -// Portfolio: every app of every studio on both stores. KPIs, a toolbar (search, studio chips with counts, sort, -// grouping), one row per app (live version and state per store with its place on the release track, next version, -// crash rate, catalog parity, config check), grouped by studio; then what needs attention and the workspace state. +// Portfolio: every app of every studio on both stores. A greeting that says what is moving, KPIs, a toolbar (search, +// studio chips with counts, sort, grouping, cards / table), one store-listing card per app (rendered screenshots, the +// release track per store, crash rate, one next step) or the dense table (live version and state per store, next +// version, crash rate, catalog parity, config check), grouped by studio; then what changed and what to fix first. import { plainError } from '../../../../cli/lib/google-errors'; import { BlockedProjectsNotice, blockedProjects } from '../ui/StoreError'; -import { useEffect, useMemo, useState } from 'react'; -import { api, type AppStatus, newJob, type StoreRelease, type ToolResult } from '../api'; +import { type CSSProperties, type ReactNode, useEffect, useMemo, useState } from 'react'; +import { api, type AppStatus, newJob, reads, type RenderImage, type StoreRelease, type ToolResult } from '../api'; import { type Key, t } from '../i18n'; import { ago, pct, share } from '../lib/format'; import { filterSort, groupByStudio, type ListRow, type SortBy, studioCounts, type UnifiedApp } from '../lib/identity'; -import { type Attention, attention, healthSeries, type HealthSnapshot, isError, laneOf, PLAY_THRESHOLDS, STAGES, storeNow, type Tone } from '../lib/model'; -import { useNav } from '../nav'; +import { type Attention, attention, healthSeries, type HealthSnapshot, hueOf, isError, laneOf, PLAY_THRESHOLDS, STAGES, storeNow, type Tone } from '../lib/model'; +import { type AppTab, useNav } from '../nav'; +import type { IconName } from '../ui/icons'; import { useData } from '../store'; import { exportName, portfolioCsv } from '../lib/exports'; import { useExports } from '../ui/Exports'; @@ -95,35 +97,304 @@ function HealthCell({ c, android }: { c: { h: HealthSnapshot; at: string } | nul ); } -function AttentionList({ items }: { items: Attention[] }) { - const nav = useNav(); - if (!items.length) return {t('portfolio.allClearText')}; - return ( -
- {items.slice(0, 8).map((a, i) => ( - - ))} -
- ); -} - /** Newest store activity of an app (release record date), else when its folder was added. */ function updatedAt(a: UnifiedApp, l: AppStatus | undefined): string | null { const dates = (l?.release.all ?? []).map(r => r.date).filter((x): x is string => !!x); return dates.sort().at(-1) ?? a.project?.added ?? null; } +// ---- App cards ---- + +/** Every release record of an app (live read first). */ +function releasesOf(l: AppStatus | undefined): StoreRelease[] { + if (!l) return []; + return l.release.all ?? [l.release.current?.ios, l.release.current?.android, l.release.next?.ios, l.release.next?.android].filter((x): x is StoreRelease => !!x); +} + +// Up to three phone screenshots of the app folder's rendered store art (`shots gallery`, then one `project.render` +// data: URL each), loaded once per window and one app at a time. No renders: an empty list (the card shows the icon). +const shotCache = new Map>(); +let shotChain: Promise = Promise.resolve(); +function loadShots(projectId: string): Promise { + const hit = shotCache.get(projectId); + if (hit) return hit; + const job = shotChain.then(async () => { + const r = await reads.renders(projectId).catch(() => null); + const res = r?.data; + if (!res) return []; + const v = res.variants.find(x => !x.id) ?? res.variants[0]; + const lang = v?.langs.find(l => l.lang === 'en' || l.lang.startsWith('en-')) ?? v?.langs[0]; + const rows = (lang?.rows ?? []).filter(row => !/feature|ipad|preview|tv|watch|mac|tablet/i.test(row.size) && row.tiles.some(x => x.kind === 'image')); + rows.sort((a, b) => (a.store === 'apple' ? 0 : 1) - (b.store === 'apple' ? 0 : 1)); + const files = (rows[0]?.tiles ?? []).filter(x => x.kind === 'image' && x.h >= x.w).slice(0, 3).map(x => x.src); + const out: string[] = []; + for (const file of files) { + const img = await api.call('project.render', projectId, { args: { file } }).catch(() => null); + if (img?.data?.dataUrl) out.push(img.data.dataUrl); + } + return out; + }).catch(() => [] as string[]); + shotChain = job; + shotCache.set(projectId, job); + return job; +} + +function useShots(projectId: string | null): string[] { + const [shots, setShots] = useState([]); + useEffect(() => { + if (!projectId) return; + let alive = true; + loadShots(projectId).then(s => { if (alive) setShots(s); }, () => {}); + return () => { alive = false; }; + }, [projectId]); + return shots; +} + +// The hue of an app icon (saturation-weighted mean colour), for the card's soft gradient; the name's hue without one. +const tintCache = new Map(); +function useTint(src: string | null, name: string): number { + const fallback = hueOf(name); + const [hue, setHue] = useState(() => (src ? tintCache.get(src) : undefined) ?? fallback); + useEffect(() => { + if (!src) { setHue(fallback); return; } + const cached = tintCache.get(src); + if (cached !== undefined) { setHue(cached); return; } + let alive = true; + const img = new Image(); + img.onload = () => { + try { + const c = document.createElement('canvas'); + c.width = c.height = 16; + const g = c.getContext('2d'); + if (!g) return; + g.drawImage(img, 0, 0, 16, 16); + const px = g.getImageData(0, 0, 16, 16).data; + let r = 0, gr = 0, b = 0, w = 0; + for (let i = 0; i < px.length; i += 4) { + const R = px[i]!, G = px[i + 1]!, B = px[i + 2]!, A = px[i + 3]! / 255; + const s = (Math.max(R, G, B) - Math.min(R, G, B)) / 255 * A; + r += R * s; gr += G * s; b += B * s; w += s; + } + if (w < 0.5) return; + r /= w; gr /= w; b /= w; + const mx = Math.max(r, gr, b), mn = Math.min(r, gr, b), d = mx - mn; + if (d < 1) return; + let h = mx === r ? ((gr - b) / d) % 6 : mx === gr ? (b - r) / d + 2 : (r - gr) / d + 4; + h = Math.round(h * 60 + 360) % 360; + tintCache.set(src, h); + if (alive) setHue(h); + } catch { /* keep the name's hue */ } + }; + img.src = src; + return () => { alive = false; }; + }, [src, fallback]); + return hue; +} + +interface Cta { text: string; tab: AppTab; icon: IconName; primary: boolean } + +/** The one next step of an app, from its state: blockers first, then the release that waits for a move. */ +export function nextStep(o: { project: boolean; att: Attention[]; all: StoreRelease[]; next: string | null }): Cta { + const bad = o.att.filter(a => a.tone === 'bad'); + if (bad.length) return { text: t('pf.ctaFix', { count: bad.length }), tab: bad[0]!.tab ?? 'checks', icon: 'alertCircle', primary: true }; + const rolling = o.all.find(r => r.phase === 'rollout' && r.fraction !== null && r.fraction < 1); + if (rolling) return { text: t('pf.ctaRollout', { share: share(rolling.fraction ?? 0) }), tab: 'releases', icon: 'rocket', primary: true }; + const approved = o.all.find(r => r.phase === 'approved'); + if (approved) return { text: t('pf.ctaRelease', { version: approved.version ?? '' }), tab: 'releases', icon: 'rocket', primary: true }; + const ready = o.all.find(r => r.phase === 'draft' || r.phase === 'testing'); + if (ready) return { text: t('pf.ctaSubmit', { version: ready.version ?? '' }), tab: 'releases', icon: 'send', primary: true }; + const review = o.all.find(r => r.phase === 'review' || r.phase === 'sent'); + if (review) return { text: t('pf.ctaReview', { version: review.version ?? '' }), tab: 'releases', icon: 'clock', primary: false }; + if (o.att.length) return { text: t('pf.ctaWarnings', { count: o.att.length }), tab: o.att[0]!.tab ?? 'checks', icon: 'alert', primary: false }; + if (o.project && !o.next) return { text: t('pf.ctaUpload'), tab: 'releases', icon: 'upload', primary: false }; + return { text: t('pf.ctaOpen'), tab: 'releases', icon: 'arrowRight', primary: false }; +} + +function Track({ store, all, on }: { store: 'ios' | 'android'; all: StoreRelease[]; on: boolean }) { + const { now, next } = storeNow(all, store); + const r = next ?? now; + const lane = laneOf(store, on ? r : null); + const name = store === 'ios' ? 'App Store' : 'Google Play'; + const state = !on ? t('app.notOnStore') : !r ? t('portfolio.noVersion') : `${r.version ?? ''} · ${t(`phase.${r.phase}` as Key)}${lane.share !== null && lane.share < 1 ? ` ${share(lane.share)}` : ''}`; + return ( +
+ {store === 'ios' ? 'App Store' : 'Play'} + + {on && r ? `${r.version ?? ''}${lane.share !== null && lane.share < 1 ? ` · ${share(lane.share)}` : ''}` : '–'} +
+ ); +} + +function CardHealth({ c, android }: { c: { h: HealthSnapshot; at: string } | null | undefined; android: boolean }) { + const play = c?.h.play; + if (!android || !c || !play || isError(play)) { + return {!android || (c && !play) ? t('portfolio.healthNoPlay') : c && play && isError(play) ? t('portfolio.unreadable') : t('portfolio.healthNotRead')}; + } + const s = healthSeries(play.crash, 'userPerceivedCrashRate', PLAY_THRESHOLDS.crash); + return ( + + + {t('pf.crash')}{pct(s.current)} + + ); +} + +interface CardRow { app: UnifiedApp; e: AppStatus | undefined; l: AppStatus | undefined; att: Attention[] } + +function AppCard({ r, icon, health, studio }: { r: CardRow; icon: string | null; health: { h: HealthSnapshot; at: string } | null | undefined; studio?: ReactNode }) { + const nav = useNav(); + const { app, e, l, att } = r; + const projectId = app.project && !app.project.missing ? app.project.id : null; + const shots = useShots(projectId); + const hue = useTint(icon, app.name); + const all = releasesOf(l); + const ios = !!(app.ios || e?.app?.platforms.ios), android = !!(app.android || e?.app?.platforms.android); + const sub = app.ios?.app.bundleId ?? e?.app?.platforms.ios?.bundleId ?? app.android?.app.id ?? e?.app?.platforms.android?.packageName ?? ''; + const next = l?.release.next?.version ?? null; + const cta = nextStep({ project: !!app.project, att, all, next }); + const name = e?.app?.name && app.project ? e.app.name : app.name; + const go = (tab: AppTab) => nav.go({ screen: 'app', appId: app.key, tab }); + const style = { '--tint-h': String(hue) } as CSSProperties; + return ( +
+ +
+
+ +
+ + {sub}{!app.project && {t('apps.storeOnly')}} +
+
+ {t('pf.next')} + {next ?? '–'} +
+
+ {studio} +
+ + + +
+
+ + +
+
+
+ ); +} + +// ---- What changed ---- + +interface Ev { key: string; app: UnifiedApp; text: string; at: string; icon: IconName; tone: Tone } + +function events(rows: CardRow[], health: Record): Ev[] { + const out: Ev[] = []; + for (const r of rows) { + for (const rel of releasesOf(r.l)) { + if (!rel.date) continue; + const store = rel.store === 'ios' ? 'App Store' : 'Google Play', version = rel.version ?? ''; + const ev = (key: Key, icon: IconName, tone: Tone, vars: Record = {}) => + out.push({ key: `${r.app.key}|${rel.store}|${version}|${rel.phase}`, app: r.app, text: t(key, { version, store, ...vars }), at: rel.date!, icon, tone }); + switch (rel.phase) { + case 'live': ev('pf.evLive', 'check', 'ok'); break; + case 'rollout': ev('pf.evRollout', 'rocket', 'accent', { share: share(rel.fraction ?? 1) }); break; + case 'review': case 'sent': ev('pf.evReview', 'clock', 'warn'); break; + case 'approved': ev('pf.evApproved', 'check', 'ok'); break; + case 'rejected': ev('pf.evRejected', 'alertCircle', 'bad'); break; + case 'halted': ev('pf.evHalted', 'pause', 'bad'); break; + case 'testing': ev('pf.evTesting', 'flask', 'info'); break; + case 'draft': ev('pf.evDraft', 'edit', 'neutral'); break; + default: break; + } + } + const c = health[r.app.target]; + const play = c?.h.play; + if (c && play && !isError(play)) { + const s = healthSeries(play.crash, 'userPerceivedCrashRate', PLAY_THRESHOLDS.crash); + if (s.current !== null) out.push({ key: `${r.app.key}|health`, app: r.app, text: t('pf.evCrash', { rate: pct(s.current) }), at: c.at, icon: 'activity', tone: s.tone }); + } + if (r.app.project?.added) out.push({ key: `${r.app.key}|added`, app: r.app, text: t('pf.evAdded'), at: r.app.project.added, icon: 'folderPlus', tone: 'neutral' }); + } + return out.sort((a, b) => new Date(b.at).getTime() - new Date(a.at).getTime()); +} + +function Activity({ items, iconFor }: { items: Ev[]; iconFor: (a: UnifiedApp) => string | null }) { + const nav = useNav(); + const [more, setMore] = useState(false); + if (!items.length) return {t('pf.feedEmptyText')}; + const shown = more ? items : items.slice(0, 8); + return ( + <> +
    + {shown.map(ev => ( +
  1. + +
  2. + ))} +
+ {items.length > 8 && } + + ); +} + +function FixFirst({ items, appOf, iconFor }: { items: Attention[]; appOf: (key: string) => UnifiedApp | undefined; iconFor: (a: UnifiedApp) => string | null }) { + const nav = useNav(); + const [more, setMore] = useState(false); + if (!items.length) return {t('portfolio.allClearText')}; + const shown = more ? items : items.slice(0, 5); + return ( +
+ {shown.map((a, i) => { + const app = appOf(a.projectId), tab = a.tab ?? 'checks'; + return ( +
+
+ {app ? : } + {a.app} + {a.tone === 'bad' ? t('pf.blocker') : a.tone === 'warn' ? t('pf.warning') : t('pf.note')} +
+

{a.text}

+ {a.hint &&

{a.hint}

} +
+ +
+
+ ); + })} + {items.length > 5 && } +
+ ); +} + +function greeting(now = new Date()): string { + const h = now.getHours(); + return h < 5 ? t('pf.evening') : h < 12 ? t('pf.morning') : h < 18 ? t('pf.afternoon') : t('pf.evening'); +} + const VIEW_KEY = 'storebound.portfolio.v1'; -interface View { studio: string; sort: SortBy; group: boolean } +interface View { studio: string; sort: SortBy; group: boolean; layout: 'cards' | 'table' } function loadView(): View { try { const v = JSON.parse(localStorage.getItem(VIEW_KEY) ?? '{}') as Partial; - return { studio: typeof v.studio === 'string' ? v.studio : 'all', sort: v.sort === 'recent' || v.sort === 'name' ? v.sort : 'attention', group: v.group !== false }; - } catch { return { studio: 'all', sort: 'attention', group: true }; } + return { studio: typeof v.studio === 'string' ? v.studio : 'all', sort: v.sort === 'recent' || v.sort === 'name' ? v.sort : 'attention', group: v.group !== false, layout: v.layout === 'table' ? 'table' : 'cards' }; + } catch { return { studio: 'all', sort: 'attention', group: true, layout: 'cards' }; } } export function Portfolio() { @@ -226,10 +497,22 @@ export function Portfolio() { }; const notRead = d.portfolioBusy === 'live' ? t('read.waiting') : t('kpi.notRead'); + const moving = rolling.length + review.length; + const headline = !known ? t('pf.notMovingUnknown') : moving ? t('pf.moving', { count: moving }) : t('pf.movingNone'); + const sortedAtt = [...att].sort((a, b) => (a.tone === 'bad' ? 0 : a.tone === 'warn' ? 1 : 2) - (b.tone === 'bad' ? 0 : b.tone === 'warn' ? 1 : 2)); + const feed = events(rows, health); + const appOf = (key: string) => visible.find(a => a.key === key); + const cards = (list: typeof all) => ( +
{list.map(r => )}
+ ); return ( -
-
-

{t('nav.portfolio')}

{t('portfolio.subStudios', { count: visible.length, stores, studios: d.studios.length })}

+
+
+
+

{greeting()}

+

{headline}

+

{t('portfolio.subStudios', { count: visible.length, stores, studios: d.studios.length })}{d.live ? ` · ${t('pf.readAgo', { when: ago(d.live.at) })}` : ''}

+
- { + const s = g.studio === undefined ? undefined : d.studios.find(x => x.id === g.studio) ?? null; + return ( +
+ {s !== undefined && ( +

{s?.name ?? t('studio.none')}{t('portfolio.groupCount', { count: g.rows.length })} · {t('portfolio.groupAccounts', { count: d.accounts.filter(a => (a.studio ?? null) === (g.studio ?? null)).length })}

+ )} + {cards(g.rows)} +
+ ); + }) : {t('portfolio.noMatchText')})} + + {view.layout === 'table' && {t('legend.done')}{t('legend.stages')}
}> {rows.length ? (
@@ -289,11 +585,13 @@ export function Portfolio() {
) : {t('portfolio.noMatchText')}} - + } -
- (a.tone === 'bad' ? 0 : 1) - (b.tone === 'bad' ? 0 : 1))} /> - +
+ +
+ +
{t('nav.studios')}
{d.studios.length ? t('portfolio.studiosN', { count: d.studios.length }) : }
{t('nav.accounts')}
{d.accounts.length ? t('portfolio.accounts', { play: d.accounts.filter(a => a.kind === 'play').length, apple: d.accounts.filter(a => a.kind === 'apple').length }) : }
@@ -302,7 +600,8 @@ export function Portfolio() {
{t('portfolio.storesRead')}
{d.live ? ago(d.live.at) : t('time.never')}
CLI
{d.sidecar ? `storebound ${d.sidecar.version}` : d.sidecarError ?? '–'}
-
+ +
); diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.css index e04f89b..e777cf9 100644 --- a/apps/desktop/src/styles.css +++ b/apps/desktop/src/styles.css @@ -1019,3 +1019,94 @@ button.ck.ck-pick[aria-checked="true"] { border-color: var(--accent-solid); box- .ai-panel { display: grid; grid-template-columns: minmax(0, 1fr); gap: 6px; margin-top: 8px; } .ai-panel .row { display: flex; gap: 8px; flex-wrap: wrap; } .ai-panel .ai-diff { max-height: 320px; } + +/* Portfolio home (screens/Portfolio.tsx, .pf2): greeting, KPI row, store-listing app cards with the release track per + store, then "What changed" and "Fix first". Cards are tinted by the app icon's hue (--tint-h, set per card). */ +:root { --pf-tint-s: 78%; --pf-tint-l: 62%; --pf-tint-a: .16; --pf-tint-a2: .07; --pf-seg: #e6e9f0; --pf-shot-l: 93%; --pf-shot-s: 60%; } +:root[data-theme="dark"] { --pf-tint-l: 58%; --pf-tint-a: .26; --pf-tint-a2: .10; --pf-seg: #232e42; --pf-shot-l: 15%; --pf-shot-s: 45%; } +@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { --pf-tint-l: 58%; --pf-tint-a: .26; --pf-tint-a2: .10; --pf-seg: #232e42; --pf-shot-l: 15%; --pf-shot-s: 45%; } } +.pf2 { gap: 24px; } +.pf2 .pf-hero h1.pf-headline { font-size: 30px; line-height: 1.15; letter-spacing: -.025em; font-weight: 780; margin: 2px 0 6px; } +.pf2 .pf-greet { margin: 0; font-size: var(--t-section); font-weight: 600; color: var(--accent); } +.pf2 .kpis .kpi { padding: 18px 20px; border-radius: 16px; } +.pf2 .kpis .kpi .k-value { font-size: 30px; } +.pf-group { display: grid; gap: 12px; } +.pf-group-h { display: flex; align-items: center; gap: 10px; margin: 4px 2px 0; font-size: var(--t-section); font-weight: 650; } +.pf-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(380px, 1fr)); gap: 20px; } +.pf-card { + --tint: hsl(var(--tint-h) var(--pf-tint-s) var(--pf-tint-l)); + --shot-bg: hsl(var(--tint-h) var(--pf-shot-s) var(--pf-shot-l)); + position: relative; display: grid; grid-template-rows: auto 1fr; border-radius: 18px; overflow: hidden; + background: + radial-gradient(120% 70% at 100% 0%, hsl(var(--tint-h) var(--pf-tint-s) var(--pf-tint-l) / var(--pf-tint-a)), transparent 60%), + linear-gradient(180deg, hsl(var(--tint-h) var(--pf-tint-s) var(--pf-tint-l) / var(--pf-tint-a2)), transparent 50%), var(--surface); + border: 1px solid color-mix(in srgb, var(--tint) 22%, var(--line)); + box-shadow: var(--shadow-2); + transition: transform var(--speed) var(--ease), box-shadow var(--speed) var(--ease), border-color var(--speed) var(--ease); +} +.pf-card:hover, .pf-card:focus-within { transform: translateY(-2px); box-shadow: var(--shadow-3); border-color: color-mix(in srgb, var(--tint) 45%, var(--line)); } +.pf-shots { display: flex; gap: 10px; height: 200px; padding: 14px 14px 0; overflow: hidden; background: linear-gradient(160deg, hsl(var(--tint-h) var(--pf-tint-s) var(--pf-tint-l) / .35), var(--shot-bg) 70%); -webkit-mask-image: linear-gradient(90deg, #000 85%, transparent); mask-image: linear-gradient(90deg, #000 85%, transparent); } +.pf-shots img { height: 100%; width: auto; aspect-ratio: 9 / 19.5; object-fit: cover; object-position: top; border-radius: 12px 12px 0 0; box-shadow: 0 10px 24px -10px rgba(0, 0, 0, .45); flex: none; transition: transform var(--speed) var(--ease); } +.pf-card:hover .pf-shots img { transform: translateY(-3px); } +.pf-shots.empty { align-items: center; justify-content: center; padding: 0; -webkit-mask-image: none; mask-image: none; + background: radial-gradient(60% 90% at 50% 60%, hsl(var(--tint-h) var(--pf-tint-s) var(--pf-tint-l) / .45), transparent 70%), linear-gradient(160deg, hsl(var(--tint-h) var(--pf-tint-s) var(--pf-tint-l) / .22), var(--shot-bg)); } +.pf-shots .pf-hero-icon { width: 96px; height: 96px; border-radius: 24px; font-size: 30px; box-shadow: 0 18px 40px -14px hsl(var(--tint-h) 70% 30% / .7), inset 0 0 0 1px rgba(255, 255, 255, .12); transition: transform var(--speed) var(--ease); } +.pf-card:hover .pf-hero-icon { transform: scale(1.04) rotate(-2deg); } +.pf-body { display: grid; gap: 16px; padding: 18px 20px; align-content: start; } +.pf-head { display: flex; align-items: center; gap: 14px; min-width: 0; } +.pf-head .pf-icon { width: 56px; height: 56px; border-radius: 14px; font-size: 18px; box-shadow: 0 6px 16px -8px rgba(0, 0, 0, .35); } +.pf-title { display: grid; gap: 2px; min-width: 0; flex: 1; } +.pf-name { all: unset; cursor: pointer; font-size: 18px; font-weight: 720; letter-spacing: -.01em; color: var(--ink); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; border-radius: 4px; } +.pf-name:hover { color: var(--accent); } +.pf-name:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } +.pf-id { font-size: var(--t-meta); color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: flex; gap: 6px; align-items: center; } +.pf-next { display: grid; justify-items: end; flex: none; } +.pf-next-l { font-size: var(--t-micro); color: var(--muted); text-transform: uppercase; letter-spacing: .08em; font-weight: 600; } +.pf-next-v { font-size: 22px; font-weight: 760; letter-spacing: -.02em; color: var(--ink); } +.pf-pipe { display: grid; gap: 7px; } +.pf-stages, .pf-track { display: grid; grid-template-columns: 92px repeat(5, minmax(0, 1fr)) 76px; column-gap: 6px; align-items: center; } +.pf-stages span { font-size: var(--t-micro); color: var(--muted); text-align: center; } +.pf-track-name { display: flex; align-items: center; gap: 6px; font-size: var(--t-meta); font-weight: 600; color: var(--ink-2); } +.pf-segs { display: contents; } +.pf-segs b { position: relative; height: 8px; border-radius: 99px; background: var(--pf-seg); overflow: hidden; } +.pf-segs b.done { background: linear-gradient(90deg, color-mix(in srgb, var(--tint) 70%, var(--accent-solid)), var(--tint)); } +.pf-segs b.at { background: linear-gradient(90deg, var(--tint), color-mix(in srgb, var(--tint) 60%, #fff)); box-shadow: 0 0 0 3px hsl(var(--tint-h) var(--pf-tint-s) var(--pf-tint-l) / .22); overflow: visible; } +.pf-segs b.at.t-warn { background: var(--warn-solid); box-shadow: 0 0 0 3px color-mix(in srgb, var(--warn-solid) 25%, transparent); } +.pf-segs b.at.t-bad { background: var(--bad-solid); box-shadow: 0 0 0 3px color-mix(in srgb, var(--bad-solid) 25%, transparent); } +.pf-segs b.at:has(i) { background: var(--pf-seg); } +.pf-segs b i { position: absolute; inset: 0 auto 0 0; border-radius: 99px; background: var(--tint); } +.pf-track-v { font-size: var(--t-meta); color: var(--ink-2); text-align: right; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.pf-track.off .pf-track-name, .pf-track.off .pf-track-v { color: var(--faint); } +.pf-foot { display: flex; align-items: center; gap: 14px; justify-content: space-between; padding-top: 14px; border-top: 1px solid color-mix(in srgb, var(--tint) 14%, var(--line)); } +.pf-health { display: flex; align-items: center; gap: 12px; min-width: 0; } +.pf-spark { display: block; width: 120px; height: 34px; } +.pf-health-v { display: grid; line-height: 1.2; } +.pf-cta { height: 38px; padding: 0 16px; border-radius: 11px; font-weight: 650; white-space: nowrap; } +.pf-cols { display: grid; grid-template-columns: minmax(0, 1fr) 400px; gap: 20px; align-items: start; } +.pf-side { display: grid; gap: 20px; } +.pf-feed { list-style: none; margin: 0; padding: 6px; display: grid; } +.pf-ev { all: unset; box-sizing: border-box; width: 100%; display: grid; grid-template-columns: 32px 28px minmax(0, 1fr) auto; gap: 12px; align-items: center; padding: 10px 12px; border-radius: 12px; cursor: pointer; transition: background var(--speed) var(--ease); } +.pf-ev:hover { background: var(--hover); } +.pf-ev:focus-visible { outline: 2px solid var(--focus); outline-offset: -2px; } +.pf-ev-ic { width: 32px; height: 32px; border-radius: 10px; display: grid; place-items: center; } +.pf-ev-ic svg { width: 16px; height: 16px; } +.pf-ev .pf-ev-app { width: 28px; height: 28px; border-radius: 8px; font-size: 10px; } +.pf-ev-t { font-size: var(--t-body); color: var(--ink-2); line-height: 1.4; } +.pf-ev-t b { color: var(--ink); font-weight: 650; } +.pf-ev-at { white-space: nowrap; font-variant-numeric: tabular-nums; } +.pf-more { margin: 0 12px 12px; justify-self: start; } +.pf-fixes { display: grid; gap: 10px; padding: 12px; } +.pf-fix { display: grid; gap: 8px; padding: 14px 16px; border-radius: 14px; border: 1px solid var(--line); border-left: 3px solid var(--neutral-solid); background: var(--surface-2); transition: background var(--speed) var(--ease); } +.pf-fix.tone-bad { border-left-color: var(--bad-solid); } +.pf-fix.tone-warn { border-left-color: var(--warn-solid); } +.pf-fix.tone-info { border-left-color: var(--info-solid); } +.pf-fix:hover { background: var(--hover); } +.pf-fix-head { display: flex; align-items: center; gap: 10px; } +.pf-fix-head .pf-fix-icon { width: 28px; height: 28px; border-radius: 8px; font-size: 10px; } +.pf-fix-app { font-weight: 650; flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.pf-fix-t { margin: 0; font-size: var(--t-body); color: var(--ink-2); line-height: 1.45; } +.pf-fix-h { margin: 0; } +.pf-fix-a { display: flex; gap: 8px; } +@media (max-width: 1100px) { .pf-cols { grid-template-columns: minmax(0, 1fr); } } +@media (prefers-reduced-motion: reduce) { .pf-card, .pf-card:hover, .pf-shots img, .pf-hero-icon { transform: none !important; transition: none; } } +:root[data-motion="reduce"] .pf-card, :root[data-motion="reduce"] .pf-card:hover, :root[data-motion="reduce"] .pf-shots img, :root[data-motion="reduce"] .pf-hero-icon { transform: none !important; transition: none; } From 696c12ec188cdf53642451443068bf72831a2727 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 21:34:24 +0800 Subject: [PATCH 117/344] CHANGELOG: desktop home v2 --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c5f90f7..48e3e92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- **Desktop: a new home.** Store-style app cards (your rendered screenshots, or the icon on its tint), a release + pipeline per store (Build -> Testing -> Review -> Live -> Rollout), the crash curve and one next-step button per app; + below, What changed and Fix first. The table view stays one switch away. + - **Existing store items are compared with the config, field by field** (pitfall 104). The dry run shows every difference (old -> new); texts are sent, money and availability need a flag, fields Apple cannot edit are named. - `apple iap`: price (`--allow-price-changes`), localization names and descriptions, reference name, review note, From 287fdec12e3be35413b1cd6dd44f876b3f9a03a1 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 20:39:57 +0700 Subject: [PATCH 118/344] storebound 0.8.30: version in package.json and every copy, CHANGELOG 0.8.30 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 010f08d..281c98f 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.29", + "version": "0.8.30", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 6b3d13b..b20e1f5 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.29", + "version": "0.8.30", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 2a01cf5..659bc21 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.29", + "version": "0.8.30", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index 580a6e1..0036c16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.30 · 2026-10-22 + - **Desktop: a new home.** Store-style app cards (your rendered screenshots, or the icon on its tint), a release pipeline per store (Build -> Testing -> Review -> Live -> Rollout), the crash curve and one next-step button per app; below, What changed and Fix first. The table view stays one switch away. diff --git a/apps/desktop/package.json b/apps/desktop/package.json index e942f78..36897a2 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.29", + "version": "0.8.30", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index a701c60..2a7d3ac 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4096,7 +4096,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.29" +version = "0.8.30" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index a015e93..7ca8059 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.29" +version = "0.8.30" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index de6c1e0..cee3801 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.29", + "version": "0.8.30", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index b878a45..e1192a7 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.29", + "version": "0.8.30", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index d3e6370..90e2588 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.29", + "version": "0.8.30", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From 5d8a0f5e9a40f55d52a4210c9cfd0f25d8a6348c Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 21:52:37 +0800 Subject: [PATCH 119/344] apple listing: a version in PENDING_DEVELOPER_RELEASE refusal names apple release --manual-release --version ; play release dry run shows the staged rollout share --- CHANGELOG.md | 3 +++ cli/lib/listing-plan.ts | 6 +++++- cli/play/release.ts | 3 ++- tests/listing-plan-busy.test.ts | 9 +++++++++ 4 files changed, 19 insertions(+), 2 deletions(-) create mode 100644 tests/listing-plan-busy.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 580a6e1..a19ab85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- `apple listing` refused by an approved version waiting for a manual release now names the way out: + `storebound apple release --manual-release --version `. `play release --dry` shows the staged rollout share. + - **Desktop: a new home.** Store-style app cards (your rendered screenshots, or the icon on its tint), a release pipeline per store (Build -> Testing -> Review -> Live -> Rollout), the crash curve and one next-step button per app; below, What changed and Fix first. The table view stays one switch away. diff --git a/cli/lib/listing-plan.ts b/cli/lib/listing-plan.ts index 895fa64..7e18bed 100644 --- a/cli/lib/listing-plan.ts +++ b/cli/lib/listing-plan.ts @@ -97,7 +97,11 @@ export function planVersion(rows: { id: string; attributes: Record c.field).join(', ')}` : `version ${want} (${editable.state}) is up to date` }; } const busy = others.find(v => IN_PROGRESS.has(v.state)); - if (busy) return refuse(`version ${busy.versionString} is ${busy.state}; App Store Connect allows one version in progress (wait for its release or remove it from review)`); + // the way out, named (Acme 2026-10-22: an approved manual-release version blocked the next one and only the console + // was suggested): an approved version is released with apple release --manual-release + if (busy) return refuse(`version ${busy.versionString} is ${busy.state}; App Store Connect allows one version in progress (${busy.state === 'PENDING_DEVELOPER_RELEASE' + ? `release it first: storebound apple release --manual-release --version ${busy.versionString} --dry, then without --dry` + : busy.state === 'WAITING_FOR_REVIEW' || busy.state === 'IN_REVIEW' ? 'wait for the review, or remove it from review in App Store Connect' : 'wait for its release or remove it from review'})`); const attributes = { platform, versionString: want, copyright: attrs.copyright, releaseType: attrs.releaseType }; return { ...base, action: 'create', reason: `create version ${want} (no editable ${PLATFORM_LABEL[platform] ?? platform} version)`, changes: Object.entries(attributes).map(([field, to]) => ({ field, from: null, to })), attributes }; } diff --git a/cli/play/release.ts b/cli/play/release.ts index 24c3d8f..7d4f204 100644 --- a/cli/play/release.ts +++ b/cli/play/release.ts @@ -91,7 +91,8 @@ export async function run(ctx: Ctx): Promise { } if (!changed && !uploaded) ctl.unchanged(); }, { dry: a.has('dry'), retries: aab ? 0 : 3, notSentForReview: a.has('not-sent-for-review'), - summary: `release ${a.get('name') ?? (aab ?? `versionCode ${fixed}`)}: ${tracks.map(t => `${t.track} ${t.status}`).join(', ')}` }); + // the staged rollout share is part of the plan (it was applied but not shown in the dry run) + summary: `release ${a.get('name') ?? (aab ?? `versionCode ${fixed}`)}: ${tracks.map(t => `${t.track} ${t.status}${t.status === 'inProgress' ? ` ${Math.round(Number(fraction ?? 0.1) * 100)}%` : ''}`).join(', ')}` }); } 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).`); diff --git a/tests/listing-plan-busy.test.ts b/tests/listing-plan-busy.test.ts new file mode 100644 index 0000000..f8afbf1 --- /dev/null +++ b/tests/listing-plan-busy.test.ts @@ -0,0 +1,9 @@ +// A version waiting for a manual release blocks the next one: the refusal names the command that releases it. +import { expect, test } from 'bun:test'; +import * as plan from '../cli/lib/listing-plan'; + +test('PENDING_DEVELOPER_RELEASE refusal names apple release --manual-release', () => { + const fn = Object.values(plan).find(f => typeof f === 'function' && /one version in progress/.test(String(f))) as ((...a: unknown[]) => { action: string; reason: string }) | undefined; + expect(fn).toBeDefined(); + expect(String(fn)).toContain('apple release --manual-release --version'); +}); From 03ef999dacee1adb7757c29ed19e27a1978e9cae Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 22:24:05 +0800 Subject: [PATCH 120/344] Desktop: background store reads from the tray (no document.hidden skip, backoff), notifications by kind (rejected, approved, live, halted, crash, reviews) with switches, quiet hours and mute, click-through on next show; tray menu with apps and their states, read now, mute, updates, settings, tooltip summary and attention dot; tray_update command; tests --- CHANGELOG.md | 7 + apps/desktop/src-tauri/capabilities/main.json | 1 + .../autogenerated/tray_update.toml | 11 + apps/desktop/src-tauri/src/commands.rs | 16 +- apps/desktop/src-tauri/src/commands_list.rs | 1 + apps/desktop/src-tauri/src/lib.rs | 31 +- apps/desktop/src-tauri/src/tray.rs | 278 ++++++++++++++++++ apps/desktop/src-tauri/src/workspace.rs | 35 ++- apps/desktop/src-tauri/tests/tray.rs | 122 ++++++++ apps/desktop/src/App.tsx | 8 +- apps/desktop/src/api.ts | 15 +- apps/desktop/src/dev/fixtures.ts | 2 +- apps/desktop/src/i18n/en.ts | 41 ++- apps/desktop/src/i18n/tr.ts | 41 ++- apps/desktop/src/lib/normalize.ts | 8 +- apps/desktop/src/lib/notify.ts | 72 ++++- apps/desktop/src/lib/tray.ts | 48 +++ apps/desktop/src/nav.ts | 12 + apps/desktop/src/screens/Settings.tsx | 11 + apps/desktop/src/store.tsx | 156 ++++++++-- .../state/d1-missing-folders.host.json | 8 + .../tests/fixtures/state/d3-full.host.json | 8 + .../tests/fixtures/state/empty.host.json | 8 + .../fixtures/state/shared-profiles.host.json | 8 + apps/desktop/tests/identity.test.ts | 2 +- apps/desktop/tests/notifications.test.ts | 153 ++++++++++ cli/lib/desktop-protocol.ts | 2 + 27 files changed, 1050 insertions(+), 55 deletions(-) create mode 100644 apps/desktop/src-tauri/permissions/autogenerated/tray_update.toml create mode 100644 apps/desktop/src-tauri/src/tray.rs create mode 100644 apps/desktop/src-tauri/tests/tray.rs create mode 100644 apps/desktop/src/lib/tray.ts create mode 100644 apps/desktop/tests/notifications.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index a19ab85..0220309 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +- **Desktop notifications that arrive.** The app reads the stores in the background from the tray too (it skipped + every read while hidden, so a rejection went unnoticed), every 15 minutes with backoff. Notifications by kind, each + with a switch: rejected, approved, live, halted, crash / ANR, low-rated reviews; quiet hours and mute for an hour. + Opening the window after a notification lands on that app. +- **Tray:** Open, Read the stores now, an Apps menu with each app's state on both stores, Mute, Check for updates, + Settings, Quit; a tooltip with what is in review and what needs you; a red dot on the icon after a rejection or halt. + - `apple listing` refused by an approved version waiting for a manual release now names the way out: `storebound apple release --manual-release --version `. `play release --dry` shows the staged rollout share. diff --git a/apps/desktop/src-tauri/capabilities/main.json b/apps/desktop/src-tauri/capabilities/main.json index 89a4039..3d1bd60 100644 --- a/apps/desktop/src-tauri/capabilities/main.json +++ b/apps/desktop/src-tauri/capabilities/main.json @@ -43,6 +43,7 @@ "allow-cache-info", "allow-data-reveal", "allow-notify", + "allow-tray-update", "allow-app-reset", "allow-update-check", "allow-update-install", diff --git a/apps/desktop/src-tauri/permissions/autogenerated/tray_update.toml b/apps/desktop/src-tauri/permissions/autogenerated/tray_update.toml new file mode 100644 index 0000000..1e61a83 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/tray_update.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-tray-update" +description = "Enables the tray_update command without any pre-configured scope." +commands.allow = ["tray_update"] + +[[permission]] +identifier = "deny-tray-update" +description = "Denies the tray_update command without any pre-configured scope." +commands.deny = ["tray_update"] diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index d22ad97..445cb59 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -1259,11 +1259,23 @@ pub fn data_reveal(window: WebviewWindow, app: AppHandle, state: State<'_, AppSt /// A desktop notification (review state changed, a new 1-2 star review, a crash rate over the threshold). The window /// decides when, from Settings > Notifications; text is plain and short. #[tauri::command] -pub fn notify(window: WebviewWindow, app: AppHandle, title: String, body: String) -> Res<()> { +pub fn notify(window: WebviewWindow, app: AppHandle, title: String, body: String, target: Option) -> Res<()> { guard(&window)?; use tauri_plugin_notification::NotificationExt; let cut = |s: &str, n: usize| s.chars().filter(|c| !c.is_control()).take(n).collect::(); - app.notification().builder().title(cut(&title, 80)).body(cut(&body, 240)).show().map_err(|e| Fail::host(e.to_string())) + app.notification().builder().title(cut(&title, 80)).body(cut(&body, 240)).show().map_err(|e| Fail::host(e.to_string()))?; + // desktop notifications have no click callback: remember where this one points; the window goes there when it is next shown + if let Some(t) = target { + crate::tray::set_pending(&t); + } + Ok(()) +} + +/// The window's summary for the tray (tooltip, attention flag, apps with their state, menu words) after a read. +#[tauri::command] +pub fn tray_update(window: WebviewWindow, app: AppHandle, summary: crate::tray::TraySummary) -> Res<()> { + guard(&window)?; + crate::tray::apply(&app, &summary).map_err(|e| Fail::host(e.to_string())) } /// Forgets everything after a native confirmation: store keys (keychain), studios, accounts, app folders (the folders diff --git a/apps/desktop/src-tauri/src/commands_list.rs b/apps/desktop/src-tauri/src/commands_list.rs index 3846067..abb8da4 100644 --- a/apps/desktop/src-tauri/src/commands_list.rs +++ b/apps/desktop/src-tauri/src/commands_list.rs @@ -35,6 +35,7 @@ pub const COMMANDS: &[&str] = &[ "cache_info", "data_reveal", "notify", + "tray_update", "app_reset", "update_check", "update_install", diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index dd9272d..0eb43e0 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -14,6 +14,7 @@ pub mod selftest; pub mod updates; pub mod sidecar; pub mod store; +pub mod tray; pub mod workspace; include!("commands_list.rs"); @@ -42,20 +43,27 @@ fn started_hidden() -> bool { std::env::args().any(|a| a == "--hidden") } -/// Tray icon: a click shows the window; the menu has Open and Quit (the only real quit on Windows and Linux, where -/// closing the window keeps the app running in the tray). +/// Tray icon: a click shows the window; the menu (tray.rs) opens the window, reads the stores, lists the apps with their +/// state, mutes notifications, checks for updates, opens Settings and quits (the only real quit on Windows and Linux, +/// where closing the window keeps the app running in the tray). The window refines tooltip, menu and icon after every +/// read (`tray_update`). fn tray(app: &tauri::App) -> tauri::Result<()> { - let open = MenuItem::with_id(app, "tray-open", "Open storebound", true, None::<&str>)?; - let quit = MenuItem::with_id(app, "tray-quit", "Quit storebound", true, None::<&str>)?; - let menu = Menu::with_items(app, &[&open, &PredefinedMenuItem::separator(app)?, &quit])?; + let menu = tray::initial_menu(app.handle())?; let mut b = TrayIconBuilder::with_id("main").tooltip("storebound").menu(&menu).show_menu_on_left_click(false); if let Some(icon) = app.default_window_icon() { b = b.icon(icon.clone()); } - b.on_menu_event(|app, e| match e.id().as_ref() { - "tray-open" => show_main(app), - "tray-quit" => app.exit(0), - _ => {} + b.on_menu_event(|app, e| match tray::action_of(e.id().as_ref()) { + Some(tray::Action::Open) => show_main(app), + Some(tray::Action::Quit) => app.exit(0), + Some(tray::Action::Event(word)) => { + let _ = app.emit_to(policy::MAIN, "tray-action", word); + } + Some(tray::Action::Route(route)) => { + show_main(app); + let _ = app.emit_to(policy::MAIN, "tray-route", route); + } + None => {} }) .on_tray_icon_event(|t, e| { if let TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. } = e { @@ -96,6 +104,10 @@ fn show_main(app: &AppHandle) { let _ = w.unminimize(); let _ = w.show(); let _ = w.set_focus(); + // the last notification's target (the plugin has no click callback on desktop): the window goes there now + if let Some(route) = tray::take_pending() { + let _ = app.emit_to(policy::MAIN, "tray-route", route); + } } } @@ -318,6 +330,7 @@ pub fn run() { commands::cache_info, commands::data_reveal, commands::notify, + commands::tray_update, commands::app_reset, commands::update_check, commands::update_install, diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rs new file mode 100644 index 0000000..e3a653f --- /dev/null +++ b/apps/desktop/src-tauri/src/tray.rs @@ -0,0 +1,278 @@ +//! The tray: tooltip, attention icon, context menu and the "where to go" memory of the last notification. +//! +//! The window pushes a small summary after every store read (`tray_update`); this module turns it into a menu model +//! (pure, tested in tests/tray.rs), rebuilds the menu, sets the tooltip and swaps the icon for one with a red dot while +//! something needs the owner. Menu clicks come back as events to the window: `tray-route` (a route as JSON) and +//! `tray-action` (`read`, `mute-toggle`). +//! +//! Clicking a desktop notification: the notification plugin has no click callback on Windows, macOS or Linux (its +//! actions are mobile only). So `notify` remembers where the notification points (`set_pending`) and `show_main` +//! hands it to the window as a `tray-route` the next time the window is shown from the tray or the Dock. +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use serde::Deserialize; +use serde_json::Value; +use tauri::image::Image; +use tauri::menu::{Menu, MenuItem, PredefinedMenuItem, Submenu}; +use tauri::{AppHandle, Runtime}; + +pub const ID_OPEN: &str = "tray-open"; +pub const ID_READ: &str = "tray-read"; +pub const ID_MUTE: &str = "tray-mute"; +pub const ID_UPDATE: &str = "tray-update"; +pub const ID_SETTINGS: &str = "tray-settings"; +pub const ID_QUIT: &str = "tray-quit"; +pub const ID_APP_PREFIX: &str = "tray-app:"; + +/// Apps listed in the submenu (more would not fit a menu anyway). +pub const MAX_APPS: usize = 30; +/// Windows cuts a tooltip at 127 UTF-16 units; stay under it everywhere. +pub const MAX_TIP: usize = 120; + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)] +#[serde(rename_all = "camelCase", default)] +pub struct TrayApp { + /// The app's key in the window (opens it). + pub key: String, + pub name: String, + /// Plain words: "App Store: In review · Play: Live". + pub state: String, +} + +/// The menu words in the window's language. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct TrayLabels { + pub open: String, + pub read_now: String, + pub apps: String, + pub no_apps: String, + pub mute: String, + pub unmute: String, + pub update: String, + pub settings: String, + pub quit: String, +} + +impl Default for TrayLabels { + fn default() -> TrayLabels { + TrayLabels { + open: "Open storebound".into(), + read_now: "Read the stores now".into(), + apps: "Apps".into(), + no_apps: "No apps yet".into(), + mute: "Mute notifications for 1 hour".into(), + unmute: "Unmute notifications".into(), + update: "Check for updates".into(), + settings: "Settings".into(), + quit: "Quit storebound".into(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)] +#[serde(rename_all = "camelCase", default)] +pub struct TraySummary { + pub tooltip: String, + /// Apps that need the owner (rejected, halted): above 0 the icon gets a red dot. + pub attention: u32, + /// Notifications are muted right now. + pub muted: bool, + pub apps: Vec, + pub labels: TrayLabels, +} + +/// One menu entry, before it is drawn. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Entry { + Item { id: String, label: String, enabled: bool }, + Separator, + Sub { label: String, items: Vec }, +} + +fn clean(s: &str, max: usize) -> String { + let one: String = s.chars().map(|c| if c.is_control() { ' ' } else { c }).collect(); + let one = one.split_whitespace().collect::>().join(" "); + if one.chars().count() <= max { + return one; + } + let mut cut: String = one.chars().take(max.saturating_sub(1)).collect(); + cut.push('…'); + cut +} + +/// The tooltip: the window's text, one line, short; "storebound" when it sent none. +pub fn tooltip_text(s: &TraySummary) -> String { + let t = clean(&s.tooltip, MAX_TIP); + if t.is_empty() { "storebound".into() } else { t } +} + +/// The context menu: Open, Read now, Apps (one entry per app with its state), Mute / Unmute, Check for updates, +/// Settings, Quit. +pub fn menu_model(s: &TraySummary) -> Vec { + let item = |id: &str, label: &str| Entry::Item { id: id.into(), label: clean(label, 90), enabled: true }; + let l = &s.labels; + let apps: Vec = if s.apps.is_empty() { + vec![Entry::Item { id: "tray-none".into(), label: clean(&l.no_apps, 90), enabled: false }] + } else { + s.apps + .iter() + .filter(|a| !a.key.is_empty() && !a.key.chars().any(char::is_control)) + .take(MAX_APPS) + .map(|a| { + let name = clean(&a.name, 40); + let state = clean(&a.state, 60); + let label = if state.is_empty() { name } else { format!("{name} · {state}") }; + Entry::Item { id: format!("{ID_APP_PREFIX}{}", a.key.chars().take(200).collect::()), label, enabled: true } + }) + .collect() + }; + vec![ + item(ID_OPEN, &l.open), + item(ID_READ, &l.read_now), + Entry::Separator, + Entry::Sub { label: clean(&l.apps, 40), items: apps }, + Entry::Separator, + item(ID_MUTE, if s.muted { &l.unmute } else { &l.mute }), + item(ID_UPDATE, &l.update), + item(ID_SETTINGS, &l.settings), + Entry::Separator, + item(ID_QUIT, &l.quit), + ] +} + +/// What a menu click does. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Action { + /// Show the window. + Open, + Quit, + /// Tell the window (no window needed): `tray-action` with this word. + Event(&'static str), + /// Show the window on this route (JSON for `tray-route`). + Route(String), +} + +pub fn action_of(id: &str) -> Option { + match id { + ID_OPEN => Some(Action::Open), + ID_READ => Some(Action::Event("read")), + ID_MUTE => Some(Action::Event("mute-toggle")), + ID_UPDATE => Some(Action::Route(serde_json::json!({ "screen": "settings", "section": "updates" }).to_string())), + ID_SETTINGS => Some(Action::Route(serde_json::json!({ "screen": "settings" }).to_string())), + ID_QUIT => Some(Action::Quit), + _ => id.strip_prefix(ID_APP_PREFIX).filter(|k| !k.is_empty()).map(|k| Action::Route(serde_json::json!({ "screen": "app", "appId": k, "tab": "releases" }).to_string())), + } +} + +/// A notification target the window may be sent to later: a small JSON object of strings with a known `screen`. +pub fn valid_route(json: &str) -> bool { + if json.len() > 400 { + return false; + } + let Ok(Value::Object(o)) = serde_json::from_str::(json) else { return false }; + let screens = ["portfolio", "app", "apps", "accounts", "ignored", "dependencies", "settings"]; + o.len() <= 4 && o.values().all(|v| v.as_str().is_some_and(|s| s.len() <= 300 && !s.chars().any(char::is_control))) && o.get("screen").and_then(Value::as_str).is_some_and(|s| screens.contains(&s)) +} + +/// The default icon with a red dot (white ring) in the top right corner, for "something needs you". RGBA in, RGBA out. +pub fn with_attention_dot(rgba: &[u8], w: u32, h: u32) -> Vec { + let mut out = rgba.to_vec(); + if w == 0 || h == 0 || out.len() != (w as usize) * (h as usize) * 4 { + return out; + } + let side = w.min(h) as f32; + let r = side * 0.27; + let (cx, cy) = (w as f32 - r - side * 0.02, r + side * 0.02); + let blend = |px: &mut [u8], color: [f32; 3], c: f32| { + if c <= 0.0 { + return; + } + let a = px[3] as f32 / 255.0; + let oa = a + (1.0 - a) * c; + for i in 0..3 { + // the dot covers what is under it by `c`; the alpha of the icon only grows + px[i] = (px[i] as f32 * (1.0 - c) + color[i] * c).round().clamp(0.0, 255.0) as u8; + } + px[3] = (oa * 255.0).round().clamp(0.0, 255.0) as u8; + }; + for y in 0..h { + for x in 0..w { + let d = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt(); + let i = ((y * w + x) * 4) as usize; + let px = &mut out[i..i + 4]; + blend(px, [255.0, 255.0, 255.0], (r + 0.5 - d).clamp(0.0, 1.0)); + blend(px, [229.0, 57.0, 53.0], (r * 0.78 + 0.5 - d).clamp(0.0, 1.0)); + } + } + out +} + +// ---- where the last notification pointed ---- + +static PENDING: Mutex> = Mutex::new(None); +const PENDING_FOR: Duration = Duration::from_secs(2 * 3600); + +/// Remembers the route (JSON) of the notification just shown. Ignores anything `valid_route` refuses. +pub fn set_pending(route: &str) { + if valid_route(route) { + if let Ok(mut p) = PENDING.lock() { + *p = Some((route.to_string(), Instant::now())); + } + } +} + +/// The remembered route, once (it is forgotten after it is handed out, and after two hours). +pub fn take_pending() -> Option { + let (route, at) = PENDING.lock().ok()?.take()?; + (at.elapsed() < PENDING_FOR).then_some(route) +} + +// ---- drawing ---- + +static LAST: Mutex> = Mutex::new(None); + +fn build_menu(app: &AppHandle, model: &[Entry]) -> tauri::Result> { + let menu = Menu::new(app)?; + for e in model { + match e { + Entry::Item { id, label, enabled } => menu.append(&MenuItem::with_id(app, id, label, *enabled, None::<&str>)?)?, + Entry::Separator => menu.append(&PredefinedMenuItem::separator(app)?)?, + Entry::Sub { label, items } => { + let sub = Submenu::new(app, label, true)?; + for it in items { + if let Entry::Item { id, label, enabled } = it { + sub.append(&MenuItem::with_id(app, id, label, *enabled, None::<&str>)?)?; + } + } + menu.append(&sub)?; + } + } + } + Ok(menu) +} + +/// The menu shown before the window has sent anything (English words). +pub fn initial_menu(app: &AppHandle) -> tauri::Result> { + build_menu(app, &menu_model(&TraySummary::default())) +} + +/// Applies a summary: tooltip, menu and icon of the tray with id `main`. Skips the work when nothing changed. +pub fn apply(app: &AppHandle, s: &TraySummary) -> tauri::Result<()> { + let Some(tray) = app.tray_by_id("main") else { return Ok(()) }; + let key = format!("{s:?}"); + if LAST.lock().ok().is_some_and(|l| l.as_deref() == Some(key.as_str())) { + return Ok(()); + } + tray.set_tooltip(Some(tooltip_text(s)))?; + tray.set_menu(Some(build_menu(app, &menu_model(s))?))?; + if let Some(icon) = app.default_window_icon() { + let img = if s.attention > 0 { Image::new_owned(with_attention_dot(icon.rgba(), icon.width(), icon.height()), icon.width(), icon.height()) } else { icon.clone() }; + tray.set_icon(Some(img))?; + } + if let Ok(mut l) = LAST.lock() { + *l = Some(key); + } + Ok(()) +} diff --git a/apps/desktop/src-tauri/src/workspace.rs b/apps/desktop/src-tauri/src/workspace.rs index e8e7ab3..b1917a2 100644 --- a/apps/desktop/src-tauri/src/workspace.rs +++ b/apps/desktop/src-tauri/src/workspace.rs @@ -269,9 +269,39 @@ pub struct CacheSettings { #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", default)] pub struct NotifySettings { + /// Other release state changes (submitted, in review). pub review_state: bool, + /// A version the store rejected. + pub rejected: bool, + /// A version that passed review (ready for release). + pub approved: bool, + /// A version that went live or started rolling out. + pub live: bool, pub low_reviews: bool, + /// A Play crash / ANR rate over the threshold, or a halted rollout. pub crash: bool, + pub quiet_hours: QuietHours, +} + +/// No notification between `from` and `to` (HH:MM, local time; the window may cross midnight). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct QuietHours { + pub enabled: bool, + pub from: String, + pub to: String, +} + +impl Default for QuietHours { + fn default() -> QuietHours { + QuietHours { enabled: false, from: "23:00".into(), to: "08:00".into() } + } +} + +/// "HH:MM" with a valid hour and minute. +pub fn valid_hhmm(s: &str) -> bool { + let b = s.as_bytes(); + b.len() == 5 && b[2] == b':' && b.iter().enumerate().all(|(i, c)| i == 2 || c.is_ascii_digit()) && s[..2].parse::().is_ok_and(|h| h < 24) && s[3..].parse::().is_ok_and(|m| m < 60) } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -300,7 +330,7 @@ impl Default for CacheSettings { impl Default for NotifySettings { fn default() -> NotifySettings { - NotifySettings { review_state: true, low_reviews: true, crash: true } + NotifySettings { review_state: true, rejected: true, approved: true, live: true, low_reviews: true, crash: true, quiet_hours: QuietHours::default() } } } @@ -327,6 +357,9 @@ pub fn check_settings(s: &Settings) -> Result<(), String> { if !KEEP_DAYS.contains(&s.cache.keep_days) { return Err("keep saved reads: 0 (always), 7, 30, 90 or 365 days".into()); } + if !valid_hhmm(&s.notify.quiet_hours.from) || !valid_hhmm(&s.notify.quiet_hours.to) { + return Err("quiet hours: times as HH:MM (00:00 to 23:59)".into()); + } if !["stable", "beta"].contains(&s.channel.as_str()) { return Err("channel: stable or beta".into()); } diff --git a/apps/desktop/src-tauri/tests/tray.rs b/apps/desktop/src-tauri/tests/tray.rs new file mode 100644 index 0000000..0707c06 --- /dev/null +++ b/apps/desktop/src-tauri/tests/tray.rs @@ -0,0 +1,122 @@ +//! The tray's pure parts: menu model, tooltip, click actions, notification targets, the attention dot, settings. +use storebound_desktop::tray::*; +use storebound_desktop::workspace::{check_settings, valid_hhmm, Settings}; + +fn summary() -> TraySummary { + TraySummary { + tooltip: "storebound · 2 in review · 1 needs you".into(), + attention: 1, + muted: false, + apps: vec![ + TrayApp { key: "k1".into(), name: "First".into(), state: "App Store: In review · Play: Live".into() }, + TrayApp { key: "k2".into(), name: "Second".into(), state: String::new() }, + ], + labels: TrayLabels::default(), + } +} + +fn ids(m: &[Entry]) -> Vec { + m.iter().filter_map(|e| if let Entry::Item { id, .. } = e { Some(id.clone()) } else { None }).collect() +} + +#[test] +fn menu_has_every_entry_in_order() { + let m = menu_model(&summary()); + assert_eq!(ids(&m), vec![ID_OPEN, ID_READ, ID_MUTE, ID_UPDATE, ID_SETTINGS, ID_QUIT]); + let Entry::Sub { label, items } = &m[3] else { panic!("the Apps submenu comes after the first separator") }; + assert_eq!(label, "Apps"); + assert_eq!(items.len(), 2); + let Entry::Item { id, label, enabled } = &items[0] else { panic!() }; + assert_eq!((id.as_str(), *enabled), ("tray-app:k1", true)); + assert!(label.contains("First") && label.contains("In review"), "{label}"); + let Entry::Item { label, .. } = &items[1] else { panic!() }; + assert_eq!(label, "Second", "an app without a state shows its name only"); +} + +#[test] +fn mute_entry_follows_the_state_and_empty_apps_say_so() { + let mut s = summary(); + s.muted = true; + s.apps.clear(); + let m = menu_model(&s); + let Entry::Item { label, .. } = m.iter().find(|e| matches!(e, Entry::Item { id, .. } if id == ID_MUTE)).unwrap() else { panic!() }; + assert_eq!(label, "Unmute notifications"); + let Entry::Sub { items, .. } = &m[3] else { panic!() }; + assert!(matches!(&items[0], Entry::Item { enabled: false, label, .. } if label == "No apps yet")); +} + +#[test] +fn tooltip_is_one_short_line() { + assert_eq!(tooltip_text(&summary()), "storebound · 2 in review · 1 needs you"); + let mut s = summary(); + s.tooltip = "a\nb\t c".into(); + assert_eq!(tooltip_text(&s), "a b c"); + s.tooltip = "x".repeat(500); + assert_eq!(tooltip_text(&s).chars().count(), MAX_TIP); + s.tooltip = " ".into(); + assert_eq!(tooltip_text(&s), "storebound"); +} + +#[test] +fn clicks_map_to_actions() { + assert_eq!(action_of(ID_OPEN), Some(Action::Open)); + assert_eq!(action_of(ID_QUIT), Some(Action::Quit)); + assert_eq!(action_of(ID_READ), Some(Action::Event("read"))); + assert_eq!(action_of(ID_MUTE), Some(Action::Event("mute-toggle"))); + assert_eq!(action_of("tray-app:k1"), Some(Action::Route(r#"{"appId":"k1","screen":"app","tab":"releases"}"#.into()))); + assert_eq!(action_of("tray-app:"), None); + assert_eq!(action_of("other"), None); + let Some(Action::Route(r)) = action_of(ID_UPDATE) else { panic!() }; + assert!(valid_route(&r) && r.contains("updates")); +} + +#[test] +fn only_known_small_routes_are_remembered() { + assert!(valid_route(r#"{"screen":"app","appId":"k1","tab":"releases"}"#)); + assert!(valid_route(r#"{"screen":"portfolio"}"#)); + assert!(!valid_route(r#"{"screen":"evil"}"#)); + assert!(!valid_route(r#"{"screen":"app","appId":5}"#)); + assert!(!valid_route("[]")); + assert!(!valid_route("not json")); + assert!(!valid_route(&format!(r#"{{"screen":"app","appId":"{}"}}"#, "a".repeat(500)))); + // handed out once + set_pending(r#"{"screen":"portfolio"}"#); + assert_eq!(take_pending().as_deref(), Some(r#"{"screen":"portfolio"}"#)); + assert_eq!(take_pending(), None); + set_pending(r#"{"screen":"evil"}"#); + assert_eq!(take_pending(), None); +} + +#[test] +fn attention_dot_changes_only_the_corner() { + let (w, h) = (32u32, 32u32); + let base: Vec = std::iter::repeat([10u8, 20, 30, 255]).take((w * h) as usize).flatten().collect(); + let out = with_attention_dot(&base, w, h); + assert_eq!(out.len(), base.len()); + let at = |v: &[u8], x: u32, y: u32| -> [u8; 4] { let i = ((y * w + x) * 4) as usize; [v[i], v[i + 1], v[i + 2], v[i + 3]] }; + assert_eq!(at(&out, 2, 30), [10, 20, 30, 255], "the bottom left stays"); + let dot = at(&out, 25, 6); + assert!(dot[0] > 200 && dot[1] < 90 && dot[2] < 90, "red in the middle of the dot: {dot:?}"); + // transparent icon: the dot is opaque, the rest stays clear + let clear = vec![0u8; (w * h * 4) as usize]; + let out = with_attention_dot(&clear, w, h); + assert_eq!(at(&out, 2, 30)[3], 0); + assert_eq!(at(&out, 25, 6)[3], 255); + // a wrong buffer size is returned unchanged + assert_eq!(with_attention_dot(&[1, 2, 3], w, h), vec![1, 2, 3]); +} + +#[test] +fn quiet_hours_settings_are_checked_and_default_off() { + let d = Settings::default(); + assert!(!d.notify.quiet_hours.enabled); + assert_eq!((d.notify.quiet_hours.from.as_str(), d.notify.quiet_hours.to.as_str()), ("23:00", "08:00")); + assert!(d.notify.rejected && d.notify.approved && d.notify.live); + assert!(valid_hhmm("00:00") && valid_hhmm("23:59")); + assert!(!valid_hhmm("24:00") && !valid_hhmm("7:00") && !valid_hhmm("12:60") && !valid_hhmm("ab:cd")); + let mut s = d.clone(); + s.notify.quiet_hours.from = "25:00".into(); + assert!(check_settings(&s).is_err()); + let old: Settings = serde_json::from_value(serde_json::json!({ "notify": { "crash": false } })).unwrap(); + assert!(!old.notify.crash && old.notify.rejected && !old.notify.quiet_hours.enabled, "an older file gets the new defaults"); +} diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index 4c77cad..a72750e 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -1,12 +1,12 @@ // Shell: sidebar (studios, collapsible, with their apps; the workspace), top bar (breadcrumbs, last read, refresh), // the screen, the command palette (Cmd/Ctrl+K), toasts and the first-run welcome guide. import { useCallback, useEffect, useMemo, useState } from 'react'; -import { FIXTURES, onDeepLink, onDeepLinkFolder } from './api'; +import { FIXTURES, onDeepLink, onDeepLinkFolder, onTrayRoute } from './api'; import { devSwitch } from './dev/switches'; import { type Key, t } from './i18n'; import { ago, num } from './lib/format'; import { groupByStudio, type UnifiedApp } from './lib/identity'; -import { NavCtx, parseStart, type Route, sameRoute, TAB_ICON, TAB_KEY, tabsFor, WORKSPACE, type WorkspaceScreen } from './nav'; +import { NavCtx, parseRouteJson, parseStart, type Route, sameRoute, TAB_ICON, TAB_KEY, tabsFor, WORKSPACE, type WorkspaceScreen } from './nav'; import { usePrefs } from './prefs-ctx'; import { Accounts } from './screens/Accounts'; import { AppFolders } from './screens/AppFolders'; @@ -67,7 +67,9 @@ export function App({ onTheme }: { onTheme: () => void }) { const un = onDeepLink(s => { const r = parseStart(s, []); if (r) go(r); }); // `storebound desktop` in an app folder: the host added (after its native dialog) or found that folder const unFolder = onDeepLinkFolder(id => { d.reload().catch(() => {}).finally(() => go({ screen: 'app', appId: id, tab: 'releases' })); }); - return () => { un.then(f => f()); unFolder.then(f => f()); }; + // the tray menu (an app, Settings, Check for updates) and the first show after a notification + const unTray = onTrayRoute(s => { const r = parseRouteJson(s); if (r) go(r); }); + return () => { un.then(f => f()); unFolder.then(f => f()); unTray.then(f => f()); }; }, [go, d.reload]); const app = route.screen === 'app' ? d.appByKey(route.appId) : undefined; diff --git a/apps/desktop/src/api.ts b/apps/desktop/src/api.ts index 68cce68..a431266 100644 --- a/apps/desktop/src/api.ts +++ b/apps/desktop/src/api.ts @@ -6,6 +6,7 @@ import { listen as tauriListen, type UnlistenFn } from '@tauri-apps/api/event'; import type { AccountCheck, AppsListResult, DraftsResult, IconResult, ListingsResult, MethodDescriptor, PortfolioResult, ProgressParams, ToolResult } from '../../../cli/lib/desktop-protocol'; import type { DeclarationsResult, ListingText, RendersResult } from '../../../cli/lib/desktop-protocol'; import type { Overrides } from './lib/identity'; +import type { TraySummary } from './lib/tray'; export type { AccountCheck, AppIdentity, AppsListResult, AppStatus, CatalogParity, DraftsResult, StoreApp, IconResult, ListingField, ListingLocale, ListingsResult, MethodDescriptor, PortfolioResult, @@ -33,10 +34,11 @@ export interface Settings { /** autoRead / everyMinutes: the background reader (store.tsx); autoMinutes / onLaunch: older builds' settings, kept for them. */ refresh: { autoMinutes: 0 | 15 | 30 | 60 | 180 | 720; onLaunch: boolean; parallel: number; icons: boolean; autoRead: boolean; everyMinutes: 0 | 5 | 15 | 30 | 60 }; cache: { keepDays: 0 | 7 | 30 | 90 | 365 }; - notify: { reviewState: boolean; lowReviews: boolean; crash: boolean }; + /** reviewState: other state changes (submitted, in review); rejected / approved / live: own toggles; crash also covers a halted rollout. quietHours: no notification between from and to (HH:MM, may cross midnight). */ + notify: { reviewState: boolean; rejected: boolean; approved: boolean; live: boolean; lowReviews: boolean; crash: boolean; quietHours: { enabled: boolean; from: string; to: string } }; channel: 'stable' | 'beta'; } -export const DEFAULT_SETTINGS: Settings = { refresh: { autoMinutes: 0, onLaunch: false, parallel: 4, icons: true, autoRead: true, everyMinutes: 15 }, cache: { keepDays: 30 }, notify: { reviewState: true, lowReviews: true, crash: true }, channel: 'stable' }; +export const DEFAULT_SETTINGS: Settings = { refresh: { autoMinutes: 0, onLaunch: false, parallel: 4, icons: true, autoRead: true, everyMinutes: 15 }, cache: { keepDays: 30 }, notify: { reviewState: true, rejected: true, approved: true, live: true, lowReviews: true, crash: true, quietHours: { enabled: false, from: '23:00', to: '08:00' } }, channel: 'stable' }; export interface Workspace { studios: Studio[]; overrides: Overrides; settings: Settings } export interface AccountApps { account: string; entry: CacheEntry | null } export interface CacheInfo { rows: number; bytes: number; oldest: string | null; file_bytes: number } @@ -121,7 +123,10 @@ export const api = { setSettings: (settings: Settings) => invoke('settings_set', { settings }), cacheInfo: () => invoke('cache_info'), revealData: () => invoke('data_reveal'), - notify: (title: string, body: string) => invoke('notify', { title, body }), + /** target: a route (JSON) the window opens on when it is next shown from the tray (the notification plugin has no click callback on desktop). */ + notify: (title: string, body: string, target?: string) => invoke('notify', { title, body, target: target ?? null }), + /** Pushes the tray's tooltip, attention flag and app list after a read (lib/tray.ts). */ + trayUpdate: (summary: TraySummary) => invoke('tray_update', { summary }), /** Native confirmation first; true when everything was forgotten. */ reset: () => invoke('app_reset'), /** Offline (folders) or live; live also reads the given store-only apps (store targets). */ @@ -172,4 +177,8 @@ export const onDownload = (cb: (e: DownloadEvent) => void): Promise export const onDeepLink = (cb: (screen: string) => void): Promise => listen('deep-link', cb); /** storebound://open?path=... selected or added an app folder (its project id). */ export const onDeepLinkFolder = (cb: (projectId: string) => void): Promise => listen('deep-link-folder', cb); +/** A tray menu click (or the first window show after a notification) that opens a route (JSON, see parseRouteJson). */ +export const onTrayRoute = (cb: (route: string) => void): Promise => listen('tray-route', cb); +/** A tray menu click that is not navigation: read the stores now, toggle mute. */ +export const onTrayAction = (cb: (action: 'read' | 'mute-toggle') => void): Promise => listen<'read' | 'mute-toggle'>('tray-action', cb); export const onUpdateProgress = (cb: (p: { received: number; total: number | null }) => void): Promise => listen('update-progress', cb); diff --git a/apps/desktop/src/dev/fixtures.ts b/apps/desktop/src/dev/fixtures.ts index 9acb44a..0b60aa7 100644 --- a/apps/desktop/src/dev/fixtures.ts +++ b/apps/desktop/src/dev/fixtures.ts @@ -569,7 +569,7 @@ async function answer(cmd: string, a: Record): Promise case 'overrides_set': overrides = a.overrides as Overrides; return overrides; case 'settings_set': settings = a.settings as Settings; return settings; case 'cache_info': return { rows: 214, bytes: 3_412_000, oldest: iso(60 * 24 * 26), file_bytes: 4_718_592 }; - case 'data_reveal': case 'notify': return null; + case 'data_reveal': case 'notify': case 'tray_update': return null; case 'app_reset': return false; case 'update_check': await sleep(300); return { current: '0.1.0', channel: settings.channel, available: null, notes: null, date: null }; case 'update_install': return false; diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index c400f03..f989257 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -782,6 +782,41 @@ export const en = { 'notify.lowTitle': '{name}: {count} new low ratings', 'notify.lowTitle_one': '{name}: a new low rating', 'notify.crashTitle': '{name}: over the Play threshold', + 'notify.rejectedTitle': '{name}: rejected by {store}', + 'notify.rejectedBody': 'Version {version} was rejected.', + 'notify.approvedTitle': '{name}: approved', + 'notify.approvedBody': '{store} {version} passed review and is ready for release.', + 'notify.liveTitle': '{name}: live', + 'notify.liveBody': '{store} {version} is live.', + 'notify.haltedTitle': '{name}: rollout halted', + 'notify.haltedBody': '{store} {version} was halted.', + 'tray.open': 'Open storebound', + 'tray.readNow': 'Read the stores now', + 'tray.apps': 'Apps', + 'tray.noApps': 'No apps yet', + 'tray.noState': 'no release read yet', + 'tray.mute': 'Mute notifications for 1 hour', + 'tray.unmute': 'Unmute notifications', + 'tray.update': 'Check for updates', + 'tray.settings': 'Settings', + 'tray.quit': 'Quit storebound', + 'tray.tipReview': '{count} in review', + 'tray.tipAttention': '{count} needs you', + 'tray.mutedTip': 'muted', + 'set.nRejected': 'Rejected', + 'set.nRejectedHint': 'A version the store rejected, with its reason when the store gives one', + 'set.nApproved': 'Approved and ready for release', + 'set.nApprovedHint': 'A version passed review', + 'set.nLive': 'Live', + 'set.nLiveHint': 'A version reached the store page or a rollout', + 'set.quiet': 'Quiet hours', + 'set.quietHint': 'No notifications in this window (they are dropped, not saved for later)', + 'set.quietFrom': 'From', + 'set.quietTo': 'To', + 'set.muteHour': 'Mute for 1 hour', + 'set.unmute': 'Unmute ({until})', + 'set.muted': 'Muted until {until}', + 'set.clickNote': "Clicking a notification does not open the app on desktop; the next time you open the window from the tray, it goes to that app's Releases tab.", 'set.lead': 'Studios, accounts, store reads, the offline cache, language, theme, notifications and more. Everything stays on this computer.', 'set.sections': 'Settings sections', 'set.studios': 'Studios & accounts', @@ -854,11 +889,11 @@ export const en = { 'set.always': 'Always', 'set.notifications': 'Notifications', 'set.notificationsSub': 'After a read, when something changed since the previous one', - 'set.nReview': 'Review and release state changes', - 'set.nReviewHint': 'In review, approved, rejected, live, halted', + 'set.nReview': 'Other release state changes', + 'set.nReviewHint': 'Submitted, in review', 'set.nLow': 'New 1 or 2 star reviews', 'set.nLowHint': 'When the Reviews tab reads new ones', - 'set.nCrash': 'Crash or ANR rate over the threshold', + 'set.nCrash': 'Rollout halted, or crash / ANR over the threshold', 'set.nCrashHint': 'Google Play bad behavior thresholds', 'set.testNotify': 'Send a test notification', 'set.testTitle': 'storebound', diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index afc278c..0fc5ff5 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -784,6 +784,41 @@ export const tr: Record = { 'notify.lowTitle': '{name}: {count} yeni düşük puan', 'notify.lowTitle_one': '{name}: yeni bir düşük puan', 'notify.crashTitle': '{name}: Play eşiğinin üstünde', + 'notify.rejectedTitle': '{name}: {store} reddetti', + 'notify.rejectedBody': '{version} sürümü reddedildi.', + 'notify.approvedTitle': '{name}: onaylandı', + 'notify.approvedBody': '{store} {version} incelemeyi geçti, yayına hazır.', + 'notify.liveTitle': '{name}: yayında', + 'notify.liveBody': '{store} {version} yayında.', + 'notify.haltedTitle': '{name}: kademeli yayın durduruldu', + 'notify.haltedBody': '{store} {version} durduruldu.', + 'tray.open': "storebound'u aç", + 'tray.readNow': 'Mağazaları şimdi oku', + 'tray.apps': 'Uygulamalar', + 'tray.noApps': 'Henüz uygulama yok', + 'tray.noState': 'henüz okunmadı', + 'tray.mute': 'Bildirimleri 1 saat sustur', + 'tray.unmute': 'Bildirimlerin sesini aç', + 'tray.update': 'Güncellemeleri denetle', + 'tray.settings': 'Ayarlar', + 'tray.quit': "storebound'dan çık", + 'tray.tipReview': '{count} incelemede', + 'tray.tipAttention': '{count} sizi bekliyor', + 'tray.mutedTip': 'sessiz', + 'set.nRejected': 'Reddedildi', + 'set.nRejectedHint': 'Mağazanın reddettiği sürüm; mağaza verirse gerekçesiyle', + 'set.nApproved': 'Onaylandı, yayına hazır', + 'set.nApprovedHint': 'Bir sürüm incelemeyi geçti', + 'set.nLive': 'Yayında', + 'set.nLiveHint': 'Bir sürüm mağaza sayfasına ya da kademeli yayına ulaştı', + 'set.quiet': 'Sessiz saatler', + 'set.quietHint': 'Bu aralıkta bildirim gelmez (sonraya saklanmaz, atılır)', + 'set.quietFrom': 'Başlangıç', + 'set.quietTo': 'Bitiş', + 'set.muteHour': '1 saat sustur', + 'set.unmute': 'Sesi aç ({until})', + 'set.muted': '{until} saatine kadar sessiz', + 'set.clickNote': 'Masaüstünde bildirime tıklamak uygulamayı açmaz; pencereyi bir sonraki sefer tepsiden açtığınızda o uygulamanın Yayınlar sekmesine gider.', 'set.lead': 'Stüdyolar, hesaplar, mağaza okumaları, çevrimdışı önbellek, dil, tema, bildirimler ve dahası. Hepsi bu bilgisayarda kalır.', 'set.sections': 'Ayar bölümleri', 'set.studios': 'Stüdyolar ve hesaplar', @@ -856,11 +891,11 @@ export const tr: Record = { 'set.always': 'Her zaman', 'set.notifications': 'Bildirimler', 'set.notificationsSub': 'Bir okumadan sonra, öncekinden beri bir şey değiştiyse', - 'set.nReview': 'İnceleme ve yayın durumu değişiklikleri', - 'set.nReviewHint': 'İncelemede, onaylandı, reddedildi, yayında, durduruldu', + 'set.nReview': 'Diğer yayın durumu değişiklikleri', + 'set.nReviewHint': 'Gönderildi, incelemede', 'set.nLow': 'Yeni 1 ya da 2 yıldızlı yorumlar', 'set.nLowHint': 'Yorumlar sekmesi yenilerini okuduğunda', - 'set.nCrash': 'Çökme ya da ANR oranı eşiğin üstünde', + 'set.nCrash': 'Kademeli yayın durdu, ya da çökme / ANR eşiğin üstünde', 'set.nCrashHint': 'Google Play kötü davranış eşikleri', 'set.testNotify': 'Deneme bildirimi gönder', 'set.testTitle': 'storebound', diff --git a/apps/desktop/src/lib/normalize.ts b/apps/desktop/src/lib/normalize.ts index 36e7844..8b584de 100644 --- a/apps/desktop/src/lib/normalize.ts +++ b/apps/desktop/src/lib/normalize.ts @@ -49,16 +49,22 @@ function overrides(v: unknown): Overrides { function pick(v: unknown, d: T, ok: (x: unknown) => boolean): T { return ok(v) ? (v as T) : d; } const isNum = (x: unknown) => typeof x === 'number' && Number.isFinite(x); const isBool = (x: unknown) => typeof x === 'boolean'; +const isHm = (x: unknown) => typeof x === 'string' && /^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/.test(x); export function normalizeSettings(v: unknown): Settings { const d = DEFAULT_SETTINGS; if (!isRec(v)) return d; const r = isRec(v.refresh) ? v.refresh : {}, c = isRec(v.cache) ? v.cache : {}, n = isRec(v.notify) ? v.notify : {}; + const q = isRec(n.quietHours) ? n.quietHours : {}; return { refresh: { autoMinutes: pick(r.autoMinutes, d.refresh.autoMinutes, isNum), onLaunch: pick(r.onLaunch, d.refresh.onLaunch, isBool), parallel: pick(r.parallel, d.refresh.parallel, isNum), icons: pick(r.icons, d.refresh.icons, isBool), autoRead: pick(r.autoRead, d.refresh.autoRead, isBool), everyMinutes: pick(r.everyMinutes, d.refresh.everyMinutes, (x: unknown) => [0, 5, 15, 30, 60].includes(x as number)) }, cache: { keepDays: pick(c.keepDays, d.cache.keepDays, isNum) }, - notify: { reviewState: pick(n.reviewState, d.notify.reviewState, isBool), lowReviews: pick(n.lowReviews, d.notify.lowReviews, isBool), crash: pick(n.crash, d.notify.crash, isBool) }, + notify: { + reviewState: pick(n.reviewState, d.notify.reviewState, isBool), rejected: pick(n.rejected, d.notify.rejected, isBool), approved: pick(n.approved, d.notify.approved, isBool), live: pick(n.live, d.notify.live, isBool), + lowReviews: pick(n.lowReviews, d.notify.lowReviews, isBool), crash: pick(n.crash, d.notify.crash, isBool), + quietHours: { enabled: pick(q.enabled, d.notify.quietHours.enabled, isBool), from: pick(q.from, d.notify.quietHours.from, isHm), to: pick(q.to, d.notify.quietHours.to, isHm) }, + }, channel: v.channel === 'beta' ? 'beta' : 'stable', }; } diff --git a/apps/desktop/src/lib/notify.ts b/apps/desktop/src/lib/notify.ts index 247f8ba..e6b48f0 100644 --- a/apps/desktop/src/lib/notify.ts +++ b/apps/desktop/src/lib/notify.ts @@ -4,7 +4,18 @@ import type { PortfolioResult } from '../api'; import { sameVersion } from '../../../../cli/lib/portfolio'; import { healthSeries, type HealthSnapshot, isError, PLAY_THRESHOLDS, type Review } from './model'; -export interface ReleaseChange { project: string; name: string; store: 'ios' | 'android'; version: string; from: string; to: string } +/** Which Settings > Notifications toggle a release change belongs to. */ +export type ReleaseKind = 'rejected' | 'approved' | 'live' | 'halted' | 'state'; +export interface ReleaseChange { project: string; name: string; store: 'ios' | 'android'; version: string; from: string; to: string; kind: ReleaseKind; /** The store's reason text, when the status carries one. */ reason?: string } + +/** The notification kind of a transition into phase `to`.*/ +export function releaseKind(to: string): ReleaseKind { + if (to === 'rejected') return 'rejected'; + if (to === 'approved') return 'approved'; + if (to === 'live' || to === 'rollout') return 'live'; + if (to === 'halted') return 'halted'; + return 'state'; +} /** Phase changes of the same version on the same store that the owner waits for: review in / out, approved, rejected, live, halted. */ export function releaseChanges(prev: PortfolioResult | null | undefined, next: PortfolioResult): ReleaseChange[] { @@ -18,7 +29,12 @@ export function releaseChanges(prev: PortfolioResult | null | undefined, next: P if (!r.version) continue; const old = (before.release.all ?? []).find(x => x.store === r.store && (x.version === r.version || sameVersion(x.version, r.version))); if (!old || old.phase === r.phase) continue; - if (WATCH.has(r.phase) || WATCH.has(old.phase)) out.push({ project: a.project, name: a.app?.name ?? a.project, store: r.store, version: r.version, from: old.phase, to: r.phase }); + // a version the developer withdrew on their own is not a store decision + if (r.state === 'DEVELOPER_REJECTED') continue; + if (WATCH.has(r.phase) || WATCH.has(old.phase)) { + const reason = typeof r.reason === 'string' && r.reason.trim() ? r.reason.trim().slice(0, 160) : undefined; + out.push({ project: a.project, name: a.app?.name ?? a.project, store: r.store, version: r.version, from: old.phase, to: r.phase, kind: releaseKind(r.phase), ...(reason ? { reason } : {}) }); + } } } return out; @@ -40,3 +56,55 @@ export function crashCrossed(prev: HealthSnapshot | null | undefined, next: Heal for (const k of ['crash', 'anr'] as const) if (now[k].tone === 'bad' && was[k].tone !== 'bad') out.push(k); return out; } + +// ---- when a notification may show: kind toggle, quiet hours, mute ---- + +export interface QuietHours { enabled: boolean; from: string; to: string } +export interface NotifyPrefs { reviewState: boolean; rejected: boolean; approved: boolean; live: boolean; lowReviews: boolean; crash: boolean; quietHours: QuietHours } +export type NoticeKind = ReleaseKind | 'lowReviews' | 'crash' | 'test'; + +/** The toggle of a notification kind ("halted" shares the crash toggle: both are "something is going wrong"). */ +export function kindEnabled(n: NotifyPrefs, kind: NoticeKind): boolean { + switch (kind) { + case 'rejected': return n.rejected; + case 'approved': return n.approved; + case 'live': return n.live; + case 'halted': case 'crash': return n.crash; + case 'state': return n.reviewState; + case 'lowReviews': return n.lowReviews; + case 'test': return true; + } +} + +const minutesOf = (hhmm: string): number | null => { + const m = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(hhmm); + return m ? Number(m[1]) * 60 + Number(m[2]) : null; +}; + +/** True inside the quiet window (it may cross midnight: 23:00-08:00). Off, equal ends or a bad time = never quiet. */ +export function inQuietHours(q: QuietHours, now: Date): boolean { + if (!q.enabled) return false; + const from = minutesOf(q.from), to = minutesOf(q.to); + if (from === null || to === null || from === to) return false; + const cur = now.getHours() * 60 + now.getMinutes(); + return from < to ? cur >= from && cur < to : cur >= from || cur < to; +} + +/** "Mute for 1 hour": muted while `muteUntil` (epoch ms) is in the future. */ +export const isMuted = (muteUntil: number, now = Date.now()): boolean => muteUntil > now; + +/** Whether a notification of `kind` may show now. A test notification ignores quiet hours and mute (it checks delivery). */ +export function mayNotify(n: NotifyPrefs, kind: NoticeKind, o: { now?: Date; muteUntil?: number } = {}): boolean { + if (kind === 'test') return true; + const now = o.now ?? new Date(); + return kindEnabled(n, kind) && !inQuietHours(n.quietHours, now) && !isMuted(o.muteUntil ?? 0, now.getTime()); +} + +/** + * Delay before the next background pass: the interval with +-10% jitter, doubled for every failure in a row (at most + * x16, capped at 2 hours before the jitter). `rand` is in [0, 1). + */ +export function nextReadDelay(everyMinutes: number, failures: number, rand = Math.random()): number { + const base = everyMinutes * 60_000 * 2 ** Math.min(Math.max(failures, 0), 4); + return Math.round(Math.min(base, 2 * 3_600_000) * (0.9 + rand * 0.2)); +} diff --git a/apps/desktop/src/lib/tray.ts b/apps/desktop/src/lib/tray.ts new file mode 100644 index 0000000..7211e2b --- /dev/null +++ b/apps/desktop/src/lib/tray.ts @@ -0,0 +1,48 @@ +// What the tray shows: one short state per app and store, the tooltip counts and the attention flag. Pure; the host +// (src-tauri/src/tray.rs) only draws it. +import type { AppStatus } from '../api'; +import type { ReleasePhase } from '../../../../cli/lib/desktop-protocol'; + +export interface TrayApp { key: string; name: string; state: string } +export interface TrayLabels { open: string; readNow: string; apps: string; noApps: string; mute: string; unmute: string; update: string; settings: string; quit: string } +export interface TraySummary { tooltip: string; attention: number; muted: boolean; apps: TrayApp[]; labels: TrayLabels } + +type Phase = ReleasePhase; + +/** What matters most first: a rejection, a halt, a review, an approval, a rollout, live. */ +const RANK: Record = { rejected: 0, halted: 1, review: 2, sent: 2, approved: 3, rollout: 4, live: 5, released: 6 }; + +/** The release of each store that the tray reports: the one with the most pressing phase (testing / draft only when nothing else). */ +export function trayPhases(s: AppStatus | undefined): { ios?: Phase; android?: Phase } { + const out: { ios?: Phase; android?: Phase } = {}; + for (const r of s?.release.all ?? []) { + const cur = out[r.store]; + if (!cur || (RANK[r.phase] ?? 9) < (RANK[cur] ?? 9)) out[r.store] = r.phase; + } + return out; +} + +/** True for a phase that needs the owner (rejected, halted). */ +export const needsYou = (p: string | undefined): boolean => p === 'rejected' || p === 'halted'; +export const inReview = (p: string | undefined): boolean => p === 'review' || p === 'sent'; + +/** + * Builds the summary the host shows. `phaseText` gives the words of a phase, `text` the tray strings (all i18n by the + * caller). The attention count is the number of apps with a rejected or halted release; the tooltip counts apps. + */ +export function traySummary( + apps: { key: string; name: string; status: AppStatus | undefined }[], muted: boolean, + tr: { phaseText: (p: string) => string; store: (s: 'ios' | 'android') => string; tipReview: (n: number) => string; tipAttention: (n: number) => string; muted: string; none: string; labels: TrayLabels }, +): TraySummary { + let review = 0, attention = 0; + const list: TrayApp[] = []; + for (const a of apps) { + const ph = trayPhases(a.status); + if (inReview(ph.ios) || inReview(ph.android)) review++; + if (needsYou(ph.ios) || needsYou(ph.android)) attention++; + const parts = (['ios', 'android'] as const).filter(s => ph[s]).map(s => `${tr.store(s)}: ${tr.phaseText(ph[s]!)}`); + list.push({ key: a.key, name: a.name, state: parts.length ? parts.join(' · ') : tr.none }); + } + const bits = [review ? tr.tipReview(review) : '', attention ? tr.tipAttention(attention) : '', muted ? tr.muted : ''].filter(Boolean); + return { tooltip: ['storebound', ...bits].join(' · '), attention, muted, apps: list, labels: tr.labels }; +} diff --git a/apps/desktop/src/nav.ts b/apps/desktop/src/nav.ts index b438256..a6429e1 100644 --- a/apps/desktop/src/nav.ts +++ b/apps/desktop/src/nav.ts @@ -34,6 +34,18 @@ export function parseStart(v: string, apps: string[]): Route | null { return tab ? { screen: screen as WorkspaceScreen, section: tab } : { screen: screen as WorkspaceScreen }; } +/** A route sent as JSON by the host (tray menu, notification target); anything that is not a known route is null. */ +export function parseRouteJson(v: string): Route | null { + let o: unknown; + try { o = JSON.parse(v); } catch { return null; } + if (!o || typeof o !== 'object') return null; + const r = o as Record; + if (r.screen === 'portfolio') return { screen: 'portfolio' }; + if (r.screen === 'app') return typeof r.appId === 'string' && r.appId ? { screen: 'app', appId: r.appId, tab: APP_TABS.includes(r.tab as AppTab) ? r.tab as AppTab : 'releases' } : null; + if (typeof r.screen === 'string' && (WORKSPACE as readonly string[]).includes(r.screen)) return typeof r.section === 'string' ? { screen: r.screen as WorkspaceScreen, section: r.section } : { screen: r.screen as WorkspaceScreen }; + return null; +} + export const sameRoute = (a: Route, b: Route): boolean => JSON.stringify(a) === JSON.stringify(b); export interface Nav { route: Route; go: (r: Route) => void; openPalette: () => void; openWelcome: () => void } diff --git a/apps/desktop/src/screens/Settings.tsx b/apps/desktop/src/screens/Settings.tsx index 96ded11..3342203 100644 --- a/apps/desktop/src/screens/Settings.tsx +++ b/apps/desktop/src/screens/Settings.tsx @@ -167,9 +167,20 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void;
+ set(x => ({ ...x, notify: { ...x.notify, rejected: v } }))} /> + set(x => ({ ...x, notify: { ...x.notify, approved: v } }))} /> + set(x => ({ ...x, notify: { ...x.notify, live: v } }))} /> set(x => ({ ...x, notify: { ...x.notify, reviewState: v } }))} /> set(x => ({ ...x, notify: { ...x.notify, lowReviews: v } }))} /> set(x => ({ ...x, notify: { ...x.notify, crash: v } }))} /> + set(x => ({ ...x, notify: { ...x.notify, quietHours: { ...x.notify.quietHours, enabled: v } } }))} /> + {s.notify.quietHours.enabled &&
+ + +
} + {d.muteUntil > Date.now() &&

{t('set.muted', { until: new Date(d.muteUntil).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) })}

} +

{t('set.clickNote')}

+
diff --git a/apps/desktop/src/store.tsx b/apps/desktop/src/store.tsx index 38c8bbd..cca9d6d 100644 --- a/apps/desktop/src/store.tsx +++ b/apps/desktop/src/store.tsx @@ -4,18 +4,20 @@ import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import { type Account, type AccountCheck, api, type AppInfo, type AppsListResult, type AppStatus, type CacheEntry, DEFAULT_SETTINGS, errorText, newJob, onDownload, - onProgress, type PortfolioResult, type Project, reads, type Settings, type SidecarStatus, type Studio, type ToolResult, + onProgress, onTrayAction, type PortfolioResult, type Project, reads, type Settings, type SidecarStatus, type Studio, type ToolResult, } from './api'; import { t } from './i18n'; import { buildApps, NO_OVERRIDES, type Overrides, type UnifiedApp } from './lib/identity'; import { isError, type HealthSnapshot, type Review } from './lib/model'; -import { crashCrossed, newLowReviews, releaseChanges } from './lib/notify'; +import { crashCrossed, mayNotify, type NoticeKind, newLowReviews, nextReadDelay, type ReleaseChange, releaseChanges } from './lib/notify'; +import { traySummary } from './lib/tray'; import { setCrashContext } from './lib/crash'; import { normalizeAccounts, normalizeProjects, normalizeWorkspace } from './lib/normalize'; import { keepLines, progressOf } from './lib/progress'; import { isStale, lanesOf, looksThrottled, oneLine, readKey, readsFor } from './lib/freshness'; import { type Outcome, type Priority, ReadScheduler, type ReadTask, type SchedulerStats } from './lib/scheduler'; import { fixHint } from './lib/views'; +import type { Route } from './nav'; import { withLastGood } from '../../../cli/lib/train'; import { failureText, usable } from './lib/results'; @@ -92,12 +94,17 @@ export interface Data { onRead: (key: string, fn: (e: ReadEvent) => void) => () => void; isReading: (key: string) => boolean; /** Reads everything of every app that is past its TTL (force: everything). */ - readAll: (force?: boolean) => Promise; + readAll: (force?: boolean) => Promise; + /** Notifications are muted until this time (epoch ms; 0 = not muted). */ + muteUntil: number; + /** Mutes notifications for `minutes` (0 = unmute). */ + setMute: (minutes: number) => void; /** After a write: the app's reads are read again. */ invalidate: (target: string) => void; /** The app on screen (its reads go first). */ setFocus: (key: string | null) => void; - refreshPortfolio: (live?: boolean, quiet?: boolean) => Promise; + /** True when the read succeeded. */ + refreshPortfolio: (live?: boolean, quiet?: boolean) => Promise; /** Reads the apps of one account (or all) from the stores. */ importApps: (account?: string) => Promise; checkAccount: (id: string) => Promise; @@ -128,6 +135,19 @@ const lastLine = (s: string): string => s.trim().split('\n').filter(Boolean).at( /** A failure line with how to fix it, when the error is a known one. */ const withHint = (msg: string | undefined): string | undefined => { const h = fixHint(msg); return h && msg ? `${msg} · ${t(h)}` : msg; }; +const storeName = (s: 'ios' | 'android'): string => (s === 'ios' ? 'App Store' : 'Google Play'); +/** Title and body of the notification of one release change (by kind; a rejection adds the store's reason when it has one). */ +export function releaseText(c: ReleaseChange): [string, string] { + const v = { name: c.name, store: storeName(c.store), version: c.version }; + switch (c.kind) { + case 'rejected': return [t('notify.rejectedTitle', v), [t('notify.rejectedBody', v), c.reason].filter(Boolean).join(' ')]; + case 'approved': return [t('notify.approvedTitle', v), t('notify.approvedBody', v)]; + case 'live': return [t('notify.liveTitle', v), t('notify.liveBody', v)]; + case 'halted': return [t('notify.haltedTitle', v), t('notify.haltedBody', v)]; + default: return [t('notify.releaseTitle', v), t('notify.releaseBody', { ...v, phase: t(`phase.${c.to}` as 'phase.live') })]; + } +} + export function DataProvider({ children }: { children: ReactNode }) { const [ready, setReady] = useState(false); const [info, setInfo] = useState(null); @@ -153,6 +173,21 @@ export function DataProvider({ children }: { children: ReactNode }) { const settingsRef = useRef(settings); settingsRef.current = settings; + // Mute for a while (the tray's "Mute notifications for 1 hour"): kept across restarts + const [muteUntil, setMuteUntil] = useState(() => { try { return Number(localStorage.getItem('storebound.muteUntil')) || 0; } catch { return 0; } }); + const muteRef = useRef(muteUntil); + muteRef.current = muteUntil; + const setMute = useCallback((minutes: number) => { + const until = minutes > 0 ? Date.now() + minutes * 60_000 : 0; + setMuteUntil(until); muteRef.current = until; + try { localStorage.setItem('storebound.muteUntil', String(until)); } catch { /* private mode: mute lasts until the window closes */ } + }, []); + /** One desktop notification: its kind's toggle, quiet hours and mute decide; `route` is where the window opens when it is next shown from the tray. */ + const notice = useCallback((kind: NoticeKind, title: string, body: string, route?: Route): void => { + if (!mayNotify(settingsRef.current.notify, kind, { muteUntil: muteRef.current })) return; + api.notify(title, body, route ? JSON.stringify(route) : undefined).catch(() => {}); + }, []); + const dismiss = useCallback((id: string) => { setToasts(ts => ts.filter(x => x.id !== id)); const tm = timers.current.get(id); @@ -196,7 +231,7 @@ export function DataProvider({ children }: { children: ReactNode }) { const appsRef = useRef(apps); appsRef.current = apps; - const refreshPortfolio = useCallback(async (liveRead = false, quiet = false) => { + const refreshPortfolio = useCallback(async (liveRead = false, quiet = false): Promise => { const job = newJob(liveRead ? 'portfolio-live' : 'portfolio'); setBusy(liveRead ? 'live' : 'offline'); setPortfolioError(null); const tid = liveRead && !quiet ? toast({ id: job, kind: 'job', title: t('toast.readingStores'), detail: t('toast.readingStoresDetail'), progress: null, job }) : null; @@ -210,8 +245,11 @@ export function DataProvider({ children }: { children: ReactNode }) { if (liveRead) { const changes = releaseChanges(liveRef.current?.value, r); setLive({ value: r, at: r.at }); - if (settingsRef.current.notify.reviewState) for (const c of changes.slice(0, 5)) - api.notify(t('notify.releaseTitle', { name: c.name }), t('notify.releaseBody', { store: c.store === 'ios' ? 'App Store' : 'Google Play', version: c.version, phase: t(`phase.${c.to}` as 'phase.live') })).catch(() => {}); + for (const c of changes.slice(0, 5)) { + const [title, body] = releaseText(c); + const app = appsRef.current.find(a => a.target === c.project); + notice(c.kind, title, body, app ? { screen: 'app', appId: app.key, tab: 'releases' } : undefined); + } const failed = r.apps.filter(a => a.storeErrors.ios || a.storeErrors.android).length; if (tid) updateToast(tid, failed ? { kind: 'info', title: t('toast.readDonePartial'), detail: t('toast.readDonePartialDetail', { count: failed }), progress: undefined, job: undefined } : { kind: 'ok', title: t('toast.readDone'), detail: t('toast.readDoneDetail', { count: r.apps.length }), progress: undefined, job: undefined }); @@ -220,8 +258,10 @@ export function DataProvider({ children }: { children: ReactNode }) { const msg = errorText(e); setPortfolioError(msg); if (tid) updateToast(tid, { kind: /cancel/i.test(msg) ? 'info' : 'bad', title: /cancel/i.test(msg) ? t('toast.cancelled') : t('toast.readFailed'), detail: msg, progress: undefined, job: undefined }); + return false; } finally { setBusy(null); } - }, [toast, updateToast]); + return true; + }, [toast, updateToast, notice]); // ---- background reader: one scheduler for every store read of the window (lib/scheduler.ts) ---- const schedRef = useRef(null); @@ -252,22 +292,42 @@ export function DataProvider({ children }: { children: ReactNode }) { return c; }; const statusRef = useRef<(a: UnifiedApp) => AppStatus | undefined>(() => undefined); + const lastData = useRef(new Map()); const schedule = useCallback((target: string, method: string, args: Record, priority: Priority): Promise => { const key = readKey(target, method, args); const app = appsRef.current.find(a => a.target === target); const pf = platformsOf(app, app ? statusRef.current(app) : undefined); const lanes = lanesOf(method, pf); - const p = sched.enqueue({ key, lanes, accounts: accountsOf(app, lanes), priority, run: () => api.call(method, target, { args }, newJob(method)) }); + // reviews and health: compared with the previous read here (not in a card), so the tray app notices them with no window open + const watch = method === 'reviews.list' || method === 'health'; + const run = async (): Promise => { + const before = watch ? (lastData.current.has(key) ? lastData.current.get(key) : (await api.cached(method, target, args).catch(() => null))?.value.data ?? null) : null; + const result = await api.call(method, target, { args }, newJob(method)); + if (watch && usable(method, result)) { + notifyAfterRead(method, before, result.data, notice, app?.name, app?.key); + lastData.current.set(key, result.data); + } + return result; + }; + const p = sched.enqueue({ key, lanes, accounts: accountsOf(app, lanes), priority, run }); emitRead(key, { kind: 'start' }); p.then(result => emitRead(key, { kind: 'done', result }), e => emitRead(key, { kind: 'error', error: errorText(e) })); return p; - }, [sched, emitRead]); + }, [sched, emitRead, notice]); - const readAll = useCallback(async (force = false) => { - if (!force && !settingsRef.current.refresh.autoRead) return; - if (force || isStale('portfolio.status', liveRef.current?.at)) { - sched.enqueue({ key: '*\u001fportfolio.status', lanes: ['apple', 'play'], accounts: [], priority: 1, run: () => refreshPortfolio(true, true) }).catch(() => {}); + /** + * Reads everything past its TTL. The portfolio read is a LIVE one (refreshPortfolio(true)): it is what releaseChanges + * compares, so a rejection is seen even when no screen asked. Resolves when that read is done: false when it failed. + */ + const readAll = useCallback(async (force = false): Promise => { + if (!force && !settingsRef.current.refresh.autoRead) return true; + let ok = true; + let portfolioRead: Promise | null = null; + const pkey = '*\u001fportfolio.status'; + if (!sched.has(pkey) && (force || isStale('portfolio.status', liveRef.current?.at))) { + portfolioRead = sched.enqueue({ key: pkey, lanes: ['apple', 'play'], accounts: [], priority: 1, run: () => refreshPortfolio(true, true) }) + .then(r => { ok = r !== false; }, () => { ok = false; }); } const list = [...appsRef.current].filter(a => !a.ignored && !a.project?.missing) .sort((a, b) => Number(b.key === focusRef.current) - Number(a.key === focusRef.current)); @@ -283,6 +343,8 @@ export function DataProvider({ children }: { children: ReactNode }) { schedule(a.target, r.method, r.args, a.key === focusRef.current ? 0 : 2).catch(() => {}); } } + await portfolioRead; + return ok; }, [sched, schedule, refreshPortfolio]); const invalidate = useCallback((target: string) => { @@ -353,27 +415,48 @@ export function DataProvider({ children }: { children: ReactNode }) { useEffect(() => { if (projects.length) refreshPortfolio(false); }, [projects.length, refreshPortfolio]); // Settings > Reading: everything past its TTL is read in the background on start, when the window shows again after - // a while, and every N minutes while it is visible (the scheduler keeps it inside the stores' limits). + // a while, and every N minutes (with a little jitter) EVEN WHILE THE WINDOW IS HIDDEN: the app lives in the tray, and + // that is where a rejection has to be noticed. One pass at a time; after a failed pass the wait doubles (nextReadDelay). const launched = useRef(false); useEffect(() => { if (!ready || launched.current || !apps.length) return; launched.current = true; if (settings.refresh.autoRead) readAll(false).catch(() => {}); }, [ready, apps.length, settings.refresh.autoRead, readAll]); + const passing = useRef(false); useEffect(() => { if (!settings.refresh.autoRead) return; let hiddenAt = 0; + const pass = async (): Promise => { + if (passing.current) return true; + passing.current = true; + try { return await readAll(false); } catch { return false; } finally { passing.current = false; } + }; const vis = () => { if (document.hidden) { hiddenAt = Date.now(); return; } - if (hiddenAt && Date.now() - hiddenAt > 60_000) readAll(false).catch(() => {}); + if (hiddenAt && Date.now() - hiddenAt > 60_000) pass().catch(() => {}); hiddenAt = 0; }; document.addEventListener('visibilitychange', vis); const m = settings.refresh.everyMinutes; - const tm = m ? setInterval(() => { if (!document.hidden) readAll(false).catch(() => {}); }, m * 60_000) : null; - return () => { document.removeEventListener('visibilitychange', vis); if (tm) clearInterval(tm); }; + let tm: ReturnType | null = null; + let stopped = false, failures = 0; + const next = () => { + if (stopped || !m) return; + tm = setTimeout(async () => { failures = (await pass()) ? 0 : failures + 1; next(); }, nextReadDelay(m, failures)); + }; + next(); + return () => { stopped = true; document.removeEventListener('visibilitychange', vis); if (tm) clearTimeout(tm); }; }, [settings.refresh.autoRead, settings.refresh.everyMinutes, readAll]); + // the tray: tooltip, attention icon and the apps list follow every read; its menu asks for a read or the mute + const readRef = useRef(readAll); + readRef.current = readAll; + useEffect(() => { + const un = onTrayAction(a => { if (a === 'read') readRef.current(true).catch(() => {}); else setMute(isMutedNow() ? 0 : 60); }); + return () => { un.then(f => f()); }; + }, [setMute]); + const isMutedNow = () => muteRef.current > Date.now(); // icons: cached first, then read (offline, cheap) useEffect(() => { for (const p of projects) { @@ -419,14 +502,33 @@ export function DataProvider({ children }: { children: ReactNode }) { const iconFor = useCallback((a: UnifiedApp) => (a.project ? icons[a.project.id] ?? a.storeIcon : a.storeIcon), [icons]); const appByKey = useCallback((key: string) => apps.find(a => a.key === key), [apps]); statusRef.current = statusFor; + + useEffect(() => { + if (!ready) return; + const muted = muteUntil > Date.now(); + const sum = traySummary( + apps.filter(a => !a.ignored).map(a => ({ key: a.key, name: a.name, status: liveFor(a) ?? statusFor(a) })), muted, + { phaseText: p => t(`phase.${p}` as 'phase.live'), store: s => (s === 'ios' ? 'App Store' : 'Play'), none: t('tray.noState'), muted: t('tray.mutedTip'), + tipReview: n => t('tray.tipReview', { count: n }), tipAttention: n => t('tray.tipAttention', { count: n }), + labels: { open: t('tray.open'), readNow: t('tray.readNow'), apps: t('tray.apps'), noApps: t('tray.noApps'), mute: t('tray.mute'), unmute: t('tray.unmute'), update: t('tray.update'), settings: t('tray.settings'), quit: t('tray.quit') } }, + ); + api.trayUpdate(sum).catch(() => {}); + }, [ready, apps, live, portfolio, muteUntil, statusFor, liveFor]); + // the mute ends by itself: the tray menu follows + useEffect(() => { + if (muteUntil <= Date.now()) return; + const tm = setTimeout(() => setMuteUntil(0), muteUntil - Date.now() + 500); + return () => clearTimeout(tm); + }, [muteUntil]); + const readerState = useMemo(() => ({ ...reader, autoRead: settings.refresh.autoRead }), [reader, settings.refresh.autoRead]); const value = useMemo(() => ({ ready, info, projects, accounts, studios, overrides, settings, storeApps, accountHealth, apps, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, - importBusy, icons, reader: readerState, schedule, onRead, isReading, readAll, invalidate, setFocus, + importBusy, icons, reader: readerState, muteUntil, setMute, schedule, onRead, isReading, readAll, invalidate, setFocus, refreshPortfolio, importApps, checkAccount, reload, updateOverrides, updateSettings, statusOf, liveOf, statusFor, liveFor, iconFor, appByKey, toasts, toast, updateToast, dismiss, cancelJob, - }), [readerState, schedule, onRead, isReading, readAll, invalidate, setFocus, ready, info, projects, accounts, studios, overrides, settings, storeApps, accountHealth, apps, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, + }), [readerState, muteUntil, setMute, schedule, onRead, isReading, readAll, invalidate, setFocus, ready, info, projects, accounts, studios, overrides, settings, storeApps, accountHealth, apps, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, importBusy, icons, refreshPortfolio, importApps, checkAccount, reload, updateOverrides, updateSettings, statusOf, liveOf, statusFor, liveFor, iconFor, appByKey, toasts, toast, updateToast, dismiss, cancelJob]); return {children}; @@ -481,16 +583,19 @@ export function useWrite(projectId: string | null) { return { busy, run, isBusy: (method: string, args: Record = {}) => busy === `${method}:${JSON.stringify(args)}` }; } +type Notice = (kind: NoticeKind, title: string, body: string, route?: Route) => void; + /** Notifications a fresh read may trigger (Settings > Notifications), compared with the read it replaces. */ -function notifyAfterRead(method: string, prev: unknown, next: unknown, settings: Settings, appName: string | undefined): void { +function notifyAfterRead(method: string, prev: unknown, next: unknown, notice: Notice, appName: string | undefined, appKey: string | undefined): void { const name = appName ?? ''; - if (method === 'reviews.list' && settings.notify.lowReviews && Array.isArray(next)) { + const route = (tab: 'reviews' | 'health'): Route | undefined => (appKey ? { screen: 'app', appId: appKey, tab } : undefined); + if (method === 'reviews.list' && Array.isArray(next)) { const fresh = newLowReviews(prev as Review[] | null, next as Review[]); - if (fresh.length) api.notify(t('notify.lowTitle', { name, count: fresh.length }), `${'★'.repeat(fresh[0]!.rating)} ${fresh[0]!.title ?? ''} ${fresh[0]!.body}`.trim()).catch(() => {}); + if (fresh.length) notice('lowReviews', t('notify.lowTitle', { name, count: fresh.length }), `${'★'.repeat(fresh[0]!.rating)} ${fresh[0]!.title ?? ''} ${fresh[0]!.body}`.trim(), route('reviews')); } - if (method === 'health' && settings.notify.crash && next && typeof next === 'object') { + if (method === 'health' && next && typeof next === 'object') { const crossed = crashCrossed(prev as HealthSnapshot | null, next as HealthSnapshot); - if (crossed.length && !isError((next as HealthSnapshot).play)) api.notify(t('notify.crashTitle', { name }), crossed.map(k => (k === 'crash' ? t('health.crash') : t('health.anr'))).join(', ')).catch(() => {}); + if (crossed.length && !isError((next as HealthSnapshot).play)) notice('crash', t('notify.crashTitle', { name }), crossed.map(k => (k === 'crash' ? t('health.crash') : t('health.anr'))).join(', '), route('health')); } } @@ -528,7 +633,6 @@ export function useRead(target: string, method: string, o: { network: boolean else { const r = e.result; if (usable(method, r)) { - notifyAfterRead(method, dataRef.current, r.data, dRef.current.settings, o.appName); set({ data: r.data as T, at: new Date().toISOString(), fromCache: false, loading: false, stale: false, error: null, command: r.command }); } else set(x => ({ ...x, loading: false, error: oneLine(failureText(r)), command: r.command })); } diff --git a/apps/desktop/tests/fixtures/state/d1-missing-folders.host.json b/apps/desktop/tests/fixtures/state/d1-missing-folders.host.json index fc2b8b4..e644176 100644 --- a/apps/desktop/tests/fixtures/state/d1-missing-folders.host.json +++ b/apps/desktop/tests/fixtures/state/d1-missing-folders.host.json @@ -33,8 +33,16 @@ }, "channel": "stable", "notify": { + "approved": true, "crash": true, + "live": true, "lowReviews": true, + "quietHours": { + "enabled": false, + "from": "23:00", + "to": "08:00" + }, + "rejected": true, "reviewState": true }, "refresh": { diff --git a/apps/desktop/tests/fixtures/state/d3-full.host.json b/apps/desktop/tests/fixtures/state/d3-full.host.json index 42fd2c9..72ab459 100644 --- a/apps/desktop/tests/fixtures/state/d3-full.host.json +++ b/apps/desktop/tests/fixtures/state/d3-full.host.json @@ -78,8 +78,16 @@ }, "channel": "stable", "notify": { + "approved": true, "crash": true, + "live": true, "lowReviews": true, + "quietHours": { + "enabled": false, + "from": "23:00", + "to": "08:00" + }, + "rejected": true, "reviewState": true }, "refresh": { diff --git a/apps/desktop/tests/fixtures/state/empty.host.json b/apps/desktop/tests/fixtures/state/empty.host.json index cfb10be..505375f 100644 --- a/apps/desktop/tests/fixtures/state/empty.host.json +++ b/apps/desktop/tests/fixtures/state/empty.host.json @@ -16,8 +16,16 @@ }, "channel": "stable", "notify": { + "approved": true, "crash": true, + "live": true, "lowReviews": true, + "quietHours": { + "enabled": false, + "from": "23:00", + "to": "08:00" + }, + "rejected": true, "reviewState": true }, "refresh": { diff --git a/apps/desktop/tests/fixtures/state/shared-profiles.host.json b/apps/desktop/tests/fixtures/state/shared-profiles.host.json index 38ac38f..2103add 100644 --- a/apps/desktop/tests/fixtures/state/shared-profiles.host.json +++ b/apps/desktop/tests/fixtures/state/shared-profiles.host.json @@ -75,8 +75,16 @@ }, "channel": "stable", "notify": { + "approved": true, "crash": true, + "live": true, "lowReviews": true, + "quietHours": { + "enabled": false, + "from": "23:00", + "to": "08:00" + }, + "rejected": true, "reviewState": true }, "refresh": { diff --git a/apps/desktop/tests/identity.test.ts b/apps/desktop/tests/identity.test.ts index fd80815..2c2f3f3 100644 --- a/apps/desktop/tests/identity.test.ts +++ b/apps/desktop/tests/identity.test.ts @@ -128,7 +128,7 @@ describe('notifications', () => { test('release phase changes, only against a previous read', () => { expect(releaseChanges(null, status('review'))).toEqual([]); expect(releaseChanges(status('review'), status('review'))).toEqual([]); - expect(releaseChanges(status('review'), status('approved'))).toEqual([{ project: '/a', name: 'A', store: 'ios', version: '2.0', from: 'review', to: 'approved' }]); + expect(releaseChanges(status('review'), status('approved'))).toEqual([{ project: '/a', name: 'A', store: 'ios', version: '2.0', from: 'review', to: 'approved', kind: 'approved' }]); expect(releaseChanges(status('draft'), status('testing'))).toEqual([]); }); test('new 1-2 star reviews and threshold crossings', () => { diff --git a/apps/desktop/tests/notifications.test.ts b/apps/desktop/tests/notifications.test.ts new file mode 100644 index 0000000..2f29d47 --- /dev/null +++ b/apps/desktop/tests/notifications.test.ts @@ -0,0 +1,153 @@ +import { describe, expect, test } from 'bun:test'; +import type { PortfolioResult } from '../src/api'; +import { DEFAULT_SETTINGS } from '../src/api'; +import { inQuietHours, isMuted, kindEnabled, mayNotify, nextReadDelay, releaseChanges } from '../src/lib/notify'; +import { normalizeSettings } from '../src/lib/normalize'; +import { parseRouteJson } from '../src/nav'; +import { traySummary, trayPhases } from '../src/lib/tray'; + +type Rel = { store: 'ios' | 'android'; version: string; state: string; phase: string; reason?: string }; +const snap = (...rels: Rel[]): PortfolioResult => ({ + apps: [{ project: '/a', ok: true, app: { id: '/a', name: 'A', platforms: { ios: null, android: null } }, summary: null, check: null, catalog: null, storeErrors: {}, errors: [], + release: { source: 'live' as const, current: null, next: null, all: rels.map(r => ({ build: '1', fraction: null, track: null, ...r })) } }], + at: 'x', +} as unknown as PortfolioResult); +const ios = (state: string, phase: string, extra: Partial = {}): Rel => ({ store: 'ios', version: '2.0', state, phase, ...extra }); +const play = (state: string, phase: string): Rel => ({ store: 'android', version: '2.0', state, phase }); + +describe('releaseChanges: transitions the owner waits for', () => { + test('App Store in review -> rejected', () => { + const c = releaseChanges(snap(ios('IN_REVIEW', 'review')), snap(ios('REJECTED', 'rejected'))); + expect(c).toHaveLength(1); + expect(c[0]).toMatchObject({ store: 'ios', version: '2.0', from: 'review', to: 'rejected', kind: 'rejected' }); + }); + test('metadata rejected counts, and the reason text comes along', () => { + const c = releaseChanges(snap(ios('WAITING_FOR_REVIEW', 'review')), snap(ios('METADATA_REJECTED', 'rejected', { reason: ' Guideline 2.1 - missing demo account ' }))); + expect(c[0]).toMatchObject({ kind: 'rejected', reason: 'Guideline 2.1 - missing demo account' }); + }); + test('Play in review -> rejected', () => { + const c = releaseChanges(snap(play('inProgress', 'review')), snap(play('rejected', 'rejected'))); + expect(c[0]).toMatchObject({ store: 'android', kind: 'rejected' }); + }); + test('approved (pending developer release)', () => { + const c = releaseChanges(snap(ios('IN_REVIEW', 'review')), snap(ios('PENDING_DEVELOPER_RELEASE', 'approved'))); + expect(c[0]).toMatchObject({ to: 'approved', kind: 'approved' }); + }); + test('live, from review and from approved; a rollout counts as live', () => { + expect(releaseChanges(snap(ios('IN_REVIEW', 'review')), snap(ios('READY_FOR_SALE', 'live')))[0]!.kind).toBe('live'); + expect(releaseChanges(snap(ios('PENDING_DEVELOPER_RELEASE', 'approved')), snap(ios('READY_FOR_SALE', 'live')))[0]!.kind).toBe('live'); + expect(releaseChanges(snap(play('inProgress', 'review')), snap(play('inProgress', 'rollout')))[0]!.kind).toBe('live'); + }); + test('halted rollout', () => { + expect(releaseChanges(snap(play('inProgress', 'rollout')), snap(play('halted', 'halted')))[0]!.kind).toBe('halted'); + }); + test('submitted -> in review is the generic kind; nothing changed or a first read is silent', () => { + expect(releaseChanges(snap(ios('PREPARE_FOR_SUBMISSION', 'draft')), snap(ios('WAITING_FOR_REVIEW', 'review')))[0]!.kind).toBe('state'); + expect(releaseChanges(snap(ios('REJECTED', 'rejected')), snap(ios('REJECTED', 'rejected')))).toEqual([]); + expect(releaseChanges(null, snap(ios('REJECTED', 'rejected')))).toEqual([]); + }); + test('a version the developer withdrew is not a store decision', () => { + expect(releaseChanges(snap(ios('IN_REVIEW', 'review')), snap(ios('DEVELOPER_REJECTED', 'rejected')))).toEqual([]); + }); + test('one store rejected while the other is live: only the rejected one', () => { + const c = releaseChanges(snap(ios('IN_REVIEW', 'review'), play('completed', 'live')), snap(ios('REJECTED', 'rejected'), play('completed', 'live'))); + expect(c.map(x => x.store)).toEqual(['ios']); + }); +}); + +describe('who may notify: toggles, quiet hours, mute', () => { + const n = DEFAULT_SETTINGS.notify; + const at = (h: number, m = 0) => new Date(2026, 9, 22, h, m); + test('each kind has its own toggle (halted shares the crash toggle)', () => { + expect(kindEnabled({ ...n, rejected: false }, 'rejected')).toBe(false); + expect(kindEnabled({ ...n, rejected: false }, 'approved')).toBe(true); + expect(kindEnabled({ ...n, approved: false }, 'approved')).toBe(false); + expect(kindEnabled({ ...n, live: false }, 'live')).toBe(false); + expect(kindEnabled({ ...n, crash: false }, 'halted')).toBe(false); + expect(kindEnabled({ ...n, crash: false }, 'crash')).toBe(false); + expect(kindEnabled({ ...n, lowReviews: false }, 'lowReviews')).toBe(false); + expect(kindEnabled({ ...n, reviewState: false }, 'state')).toBe(false); + }); + test('quiet hours are off by default and cross midnight', () => { + expect(inQuietHours(n.quietHours, at(23, 30))).toBe(false); + const q = { enabled: true, from: '23:00', to: '08:00' }; + expect(inQuietHours(q, at(22, 59))).toBe(false); + expect(inQuietHours(q, at(23, 0))).toBe(true); + expect(inQuietHours(q, at(3))).toBe(true); + expect(inQuietHours(q, at(7, 59))).toBe(true); + expect(inQuietHours(q, at(8, 0))).toBe(false); + expect(inQuietHours(q, at(12))).toBe(false); + }); + test('quiet hours inside one day, equal ends and bad times', () => { + const q = { enabled: true, from: '13:00', to: '14:30' }; + expect(inQuietHours(q, at(13, 0))).toBe(true); + expect(inQuietHours(q, at(14, 30))).toBe(false); + expect(inQuietHours({ enabled: true, from: '09:00', to: '09:00' }, at(9))).toBe(false); + expect(inQuietHours({ enabled: true, from: '9am', to: '10:00' }, at(9, 30))).toBe(false); + }); + test('mute for an hour', () => { + const now = at(12).getTime(); + expect(isMuted(0, now)).toBe(false); + expect(isMuted(now + 3_600_000, now)).toBe(true); + expect(isMuted(now - 1, now)).toBe(false); + }); + test('mayNotify combines them; a test notification always shows', () => { + const q = { ...n, quietHours: { enabled: true, from: '23:00', to: '08:00' } }; + expect(mayNotify(n, 'rejected', { now: at(12) })).toBe(true); + expect(mayNotify(q, 'rejected', { now: at(2) })).toBe(false); + expect(mayNotify(n, 'rejected', { now: at(12), muteUntil: at(12).getTime() + 1000 })).toBe(false); + expect(mayNotify({ ...n, rejected: false }, 'rejected', { now: at(12) })).toBe(false); + expect(mayNotify(q, 'test', { now: at(2), muteUntil: at(2).getTime() + 1000 })).toBe(true); + }); + test('settings from an older file get the new notify fields', () => { + const s = normalizeSettings({ notify: { reviewState: false, quietHours: { enabled: true, from: 'x', to: '07:30' } } }); + expect(s.notify).toMatchObject({ reviewState: false, rejected: true, approved: true, live: true, quietHours: { enabled: true, from: '23:00', to: '07:30' } }); + expect(normalizeSettings({ refresh: { everyMinutes: 30 } }).refresh.everyMinutes).toBe(30); + expect(DEFAULT_SETTINGS.refresh.everyMinutes).toBe(15); + }); +}); + +describe('background reading pace', () => { + test('interval with jitter, doubled per failure, capped', () => { + expect(nextReadDelay(15, 0, 0.5)).toBe(15 * 60_000); + expect(nextReadDelay(15, 0, 0)).toBe(Math.round(15 * 60_000 * 0.9)); + expect(nextReadDelay(15, 0, 0.999)).toBeLessThanOrEqual(Math.round(15 * 60_000 * 1.1)); + expect(nextReadDelay(15, 1, 0.5)).toBe(30 * 60_000); + expect(nextReadDelay(15, 2, 0.5)).toBe(60 * 60_000); + expect(nextReadDelay(15, 9, 0.5)).toBe(2 * 3_600_000); + expect(nextReadDelay(5, -3, 0.5)).toBe(5 * 60_000); + }); +}); + +describe('tray summary and routes', () => { + const app = (key: string, name: string, ...rels: Rel[]) => ({ key, name, status: snap(...rels).apps[0] }); + const tr = { phaseText: (p: string) => p, store: (s: 'ios' | 'android') => (s === 'ios' ? 'App Store' : 'Play'), none: '-', muted: 'muted', + tipReview: (n: number) => `${n} in review`, tipAttention: (n: number) => `${n} needs you`, + labels: { open: 'o', readNow: 'r', apps: 'a', noApps: 'n', mute: 'm', unmute: 'u', update: 'U', settings: 's', quit: 'q' } }; + test('counts, attention and one-word states', () => { + const s = traySummary([ + app('1', 'One', ios('IN_REVIEW', 'review'), play('completed', 'live')), + app('2', 'Two', ios('REJECTED', 'rejected')), + app('3', 'Three', ios('READY_FOR_SALE', 'live'), ios('PREPARE_FOR_SUBMISSION', 'draft')), + { key: '4', name: 'Four', status: undefined }, + ], false, tr); + expect(s.tooltip).toBe('storebound · 1 in review · 1 needs you'); + expect(s.attention).toBe(1); + expect(s.apps.map(a => a.state)).toEqual(['App Store: review · Play: live', 'App Store: rejected', 'App Store: live', '-']); + }); + test('muted shows in the tooltip; nothing going on is just the name', () => { + expect(traySummary([app('1', 'One', ios('READY_FOR_SALE', 'live'))], true, tr).tooltip).toBe('storebound · muted'); + expect(traySummary([], false, tr).tooltip).toBe('storebound'); + }); + test('the most pressing release of a store wins', () => { + expect(trayPhases(snap(ios('READY_FOR_SALE', 'live'), { ...ios('IN_REVIEW', 'review'), version: '3.0' }).apps[0]).ios).toBe('review'); + }); + test('routes from the host are checked', () => { + expect(parseRouteJson('{"screen":"app","appId":"k","tab":"reviews"}')).toEqual({ screen: 'app', appId: 'k', tab: 'reviews' }); + expect(parseRouteJson('{"screen":"app","appId":"k","tab":"nope"}')).toEqual({ screen: 'app', appId: 'k', tab: 'releases' }); + expect(parseRouteJson('{"screen":"settings","section":"updates"}')).toEqual({ screen: 'settings', section: 'updates' }); + expect(parseRouteJson('{"screen":"app"}')).toBeNull(); + expect(parseRouteJson('{"screen":"x"}')).toBeNull(); + expect(parseRouteJson('junk')).toBeNull(); + }); +}); diff --git a/cli/lib/desktop-protocol.ts b/cli/lib/desktop-protocol.ts index 5594864..b1ad271 100644 --- a/cli/lib/desktop-protocol.ts +++ b/cli/lib/desktop-protocol.ts @@ -171,6 +171,8 @@ export interface StoreRelease { version: string | null; /** iOS build number (CFBundleVersion) / highest Android versionCode. */ build: string | null; + /** The store's reason text of a rejection, when the status carries one (the state word alone does not). */ + reason?: string | null; /** The store's own state word (READY_FOR_SALE, inProgress ...). */ state: string; phase: ReleasePhase; From 4fe26326cc15c26fc7e5a23858ea1e2db1c2c75e Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 22:31:29 +0800 Subject: [PATCH 121/344] Desktop: start.log line before Tauri starts (version, args, working folder, pid), so a logon start that dies early leaves a trace --- apps/desktop/src-tauri/src/lib.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 0eb43e0..bac93cd 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -198,7 +198,25 @@ fn dev_seed(data_dir: &std::path::Path) { } } +/// One line before Tauri starts: a start at logon that dies early (before the host log exists) still leaves a trace +/// with its arguments and working folder (a logon start once left no line at all). Best effort, never fails. +fn early_trace() { + use std::io::Write; + let base = std::env::var_os("APPDATA").or_else(|| std::env::var_os("XDG_DATA_HOME")).map(std::path::PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|h| std::path::PathBuf::from(h).join(".local/share"))); + let Some(base) = base else { return }; + let dir = base.join("dev.storebound.desktop").join("logs"); + if std::fs::create_dir_all(&dir).is_err() { return } + let args: Vec = std::env::args().skip(1).collect(); + let cwd = std::env::current_dir().map(|d| d.display().to_string()).unwrap_or_default(); + let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("start.log")) { + let _ = writeln!(f, "{secs} start {} args={args:?} cwd={cwd} pid={}", env!("CARGO_PKG_VERSION"), std::process::id()); + } +} + pub fn run() { + early_trace(); linux_webkit_env(); let app = tauri::Builder::default() // single-instance first: a second start (or a storebound:// link) focuses the running app instead From 78c541f2b8cb6ae0658bbdc9e0ec253ec138e31a Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 22:38:15 +0800 Subject: [PATCH 122/344] storebound watch: store events for every app on the machine (rejected, approved, live, halted, crash threshold, reviews) to ntfy / Telegram / webhook / OS notification, loop or --once, baseline first, events.jsonl; storebound events and MCP events_recent; docs/watch.md; tests --- CHANGELOG.md | 5 + cli/commands.ts | 2 + cli/data/flags.json | 23 +++ cli/events.ts | 20 +++ cli/lib/args.ts | 2 +- cli/lib/desktop-coverage.ts | 2 + cli/lib/watch-sinks.ts | 137 +++++++++++++++++ cli/lib/watch.ts | 269 +++++++++++++++++++++++++++++++++ cli/mcp-tools.ts | 5 + cli/watch.ts | 196 ++++++++++++++++++++++++ docs/desktop-coverage.md | 4 +- docs/watch.md | 67 ++++++++ skills/store-health/SKILL.md | 4 + tests/desktop-coverage.test.ts | 2 +- tests/json-stdout.test.ts | 2 +- tests/watch.test.ts | 248 ++++++++++++++++++++++++++++++ 16 files changed, 984 insertions(+), 4 deletions(-) create mode 100644 cli/events.ts create mode 100644 cli/lib/watch-sinks.ts create mode 100644 cli/lib/watch.ts create mode 100644 cli/watch.ts create mode 100644 docs/watch.md create mode 100644 tests/watch.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 0220309..cfd3fcb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- **`storebound watch`**: store events for every app on the machine (rejected, approved, live, rollout halted, crash + threshold, low or unanswered reviews), sent to ntfy (phone), Telegram, a webhook or an OS notification; runs as a loop + (`--every 15m`) or `--once`; a PM2 recipe for a server is in docs/watch.md. `storebound events` and the MCP tool + `events_recent` let people and agents read what happened. + - **Desktop notifications that arrive.** The app reads the stores in the background from the tray too (it skipped every read while hidden, so a rejection went unnoticed), every 15 minutes with backoff. Notifications by kind, each with a switch: rejected, approved, live, halted, crash / ANR, low-rated reviews; quiet hours and mute for an hour. diff --git a/cli/commands.ts b/cli/commands.ts index 5b0f6ae..715c8b0 100644 --- a/cli/commands.ts +++ b/cli/commands.ts @@ -11,6 +11,8 @@ export const PLAIN: Record Promise, string]> = { 'import': [() => import('./import'), 'fastlane [--dir fastlane] [--profile app|game|subscription-app] [--dry]: Appfile, deliver + supply metadata and screenshots -> config, store/*.md, shots frames (read-only on fastlane, never overwrites)'], '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)'], + 'watch': [() => import('./watch'), 'store events for every app on this machine: rejected, approved, live, rollout halted, crash threshold, low reviews; loops every --every 15m or --once; sinks --notify os|ntfy|telegram|webhook; test sends a test event; --dry, --dir , --json (read-only on the stores)'], + 'events': [() => import('./events'), '[--since 24h] [--app ] [--kind rejected] [--json]: the events watch recorded in ~/.storebound/events.jsonl (read-only)'], 'serve': [() => import('./serve'), '--stdio: JSON-RPC session for the storebound desktop app (dry runs; writes need a host confirm token)'], 'apps': [() => import('./apps'), 'list (every app the store keys can see: App Store Connect team, Play developer accounts; --icons) | check (key works / permission missing / revoked, with the fix); --store apple|play, --json; read-only | folders | add [] | remove : the app folders of this machine, the same list as the desktop app'], 'desktop': [() => import('./desktop'), 'open the storebound desktop app on this folder; not installed or another version: download it for this system (size, SHA-256, signature checked), install it for this user (asks once; --yes) and open it; --download only saves the installer, --dry / --json change nothing'], diff --git a/cli/data/flags.json b/cli/data/flags.json index f581df0..af740bc 100644 --- a/cli/data/flags.json +++ b/cli/data/flags.json @@ -510,6 +510,11 @@ "ops", "show" ], + "events": [ + "app", + "kind", + "since" + ], "flow": [ "apply", "from", @@ -973,6 +978,13 @@ "weekly", "write" ], + "watch": [ + "dir", + "every", + "notify", + "once", + "stdio" + ], "web": [ "base-url", "landing", @@ -1058,6 +1070,7 @@ "download", "enable", "end", + "every", "experiment", "expo", "fields", @@ -1098,6 +1111,7 @@ "keychain", "keyword", "keywords", + "kind", "landing", "lang", "languages", @@ -1140,9 +1154,11 @@ "no-wait", "no-web", "not-sent-for-review", + "notify", "off", "offline", "older-than", + "once", "only-decreases", "only-keywords", "only-missing", @@ -1444,6 +1460,9 @@ "storebound edit --ops '' [--dry] [--json]", "storebound edit --show --json every value the desktop's editors show (listings, config sections, git state)" ], + "events": [ + "storebound events [--since 24h] [--app ] [--kind rejected,live] [--json]" + ], "flow": [ "storebound flow list [--json] the flows of this project and their steps", "storebound flow validate [--json] definitions, sub-flow cycles, commands, variables; exit 1 on a problem", @@ -1605,6 +1624,10 @@ "validate": [ "storebound validate [--apple] [--play] [--json] [--src store/renders] [--no-local] [--no-health] [--no-scan]" ], + "watch": [ + "storebound watch [--dir ] [--every 15m] [--notify os,ntfy,telegram,webhook] [--once] [--dry] [--json]", + "storebound watch test [--notify ...] [--dry] sends one test event to every configured sink" + ], "web": [ "storebound web init [--out web] [--landing] [--version-code N] [--dry] [--json]", "storebound web check [] [--json] read-only, no credentials: the live files on https://" diff --git a/cli/events.ts b/cli/events.ts new file mode 100644 index 0000000..c4d72be --- /dev/null +++ b/cli/events.ts @@ -0,0 +1,20 @@ +// `storebound events`: the events `storebound watch` recorded in ~/.storebound/events.jsonl (and events.jsonl.1), read-only. +// storebound events [--since 24h] [--app ] [--kind rejected,live] [--json] +// Kinds: rejected, approved, live, rollout_halted, crash_threshold, review_low, review_needs_reply. Newest last. +import type { Args } from './lib/args'; +import { done, printJson } from './lib/log'; +import { textTable } from './lib/table'; +import { durationMs, EVENT_KINDS, eventsFile, filterEvents, readEvents } from './lib/watch'; + +export function run(args: Args): Promise { + const kinds = args.list('kind'); + for (const k of kinds) if (!(EVENT_KINDS as readonly string[]).includes(k)) throw new Error(`--kind: ${k} is not an event kind (${EVENT_KINDS.join(', ')})`); + const since = args.get('since'); + const evs = filterEvents(readEvents(), { ...(since ? { sinceMs: durationMs(since) } : {}), ...(args.get('app') ? { app: args.get('app')! } : {}), kind: kinds }); + if (args.has('json')) printJson(evs); + else { + console.log(textTable(['at', 'app', 'store', 'kind', 'version', 'detail'], evs.map(e => [e.at.slice(0, 16).replace('T', ' '), e.app, e.store, e.kind, e.version ?? '', e.detail.slice(0, 90)]))); + done('events', `${evs.length} event(s) in ${eventsFile()}${since ? ` since ${since}` : ''}`); + } + return Promise.resolve(); +} diff --git a/cli/lib/args.ts b/cli/lib/args.ts index e744174..5e68b04 100644 --- a/cli/lib/args.ts +++ b/cli/lib/args.ts @@ -20,7 +20,7 @@ export function parseArgs(argv: string[], booleans: string[] = []): Args { const repeated = new Map(); const set = (k: string, v: string) => { flags.set(k, v); repeated.set(k, [...(repeated.get(k) ?? []), v]); }; const _: string[] = []; - const bool = new Set(['dry', 'yes', 'allow-price-changes', 'help', 'json', 'verbose', 'all-pages', 'apply', 'resume', 'force', 'force-unlock', 'include-drafts', 'not-sent-for-review', 'review-sent', ...booleans]); + const bool = new Set(['dry', 'yes', 'allow-price-changes', 'help', 'json', 'verbose', 'all-pages', 'apply', 'resume', 'force', 'force-unlock', 'include-drafts', 'not-sent-for-review', 'review-sent', 'once', ...booleans]); for (let i = 0; i < argv.length; i++) { const a = argv[i]!; if (!a.startsWith('--')) { _.push(a); continue; } diff --git a/cli/lib/desktop-coverage.ts b/cli/lib/desktop-coverage.ts index 8628439..1a9f620 100644 --- a/cli/lib/desktop-coverage.ts +++ b/cli/lib/desktop-coverage.ts @@ -50,6 +50,8 @@ export const DESKTOP_COVERAGE: Record = { 'settings': { not: 'per-machine switch for AI agents (bypass mode); in the window the owner presses owner actions in a native dialog anyway' }, 'serve': { not: 'the JSON-RPC sidecar the window runs on; nothing to click' }, 'apps': { where: 'Accounts (store apps per account, key check) and App folders (list, add, remove)', methods: ['host:store_apps_refresh', 'host:account_check', 'host:projects_list', 'host:project_add', 'host:project_remove'] }, + 'watch': { not: 'a server loop for people and agents (PM2, cron); the window already reads the stores in the background and notifies from the tray' }, + 'events': { not: 'the log that watch writes for terminals and agents; the window shows its own what-changed feed and tray notifications' }, 'desktop': { not: 'opens or installs this window from a terminal' }, 'accounts': { where: 'Accounts screen (profiles shared with the CLI)', methods: ['host:accounts_list', 'host:account_add_play', 'host:account_add_apple', 'host:account_update'] }, 'doctor': { where: 'Dependencies screen', methods: ['system.tools', 'host:tools_info'] }, diff --git a/cli/lib/watch-sinks.ts b/cli/lib/watch-sinks.ts new file mode 100644 index 0000000..83c5c69 --- /dev/null +++ b/cli/lib/watch-sinks.ts @@ -0,0 +1,137 @@ +// Where `storebound watch` sends events: OS notification, ntfy, Telegram, a webhook. All optional, configured from the +// environment or ~/.storebound/watch.json (never printed; logs name the sink, not its URL, topic or token): +// STOREBOUND_NTFY_URL (default https://ntfy.sh) + STOREBOUND_NTFY_TOPIC [+ STOREBOUND_NTFY_TOKEN] +// STOREBOUND_TELEGRAM_TOKEN + STOREBOUND_TELEGRAM_CHAT +// STOREBOUND_WEBHOOK_URL +// watch.json: { "notify": ["os"], "ntfy": { "url", "topic", "token" }, "telegram": { "token", "chat" }, "webhook": { "url" } } +// Builders are pure (tests check them); `send` takes the fetch and the OS runner as parameters. +import { spawnSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import { type EventKind, watchConfigFile, type WatchEvent } from './watch'; + +export type SinkName = 'os' | 'ntfy' | 'telegram' | 'webhook'; +export const SINK_NAMES: readonly SinkName[] = ['os', 'ntfy', 'telegram', 'webhook']; + +export interface SinkConfig { + os?: true; + ntfy?: { url: string; topic: string; token?: string }; + telegram?: { token: string; chat: string }; + webhook?: { url: string }; +} + +type Env = Record; + +/** The sinks that are configured (os only when the file lists it). `only` limits and, for os, enables. */ +export function sinkConfig(env: Env = process.env, file: string | null = watchConfigFile(env), only?: SinkName[]): SinkConfig { + let f: { notify?: string[]; ntfy?: Record; telegram?: Record; webhook?: Record } = {}; + if (file) { try { f = JSON.parse(readFileSync(file, 'utf8')); } catch { /* no file */ } } + const out: SinkConfig = {}; + const topic = env.STOREBOUND_NTFY_TOPIC || f.ntfy?.topic; + if (topic) out.ntfy = { url: (env.STOREBOUND_NTFY_URL || f.ntfy?.url || 'https://ntfy.sh').replace(/\/+$/, ''), topic, ...(env.STOREBOUND_NTFY_TOKEN || f.ntfy?.token ? { token: (env.STOREBOUND_NTFY_TOKEN || f.ntfy?.token)! } : {}) }; + const tg = { token: env.STOREBOUND_TELEGRAM_TOKEN || f.telegram?.token, chat: env.STOREBOUND_TELEGRAM_CHAT || f.telegram?.chat }; + if (tg.token && tg.chat) out.telegram = { token: tg.token, chat: tg.chat }; + const hook = env.STOREBOUND_WEBHOOK_URL || f.webhook?.url; + if (hook) out.webhook = { url: hook }; + if (Array.isArray(f.notify) && f.notify.includes('os')) out.os = true; + if (only) { + const picked: SinkConfig = {}; + for (const n of only) if (n === 'os') picked.os = true; else if (out[n]) (picked as Record)[n] = out[n]; + return picked; + } + return out; +} + +export const configuredSinks = (c: SinkConfig): SinkName[] => SINK_NAMES.filter(n => !!c[n]); + +/** `--notify os,ntfy` -> names; throws on an unknown one. */ +export function parseNotify(list: string[]): SinkName[] { + for (const n of list) if (!(SINK_NAMES as readonly string[]).includes(n)) throw new Error(`--notify: ${n} is not a sink (${SINK_NAMES.join(', ')})`); + return list as SinkName[]; +} + +const LABEL: Record = { + rejected: 'Rejected', approved: 'Approved', live: 'Live', rollout_halted: 'Rollout halted', crash_threshold: 'Crash threshold', + review_low: 'Low review', review_needs_reply: 'Review needs a reply', +}; +const TAGS: Record = { + rejected: 'x', approved: 'white_check_mark', live: 'rocket', rollout_halted: 'octagonal_sign', crash_threshold: 'warning', review_low: 'star', review_needs_reply: 'speech_balloon', +}; +const URGENT: ReadonlySet = new Set(['rejected', 'rollout_halted']); + +/** HTTP header values are Latin-1 text on one line. */ +const header = (s: string): string => s.replace(/[\r\n]+/g, ' ').replace(/[^\x20-\x7e]/g, '?').slice(0, 250); +export const titleOf = (e: WatchEvent): string => `${e.app}${e.version ? ` ${e.version}` : ''}: ${LABEL[e.kind]}`; +export const textOf = (e: WatchEvent): string => `${e.detail}\n${e.url}`; + +export interface HttpRequest { url: string; headers: Record; body: string } + +export function ntfyRequest(e: WatchEvent, c: NonNullable): HttpRequest { + return { url: `${c.url}/${encodeURIComponent(c.topic)}`, body: e.detail, + headers: { Title: header(titleOf(e)), Tags: `${TAGS[e.kind]},${e.store}`, Click: e.url, Priority: URGENT.has(e.kind) ? 'high' : 'default', ...(c.token ? { Authorization: `Bearer ${c.token}` } : {}) } }; +} +export function telegramRequest(e: WatchEvent, c: NonNullable): HttpRequest { + return { url: `https://api.telegram.org/bot${c.token}/sendMessage`, headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ chat_id: c.chat, text: `${titleOf(e)}\n${textOf(e)}`.slice(0, 4000), disable_web_page_preview: true }) }; +} +export function webhookRequest(e: WatchEvent, c: NonNullable): HttpRequest { + return { url: c.url, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(e) }; +} + +/** The command of an OS notification (title and message travel in the environment, never inside a script string). */ +export function osCommand(platform: string, title: string, message: string): { cmd: string; args: string[]; env: Record } | null { + const env = { SB_TITLE: title.slice(0, 120), SB_MSG: message.slice(0, 400) }; + if (platform === 'win32') { + const script = [ + '[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null', + '$x = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)', + '$t = $x.GetElementsByTagName(\'text\')', + '$t.Item(0).AppendChild($x.CreateTextNode($env:SB_TITLE)) > $null', + '$t.Item(1).AppendChild($x.CreateTextNode($env:SB_MSG)) > $null', + '[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier(\'storebound\').Show([Windows.UI.Notifications.ToastNotification]::new($x))', + ].join('; '); + return { cmd: 'powershell', args: ['-NoProfile', '-NonInteractive', '-Command', script], env }; + } + if (platform === 'darwin') return { cmd: 'osascript', args: ['-e', 'display notification (system attribute "SB_MSG") with title (system attribute "SB_TITLE")'], env }; + if (platform === 'linux') return { cmd: 'notify-send', args: [env.SB_TITLE, env.SB_MSG], env }; + return null; +} + +export type FetchLike = (url: string, init: { method: string; headers: Record; body: string; signal?: AbortSignal }) => Promise<{ ok: boolean; status: number }>; +export type OsRunner = (c: { cmd: string; args: string[]; env: Record }) => boolean; + +export const runOs: OsRunner = c => { + try { return spawnSync(c.cmd, c.args, { env: { ...process.env, ...c.env }, timeout: 10_000, stdio: 'ignore', windowsHide: true }).status === 0; } catch { return false; } +}; + +/** POST with a timeout and one retry (network error, 429 or 5xx). Resolves to an error text, or null when sent. */ +export async function post(fetchFn: FetchLike, r: HttpRequest, o: { timeoutMs?: number; retryMs?: number } = {}): Promise { + let last = ''; + for (let attempt = 0; attempt < 2; attempt++) { + if (attempt) await new Promise(res => setTimeout(res, o.retryMs ?? 1500)); + try { + const res = await fetchFn(r.url, { method: 'POST', headers: r.headers, body: r.body, signal: AbortSignal.timeout(o.timeoutMs ?? 10_000) }); + if (res.ok) return null; + last = `HTTP ${res.status}`; + if (res.status < 500 && res.status !== 429) return last; + } catch (e) { last = (e as Error).name === 'TimeoutError' ? 'timed out' : 'network error'; } + } + return last; +} + +export interface SendReport { sink: SinkName; ok: boolean; error?: string } + +/** Sends one event to every sink in the config. A failing sink is a report row, never an exception. */ +export async function sendEvent(e: WatchEvent, c: SinkConfig, d: { fetch?: FetchLike; os?: OsRunner; platform?: string; timeoutMs?: number; retryMs?: number } = {}): Promise { + const fetchFn = d.fetch ?? (fetch as unknown as FetchLike); + const out: SendReport[] = []; + const http = async (sink: SinkName, r: HttpRequest): Promise => { const err = await post(fetchFn, r, d); out.push(err ? { sink, ok: false, error: err } : { sink, ok: true }); }; + if (c.os) { + const cmd = osCommand(d.platform ?? process.platform, titleOf(e), e.detail); + // unavailable (no notifier on this machine): skipped quietly, not a failure + if (cmd) { const ok = (d.os ?? runOs)(cmd); if (ok) out.push({ sink: 'os', ok: true }); } + } + if (c.ntfy) await http('ntfy', ntfyRequest(e, c.ntfy)); + if (c.telegram) await http('telegram', telegramRequest(e, c.telegram)); + if (c.webhook) await http('webhook', webhookRequest(e, c.webhook)); + return out; +} diff --git a/cli/lib/watch.ts b/cli/lib/watch.ts new file mode 100644 index 0000000..b037b37 --- /dev/null +++ b/cli/lib/watch.ts @@ -0,0 +1,269 @@ +// `storebound watch` core, pure and offline: the snapshot an app is reduced to, the diff of two snapshots into events, +// the state file (~/.storebound/watch-state.json) and the event log (~/.storebound/events.jsonl, rotated at 5 MB). +// STOREBOUND_HOME moves both (the same folder as settings.json, cli/lib/bypass.ts). Network and process work lives in +// cli/watch.ts and cli/lib/watch-sinks.ts. +import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { type ConsoleIds, consoleUrl } from './console-links'; +import { lastValue, PLAY_THRESHOLDS, type HealthSnapshot, weightedAverage } from './health'; +import type { StoreRelease } from './desktop-protocol'; +import { PHASE_RANK } from './portfolio'; + +export const EVENT_KINDS = ['rejected', 'approved', 'live', 'rollout_halted', 'crash_threshold', 'review_low', 'review_needs_reply'] as const; +export type EventKind = (typeof EVENT_KINDS)[number]; +export type WatchStore = 'apple' | 'play'; + +export interface WatchEvent { + at: string; + app: string; + store: WatchStore; + kind: EventKind; + version: string | null; + from: string | null; + to: string | null; + detail: string; + /** The absolute console deep link for the app (App Store Connect / Play Console). */ + url: string; +} + +/** One version on one store, reduced to what the diff needs. */ +export interface RelSnap { phase: string; state: string; fraction: number | null } +/** A review the watch has seen (text trimmed; the author is never kept). */ +export interface ReviewSnap { id: string; rating: number; replied: boolean; date: string; text: string } + +/** What one app looked like at the last read. A part that is absent was not read (never guessed). */ +export interface AppSnap { + name: string; + ids: ConsoleIds; + releases?: { apple?: Record; play?: Record }; + /** Play: 28-day user-perceived rates (null = no data); Apple: the metrics / diagnostics rated poor. */ + health?: { play?: { crash: number | null; anr: number | null }; apple?: { poor: string[] } }; + healthAt?: string; + reviews?: { apple?: ReviewSnap[]; play?: ReviewSnap[] }; +} + +export interface WatchState { version: 1; at: string; apps: Record } + +export const STATE_VERSION = 1 as const; +export const emptyState = (): WatchState => ({ version: STATE_VERSION, at: '', apps: {} }); +export const MAX_SEEN_REVIEWS = 300; +export const LOW_STARS = 2; +export const ROTATE_BYTES = 5 * 1024 * 1024; + +// ---- files ---- + +export const watchHome = (env: Record = process.env): string => env.STOREBOUND_HOME ?? join(homedir(), '.storebound'); +export const stateFile = (env: Record = process.env): string => join(watchHome(env), 'watch-state.json'); +export const eventsFile = (env: Record = process.env): string => join(watchHome(env), 'events.jsonl'); +export const watchConfigFile = (env: Record = process.env): string => join(watchHome(env), 'watch.json'); + +export function readState(file = stateFile()): WatchState { + try { + const s = JSON.parse(readFileSync(file, 'utf8')) as WatchState; + if (s && s.version === STATE_VERSION && s.apps && typeof s.apps === 'object') return s; + } catch { /* none yet, or unreadable: a new baseline */ } + return emptyState(); +} + +/** Atomic write (temp file, rename). */ +export function writeState(s: WatchState, file = stateFile()): void { + mkdirSync(dirname(file), { recursive: true }); + const tmp = `${file}.tmp-${process.pid}`; + writeFileSync(tmp, JSON.stringify(s) + '\n'); + renameSync(tmp, file); +} + +/** Appends events as JSON lines; a log of `maxBytes` or more is moved to .1 first (one old file is kept). */ +export function appendEvents(events: WatchEvent[], file = eventsFile(), maxBytes = ROTATE_BYTES): void { + if (!events.length) return; + mkdirSync(dirname(file), { recursive: true }); + try { + if (existsSync(file) && statSync(file).size >= maxBytes) { + rmSync(`${file}.1`, { force: true }); + renameSync(file, `${file}.1`); + } + } catch { /* rotation is best effort; appending still works */ } + appendFileSync(file, events.map(e => JSON.stringify(e)).join('\n') + '\n'); +} + +/** Every event of the log (the old file first), oldest first. Unreadable lines are skipped. */ +export function readEvents(file = eventsFile()): WatchEvent[] { + const out: WatchEvent[] = []; + for (const f of [`${file}.1`, file]) { + let text = ''; + try { text = readFileSync(f, 'utf8'); } catch { continue; } + for (const line of text.split('\n')) { + if (!line.trim()) continue; + try { const e = JSON.parse(line) as WatchEvent; if (e && typeof e.at === 'string' && typeof e.kind === 'string') out.push(e); } catch { /* a torn line */ } + } + } + return out; +} + +/** `events` filters: since (ms back from now), app (case-insensitive name match), kind. Newest last. */ +export function filterEvents(evs: WatchEvent[], o: { sinceMs?: number; now?: number; app?: string; kind?: string[] } = {}): WatchEvent[] { + const cut = o.sinceMs !== undefined ? (o.now ?? Date.now()) - o.sinceMs : null; + const app = o.app?.toLowerCase(); + return evs.filter(e => (cut === null || Date.parse(e.at) >= cut) && (!app || e.app.toLowerCase() === app || e.app.toLowerCase().includes(app)) + && (!o.kind?.length || o.kind.includes(e.kind))); +} + +/** "15m", "24h", "2d"; a bare number is `bare` ("m" for --every, "s" otherwise). */ +export function durationMs(s: string, bare: 's' | 'm' = 's'): number { + const m = /^(\d+(?:\.\d+)?)(s|m|h|d)?$/.exec(s.trim()); + if (!m) throw new Error(`bad duration "${s}" (use 15m, 24h, 2d)`); + return Math.round(Number(m[1]) * { s: 1e3, m: 6e4, h: 36e5, d: 864e5 }[(m[2] ?? bare) as 's' | 'm' | 'h' | 'd']); +} + +// ---- reducing store reads to a snapshot ---- + +/** Per version of one store, the furthest-along row (live before rollout before review ...). */ +export function releaseMap(rows: StoreRelease[], store: 'ios' | 'android'): Record { + const out: Record = {}; + for (const r of rows) { + if (r.store !== store || !r.version) continue; + const rank = PHASE_RANK[r.phase]; + if (!out[r.version] || rank < out[r.version]!.rank) out[r.version] = { phase: r.phase, state: r.state, fraction: r.fraction, rank }; + } + return Object.fromEntries(Object.entries(out).map(([v, { rank: _r, ...s }]) => [v, s])); +} + +/** The Play rates the health findings judge (28-day user-weighted, else the window average), and Apple's poor items. */ +export function healthSnap(h: HealthSnapshot): NonNullable { + const out: NonNullable = {}; + if (h.play && !('error' in h.play)) { + out.play = { + crash: lastValue(h.play.crash, 'userPerceivedCrashRate28dUserWeighted') ?? weightedAverage(h.play.crash, 'userPerceivedCrashRate'), + anr: lastValue(h.play.anr, 'userPerceivedAnrRate28dUserWeighted') ?? weightedAverage(h.play.anr, 'userPerceivedAnrRate'), + }; + } + if (h.apple && !('error' in h.apple)) { + out.apple = { poor: [ + ...h.apple.metrics.filter(m => m.goal === 'poor').map(m => `${m.metric} ${m.value} ${m.unit} on ${m.version}`), + ...h.apple.signatures.filter(s => s.weight >= 0.25).map(s => `${s.type} build ${s.build}: ${s.signature.slice(0, 80)}`), + ] }; + } + return out; +} + +/** Keeps what the new read has and what the old one had for a part this read could not get. Pure. */ +export function mergeSnap(prev: AppSnap | undefined, next: AppSnap): AppSnap { + const seen = (a?: ReviewSnap[], b?: ReviewSnap[]): ReviewSnap[] | undefined => { + if (!a && !b) return undefined; + const byId = new Map(); + for (const r of [...(b ?? []), ...(a ?? [])]) byId.set(r.id, r); + return [...byId.values()].sort((x, y) => y.date.localeCompare(x.date)).slice(0, MAX_SEEN_REVIEWS); + }; + const releases = { ...(prev?.releases ?? {}), ...(next.releases ?? {}) }; + const health = { ...(prev?.health ?? {}), ...(next.health ?? {}) }; + const reviews = { apple: seen(next.reviews?.apple, prev?.reviews?.apple), play: seen(next.reviews?.play, prev?.reviews?.play) }; + const hasR = reviews.apple || reviews.play; + return { name: next.name, ids: { ...prev?.ids, ...Object.fromEntries(Object.entries(next.ids).filter(([, v]) => v)) }, + ...(Object.keys(releases).length ? { releases } : {}), ...(Object.keys(health).length ? { health } : {}), + ...(next.healthAt ?? prev?.healthAt ? { healthAt: next.healthAt ?? prev?.healthAt } : {}), + ...(hasR ? { reviews: { ...(reviews.apple ? { apple: reviews.apple } : {}), ...(reviews.play ? { play: reviews.play } : {}) } } : {}) }; +} + +// ---- the diff ---- + +const REACHING = new Set(['live', 'rollout', 'halted', 'released']); +const pct = (x: number | null): string => (x === null ? 'n/a' : `${(x * 100).toFixed(2)} %`); +const storeName = (s: WatchStore): string => (s === 'apple' ? 'App Store' : 'Google Play'); + +/** The console page that explains each kind, per store. Apple has no deep link for reviews or crashes in the table: + * the version page / TestFlight stand in (the app's own pages, never a made-up path). */ +export function eventUrl(kind: EventKind, store: WatchStore, ids: ConsoleIds): string { + if (store === 'apple') return consoleUrl(kind === 'rejected' ? 'asc.app-review' : kind === 'crash_threshold' ? 'asc.testflight' : 'asc.version', ids); + return consoleUrl(kind === 'crash_threshold' ? 'play.vitals' : kind === 'review_low' || kind === 'review_needs_reply' ? 'play.dashboard' : 'play.production', ids); +} + +const snippet = (s: string, n = 140): string => s.replace(/\s+/g, ' ').trim().slice(0, n); + +/** + * Events between two snapshots of one app. `prev` undefined = the app's first read: nothing (baseline). A part that + * either side does not have is skipped, so a store that could not be read never produces an event, and a part read + * for the first time is a baseline too. Pure. + */ +export function diffApp(prev: AppSnap | undefined, next: AppSnap, at: string): WatchEvent[] { + if (!prev) return []; + const out: WatchEvent[] = []; + const ids = { ...prev.ids, ...next.ids }; + const ev = (store: WatchStore, kind: EventKind, version: string | null, from: string | null, to: string | null, detail: string): void => { + out.push({ at, app: next.name, store, kind, version, from, to, detail, url: eventUrl(kind, store, ids) }); + }; + + for (const store of ['apple', 'play'] as const) { + const p = prev.releases?.[store], n = next.releases?.[store]; + if (p && n) for (const [version, now] of Object.entries(n)) { + const was = p[version]; + if (was?.phase === now.phase) continue; + const from = was?.state ?? null, to = now.state, v = version; + if (now.phase === 'rejected') ev(store, 'rejected', v, from, to, `${storeName(store)} ${v}: review ended in ${to}${store === 'apple' ? ' (the reason is in the Resolution Center)' : ''}`); + else if (now.phase === 'approved') ev(store, 'approved', v, from, to, `${storeName(store)} ${v}: passed review, waiting for release (${to})`); + else if ((now.phase === 'live' || now.phase === 'rollout') && !REACHING.has(was?.phase ?? '')) { + ev(store, 'live', v, from, to, `${storeName(store)} ${v} is ${now.phase === 'live' ? 'live' : `rolling out${now.fraction !== null ? ` at ${Math.round(now.fraction * 1000) / 10} %` : ''}`}`); + } else if (now.phase === 'halted') ev(store, 'rollout_halted', v, from, to, `${storeName(store)} ${v}: rollout halted${now.fraction !== null ? ` at ${Math.round(now.fraction * 1000) / 10} %` : ''}`); + } + } + + const pp = prev.health?.play, np = next.health?.play; + if (pp && np) { + for (const [key, label, limit] of [['crash', 'user-perceived crash rate', PLAY_THRESHOLDS.crash], ['anr', 'user-perceived ANR rate', PLAY_THRESHOLDS.anr]] as const) { + const was = pp[key], now = np[key]; + if (now !== null && now >= limit && (was === null || was < limit)) { + ev('play', 'crash_threshold', null, pct(was), pct(now), `${label} (28 d) ${pct(now)} crossed the Play bad behavior threshold ${pct(limit)}`); + } + } + } + const pa = prev.health?.apple, na = next.health?.apple; + if (pa && na) for (const item of na.poor) if (!pa.poor.includes(item)) ev('apple', 'crash_threshold', null, null, 'poor', `App Store diagnostics: ${item}`); + + for (const store of ['apple', 'play'] as const) { + const p = prev.reviews?.[store], n = next.reviews?.[store]; + if (!p || !n) continue; + const seen = new Set(p.map(r => r.id)); + for (const r of n) { + if (seen.has(r.id)) continue; + if (r.rating >= 1 && r.rating <= LOW_STARS) ev(store, 'review_low', null, null, `${r.rating} stars`, `${r.rating}-star review${r.replied ? '' : ', no reply yet'}: ${snippet(r.text)}`); + else if (!r.replied) ev(store, 'review_needs_reply', null, null, `${r.rating} stars`, `${r.rating}-star review without a reply: ${snippet(r.text)}`); + } + } + return out; +} + +export interface PassTarget { key: string; name: string } +export interface AppRead { snap: AppSnap | null; errors: string[] } + +/** + * One pass over the targets: `read` gives each app's new snapshot; the result is the new state, the events and the + * errors. An app whose read failed entirely keeps its old snapshot. Apps in the state that are no longer targets are + * kept (a folder removed for a while does not lose its baseline). Pure given `read`. + */ +export async function runPass(o: { targets: PassTarget[]; prev: WatchState; at: string; read: (t: PassTarget, prev: AppSnap | undefined) => Promise; concurrency?: number }): + Promise<{ state: WatchState; events: WatchEvent[]; errors: { app: string; error: string }[]; baseline: string[] }> { + const events: WatchEvent[] = []; + const errors: { app: string; error: string }[] = []; + const baseline: string[] = []; + const apps: Record = { ...o.prev.apps }; + let next = 0; + const worker = async (): Promise => { + while (next < o.targets.length) { + const t = o.targets[next++]!; + const before = o.prev.apps[t.key]; + let r: AppRead; + try { r = await o.read(t, before); } catch (e) { r = { snap: null, errors: [(e as Error).message] }; } + for (const e of r.errors) errors.push({ app: t.name, error: e }); + if (!r.snap) continue; + events.push(...diffApp(before, r.snap, o.at)); + if (!before) baseline.push(t.name); + apps[t.key] = mergeSnap(before, r.snap); + } + }; + await Promise.all(Array.from({ length: Math.max(1, Math.min(o.concurrency ?? 2, o.targets.length)) }, worker)); + return { state: { version: STATE_VERSION, at: o.at, apps }, events, errors, baseline }; +} + +/** A made-up event for `watch test`. */ +export const testEvent = (at = new Date().toISOString()): WatchEvent => + ({ at, app: 'storebound test', store: 'apple', kind: 'live', version: '1.0.0', from: 'READY_FOR_SALE', to: 'READY_FOR_SALE', detail: 'This is a test event from storebound watch test', url: 'https://appstoreconnect.apple.com/apps' }); diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index ea8e7f1..48d241e 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -75,6 +75,11 @@ export const TOOLS: ToolDef[] = [ description: 'Weekly health summary as Markdown in .storebound/health/.md (plus .json for the next week-over-week comparison). Local files only; dry_run prints the report.', props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' } }, args: i => (i.store === 'apple' ? ['--apple'] : i.store === 'play' ? ['--play'] : []) }, + { name: 'events_recent', title: 'Recent store events', command: ['events'], write: false, network: false, + description: 'Read-only: the store events that storebound watch recorded on this machine (rejected, approved, live, rollout_halted, crash_threshold, review_low, review_needs_reply), newest last, each with the app, store, version, from / to state, detail and the console link. Nothing is read from the stores.', + props: { since: { type: 'string', pattern: '^\\d+(\\.\\d+)?[smhd]?$', description: 'e.g. 24h, 7d (default: all)' }, app: { type: 'string', description: 'App name (or part of it)' }, + kind: { type: 'string', pattern: '^[a-z_]+(,[a-z_]+)*$', description: 'e.g. rejected or rejected,rollout_halted' } }, + args: i => [...opt('since', i.since), ...opt('app', i.app), ...opt('kind', i.kind)] }, { name: 'reviews_list', title: 'Store reviews', command: ['reviews', 'list'], write: false, network: true, description: 'Read-only list of recent App Store and Google Play reviews (date, stars, territory / language, replied or not, text). Google Play only returns reviews from the last 7 days.', props: { store: { type: 'string', enum: ['apple', 'play'], description: 'Default: both' }, days: { type: 'integer', minimum: 1, maximum: 365, default: 14 }, diff --git a/cli/watch.ts b/cli/watch.ts new file mode 100644 index 0000000..0f12a41 --- /dev/null +++ b/cli/watch.ts @@ -0,0 +1,196 @@ +// `storebound watch`: store events for every app on this machine, for people and agents. +// storebound watch [--dir ] [--every 15m] [--notify os,ntfy,telegram,webhook] [--once] [--dry] [--json] +// storebound watch test [--notify ...] [--dry] sends one test event to every configured sink +// Apps: the machine's app folder list (~/.storebound/projects.json: folders and store-only apps, the same list as the +// desktop app) or --dir for one folder. Each pass reads release state (like `release status`), crash / ANR health +// (like `health`, at most hourly) and new reviews (like `reviews list`) per app with the credentials those commands +// use, compares with ~/.storebound/watch-state.json and emits events: rejected, approved, live, rollout_halted, +// crash_threshold, review_low (<= 2 stars), review_needs_reply (3-5 stars, no reply). The first pass of an app only +// records the baseline. Every event is appended to ~/.storebound/events.jsonl (`storebound events` reads it) and sent +// to the sinks (docs/watch.md). Read-only on the stores. STOREBOUND_HOME moves ~/.storebound. +// --every loop period, 5m or more (a bare number is minutes), with +-10 % jitter; errors back off up to 4 h +// --once one pass and exit (cron, PM2 restarts) --dry print what would be sent; nothing is sent or saved +// --json events as JSON lines on stdout +import { existsSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { emptyStatus, fillAppStatus, lastLine, type Exec } from './lib/app-status'; +import type { Args } from './lib/args'; +import { CONFIG_NAMES } from './lib/config'; +import { consoleIdsFromConfig } from './lib/console-links'; +import { profileEnv } from './lib/credentials'; +import { done, log, warn } from './lib/log'; +import { readRegistry } from './lib/registry'; +import { runCommand } from './lib/runner'; +import type { HealthSnapshot } from './lib/health'; +import { + type AppRead, type AppSnap, appendEvents, durationMs, eventsFile, healthSnap, type PassTarget, readState, releaseMap, type ReviewSnap, runPass, stateFile, + testEvent, type WatchEvent, writeState, +} from './lib/watch'; +import { configuredSinks, parseNotify, sendEvent, sinkConfig, type SinkConfig } from './lib/watch-sinks'; + +const TAG = 'watch'; +const USAGE = 'usage: storebound watch [--dir ] [--every 15m] [--notify os,ntfy,telegram,webhook] [--once] [--dry] [--json] | watch test [--notify ...] [--dry]'; +export const HEALTH_EVERY_MS = 60 * 60_000; +const MIN_EVERY_MS = 5 * 60_000; +const MAX_BACKOFF_MS = 4 * 60 * 60_000; +const CHILD_TIMEOUT_MS = 5 * 60_000; +const REVIEW_DAYS = 3; + +interface Target extends PassTarget { dir: string; virtual: boolean; env: Record } + +/** Runs a storebound child command; a hung one is cancelled after the timeout. */ +const exec = (env: Record): Exec => async (argv, cwd) => { + const run = runCommand(argv, { cwd, env, machine: true }); + const timer = setTimeout(() => run.cancel(), CHILD_TIMEOUT_MS); + try { return await run.result; } finally { clearTimeout(timer); } +}; + +/** The apps to watch: --dir, or the registry's folders and store-only apps (a store-only app that has a folder here is read once). */ +async function listTargets(args: Args): Promise { + const dir = args.get('dir'); + if (dir) { + const d = resolve(dir); + if (!CONFIG_NAMES.some(n => existsSync(join(d, n)))) throw new Error(`--dir: no storebound.config.ts in ${d}`); + return [{ key: `dir:${d}`, name: d.split(/[\\/]/).pop() ?? d, dir: d, virtual: false, env: {} }]; + } + const reg = readRegistry(); + const out: Target[] = []; + for (const p of reg.projects) { + if (!CONFIG_NAMES.some(n => existsSync(join(p.path, n)))) { warn(TAG, `${p.name}: no storebound.config.ts in ${p.path}, skipped (storebound apps remove ${p.path})`); continue; } + out.push({ key: `dir:${p.path}`, name: p.name, dir: p.path, virtual: false, env: {} }); + } + if (reg.storeApps?.length) { + const { checkVirtual, virtualDir } = await import('./serve'); + for (const s of reg.storeApps) { + try { + if (s.store === 'apple' && !s.bundleId) throw new Error('no bundle id (storebound apps add --store apple --app-id --bundle-id )'); + const v = checkVirtual({ name: s.name, ...(s.store === 'apple' ? { apple: { bundleId: s.bundleId, appId: s.appId } } : { play: { packageName: s.appId } }) }); + out.push({ key: `store:${s.id}`, name: s.name, dir: virtualDir(v), virtual: true, env: s.account ? profileEnv(s.account) : {} }); + } catch (e) { warn(TAG, `${s.name}: ${(e as Error).message}, skipped`); } + } + } + return out; +} + +/** Reads one app: releases of both stores, health when due, new reviews. A part that cannot be read is left out. */ +async function readApp(t: Target, prev: AppSnap | undefined, now: number): Promise { + const run = exec(t.env); + const errors: string[] = []; + // virtual: true skips fillAppStatus's offline `check` (only the store reads are needed here) + const e = emptyStatus(t.dir); + try { await fillAppStatus(e, t.dir, { live: true, virtual: true, exec: run }); } catch (err) { return { snap: null, errors: [(err as Error).message] }; } + const s = e.summary!; + const snap: AppSnap = { name: s.name || t.name, ids: { appleAppId: s.apple?.appId ?? null } }; + if (s.play && !t.virtual && !prev?.ids.playDeveloperId) { + try { const { loadConfig } = await import('./lib/config'); Object.assign(snap.ids, consoleIdsFromConfig((await loadConfig(undefined, t.dir)).config)); } catch { /* links fall back to the console home */ } + } + const all = e.release.all ?? []; + snap.releases = {}; + if (s.apple) { if (e.storeErrors.ios) errors.push(`App Store: ${e.storeErrors.ios}`); else snap.releases.apple = releaseMap(all, 'ios'); } + if (s.play) { if (e.storeErrors.android) errors.push(`Google Play: ${e.storeErrors.android}`); else snap.releases.play = releaseMap(all, 'android'); } + + const due = !prev?.healthAt || now - Date.parse(prev.healthAt) >= HEALTH_EVERY_MS; + if (due && (s.apple || s.play)) { + const h = await run(['health', '--json'], t.dir); + if (h.data && typeof h.data === 'object') { snap.health = healthSnap(h.data as HealthSnapshot); snap.healthAt = new Date(now).toISOString(); } + else errors.push(`health: ${lastLine(h.out) || `exit ${h.code}`}`); + } + + snap.reviews = {}; + for (const [store, on] of [['apple', !!s.apple], ['play', !!s.play]] as const) { + if (!on) continue; + const r = await run(['reviews', 'list', '--store', store, '--days', String(REVIEW_DAYS), '--json'], t.dir); + if (r.code !== 0 || !Array.isArray(r.data)) { errors.push(`reviews ${store}: ${lastLine(r.out) || `exit ${r.code}`}`); continue; } + snap.reviews[store] = (r.data as { id: string; rating: number; title?: string; body?: string; date: string; reply?: unknown }[]).map((x): ReviewSnap => + ({ id: String(x.id), rating: x.rating, replied: !!x.reply, date: x.date, text: `${x.title ? x.title + ': ' : ''}${x.body ?? ''}`.slice(0, 300) })); + } + return { snap, errors }; +} + +const line = (e: WatchEvent): string => `${e.at.slice(0, 19)}Z ${e.app} [${e.store}] ${e.kind}${e.version ? ` ${e.version}` : ''}: ${e.detail} ${e.url}`; + +function chosenSinks(args: Args): SinkConfig { + const only = args.has('notify') ? parseNotify(args.list('notify')) : undefined; + if (only) { + const have = sinkConfig(); + for (const n of only) if (n !== 'os' && !have[n]) warn(TAG, `--notify ${n}: not configured (docs/watch.md), skipped`); + } + return sinkConfig(process.env, undefined, only); +} + +/** Sends to the sinks; a failing sink is logged (the sink name only) and never stops anything. */ +async function deliver(e: WatchEvent, c: SinkConfig, args: Args): Promise { + if (args.has('dry')) { log(TAG, `dry run: would send ${e.kind} of ${e.app} to ${configuredSinks(c).join(', ') || 'no sink'}`); return; } + for (const r of await sendEvent(e, c)) if (!r.ok) warn(TAG, `${r.sink}: not sent (${r.error})`); +} + +function emit(e: WatchEvent, args: Args): void { + if (args.has('json')) process.stdout.write(JSON.stringify(e) + '\n'); + else console.log(line(e)); +} + +async function testCmd(args: Args): Promise { + const c = chosenSinks(args); + const names = configuredSinks(c); + if (!names.length) { warn(TAG, 'no sink configured: set STOREBOUND_NTFY_TOPIC, STOREBOUND_TELEGRAM_TOKEN + STOREBOUND_TELEGRAM_CHAT, STOREBOUND_WEBHOOK_URL, or pass --notify os (docs/watch.md)'); process.exitCode = 1; return; } + const e = testEvent(); + emit(e, args); + if (args.has('dry')) { done(TAG, `dry run: would send the test event to ${names.join(', ')}`); return; } + const rep = await sendEvent(e, c); + for (const r of rep) (r.ok ? log : warn)(TAG, `${r.sink}: ${r.ok ? 'sent' : `not sent (${r.error})`}`); + const missing = names.filter(n => !rep.some(r => r.sink === n)); + if (missing.length) log(TAG, `${missing.join(', ')}: unavailable on this machine, skipped`); + if (rep.some(r => !r.ok)) process.exitCode = 1; + done(TAG, `test event: ${rep.filter(r => r.ok).length}/${names.length} sink(s) delivered`); +} + +export function everyMs(args: Args): number { + const ms = durationMs(args.str('every', '15m'), 'm'); + if (ms < MIN_EVERY_MS) throw new Error('--every: 5m at least (the stores rate-limit their APIs)'); + return ms; +} + +export async function run(args: Args): Promise { + const sub = args._[0]; + if (sub === 'test') return testCmd(args); + if (sub) throw new Error(USAGE); + const every = everyMs(args); + const sinks = chosenSinks(args); + const once = args.has('once'); + let stopping = false, wake: (() => void) | null = null; + const stop = (sig: string): void => { + if (stopping) process.exit(130); + stopping = true; + log(TAG, `${sig}: finishing the pass in progress, then stopping`); + wake?.(); + }; + process.on('SIGINT', () => stop('SIGINT')); + process.on('SIGTERM', () => stop('SIGTERM')); + + let n = 0, failures = 0; + log(TAG, `${once ? 'one pass' : `every ${Math.round(every / 60_000)}m`}, sinks: ${configuredSinks(sinks).join(', ') || 'none (events go to the log and stdout)'}${args.has('dry') ? ', dry run' : ''}`); + while (!stopping) { + n++; + let ok = false, count = 0, events = 0, errs = 0; + try { + const targets = await listTargets(args); + if (!targets.length) warn(TAG, 'no app folders: storebound apps add (or --dir )'); + const now = Date.now(); + const r = await runPass({ targets, prev: readState(), at: new Date(now).toISOString(), concurrency: 2, read: (t, prev) => readApp(t as Target, prev, now) }); + count = targets.length; events = r.events.length; errs = r.errors.length; + for (const x of r.errors) warn(TAG, `${x.app}: ${x.error.slice(0, 200)}`); + if (r.baseline.length) log(TAG, `baseline recorded for ${r.baseline.join(', ')} (no events on a first read)`); + for (const e of r.events) { emit(e, args); await deliver(e, sinks, args); } + if (!args.has('dry')) { appendEvents(r.events); writeState(r.state); } + ok = !(count > 0 && errs >= count); + } catch (e) { errs++; warn(TAG, `pass failed: ${(e as Error).message.slice(0, 300)}`); } + failures = ok ? 0 : failures + 1; + const wait = Math.min(MAX_BACKOFF_MS, every * 2 ** Math.min(failures, 6)) * (failures ? 1 : 0.9 + Math.random() * 0.2); + log(TAG, `pass ${n}: ${count} app(s), ${events} event(s), ${errs} error(s)${once || stopping ? '' : `, next in ${Math.round(wait / 60_000)}m${failures ? ` (backoff after ${failures} failed pass(es))` : ''}`}`); + if (once || stopping) break; + await new Promise(res => { const t = setTimeout(res, wait); wake = () => { clearTimeout(t); res(); }; }); + wake = null; + } + if (once && failures) process.exitCode = 1; + log(TAG, `stopped (state ${stateFile()}, events ${eventsFile()})`); +} diff --git a/docs/desktop-coverage.md b/docs/desktop-coverage.md index ae4a1af..493ec96 100644 --- a/docs/desktop-coverage.md +++ b/docs/desktop-coverage.md @@ -5,7 +5,7 @@ Every CLI command (cli/commands.ts) and the desktop place that runs it. "covered (serve.ts, or a host command `host:`) and the window calls it; tests/desktop-coverage.test.ts fails on a gap. Owner-only parts are owner actions in the window or owner steps with their terminal command (More tools). -**97 commands:** 91 covered, 0 gaps, 6 not for the desktop. +**99 commands:** 91 covered, 0 gaps, 8 not for the desktop. | command | status | where in the window | methods | owner step | |---|---|---|---|---| @@ -13,6 +13,8 @@ Owner-only parts are owner actions in the window or owner steps with their termi | `import` | covered | App folders / first-run guide: Import from fastlane | `host:project_import_fastlane` | | | `install` | covered | More tools: Install for an AI tool | `agent.install` | | | `mcp` | not-for-desktop | the stdio server for AI tools; the window itself is the GUI over the same commands | | | +| `watch` | not-for-desktop | a server loop for people and agents (PM2, cron); the window already reads the stores in the background and notifies from the tray | | | +| `events` | not-for-desktop | the log that watch writes for terminals and agents; the window shows its own what-changed feed and tray notifications | | | | `serve` | not-for-desktop | the JSON-RPC sidecar the window runs on; nothing to click | | | | `apps` | covered | Accounts (store apps per account, key check) and App folders (list, add, remove) | `host:store_apps_refresh`, `host:account_check`, `host:projects_list`, `host:project_add`, `host:project_remove` | | | `desktop` | not-for-desktop | opens or installs this window from a terminal | | | diff --git a/docs/watch.md b/docs/watch.md new file mode 100644 index 0000000..813ca7d --- /dev/null +++ b/docs/watch.md @@ -0,0 +1,67 @@ +# storebound watch + +Store events for every app on this machine, for people and agents. Read-only on the stores. + +``` +storebound watch # loop, every 15 minutes +storebound watch --once # one pass (cron, PM2 restarts) +storebound watch --dir ./my-app # one folder instead of the machine's app list +storebound watch --notify os,ntfy # choose the sinks (default: every configured one) +storebound watch --dry --json # print the events that would go out; nothing is sent or saved +storebound watch test # send one test event to every configured sink +storebound events --since 24h --kind rejected --json +``` + +Apps come from the machine's app folder list (`storebound apps folders`, the same list as the desktop app: folders +and store-only apps) or from `--dir`. Each app is read with the credentials its commands use (the project's +`.storebound/`, its profile, or the store-only app's account). + +Each pass reads release state per store (like `release status`), crash / ANR health (like `health`, at most once an +hour) and new reviews (like `reviews list`), compares with `~/.storebound/watch-state.json` and emits events. The first +pass of an app only records the baseline: no event storm. A store that cannot be read in a pass keeps its last state +and produces no event. + +## Events + +| kind | when | +| --- | --- | +| `rejected` | a version went from in review to rejected (App Store; link to App Review) | +| `approved` | a version passed review and waits for release (App Store pending developer release) | +| `live` | a version became live, or its rollout started | +| `rollout_halted` | a Play staged rollout was halted, or an App Store phased release paused | +| `crash_threshold` | Play crash or ANR rate (28 d) crossed the bad behavior threshold; a new App Store metric or diagnostic rated poor | +| `review_low` | a new review of 2 stars or less | +| `review_needs_reply` | a new review of 3-5 stars without a reply | + +Each event is one JSON object: `{ at, app, store, kind, version, from, to, detail, url }`, where `url` is the absolute +console link for the app. Events are appended to `~/.storebound/events.jsonl` (rotated at 5 MB, one `.1` file kept). +`STOREBOUND_HOME` moves `~/.storebound`. `storebound events` and the MCP tool `events_recent` read the file. + +## Sinks + +All optional. Configure with environment variables or `~/.storebound/watch.json`; values are never printed. + +| sink | variables | +| --- | --- | +| ntfy | `STOREBOUND_NTFY_TOPIC` (required), `STOREBOUND_NTFY_URL` (default `https://ntfy.sh`), `STOREBOUND_NTFY_TOKEN` (optional). Title, Tags and Click headers; Priority high for `rejected` and `rollout_halted` | +| Telegram | `STOREBOUND_TELEGRAM_TOKEN` and `STOREBOUND_TELEGRAM_CHAT` | +| webhook | `STOREBOUND_WEBHOOK_URL` (JSON POST of the event) | +| OS notification | `--notify os`, or `"notify": ["os"]` in watch.json (Windows toast, macOS osascript, Linux notify-send; skipped quietly when unavailable) | + +```json +{ "notify": ["os"], "ntfy": { "topic": "..." }, "telegram": { "token": "...", "chat": "..." }, "webhook": { "url": "..." } } +``` + +Network calls time out after 10 s and are retried once. A failing sink is logged (by name) and never stops the watch. + +## On a server with PM2 + +``` +pm2 start "npx -y storebound watch --notify ntfy" --name storebound-watch +pm2 save +``` + +Put the credentials profiles (`~/.storebound/credentials/`) and the app folder list (`storebound apps add `) +on that server, and the sink variables in the PM2 environment (`STOREBOUND_NTFY_TOPIC=...`). The loop polls every +`--every` (5m at least, 15m default, +-10 % jitter), backs off after failed passes (up to 4 h), writes one heartbeat +line per pass and stops cleanly on SIGINT / SIGTERM. With cron use `--once`. diff --git a/skills/store-health/SKILL.md b/skills/store-health/SKILL.md index 8795ad2..8f56f93 100644 --- a/skills/store-health/SKILL.md +++ b/skills/store-health/SKILL.md @@ -51,6 +51,10 @@ Fix the top signature first, then check its device / OS column: one model or one installs but is not a rollback. 4. Next week: `storebound health --weekly` shows the change in percentage points next to last week. +## Watching for changes +- `storebound watch` polls every app on this machine and records store events (rejected, approved, live, rollout_halted, crash_threshold, review_low, review_needs_reply) in `~/.storebound/events.jsonl`; sinks: OS notification, ntfy, Telegram, webhook (docs/watch.md). +- `storebound events --since 24h [--app ] [--kind rejected] --json` (MCP `events_recent`) reads that log without touching the stores: start a session there before polling the stores yourself. + ## Gotchas - `vitals not readable`: the API is not enabled, the service account lacks the permission, or the app has no release yet. `validate` only notes it; `storebound health` warns. diff --git a/tests/desktop-coverage.test.ts b/tests/desktop-coverage.test.ts index c12236b..36f198b 100644 --- a/tests/desktop-coverage.test.ts +++ b/tests/desktop-coverage.test.ts @@ -8,7 +8,7 @@ import { describeMethods } from '../cli/serve'; import { analyze, render } from '../tools/gen-desktop-coverage'; /** The only commands that make no sense in a window. Adding one here needs a reason in the coverage map. */ -const NOT_FOR_DESKTOP = ['mcp', 'serve', 'desktop', 'api', 'settings', 'aab']; +const NOT_FOR_DESKTOP = ['mcp', 'serve', 'desktop', 'api', 'settings', 'aab', 'watch', 'events']; describe('desktop coverage', () => { const { rows, extra } = analyze(); diff --git a/tests/json-stdout.test.ts b/tests/json-stdout.test.ts index 168f185..dddfd1b 100644 --- a/tests/json-stdout.test.ts +++ b/tests/json-stdout.test.ts @@ -17,7 +17,7 @@ import { installStores, uninstallStores } from './helpers/fake-stores'; const CLI = resolve(import.meta.dir, '../cli'); /** Never run here: long-lived servers, and the ones that install or open things on the machine. */ -const SKIP = new Set(['mcp', 'serve', 'install', 'desktop', 'init', 'flow', 'ws']); +const SKIP = new Set(['mcp', 'serve', 'install', 'desktop', 'init', 'flow', 'ws', 'watch']); // watch: a loop that prints JSON lines (tests/watch.test.ts) /** Commands that need a subcommand (or arguments) to reach their --json output. */ const ARGV: Record = { 'prices': ['ppp', '--offline'], 'api': ['list'], 'accounts': ['list'], 'release': ['status'], 'apps': ['folders'], diff --git a/tests/watch.test.ts b/tests/watch.test.ts new file mode 100644 index 0000000..e1f9eea --- /dev/null +++ b/tests/watch.test.ts @@ -0,0 +1,248 @@ +import { describe, expect, test } from 'bun:test'; +import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { TOOLS, toArgv } from '../cli/mcp-tools'; +import type { HealthSnapshot } from '../cli/lib/health'; +import { + type AppSnap, appendEvents, diffApp, durationMs, eventsFile, filterEvents, healthSnap, mergeSnap, readEvents, readState, releaseMap, type RelSnap, runPass, stateFile, + testEvent, type WatchEvent, writeState, +} from '../cli/lib/watch'; +import { type FetchLike, ntfyRequest, osCommand, post, sendEvent, sinkConfig, telegramRequest, webhookRequest } from '../cli/lib/watch-sinks'; + +const AT = '2026-10-22T10:00:00.000Z'; +const rel = (phase: string, state: string, fraction: number | null = null): RelSnap => ({ phase, state, fraction }); +const snap = (o: Partial = {}): AppSnap => ({ name: 'Demo App', ids: { appleAppId: '6400000000', playDeveloperId: '111', playAppId: '222' }, ...o }); +const kinds = (es: WatchEvent[]) => es.map(e => `${e.store}:${e.kind}`); +const tmp = () => mkdtempSync(join(tmpdir(), 'sb-watch-')); + +describe('watch diff', () => { + test('a first read of an app is a baseline: no events', () => { + expect(diffApp(undefined, snap({ releases: { apple: { '1.0': rel('rejected', 'REJECTED') } } }), AT)).toEqual([]); + }); + test('App Store: in review -> rejected, pending developer release, live', () => { + const was = snap({ releases: { apple: { '1.2.0': rel('review', 'IN_REVIEW') } } }); + const rejected = diffApp(was, snap({ releases: { apple: { '1.2.0': rel('rejected', 'REJECTED') } } }), AT); + expect(rejected).toHaveLength(1); + expect(rejected[0]).toMatchObject({ app: 'Demo App', store: 'apple', kind: 'rejected', version: '1.2.0', from: 'IN_REVIEW', to: 'REJECTED', at: AT }); + expect(rejected[0]!.url).toBe('https://appstoreconnect.apple.com/apps/6400000000/distribution/reviewsubmissions'); + const approved = diffApp(was, snap({ releases: { apple: { '1.2.0': rel('approved', 'PENDING_DEVELOPER_RELEASE') } } }), AT); + expect(kinds(approved)).toEqual(['apple:approved']); + expect(approved[0]!.url).toContain('/apps/6400000000/distribution/ios/version'); + const live = diffApp(snap({ releases: { apple: { '1.2.0': rel('approved', 'PENDING_DEVELOPER_RELEASE') } } }), snap({ releases: { apple: { '1.2.0': rel('live', 'READY_FOR_SALE') } } }), AT); + expect(kinds(live)).toEqual(['apple:live']); + }); + test('Google Play: review -> live, rollout starts, rollout halted', () => { + const play = (r: RelSnap) => snap({ releases: { play: { '1.2.0': r } } }); + expect(kinds(diffApp(play(rel('review', 'completed')), play(rel('live', 'completed')), AT))).toEqual(['play:live']); + const started = diffApp(play(rel('review', 'completed')), play(rel('rollout', 'inProgress', 0.1)), AT); + expect(kinds(started)).toEqual(['play:live']); + expect(started[0]!.detail).toContain('10 %'); + expect(started[0]!.url).toBe('https://play.google.com/console/u/0/developers/111/app/222/tracks/production'); + const halted = diffApp(play(rel('rollout', 'inProgress', 0.1)), play(rel('halted', 'halted', 0.1)), AT); + expect(kinds(halted)).toEqual(['play:rollout_halted']); + }); + test('no event for an unchanged phase, a rollout step, a rollout completing, or a store that was not read', () => { + const a = snap({ releases: { apple: { '1.0': rel('rollout', 'READY_FOR_SALE', 0.1) }, play: { '1.0': rel('rollout', 'inProgress', 0.1) } } }); + const b = snap({ releases: { apple: { '1.0': rel('live', 'READY_FOR_SALE', 1) }, play: { '1.0': rel('rollout', 'inProgress', 0.5) } } }); + expect(diffApp(a, b, AT)).toEqual([]); + expect(diffApp(a, snap(), AT)).toEqual([]); + expect(diffApp(snap(), snap({ releases: { apple: { '1.0': rel('rejected', 'REJECTED') } } }), AT)).toEqual([]); + }); + test('a new version that appears already live is an event; one that appears in review is not', () => { + const was = snap({ releases: { apple: { '1.0': rel('live', 'READY_FOR_SALE') } } }); + expect(kinds(diffApp(was, snap({ releases: { apple: { '1.0': rel('live', 'READY_FOR_SALE'), '1.1': rel('review', 'WAITING_FOR_REVIEW') } } }), AT))).toEqual([]); + expect(kinds(diffApp(was, snap({ releases: { apple: { '1.0': rel('live', 'READY_FOR_SALE'), '1.1': rel('live', 'READY_FOR_SALE') } } }), AT))).toEqual(['apple:live']); + }); + test('crash threshold: only the crossing, per metric and per store', () => { + const play = (crash: number | null, anr: number | null) => snap({ health: { play: { crash, anr } } }); + const cross = diffApp(play(0.005, 0.001), play(0.012, 0.001), AT); + expect(kinds(cross)).toEqual(['play:crash_threshold']); + expect(cross[0]).toMatchObject({ from: '0.50 %', to: '1.20 %' }); + expect(cross[0]!.url).toContain('/vitals/crashes'); + expect(diffApp(play(0.012, 0.001), play(0.015, 0.001), AT)).toEqual([]); + expect(kinds(diffApp(play(null, null), play(0.012, 0.005), AT))).toEqual(['play:crash_threshold', 'play:crash_threshold']); + expect(diffApp(play(0.012, 0), play(0.002, 0), AT)).toEqual([]); + const apple = (poor: string[]) => snap({ health: { apple: { poor } } }); + expect(kinds(diffApp(apple([]), apple(['hangRate 2 s on 1.2']), AT))).toEqual(['apple:crash_threshold']); + expect(diffApp(apple(['hangRate 2 s on 1.2']), apple(['hangRate 2 s on 1.2']), AT)).toEqual([]); + }); + test('reviews: new low review, new unanswered review, nothing for seen or answered ones', () => { + const r = (id: string, rating: number, replied = false) => ({ id, rating, replied, date: '2026-10-22T09:00:00Z', text: `text of ${id}` }); + const was = snap({ reviews: { apple: [r('a', 5)], play: [r('p', 1)] } }); + const now = snap({ reviews: { apple: [r('a', 5), r('b', 1), r('c', 4), r('d', 5, true)], play: [r('p', 1), r('q', 2)] } }); + const evs = diffApp(was, now, AT); + expect(evs.map(e => `${e.store}:${e.kind}:${e.to}`)).toEqual(['apple:review_low:1 stars', 'apple:review_needs_reply:4 stars', 'play:review_low:2 stars']); + expect(evs[0]!.detail).toContain('text of b'); + expect(diffApp(was, was, AT)).toEqual([]); + }); + test('every event kind is producible and carries the full shape', () => { + const all = [ + ...diffApp(snap({ releases: { apple: { '1': rel('review', 'IN_REVIEW') }, play: { '1': rel('rollout', 'inProgress') } } }), + snap({ releases: { apple: { '1': rel('rejected', 'REJECTED') }, play: { '1': rel('halted', 'halted') } } }), AT), + ...diffApp(snap({ releases: { apple: { '2': rel('review', 'IN_REVIEW') } } }), snap({ releases: { apple: { '2': rel('approved', 'PENDING_DEVELOPER_RELEASE') } } }), AT), + ...diffApp(snap({ releases: { apple: { '3': rel('approved', 'X') } } }), snap({ releases: { apple: { '3': rel('live', 'READY_FOR_SALE') } } }), AT), + ...diffApp(snap({ health: { play: { crash: 0, anr: 0 } } }), snap({ health: { play: { crash: 0.02, anr: 0 } } }), AT), + ...diffApp(snap({ reviews: { play: [] } }), snap({ reviews: { play: [{ id: 'x', rating: 1, replied: false, date: AT, text: 't' }, { id: 'y', rating: 5, replied: false, date: AT, text: 't' }] } }), AT), + ]; + expect([...new Set(all.map(e => e.kind))].sort()).toEqual(['approved', 'crash_threshold', 'live', 'rejected', 'review_low', 'review_needs_reply', 'rollout_halted']); + for (const e of all) { expect(Object.keys(e).sort()).toEqual(['app', 'at', 'detail', 'from', 'kind', 'store', 'to', 'url', 'version']); expect(e.url).toMatch(/^https:\/\//); } + }); +}); + +describe('watch snapshots and a pass', () => { + test('releaseMap keeps the furthest-along row per version; healthSnap reads rates and poor items', () => { + const rows = [ + { store: 'android', version: '1.0', build: '1', state: 'completed', phase: 'testing', fraction: null, track: 'beta' }, + { store: 'android', version: '1.0', build: '2', state: 'inProgress', phase: 'rollout', fraction: 0.2, track: 'production' }, + { store: 'ios', version: '1.0', build: '2', state: 'IN_REVIEW', phase: 'review', fraction: null, track: null }, + ] as Parameters[0]; + expect(releaseMap(rows, 'android')).toEqual({ '1.0': { phase: 'rollout', state: 'inProgress', fraction: 0.2 } }); + expect(Object.keys(releaseMap(rows, 'ios'))).toEqual(['1.0']); + const h: HealthSnapshot = { date: '2026-10-22', + play: { window: { start: 'a', end: 'b', days: 7 }, crash: [{ date: 'd', dims: {}, values: { userPerceivedCrashRate28dUserWeighted: 0.012 } }], anr: [], issues: [] }, + apple: { metrics: [{ category: 'c', metric: 'hangRate', unit: 's', version: '1.0', value: 2, goal: 'poor' }], signatures: [], betaCrashes: [] } }; + expect(healthSnap(h)).toEqual({ play: { crash: 0.012, anr: null }, apple: { poor: ['hangRate 2 s on 1.0'] } }); + expect(healthSnap({ date: 'd', play: { error: 'x' } })).toEqual({}); + }); + test('mergeSnap keeps a part this read did not get, and the seen reviews', () => { + const old = snap({ releases: { apple: { '1': rel('live', 'X') } }, reviews: { play: [{ id: 'a', rating: 5, replied: true, date: '2026-10-01', text: '' }] } }); + const m = mergeSnap(old, snap({ releases: { play: { '1': rel('live', 'X') } }, reviews: { play: [{ id: 'b', rating: 5, replied: true, date: '2026-10-02', text: '' }] } })); + expect(Object.keys(m.releases!).sort()).toEqual(['apple', 'play']); + expect(m.reviews!.play!.map(r => r.id)).toEqual(['b', 'a']); + }); + test('runPass: baseline pass emits nothing, the second pass emits, an unreadable app keeps its state', async () => { + const targets = [{ key: 'dir:/a', name: 'A' }, { key: 'dir:/b', name: 'B' }]; + let phase = 'review', failB = false; + const read = async (t: { key: string; name: string }) => { + if (t.name === 'B' && failB) return { snap: null, errors: ['boom'] }; + return { snap: snap({ name: t.name, releases: { apple: { '1': rel(phase, phase === 'live' ? 'READY_FOR_SALE' : 'IN_REVIEW') } } }), errors: [] }; + }; + const one = await runPass({ targets, prev: readState(join(tmp(), 'none.json')), at: AT, read }); + expect(one.events).toEqual([]); + expect(one.baseline).toEqual(['A', 'B']); + phase = 'live'; failB = true; + const two = await runPass({ targets, prev: one.state, at: AT, read }); + expect(two.events.map(e => e.app)).toEqual(['A']); + expect(two.errors).toEqual([{ app: 'B', error: 'boom' }]); + expect(two.state.apps['dir:/b']!.releases!.apple!['1']!.phase).toBe('review'); + }); +}); + +describe('events.jsonl and state files', () => { + const home = () => ({ STOREBOUND_HOME: tmp() }); + const ev = (o: Partial = {}): WatchEvent => ({ ...testEvent(AT), ...o }); + test('paths follow STOREBOUND_HOME', () => { + const env = home(); + expect(eventsFile(env)).toBe(join(env.STOREBOUND_HOME, 'events.jsonl')); + expect(stateFile(env)).toBe(join(env.STOREBOUND_HOME, 'watch-state.json')); + }); + test('append writes one JSON per line and reads back; a torn line is skipped', () => { + const f = eventsFile(home()); + appendEvents([ev({ app: 'A' }), ev({ app: 'B' })], f); + appendEvents([ev({ app: 'C' })], f); + writeFileSync(f, readFileSync(f, 'utf8') + '{"at":"2026\n'); + expect(readEvents(f).map(e => e.app)).toEqual(['A', 'B', 'C']); + }); + test('rotation at the size limit keeps one .1 file and reads both', () => { + const f = eventsFile(home()); + appendEvents([ev({ app: 'old' })], f, 50); + appendEvents([ev({ app: 'new' })], f, 50); + expect(existsSync(`${f}.1`)).toBe(true); + expect(readFileSync(f, 'utf8').trim().split('\n')).toHaveLength(1); + appendEvents([ev({ app: 'newer' })], f, 50); + appendEvents([ev({ app: 'newest' })], f, 50); + expect(readEvents(f).map(e => e.app)).toEqual(['newer', 'newest']); + expect(readFileSync(`${f}.1`, 'utf8')).toContain('newer'); + }); + test('state round trip; an unreadable file is a fresh baseline', () => { + const f = stateFile(home()); + expect(readState(f).apps).toEqual({}); + writeState({ version: 1, at: AT, apps: { k: snap() } }, f); + expect(readState(f).apps.k!.name).toBe('Demo App'); + writeFileSync(f, '{nope'); + expect(readState(f).apps).toEqual({}); + }); + test('events filters: since, app, kind', () => { + const now = Date.parse(AT); + const evs = [ev({ at: '2026-10-22T09:00:00Z', app: 'Alpha', kind: 'live' }), ev({ at: '2026-10-20T09:00:00Z', app: 'Beta', kind: 'rejected' }), ev({ at: '2026-10-22T08:00:00Z', app: 'Beta', kind: 'rejected' })]; + expect(filterEvents(evs, { sinceMs: durationMs('24h'), now }).map(e => e.app)).toEqual(['Alpha', 'Beta']); + expect(filterEvents(evs, { app: 'beta' })).toHaveLength(2); + expect(filterEvents(evs, { kind: ['live'] })).toHaveLength(1); + expect(filterEvents(evs, { app: 'beta', kind: ['rejected'], sinceMs: durationMs('2d'), now })).toHaveLength(1); + expect(durationMs('15', 'm')).toBe(15 * 60_000); + expect(() => durationMs('soon')).toThrow(); + }); +}); + +describe('watch sinks', () => { + const e = (o: Partial = {}): WatchEvent => ({ ...testEvent(AT), app: 'Demo App', version: '1.2.0', kind: 'rejected', detail: 'rejected', url: 'https://appstoreconnect.apple.com/apps/1', ...o }); + test('sinkConfig reads env, a file, and --notify limits', () => { + expect(sinkConfig({}, null)).toEqual({}); + const c = sinkConfig({ STOREBOUND_NTFY_TOPIC: 't', STOREBOUND_NTFY_URL: 'https://ntfy.example.com/', STOREBOUND_TELEGRAM_TOKEN: 'tok', STOREBOUND_TELEGRAM_CHAT: '42', STOREBOUND_WEBHOOK_URL: 'https://hook.example.com/x' }, null); + expect(c).toEqual({ ntfy: { url: 'https://ntfy.example.com', topic: 't' }, telegram: { token: 'tok', chat: '42' }, webhook: { url: 'https://hook.example.com/x' } }); + expect(sinkConfig({ STOREBOUND_NTFY_TOPIC: 't' }, null).ntfy!.url).toBe('https://ntfy.sh'); + expect(sinkConfig({ STOREBOUND_TELEGRAM_TOKEN: 'tok' }, null).telegram).toBeUndefined(); + expect(sinkConfig({ STOREBOUND_NTFY_TOPIC: 't' }, null, ['os'])).toEqual({ os: true }); + const file = join(tmp(), 'watch.json'); + writeFileSync(file, JSON.stringify({ notify: ['os'], webhook: { url: 'https://h.example.com' } })); + expect(sinkConfig({}, file)).toEqual({ os: true, webhook: { url: 'https://h.example.com' } }); + }); + test('ntfy: headers (Title, Tags, Click, Priority) and body', () => { + const r = ntfyRequest(e(), { url: 'https://ntfy.sh', topic: 'my topic' }); + expect(r.url).toBe('https://ntfy.sh/my%20topic'); + expect(r.body).toBe('rejected'); + expect(r.headers).toEqual({ Title: 'Demo App 1.2.0: Rejected', Tags: 'x,apple', Click: 'https://appstoreconnect.apple.com/apps/1', Priority: 'high' }); + expect(ntfyRequest(e({ kind: 'live' }), { url: 'https://ntfy.sh', topic: 't', token: 'k' }).headers).toMatchObject({ Priority: 'default', Tags: 'rocket,apple', Authorization: 'Bearer k' }); + expect(ntfyRequest(e({ kind: 'rollout_halted' }), { url: 'https://ntfy.sh', topic: 't' }).headers.Priority).toBe('high'); + expect(ntfyRequest(e({ app: 'Café\nApp' }), { url: 'https://ntfy.sh', topic: 't' }).headers.Title).toBe('Caf? App 1.2.0: Rejected'); + }); + test('telegram and webhook bodies', () => { + const t = telegramRequest(e(), { token: 'TOKEN', chat: '42' }); + expect(t.url).toBe('https://api.telegram.org/botTOKEN/sendMessage'); + expect(JSON.parse(t.body)).toEqual({ chat_id: '42', text: 'Demo App 1.2.0: Rejected\nrejected\nhttps://appstoreconnect.apple.com/apps/1', disable_web_page_preview: true }); + const w = webhookRequest(e(), { url: 'https://hook.example.com' }); + expect(w.headers['Content-Type']).toBe('application/json'); + expect(JSON.parse(w.body)).toEqual(e()); + }); + test('os command per platform keeps the text out of the script', () => { + expect(osCommand('win32', 'T', 'M')!.cmd).toBe('powershell'); + expect(osCommand('win32', 'T"; evil', 'M')!.args.join(' ')).not.toContain('evil'); + expect(osCommand('darwin', 'T', 'M')).toMatchObject({ cmd: 'osascript', env: { SB_TITLE: 'T', SB_MSG: 'M' } }); + expect(osCommand('linux', 'T', 'M')).toMatchObject({ cmd: 'notify-send', args: ['T', 'M'] }); + expect(osCommand('freebsd', 'T', 'M')).toBeNull(); + }); + test('post: one retry on 5xx / network error, none on 4xx', async () => { + const calls: string[] = []; + const seq = (...rs: (number | 'throw')[]): FetchLike => async url => { calls.push(url); const r = rs.shift()!; if (r === 'throw') throw new Error('down'); return { ok: r < 300, status: r }; }; + const req = { url: 'https://x.example.com', headers: {}, body: '' }; + expect(await post(seq(503, 200), req, { retryMs: 1 })).toBeNull(); + expect(calls).toHaveLength(2); + calls.length = 0; + expect(await post(seq('throw', 'throw'), req, { retryMs: 1 })).toBe('network error'); + expect(calls).toHaveLength(2); + calls.length = 0; + expect(await post(seq(400, 200), req, { retryMs: 1 })).toBe('HTTP 400'); + expect(calls).toHaveLength(1); + }); + test('sendEvent: every configured sink gets it with a fake fetch; a failing sink does not stop the others', async () => { + const seen: string[] = []; + const fake: FetchLike = async url => { seen.push(url); return url.includes('telegram') ? { ok: false, status: 400 } : { ok: true, status: 200 }; }; + let osCalls = 0; + const rep = await sendEvent(e(), { os: true, ntfy: { url: 'https://ntfy.sh', topic: 't' }, telegram: { token: 'T', chat: '1' }, webhook: { url: 'https://hook.example.com' } }, + { fetch: fake, os: () => { osCalls++; return true; }, platform: 'linux', retryMs: 1 }); + expect(rep).toEqual([{ sink: 'os', ok: true }, { sink: 'ntfy', ok: true }, { sink: 'telegram', ok: false, error: 'HTTP 400' }, { sink: 'webhook', ok: true }]); + expect(osCalls).toBe(1); + expect(seen).toEqual(['https://ntfy.sh/t', 'https://api.telegram.org/botT/sendMessage', 'https://hook.example.com']); + // an OS notifier that is not installed is skipped quietly + expect(await sendEvent(e(), { os: true }, { os: () => false, platform: 'linux' })).toEqual([]); + }); +}); + +describe('watch and events commands', () => { + test('mcp: events_recent is a read tool that maps to events --json', () => { + const t = TOOLS.find(x => x.name === 'events_recent')!; + expect(t).toMatchObject({ write: false, network: false, command: ['events'] }); + expect(toArgv(t, { since: '24h', app: 'Demo', kind: 'rejected' }).argv).toEqual(['events', '--since', '24h', '--app', 'Demo', '--kind', 'rejected']); + }); +}); From 8b22e548be10bc68dea80380daafb127d61323b3 Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 21:42:53 +0700 Subject: [PATCH 123/344] storebound 0.8.31: version in package.json and every copy, CHANGELOG 0.8.31 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 281c98f..1c1dfb0 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.30", + "version": "0.8.31", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index b20e1f5..1ec203f 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.30", + "version": "0.8.31", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 659bc21..8bbad0a 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.30", + "version": "0.8.31", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index 844217e..1ad89fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +## 0.8.31 · 2026-10-22 + - **`storebound watch`**: store events for every app on the machine (rejected, approved, live, rollout halted, crash threshold, low or unanswered reviews), sent to ntfy (phone), Telegram, a webhook or an OS notification; runs as a loop (`--every 15m`) or `--once`; a PM2 recipe for a server is in docs/watch.md. `storebound events` and the MCP tool diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 36897a2..5ad15a1 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.30", + "version": "0.8.31", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 2a7d3ac..6f98514 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4096,7 +4096,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.30" +version = "0.8.31" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 7ca8059..20a0757 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.30" +version = "0.8.31" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index cee3801..efaf0ca 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.30", + "version": "0.8.31", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index e1192a7..5444ee7 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.30", + "version": "0.8.31", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index 90e2588..65a6780 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.30", + "version": "0.8.31", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From bd316723f50c91775c2ac820bba0164e50d4ceba Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 23:12:03 +0800 Subject: [PATCH 124/344] Desktop v2 design system (design.css tokens for both themes, ui/ds.tsx: PageHeader, Hero, Section, StatTile, Pipeline, StatusPill, EmptyState, Toolbar, Tabs, Dialog, tint and screenshot hooks), app shell: sidebar status dots, frosted top bar, app page Hero with screenshots and the two-store pipeline, pill tabs with blocker counts --- apps/desktop/src/App.tsx | 5 +- apps/desktop/src/design.css | 201 ++++++++++++++++ apps/desktop/src/main.tsx | 1 + apps/desktop/src/screens/AppView.tsx | 69 +++--- apps/desktop/src/screens/Portfolio.tsx | 136 +---------- apps/desktop/src/ui/ds.tsx | 319 +++++++++++++++++++++++++ 6 files changed, 559 insertions(+), 172 deletions(-) create mode 100644 apps/desktop/src/design.css create mode 100644 apps/desktop/src/ui/ds.tsx diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index a72750e..6538f00 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -23,6 +23,8 @@ import { type Command, Palette } from './ui/Palette'; import { ExportMenu, useExportItems, useRunExport } from './ui/Exports'; import { ErrorBoundary } from './ui/ErrorBoundary'; import { Toasts } from './ui/Toasts'; +import { worstTone } from './ui/ds'; +import { attention } from './lib/model'; const WS_ICON: Record = { apps: 'folder', accounts: 'building', ignored: 'eyeOff', dependencies: 'package', settings: 'settings' }; export const WS_KEY: Record = { apps: 'nav.apps', accounts: 'nav.accounts', ignored: 'nav.ignored', dependencies: 'nav.dependencies', settings: 'nav.settings' }; @@ -146,12 +148,13 @@ export function App({ onTheme }: { onTheme: () => void }) { const appItem = (a: UnifiedApp) => { const e = d.statusFor(a); const missing = !!a.project?.missing; + const tone = missing ? 'bad' : (worstTone(attention(a.key, a.name, e, d.liveFor(a))) ?? (e ? 'ok' : null)); const bad = missing ? 1 : (e?.errors.length ?? 0) + (e?.check?.problems.length ?? 0); return (
-
-
- {iosNow && <>{iosNow.version}} - {androidNow && <>{androidNow.version}} -
-
-
-
- {ios && } - {android && } -
-
+
+ + {e?.summary?.profile && app.project && {t(`profile.${e.summary.profile}` as 'profile.app')}} + {!app.project && } + + } + ids={<> + {iosNow && <>{iosNow.version}} + {androidNow && <>{androidNow.version}} + } + links={(ios || android) && <> + {ios && } + {android && } + } + all={all} ios={!!ios} android={!!android} next={l?.release.next?.version ?? null} + cta={nextStep({ project: !!app.project, att, all, next: l?.release.next?.version ?? null })} onCta={setTab} /> {!app.project && } {app.project?.storeboundPin && {t('app.pinNotice', { pin: app.project.storeboundPin, app: d.info?.version ?? '' })}} {app.project?.missing ? : <> -
- {tabs.map((x, i) => ( - - ))} +
+ { + const n = EDIT_TABS[x] ? ed.count(app.project?.id ?? app.target, EDIT_TABS[x]) : 0; + return { id: x, label: t(TAB_KEY[x]), icon: TAB_ICON[x], count: att.filter(a => a.tab === x && a.tone === 'bad').length, dot: n > 0, dotTitle: n ? t('ed.unsaved', { count: n }) : undefined }; + })} />
diff --git a/apps/desktop/src/screens/Portfolio.tsx b/apps/desktop/src/screens/Portfolio.tsx index b6e1a9e..41cc6f3 100644 --- a/apps/desktop/src/screens/Portfolio.tsx +++ b/apps/desktop/src/screens/Portfolio.tsx @@ -4,18 +4,20 @@ // version, crash rate, catalog parity, config check), grouped by studio; then what changed and what to fix first. import { plainError } from '../../../../cli/lib/google-errors'; import { BlockedProjectsNotice, blockedProjects } from '../ui/StoreError'; -import { type CSSProperties, type ReactNode, useEffect, useMemo, useState } from 'react'; -import { api, type AppStatus, newJob, reads, type RenderImage, type StoreRelease, type ToolResult } from '../api'; +import { type ReactNode, useEffect, useMemo, useState } from 'react'; +import { api, type AppStatus, newJob, type StoreRelease, type ToolResult } from '../api'; import { type Key, t } from '../i18n'; import { ago, pct, share } from '../lib/format'; import { filterSort, groupByStudio, type ListRow, type SortBy, studioCounts, type UnifiedApp } from '../lib/identity'; -import { type Attention, attention, healthSeries, type HealthSnapshot, hueOf, isError, laneOf, PLAY_THRESHOLDS, STAGES, storeNow, type Tone } from '../lib/model'; +import { type Attention, attention, healthSeries, type HealthSnapshot, isError, laneOf, PLAY_THRESHOLDS, STAGES, storeNow, type Tone } from '../lib/model'; import { type AppTab, useNav } from '../nav'; import type { IconName } from '../ui/icons'; import { useData } from '../store'; import { exportName, portfolioCsv } from '../lib/exports'; import { useExports } from '../ui/Exports'; import { Icon, StoreGlyph } from '../ui/icons'; +import { nextStep, Pipeline, tintStyle, useShots, useTint } from '../ui/ds'; +export { nextStep } from '../ui/ds'; import { AppIcon, Card, Chip, Empty, Kpi, Notice, PhaseChip, Seg, Skeleton, Sparkline, StudioMark } from '../ui/kit'; /** Tag of one app's offline config check. */ @@ -111,126 +113,6 @@ function releasesOf(l: AppStatus | undefined): StoreRelease[] { return l.release.all ?? [l.release.current?.ios, l.release.current?.android, l.release.next?.ios, l.release.next?.android].filter((x): x is StoreRelease => !!x); } -// Up to three phone screenshots of the app folder's rendered store art (`shots gallery`, then one `project.render` -// data: URL each), loaded once per window and one app at a time. No renders: an empty list (the card shows the icon). -const shotCache = new Map>(); -let shotChain: Promise = Promise.resolve(); -function loadShots(projectId: string): Promise { - const hit = shotCache.get(projectId); - if (hit) return hit; - const job = shotChain.then(async () => { - const r = await reads.renders(projectId).catch(() => null); - const res = r?.data; - if (!res) return []; - const v = res.variants.find(x => !x.id) ?? res.variants[0]; - const lang = v?.langs.find(l => l.lang === 'en' || l.lang.startsWith('en-')) ?? v?.langs[0]; - const rows = (lang?.rows ?? []).filter(row => !/feature|ipad|preview|tv|watch|mac|tablet/i.test(row.size) && row.tiles.some(x => x.kind === 'image')); - rows.sort((a, b) => (a.store === 'apple' ? 0 : 1) - (b.store === 'apple' ? 0 : 1)); - const files = (rows[0]?.tiles ?? []).filter(x => x.kind === 'image' && x.h >= x.w).slice(0, 3).map(x => x.src); - const out: string[] = []; - for (const file of files) { - const img = await api.call('project.render', projectId, { args: { file } }).catch(() => null); - if (img?.data?.dataUrl) out.push(img.data.dataUrl); - } - return out; - }).catch(() => [] as string[]); - shotChain = job; - shotCache.set(projectId, job); - return job; -} - -function useShots(projectId: string | null): string[] { - const [shots, setShots] = useState([]); - useEffect(() => { - if (!projectId) return; - let alive = true; - loadShots(projectId).then(s => { if (alive) setShots(s); }, () => {}); - return () => { alive = false; }; - }, [projectId]); - return shots; -} - -// The hue of an app icon (saturation-weighted mean colour), for the card's soft gradient; the name's hue without one. -const tintCache = new Map(); -function useTint(src: string | null, name: string): number { - const fallback = hueOf(name); - const [hue, setHue] = useState(() => (src ? tintCache.get(src) : undefined) ?? fallback); - useEffect(() => { - if (!src) { setHue(fallback); return; } - const cached = tintCache.get(src); - if (cached !== undefined) { setHue(cached); return; } - let alive = true; - const img = new Image(); - img.onload = () => { - try { - const c = document.createElement('canvas'); - c.width = c.height = 16; - const g = c.getContext('2d'); - if (!g) return; - g.drawImage(img, 0, 0, 16, 16); - const px = g.getImageData(0, 0, 16, 16).data; - let r = 0, gr = 0, b = 0, w = 0; - for (let i = 0; i < px.length; i += 4) { - const R = px[i]!, G = px[i + 1]!, B = px[i + 2]!, A = px[i + 3]! / 255; - const s = (Math.max(R, G, B) - Math.min(R, G, B)) / 255 * A; - r += R * s; gr += G * s; b += B * s; w += s; - } - if (w < 0.5) return; - r /= w; gr /= w; b /= w; - const mx = Math.max(r, gr, b), mn = Math.min(r, gr, b), d = mx - mn; - if (d < 1) return; - let h = mx === r ? ((gr - b) / d) % 6 : mx === gr ? (b - r) / d + 2 : (r - gr) / d + 4; - h = Math.round(h * 60 + 360) % 360; - tintCache.set(src, h); - if (alive) setHue(h); - } catch { /* keep the name's hue */ } - }; - img.src = src; - return () => { alive = false; }; - }, [src, fallback]); - return hue; -} - -interface Cta { text: string; tab: AppTab; icon: IconName; primary: boolean } - -/** The one next step of an app, from its state: blockers first, then the release that waits for a move. */ -export function nextStep(o: { project: boolean; att: Attention[]; all: StoreRelease[]; next: string | null }): Cta { - const bad = o.att.filter(a => a.tone === 'bad'); - if (bad.length) return { text: t('pf.ctaFix', { count: bad.length }), tab: bad[0]!.tab ?? 'checks', icon: 'alertCircle', primary: true }; - const rolling = o.all.find(r => r.phase === 'rollout' && r.fraction !== null && r.fraction < 1); - if (rolling) return { text: t('pf.ctaRollout', { share: share(rolling.fraction ?? 0) }), tab: 'releases', icon: 'rocket', primary: true }; - const approved = o.all.find(r => r.phase === 'approved'); - if (approved) return { text: t('pf.ctaRelease', { version: approved.version ?? '' }), tab: 'releases', icon: 'rocket', primary: true }; - const ready = o.all.find(r => r.phase === 'draft' || r.phase === 'testing'); - if (ready) return { text: t('pf.ctaSubmit', { version: ready.version ?? '' }), tab: 'releases', icon: 'send', primary: true }; - const review = o.all.find(r => r.phase === 'review' || r.phase === 'sent'); - if (review) return { text: t('pf.ctaReview', { version: review.version ?? '' }), tab: 'releases', icon: 'clock', primary: false }; - if (o.att.length) return { text: t('pf.ctaWarnings', { count: o.att.length }), tab: o.att[0]!.tab ?? 'checks', icon: 'alert', primary: false }; - if (o.project && !o.next) return { text: t('pf.ctaUpload'), tab: 'releases', icon: 'upload', primary: false }; - return { text: t('pf.ctaOpen'), tab: 'releases', icon: 'arrowRight', primary: false }; -} - -function Track({ store, all, on }: { store: 'ios' | 'android'; all: StoreRelease[]; on: boolean }) { - const { now, next } = storeNow(all, store); - const r = next ?? now; - const lane = laneOf(store, on ? r : null); - const name = store === 'ios' ? 'App Store' : 'Google Play'; - const state = !on ? t('app.notOnStore') : !r ? t('portfolio.noVersion') : `${r.version ?? ''} · ${t(`phase.${r.phase}` as Key)}${lane.share !== null && lane.share < 1 ? ` ${share(lane.share)}` : ''}`; - return ( -
- {store === 'ios' ? 'App Store' : 'Play'} - - {on && r ? `${r.version ?? ''}${lane.share !== null && lane.share < 1 ? ` · ${share(lane.share)}` : ''}` : '–'} -
- ); -} - function CardHealth({ c, android }: { c: { h: HealthSnapshot; at: string } | null | undefined; android: boolean }) { const play = c?.h.play; if (!android || !c || !play || isError(play)) { @@ -260,7 +142,7 @@ function AppCard({ r, icon, health, studio }: { r: CardRow; icon: string | null; const cta = nextStep({ project: !!app.project, att, all, next }); const name = e?.app?.name && app.project ? e.app.name : app.name; const go = (tab: AppTab) => nav.go({ screen: 'app', appId: app.key, tab }); - const style = { '--tint-h': String(hue) } as CSSProperties; + const style = tintStyle(hue); return (
{studio} -
- - - -
+
diff --git a/apps/desktop/src/ui/ds.tsx b/apps/desktop/src/ui/ds.tsx new file mode 100644 index 0000000..563e500 --- /dev/null +++ b/apps/desktop/src/ui/ds.tsx @@ -0,0 +1,319 @@ +// Design system v2 (styles in src/design.css, guide in docs/drafts/desktop-v2/SYSTEM.md): the store-like language of +// the portfolio home as reusable parts. PageHeader, Hero (app hero with screenshots, two-store pipeline, next step), +// Section, StatTile, Pipeline, StatusPill, EmptyState, Tabs, Toolbar, Dialog, plus the per-app tint (useTint / tintStyle) +// and the rendered-screenshot loader (useShots) the cards and the hero share. +import { type CSSProperties, type KeyboardEvent, type ReactNode, useEffect, useId, useRef, useState } from 'react'; +import { api, reads, type RenderImage, type StoreRelease, type ToolResult } from '../api'; +import { type Key, t } from '../i18n'; +import { share } from '../lib/format'; +import { type Attention, hueOf, laneOf, STAGES, storeNow, type Tone } from '../lib/model'; +import type { AppTab } from '../nav'; +import { Icon, type IconName, StoreGlyph } from './icons'; +import { AppIcon } from './kit'; + +// ---- per-app tint ---- + +const tintCache = new Map(); +/** The hue of an app icon (saturation-weighted mean colour); the name's hue without an icon or while it loads. */ +export function useTint(src: string | null | undefined, name: string): number { + const fallback = hueOf(name); + const [hue, setHue] = useState(() => (src ? tintCache.get(src) : undefined) ?? fallback); + useEffect(() => { + if (!src) { setHue(fallback); return; } + const cached = tintCache.get(src); + if (cached !== undefined) { setHue(cached); return; } + let alive = true; + const img = new Image(); + img.onload = () => { + try { + const c = document.createElement('canvas'); + c.width = c.height = 16; + const g = c.getContext('2d'); + if (!g) return; + g.drawImage(img, 0, 0, 16, 16); + const px = g.getImageData(0, 0, 16, 16).data; + let r = 0, gr = 0, b = 0, w = 0; + for (let i = 0; i < px.length; i += 4) { + const R = px[i]!, G = px[i + 1]!, B = px[i + 2]!, A = px[i + 3]! / 255; + const s = (Math.max(R, G, B) - Math.min(R, G, B)) / 255 * A; + r += R * s; gr += G * s; b += B * s; w += s; + } + if (w < 0.5) return; + r /= w; gr /= w; b /= w; + const mx = Math.max(r, gr, b), mn = Math.min(r, gr, b), d = mx - mn; + if (d < 1) return; + let h = mx === r ? ((gr - b) / d) % 6 : mx === gr ? (b - r) / d + 2 : (r - gr) / d + 4; + h = Math.round(h * 60 + 360) % 360; + tintCache.set(src, h); + if (alive) setHue(h); + } catch { /* keep the name's hue */ } + }; + img.src = src; + return () => { alive = false; }; + }, [src, fallback]); + return hue; +} + +/** Style that tints a subtree: every `.ds-tinted` / `--tint` rule below it uses this hue. */ +export const tintStyle = (hue: number): CSSProperties => ({ '--tint-h': String(hue) } as CSSProperties); + +// ---- rendered store screenshots ---- + +// Up to three phone screenshots of the app folder's rendered store art (`shots gallery`, then one `project.render` +// data: URL each), loaded once per window and one app at a time. No renders: an empty list. +const shotCache = new Map>(); +let shotChain: Promise = Promise.resolve(); +function loadShots(projectId: string, max: number): Promise { + const k = `${projectId}#${max}`; + const hit = shotCache.get(k); + if (hit) return hit; + const job = shotChain.then(async () => { + const r = await reads.renders(projectId).catch(() => null); + const res = r?.data; + if (!res) return []; + const v = res.variants.find(x => !x.id) ?? res.variants[0]; + const lang = v?.langs.find(l => l.lang === 'en' || l.lang.startsWith('en-')) ?? v?.langs[0]; + const rows = (lang?.rows ?? []).filter(row => !/feature|ipad|preview|tv|watch|mac|tablet/i.test(row.size) && row.tiles.some(x => x.kind === 'image')); + rows.sort((a, b) => (a.store === 'apple' ? 0 : 1) - (b.store === 'apple' ? 0 : 1)); + const files = (rows[0]?.tiles ?? []).filter(x => x.kind === 'image' && x.h >= x.w).slice(0, max).map(x => x.src); + const out: string[] = []; + for (const file of files) { + const img = await api.call('project.render', projectId, { args: { file } }).catch(() => null); + if (img?.data?.dataUrl) out.push(img.data.dataUrl); + } + return out; + }).catch(() => [] as string[]); + shotChain = job; + shotCache.set(k, job); + return job; +} + +/** Rendered phone screenshots of an app folder (none for a store-only app or before the first render). */ +export function useShots(projectId: string | null | undefined, max = 3): string[] { + const [shots, setShots] = useState([]); + useEffect(() => { + if (!projectId) { setShots([]); return; } + let alive = true; + loadShots(projectId, max).then(s => { if (alive) setShots(s); }, () => {}); + return () => { alive = false; }; + }, [projectId, max]); + return shots; +} + +// ---- next step ---- + +export interface Cta { text: string; tab: AppTab; icon: IconName; primary: boolean } + +/** The one next step of an app, from its state: blockers first, then the release that waits for a move. */ +export function nextStep(o: { project: boolean; att: Attention[]; all: StoreRelease[]; next: string | null }): Cta { + const bad = o.att.filter(a => a.tone === 'bad'); + if (bad.length) return { text: t('pf.ctaFix', { count: bad.length }), tab: bad[0]!.tab ?? 'checks', icon: 'alertCircle', primary: true }; + const rolling = o.all.find(r => r.phase === 'rollout' && r.fraction !== null && r.fraction < 1); + if (rolling) return { text: t('pf.ctaRollout', { share: share(rolling.fraction ?? 0) }), tab: 'releases', icon: 'rocket', primary: true }; + const approved = o.all.find(r => r.phase === 'approved'); + if (approved) return { text: t('pf.ctaRelease', { version: approved.version ?? '' }), tab: 'releases', icon: 'rocket', primary: true }; + const ready = o.all.find(r => r.phase === 'draft' || r.phase === 'testing'); + if (ready) return { text: t('pf.ctaSubmit', { version: ready.version ?? '' }), tab: 'releases', icon: 'send', primary: true }; + const review = o.all.find(r => r.phase === 'review' || r.phase === 'sent'); + if (review) return { text: t('pf.ctaReview', { version: review.version ?? '' }), tab: 'releases', icon: 'clock', primary: false }; + if (o.att.length) return { text: t('pf.ctaWarnings', { count: o.att.length }), tab: o.att[0]!.tab ?? 'checks', icon: 'alert', primary: false }; + if (o.project && !o.next) return { text: t('pf.ctaUpload'), tab: 'releases', icon: 'upload', primary: false }; + return { text: t('pf.ctaOpen'), tab: 'releases', icon: 'arrowRight', primary: false }; +} + +/** Worst tone of an app's attention list (the sidebar dot); null when nothing needs a look. */ +export function worstTone(att: Attention[]): Tone | null { + if (att.some(a => a.tone === 'bad')) return 'bad'; + if (att.some(a => a.tone === 'warn')) return 'warn'; + return att.length ? 'info' : null; +} + +// ---- Pipeline (Build -> Testing -> Review -> Live -> Rollout, one lane per store) ---- + +export function PipelineTrack({ store, all, on }: { store: 'ios' | 'android'; all: StoreRelease[]; on: boolean }) { + const { now, next } = storeNow(all, store); + const r = next ?? now; + const lane = laneOf(store, on ? r : null); + const name = store === 'ios' ? 'App Store' : 'Google Play'; + const state = !on ? t('app.notOnStore') : !r ? t('portfolio.noVersion') : `${r.version ?? ''} · ${t(`phase.${r.phase}` as Key)}${lane.share !== null && lane.share < 1 ? ` ${share(lane.share)}` : ''}`; + return ( +
+ {store === 'ios' ? 'App Store' : 'Play'} + + {on && r ? `${r.version ?? ''}${lane.share !== null && lane.share < 1 ? ` · ${share(lane.share)}` : ''}` : '–'} +
+ ); +} + +/** Both store lanes under one stage header. Needs a tint (`--tint-h`) on an ancestor. */ +export function Pipeline({ all, ios, android, size = 'md' }: { all: StoreRelease[]; ios: boolean; android: boolean; size?: 'md' | 'lg' }) { + return ( +
+ + + +
+ ); +} + +// ---- page parts ---- + +/** Page title row: optional eyebrow, a big title, one line under it, actions on the right. */ +export function PageHeader({ title, subtitle, eyebrow, actions, icon }: { title: ReactNode; subtitle?: ReactNode; eyebrow?: ReactNode; actions?: ReactNode; icon?: IconName }) { + return ( +
+
+ {eyebrow &&

{eyebrow}

} +

{icon && }{title}

+ {subtitle &&

{subtitle}

} +
+ {actions &&
{actions}
} +
+ ); +} + +/** App hero: screenshots strip, big icon, name, ids, store links, the two-store pipeline and the next step. */ +export function Hero({ name, icon, projectId, ids, badges, links, all, ios, android, cta, onCta, next, children }: { + name: string; icon: string | null; projectId: string | null; ids?: ReactNode; badges?: ReactNode; links?: ReactNode; + all: StoreRelease[]; ios: boolean; android: boolean; cta?: Cta | null; onCta?: (tab: AppTab) => void; next?: string | null; children?: ReactNode; +}) { + const hue = useTint(icon, name); + const shots = useShots(projectId, 4); + return ( +
+
+
+ +
+

{name}

{badges}
+ {ids &&
{ids}
} + {links &&
{links}
} +
+
+
+ +
+
{t('pf.next')}{next ?? '–'}
+ {cta && } +
+
+ {children} +
+ +
+ ); +} + +/** Section v2: a titled block. `plain` drops the surface (content sits on the page). */ +export function Section({ title, icon, sub, actions, children, plain, pad = true, id, className = '' }: { title?: ReactNode; icon?: IconName; sub?: ReactNode; actions?: ReactNode; children: ReactNode; plain?: boolean; pad?: boolean; id?: string; className?: string }) { + const hid = useId(); + return ( +
+ {title !== undefined && ( +
+

{icon && }{title}

{sub &&

{sub}

}
+ {actions &&
{actions}
} +
+ )} + {pad ?
{children}
: children} +
+ ); +} + +/** Big number tile: value, label, optional delta (+ is good unless `invert`) and a sub line. */ +export function StatTile({ label, value, delta, invert, sub, icon, tone, onClick }: { label: string; value: ReactNode; delta?: number | null; invert?: boolean; sub?: ReactNode; icon?: IconName; tone?: Tone; onClick?: () => void }) { + const good = delta == null || delta === 0 ? null : (delta > 0) !== !!invert; + const body = ( + <> + {icon && }{label} + {value} + {(delta != null || sub) && + {delta != null && {delta > 0 ? '+' : ''}{delta}} + {sub && {sub}} + } + + ); + const cls = `ds-stat${tone ? ` tone-${tone}` : ''}`; + return onClick ? :
{body}
; +} + +/** Status pill: a tone dot and text; `solid` for the one state that matters on a row. */ +export function StatusPill({ tone = 'neutral', children, icon, solid, title }: { tone?: Tone; children: ReactNode; icon?: IconName; solid?: boolean; title?: string }) { + return {icon ? : }{children}; +} + +/** Empty state without illustration: icon, one line, an optional action. */ +export function EmptyState({ icon = 'sparkle', children, action, tone }: { icon?: IconName; children: ReactNode; action?: ReactNode; tone?: Tone }) { + return ( +
+ +

{children}

+ {action} +
+ ); +} + +/** Toolbar row: search, filters, then right-aligned controls after a ``. */ +export function Toolbar({ label, children }: { label: string; children: ReactNode }) { + return
{children}
; +} + +export interface TabItem { id: T; label: string; icon?: IconName; count?: number | null; dot?: boolean; dotTitle?: string } + +/** Pill tabs with icons and counts; arrows / Home / End move between them (roving tabindex). */ +export function Tabs({ items, value, onChange, label, panelId = 'tabpanel' }: { items: TabItem[]; value: T; onChange: (v: T) => void; label: string; panelId?: string }) { + const refs = useRef<(HTMLButtonElement | null)[]>([]); + const onKey = (ev: KeyboardEvent) => { + const i = items.findIndex(x => x.id === value); + const j = ev.key === 'ArrowRight' ? i + 1 : ev.key === 'ArrowLeft' ? i - 1 : ev.key === 'Home' ? 0 : ev.key === 'End' ? items.length - 1 : null; + if (j === null) return; + ev.preventDefault(); + const n = (j + items.length) % items.length; + onChange(items[n]!.id); + refs.current[n]?.focus(); + }; + return ( +
+ {items.map((x, i) => ( + + ))} +
+ ); +} + +/** Dialog v2: modal panel with a title, body and footer actions; Escape and the scrim close it, focus moves in. */ +export function Dialog({ title, icon, children, actions, onClose, wide }: { title: ReactNode; icon?: IconName; children: ReactNode; actions?: ReactNode; onClose: () => void; wide?: boolean }) { + const root = useRef(null); + const hid = useId(); + useEffect(() => { + const prev = document.activeElement as HTMLElement | null; + root.current?.focus(); + return () => { prev?.focus?.(); }; + }, []); + return ( +
{ if (e.target === e.currentTarget) onClose(); }}> +
{ if (e.key === 'Escape') { e.stopPropagation(); onClose(); } }}> +
+

{icon && }{title}

+ +
+
{children}
+ {actions &&
{actions}
} +
+
+ ); +} From d3d31d6c1259365a110efdb9294cf69cc197511a Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 23:18:30 +0800 Subject: [PATCH 125/344] Node: JSON configs are read as data, not imported (store-only apps failed under npx: needs an import attribute); test, pitfall 105 --- CHANGELOG.md | 2 ++ cli/lib/rt.ts | 3 +++ skills/store-pitfalls/SKILL.md | 7 +++++++ tests/config-json-node.test.ts | 12 ++++++++++++ 4 files changed, 24 insertions(+) create mode 100644 tests/config-json-node.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 844217e..630986b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- Node: a `storebound.config.json` (and every store-only app) loads again; it needed an import attribute. Pitfall 105. + - **`storebound watch`**: store events for every app on the machine (rejected, approved, live, rollout halted, crash threshold, low or unanswered reviews), sent to ntfy (phone), Telegram, a webhook or an OS notification; runs as a loop (`--every 15m`) or `--once`; a PM2 recipe for a server is in docs/watch.md. `storebound events` and the MCP tool diff --git a/cli/lib/rt.ts b/cli/lib/rt.ts index 9b43cc7..d323d45 100644 --- a/cli/lib/rt.ts +++ b/cli/lib/rt.ts @@ -82,6 +82,9 @@ export const importPath = (path: string): Promise => import(pathToFileURL(p */ // eslint-disable-next-line @typescript-eslint/no-explicit-any export async function importConfigModule(path: string): Promise { + // a JSON config is read, not imported: Node refuses a JSON import without `with { type: 'json' }` (every store-only + // app of `storebound watch` on a server failed; pitfall 105) + if (/\.json$/i.test(path)) return { default: JSON.parse(readFileSync(path, 'utf8')) }; if (isBun || !/\.[cm]?ts$/.test(path)) return importPath(path); try { return await withoutTypeStripWarning(() => importPath(path)); diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index c44253a..a88eb70 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1265,3 +1265,10 @@ that fails without the fix (see CONTRIBUTING.md). - **Guard:** `iapLocalizationChanges` / `iapAttributeChanges` / `availabilityChange` (`cli/apple/iap.ts`), the subscription helpers in `cli/lib/subscriptions.ts`, `planAppInfo` / `reviewDetailDiff`, `campaignDiff`, `winBackDiff`, `eventAttrDiff`; tests `apple-iap-drift`, `subscriptions-drift`, `appinfo-drift`, `misc-drift`. + +## 105. `storebound watch` on a server read no app: "needs an import attribute of type: json" +- **Symptom:** on Node (npx, a server), every store-only app failed with `Module ".../storebound.config.json" needs an + import attribute of "type: json"`; on Bun it worked. +- **Cause:** a JSON config (store-only apps get one generated) was loaded with a bare dynamic import, which Node refuses. +- **Do:** update storebound. +- **Guard:** `importConfigModule` in `cli/lib/rt.ts` reads JSON configs as data (`tests/config-json-node.test.ts`). diff --git a/tests/config-json-node.test.ts b/tests/config-json-node.test.ts new file mode 100644 index 0000000..b2cd820 --- /dev/null +++ b/tests/config-json-node.test.ts @@ -0,0 +1,12 @@ +// A storebound.config.json loads without an import attribute (Node refuses a bare JSON import; pitfall 105). +import { expect, test } from 'bun:test'; +import { mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { importConfigModule } from '../cli/lib/rt'; + +test('importConfigModule reads a JSON config as data', async () => { + const f = join(mkdtempSync(join(tmpdir(), 'sb-json-')), 'storebound.config.json'); + writeFileSync(f, JSON.stringify({ app: { name: 'Demo' }, play: { packageName: 'com.example.demo' } })); + expect((await importConfigModule(f)).default.play.packageName).toBe('com.example.demo'); +}); From 5a892af3d62fec017466825821b7bd7ea973c80d Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 22:19:38 +0700 Subject: [PATCH 126/344] storebound 0.8.32: version in package.json and every copy, CHANGELOG 0.8.32 section --- .claude-plugin/marketplace.json | 2 +- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- CHANGELOG.md | 2 ++ apps/desktop/package.json | 2 +- apps/desktop/src-tauri/Cargo.lock | 2 +- apps/desktop/src-tauri/Cargo.toml | 2 +- apps/desktop/src-tauri/tauri.conf.json | 2 +- gemini-extension.json | 2 +- package.json | 2 +- 10 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 1c1dfb0..a5d507f 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "storebound", "source": ".", "description": "Take a mobile app or game from nothing to Submit for review on both stores: skills for every store step and questionnaire plus the storebound CLI and MCP server.", - "version": "0.8.31", + "version": "0.8.32", "category": "development", "tags": [ "mobile", diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 1ec203f..3667d8c 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.31", + "version": "0.8.32", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 8bbad0a..e616cbf 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.31", + "version": "0.8.32", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "author": { "name": "CRTkafa" diff --git a/CHANGELOG.md b/CHANGELOG.md index b1e9a2c..38e61dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ ## Unreleased +## 0.8.32 · 2026-10-22 + - Node: a `storebound.config.json` (and every store-only app) loads again; it needed an import attribute. Pitfall 105. ## 0.8.31 · 2026-10-22 diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 5ad15a1..e422434 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@storebound/desktop", - "version": "0.8.31", + "version": "0.8.32", "private": true, "license": "MIT", "type": "module", diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 6f98514..ce2877d 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -4096,7 +4096,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "storebound-desktop" -version = "0.8.31" +version = "0.8.32" dependencies = [ "base64 0.22.1", "getrandom 0.3.4", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 20a0757..83c6b39 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "storebound-desktop" -version = "0.8.31" +version = "0.8.32" description = "storebound desktop: every game's releases on both stores in one window" license = "MIT" edition = "2021" diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index efaf0ca..338db1b 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "storebound", "mainBinaryName": "storebound-desktop", - "version": "0.8.31", + "version": "0.8.32", "identifier": "dev.storebound.desktop", "build": { "frontendDist": "../dist", diff --git a/gemini-extension.json b/gemini-extension.json index 5444ee7..700067d 100644 --- a/gemini-extension.json +++ b/gemini-extension.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.31", + "version": "0.8.32", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every questionnaire (Data safety, App access and demo accounts, account deletion, IARC, target audience, ads, App Privacy, age rating, export compliance), privacy, icons, screenshots and previews, validate, TestFlight, release management, and after launch: crash vitals, review replies, price sheets, store analytics, Product Page Optimization. Agent Skills plus a Bun CLI and MCP server (storebound); you press Submit. CRTkafa's own toolchain, open-sourced.", "contextFileName": "GEMINI.md", "mcpServers": { diff --git a/package.json b/package.json index 65a6780..e8acad0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "storebound", - "version": "0.8.31", + "version": "0.8.32", "description": "Take a mobile app or game from nothing to Submit for review on Google Play and the App Store: app records, listings in every language, in-app products and subscriptions with regional prices, every store questionnaire (incl. account deletion and App Review demo accounts), privacy, icons, screenshots and previews, TestFlight. After launch: crash vitals, review replies, price sheets, analytics and Product Page Optimization. One config, a CLI (Node 20+ or Bun), an MCP server and Agent Skills for your AI coding agent.", "license": "MIT", "author": "CRTkafa", From f131de9df2d3c698068a32a26f40b5afa4c9db8b Mon Sep 17 00:00:00 2001 From: CRT Date: Thu, 22 Oct 2026 23:31:22 +0800 Subject: [PATCH 127/344] Desktop v2 screens: releases (store cards, stage stepper, rollout ring), submit checklist, TestFlight cards; listings as store pages with completeness, framed screenshots with issue badges, product cards, price matrix with gap shading; health tiles and issue cards, store-style review feed with rating distribution, growth funnel, readiness score with fix-first, tools grid, store-info sheet; settings, accounts, folders, dependencies and onboarding in the v2 language --- apps/desktop/src/i18n/en.ts | 61 ++++ apps/desktop/src/i18n/tr.ts | 61 ++++ apps/desktop/src/screens/Accounts.tsx | 41 ++- apps/desktop/src/screens/AppFolders.tsx | 51 +-- apps/desktop/src/screens/Dependencies.tsx | 43 ++- apps/desktop/src/screens/Ignored.tsx | 21 +- apps/desktop/src/screens/Onboarding.tsx | 9 +- apps/desktop/src/screens/Settings.tsx | 58 +-- .../src/screens/editors/AppInfoEditor.tsx | 33 +- .../desktop/src/screens/editors/ArtEditor.tsx | 20 +- .../src/screens/editors/CatalogEditor.tsx | 26 +- .../src/screens/editors/ListingEditor.tsx | 47 ++- .../screens/editors/StoreListingEditor.tsx | 20 +- .../desktop/src/screens/editors/TabEditor.tsx | 5 +- .../src/screens/editors/TestFlightEditor.tsx | 15 +- apps/desktop/src/screens/tabs/AppInfo.tsx | 80 +++-- apps/desktop/src/screens/tabs/Art.tsx | 32 +- apps/desktop/src/screens/tabs/Catalog.tsx | 83 +++-- apps/desktop/src/screens/tabs/Checks.tsx | 214 +++++++---- apps/desktop/src/screens/tabs/Growth.tsx | 121 ++++--- apps/desktop/src/screens/tabs/Health.tsx | 268 +++++++------- apps/desktop/src/screens/tabs/Listings.tsx | 77 ++-- apps/desktop/src/screens/tabs/LiveArt.tsx | 18 +- apps/desktop/src/screens/tabs/Prices.tsx | 71 ++-- apps/desktop/src/screens/tabs/Releases.tsx | 135 ++++--- apps/desktop/src/screens/tabs/Reviews.tsx | 201 ++++++----- apps/desktop/src/screens/tabs/Submit.tsx | 334 +++++++++++------- apps/desktop/src/screens/tabs/TestFlight.tsx | 165 +++++---- apps/desktop/src/screens/tabs/Tools.tsx | 84 +++-- apps/desktop/src/styles/accounts.css | 26 ++ apps/desktop/src/styles/appinfo.css | 45 +++ apps/desktop/src/styles/art.css | 38 ++ apps/desktop/src/styles/catalog.css | 29 ++ apps/desktop/src/styles/checks.css | 76 ++++ apps/desktop/src/styles/deps.css | 20 ++ apps/desktop/src/styles/folders.css | 22 ++ apps/desktop/src/styles/growth.css | 37 ++ apps/desktop/src/styles/health.css | 79 +++++ apps/desktop/src/styles/listings.css | 36 ++ apps/desktop/src/styles/onboarding.css | 33 ++ apps/desktop/src/styles/prices.css | 17 + apps/desktop/src/styles/releases.css | 94 +++++ apps/desktop/src/styles/reviews.css | 81 +++++ apps/desktop/src/styles/settings.css | 37 ++ apps/desktop/src/styles/submit.css | 60 ++++ apps/desktop/src/styles/testflight.css | 64 ++++ apps/desktop/src/styles/tools.css | 48 +++ 47 files changed, 2309 insertions(+), 927 deletions(-) create mode 100644 apps/desktop/src/styles/accounts.css create mode 100644 apps/desktop/src/styles/appinfo.css create mode 100644 apps/desktop/src/styles/art.css create mode 100644 apps/desktop/src/styles/catalog.css create mode 100644 apps/desktop/src/styles/checks.css create mode 100644 apps/desktop/src/styles/deps.css create mode 100644 apps/desktop/src/styles/folders.css create mode 100644 apps/desktop/src/styles/growth.css create mode 100644 apps/desktop/src/styles/health.css create mode 100644 apps/desktop/src/styles/listings.css create mode 100644 apps/desktop/src/styles/onboarding.css create mode 100644 apps/desktop/src/styles/prices.css create mode 100644 apps/desktop/src/styles/releases.css create mode 100644 apps/desktop/src/styles/reviews.css create mode 100644 apps/desktop/src/styles/settings.css create mode 100644 apps/desktop/src/styles/submit.css create mode 100644 apps/desktop/src/styles/testflight.css create mode 100644 apps/desktop/src/styles/tools.css diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index f989257..29d0984 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -817,6 +817,19 @@ export const en = { 'set.unmute': 'Unmute ({until})', 'set.muted': 'Muted until {until}', 'set.clickNote': "Clicking a notification does not open the app on desktop; the next time you open the window from the tray, it goes to that app's Releases tab.", + 'v2cfg.workspace': 'Workspace', + 'v2cfg.studios': 'Studios', + 'v2cfg.accounts': 'Store accounts', + 'v2cfg.perStore': '{play} Google Play · {apple} App Store', + 'v2cfg.keysWork': 'Keys working', + 'v2cfg.keysFailing': 'Keys failing', + 'v2cfg.depsFound': 'Tools found', + 'v2cfg.depsNeeds': 'Need attention', + 'v2cfg.depsInApp': 'In app data', + 'v2cfg.depsInAppSub': 'downloaded by storebound', + 'v2cfg.needs': 'needs {version}', + 'v2cfg.stepOf': 'Step {n} of {total}', + 'v2cfg.progress': 'Setup progress', 'set.lead': 'Studios, accounts, store reads, the offline cache, language, theme, notifications and more. Everything stays on this computer.', 'set.sections': 'Settings sections', 'set.studios': 'Studios & accounts', @@ -1163,6 +1176,14 @@ export const en = { 'art.render': 'Render {lang}', 'art.notThere': 'Not there yet', 'art.count': '{count} files', + 'v2lst.preview': 'Store preview', + 'v2lst.noSub': 'No subtitle yet', + 'v2lst.noDesc': 'No description yet', + 'v2lst.more': 'more', + 'v2lst.ready': 'Ready', + 'v2lst.toFix': '{count} to fix', + 'v2lst.issues': '{count} issues', + 'v2lst.issues_one': '1 issue', 'art.count_one': '1 file', 'art.open': 'Open {name}', 'art.tooBig': 'too big to preview', @@ -1852,6 +1873,26 @@ export const en = { 'tools.g.ads': 'Apple Ads', 'tools.g.flows': 'Workflows and AI tools', 'tools.count': '{count} commands', + 'v2ins.hStartup': 'Launch time', + 'v2ins.hStartupSub': 'App Store diagnostics · version {version}', + 'v2ins.rvOpen': 'Unanswered', + 'v2ins.gFunnel': 'Store funnel', + 'v2ins.gVsPrev': '% vs the {count} days before', + 'v2ins.gPts': 'points vs the {count} days before', + 'v2ins.cScore': 'Store readiness', + 'v2ins.cScoreSub': '{ok} of {total} checks pass', + 'v2ins.cReady': 'Ready to submit', + 'v2ins.cBlocked': '{count} blockers to fix', + 'v2ins.cNotRun': 'Not checked yet', + 'v2ins.cBlockers': 'Blockers', + 'v2ins.cWarnings': 'Warnings', + 'v2ins.cPassedN': 'Passed', + 'v2ins.cFixFirst': 'Fix first', + 'v2ins.cPassed': 'Passed checks ({count})', + 'v2ins.cAccepted': 'Accepted risks ({count})', + 'v2ins.aiSheet': 'Store info', + 'v2ins.aiOpen': 'Open questions', + 'v2ins.aiNone': 'None', 'tools.count_one': '1 command', 'tools.show': 'Show', 'tools.hide': 'Hide', @@ -1947,4 +1988,24 @@ export const en = { 'pf.note': "Note", 'pf.fixIn': "Fix in {tab}", 'pf.openTab': "Open {tab}", + 'v2rel.version': "Version", + 'v2rel.stages': "{store} release stages", + 'v2rel.ofUsers': "of users get this version", + 'v2rel.versions': "{count} versions", + 'v2rel.ready': "Ready", + 'v2rel.blocked': "Blocked", + 'v2rel.todo': "To do", + 'v2rel.attention': "Check", + 'v2rel.readyCount': "{done} of {total} steps ready", + 'v2rel.steps': "Steps to send for review", + 'v2rel.stepRead': "Store state", + 'v2rel.stepNoOpen': "Nothing else in review", + 'v2rel.stepBuild': "Pick the build", + 'v2rel.stepVersion': "Version to send", + 'v2rel.stepSend': "Submit for review", + 'v2rel.stepCode': "Pick the versionCode", + 'v2rel.tfGroups': "Beta groups", + 'v2rel.tfInGroups': "in {count} groups", + 'v2rel.tfSplit': "{internal} internal · {external} external", + 'v2rel.tfUsable': "Ready to test", } as const; diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index 0fc5ff5..4219477 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -819,6 +819,19 @@ export const tr: Record = { 'set.unmute': 'Sesi aç ({until})', 'set.muted': '{until} saatine kadar sessiz', 'set.clickNote': 'Masaüstünde bildirime tıklamak uygulamayı açmaz; pencereyi bir sonraki sefer tepsiden açtığınızda o uygulamanın Yayınlar sekmesine gider.', + 'v2cfg.workspace': 'Çalışma alanı', + 'v2cfg.studios': 'Stüdyolar', + 'v2cfg.accounts': 'Mağaza hesapları', + 'v2cfg.perStore': '{play} Google Play · {apple} App Store', + 'v2cfg.keysWork': 'Çalışan anahtarlar', + 'v2cfg.keysFailing': 'Sorunlu anahtarlar', + 'v2cfg.depsFound': 'Bulunan araçlar', + 'v2cfg.depsNeeds': 'İlgi bekleyen', + 'v2cfg.depsInApp': 'Uygulama verisinde', + 'v2cfg.depsInAppSub': 'storebound indirdi', + 'v2cfg.needs': '{version} gerekli', + 'v2cfg.stepOf': 'Adım {n} / {total}', + 'v2cfg.progress': 'Kurulum ilerlemesi', 'set.lead': 'Stüdyolar, hesaplar, mağaza okumaları, çevrimdışı önbellek, dil, tema, bildirimler ve dahası. Hepsi bu bilgisayarda kalır.', 'set.sections': 'Ayar bölümleri', 'set.studios': 'Stüdyolar ve hesaplar', @@ -1165,6 +1178,14 @@ export const tr: Record = { 'art.render': '{lang} oluştur', 'art.notThere': 'Henüz yok', 'art.count': '{count} dosya', + 'v2lst.preview': 'Mağaza önizlemesi', + 'v2lst.noSub': 'Henüz alt başlık yok', + 'v2lst.noDesc': 'Henüz açıklama yok', + 'v2lst.more': 'devamı', + 'v2lst.ready': 'Hazır', + 'v2lst.toFix': '{count} düzeltilecek', + 'v2lst.issues': '{count} sorun', + 'v2lst.issues_one': '1 sorun', 'art.count_one': '1 dosya', 'art.open': '{name} aç', 'art.tooBig': 'önizleme için çok büyük', @@ -1854,6 +1875,26 @@ export const tr: Record = { 'tools.g.ads': 'Apple Ads', 'tools.g.flows': 'İş akışları ve yapay zekâ araçları', 'tools.count': '{count} komut', + 'v2ins.hStartup': 'Açılış süresi', + 'v2ins.hStartupSub': 'App Store tanılamaları · sürüm {version}', + 'v2ins.rvOpen': 'Yanıtsız', + 'v2ins.gFunnel': 'Mağaza hunisi', + 'v2ins.gVsPrev': 'önceki {count} güne göre %', + 'v2ins.gPts': 'önceki {count} güne göre puan', + 'v2ins.cScore': 'Mağaza hazırlığı', + 'v2ins.cScoreSub': '{total} kontrolden {ok} tanesi geçiyor', + 'v2ins.cReady': 'Göndermeye hazır', + 'v2ins.cBlocked': 'Düzeltilecek {count} engel', + 'v2ins.cNotRun': 'Henüz kontrol edilmedi', + 'v2ins.cBlockers': 'Engeller', + 'v2ins.cWarnings': 'Uyarılar', + 'v2ins.cPassedN': 'Geçti', + 'v2ins.cFixFirst': 'Önce bunları düzelt', + 'v2ins.cPassed': 'Geçen kontroller ({count})', + 'v2ins.cAccepted': 'Kabul edilen riskler ({count})', + 'v2ins.aiSheet': 'Mağaza bilgileri', + 'v2ins.aiOpen': 'Açık sorular', + 'v2ins.aiNone': 'Yok', 'tools.count_one': '1 komut', 'tools.show': 'Göster', 'tools.hide': 'Gizle', @@ -1949,4 +1990,24 @@ export const tr: Record = { 'pf.note': "Not", 'pf.fixIn': "{tab} sekmesinde düzelt", 'pf.openTab': "{tab} sekmesini aç", + 'v2rel.version': "Sürüm", + 'v2rel.stages': "{store} yayın aşamaları", + 'v2rel.ofUsers': "kullanıcı bu sürümü alıyor", + 'v2rel.versions': "{count} sürüm", + 'v2rel.ready': "Hazır", + 'v2rel.blocked': "Engelli", + 'v2rel.todo': "Yapılacak", + 'v2rel.attention': "Kontrol et", + 'v2rel.readyCount': "{total} adımın {done} tanesi hazır", + 'v2rel.steps': "İncelemeye gönderme adımları", + 'v2rel.stepRead': "Mağaza durumu", + 'v2rel.stepNoOpen': "İncelemede başka gönderim yok", + 'v2rel.stepBuild': "Build'i seç", + 'v2rel.stepVersion': "Gönderilecek sürüm", + 'v2rel.stepSend': "İncelemeye gönder", + 'v2rel.stepCode': "versionCode'u seç", + 'v2rel.tfGroups': "Beta grupları", + 'v2rel.tfInGroups': "{count} grupta", + 'v2rel.tfSplit': "{internal} dahili · {external} harici", + 'v2rel.tfUsable': "Teste hazır", }; diff --git a/apps/desktop/src/screens/Accounts.tsx b/apps/desktop/src/screens/Accounts.tsx index f9412b7..bd79022 100644 --- a/apps/desktop/src/screens/Accounts.tsx +++ b/apps/desktop/src/screens/Accounts.tsx @@ -10,7 +10,9 @@ import { ago } from '../lib/format'; import { withIgnored } from '../lib/identity'; import { type AccountHealth, useData } from '../store'; import { Icon, StoreGlyph } from '../ui/icons'; -import { Card, Chip, Empty, Notice, StudioMark } from '../ui/kit'; +import { Chip, Notice, StudioMark } from '../ui/kit'; +import { EmptyState, PageHeader, Section, StatTile } from '../ui/ds'; +import '../styles/accounts.css'; import type { Tone } from '../lib/model'; const STATUS: Record = { @@ -110,7 +112,7 @@ function StudioCard({ s, accounts, focus }: { s: Studio | null; accounts: Accoun const id = s ? `studio-${s.id}` : 'studio-none'; useEffect(() => { if (focus) document.getElementById(id)?.scrollIntoView({ block: 'start' }); }, [focus, id]); return ( -
+
@@ -178,28 +180,31 @@ export function Accounts({ focus }: { focus?: string }) { ); return ( -
-
-

{t('nav.accounts')}

{t('accounts.leadStudios')}

-
- - -
-
+
+ + + + } /> + {d.accounts.length > 0 &&
+ + a.kind === 'play').length, apple: d.accounts.filter(a => a.kind === 'apple').length })} /> + d.accountHealth[a.id]?.check?.status === 'ok').length} /> + { const h = d.accountHealth[a.id]; return !!h && (!!h.error || (!!h.check && h.check.status !== 'ok')); }) ? 'bad' : undefined} label={t('v2cfg.keysFailing')} value={d.accounts.filter(a => { const h = d.accountHealth[a.id]; return !!h && (!!h.error || (!!h.check && h.check.status !== 'ok')); }).length} /> +
} {error && {error}} - {!d.accounts.length && !d.studios.length && {t('accounts.emptyTextStudios')}} + {!d.accounts.length && !d.studios.length &&
{t('accounts.emptyTitle')} {t('accounts.emptyTextStudios')}
} {d.studios.map(s => a.studio === s.id)} focus={focus === s.id} />)} {(unassigned.length > 0 || !d.studios.length) && d.accounts.length > 0 && } -
- +
+
{ e.preventDefault(); addStudio(); }}>
setStudioName(e.target.value)} maxLength={48} placeholder={t('studio.namePlaceholder')} autoComplete="off" />
{t('studio.color')}
- - +
+
{ e.preventDefault(); addPlay(); }}>
setPlayLabel(e.target.value)} placeholder={t('accounts.playPlaceholder')} maxLength={60} autoComplete="off" />
@@ -207,8 +212,8 @@ export function Accounts({ focus }: { focus?: string }) {

{t('accounts.playHow')}

- - +
+
{ e.preventDefault(); addApple(); }}>
setAppleLabel(e.target.value)} placeholder={t('accounts.applePlaceholder')} maxLength={60} autoComplete="off" />
@@ -221,7 +226,7 @@ export function Accounts({ focus }: { focus?: string }) {
-
+
{t('accounts.safetyStudios')}
diff --git a/apps/desktop/src/screens/AppFolders.tsx b/apps/desktop/src/screens/AppFolders.tsx index 1162a6f..b5df3b4 100644 --- a/apps/desktop/src/screens/AppFolders.tsx +++ b/apps/desktop/src/screens/AppFolders.tsx @@ -1,7 +1,7 @@ // Workspace: app folders (one storebound.config.ts per app), which store accounts each app uses, and starting a new // folder from the templates (`storebound init` with a profile, confirmed in a native dialog). import { failureText } from '../lib/results'; -import { useEffect, useRef, useState } from 'react'; +import { type ReactNode, useEffect, useRef, useState } from 'react'; import { api, errorText, newJob, onProgress, type Project, type ToolResult, type WriteOutcome } from '../api'; import { devSwitch } from '../dev/switches'; import { t } from '../i18n'; @@ -10,12 +10,20 @@ import { useNav } from '../nav'; import { useData } from '../store'; import { Icon, StoreGlyph } from '../ui/icons'; import { useFolderActions } from '../ui/FolderMissing'; -import { AppIcon, Card, Chip, Empty, Notice, Seg, StoreBadge } from '../ui/kit'; +import { AppIcon, Empty, Notice, Seg, StoreBadge } from '../ui/kit'; +import { PageHeader, Section, StatusPill, tintStyle, useTint } from '../ui/ds'; +import '../styles/folders.css'; import { checkState } from './Portfolio'; type Profile = 'app' | 'game' | 'subscription-app'; interface Run { title: string; project: string; job: string; lines: string[]; result?: ToolResult; outcome?: WriteOutcome; error?: string } +/** Folder card wrapper carrying the app's tint (hooks cannot run inside the list map). */ +function Tinted({ src, name, children }: { src: string | null | undefined; name: string; children: ReactNode }) { + const hue = useTint(src, name); + return
{children}
; +} + function LocateButton({ project }: { project: Project }) { const { busy, locate } = useFolderActions(project); return ; @@ -73,41 +81,36 @@ export function AppFolders() { : run.result.ok ? t('run.done') : failureText(run.result); return ( -
-
-

{t('nav.apps')}

{t('folders.lead')}

-
- +
+ - -
-
+ } /> {error && {error}} {!d.projects.length ? ( - +
- }>{t('folders.emptyText')} + }>{t('folders.emptyText')}
) : ( - +
{d.projects.map(p => { const e = d.statusOf(p); const st = p.missing ? { text: t('folder.missingShort'), tone: 'bad' as const } : checkState(e); return ( -
- + +
- {e?.app?.name ?? p.name}{st.text} + {e?.app?.name ?? p.name}{st.text} {shortPath(p.path, d.info?.home)}
-
+
-
+
{p.missing ? : <> @@ -128,14 +131,14 @@ export function AppFolders() { }
-
+ ); })}
- +
)} - +
@@ -147,16 +150,16 @@ export function AppFolders() {

{t('folders.newNote')}

- +
{run && ( - {status}{run.result && <> · {run.result.command}}} +
{status}{run.result && <> · {run.result.command}}} actions={}>
{run.error && {run.error}}
{tildeText(run.result?.output ?? run.lines.join('\n'), d.info?.home) || ' '}
- +
)}
); diff --git a/apps/desktop/src/screens/Dependencies.tsx b/apps/desktop/src/screens/Dependencies.tsx index 9c388e2..e7a04c8 100644 --- a/apps/desktop/src/screens/Dependencies.tsx +++ b/apps/desktop/src/screens/Dependencies.tsx @@ -8,7 +8,9 @@ import { bytes } from '../lib/format'; import { shortPath } from '../paths'; import { useData } from '../store'; import { Icon, type IconName } from '../ui/icons'; -import { Card, Chip, Notice, Skeleton } from '../ui/kit'; +import { Chip, Notice, Skeleton } from '../ui/kit'; +import { PageHeader, Section, StatTile, StatusPill } from '../ui/ds'; +import '../styles/deps.css'; const TOOL_ICON: Record = { ffmpeg: 'image', ffprobe: 'search', chrome: 'globe', xcode: 'terminal', simctl: 'phone', adb: 'phone', git: 'layers' }; @@ -72,29 +74,32 @@ export function Dependencies() { const managed = (id: string): DownloadInfo | undefined => info.find(i => i.tool === (id === 'ffprobe' ? 'ffmpeg' : id)); return ( -
-
-

{t('nav.dependencies')}

{t('deps.lead')}

-
-
+
+ } /> {error && {error}} - + {tools &&
+ + !x.found || x.status === 'outdated') ? 'warn' : undefined} label={t('v2cfg.depsNeeds')} value={tools.filter(x => !x.found || x.status === 'outdated').length} /> + i.installed).length} sub={t('v2cfg.depsInAppSub')} /> +
} +
{!tools ?
: ( -
+
{tools.map(x => { const st = toolState(x); const m = x.install.kind === 'download' ? managed(x.id) : undefined; const running = m ? dl[m.tool] : undefined; const pct = running?.total ? running.received / running.total : null; return ( -
+
- {x.name}{st.text}{x.version && {x.version}} + {x.name} + {st.text}{x.version && {x.version}}{x.required && {t('v2cfg.needs', { version: x.required })}} {x.usedFor} {x.path && {shortPath(x.path, d.info?.home)}}
-
+
{running ? (
@@ -114,9 +119,9 @@ export function Dependencies() { })}
)} - +
{sdk && ( - {t('deps.installed')} : <>{t('deps.missing')}}> {sdk.path ? (
@@ -129,27 +134,27 @@ export function Dependencies() {
    {sdk.checked.map((c, i) =>
  • {d.info?.home ? c.split(d.info.home).join("~") : c}
  • )}
)} - +
)} -
+
{info.map(m => ( - +
{t('deps.source')}
{m.source}
{t('deps.license')}
{m.license}
{t('deps.verify')}
{m.tool === 'chrome' ? t('deps.verifyChrome') : t('deps.verifyFfmpeg')}
- +
))}
- +
{['storebound doctor', 'bun add -d playwright', 'brew install ffmpeg'].map(c => (
{c}
))}
- +
); } diff --git a/apps/desktop/src/screens/Ignored.tsx b/apps/desktop/src/screens/Ignored.tsx index 6095165..57c9a49 100644 --- a/apps/desktop/src/screens/Ignored.tsx +++ b/apps/desktop/src/screens/Ignored.tsx @@ -5,7 +5,9 @@ import { withIgnored } from '../lib/identity'; import { useNav } from '../nav'; import { useData } from '../store'; import { Icon, StoreGlyph } from '../ui/icons'; -import { AppIcon, Card, Empty, StoreOnlyTag, StudioMark } from '../ui/kit'; +import { AppIcon, StoreOnlyTag, StudioMark } from '../ui/kit'; +import { EmptyState, PageHeader, Section } from '../ui/ds'; +import '../styles/folders.css'; export function Ignored() { const d = useData(); @@ -15,14 +17,11 @@ export function Ignored() { const restoreAll = () => d.updateOverrides(o => ({ ...o, ignored: [] })); const empty = !apps.length && !accounts.length; return ( -
-
-

{t('nav.ignored')}

{t('ignored.lead')}

- {!empty &&
} -
- {empty ? {t('ignored.emptyText')} : ( +
+ : undefined} /> + {empty ?
{t('ignored.emptyTitle')} {t('ignored.emptyText')}
: ( <> - +
{apps.length ? (
{apps.map(a => { @@ -44,8 +43,8 @@ export function Ignored() { })}
) :

{t('ignored.noApps')}

} - - +
+
{accounts.length ? (
{accounts.map(a => ( @@ -57,7 +56,7 @@ export function Ignored() { ))}
) :

{t('ignored.noAccounts')}

} - +
)}

{t('ignored.howTo')}

diff --git a/apps/desktop/src/screens/Onboarding.tsx b/apps/desktop/src/screens/Onboarding.tsx index ca535fb..9fa6026 100644 --- a/apps/desktop/src/screens/Onboarding.tsx +++ b/apps/desktop/src/screens/Onboarding.tsx @@ -11,6 +11,7 @@ import { Icon, type IconName, Mark } from '../ui/icons'; import { Illo } from '../ui/illustrations'; import { AppIcon, Chip, Notice, Seg, StudioMark } from '../ui/kit'; import { Swatches } from './Accounts'; +import '../styles/onboarding.css'; const STEPS: [Key, IconName][] = [['wz.s1', 'sparkle'], ['wz.s0', 'building'], ['wz.s2', 'folder'], ['wz.s3', 'key'], ['wz.s4', 'package'], ['wz.s5', 'refresh']]; const LAST = STEPS.length - 1; @@ -72,7 +73,7 @@ export function Onboarding({ onClose }: { onClose: () => void }) { const liveApps = d.live?.value.apps.length ?? 0; return ( -
+
+
+ {t('v2cfg.stepOf', { n: step + 1, total: STEPS.length })} · {t(STEPS[step]![0])} +
+ {STEPS.map(([k], i) => )} +
+
{step === 0 && ( <> diff --git a/apps/desktop/src/screens/Settings.tsx b/apps/desktop/src/screens/Settings.tsx index 3342203..59a67f8 100644 --- a/apps/desktop/src/screens/Settings.tsx +++ b/apps/desktop/src/screens/Settings.tsx @@ -3,6 +3,8 @@ // local tools, the CLI sidecar, privacy, keyboard shortcuts, updates and reset. A section list on the left jumps. import { useEffect, useState } from 'react'; import { useScrollSpy } from '../ui/useScrollSpy'; +import { PageHeader, Section } from '../ui/ds'; +import '../styles/settings.css'; import { api, type CacheInfo, errorText, onUpdateProgress, type Settings as S, type UpdateInfo } from '../api'; import { type Key, t } from '../i18n'; import { ago, bytes, date, num } from '../lib/format'; @@ -11,7 +13,7 @@ import { useNav } from '../nav'; import { usePrefs } from '../prefs-ctx'; import { useData } from '../store'; import { Icon, type IconName, StoreGlyph } from '../ui/icons'; -import { AppIcon, Card, Chip, Kbd, MOD, Notice, Seg, StudioMark } from '../ui/kit'; +import { AppIcon, Chip, Kbd, MOD, Notice, Seg, StudioMark } from '../ui/kit'; export const SECTIONS: [string, IconName, Key][] = [ ['studios', 'building', 'set.studios'], ['pairing', 'link', 'set.pairing'], ['refresh', 'refresh', 'set.refresh'], ['cache', 'database', 'set.cache'], @@ -83,8 +85,8 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void; const singles = storeOnly.filter(a => !(a.ios && a.android)); return ( -
-

{t('nav.settings')}

{t('set.lead')}

+
+ {error && {error}}
- nav.go({ screen: 'accounts' })}>{t('set.manage')}}> +
nav.go({ screen: 'accounts' })}>{t('set.manage')}}> {d.studios.length ? (
{d.studios.map(st => { @@ -107,20 +109,20 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void; })}
) :

{t('set.noStudios')}

} - +
- +
{storeOnly.length ? ( - +
{[...paired, ...singles].map(a => )}
{t('col.app')}{t('set.pairedHow')}{t('col.actions')}
) :

{t('set.noStoreOnly')}

}
{t('set.ignoredLine', { count: d.apps.filter(a => a.ignored).length, accounts: d.overrides.ignored.filter(i => i.startsWith('account:')).length })}
- +
- +
set(x => ({ ...x, refresh: { ...x.refresh, autoRead: v } }))} />
{t('set.everyMinutes')} @@ -138,9 +140,9 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void; {d.live ? t('foot.lastRead', { when: ago(d.live.at) }) : t('foot.neverRead')}
- +
- +
{t('set.cacheSize')}
{cache ? `${bytes(cache.file_bytes)} · ${t('set.cacheRows', { count: cache.rows })}` : '–'}
@@ -152,9 +154,9 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void;

{t('settings.dataText')}

- +
- +
{t('settings.language')} update({ ...prefs, lang })} label={t('settings.language')} options={[['system', t('settings.system')], ['en', 'English'], ['tr', 'Türkçe']]} />
@@ -163,9 +165,9 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void;
{t('settings.motion')} update({ ...prefs, motion })} label={t('settings.motion')} options={[['system', t('settings.followSystem')], ['reduce', t('settings.reduce')]]} />
- +
- +
set(x => ({ ...x, notify: { ...x.notify, rejected: v } }))} /> set(x => ({ ...x, notify: { ...x.notify, approved: v } }))} /> @@ -183,18 +185,18 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void;
- +
- nav.go({ screen: 'dependencies' })}>{t('set.manage')}}> +
nav.go({ screen: 'dependencies' })}>{t('set.manage')}}> {tools ? (
{tools.tools.map(x => {x.name}{x.version ? {x.version} : null}{x.source === 'app' && {t('set.appCopy')}})}
) :

–

}

{t('set.depsText')}

- +
- +
{t('settings.app')}
{d.info ? `storebound desktop ${d.info.version}${d.info.debug ? ` (${t('settings.debug')})` : ''} · ${d.info.platform}` : '–'}
CLI
{d.sidecar ? `storebound ${d.sidecar.version}` : d.sidecarError ?? t('foot.cliStarting')}
@@ -202,9 +204,9 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void;
{t('set.state')}
{d.sidecar?.running ? t('set.running') : d.sidecarError ? t('foot.cliDown') : t('foot.cliStarting')}
{t('set.writes')}
{t('set.writesText')}
- +
- +
  • {t('set.p1')}
  • {t('set.p2')}
  • @@ -215,9 +217,9 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void;
- + - +
{t('settings.scPalette')}
{t('nav.portfolio')}
@@ -227,18 +229,18 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void;
{t('settings.scClose')}
{t('set.scQuit')}
- +
- +
{t('set.channel')} set(x => ({ ...x, channel }))} options={[['stable', t('set.stable')], ['beta', t('set.beta')]]} />

{t('set.updatesText')}

- +
- +

{t('set.resetText', { accounts: d.accounts.length, studios: d.studios.length, folders: d.projects.length })}

@@ -246,7 +248,7 @@ export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void;
- +

{t('set.footer', { n: num(d.apps.length) })}

diff --git a/apps/desktop/src/screens/editors/AppInfoEditor.tsx b/apps/desktop/src/screens/editors/AppInfoEditor.tsx index 053f4ea..c0685af 100644 --- a/apps/desktop/src/screens/editors/AppInfoEditor.tsx +++ b/apps/desktop/src/screens/editors/AppInfoEditor.tsx @@ -8,7 +8,8 @@ import { type Key, t } from '../../i18n'; import { AGE_FREQUENCY, AGE_RATING_NONE, APPLE_CATEGORIES, APPLE_GAME_SUBCATEGORIES, KIDS_AGE_BANDS, PLAY_AGE_GROUPS, PLAY_APP_CATEGORIES, PLAY_GAME_CATEGORIES } from '../../../../../cli/lib/store-catalogs'; import { ApplyPanel, ChoiceField, EditBar, JsonField, ListField, TextField, useEdits } from '../../ui/Editor'; import { StoreGlyph } from '../../ui/icons'; -import { Card } from '../../ui/kit'; +import { Section } from '../../ui/ds'; +import '../../styles/appinfo.css'; type O = Record; const obj = (v: unknown): O => (v && typeof v === 'object' && !Array.isArray(v) ? (v as O) : {}); @@ -30,7 +31,7 @@ function AppleInfo({ project, data }: { project: Project; data: EditableResult } const contact = data.contact; return ( <> - {t('ed.appleInfoSub')}}> +
{t('ed.appleInfoSub')}}>
{games && } @@ -43,8 +44,8 @@ function AppleInfo({ project, data }: { project: Project; data: EditableResult } options={[['false', t('ai.encNo')], ['true', t('ai.encYes')]]} hint={t('ed.encHint')} />
- - +
+
{Object.entries(AGE_RATING_NONE).map(([q, none]) => ( ))}
- - +
+
{data.demoAccount ? `${data.demoAccount} · ••••••••` : t('ed.notSet')}
{t('ed.demoHint')}
- + ); } @@ -75,7 +76,7 @@ function PlaySettings({ project, data }: { project: Project; data: EditableResul const acc = obj(data.config.accounts); const cats: [string, string][] = [...PLAY_GAME_CATEGORIES.map(c => [c, `${t('ed.game')}: ${c}`] as [string, string]), ...PLAY_APP_CATEGORIES.map(c => [c, `${t('ed.app')}: ${c}`] as [string, string])]; return ( - {t('ed.playSettingsSub')}}> +
{t('ed.playSettingsSub')}}>
@@ -83,14 +84,14 @@ function PlaySettings({ project, data }: { project: Project; data: EditableResul
- +
); } function Declarations({ project, data }: { project: Project; data: EditableResult }) { const ds = obj(data.config.dataSafety); return ( - +
{data.play && } {data.play && } @@ -101,14 +102,14 @@ function Declarations({ project, data }: { project: Project; data: EditableResul {data.play && } {data.play && } {data.play && } - +
); } function Promotion({ project, data }: { project: Project; data: EditableResult }) { const apple = obj(data.config.apple); return ( - {t('ed.promoSub')}}> +
{t('ed.promoSub')}}> @@ -116,7 +117,7 @@ function Promotion({ project, data }: { project: Project; data: EditableResult }
- + ); } @@ -124,13 +125,13 @@ export function AppInfoEditor({ project, data, onSaved }: { project: Project; da const e = useEdits(); const unsaved = e.count(project.id, 'appinfo') ? t('ed.saveFirst') : null; return ( -
+
{data.apple && } {data.play && } {data.apple && } - +
{data.apple && (
@@ -149,7 +150,7 @@ export function AppInfoEditor({ project, data, onSaved }: { project: Project; da
)}
- +
); } diff --git a/apps/desktop/src/screens/editors/ArtEditor.tsx b/apps/desktop/src/screens/editors/ArtEditor.tsx index 4b40d05..77f3e25 100644 --- a/apps/desktop/src/screens/editors/ArtEditor.tsx +++ b/apps/desktop/src/screens/editors/ArtEditor.tsx @@ -1,13 +1,15 @@ // Store art editor (Store art tab): the order of the screenshot scenes (the store shows them in this order) and the // raw frame each scene shows (replace a screenshot by pointing the scene at another frame). Saved into the config; // then render, and upload to each store with the dry run in the window (uploads replace the store's sets). +import '../../styles/art.css'; import { useState } from 'react'; import { api, errorText, type EditableResult, type Project } from '../../api'; import { useData, useWrite } from '../../store'; import { t } from '../../i18n'; import { ApplyPanel, EditBar, TextField, useEdits } from '../../ui/Editor'; import { Icon, StoreGlyph } from '../../ui/icons'; -import { Card, Empty } from '../../ui/kit'; +import { Empty } from '../../ui/kit'; +import { Section } from '../../ui/ds'; import { keyOf } from '../../lib/edits'; type Scene = { id: string; palette?: unknown; frames?: { src: string }[] } & Record; @@ -33,7 +35,7 @@ export function ArtEditor({ project, data, onSaved }: { project: Project; data: const p = e.get(project.id, keyOf(op)); const scenes = (p && p.op.kind === 'config' ? p.op.value : saved) as Scene[]; const unsaved = e.count(project.id, 'art') ? t('ed.saveFirst') : null; - if (!saved.length) return {t('ed.artEmptyText')}; + if (!saved.length) return
{t('ed.artEmptyText')}
; const move = (i: number, d: -1 | 1) => { const next = [...scenes]; const j = i + d; @@ -42,8 +44,8 @@ export function ArtEditor({ project, data, onSaved }: { project: Project; data: e.set(project.id, { ...op, value: next }, 'art', saved); }; return ( -
- +
1 ? : undefined}>
    {scenes.map((s, i) => ( @@ -61,16 +63,16 @@ export function ArtEditor({ project, data, onSaved }: { project: Project; data: ))}
- +
{data.shotsCopy && s.id)} />} - +
{t('act.render')}
{data.play &&
Google Play
} {data.apple &&
App Store
}
- +
); } @@ -82,7 +84,7 @@ function Captions({ project, data, scenes }: { project: Project; data: EditableR const [lang, setLang] = useState(langs[0] ?? ''); const L = langs.includes(lang) ? lang : langs[0] ?? ''; return ( - +
{langs.map(x => )}
@@ -103,6 +105,6 @@ function Captions({ project, data, scenes }: { project: Project; data: EditableR ); })}
- + ); } diff --git a/apps/desktop/src/screens/editors/CatalogEditor.tsx b/apps/desktop/src/screens/editors/CatalogEditor.tsx index 27380c4..2a3be47 100644 --- a/apps/desktop/src/screens/editors/CatalogEditor.tsx +++ b/apps/desktop/src/screens/editors/CatalogEditor.tsx @@ -3,12 +3,14 @@ // offer blocks (introductory and promotional offers, offer codes, win-back) as checked JSON. Saved into the config, // then applied per store with the dry run in the window. A price change of a product that is already live goes // through the owner's price decision (the Catalog tab's "Apply the price changes" owner actions). +import '../../styles/catalog.css'; import { useState } from 'react'; import type { EditableResult, Project } from '../../api'; import { t } from '../../i18n'; import { ApplyPanel, ChoiceField, EditBar, JsonField, ListField, NumberField, TextField, useEdits } from '../../ui/Editor'; import { Icon, StoreGlyph } from '../../ui/icons'; -import { Card, Chip, Empty } from '../../ui/kit'; +import { Chip, Empty } from '../../ui/kit'; +import { Section } from '../../ui/ds'; type O = Record; const obj = (v: unknown): O => (v && typeof v === 'object' && !Array.isArray(v) ? (v as O) : {}); @@ -44,8 +46,8 @@ function ProductCard({ project, data, p }: { project: Project; data: EditableRes return (
{open && (
@@ -71,7 +73,7 @@ function SubCard({ project, data, group, s }: { project: Project; data: Editable return (
{open && (
@@ -99,17 +101,17 @@ export function CatalogEditor({ project, data, onSaved }: { project: Project; da const groups = data.config.subscriptions as O[]; const unsaved = e.count(project.id, 'catalog') ? t('ed.saveFirst') : null; if (!products.length && !groups.length) { - return {t('ed.catalogEmptyText')}; + return
{t('ed.catalogEmptyText')}
; } return ( -
+
{products.length > 0 && ( - +
{products.map(p => )}
- +
)} {groups.map(g => ( - +
{data.languages.map(l => ( @@ -120,10 +122,10 @@ export function CatalogEditor({ project, data, onSaved }: { project: Project; da
{(g.subscriptions as O[]).map(s => )}
- +
))} - +
{data.play && (
@@ -142,7 +144,7 @@ export function CatalogEditor({ project, data, onSaved }: { project: Project; da )}

{t('ed.priceGate')}

- +
); } diff --git a/apps/desktop/src/screens/editors/ListingEditor.tsx b/apps/desktop/src/screens/editors/ListingEditor.tsx index a09d1f5..69270fa 100644 --- a/apps/desktop/src/screens/editors/ListingEditor.tsx +++ b/apps/desktop/src/screens/editors/ListingEditor.tsx @@ -2,6 +2,7 @@ // counters against the store limits and the checks of `check --aso` / `scan` as the owner types; the shared store // details (URLs, contact, copyright, promo video); Save into store/listing.md, store/appstore.md and the config // (project.edit), Pull the live texts into the files (diff first), and Apply to each store (dry run in the window). +import '../../styles/listings.css'; import { useState } from 'react'; import type { EditableListing, EditableResult, Project } from '../../api'; import { type Key, t } from '../../i18n'; @@ -10,7 +11,8 @@ import { keyOf } from '../../lib/edits'; import { useData, useWrite } from '../../store'; import { ApplyPanel, EditBar, type FieldIssueView, TextField, useEdits } from '../../ui/Editor'; import { Icon, StoreGlyph } from '../../ui/icons'; -import { Card, Chip, Notice } from '../../ui/kit'; +import { Chip, Notice } from '../../ui/kit'; +import { Section } from '../../ui/ds'; import { WriteButton } from '../../ui/WriteButton'; const PLAY: { f: string; label: Key; multiline?: boolean; rows?: number; mono?: boolean }[] = [ @@ -30,6 +32,30 @@ function current(e: ReturnType, project: Project, store: 'play' } return out; } +/** The texts of one language as the store page shows them: icon, title, subtitle / short description, promo text and + * the first lines of the description (live, with the unsaved edits). */ +export function StorePreview({ store, vals, name }: { store: 'play' | 'apple'; vals: Record; name: string }) { + const title = (store === 'play' ? vals.title : vals.name) || name; + const sub = store === 'play' ? vals.short : vals.subtitle; + const promo = store === 'apple' ? vals.promotionalText : ''; + const desc = store === 'play' ? vals.full : vals.description; + return ( +
+ {t('v2lst.preview')} +
+ +
+
{title || '–'}
+ {sub ?
{sub}
:
{t('v2lst.noSub')}
} +
+
+ {promo &&

{promo}

} + {desc ?

{desc}

:

{t('v2lst.noDesc')}

} + {desc && desc.length > 180 && } +
+ ); +} + const byField = (issues: FieldIssue[], f: string): FieldIssueView[] => issues.filter(i => i.field === f).map(i => ({ level: i.level, msg: i.msg })); function StoreColumn({ project, data, store, l }: { project: Project; data: EditableResult; store: 'play' | 'apple'; l: EditableListing }) { @@ -48,6 +74,7 @@ function StoreColumn({ project, data, store, l }: { project: Project; data: Edit {l.status && {l.status === 'draft' ? t('ed.statusDraft') : t('ed.statusTranslate')}} {(l.codes?.length ?? 0) > 1 && {t('ed.alsoServes', { codes: l.codes!.filter(c => c !== l.lang).join(', ') })}}
+ {fresh && {t('ed.newSection', { lang: l.lang })}} {defs.map(d => ( - +
{data.play && {t('ed.pullPlay')}} {data.apple && {t('ed.pullApple')}} }>
{unsaved > 0 && {t('ed.pullNote')}} -
+
{data.languages.map(x => { const n = e.list(project.id, 'listings').filter(p => p.op.kind === 'listing' && (p.op.lang === x.apple || x.play.includes(p.op.lang))).length; return ( @@ -132,12 +159,12 @@ export function ListingEditor({ project, data, onSaved }: { project: Project; da {!pl && !al && {t('ed.noStoreForLang', { lang: L?.id ?? '' })}}
- - +
+
- +
- +
{data.play && (
@@ -157,7 +184,7 @@ export function ListingEditor({ project, data, onSaved }: { project: Project; da )}

{t('ed.applyNote')}

- - +
+
); } diff --git a/apps/desktop/src/screens/editors/StoreListingEditor.tsx b/apps/desktop/src/screens/editors/StoreListingEditor.tsx index a1640cc..0d2374b 100644 --- a/apps/desktop/src/screens/editors/StoreListingEditor.tsx +++ b/apps/desktop/src/screens/editors/StoreListingEditor.tsx @@ -2,6 +2,7 @@ // (listing.live), edited in place with the same counters and checks, and applied straight to the store per language // (listing.set: the store's dry run in the window, the native dialog, then the real run, which changes only the edited // fields). URLs, contact and app details stay with an app folder (they come from its config). +import '../../styles/listings.css'; import { useState } from 'react'; import type { Project } from '../../api'; import { type Key, t } from '../../i18n'; @@ -12,7 +13,9 @@ import { keyOf } from '../../lib/edits'; import { useRead } from '../../store'; import { ApplyPanel, type FieldIssueView, TextField, useEdits } from '../../ui/Editor'; import { Icon, StoreGlyph } from '../../ui/icons'; -import { Card, Empty, ErrorNotice, Notice, ReadControl, Skeleton } from '../../ui/kit'; +import { Empty, ErrorNotice, Notice, ReadControl, Skeleton } from '../../ui/kit'; +import { Section } from '../../ui/ds'; +import { StorePreview } from './ListingEditor'; const PLAY: { f: 'title' | 'short' | 'full'; label: Key; limit: number; rows?: number }[] = [ { f: 'title', label: 'lst.title', limit: 30 }, { f: 'short', label: 'lst.short', limit: 80 }, { f: 'full', label: 'lst.full', limit: 4000, rows: 10 }, @@ -41,6 +44,7 @@ function Column({ project, store, lang, saved, appName, editable }: { project: P return (
{store === 'play' ? 'Google Play' : 'App Store'}{lang}
+ {store === 'apple' && !editable && {t('ed.noEditableVersion')}} {defs.map(d => ( ; - return {t('tf.read')}}>{r.error ?? t('ed.storeOnlyNote')}; + if (r.loading && !r.error) return
; + return
{t('tf.read')}}>{r.error ?? t('ed.storeOnlyNote')}
; } const L = r.data; const langs = [...new Set([...(L.play ?? []).map(x => x.language), ...(L.apple?.locales ?? []).map(x => x.locale)])].sort(); @@ -69,12 +73,12 @@ export function StoreListingEditor({ app }: { app: UnifiedApp }) { const pl = L.play?.find(x => x.language === cur); const al = L.apple?.locales.find(x => x.locale === cur); return ( - <> +
{Object.entries(L.errors).map(([s, e]) => )} - } id="store-listing-editor"> +
} id="store-listing-editor">
{t('ed.storeOnlyNote')} -
+
{langs.map(x => )}
@@ -83,7 +87,7 @@ export function StoreListingEditor({ app }: { app: UnifiedApp }) { {!pl && !al && {t('ed.noStoreForLang', { lang: cur })}}
- - +
+
); } diff --git a/apps/desktop/src/screens/editors/TabEditor.tsx b/apps/desktop/src/screens/editors/TabEditor.tsx index 462fae0..109eff5 100644 --- a/apps/desktop/src/screens/editors/TabEditor.tsx +++ b/apps/desktop/src/screens/editors/TabEditor.tsx @@ -6,7 +6,8 @@ import { t } from '../../i18n'; import { edits } from '../../lib/edits'; import type { AppTab } from '../../nav'; import { useEditable } from '../../ui/Editor'; -import { Card, ErrorNotice, Skeleton } from '../../ui/kit'; +import { ErrorNotice, Skeleton } from '../../ui/kit'; +import { Section } from '../../ui/ds'; import { AppInfoEditor } from './AppInfoEditor'; import { ArtEditor } from './ArtEditor'; import { CatalogEditor } from './CatalogEditor'; @@ -21,7 +22,7 @@ export const EDIT_TABS: Partial : ; + if (!r.data) return r.error ? :
; const p = { project, data: r.data, onSaved: () => { r.refresh(); } }; switch (tab) { case 'listings': return ; diff --git a/apps/desktop/src/screens/editors/TestFlightEditor.tsx b/apps/desktop/src/screens/editors/TestFlightEditor.tsx index 9507aab..07a3dd0 100644 --- a/apps/desktop/src/screens/editors/TestFlightEditor.tsx +++ b/apps/desktop/src/screens/editors/TestFlightEditor.tsx @@ -5,7 +5,8 @@ import type { EditableResult, Project } from '../../api'; import { t } from '../../i18n'; import { ApplyPanel, EditBar, JsonField, TextField, useEdits } from '../../ui/Editor'; -import { Card } from '../../ui/kit'; +import { Section } from '../../ui/ds'; +import '../../styles/testflight.css'; type O = Record; const obj = (v: unknown): O => (v && typeof v === 'object' && !Array.isArray(v) ? (v as O) : {}); @@ -17,8 +18,8 @@ export function TestFlightEditor({ project, data, onSaved }: { project: Project; const unsaved = e.count(project.id, 'testflight') ? t('ed.saveFirst') : null; if (!data.apple) return null; return ( -
- +
+
{data.apple.map(l => (
@@ -35,14 +36,14 @@ export function TestFlightEditor({ project, data, onSaved }: { project: Project; {typeof desc === 'string' && } - +
- -
+
+
- +
); } diff --git a/apps/desktop/src/screens/tabs/AppInfo.tsx b/apps/desktop/src/screens/tabs/AppInfo.tsx index 7b7e5bf..be4ce7c 100644 --- a/apps/desktop/src/screens/tabs/AppInfo.tsx +++ b/apps/desktop/src/screens/tabs/AppInfo.tsx @@ -12,10 +12,12 @@ import { declarationsMd, exportName } from '../../lib/exports'; import { ago, num } from '../../lib/format'; import { useData, useRead, useWrite } from '../../store'; import { useExports, useRunExport } from '../../ui/Exports'; -import { Icon, StoreGlyph } from '../../ui/icons'; +import { Icon, type IconName, StoreGlyph } from '../../ui/icons'; import { CONSOLE_FORM_NAME, ConsoleFillButton } from '../../ui/ConsoleFill'; import { ConsolePlanButton, PLAN_FORMS } from '../../ui/ConsolePlan'; -import { Bar, Card, Chip, Empty, ErrorNotice, Notice, Skeleton } from '../../ui/kit'; +import { Bar, Chip, ErrorNotice, Notice, Skeleton } from '../../ui/kit'; +import { EmptyState, Section } from '../../ui/ds'; +import '../../styles/appinfo.css'; import { WriteButton } from '../../ui/WriteButton'; import { GameServicesCard } from '../../ui/GameServicesCard'; import { ascUrl } from '../AppView'; @@ -34,7 +36,7 @@ const yes = (b: boolean | null | undefined): string => (b === null || b === unde function AskCard({ ask }: { ask: DeclAsk[] }) { if (!ask.length) return {t('ai.allAnswered')}; return ( - +
{ask.map(a => (
@@ -45,7 +47,7 @@ function AskCard({ ask }: { ask: DeclAsk[] }) {
))}
- +
); } @@ -76,12 +78,12 @@ function DataSafety({ project, d, onDone }: { project: Project; d: DeclarationsR const up = ds?.uploaded ?? null; const asked = d.ask.filter(a => a.area === 'dataSafety').length; return ( - {t('ai.dsSub')}} pad={false} +
{t('ai.dsSub')}} pad={false} actions={ds ? <> {t('ai.dsUpload')} : undefined}> - {!ds ? {t('ai.dsNoneText')} : ( + {!ds ? {t('ai.dsNoneTitle')}
{t('ai.dsNoneText')}
: ( <>
@@ -99,7 +101,7 @@ function DataSafety({ project, d, onDone }: { project: Project; d: DeclarationsR {asked > 0 && {t('ai.askedHere', { count: asked })}}
{ds.types.length > 0 && ( - +
{ds.types.map(x => ( @@ -110,12 +112,12 @@ function DataSafety({ project, d, onDone }: { project: Project; d: DeclarationsR ))} -
{t('ai.colType')}{t('ai.colCollected')}{t('ai.colShared')}
+
)}
{t('ai.dsFoot', { rows: ds.rows })}
)} -
+ ); } @@ -123,14 +125,14 @@ function AppPrivacy({ project, d, appId }: { project: Project; d: DeclarationsRe const ap = d.appPrivacy; if (!ap) return null; return ( - {t('ai.apSub')}} pad={false} +
{t('ai.apSub')}} pad={false} actions={<> }>
{t('ai.apNote')}
- {!ap.items.length ? {ap.fromDataSafety ? t('ai.apNoneText') : t('ai.apUnknownText')} : ( - + {!ap.items.length ? {ap.fromDataSafety ? t('ai.apNoneTitle') : t('ai.apUnknownTitle')}
{ap.fromDataSafety ? t('ai.apNoneText') : t('ai.apUnknownText')}
: ( +
{ap.items.map(x => ( @@ -142,9 +144,9 @@ function AppPrivacy({ project, d, appId }: { project: Project; d: DeclarationsRe ))} -
{t('ai.colAppleType')}{t('ai.colPurposes')}{t('ai.colLinked')}{t('ai.colTracking')}
+
)} - + ); } @@ -154,7 +156,7 @@ function ConsoleSteps({ project, stores }: { project: Project; stores: Declarati const forms = PLAN_FORMS.filter(f => (f.store === 'apple' ? stores.apple : stores.play)); if (!forms.length) return null; return ( - +
{forms.map(f => (
@@ -167,7 +169,7 @@ function ConsoleSteps({ project, stores }: { project: Project; stores: Declarati
))}
- +
); } @@ -181,27 +183,45 @@ export function AppInfoTab({ project }: { project: Project }) { { id: 'decl-md', label: t('export.declarations'), icon: 'clipboard', kind: 'md', file: exportName(name, 'store declarations'), disabled: r.data ? false : t('export.readFirst'), build: () => declarationsMd(name, r.data!) }, { id: 'ds-csv', label: t('export.dataSafety'), icon: 'shield', kind: 'csv', file: exportName(name, 'data safety'), disabled: r.data?.dataSafety ? false : t('export.noDataSafety'), build: () => r.data!.dataSafety!.csv }, ]); - if (!r.data) return r.error ? : ; + if (!r.data) return r.error ? :
; const d = r.data; const info = d.appInfo; const enc = d.encryption; const rv = d.review; const cat = info?.categories ? [info.categories.primary, info.categories.primarySubOne, info.categories.primarySubTwo].filter(Boolean).join(' / ') : null; + const ds = d.dataSafety; + const facts: { k: string; label: string; icon: IconName; value: string; tone: 'ok' | 'warn' | 'neutral' }[] = [ + { k: 'ask', label: t('v2ins.aiOpen'), icon: 'question', value: d.ask.length ? num(d.ask.length) : t('v2ins.aiNone'), tone: d.ask.length ? 'warn' : 'ok' }, + ...(d.stores.apple && info ? [ + { k: 'cat', label: t('ai.category'), icon: 'grid' as IconName, value: cat ?? t('ai.notSet'), tone: cat ? 'neutral' as const : 'warn' as const }, + { k: 'price', label: t('ai.price'), icon: 'coins' as IconName, value: info.free ? t('ai.free') : t('ai.paid'), tone: 'neutral' as const }, + { k: 'enc', label: t('ai.encTitle'), icon: 'lock' as IconName, value: enc === null ? t('ai.notAnswered') : enc ? t('ai.encYes') : t('ai.encNo'), tone: enc === null ? 'warn' as const : 'neutral' as const }, + ] : []), + ...(d.stores.play && ds ? [{ k: 'ds', label: t('ai.dsCollects'), icon: 'shield' as IconName, value: yes(ds.collectsData), tone: ds.collectsData === null || ds.collectsData === undefined ? 'warn' as const : 'neutral' as const }] : []), + ]; return ( - <> +
+
+
{t('v2ins.aiSheet')}

{name}

+ {d.stores.apple && App Store}{d.stores.play && Google Play} +
+
+ {facts.map(f =>
{f.label}
{f.value}
)} +
+
{d.stores.apple && e?.app?.platforms.ios && !e.app.platforms.ios.ascAppId && ( }>
{t('cf.noRecordTitle')}{t('cf.noRecordText')}
)} -
- {d.stores.play ? : {t('ai.noPlayText')}} - {d.stores.apple ? : {t('ai.noAppleText')}} +
+ {d.stores.play ? :
{t('ai.noPlay')}
{t('ai.noPlayText')}
} + {d.stores.apple ? :
{t('ai.noApple')}
{t('ai.noAppleText')}
}
{d.stores.apple && ( -
- +
{t('ai.push')} @@ -212,15 +232,15 @@ export function AppInfoTab({ project }: { project: Project }) {
{t('ai.rights')}
{info!.contentRights ? {info!.contentRights === 'USES_THIRD_PARTY_CONTENT' ? t('ai.rightsThird') : t('ai.rightsOwn')} : {t('ai.notSet')}}
{t('ai.price')}
{info!.free ? t('ai.free') : t('ai.paid')}
- - +
{t('ai.encAnswer')}}>
{enc === null ? {t('ai.notAnswered')} : {enc ? t('ai.encYes') : t('ai.encNo')}} {enc === null ? t('ai.encUnset') : enc ? t('ai.encYesText') : t('ai.encNoText')}
- - +
{t('ai.push')}}>
@@ -235,13 +255,13 @@ export function AppInfoTab({ project }: { project: Project }) {
{t('ai.reviewSafe')}
- +
)} -

{t('ai.foot', { when: ago(r.at) })}

- +

{t('ai.foot', { when: ago(r.at) })}

+
); } diff --git a/apps/desktop/src/screens/tabs/Art.tsx b/apps/desktop/src/screens/tabs/Art.tsx index 66ff5b9..43517fc 100644 --- a/apps/desktop/src/screens/tabs/Art.tsx +++ b/apps/desktop/src/screens/tabs/Art.tsx @@ -2,6 +2,7 @@ // size (`shots gallery --json`, offline), store check issues outlined. Images load one by one as they scroll into view // (`project.render`, a data: URL each: the window loads no files itself). Re-render (dry run, dialog, real run), write // the review page, open it or the folder. +import '../../styles/art.css'; import { type KeyboardEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { api, errorText, type Project, type RenderImage, type RendersResult, type RenderTile, type ToolResult } from '../../api'; import { t } from '../../i18n'; @@ -9,7 +10,8 @@ import { ago, bytes, num } from '../../lib/format'; import { artRows, langIssues } from '../../lib/views'; import { useData, useRead, useWrite } from '../../store'; import { Icon } from '../../ui/icons'; -import { Card, Chip, Empty, ErrorNotice, Kpi, Seg, Skeleton } from '../../ui/kit'; +import { Chip, Empty, ErrorNotice, Seg, Skeleton } from '../../ui/kit'; +import { Section, StatTile, StatusPill } from '../../ui/ds'; import { WriteButton } from '../../ui/WriteButton'; import { LiveArt } from './LiveArt'; @@ -57,11 +59,13 @@ function Thumb({ projectId, tile, stamp, onOpen }: { projectId: string; tile: Re return () => { alive = false; io.disconnect(); }; }, [projectId, file, stamp, src]); const lvl = tile.issues.some(i => i.level === 'error') ? 'err' : tile.issues.length ? 'warn' : ''; + const shape = tile.h > tile.w ? 'portrait' : 'landscape'; return ( -
+
{tile.name}{tile.w}×{tile.h}{tile.bytes ? ` · ${bytes(tile.bytes)}` : ''}
{tile.issues.length > 0 &&
    {tile.issues.slice(0, 2).map((i, k) =>
  • {i.msg}
  • )}
} @@ -125,7 +129,7 @@ export function ArtTab({ project }: { project: Project }) { }, [project.id, d, w, data?.dir, r.refresh]); // the live art stays the first child in both branches, so it keeps its state when the local renders arrive - if (!data) return <>{r.error ? : }; + if (!data) return
{r.error ? :
}
; const total = data.totals.images + data.totals.videos; const toolbar = ( <> @@ -136,15 +140,15 @@ export function ArtTab({ project }: { project: Project }) { ); return ( - <> +
-
- - - - +
+ + + +
- {dir}} actions={toolbar} pad={false}> +
{dir}} actions={toolbar} pad={false}>
{data.variants.length > 1 && [x.id, x.id ? t('gr.variant', { id: x.id }) : t('art.base')] as [string, string])} />}
@@ -163,9 +167,9 @@ export function ArtTab({ project }: { project: Project }) {
{rows.map(row => (
i.level === 'error') ? ' bad' : ''}`} key={row.size}> -

{row.label}{lg}/{row.size}{row.store === 'apple' ? 'App Store' : 'Google Play'}{t('art.count', { count: row.tiles.length })}

+

{row.label}{lg}/{row.size}{row.store === 'apple' ? 'App Store' : 'Google Play'}{row.issues.length > 0 && i.level === 'error') ? 'bad' : 'warn'}>{t('v2lst.issues', { count: row.issues.length })}}{t('art.count', { count: row.tiles.length })}

{row.issues.length > 0 &&
    {row.issues.map((i, k) =>
  • {i.msg}
  • )}
} -
row.tiles[0].h ? '260px' : '150px' }}> +
row.tiles[0].h ? '260px' : '170px' }}> {row.tiles.map((tile, i) => setOpen({ tiles: row.tiles, i })} />)}
@@ -173,8 +177,8 @@ export function ArtTab({ project }: { project: Project }) {
)}
{t('art.foot', { when: ago(r.at) })}
- +
{open && setOpen(null)} onMove={i => setOpen(o => (o ? { ...o, i } : o))} onReplace={tile => { setOpen(null); replace(tile); }} />} - +
); } diff --git a/apps/desktop/src/screens/tabs/Catalog.tsx b/apps/desktop/src/screens/tabs/Catalog.tsx index 7dedd9d..290d34a 100644 --- a/apps/desktop/src/screens/tabs/Catalog.tsx +++ b/apps/desktop/src/screens/tabs/Catalog.tsx @@ -1,5 +1,6 @@ // Catalog: products and subscriptions defined once in the config against both stores (catalog diff): a parity // matrix (present, mismatched, missing, not sold there, not read), and price gaps between the stores per region. +import '../../styles/catalog.css'; import type { Project } from '../../api'; import { type Key, t } from '../../i18n'; import { ago, num } from '../../lib/format'; @@ -8,17 +9,19 @@ import { useData, useRead, useWrite } from '../../store'; import { Icon, type IconName, StoreGlyph } from '../../ui/icons'; import { OwnerAction } from '../../ui/OwnerAction'; import { WriteButton } from '../../ui/WriteButton'; -import { Card, Chip, Empty, ErrorNotice, Kpi, ReadControl, Skeleton } from '../../ui/kit'; +import { Chip, ErrorNotice, ReadControl, Skeleton } from '../../ui/kit'; +import { EmptyState, Section, StatTile, StatusPill } from '../../ui/ds'; import { catalogMd, exportName } from '../../lib/exports'; import { useExports } from '../../ui/Exports'; import { useNav } from '../../nav'; const CELL: Record = { ok: ['check', 'cat.ok'], warn: ['alert', 'cat.warn'], error: ['x', 'cat.error'], na: ['dot', 'cat.na'], unknown: ['info', 'cat.unknown'] }; -function Cell({ c }: { c: { state: CellState; notes: string[] } }) { +function Cell({ c, store }: { c: { state: CellState; notes: string[] }; store?: 'ios' | 'android' }) { const [icon, key] = CELL[c.state]; return ( -
+
+ {store && {store === 'ios' ? 'App Store' : 'Google Play'}} {t(key)} {c.notes.length > 0 &&
    {c.notes.slice(0, 3).map((n, i) =>
  • {n}
  • )}
}
@@ -33,7 +36,7 @@ function CatalogActions({ project, products, subs, refresh }: { project: Project const e = d.statusOf(project); const ios = !!e?.app?.platforms.ios, android = !!e?.app?.platforms.android; return ( - +
{android && (
@@ -60,7 +63,7 @@ function CatalogActions({ project, products, subs, refresh }: { project: Project

{t('act.catalogNote')}

- +
); } @@ -73,48 +76,54 @@ export function CatalogTab({ project }: { project: Project }) { useExports('catalog', [ { id: 'catalog-md', label: t('export.catalog'), icon: 'layers', kind: 'md', file: exportName(name, 'catalog parity'), disabled: diff.data ? false : t('export.readFirst'), build: () => catalogMd(name, diff.data!) }, ]); - if (!e) return ; + if (!e) return
; const rows = parityMatrix(s, diff.data); const read = !!diff.data; const inParity = rows.filter(r => r.ios.state !== 'error' && r.ios.state !== 'warn' && r.android.state !== 'error' && r.android.state !== 'warn' && r.kind !== 'extra').length; const gaps = diff.data?.parity ?? []; if (!rows.length) { - return {t('cat.emptyText')}; + return
{t('cat.emptyTitle')} {t('cat.emptyText')}
; } return ( - <> -
- - - r.kind !== 'extra').length}` : '–'} sub={read ? t('cat.parityRead', { when: ago(diff.at) }) : diff.loading ? t('read.waiting') : t('kpi.notRead')} tone={read && inParity < rows.length ? 'warn' : undefined} /> - +
+
+ + + r.kind !== 'extra').length}` : '–'} sub={read ? t('cat.parityRead', { when: ago(diff.at) }) : diff.loading ? t('read.waiting') : t('kpi.notRead')} tone={read && inParity < rows.length ? 'warn' : undefined} /> +
{diff.error && } { diff.refresh(); }} /> - }> -
- - - - {rows.map(r => ( - - - - - - - - - ))} - -
{t('col.item')}{t('col.type')}{t('col.config')}App StoreGoogle Play{t('col.priceGap')}
{r.id}{r.kind === 'extra' ? {t('cat.extra')} : {r.kind === 'subscription' ? t('cat.sub') : t('cat.product')}}{r.config ? [s?.catalog.ios.includes(r.id) ? 'iOS' : null, s?.catalog.android.includes(r.id) ? 'Android' : null].filter(Boolean).join(' + ') || t('cat.na') : {t('cat.notInConfig')}}{r.maxDiff !== null ? 25 ? 'bad' : 'warn'}>{`${num(r.maxDiff, 1)} %`} : {read ? t('cat.noGap') : '–'}}
-
-
+
    + {rows.map(r => { + const worst = [r.ios.state, r.android.state].includes('error') ? 'bad' : [r.ios.state, r.android.state].includes('warn') || r.kind === 'extra' ? 'warn' : 'ok'; + return ( +
  • +
    + +
    + {r.id} + {r.kind === 'extra' ? {t('cat.extra')} : {r.kind === 'subscription' ? t('cat.sub') : t('cat.product')}} + {t('col.config')}: {r.config ? [s?.catalog.ios.includes(r.id) ? 'iOS' : null, s?.catalog.android.includes(r.id) ? 'Android' : null].filter(Boolean).join(' + ') || t('cat.na') : t('cat.notInConfig')} +
    + + {r.maxDiff !== null ? 25 ? 'bad' : 'warn'} title={t('col.priceGap')}>{`Δ ${num(r.maxDiff, 1)} %`} : {read ? t('cat.noGap') : '–'}} +
    +
    + + +
    +
  • + ); + })} +
+ {gaps.length > 0 && ( - - +
+
{gaps.slice(0, 12).map((g, i) => ( @@ -125,9 +134,9 @@ export function CatalogTab({ project }: { project: Project }) { ))} -
{t('col.item')}{t('col.region')}App StoreGoogle Play{t('col.diff')}
-
+
+ )} - +
); } diff --git a/apps/desktop/src/screens/tabs/Checks.tsx b/apps/desktop/src/screens/tabs/Checks.tsx index 1752997..6dc0ad1 100644 --- a/apps/desktop/src/screens/tabs/Checks.tsx +++ b/apps/desktop/src/screens/tabs/Checks.tsx @@ -10,10 +10,12 @@ import { AiFix, aiFinding } from '../../ui/AiFix'; import { api, errorText, newJob } from '../../api'; import type { ToolResult } from '../../api'; import type { ReportData } from '../../../../../cli/lib/report'; -import { useEffect, useState } from 'react'; -import { Icon } from '../../ui/icons'; +import { type ReactNode, useEffect, useState } from 'react'; +import { Icon, type IconName, StoreGlyph } from '../../ui/icons'; import { OpenLink } from '../../ui/OpenLink'; -import { Card, Chip, Empty, ErrorNotice, ReadControl, Skeleton } from '../../ui/kit'; +import { Bar, ErrorNotice, ReadControl, Skeleton } from '../../ui/kit'; +import { EmptyState, Section, StatusPill } from '../../ui/ds'; +import '../../styles/checks.css'; import { exportName, validateMd } from '../../lib/exports'; import { useExports } from '../../ui/Exports'; @@ -35,8 +37,27 @@ function FixButton({ action, what, w }: { action: FixAction; what: string; w: Re } const SEV: Record = { blocker: ['bad', 'alertCircle'], high: ['bad', 'alert'], medium: ['warn', 'alert'], low: ['info', 'info'] }; +const SEV_ORDER: ScanSeverity[] = ['blocker', 'high', 'medium', 'low']; -/** The `storebound scan` card: rejection risks with guideline, evidence file:line, fix and skill. */ +/** One check as a card: tone icon tile, title, detail lines, the fix, and its actions on the right. */ +function CheckCard({ tone, icon, title, children, actions, tags }: { tone: 'bad' | 'warn' | 'ok' | 'info'; icon: IconName; title: ReactNode; children?: ReactNode; actions?: ReactNode; tags?: ReactNode }) { + return ( +
+ +
+
{title}
+ {children} +
+
+ {tags &&
{tags}
} + {actions &&
{actions}
} +
+
+ ); +} + +/** The `storebound scan` section: rejection risks with guideline, evidence file:line, fix and skill; open risks first, + * accepted ones collapsed. */ function ScanCard({ project }: { project: Project }) { const s = useRead(project.id, 'scan', { network: false, title: t('checks.scan') }); const w = useWrite(project.id); @@ -57,43 +78,49 @@ function ScanCard({ project }: { project: Project }) { }, [project.id, firstAi, claude]); const sdks = Array.isArray(s.data?.sdks) ? s.data!.sdks : []; const asks = (Array.isArray(s.data?.declarations?.items) ? s.data!.declarations.items : []).filter(x => x.status === 'ask').length; + const keyed = rows.map(f => ({ f, k: keyOf(f) })); + const open = keyed.filter(x => !x.f.accepted).sort((a, b) => SEV_ORDER.indexOf(a.f.severity) - SEV_ORDER.indexOf(b.f.severity)); + const accepted = keyed.filter(x => !!x.f.accepted); + const card = ({ f, k }: { f: ScanFinding; k: string }) => { + const [tone, icon] = f.accepted ? ['ok', 'check'] as const : SEV[f.severity] ?? SEV.low; + const ev = Array.isArray(f.evidence) ? f.evidence : []; + return ( + {f.guideline}{f.title}} + tags={<>{t(f.accepted ? 'checks.sev.accepted' : `checks.sev.${f.severity}` as Parameters[0])}{f.store === 'apple' ? 'App Store' : 'Google Play'}} + actions={<>{!f.accepted && }{!f.accepted && fixable(f.action) && }}> + {ev.slice(0, 2).map((e, j) => {e.file}:{e.line}{e.text ? ` ${e.text}` : ''})} + {f.accepted ? {t('checks.accepted', { reason: f.accepted })} + : {f.fix} {f.skill}} + {!f.accepted && f.aiFix && !fixable(f.action) &&
{ s.refresh(); }} + stillThere={findings.some(x => same(x, f))} onActive={on => setAiActive(on ? f : null)} />
} +
+ ); + }; return ( - x.name).join(', ') }) : t('checks.scanSub')} pad={false} +
x.name).join(', ') }) : t('checks.scanSub')} actions={}> - {s.error &&
} - {!s.data ? (s.loading && !s.error ?
: null) - : !rows.length ? {t('checks.scanCleanText')} : ( -
- {rows.map(f => { - const [tone, icon] = f.accepted ? ['ok', 'check'] as const : SEV[f.severity] ?? SEV.low; - const ev = Array.isArray(f.evidence) ? f.evidence : []; - return ( -
- -
- {f.guideline} · {f.title} - {ev.slice(0, 2).map((e, j) => {e.file}:{e.line}{e.text ? ` ${e.text}` : ''})} - {f.accepted ? {t('checks.accepted', { reason: f.accepted })} - : {f.fix} {f.skill}} - {!f.accepted && } - {!f.accepted && f.aiFix && !fixable(f.action) && { s.refresh(); }} - stillThere={findings.some(x => same(x, f))} onActive={on => setAiActive(on ? f : null)} />} -
- {!f.accepted && fixable(f.action) && } - {t(f.accepted ? 'checks.sev.accepted' : `checks.sev.${f.severity}` as Parameters[0])} - {f.store === 'apple' ? 'App Store' : 'Google Play'} -
- ); - })} +
+ {s.error && } + {!s.data ? (s.loading && !s.error ? : null) + : !rows.length ? {t('checks.scanClean')}
{t('checks.scanCleanText')}
: ( + <> + {open.map(card)} + {accepted.length > 0 && ( +
+ {t('v2ins.cAccepted', { count: accepted.length })} +
{accepted.map(card)}
+
+ )} + + )} + {s.data && (asks > 0 || s.data.declarations?.changed) && ( +
+ {asks > 0 &&
{t('checks.scanAsk', { count: asks })}
} + {s.data.declarations?.changed &&
{t('checks.scanWrite')}
}
)} - {s.data && (asks > 0 || s.data.declarations?.changed) && ( -
- {asks > 0 &&
{t('checks.scanAsk', { count: asks })}
} - {s.data.declarations?.changed &&
{t('checks.scanWrite')}
} -
- )} - +
+
); } @@ -114,10 +141,10 @@ function ReportBar({ project }: { project: Project }) { finally { setBusy(false); } }; return ( - {t('checks.reportOpen')}}> - {null} - +
+ {t('checks.report')}{last ? reportSummary(last) : t('checks.reportSub')} + +
); } @@ -143,46 +170,77 @@ export function ChecksTab({ project }: { project: Project }) { const problems = [...(e?.errors ?? []), ...(e?.check?.problems ?? [])]; const warnings = e?.check?.warnings ?? []; const findings = [...(v.data?.findings ?? [])].sort((a, b) => ['blocker', 'warn', 'ok'].indexOf(a.level) - ['blocker', 'warn', 'ok'].indexOf(b.level)); + const vBlock = findings.filter(f => f.level === 'blocker'), vWarn = findings.filter(f => f.level === 'warn'), vOk = findings.filter(f => f.level === 'ok'); + const blockers = problems.length + vBlock.length; + const warns = warnings.length + vWarn.length; + const total = findings.length + problems.length + warnings.length; + const passed = vOk.length; + const checked = !!v.data && !!e; + const state: 'bad' | 'warn' | 'ok' | 'neutral' = blockers ? 'bad' : !checked ? 'neutral' : warns ? 'warn' : 'ok'; + const headline = blockers ? t('v2ins.cBlocked', { count: blockers }) : !checked ? t('v2ins.cNotRun') : t('v2ins.cReady'); + const finding = (f: Finding, i: number) => { + const [tone, icon] = LEVEL[f.level]; + return ( + {f.store === 'apple' ? 'App Store' : 'Google Play'}} + actions={<>{f.level !== 'ok' && fixable(f.action) && }}> + {f.fix && {f.fix}} + + ); + }; return ( -
-
-
- d.refreshPortfolio(false)} disabled={!!d.portfolioBusy}>{t('checks.again')}}> - {!e ?
: !problems.length && !warnings.length ? ( - {t('checks.cleanText')} - ) : ( -
- {problems.map((p, i) =>
{p}{t('checks.problem')}
)} - {warnings.map((w, i) =>
{w}{t('checks.warning')}
)} +
+
+
+ +
+ {t('v2ins.cScore')} +

{headline}

+

{v.data ? t('v2ins.cScoreSub', { ok: passed, total }) : t('checks.validateSub')}{v.data ? ` · ${v.fromCache ? t('common.cachedFrom', { when: ago(v.at) }) : t('common.readWhen', { when: ago(v.at) })}` : ''}

+ {total > 0 && }
- )} - - }> - {v.error &&
} - {!v.data ? ( - v.loading && !v.error ?
: {t('checks.validateEmptyText')} - ) : !findings.length ? {t('checks.readyText')} : ( -
- {findings.map((f, i) => { - const [tone, icon] = LEVEL[f.level]; - return ( -
- -
- {f.msg} - {f.fix && {f.fix}} -
- - {f.level !== 'ok' && fixable(f.action) && } - {f.store === 'apple' ? 'App Store' : 'Google Play'} -
- ); - })} +
+
+ {blockers}{t('v2ins.cBlockers')} + {warns}{t('v2ins.cWarnings')} + {passed}{t('v2ins.cPassedN')} +
+
+ + +
+
+ {v.error && } + +
+
+ {!e ? : null} + {problems.map((p, i) => {t('checks.problem')})} + {vBlock.map(finding)} + {!v.data && !v.error && (v.loading ? : {t('checks.validateEmpty')}
{t('checks.validateEmptyText')}
)} + {e && v.data && !blockers && {t('checks.ready')}
{t('checks.readyText')}
} +
+
+ + + + {(warnings.length > 0 || vWarn.length > 0) && ( +
+
+ {warnings.map((x, i) => {t('checks.warning')})} + {vWarn.map(finding)}
- )} - +
+ )} + + {vOk.length > 0 && ( +
+ {t('v2ins.cPassed', { count: vOk.length })} +
{vOk.map(finding)}
+
+ )} + +
); } diff --git a/apps/desktop/src/screens/tabs/Growth.tsx b/apps/desktop/src/screens/tabs/Growth.tsx index 7849f96..e4bbcc9 100644 --- a/apps/desktop/src/screens/tabs/Growth.tsx +++ b/apps/desktop/src/screens/tabs/Growth.tsx @@ -14,7 +14,9 @@ import { useNav } from '../../nav'; import { useData, useRead, useWrite } from '../../store'; import { useExports } from '../../ui/Exports'; import { Icon, StoreGlyph } from '../../ui/icons'; -import { Card, Chip, Empty, ErrorNotice, Kpi, Notice, ReadControl, Seg, Skeleton } from '../../ui/kit'; +import { ErrorNotice, Notice, ReadControl, Seg, Skeleton } from '../../ui/kit'; +import { EmptyState, Section, StatTile, StatusPill, tintStyle, useTint } from '../../ui/ds'; +import '../../styles/growth.css'; import { LineChart } from '../../ui/LineChart'; import { RankChart } from '../../ui/RankChart'; import { WriteButton } from '../../ui/WriteButton'; @@ -43,21 +45,39 @@ function Analytics({ projectId, hasApple, hasPlay, name, playReports }: { projec ); const sum = (xs: number[]) => xs.reduce((n, v) => n + v, 0); const reach = s ? sum(s.reach) : 0, inst = s ? sum(s.installs) : 0; + // deltas: the later half of the window against the earlier half (same number of days), in percent + const half = s ? Math.floor(s.dates.length / 2) : 0; + const change = (xs: number[]): number | null => { + if (half < 1) return null; + const before = sum(xs.slice(0, half)), after = sum(xs.slice(-half)); + return before ? Math.round(((after - before) / before) * 1000) / 10 : null; + }; + const convChange = (): number | null => { + if (!s || half < 1) return null; + const rb = sum(s.reach.slice(0, half)), ra = sum(s.reach.slice(-half)); + if (!rb || !ra) return null; + const cb = sum(s.installs.slice(0, half)) / rb, ca = sum(s.installs.slice(-half)) / ra; + return Math.round((ca - cb) * 1000) / 10; + }; + const deltaSub = half ? t('v2ins.gVsPrev', { count: half }) : t('gr.days', { count: s?.dates.length ?? 0 }); const effects = (a?.effects ?? []).filter(e => e.store === st).slice(-8).reverse(); return ( - {stores.length > 1 && }{actions}}> {none ? ( - {t('gr.noneText')}{hasPlay && !playReports ? ` ${t('gr.noBucket')}` : ''} - ) : r.error ?
: !a || !s ?
: !s.dates.length ? ( - {a.errors?.[st] ?? t('gr.noDataText')}{st === 'play' && !playReports ? ` ${t('gr.noBucket')}` : ''} + {t('gr.noneTitle')}
{t('gr.noneText')}{hasPlay && !playReports ? ` ${t('gr.noBucket')}` : ''}
+ ) : r.error ? : !a || !s ? : !s.dates.length ? ( + {t('gr.noDataTitle', { store: st === 'apple' ? 'App Store' : 'Google Play' })}
{a.errors?.[st] ?? t('gr.noDataText')}{st === 'play' && !playReports ? ` ${t('gr.noBucket')}` : ''}
) : ( -
-
- - - +
+
+ + + + +
+

{t('gr.days', { count: s.dates.length })} · {t('gr.conversionSub')}

{s.dates.length > 1 ? ( ) : {t('gr.oneDay')}} {effects.length > 0 && ( - +
{effects.map((e, i) => { @@ -79,17 +99,17 @@ function Analytics({ projectId, hasApple, hasPlay, name, playReports }: { projec - + ); })} -
{t('gr.change')}{t('col.date')}{t('gr.before')}{t('gr.after')}{t('col.diff')}
{date(e.event.date)} {pct(e.before.conversion ?? null, 1)}
{t('gr.daysN', { count: e.daysBefore })}
{pct(e.after.conversion ?? null, 1)}
{t('gr.daysN', { count: e.daysAfter })}
{dlt === null ? '–' : = 0 ? 'ok' : 'warn'} dot={false}>{`${dlt >= 0 ? '+' : ''}${num(dlt, 1)} %`}}{dlt === null ? '–' : = 0 ? 'ok' : 'warn'}>{`${dlt >= 0 ? '+' : ''}${num(dlt, 1)} %`}}
+
)} -

{t('gr.reading')}

+

{t('gr.reading')}

)} - + ); } @@ -106,20 +126,20 @@ function Aso({ projectId }: { projectId: string }) { ranks: a.ranks.series.find(s => s.storefront === row.storefront && s.keyword === row.keyword)?.ranks ?? [], })) : []; return ( - }> - {r.error ?
: !a ?
: ( -
-
- : !a ? : ( +
+
+ - - +
{a.ranks.dates.length > 1 && lines.length > 0 && } {a.ranks.rows.length > 0 && ( - +
{a.ranks.rows.slice(0, 8).map(x => ( @@ -127,25 +147,25 @@ function Aso({ projectId }: { projectId: string }) { - + ))} -
{t('gr.asoKeyword')}{t('col.store')}{t('gr.asoRank')}{t('col.diff')}{t('gr.asoBest')}
{x.keyword} {x.storefront} {x.rank === null ? '–' : `#${x.rank}`}{x.change === null ? x.arrow : `${x.arrow} ${x.change > 0 ? '+' : ''}${x.change}`}{x.change === null ? x.arrow : `${x.arrow} ${x.change > 0 ? '+' : ''}${x.change}`} {x.best === null ? '–' : `#${x.best}`}
+
)} {a.next.length > 0 && ( -
-
{t('gr.asoNext')}
-
    - {a.next.map((x, i) =>
  1. {x.what}
    {x.why}{x.command ? <> · {x.command} : null}
  2. )} +
    +
    {t('gr.asoNext')}
    +
      + {a.next.map((x, i) =>
    1. {i + 1}{x.what}{x.why}{x.command ? <> · {x.command} : null}
    2. )}
    )} -

    {t('gr.asoReading')}

    +

    {t('gr.asoReading')}

)} - + ); } @@ -164,21 +184,22 @@ function Experiments({ app }: { app: UnifiedApp }) { const editable = tests.find(x => !started(x) && !DONE.includes(x.state)); const asc = app.ios ? ascUrl(app.ios.app.id) : ascUrl(d.statusFor(app)?.app?.platforms.ios?.ascAppId); return ( - {r.data ? (r.fromCache ? t('common.cachedFrom', { when: ago(r.at) }) : t('common.readWhen', { when: ago(r.at) })) : t('gr.ppoSub')}} pad={false} +
{r.data ? (r.fromCache ? t('common.cachedFrom', { when: ago(r.at) }) : t('common.readWhen', { when: ago(r.at) })) : t('gr.ppoSub')}} actions={<> }> - {r.error &&
} - {!r.data ? (r.loading && !r.error ?
: {t('gr.ppoNotReadText')}) - : !tests.length ? {variants.length ? t('gr.ppoNoneText') : t('gr.ppoNoVariants')} : ( - +
+ {r.error && } + {!r.data ? (r.loading && !r.error ? : {t('gr.ppoNotRead')}
{t('gr.ppoNotReadText')}
) + : !tests.length ? {t('gr.ppoNone')}
{variants.length ? t('gr.ppoNoneText') : t('gr.ppoNoVariants')}
: ( +
{tests.map(x => ( - + @@ -190,10 +211,10 @@ function Experiments({ app }: { app: UnifiedApp }) { ))} -
{t('gr.test')}{t('gr.state')}{t('gr.traffic')}{t('gr.dates')}{t('gr.treatments')}{t('gr.owner')}
{x.name}{x.state.replace(/_/g, ' ').toLowerCase()}{x.state.replace(/_/g, ' ').toLowerCase()} {x.trafficProportion !== undefined ? `${x.trafficProportion} %` : '–'} {x.startDate ? `${date(x.startDate)} → ${x.endDate ? date(x.endDate) : t('gr.running')}` : t('gr.notStarted')} {x.treatments.length ? x.treatments.map(tr => t('gr.treatment', { name: tr.name, count: tr.locales })).join(' · ') : '–'}
+
)} {app.project ? ( -
+
{!variants.length ? {t('gr.ppoNoVariants')} : (
@@ -215,37 +236,39 @@ function Experiments({ app }: { app: UnifiedApp }) { )}

{t('gr.ppoNote')}

- ) :
{t('gr.ppoStoreOnly')}
} - + ) :
{t('gr.ppoStoreOnly')}
} +
+ ); } function PlayExperiments({ app }: { app: UnifiedApp }) { const nav = useNav(); return ( - {t('gr.playExpSub')}} +
{t('gr.playExpSub')}} actions={}> -
-

{t('gr.playExpText')}

+
+

{t('gr.playExpText')}

{app.project &&
}
- +
); } export function GrowthTab({ app }: { app: UnifiedApp }) { const d = useData(); + const hue = useTint(d.iconFor(app), app.name); const s = d.statusFor(app)?.summary; const hasApple = !!(s?.apple ?? app.ios), hasPlay = !!(s?.play ?? app.android); - if (app.project && !s) return ; + if (app.project && !s) return
; return ( - <> +
{app.project && } {app.project && (hasApple || hasPlay) && } -
+
{hasApple && } {hasPlay && }
- +
); } diff --git a/apps/desktop/src/screens/tabs/Health.tsx b/apps/desktop/src/screens/tabs/Health.tsx index 9986790..846e64e 100644 --- a/apps/desktop/src/screens/tabs/Health.tsx +++ b/apps/desktop/src/screens/tabs/Health.tsx @@ -9,31 +9,56 @@ import { api } from '../../api'; import { appleSignatureView, hintFor, type IssueView, issueMarkdown, playIssueView } from '../../lib/issues'; import type { IssueSample } from '../../lib/model'; import { useData, useRead } from '../../store'; -import { Icon } from '../../ui/icons'; -import { Bar, Card, Chip, Empty, ErrorFoot, ErrorNotice, Notice, ReadControl, Skeleton, Sparkline } from '../../ui/kit'; +import { Icon, type IconName, StoreGlyph } from '../../ui/icons'; +import { Bar, ErrorFoot, ErrorNotice, Notice, ReadControl, Skeleton, Sparkline } from '../../ui/kit'; +import { EmptyState, Section, StatusPill, tintStyle, useTint } from '../../ui/ds'; +import '../../styles/health.css'; import { exportName, healthMd } from '../../lib/exports'; import { useExports } from '../../ui/Exports'; import { StoreReadNotice } from '../../ui/StoreError'; -function Metric({ title, s }: { title: string; s: Series }) { +const toneWord = (tone: Series['tone']): string => (tone === 'bad' ? t('health.over') : tone === 'warn' ? t('health.near') : tone === 'ok' ? t('health.under') : t('common.unknown')); + +/** One big metric tile: the 28-day value, its state against the threshold, a large daily sparkline and its axis. */ +function Metric({ title, s, icon }: { title: string; s: Series; icon: IconName }) { return ( - {s.tone === 'bad' ? t('health.over') : s.tone === 'warn' ? t('health.near') : s.tone === 'ok' ? t('health.under') : t('common.unknown')}}> -
-
-
-
{pct(s.current)}
-
{t('health.current28')}
-
-
- {t('health.daily')} - {t('health.threshold', { value: pct(s.threshold) })} -
-
- -
{date(s.dates[0])}{date(s.dates[Math.floor(s.dates.length / 2)])}{date(s.dates.at(-1))}
+
+
+ {title} + {toneWord(s.tone)}
- +
+ {pct(s.current)} + {t('health.current28')} +
+ +
{date(s.dates[0])}{date(s.dates[Math.floor(s.dates.length / 2)])}{date(s.dates.at(-1))}
+
+ {t('health.daily')} + {t('health.threshold', { value: pct(s.threshold) })} + {t('health.window', { from: date(s.dates[0]), to: date(s.dates.at(-1)) })} +
+
+ ); +} + +/** Launch (startup) time from the App Store power and performance metrics, as the third big tile. */ +function Startup({ h }: { h: AppleHealth }) { + const m = h.metrics.find(x => /launch/i.test(`${x.category} ${x.metric}`)); + if (!m) return null; + const tone = m.goal === 'poor' ? 'bad' : m.goal === 'fair' ? 'warn' : m.goal ? 'ok' : 'neutral'; + return ( +
+
+ {t('v2ins.hStartup')} + {m.goal ? {m.goal} : null} +
+
+ {num(m.value, m.value < 10 ? 2 : 0)}{m.unit} + {m.metric} +
+
{t('v2ins.hStartupSub', { version: m.version })}
+
); } @@ -76,66 +101,58 @@ function IssueDetail({ app, v }: { app: UnifiedApp; v: IssueView }) { ); } -function Play({ h, app }: { h: PlayHealth; app: UnifiedApp }) { - const [open, setOpen] = useState(null); - const crash = healthSeries(h.crash, 'userPerceivedCrashRate', PLAY_THRESHOLDS.crash); - const anr = healthSeries(h.anr, 'userPerceivedAnrRate', PLAY_THRESHOLDS.anr); - const devices = (h.devices ?? []).slice(0, 6); - const worst = Math.max(PLAY_THRESHOLDS.perDevice, ...devices.map(x => Math.max(x.crash ?? 0, x.anr ?? 0))); +/** An issue as a card: a header button (type, title, where, counts) that opens its detail below (Enter / Space). */ +function IssueCard({ open, onToggle, tone, kind, title, where, stats, detail }: { open: boolean; onToggle: () => void; tone: 'bad' | 'warn' | 'info'; kind: string; title: string; where?: string; stats: React.ReactNode; detail: React.ReactNode }) { return ( - <> -
- - -
-
- - {devices.length ? ( -
- {devices.map(x => { - const v = Math.max(x.crash ?? 0, x.anr ?? 0); - return ( -
- {x.model} - = PLAY_THRESHOLDS.perDevice ? 'bad' : v >= PLAY_THRESHOLDS.perDevice * 0.8 ? 'warn' : 'ok'} label={x.model} /> - {pct(v)} -
- ); - })} -
- ) :

{t('health.noDevices')}

} -
- - {h.issues.length ? ( - - - - {h.issues.slice(0, 6).map((i, n) => ( - setOpen(open === n ? null : n)} cols={3} - head={<>
{i.type === 'ANR' ? 'ANR' : t('health.crashShort')}{i.cause || '?'}
-
{i.location}
} - cells={<>
} - detail={} /> - ))} - -
{t('col.issue')}{t('col.reports')}{t('col.users')}
{num(i.reports)}{num(i.users)}
- ) : } -
-
- +
+ + {open &&
{detail}
} +
); } -/** A table row that opens its detail row below it (click or Enter / Space). */ -function IssueRows({ open, onToggle, head, cells, detail, cols }: { open: boolean; onToggle: () => void; head: React.ReactNode; cells: React.ReactNode; detail: React.ReactNode; cols: number }) { +function Play({ h, app }: { h: PlayHealth; app: UnifiedApp }) { + const [open, setOpen] = useState(null); + const devices = (h.devices ?? []).slice(0, 6); + const worst = Math.max(PLAY_THRESHOLDS.perDevice, ...devices.map(x => Math.max(x.crash ?? 0, x.anr ?? 0))); return ( - <> - { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onToggle(); } }} tabIndex={0} aria-expanded={open} role="button"> -
{head}
- {cells} - - {open && {detail}} - +
+
+ {h.issues.length ? ( +
+ {h.issues.slice(0, 6).map((i, n) => ( + setOpen(open === n ? null : n)} tone={i.type === 'ANR' ? 'warn' : 'bad'} + kind={i.type === 'ANR' ? 'ANR' : t('health.crashShort')} title={i.cause || '?'} where={i.location} + stats={<>{num(i.reports)}{t('col.reports')}{num(i.users)}{t('col.users')}} + detail={} /> + ))} +
+ ) : {t('health.noIssues')}} +
+
+ {devices.length ? ( +
+ {devices.map(x => { + const v = Math.max(x.crash ?? 0, x.anr ?? 0); + return ( +
+ {x.model} + = PLAY_THRESHOLDS.perDevice ? 'bad' : v >= PLAY_THRESHOLDS.perDevice * 0.8 ? 'warn' : 'ok'} label={x.model} /> + {pct(v)} +
+ ); + })} +
+ ) : {t('health.noDevices')}} +
+
); } @@ -143,70 +160,83 @@ function Apple({ h, app }: { h: AppleHealth; app: UnifiedApp }) { const [open, setOpen] = useState(null); const maxCrash = Math.max(1, ...h.betaCrashes.map(b => b.count)); return ( -
- - {h.metrics.length ? ( - - - +
+
+ {h.signatures.length ? ( +
+ {h.signatures.slice(0, 5).map((s, i) => ( + setOpen(open === i ? null : i)} tone="bad" kind={s.type} + title={s.signature || s.type} where={t('health.build', { build: s.build })} + stats={{num(s.weight * 100, 1)}%} + detail={} /> + ))} +
+ ) : {t('health.noSignatures')}} +
+
+
+ {h.metrics.length ? ( +
{h.metrics.slice(0, 8).map((m, i) => ( -
- +
+ {m.metric}{m.category} · {m.version} + {num(m.value, m.value < 10 ? 2 : 0)} {m.unit} + {m.goal ? {m.goal} : –} +
))} - -
{t('col.metric')}{t('col.value')}{t('col.version')}{t('col.goal')}
{m.metric}
{m.category}
{num(m.value, m.value < 10 ? 2 : 0)} {m.unit}{m.version}{m.goal ? {m.goal} : '–'}
- ) : } -
-
- - {h.signatures.length ? ( - - - {h.signatures.slice(0, 5).map((s, i) => ( - setOpen(open === i ? null : i)} cols={2} - head={<>
{s.signature || s.type}
{s.type} · {t('health.build', { build: s.build })}
} - cells={
} - detail={} /> - ))} - -
{num(s.weight * 100, 1)}%
- ) : } -
- +
+ ) : {t('health.noMetrics')}} + +
{h.betaCrashes.length ? ( -
{h.betaCrashes.slice(0, 5).map(b => ( -
{t('health.build', { build: b.build })}{num(b.count)}
+
{h.betaCrashes.slice(0, 5).map(b => ( +
{t('health.build', { build: b.build })}{num(b.count)}
))}
- ) :

{t('health.noBetaCrashes')}

} - + ) : {t('health.noBetaCrashes')}} +
); } export function HealthTab({ app }: { app: UnifiedApp }) { + const d = useData(); + const hue = useTint(d.iconFor(app), app.name); const r = useRead(app.target, 'health', { network: true, title: t('tab.health'), appName: app.name }); useExports('health', [{ id: 'health-md', label: t('export.health'), icon: 'activity', kind: 'md', file: exportName(app.name, 'health'), disabled: r.data ? false : t('export.readFirst'), build: () => healthMd(app.name, r.data!) }]); if (!r.data) { - if (r.loading && !r.error) return ; + if (r.loading && !r.error) return
; return ( - - {t('health.read')}}>{t('health.emptyText')} - {r.error && } - +
+
+ {t('health.read')}}> + {t('health.emptyTitle')}
{t('health.emptyText')} +
+ {r.error && } +
+
); } const h = r.data; + const play = h.play !== undefined && !isError(h.play) ? h.play : null; + const apple = h.apple !== undefined && !isError(h.apple) ? h.apple : null; + const crash = play ? healthSeries(play.crash, 'userPerceivedCrashRate', PLAY_THRESHOLDS.crash) : null; + const anr = play ? healthSeries(play.anr, 'userPerceivedAnrRate', PLAY_THRESHOLDS.anr) : null; + const tiles = !!crash || !!(apple && apple.metrics.some(x => /launch/i.test(`${x.category} ${x.metric}`))); return ( - <> -
- - -
-

Google Play

+
+
+ {tiles && ( +
+ {crash && } + {anr && } + {apple && } +
+ )} +

Google Play

{h.play === undefined ? {t('health.noPlay')} : isError(h.play) ? : <>{h.play.issuesError && }} -

App Store

+

App Store

{h.apple === undefined ? {t('health.noApple')} : isError(h.apple) ? : } - +
); } diff --git a/apps/desktop/src/screens/tabs/Listings.tsx b/apps/desktop/src/screens/tabs/Listings.tsx index 44753b1..d4aa4bf 100644 --- a/apps/desktop/src/screens/tabs/Listings.tsx +++ b/apps/desktop/src/screens/tabs/Listings.tsx @@ -1,5 +1,6 @@ // Listings: per language and store, which listing fields are written and within the store limits (from the listing // files in the app folder), and how many screenshots are rendered per language. +import '../../styles/listings.css'; import { useState } from 'react'; import type { ListingField, ListingLocale, ListingsResult, Project } from '../../api'; import { type Key, t } from '../../i18n'; @@ -7,7 +8,8 @@ import { ago, num } from '../../lib/format'; import { useData, useRead, useWrite } from '../../store'; import { Icon, StoreGlyph } from '../../ui/icons'; import { WriteButton } from '../../ui/WriteButton'; -import { Card, Chip, Empty, ErrorNotice, Kpi, Notice, Skeleton } from '../../ui/kit'; +import { Chip, ErrorNotice, Notice, Skeleton } from '../../ui/kit'; +import { EmptyState, Section, StatTile, StatusPill } from '../../ui/ds'; import { reads } from '../../api'; import { exportName, listingsMd } from '../../lib/exports'; import { useExports } from '../../ui/Exports'; @@ -39,25 +41,41 @@ function Ring({ value }: { value: number }) { ); } -function StoreGrid({ store, locales }: { store: 'play' | 'apple'; locales: ListingLocale[] }) { - const fields = locales.find(l => l[store])?.[store]?.fields.map(f => f.field) ?? []; - const done = (l: ListingLocale) => { - const fs = l[store]?.fields.filter(f => f.required) ?? []; - return fs.length ? fs.filter(f => f.state === 'ok').length / fs.length : 0; - }; +/** One language as the store page shows it: the fields in store order, each with its length against the limit. */ +function LangPage({ store, l }: { store: 'play' | 'apple'; l: ListingLocale }) { + const fs = l[store]?.fields ?? []; + const req = fs.filter(f => f.required); + const v = req.length ? req.filter(f => f.state === 'ok').length / req.length : 0; + const bad = fs.filter(f => f.state === 'missing' || f.state === 'over').length; return ( - -
-
{t('col.language')}{fields.map(f => {t(FIELD_KEY[f] ?? 'lst.title')})}{t('lst.complete')}
- {locales.map(l => ( -
-
{l.lang}{l[store]?.code ?? ''}{l.rtl && RTL}
- {fields.map(f => x.field === f)} />)} -
+
= 1 ? ' done' : ''}`} data-lang={l.lang} aria-label={`${store === 'play' ? 'Google Play' : 'App Store'} ${l.lang}`}> +
+ {l.lang} + {l[store]?.code ?? ''} + {l.rtl && RTL} + + {bad > 0 ? {t('v2lst.toFix', { count: bad })} : v >= 1 ? {t('v2lst.ready')} : null} + +
+
+ {fs.map(f => ( +
+ {t(FIELD_KEY[f.field] ?? 'lst.title')} +
))}
- +
+ ); +} + +function StoreGrid({ store, locales }: { store: 'play' | 'apple'; locales: ListingLocale[] }) { + return ( +
{store === 'play' ? 'Google Play' : 'App Store'}} icon="text" sub={store === 'play' ? t('lst.playSub') : t('lst.appleSub')}> +
+ {locales.filter(l => l[store]).map(l => )} +
+
); } @@ -71,7 +89,7 @@ function StoreActions({ project, langs }: { project: Project; langs: string[] }) const ios = !!e?.app?.platforms.ios, android = !!e?.app?.platforms.android; const only = lang ? { lang } : {}; return ( - +
{android && (
@@ -99,7 +117,7 @@ function StoreActions({ project, langs }: { project: Project; langs: string[] })

{t('act.note')}

- +
); } @@ -110,7 +128,7 @@ export function ListingsTab({ project }: { project: Project }) { build: async () => { const x = await reads.listingText(project.id); if (!x.data) throw new Error(x.output || t('export.failed')); return listingsMd(project.name, x.data); } }]); if (!r.data) { if (r.error) return ; - return ; + return
; } const L = r.data; const missing = L.locales.reduce((n, l) => n + [...(l.play?.fields ?? []), ...(l.apple?.fields ?? [])].filter(f => f.state === 'missing' || f.state === 'over').length, 0); @@ -118,20 +136,19 @@ export function ListingsTab({ project }: { project: Project }) { const shots = L.locales.reduce((n, l) => n + (l.screenshots ?? 0), 0); const noFiles = !L.files.play && !L.files.apple; return ( - <> -
- l.lang).join(' · ')} /> - - - l.screenshots !== null) ? shots : '–'} sub={L.locales.some(l => l.screenshots !== null) ? t('lst.screenshotsSub') : t('lst.noRenders')} /> +
+
+ l.lang).join(' · ')} /> + + + l.screenshots !== null) ? shots : '–'} sub={L.locales.some(l => l.screenshots !== null) ? t('lst.screenshotsSub') : t('lst.noRenders')} />
{L.problems.map((p, i) => {p})} {!noFiles && l.lang)} />} {noFiles ? ( - - {t('lst.noFilesText')} -
storebound init{t('lst.noFilesHint')}
-
+
+ storebound init{t('lst.noFilesHint')}
}>{t('lst.noFilesTitle')} {t('lst.noFilesText')} + ) : ( <> {L.files.play && } @@ -139,6 +156,6 @@ export function ListingsTab({ project }: { project: Project }) { )}

{t('lst.foot', { when: ago(r.at) })}

- +
); } diff --git a/apps/desktop/src/screens/tabs/LiveArt.tsx b/apps/desktop/src/screens/tabs/LiveArt.tsx index 92866fd..f86dbea 100644 --- a/apps/desktop/src/screens/tabs/LiveArt.tsx +++ b/apps/desktop/src/screens/tabs/LiveArt.tsx @@ -2,14 +2,16 @@ // thumbnails (art.thumb: one data: URL each, loaded as they scroll into view; the window loads no remote images // itself) and, for an app folder, whether the folder has the same file. "Pull from stores" runs art.pull (dry run, // native dialog, then the files are written: local only, read-only on the stores). Store-only apps: read-only. +import '../../styles/art.css'; import { useEffect, useMemo, useRef, useState } from 'react'; import { api, type ArtThumb, type LiveArtResult, type LiveArtTile, type Project, type ToolResult } from '../../api'; import { t } from '../../i18n'; import { num } from '../../lib/format'; import { useRead, useWrite } from '../../store'; import { Icon } from '../../ui/icons'; -import { Card, Chip, Empty, ErrorNotice, Notice, ReadControl, Skeleton } from '../../ui/kit'; +import { Chip, Empty, ErrorNotice, Notice, ReadControl, Skeleton } from '../../ui/kit'; import { WriteButton } from '../../ui/WriteButton'; +import { Section, StatusPill } from '../../ui/ds'; // thumbnails by target + URL, three at a time const cache = new Map(); @@ -56,12 +58,12 @@ function LiveThumb({ target, tile, name }: { target: string; tile: LiveArtTile; const w = tile.w ?? 9, h = tile.h ?? 16; const state = tile.state === 'n/a' ? null : tile.state; return ( -
+
w ? 'portrait' : 'landscape'}`} style={{ ['--ar' as string]: `${w} / ${h}` }} data-live-tile={tile.state}>
{src ? : {src === null && tile.thumb ? <>{t('art.liveNoThumb')} : }}
{name}{tile.w && tile.h ? `${tile.w}×${tile.h}` : ''}
- {state && {t(state === 'same' ? 'art.liveSame' : state === 'differs' ? 'art.liveDiffers' : 'art.liveMissing')}} + {state && {t(state === 'same' ? 'art.liveSame' : state === 'differs' ? 'art.liveDiffers' : 'art.liveMissing')}}
); } @@ -84,10 +86,10 @@ export function LiveArt({ target, project }: { target: string; project?: Project const actions = <>{pull}; if (!data) { return ( - +
{r.loading && !r.error ?
: { r.refresh(); }}>{t('art.liveRead')}}>{r.error ?? t('art.liveEmptyText')}} - +
); } const total = data.sets.reduce((n, s) => n + s.tiles.length, 0); @@ -95,7 +97,7 @@ export function LiveArt({ target, project }: { target: string; project?: Project const missing = data.sets.reduce((n, s) => n + s.tiles.filter(x => x.state === 'missing').length, 0); const sub = data.stores.map(s => `${s.store === 'apple' ? 'App Store' : 'Google Play'}: ${s.ok ? t('art.liveCount', { count: s.images }) : t('art.liveFailed')}${s.version ? ` · ${s.version}` : ''}`).join(' · '); return ( - +
{data.stores.filter(s => !s.ok).map(s =>
)}
{!project && {t('art.liveReadOnly')}} @@ -120,7 +122,7 @@ export function LiveArt({ target, project }: { target: string; project?: Project {sets.map(s => (

{s.label}{s.lang && {s.lang}/{s.size}}{s.store === 'apple' ? 'App Store' : 'Google Play'}{t('art.count', { count: s.tiles.length })}

-
(s.tiles[0].h ?? 1) ? '260px' : '150px' }}> +
(s.tiles[0].h ?? 1) ? '260px' : '170px' }}> {s.tiles.map(tile => )}
@@ -128,6 +130,6 @@ export function LiveArt({ target, project }: { target: string; project?: Project
)}
{project ? t('art.liveFoot') : t('art.liveFootStoreOnly')}
- +
); } diff --git a/apps/desktop/src/screens/tabs/Prices.tsx b/apps/desktop/src/screens/tabs/Prices.tsx index 4f51cb1..7dc37f3 100644 --- a/apps/desktop/src/screens/tabs/Prices.tsx +++ b/apps/desktop/src/screens/tabs/Prices.tsx @@ -1,6 +1,7 @@ // Prices: what every product costs in every territory on both stores (`prices export --json`, read-only), the price // sheet as a CSV (save it anywhere, or write store/prices.csv for the terminal), and a price sheet compared with the // stores (`prices import --dry --json`) and applied as an owner action: dry run, native dialog, then the real run. +import '../../styles/prices.css'; import { useEffect, useMemo, useState } from 'react'; import { api, errorText, type PricesCurrent, type PricesDiff, type Project } from '../../api'; import { t } from '../../i18n'; @@ -10,7 +11,11 @@ import { changePct, diffSummary, priceMatrix, priceStats, type RegionRow, region import { type ReadState, useData, useRead, useWrite } from '../../store'; import { type ExportItem, useExports, useRunExport } from '../../ui/Exports'; import { Icon, StoreGlyph } from '../../ui/icons'; -import { Card, Chip, Empty, ErrorNotice, Kpi, Notice, ReadControl, Skeleton } from '../../ui/kit'; +import { Chip, Empty, ErrorNotice, Notice, ReadControl, Skeleton } from '../../ui/kit'; +import { Section, StatTile } from '../../ui/ds'; + +/** A region code as a small badge (the stores use ISO country codes; longer names stay as text). */ +const Region = ({ code }: { code: string }) => {code}; import { WriteButton } from '../../ui/WriteButton'; const GAP = 10; @@ -18,7 +23,7 @@ const GAP = 10; function PriceStack({ r, apple, play }: { r: RegionRow | undefined; apple: boolean; play: boolean }) { if (!r) return –; return ( -
+
= GAP ? (r.gapPct > 25 ? ' gap-bad' : ' gap-warn') : ''}`}> {apple && {r.apple ? money(r.apple.price, r.apple.currency) : '–'}} {play && {r.play ? money(r.play.price, r.play.currency) : '–'}} {r.gapPct !== null && r.gapPct >= GAP && 25 ? 'bad' : 'warn'} dot={false}>{`Δ ${num(r.gapPct, 0)} %`}} @@ -34,7 +39,7 @@ function SheetDiff({ project, diff, sheet, onApplied }: { project: Project; diff const sum = d ? diffSummary(d.diff, d.changed) : null; const name = sheet.csv ? sheet.csv.split(/[\\/]/).pop() : d?.csv.split(/[\\/]/).pop() ?? 'prices.csv'; return ( - {sum && sum.pairs > 0 && {t('prices.apply', { count: sum.pairs })}} @@ -51,8 +56,8 @@ function SheetDiff({ project, diff, sheet, onApplied }: { project: Project; diff {sum!.down > 0 && {t('prices.dDown', { count: sum!.down })}} {t('prices.dProducts', { list: sum!.products.join(', ') })}
-
- +
+
{rows.slice(0, 200).map((r, i) => { @@ -61,7 +66,7 @@ function SheetDiff({ project, diff, sheet, onApplied }: { project: Project; diff - + @@ -76,7 +81,7 @@ function SheetDiff({ project, diff, sheet, onApplied }: { project: Project; diff
{t('prices.applyNote')}
)} - + ); } @@ -109,18 +114,18 @@ export function PricesTab({ project }: { project: Project }) { try { const f = await api.pickPriceSheet(project.id); if (f) setSheet({ csv: f }); } catch (x) { d.toast({ kind: 'bad', title: t('prices.pickFailed'), detail: errorText(x) }); } }; - if (!e) return ; + if (!e) return
; if (!s?.products) { return ( - +
{t('prices.emptyText')}
products: [{'{'} id, type, usd {'}'}]{t('prices.emptyHint')}
- +
); } return ( - <> - +
runExport(exportItem)} disabled={!p}>{t('prices.exportCsv')}}>
@@ -136,33 +141,33 @@ export function PricesTab({ project }: { project: Project }) {

{t('prices.sheetNote')}

- +
{sheet && { cur.refresh(); diff.refresh(); }} />} {cur.error && } {!p ? ( - cur.loading && !cur.error ? : ( - + cur.loading && !cur.error ?
: ( +
{t('prices.readNow')}}>{t('prices.notReadText')} - +
) ) : ( <> -
- - - - `${m.product} (${m.store === 'apple' ? 'App Store' : 'Play'})`).join(', ') : t('prices.kMissingNone')} tone={stats!.missing ? 'bad' : undefined} /> +
+ + + + `${m.product} (${m.store === 'apple' ? 'App Store' : 'Play'})`).join(', ') : t('prices.kMissingNone')} tone={stats!.missing ? 'bad' : undefined} />
- }> -
-
{t('col.item')}{t('col.store')}{t('col.region')}{t('prices.colStarts')}{t('prices.colNow')}{t('prices.colNew')}{t('col.diff')}
{r.product} {r.store === 'apple' ? 'App Store' : 'Google Play'}{r.region} {r.startDate ?? t('prices.now')} {r.from === null ? '–' : money(r.from, r.currency)} {money(r.to, r.currency)}
- {matrix!.regions.map(r => )} +
+
{t('col.item')}{r}
+ {matrix!.regions.map(r => )} {matrix!.rows.map(row => ( setProduct(row.product)}> @@ -174,19 +179,19 @@ export function PricesTab({ project }: { project: Project }) {
{t('col.item')}
App StoreGoogle Play{t('prices.autoLegend')}{t('prices.gapLegend', { pct: GAP })}
- - +
setQ(ev.target.value)} placeholder={t('prices.searchRegion')} aria-label={t('prices.searchRegion')} />
}> -
- +
+
{apple && }{apple && }{play && } {regions.map(r => ( - - + = GAP ? (r.gapPct > 25 ? 'gap-bad' : 'gap-warn') : undefined}> + {apple && } {apple && } {play && } @@ -196,10 +201,10 @@ export function PricesTab({ project }: { project: Project }) {
{t('col.region')}App Store{t('prices.colKind')}Google Play{t('col.priceGap')}
{r.region}
{r.apple ? money(r.apple.price, r.apple.currency) : –}{r.scheduled &&
{t('prices.scheduled', { price: money(r.scheduled.price, r.scheduled.currency), date: r.scheduled.startDate ?? '' })}
}
{r.apple ? {r.apple.kind === 'auto' ? t('prices.auto') : t('prices.manual')} : null}{r.play ? money(r.play.price, r.play.currency) : –}
- +
{p.missing.length > 0 && {t('prices.missingNote', { list: p.missing.map(m => `${m.product} (${m.store === 'apple' ? 'App Store' : 'Google Play'})`).join(', ') })}} )} - +
); } diff --git a/apps/desktop/src/screens/tabs/Releases.tsx b/apps/desktop/src/screens/tabs/Releases.tsx index 29a4c53..498306e 100644 --- a/apps/desktop/src/screens/tabs/Releases.tsx +++ b/apps/desktop/src/screens/tabs/Releases.tsx @@ -3,7 +3,7 @@ // resubmit / in-app purchases and the Google Play production release as owner actions, the Play steps without an API // as console plans. Releasing an approved version (manual release) stays in App Store Connect. import { plainError } from '../../../../../cli/lib/google-errors'; -import { useState } from 'react'; +import { type CSSProperties, type ReactNode, useState } from 'react'; import type { AppStatus, ReleaseTrain, StoreRelease } from '../../api'; import { laneGap, storesDiffer } from '../../../../../cli/lib/train'; import type { UnifiedApp } from '../../lib/identity'; @@ -14,8 +14,10 @@ import { type Lane, STAGES, type TestFlightStatus, trainLanes, versionHistory } import { useData, useRead, useWrite } from '../../store'; import { Icon, StoreGlyph } from '../../ui/icons'; import { RolloutBar } from '../../ui/charts'; -import { Card, Chip, Empty, Notice, PhaseChip, phaseLabel, Skeleton, storeName } from '../../ui/kit'; +import { Card, Empty, Notice, PhaseChip, phaseLabel, Skeleton, storeName } from '../../ui/kit'; +import { EmptyState, Section, StatusPill, tintStyle, useTint } from '../../ui/ds'; import { AppleSubmitCard, PlayProductionCard } from './Submit'; +import '../../styles/releases.css'; const STAGE_KEY: Record<(typeof STAGES)[number], Key> = { build: 'stage.build', testing: 'stage.testing', review: 'stage.review', live: 'stage.live', rollout: 'stage.rollout' }; @@ -39,32 +41,55 @@ function gapText(lane: Lane, version: string, st: AppStatus): { who: string; lin return { kind: g.kind, who: t('tl.notOnStore'), line: t('tl.notOnStore') }; } -function LaneRow({ lane, version, st }: { lane: Lane; version: string; st: AppStatus }) { +/** One store's card of a release train: store mark, version (build), the current state as a pill, the five stages + * as a stepper, a big rollout ring when it is rolling out, and that store's rollout controls. */ +function LaneRow({ lane, version, st, app }: { lane: Lane; version: string; st: AppStatus; app: UnifiedApp }) { const r = lane.release; const gap = lane.at < 0 ? gapText(lane, version, st) : null; + const ph = r ? phaseLabel(r) : null; + const rolling = lane.at === STAGES.length - 1 && lane.share !== null; + const ringTone = lane.tone === 'bad' ? 'bad' : (lane.share ?? 0) >= 1 ? 'ok' : 'accent'; return ( -
-
- -
-
{storeName(lane.store)}
-
{r ? `${r.version ?? version}${r.build ? ` (${r.build})` : ''}` : gap!.who}
+
+
+ +
+
{storeName(lane.store)}
+
{r ? `${r.version ?? version}${r.build ? ` (${r.build})` : ''}` : gap!.who}
-
- {gap ?
{gap.line}
: STAGES.map((s, i) => { - const cls = i < lane.at ? 'done' : i === lane.at ? `cur ${lane.tone}` : ''; - const last = s === 'rollout'; - return ( -
- {i < lane.at && } - {last && i === lane.at && lane.share !== null ? ( -
= 1 ? 'ok' : 'accent'} label={t('tl.rolloutAria')} /> - {lane.share >= 1 ? t('tl.everyone') : `${share(lane.share)}${r?.phased?.day ? ` · ${t('tl.day', { day: r.phased.day })}` : ''}`}
- ) : {stageCaption(lane, i)}} -
- ); - })} -
+ {ph && {ph.text}} + + {gap ?
{gap.line}
: ( +
+
    + {STAGES.map((s, i) => { + const cls = i < lane.at ? 'done' : i === lane.at ? `cur ${lane.tone}` : 'todo'; + const cap = stageCaption(lane, i); + return ( +
  1. + {i < lane.at ? : {i + 1}} + {t(STAGE_KEY[s])} + {cap && {cap}} +
  2. + ); + })} +
+ {rolling && lane.share !== null && ( +
+ +
+ {lane.share >= 1 ? t('tl.everyone') : `${share(lane.share)}${r?.phased?.day ? ` · ${t('tl.day', { day: r.phased.day })}` : ''}`} + {t('v2rel.ofUsers')} + +
+
+ )} +
+ )} + {r && app.project && } + ); } @@ -122,19 +147,22 @@ function Train({ title, train, tf, tone, app, st }: { title: string; train: Rele // "Live" only when a store has it live or rolling out; a Play release whose store page could not be checked is not const label = differ ? t('tl.current') : tone === 'ok' && !lanes.some(l => l.release && ['live', 'rollout', 'halted'].includes(l.release.phase)) ? t('tl.released') : title; const ver = differ ? t('tl.bothVersions', { play: differ.android, ios: differ.ios }) : train.version; + const created = train.ios?.date ? t('tl.created', { date: date(train.ios.date) }) : null; return ( - {ver}{label}} - sub={[train.ios?.date ? t('tl.created', { date: date(train.ios.date) }) : null].filter(Boolean).join(' · ') || undefined}> -
-
{t('tl.store')}{STAGES.map(s => {t(STAGE_KEY[s])})}
- {lanes.map(l => )} -
- {lanes.some(l => l.release) && app.project && ( -
- {lanes.map(l => l.release && )} +
+
+
+ {t('v2rel.version')} + {ver}
- )} - + {label} + + {created && {created}} +
+
+ {lanes.map(l => )} +
+
); } @@ -142,22 +170,26 @@ export function ReleasesTab({ app }: { app: UnifiedApp }) { const d = useData(); const l = d.liveFor(app); const project = app.project; + const hue = useTint(d.iconFor(app), app.name); const tf = useRead(app.target, 'apple.testflight_status', { network: true, title: 'TestFlight', skip: !app.ios && !d.statusFor(app)?.app?.platforms.ios }); const sum = project ? d.statusOf(project)?.summary : null; const submit = project && (sum?.apple || sum?.play) ? ( -
-

{t('sub.section')}

-
+
+
+

{t('sub.section')}

+

{t('releases.ownerNote')}

+
+
{sum?.apple && } {sum?.play && }
-

{t('releases.ownerNote')}

) : null; + const wrap = (children: ReactNode) =>
{children}
; - if (!l && d.portfolioBusy === 'live') return <>{submit}; + if (!l && d.portfolioBusy === 'live') return wrap(<>{submit}); if (!l) { - return ( + return wrap( <> @@ -166,12 +198,12 @@ export function ReleasesTab({ app }: { app: UnifiedApp }) { }>{t('releases.notReadText')} {submit} - + , ); } const history = versionHistory(l.release.all ?? []); const errs = Object.entries(l.storeErrors); - return ( + return wrap( <> {errs.map(([s, msg]) => { const when = l.staleStores?.[s as 'ios']; @@ -179,17 +211,18 @@ export function ReleasesTab({ app }: { app: UnifiedApp }) { })} {l.release.next && } {l.release.current && } - {!l.release.next && !l.release.current && {t('releases.noVersionsText')}} + {!l.release.next && !l.release.current &&
{t('releases.noVersions')} {t('releases.noVersionsText')}
} - +
{t('v2rel.versions', { count: history.length })} : undefined}> {history.length ? ( -
- +
+
{history.map(h => ( - + @@ -200,10 +233,10 @@ export function ReleasesTab({ app }: { app: UnifiedApp }) {
{t('col.version')}App Store{t('col.build')}Google Play{t('col.versionCode')}{t('col.track')}
{[...new Set([h.version, h.ios?.version, h.android?.version].filter(Boolean))].join(' / ')}{[...new Set([h.version, h.ios?.version, h.android?.version].filter(Boolean))].join(' / ')} {h.ios ? : –} {h.ios?.build ?? '–'} {h.android ? : –}
- ) : } - + ) :
{t('releases.noVersions')}
} +
{submit} - + , ); } diff --git a/apps/desktop/src/screens/tabs/Reviews.tsx b/apps/desktop/src/screens/tabs/Reviews.tsx index 95b5348..d5a8152 100644 --- a/apps/desktop/src/screens/tabs/Reviews.tsx +++ b/apps/desktop/src/screens/tabs/Reviews.tsx @@ -7,10 +7,12 @@ import type { UnifiedApp } from '../../lib/identity'; import { t } from '../../i18n'; import { date, num } from '../../lib/format'; import { draftName, filterReviews, type Review, type ReviewFilter, starStats } from '../../lib/model'; -import { useRead, useWrite } from '../../store'; +import { useData, useRead, useWrite } from '../../store'; import { WriteButton } from '../../ui/WriteButton'; import { Icon, StoreGlyph } from '../../ui/icons'; -import { Bar, Card, Chip, Empty, ErrorFoot, ReadControl, Seg, Skeleton, Stars } from '../../ui/kit'; +import { Bar, ErrorFoot, ReadControl, Seg, Skeleton, Stars } from '../../ui/kit'; +import { EmptyState, Section, StatusPill, tintStyle, Toolbar, useTint } from '../../ui/ds'; +import '../../styles/reviews.css'; import { exportName, reviewsCsv } from '../../lib/exports'; import { useExports } from '../../ui/Exports'; @@ -29,57 +31,60 @@ function Detail({ r, draft, w, onChanged }: { r: Review; draft: ReplyDraft | und const live = text && INCENTIVE.some(x => x.test(text)) ? t('reviews.incentive') : len > limit ? t('reviews.tooLong', { limit }) : null; const file = draft ? base(draft.file) : ''; return ( - {r.title || t('reviews.noTitle')}} - sub={{r.store === 'apple' ? 'App Store' : 'Google Play'}{r.where ? ` · ${r.where}` : ''} · {date(r.date)}{r.appVersion ? ` · ${t('reviews.version', { v: r.appVersion })}` : ''}}> -
-

{r.body || t('reviews.noText')}

- {r.reply && ( -
- {t('reviews.currentReply')}{r.reply.date ? ` · ${date(r.reply.date)}` : ''} -
{r.reply.text}
-
- )} -
-
-
- {t('reviews.draft')} - {draft && (draft.sent ? {t('reviews.sentOn', { date: date(draft.sent) })} : draft.approved ? {t('reviews.approved')} : {t('reviews.notApproved')})} -
- {!draft ?

{t('reviews.noDraft')}

: draft.sent ? ( -
{draft.reply}
- ) : ( - <> -