diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml index 4014e849..f92a44c7 100644 --- a/.forgejo/workflows/ci.yml +++ b/.forgejo/workflows/ci.yml @@ -1,5 +1,7 @@ # bun run ci on every push to main and every pull request into main: adapters, desktop version, tests, typecheck, # desktop i18n / typecheck / build, desktop boot check (headless Chromium), desktop Rust tests and clippy, scrub. Runs on the VDS runner (docs/desktop-release.md). +# tools/ci.ts runs the steps as a task graph and the tests as parallel shards (CPU cores - 1, max 8) on the one +# self-hosted runner, so a job matrix would only queue; CI=full makes it run the Rust steps on every push. # Publishes nothing: site/ is still published by Jenkins. name: ci @@ -14,6 +16,7 @@ env: BUN_VERSION: '1.4.0' CARGO_TERM_COLOR: never CARGO_INCREMENTAL: '0' + CI: full jobs: ci: @@ -40,6 +43,12 @@ jobs: apps/desktop/src-tauri/target key: ci-${{ runner.os }}-${{ hashFiles('bun.lock', 'apps/desktop/src-tauri/Cargo.lock') }} restore-keys: ci-${{ runner.os }}- + # recorded test durations (shard balance) and tsc's incremental build info + - uses: actions/cache@v4 + with: + path: node_modules/.cache/storebound-ci + key: ci-timings-${{ runner.os }}-${{ github.sha }} + restore-keys: ci-timings-${{ runner.os }}- - name: Bun and Rust run: | P="${FORGEJO_PATH:-$GITHUB_PATH}" diff --git a/AGENTS.md b/AGENTS.md index eca863aa..e39728ae 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -86,5 +86,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t ## Working on storebound itself - Bun + TypeScript strict, zero runtime dependencies. `bun run ci` must pass (adapters fresh, tests, typecheck, scrub). +- 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`. - Never commit credentials, account / team / issuer / key / app ids or personal data; placeholders use example.com. diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c73be88..72782085 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,43 @@ `agreement` field is outlined whatever its answer). The log and guidance say the package name is set by the first AAB upload (`play upload --track internal` / `flow run release`). - In `--dry`, the `console fill` list, the MCP / desktop form list and the desktop App info "Play Console forms" card. +- Faster CI: `bun run ci` runs as a task graph (independent steps at once, `[step]`-prefixed output, fail fast, time + per step) with the tests split into parallel shards (CPU cores - 1, max 8) balanced by recorded durations, browser + suites in shards of their own. New `bun run ci:quick` for the inner loop: typecheck plus the tests related to the + change against origin/main (through imports) plus scrub. The desktop Rust host runs only when `src-tauri` or the + sidecar build changed (`CI=full` always; Forgejo CI sets it). Fixed sleeps in tests became event waits. +- ASO from official and public data only (no scraping, no third-party ASO services): + - `aso competitors [--term ] [--storefront us,tr] [--top 10]`: per keyword of the locale's keyword field (and + `--term`) the top apps in the iTunes Search API (name, developer, rating count, first release, last update, genre + localized to the storefront), the words in their names that the name / subtitle / keywords do not cover (only + words of two or more developers: a one-developer word is likely a brand) and the apps new in a term's top N since + the last snapshot (`.storebound/aso/competitors/.json`). Same pace as `aso rank` (one call every 3.5 s, stop + on 403 / 429). Competitor subtitles are not in any public API and are not shown. + - `aso suggest [--locale] [--fresh] [--offline] [--write]`: keyword candidates from the own name / subtitle / + description (words and two-word phrases), competitor names, the localized category names (from the Search API's + `genres`) and, with Apple Ads credentials, the Apple Ads Platform API keyword suggestions + (`POST /v1/suggestions/keywords/query`, relative popularity 0-100). Each candidate shows relevance (own text, + competitor names), competition (top apps with the word in their name) and popularity (Apple Ads only, else + "unknown"). Proposes a keyword field per locale that fits 100 bytes with the existing rules (no spaces, no + duplicates, plural-insensitive, no name / subtitle words, no filler or category words; current terms kept first + unless `--fresh`) as old -> new; `--write` puts it into `store/appstore.md` with a draft line that `check --aso` and + `aso audit` report until the owner deletes it. + - `aso audit`: one offline report: `check --aso` findings, the cross-locale free keyword room, rank trend arrows from + the `aso rank` snapshots, competitor coverage gaps, Play short description use and keyword density, App Store + conversion from the analytics snapshots, Product Page Optimization / Play listing experiment ideas (suggestions + only: PPO cannot test the subtitle; Play experiments stay in Play Console) and the next 3 actions. + - MCP: read-only `aso_competitors` (saves no snapshot), `aso_suggest` (never writes), `aso_audit` (offline). + - Desktop: an ASO card on the Growth tab (`aso.audit`): keyword field state, keywords ranked, coverage gaps, the + rank trend of the best three keywords (visx, rank 1 at the top), the rank table and the next 3 actions. + - `examples/demo-app` has listing files (`store/appstore.md`, `store/listing.md`) to try the ASO commands on. +- Local font files in `shots.fonts`: `title`, `body` and `fallback[]` take, besides a Google Fonts family, a path + (relative to the config) or `{ family, file, weight?, style?, license? }` (TTF / OTF / WOFF / WOFF2, validated by + extension and signature; the family comes from the name table when not given). `shots fonts` checks the file's cmap + per language, tries the listed fallbacks in order before the automatic Noto ones (`pl title: ę ł ą Ł not in ER + Display -> Noto Sans Display`), errors when nothing covers a character, and records the file in fonts.json with its + path, sha256 and license. Render and `shots video` serve it in place at `/fonts/local/...` (never copied); the hash + in fonts.css invalidates the capture cache, and render refuses a font file changed since `shots fonts`. `shots check` + treats the local font and listed fallbacks as configured and warns when a local font has no license note. - Idempotency: every store write is an upsert; running a command twice, or again after a crash or a lost answer, leaves exactly one of each thing (table of every write path: `docs/idempotency.md`). - New `cli/lib/upsert.ts`: `findOrCreate` looks again with a fresh GET right before a create and asks a journal of @@ -70,6 +107,18 @@ with zero writes on the second run, a crash in the middle of a screenshot set, IAP and subscription creates whose answer is lost, 409 duplicates, the list lag after a crash, Play edit error paths and an unclear commit, the lock. Pitfall 9 in `docs/pitfalls.md` and the store-pitfalls skill. + - The last open rows are closed (`docs/idempotency.md` has none left): + - `apple listing`: the App Store version is created through `findOrCreate` (a fresh look right before the create, + the journal for the list lag, a lost answer looks first); localizations through `createOnce` (409 = found, then + only the differing fields are PATCHed); unchanged localizations and an attached build are left alone. + - `play listing`: compares again inside the write edit and PUTs only differing details and languages; nothing left + to change = the edit is deleted, not committed. + - `apple appinfo`: categories, age rating, content rights compared with the live values, only differences PATCHed. + - `play data-safety`: Play cannot read the form back, so the sha256 of the last uploaded CSV is kept in + `.storebound/data-safety.sha256`; the same CSV is not sent again unless `--force` (MCP `force`). + - Twice-run tests for `apple listing` (plus a lost version create and a 409 localization), `play listing` (plus a + store that became current before the edit), `apple appinfo`, `play data-safety`, `apple promoted`, + `apple win-back`, `apple preorder`, `apple testflight testers`, `play upload` and `prices import` (Play). - Faster `shots capture` (web) and `shots render` (a 22-language game took about 50 min to capture, serially, with a new context and a full game boot per frame): diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 46059864..5dd810c4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,9 +7,25 @@ but fixes, store rule updates and new engines / AI tools are very welcome. ```sh bun install # Bun 1.1+; playwright is a dev dependency (renders, web capture) -bun run ci # adapters fresh, tests, typecheck, secrets / personal data scrub +bun run ci:quick # inner loop: typecheck + the tests your change touches + scrub (seconds) +bun run ci # full gate before pushing: every check and test (adapters, API tables, typecheck, + # desktop build and boot check, Rust host when it changed, scrub) ``` +**Which one when.** Run `bun run ci:quick` while you work: it diffs against `origin/main` (committed, staged, +unstaged and new files), maps the changed files to the tests that import them (directly, through other modules, or +by naming a fixture or page) and runs those, plus `tsc` (incremental) and the scrub. A change to `package.json`, +`bun.lock`, `bunfig.toml`, `tsconfig.json` or the test preload runs every test. Run the full `bun run ci` before every +push and check its exit code: it is the gate, `ci:quick` is not. + +`tools/ci.ts` runs the steps as a task graph (independent steps at the same time, output prefixed with the step +name, the first failure stops the rest, a time-per-step summary at the end). The tests run as parallel shards +(CPU cores - 1, at most 8; `STOREBOUND_CI_SHARDS=n` overrides) balanced by the durations of the last run, kept in +`node_modules/.cache/storebound-ci/`; the browser suites get a shard each. So tests must be shard-safe: temp folders +from `mkdtempSync`, servers on port 0, no fixed sleeps (wait for the event), no state shared through files in the +checkout. The desktop Rust host (`cargo test`, `clippy`) runs only when `apps/desktop/src-tauri/` or +`tools/build-sidecars.ts` changed against `origin/main`; `CI=full bun run ci` always runs it (Forgejo CI does). + Try the screenshot and video pipeline on the demo game without any store account: see [examples/demo-game/README.md](examples/demo-game/README.md). diff --git a/README.md b/README.md index 15390292..c1a55df1 100644 --- a/README.md +++ b/README.md @@ -422,6 +422,9 @@ run in the background with a log (`storebound shots render > .storebound/render. | `reports apple-sales \| apple-finance \| play-earnings \| play-sales` | API, read-only + local | sales / finance reports into `.storebound/reports/`, summary per product and currency, CSV export | | `triage [--days 14]` | API, read-only | TestFlight crash and screenshot feedback, Play error reports: grouped by signature with devices, OS versions, builds | | `aso rank [--storefronts us,de]` | network + local | App Store rank per keyword and storefront plus competitors from the public iTunes Search API (rate limited) -> `.storebound/aso/` | +| `aso competitors [--term ] [--storefront us,tr] [--top 10]` | network + local | top apps per keyword (name, developer, rating count, first release, last update, localized genre; no subtitles: not in any public API) and the words in their names you do not cover, same rate limit -> `.storebound/aso/competitors/` | +| `aso suggest [--locale en-US] [--write]` | local (+ Apple Ads API with credentials) | keyword candidates (own text, competitor names, localized category names, Apple Ads keyword suggestions with their relative 0-100 popularity) scored by relevance and competition, and a 100-byte keyword field per locale as a diff; `--write` puts it into `store/appstore.md` as a draft for review. Popularity is never estimated | +| `aso audit` | local | one report: `check --aso`, free keyword room, rank trend arrows, competitor gaps, Play short description and density, App Store conversion from the analytics snapshots, PPO / Play experiment ideas and the next 3 actions | @@ -431,7 +434,7 @@ 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 fonts` | network | font subsets for your copy (Noto for CJK / Arabic / Cyrillic / Devanagari ...) and the glyph coverage check per language | +| `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) | | `shots check [--variants] [--json]` | local, read-only | store rules: sizes, alpha, format, bytes, counts, overflow, fallback / missing glyphs, videos, folder frames | @@ -735,6 +738,23 @@ languages, every store size, a review gallery and an app preview video. No store Some display fonts lack Latin Extended: Lilita One has no ş ğ İ ą ę ń ś ź ż ć ă ș ț č ř ě ů ő ű or Vietnamese, so Turkish, Polish, Czech, Romanian, Hungarian or Vietnamese titles need another title font (Paytone One, Baloo 2, Rowdies) or `fonts: { ..., fallback: ['Noto Sans Display'] }` to accept the mixed glyphs. + + **Your own brand font.** `shots.fonts.title` / `body` / `fallback[]` also take a local file (relative to the + config; TTF, OTF, WOFF or WOFF2, checked by extension and signature) or `{ family, file, weight?, style?, license? }`: + + ```ts + fonts: { + title: { family: 'ER Display', file: 'apps/game/public/assets/fonts/er-display.woff2', license: 'OFL-1.1' }, + body: 'Montserrat', + fallback: ['Noto Sans Display'], // tried in order, before the automatic Noto fallbacks + }, + ``` + + `shots fonts` runs the same cmap check on the file (`pl title: ę ł ą Ł not in ER Display -> Noto Sans Display`), + prints its size, glyph count, sha256 and license, and records it in `fonts.json`. The file is never copied: render + (and `shots video` captions) serve it from where it is, and a changed file changes `fonts.css` (the capture cache + misses) and makes `shots render` ask for `shots fonts` again. `shots check` counts the local font and listed + fallbacks as configured, not as fallbacks, and warns when a local font has no `license` note. 3. **Render.** Every store size at exact pixels: iPhone 6.9" and 6.5", 13" iPad (if your app runs on iPad), Play phone, 7" and 10" tablets, the 1024 x 500 feature graphic. 24-bit RGB, no alpha (both stores reject it). 4. **Check and review.** `shots check` applies the store rules locally (sources cited in `cli/shots/spec.ts`); @@ -766,7 +786,7 @@ navigation. | `store-subscriptions` | subscription groups, levels, base plans, prices, intro and promotional offers, offer codes, disclosure and Terms (3.1.2), first submission | | `review-access` | demo account for reviewers (App Review fields, Play App access), never committed | | `account-deletion` | Apple 5.1.1(v) in-app deletion, Play delete-account web page and Data safety | -| `aso-basics` | keyword field, subtitle, cross-localization, Play placement without stuffing, keyword ranks via the iTunes Search API | +| `aso-basics` | keyword field, subtitle, cross-localization, Play placement without stuffing, keyword ranks, competitors, keyword field proposals and the ASO audit (iTunes Search API, Apple Ads popularity with credentials) | | `app-store-promotion` | IAP offer codes, win-back offers, promoted IAPs, pre-orders (Play pre-registration: console guide), custom product pages, in-app events | | `store-declarations` | every questionnaire: Play Data safety (API) and App content (IARC, target audience, ads, advertising ID, app access, government / financial / health), Apple App Privacy labels and age rating | | `export-compliance` | encryption answer, Info.plist key, declarations; never exempt by default | @@ -797,7 +817,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`, `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`, `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`. Local writes: `import_fastlane`, `whats_new`, `listing_translate`, `icons`, diff --git a/apps/desktop/src/api.ts b/apps/desktop/src/api.ts index c6acdea4..bb026feb 100644 --- a/apps/desktop/src/api.ts +++ b/apps/desktop/src/api.ts @@ -10,7 +10,7 @@ import type { Overrides } from './lib/identity'; export type { AccountCheck, AppIdentity, AppsListResult, AppStatus, CatalogParity, DraftsResult, StoreApp, IconResult, ListingField, ListingLocale, ListingsResult, MethodDescriptor, PortfolioResult, ProgressParams, ProjectSummary, ReleasePhase, ReleaseTrain, ReplyDraft, StoreRelease, ToolResult, - AnalyticsCompare, ConsoleAnswer, ConsoleFillResult, ConsoleForm, DeclAsk, DeclarationsResult, ListingText, PpoStatus, PpoTest, PriceDiffRow, PriceRowData, PricesCurrent, PricesDiff, RenderImage, RenderTile, RendersResult, + AnalyticsCompare, AsoAuditView, AsoTrendRow, ConsoleAnswer, ConsoleFillResult, ConsoleForm, DeclAsk, DeclarationsResult, ListingText, PpoStatus, PpoTest, PriceDiffRow, PriceRowData, PricesCurrent, PricesDiff, RenderImage, RenderTile, RendersResult, } from '../../../cli/lib/desktop-protocol'; export interface AppInfo { version: string; identifier: string; platform: string; debug: boolean; home: string | null } diff --git a/apps/desktop/src/dev/fixtures-more.ts b/apps/desktop/src/dev/fixtures-more.ts index ed9ed93c..faf3e00f 100644 --- a/apps/desktop/src/dev/fixtures-more.ts +++ b/apps/desktop/src/dev/fixtures-more.ts @@ -1,7 +1,7 @@ // DEV-ONLY FIXTURE DATA for the screens that cover the rest of the CLI (prices, store art, growth, app info). Made-up // numbers around the two demo apps; drawn SVG stand-ins for the rendered screenshots. Only src/dev/fixtures.ts imports // this module, and only fixture mode (dev builds) loads that. -import type { AnalyticsCompare, DeclarationsResult, ListingText, PpoStatus, PriceRowData, PricesCurrent, PricesDiff, RendersResult, RenderTile } from '../api'; +import type { AnalyticsCompare, AsoAuditView, DeclarationsResult, ListingText, PpoStatus, PriceRowData, PricesCurrent, PricesDiff, RendersResult, RenderTile } from '../api'; const HOME = '/home/you'; const NOW = Date.now(); @@ -200,3 +200,38 @@ function analytics(days: number, seed: number): AnalyticsCompare { return { snapshots: Math.ceil(days / 28) + 1, since: day(days), series: { apple, play }, effects }; } export const ANALYTICS: Record = { 'p-prism': analytics(56, 1), 'p-tidy': null }; + +// ---- aso.audit: `aso audit --json` of the demo apps (made up: four rank snapshots two weeks apart) ---- +function asoAudit(withRanks: boolean): AsoAuditView { + const dates = [day(42), day(28), day(14), day(0)]; + const series = [ + { storefront: 'us', keyword: 'match', ranks: [48, 39, 31, 24] }, + { storefront: 'us', keyword: 'puzzle', ranks: [88, 92, 71, 66] }, + { storefront: 'us', keyword: 'tiles', ranks: [null, 140, 118, 121] }, + { storefront: 'us', keyword: 'offline', ranks: [null, null, null, null] }, + ]; + const rows = series.map(x => { + const rank = x.ranks.at(-1) ?? null, previous = x.ranks.at(-2) ?? null; + const known = x.ranks.filter((v): v is number => v !== null); + return { storefront: x.storefront, keyword: x.keyword, rank, previous, change: rank !== null && previous !== null ? previous - rank : null, + arrow: rank === null ? '·' as const : previous === null ? 'new' as const : rank < previous ? '↑' as const : rank > previous ? '↓' as const : '→' as const, + best: known.length ? Math.min(...known) : null, snapshots: x.ranks.length }; + }); + return { + generated: day(0), + keywordField: { errors: 0, warnings: 1, hints: 2, findings: [{ level: 'warn', where: 'apple en-US', msg: 'keywords: 71/100 bytes used; fill at least 90 (29 bytes free)' }] }, + drafts: [], + ranks: withRanks ? { snapshots: 4, latest: day(0), rows, dates, series } : { snapshots: 0, latest: null, rows: [], dates: [], series: [] }, + competitors: withRanks ? { date: day(3), gaps: [{ storefront: 'us', locale: 'en-US', gaps: [{ word: 'blast', apps: 4, developers: 3 }, { word: 'block', apps: 3, developers: 3 }] }] } : { date: null, gaps: [] }, + experiments: [{ store: 'apple', what: 'first screenshot caption', why: 'the first screenshot is what search results show', how: 'storebound apple ppo create --variant b --dry' }], + next: withRanks ? [ + { what: 'fill the keyword field of en-US (71/100 bytes used)', why: 'unused bytes are unused search reach', command: 'storebound aso suggest --locale en-US' }, + { what: 'consider "blast", "block" for en-US (in the names of 3 developers\' top apps)', why: 'words the top apps lead with; only if they describe your app', command: 'storebound aso suggest --locale en-US' }, + { what: 'look at the keywords that dropped: us "tiles" 118 -> 121', why: 'a drop after a listing change is the signal to revert or adjust it' }, + ] : [ + { what: 'take a first rank snapshot', why: 'trends need a baseline before the next listing change', command: 'storebound aso rank --dry, then storebound aso rank' }, + { what: 'read the competitors for your keywords', why: 'coverage gaps and suggest need the top apps per term', command: 'storebound aso competitors --dry, then storebound aso competitors' }, + ], + }; +} +export const ASO: Record = { 'p-prism': asoAudit(true), 'p-tidy': asoAudit(false) }; diff --git a/apps/desktop/src/dev/fixtures.ts b/apps/desktop/src/dev/fixtures.ts index 662309ef..83839bc4 100644 --- a/apps/desktop/src/dev/fixtures.ts +++ b/apps/desktop/src/dev/fixtures.ts @@ -7,7 +7,7 @@ import { type Account, type AccountCheck, type ConsoleFillResult, type ConsoleFo type PortfolioResult, type Project, type ProjectSummary, type Settings, type StoreApp, type StoreRelease, type Studio, type ToolResult } from '../api'; import { buildApps, type Overrides } from '../lib/identity'; import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult, ScanResult } from '../lib/model'; -import { ANALYTICS, DECLARATIONS, LISTING_TEXT, PPO, PPO_STORE, PRICE_DIFF, PRICES, renderArt, RENDERS } from './fixtures-more'; +import { ANALYTICS, ASO, DECLARATIONS, LISTING_TEXT, PPO, PPO_STORE, PRICE_DIFF, PRICES, renderArt, RENDERS } from './fixtures-more'; export const FIXTURE_MARKER = 'storebound-dev-fixtures'; @@ -438,6 +438,7 @@ function read(method: string, id: string, args: Record = {}): T case 'prices.diff': return ok(method, PRICE_DIFF[id]); case 'apple.ppo_status': return ok(method, PPO[id]); case 'analytics.compare': return ANALYTICS[id] ? ok(method, ANALYTICS[id]) : { method, ok: false, exitCode: 1, dryRun: false, command: 'storebound analytics compare --json', output: `error: no snapshots in ${HOME}/apps/tidy-lists/.storebound/analytics (storebound analytics snapshot)` }; + case 'aso.audit': return ASO[id] ? ok(method, ASO[id]) : { method, ok: false, exitCode: 1, dryRun: false, command: 'storebound aso audit --json', output: 'fixture: no data for aso.audit' }; case 'check': return { method, ok: true, exitCode: 0, dryRun: false, command: 'storebound check', output: '12:00:01 [check] config ok: storebound.config.ts\n12:00:01 [check] listing: 4 languages\n12:00:01 [check] 0 problems, 2 warnings' }; default: return { method, ok: false, exitCode: 1, dryRun: false, command: `storebound ${method}`, output: `fixture: no data for ${method}` }; } diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 53094ca0..6b7a3a9a 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -1068,6 +1068,29 @@ export const en = { 'gr.before': 'Before', 'gr.after': 'After', 'gr.reading': 'A change needs several days on both sides and enough traffic; seasonality, featuring and ads move these numbers too.', + 'gr.aso': 'ASO', + 'gr.asoSub': 'aso audit, offline, {date}', + 'gr.asoSubNone': 'Keyword field, rank trend and next steps from the app folder (aso audit, offline)', + 'gr.asoField': 'Keyword field', + 'gr.asoFieldSub': 'check --aso over store/appstore.md', + 'gr.asoErrors': '{count} errors', + 'gr.asoErrors_one': '1 error', + 'gr.asoWarnings': '{count} warnings', + 'gr.asoWarnings_one': '1 warning', + 'gr.asoDrafts': 'Draft keywords to review: {locales}', + 'gr.asoRanked': 'Keywords ranked', + 'gr.asoLatest': 'In the first 200 results · {date}', + 'gr.asoNoRanks': 'No rank snapshot yet: storebound aso rank', + 'gr.asoGaps': 'Coverage gaps', + 'gr.asoGapsSub': 'Words in top apps\' names you do not cover · {date}', + 'gr.asoNoCompetitors': 'No competitor snapshot yet: storebound aso competitors', + 'gr.asoChartAria': 'Keyword ranks over the rank snapshots, rank 1 at the top', + 'gr.asoNotRanked': 'not ranked', + 'gr.asoKeyword': 'Keyword', + 'gr.asoRank': 'Rank', + 'gr.asoBest': 'Best', + 'gr.asoNext': 'Next 3 actions', + 'gr.asoReading': 'Ranks follow the public iTunes Search API order, which is close to, not equal to, App Store search: read them as a trend. Popularity comes only from Apple Ads (aso suggest with an Apple Ads API key), never estimated.', 'gr.ppo': 'Product Page Optimization', 'gr.ppoSub': 'App Store A/B tests of the screenshots', 'gr.ppoRead': 'Read tests', diff --git a/apps/desktop/src/i18n/tr.ts b/apps/desktop/src/i18n/tr.ts index 37cf51bc..1902350f 100644 --- a/apps/desktop/src/i18n/tr.ts +++ b/apps/desktop/src/i18n/tr.ts @@ -1070,6 +1070,29 @@ export const tr: Record = { 'gr.before': 'Önce', 'gr.after': 'Sonra', 'gr.reading': 'Bir değişiklik iki tarafta da birkaç gün ve yeterli trafik ister; mevsim, öne çıkarılma ve reklamlar da bu sayıları oynatır.', + 'gr.aso': 'ASO', + 'gr.asoSub': 'aso audit, çevrimdışı, {date}', + 'gr.asoSubNone': 'Uygulama klasöründen anahtar kelime alanı, sıralama eğilimi ve sonraki adımlar (aso audit, çevrimdışı)', + 'gr.asoField': 'Anahtar kelime alanı', + 'gr.asoFieldSub': 'store/appstore.md üzerinde check --aso', + 'gr.asoErrors': '{count} hata', + 'gr.asoErrors_one': '1 hata', + 'gr.asoWarnings': '{count} uyarı', + 'gr.asoWarnings_one': '1 uyarı', + 'gr.asoDrafts': 'Gözden geçirilecek taslak kelimeler: {locales}', + 'gr.asoRanked': 'Sıralanan kelimeler', + 'gr.asoLatest': 'İlk 200 sonuçta · {date}', + 'gr.asoNoRanks': 'Henüz sıralama anlık görüntüsü yok: storebound aso rank', + 'gr.asoGaps': 'Kapsama boşlukları', + 'gr.asoGapsSub': 'Üst sıradaki uygulamaların adlarında olup sende olmayan kelimeler · {date}', + 'gr.asoNoCompetitors': 'Henüz rakip anlık görüntüsü yok: storebound aso competitors', + 'gr.asoChartAria': 'Sıralama anlık görüntülerine göre anahtar kelime sıraları, 1. sıra en üstte', + 'gr.asoNotRanked': 'sırada değil', + 'gr.asoKeyword': 'Anahtar kelime', + 'gr.asoRank': 'Sıra', + 'gr.asoBest': 'En iyi', + 'gr.asoNext': 'Sonraki 3 adım', + 'gr.asoReading': 'Sıralar herkese açık iTunes Search API sırasını izler; bu App Store aramasına yakındır ama aynı değildir: eğilim olarak oku. Popülerlik yalnızca Apple Ads\'ten gelir (Apple Ads API anahtarıyla aso suggest), asla tahmin edilmez.', 'gr.ppo': 'Ürün Sayfası Optimizasyonu', 'gr.ppoSub': 'Ekran görüntülerinin App Store A/B testleri', 'gr.ppoRead': 'Testleri oku', diff --git a/apps/desktop/src/screens/tabs/Growth.tsx b/apps/desktop/src/screens/tabs/Growth.tsx index d6f338fb..cf40c5da 100644 --- a/apps/desktop/src/screens/tabs/Growth.tsx +++ b/apps/desktop/src/screens/tabs/Growth.tsx @@ -1,9 +1,10 @@ // Growth: store analytics snapshots against the listing changes from git (`analytics compare --json`, offline; a new // snapshot and the App Store report request are confirm-gated writes), App Store Product Page Optimization tests // (status read; create and upload treatments: dry run, dialog, real run; start / stop are owner actions with their -// own dialog, never MCP tools), and Google Play store listing experiments (no API: Play Console). +// own dialog, never MCP tools), Google Play store listing experiments (no API: Play Console), and the ASO card +// (`aso audit --json`, offline: keyword field findings, rank trend from the `aso rank` snapshots, the next 3 actions). import { useMemo, useState } from 'react'; -import { type AnalyticsCompare, api, type PpoStatus, type PpoTest } from '../../api'; +import { type AnalyticsCompare, api, type AsoAuditView, type AsoTrendRow, type PpoStatus, type PpoTest } from '../../api'; import { t } from '../../i18n'; import type { UnifiedApp } from '../../lib/identity'; import { analyticsCsv, exportName } from '../../lib/exports'; @@ -15,6 +16,7 @@ import { useExports } from '../../ui/Exports'; import { Icon, StoreGlyph } from '../../ui/icons'; import { Card, Chip, Empty, ErrorNotice, Kpi, Notice, Seg, Skeleton } from '../../ui/kit'; import { LineChart } from '../../ui/LineChart'; +import { RankChart } from '../../ui/RankChart'; import { WriteButton } from '../../ui/WriteButton'; import { ascUrl, PLAY_CONSOLE } from '../AppView'; @@ -91,6 +93,62 @@ function Analytics({ projectId, hasApple, hasPlay, name, playReports }: { projec ); } +const arrowTone = (a: AsoTrendRow['arrow']): 'ok' | 'warn' | 'bad' | 'info' | 'neutral' => (a === '↑' || a === 'new' ? 'ok' : a === '↓' ? 'warn' : a === 'lost' ? 'bad' : 'neutral'); + +function Aso({ projectId }: { projectId: string }) { + const r = useRead(projectId, 'aso.audit', { network: false }); + const a = r.data; + const ranked = a ? a.ranks.rows.filter(x => x.rank !== null) : []; + const gaps = a ? a.competitors.gaps.reduce((n, g) => n + g.gaps.length, 0) : 0; + // the three best-ranked keywords of the latest snapshot, as lines (rank 1 at the top) + const lines = a ? ranked.slice().sort((x, y) => (x.rank ?? 999) - (y.rank ?? 999)).slice(0, 3).map((row, i) => ({ + label: `${row.keyword} (${row.storefront})`, cls: (['l1', 'l2', 'l3'] as const)[i]!, + ranks: a.ranks.series.find(s => s.storefront === row.storefront && s.keyword === row.keyword)?.ranks ?? [], + })) : []; + return ( + {t('action.refresh')}}> + {r.error ?
: !a ?
: ( +
+
+ + + +
+ {a.ranks.dates.length > 1 && lines.length > 0 && } + {a.ranks.rows.length > 0 && ( + + + + {a.ranks.rows.slice(0, 8).map(x => ( + + + + + + + + ))} + +
{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.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.asoReading')}

+
+ )} +
+ ); +} + function Experiments({ app }: { app: UnifiedApp }) { const d = useData(); const target = app.project?.id ?? app.target; @@ -183,6 +241,7 @@ export function GrowthTab({ app }: { app: UnifiedApp }) { return ( <> {app.project && } + {app.project && (hasApple || hasPlay) && }
{hasApple && } {hasPlay && } diff --git a/apps/desktop/src/ui/RankChart.tsx b/apps/desktop/src/ui/RankChart.tsx new file mode 100644 index 00000000..0b186323 --- /dev/null +++ b/apps/desktop/src/ui/RankChart.tsx @@ -0,0 +1,73 @@ +// Keyword ranks over the `aso rank` snapshots, drawn with visx (scales, axes, shapes, tooltip, responsive width). +// Rank 1 is the top of the chart (the y axis runs from the worst rank shown down to 1); a keyword the app was not in +// the first results for has no point that day. Reuses the line chart's styles (.lchart) and crosshair tooltip. +import { AxisBottom, AxisLeft } from '@visx/axis'; +import { curveMonotoneX } from '@visx/curve'; +import { Group } from '@visx/group'; +import { useParentSize } from '@visx/responsive'; +import { scaleLinear } from '@visx/scale'; +import { Bar, Circle, Line, LinePath } from '@visx/shape'; +import { date } from '../lib/format'; +import { ChartTip, useIndexHover } from './charts'; +import { dateTicks } from './LineChart'; + +export interface RankLine { label: string; ranks: (number | null)[]; cls: 'l1' | 'l2' | 'l3' } + +const M = { top: 12, right: 18, bottom: 26, left: 40 }; + +/** The y domain: rank 1 at the top, a round worst rank at the bottom (at least 10) and up to 5 ticks. */ +export function rankAxis(lines: (number | null)[][]): { worst: number; ticks: number[] } { + const hi = Math.max(10, ...lines.flat().filter((v): v is number => v !== null)); + const step = hi <= 10 ? 3 : hi <= 50 ? 10 : hi <= 100 ? 25 : 50; + const worst = hi <= 10 ? 10 : Math.ceil(hi / step) * step; + const ticks = [1, ...Array.from({ length: Math.floor(worst / step) }, (_, i) => (i + 1) * step)].filter((v, i, a) => a.indexOf(v) === i && v <= worst); + return { worst, ticks }; +} + +export function RankChart({ dates, lines, label, noRank }: { dates: string[]; lines: RankLine[]; label: string; noRank: string }) { + const { parentRef, width } = useParentSize({ debounceTime: 50 }); + const n = dates.length; + const h = useIndexHover(n, width, M.left, M.right); + if (n < 2 || !lines.length) return null; + const height = Math.round(Math.max(170, Math.min(230, width * 0.28))); + const { worst, ticks } = rankAxis(lines.map(l => l.ranks)); + const x = scaleLinear({ domain: [0, n - 1], range: [M.left, Math.max(M.left + 1, width - M.right)] }); + const y = scaleLinear({ domain: [1, worst], range: [M.top, height - M.bottom] }); + const pts = (vs: (number | null)[]) => vs.map((v, i) => [i, v] as const); + const defined = (d: readonly [number, number | null]) => d[1] !== null; + const xs = dateTicks(n, Math.max(2, Math.floor(width / 110))); + const hv = h.hover; + return ( +
+
+ {width > 0 && ( + + + {ticks.map(v => )} + + `#${Number(v)}`} hideAxisLine hideTicks tickClassName="ax" tickLabelProps={{ className: 'ax', textAnchor: 'end', dx: -4, dy: 4 }} /> + date(dates[Number(v)])} hideAxisLine hideTicks + tickLabelProps={(_, i) => ({ className: 'ax', textAnchor: i === 0 ? 'start' : i === xs.length - 1 ? 'end' : 'middle', dy: 4 })} /> + {lines.map(l => x(d[0])} y={d => y(d[1] ?? worst)} curve={curveMonotoneX} />)} + {lines.map(l => l.ranks.map((v, i) => (v === null ? null : )))} + {hv !== null && ( + + + + )} + + + )} + {hv !== null && width > 0 && ( + + {date(dates[hv])} + {lines.map(l => {l.label}{l.ranks[hv] == null ? noRank : `#${l.ranks[hv]}`})} + + )} +
+
+ {lines.map(l => {l.label})} +
+
+ ); +} diff --git a/apps/desktop/tests/webview.test.ts b/apps/desktop/tests/webview.test.ts index f09fbc48..7ad2a2fe 100644 --- a/apps/desktop/tests/webview.test.ts +++ b/apps/desktop/tests/webview.test.ts @@ -48,7 +48,8 @@ describe('webview rules', () => { }); test('built bundle (when present) has no fixture mode and no dev switches', () => { const dist = join(ROOT, 'dist', 'assets'); - if (!existsSync(dist)) return; + // tools/ci.ts runs this file again as "desktop bundle check" after the build; its test shards skip it here + if (!existsSync(dist) || process.env.STOREBOUND_SKIP_DIST_CHECK === '1') return; for (const n of readdirSync(dist)) { const s = readFileSync(join(dist, n), 'utf8'); expect(s, n).not.toContain('storebound-dev-fixtures'); diff --git a/cli/api/wrapped.gen.ts b/cli/api/wrapped.gen.ts index 05d92c0f..d9b8ac30 100644 --- a/cli/api/wrapped.gen.ts +++ b/cli/api/wrapped.gen.ts @@ -60,6 +60,7 @@ export const WRAPPED: { apple: Record; play: Record { +async function applyLocales(c: Asc, type: string, parentRel: string, parentType: string, parentId: string, listPath: string, plan: ItemPlan[]): Promise { + const patch = async (key: string, id: string, changes: ItemPlan['changes']) => { + await c.asc('PATCH', `/v1/${type}/${id}`, { data: { type, id, attributes: Object.fromEntries(changes.map(ch => [ch.field, ch.to ?? ''])) } }); + log('apple', `${type} ${key}: updated ${changes.map(ch => ch.field).join(', ')}`); + }; for (const l of plan) { if (l.action === 'create') { - await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { locale: l.key, ...l.attributes }, relationships: { [parentRel]: { data: { type: parentType, id: parentId } } } } }); - log('apple', `${type} ${l.key}: created`); - } else if (l.action === 'update') { - await c.asc('PATCH', `/v1/${type}/${l.id}`, { data: { type, id: l.id, attributes: Object.fromEntries(l.changes.map(ch => [ch.field, ch.to ?? ''])) } }); - log('apple', `${type} ${l.key}: updated ${l.changes.map(ch => ch.field).join(', ')}`); - } + // a locale is unique per parent: a 409 (or a lost answer) finds the existing one, which is then updated, never created twice + const made = await createOnce({ what: `${type} ${l.key}`, tag: 'apple', unique: true, + find: async () => (await c.all(`${listPath}?limit=200`)).find((x: J) => x.attributes.locale === l.key) ?? null, + create: async () => (await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { locale: l.key, ...l.attributes }, relationships: { [parentRel]: { data: { type: parentType, id: parentId } } } } })).data }); + if (made.created) { log('apple', `${type} ${l.key}: created`); continue; } + const again = planItem(l.key, { id: made.value.id, attributes: made.value.attributes ?? {} }, l.attributes); + if (again.action === 'update') await patch(l.key, made.value.id, again.changes); + } else if (l.action === 'update') await patch(l.key, l.id!, l.changes); } } @@ -189,9 +196,21 @@ export async function run(ctx: Ctx): Promise { const vp = p.versionPlan; let versionId = vp.id; if (vp.action === 'create') { - versionId = (await c.asc('POST', '/v1/appStoreVersions', { data: { type: 'appStoreVersions', - attributes: Object.fromEntries(Object.entries(vp.attributes)), relationships: { app: { data: { type: 'apps', id: appId } } } } })).data.id; - log('apple', `version ${version} created`); + // 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((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 }, + 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; + if (made.created) log('apple', `version ${version} created`); + else { + const { platform: _p, ...want } = vp.attributes; + const again = planItem(version, { id: versionId!, attributes: made.value.attributes ?? {} }, want); + if (again.action === 'update') await c.asc('PATCH', `/v1/appStoreVersions/${versionId}`, { data: { type: 'appStoreVersions', id: versionId, attributes: Object.fromEntries(again.changes.map(ch => [ch.field, ch.to])) } }); + log('apple', `version ${version} exists already (an earlier run made it): using it${again.action === 'update' ? `, updated ${again.changes.map(ch => ch.field).join(', ')}` : ''}`); + } } else if (vp.action === 'update') { await c.asc('PATCH', `/v1/appStoreVersions/${versionId}`, { data: { type: 'appStoreVersions', id: versionId, attributes: Object.fromEntries(vp.changes.map(ch => [ch.field, ch.to])) } }); log('apple', `version: ${vp.changes.map(ch => `${ch.field} ${ch.from ?? '(none)'} -> ${ch.to}`).join(', ')}`); @@ -200,8 +219,9 @@ export async function run(ctx: Ctx): Promise { await c.asc('PATCH', `/v1/appStoreVersions/${versionId}/relationships/build`, { data: { type: 'builds', id: p.build.id } }); log('apple', `build ${version} (${p.build.number}) attached`); } - await applyLocales(c, 'appInfoLocalizations', 'appInfo', 'appInfos', p.appInfo.id, p.appInfo.locales); - const vl = p.versionLocales ?? planLocales(await c.all(`/v1/appStoreVersions/${versionId}/appStoreVersionLocalizations?limit=200`), p.wanted); - await applyLocales(c, 'appStoreVersionLocalizations', 'appStoreVersion', 'appStoreVersions', versionId!, vl); + await applyLocales(c, 'appInfoLocalizations', 'appInfo', 'appInfos', p.appInfo.id, `/v1/appInfos/${p.appInfo.id}/appInfoLocalizations`, p.appInfo.locales); + const vlPath = `/v1/appStoreVersions/${versionId}/appStoreVersionLocalizations`; + const vl = p.versionLocales ?? planLocales(await c.all(`${vlPath}?limit=200`), p.wanted); + await applyLocales(c, 'appStoreVersionLocalizations', 'appStoreVersion', 'appStoreVersions', versionId!, vlPath, vl); done('apple', 'listing done'); } diff --git a/cli/aso.ts b/cli/aso.ts index 5bac96a7..bd2a1656 100644 --- a/cli/aso.ts +++ b/cli/aso.ts @@ -1,32 +1,86 @@ -// App Store keyword rank check through Apple's public iTunes Search API (no account, no scraping). +// App Store keyword work from official / public data only (no scraping, no third-party ASO services). // storebound aso rank [--storefronts us,de=de-DE] [--keywords "a,b"] [--only-keywords] [--competitors 3] [--limit 200] // [--delay 3500] [--dry] [--json] -// Keywords: the keyword field of each storefront's locale in store/appstore.md (us -> the primary locale unless +// storebound aso competitors [--term ]... [--storefront us,tr] [--only-terms] [--top 10] [--delay 3500] [--no-save] [--dry] [--json] +// storebound aso suggest [--locale en-US,tr] [--fresh] [--offline] [--write] [--json] +// storebound aso audit [--storefront US] [--json] +// rank: keywords = the keyword field of each storefront's locale in store/appstore.md (us -> the primary locale unless // "us=en-GB"), plus --keywords (--only-keywords: just those). One request per keyword and storefront, at most one // every 3.5 s (Apple allows about 20 a minute); a 403 / 429 stops the run with what was read. Rank = position of the // app (apple.appId, else the bundle id) in the first --limit results, "-" when not there; plus the first competitors -// (title, developer, rating). Subtitles are not in the public API and are not shown. Writes -// .storebound/aso/.json (and compares with the previous one) unless --dry. Pure parts: cli/lib/aso-rank.ts. +// (title, developer, rating). Writes .storebound/aso/.json (and compares with the previous one) unless --dry. +// competitors: the same queries and rate limit; per term the top N other apps (name, developer, rating count, first +// release, last update, genre) and the words in their names that our name / subtitle / keywords do not cover. Saves +// .storebound/aso/competitors/.json unless --dry / --no-save; names the apps new in a term's top N since the +// previous snapshot. Competitor subtitles are not in any public API and are not shown. +// suggest: keyword candidates per App Store locale from our own name / subtitle / description, the latest competitor +// snapshot, the localized category names (from the Search API's genres) and, when Apple Ads credentials exist (and +// not --offline), Apple Ads keyword suggestions with their relative popularity (0-100). Prints the ranked candidates +// and a 100-byte keyword field per locale as a diff against store/appstore.md; --write puts it there with a draft +// line above it (review, then delete the line). Never invents a popularity. +// audit: one offline report (cli/lib/aso-audit.ts) with experiment ideas and the next 3 actions. Never writes. +// Pure parts: cli/lib/aso-rank.ts, cli/lib/aso-intel.ts, cli/lib/aso-audit.ts. import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; +import { adsClient } from './ads/client'; +import type { Snapshot } from './lib/analytics'; +import { mergeSeries } from './lib/analytics'; +import { auditAso } from './lib/aso'; +import { auditText, buildAudit, type RankSnap } from './lib/aso-audit'; +import { + ADS_KEYWORD_SUGGESTIONS, type AdsSuggestion, candidates, categoryNames, competitorRow, type CompetitorRow, type CompetitorSnapshot, coverageGaps, draftLocales, + draftMark, fitKeywordField, keywordSuggestionBody, newEntrants, parseKeywordSuggestions, setKeywords, storefrontOf, tokens, +} from './lib/aso-intel'; +import { competitors, keywordList, MIN_DELAY_MS, parseStorefronts, rankDelta, rankOf, type RankRow, type SearchApp, searchUrl } from './lib/aso-rank'; +import { appleName } from './lib/config'; +import { parseAppStoreListing, parsePlayListing } from './lib/copy'; import type { Ctx } from './lib/ctx'; import { done, log, printJson, warn } from './lib/log'; -import { competitors, keywordList, MIN_DELAY_MS, parseStorefronts, rankDelta, rankOf, type RankRow, type SearchApp, searchUrl } from './lib/aso-rank'; import { appleSections } from './lib/project-files'; import { textTable } from './lib/table'; const TAG = 'aso'; +const SUBS = ['rank', 'competitors', 'suggest', 'audit']; +const SNAP_RE = /^\d{4}-\d{2}-\d{2}\.json$/; +const today = () => new Date().toISOString().slice(0, 10); -export async function run(ctx: Ctx): Promise { +function listingOf(ctx: Ctx): { file: string; md: string; sections: Map> } { + const { config, resolve } = ctx.loaded; + const file = resolve(config.apple?.listing ?? 'store/appstore.md'); + const md = existsSync(file) ? readFileSync(file, 'utf8') : ''; + return { file, md, sections: appleSections(md) }; +} + +const primaryLocale = (ctx: Ctx): string => ctx.loaded.config.apple?.primaryLocale ?? ctx.loaded.config.languages.find(l => l.apple)?.apple ?? 'en-US'; + +function snapshots(dir: string): { file: string; data: T }[] { + if (!existsSync(dir)) return []; + return readdirSync(dir).filter(f => SNAP_RE.test(f)).sort().map(f => { + try { return { file: f, data: JSON.parse(readFileSync(join(dir, f), 'utf8')) as T }; } catch { return null; } + }).filter((x): x is { file: string; data: T } => x !== null); +} + +/** One Search API call per item, one every `delay` ms; stops on 403 / 429 with what was read. */ +async function searchAll

(plan: P[], limit: number, delay: number, each: (p: P, results: SearchApp[], i: number) => void): Promise { + let read = 0; + for (const [i, p] of plan.entries()) { + if (i) await Bun.sleep(delay); + const r = await fetch(searchUrl(p.keyword, p.storefront, limit), { headers: { Accept: 'application/json' } }); + if (r.status === 403 || r.status === 429) { warn(TAG, `Search API answered ${r.status} (rate limit): stopped after ${read} of ${plan.length}; try later or with a larger --delay`); break; } + if (!r.ok) { warn(TAG, `${p.storefront} "${p.keyword}": HTTP ${r.status}`); continue; } + each(p, ((await r.json()) as { results?: SearchApp[] }).results ?? [], i); + read++; + } + return read; +} + +async function rank(ctx: Ctx): Promise { const { config, resolve } = ctx.loaded; const a = ctx.args; - if (a._[0] !== 'rank') throw new Error('usage: storebound aso rank [--storefronts us,de=de-DE] [--keywords "a,b"] [--dry] [--json]'); if (!config.apple) throw new Error('aso rank checks App Store search: the config has no apple section'); - const primary = config.apple.primaryLocale ?? config.languages.find(l => l.apple)?.apple ?? 'en-US'; - const listingFile = resolve(config.apple.listing ?? 'store/appstore.md'); - const listing = existsSync(listingFile) ? appleSections(readFileSync(listingFile, 'utf8')) : new Map>(); + const { file: listingFile, sections: listing } = listingOf(ctx); const extra = a.list('keywords'); - const fronts = parseStorefronts(a.list('storefronts'), primary); + const fronts = parseStorefronts(a.list('storefronts'), primaryLocale(ctx)); const n = a.num('competitors', 3); const limit = a.num('limit', 200); const delay = Math.max(MIN_DELAY_MS, a.num('delay', MIN_DELAY_MS)); @@ -40,21 +94,16 @@ export async function run(ctx: Ctx): Promise { return; } const rows: RankRow[] = []; - for (const [i, p] of plan.entries()) { - if (i) await Bun.sleep(delay); - const r = await fetch(searchUrl(p.keyword, p.storefront, limit), { headers: { Accept: 'application/json' } }); - if (r.status === 403 || r.status === 429) { warn(TAG, `Search API answered ${r.status} (rate limit): stopped after ${rows.length} of ${plan.length}; try later or with a larger --delay`); break; } - if (!r.ok) { warn(TAG, `${p.storefront} "${p.keyword}": HTTP ${r.status}`); continue; } - const results = ((await r.json()) as { results?: SearchApp[] }).results ?? []; + await searchAll(plan, limit, delay, (p, results, i) => { const row: RankRow = { storefront: p.storefront, locale: p.locale, keyword: p.keyword, rank: rankOf(results, app), results: results.length, competitors: competitors(results, app, n) }; rows.push(row); log(TAG, `${i + 1}/${plan.length} ${p.storefront} "${p.keyword}": ${row.rank ?? `not in the first ${results.length}`}`); - } + }); const dir = resolve('.storebound/aso'); - const prevFile = existsSync(dir) ? readdirSync(dir).filter(f => /^\d{4}-\d{2}-\d{2}\.json$/.test(f)).sort().at(-1) : undefined; + const prevFile = snapshots(dir).at(-1)?.file; const prev = prevFile ? (JSON.parse(readFileSync(join(dir, prevFile), 'utf8')) as { rows?: RankRow[] }).rows : undefined; const delta = rankDelta(rows, prev); - const date = new Date().toISOString().slice(0, 10); + const date = today(); if (a.has('json')) printJson({ date, previous: prevFile ?? null, rows: rows.map(r => ({ ...r, change: delta.get(`${r.storefront}|${r.keyword.toLowerCase()}`) ?? null })) }); else console.log(textTable(['store', 'keyword', 'rank', 'change', 'top competitors'], rows.map(r => { const d = delta.get(`${r.storefront}|${r.keyword.toLowerCase()}`); @@ -64,3 +113,148 @@ export async function run(ctx: Ctx): Promise { writeFileSync(join(dir, `${date}.json`), JSON.stringify({ date, app: { appId: app.appId ?? null, bundleId: app.bundleId }, rows }, null, 2) + '\n'); done(TAG, `${rows.length} rank(s) saved to ${join(dir, `${date}.json`)}${prevFile ? ` (change vs ${prevFile})` : ''}; Search API order is close to App Store search, read it as a trend`); } + +async function competitorsCmd(ctx: Ctx): Promise { + const { config, resolve } = ctx.loaded; + const a = ctx.args; + if (!config.apple) throw new Error('aso competitors reads App Store search: the config has no apple section'); + const { file, sections } = listingOf(ctx); + const terms = a.many('term').flatMap(t => t.split(',')).map(t => t.trim()).filter(Boolean); + const fronts = parseStorefronts([...a.list('storefront'), ...a.list('storefronts')], primaryLocale(ctx)); + const top = Math.max(1, Math.min(50, a.num('top', 10))); + const delay = Math.max(MIN_DELAY_MS, a.num('delay', MIN_DELAY_MS)); + const app = { appId: config.apple.appId, bundleId: config.apple.bundleId }; + const plan = fronts.flatMap(f => keywordList(a.has('only-terms') ? '' : sections.get(f.locale)?.keywords, terms).map(k => ({ ...f, keyword: k }))); + if (!plan.length) throw new Error(`no terms: ${file} has no keywords for ${fronts.map(f => f.locale).join(', ')}; pass --term `); + const limit = top + 1; + const save = !a.has('dry') && !a.has('no-save'); + if (!a.has('json')) log(TAG, `${plan.length} quer${plan.length === 1 ? 'y' : 'ies'} (${fronts.map(f => f.storefront).join(', ')}), top ${top} each, one every ${delay / 1000}s: about ${Math.ceil(plan.length * delay / 60_000)} min`); + if (a.has('dry')) { + if (a.has('json')) printJson({ dryRun: true, top, queries: plan.map(p => ({ storefront: p.storefront, locale: p.locale, term: p.keyword, url: searchUrl(p.keyword, p.storefront, limit) })) }); + else for (const p of plan) log(TAG, `would GET ${searchUrl(p.keyword, p.storefront, limit)}`); + return; + } + const rows: CompetitorRow[] = []; + await searchAll(plan, limit, delay, (p, results, i) => { + rows.push(competitorRow(results, app, { storefront: p.storefront, locale: p.locale, term: p.keyword }, top)); + if (!a.has('json')) log(TAG, `${i + 1}/${plan.length} ${p.storefront} "${p.keyword}": ${results.length} result(s)`); + }); + const dir = resolve('.storebound/aso/competitors'); + const prev = snapshots(dir).filter(s => s.file !== `${today()}.json`).at(-1); + const fresh = newEntrants(rows, prev?.data.rows); + const gaps = fronts.map(f => { + const s = sections.get(f.locale) ?? {}; + const covered = [...tokens(s.name ?? appleName(config), f.locale), ...tokens(s.subtitle ?? '', f.locale), ...(s.keywords ?? '').split(',').flatMap(t => tokens(t, f.locale))]; + return { storefront: f.storefront, locale: f.locale, gaps: coverageGaps(rows.filter(r => r.storefront === f.storefront && r.locale === f.locale), covered, f.locale) }; + }); + const snap: CompetitorSnapshot = { date: today(), app: { appId: app.appId ?? null, bundleId: app.bundleId }, top, rows }; + if (a.has('json')) printJson({ ...snap, previous: prev?.file ?? null, newEntrants: Object.fromEntries(fresh), gaps, saved: save, + notes: ['Search API order is close to, not equal to, App Store search', 'competitor subtitles are not in any public API'] }); + else { + for (const r of rows) { + console.log(`\n${r.storefront} "${r.term}"${r.ourRank ? ` (you: #${r.ourRank})` : ''}`); + console.log(textTable(['#', 'app', 'developer', 'ratings', 'released', 'updated', 'genre'], + r.apps.map(x => [x.rank, x.name.slice(0, 40), x.developer.slice(0, 24), x.ratings, x.released ?? '-', x.updated ?? '-', x.genres[0]?.name || x.genre]))); + const n = fresh.get(`${r.storefront}|${r.term.toLowerCase()}`); + if (n?.length) log(TAG, `new in the top ${top} since ${prev!.data.date}: ${n.join(', ')}`); + } + for (const g of gaps) console.log(`\n${g.storefront} ${g.locale}: words in competitors' names you do not cover: ${g.gaps.length ? g.gaps.map(x => `${x.word} (${x.apps} apps, ${x.developers} developers)`).join(', ') : 'none'}`); + log(TAG, 'subtitles are not in any public API, so they are not shown; words one developer uses are left out (likely a brand); never put other apps\' names into your keywords'); + } + if (save) { + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, `${snap.date}.json`), JSON.stringify(snap, null, 2) + '\n'); + if (!a.has('json')) done(TAG, `${rows.length} term(s) saved to ${join(dir, `${snap.date}.json`)}`); + } +} + +async function suggest(ctx: Ctx): Promise { + const { config, resolve, root } = ctx.loaded; + const a = ctx.args; + const json = a.has('json'); + if (!config.apple) throw new Error('aso suggest proposes App Store keyword fields: the config has no apple section'); + const { file, md } = listingOf(ctx); + if (!md) throw new Error(`${file} not found`); + const listing = parseAppStoreListing(md); + const locales = a.list('locale').length ? a.list('locale') : Object.keys(listing); + for (const l of locales) if (!listing[l]) throw new Error(`--locale ${l}: no "## ${l}" section in ${file}`); + const comp = snapshots(resolve('.storebound/aso/competitors')).at(-1)?.data ?? null; + const cats = Object.values(config.apple.info?.categories ?? {}).filter((x): x is string => typeof x === 'string'); + // Apple Ads keyword suggestions: only with the owner's credentials and an Apple ID; never estimated without them + let ads: ReturnType | null = null; + let adsNote = ''; + if (a.has('offline')) adsNote = '--offline: Apple Ads not asked; popularity unknown'; + else if (!config.apple.appId) adsNote = 'no apple.appId in the config: Apple Ads suggestions need the app\'s Apple ID; popularity unknown'; + else { + try { ads = adsClient(root); if (!ads.accountId) { ads = null; adsNote = 'APPLE_ADS_ACCOUNT_ID is not set: popularity unknown'; } } catch (e) { adsNote = `no Apple Ads credentials (${(e as Error).message.split(';')[0]}): popularity unknown`; } + } + const results: { locale: string; storefront: string; ads: string; competitors: string | null; candidates: ReturnType; proposal: ReturnType }[] = []; + for (const locale of locales) { + const c = listing[locale]!; + const sf = storefrontOf(locale); + const rows = (comp?.rows ?? []).filter(r => r.locale === locale); + const name = c.name ?? appleName(config); + let sugg: AdsSuggestion[] = []; + let adsState = adsNote; + if (ads) { + const seeds = [...new Set([...tokens(name, locale), ...tokens(c.subtitle ?? '', locale), ...(c.keywords ?? '').split(',').map(t => t.trim()).filter(Boolean)])].slice(0, 20); + try { + sugg = parseKeywordSuggestions(await ads.post(ADS_KEYWORD_SUGGESTIONS, keywordSuggestionBody(config.apple.appId!, seeds, [sf]))); + adsState = `Apple Ads keyword suggestions (${sf.toUpperCase()}): ${sugg.length}; popularity is Apple's relative 0-100 score, not a search volume`; + } catch (e) { adsState = `Apple Ads keyword suggestions failed (${(e as Error).message.slice(0, 160)}): popularity unknown`; } + } + const cands = candidates({ locale, name, subtitle: c.subtitle ?? '', keywords: c.keywords ?? '', description: c.description ?? '', competitors: rows, categories: categoryNames(rows, cats), ads: sugg }); + const proposal = fitKeywordField({ locale, current: c.keywords ?? '', name, subtitle: c.subtitle ?? '', ranked: cands, fresh: a.has('fresh') }); + results.push({ locale, storefront: sf, ads: adsState, competitors: rows.length ? `${comp!.date}: ${rows.length} term(s)` : null, candidates: cands, proposal }); + } + const write = a.has('write') && !a.has('dry'); + const changed = results.filter(r => r.proposal.after !== r.proposal.before); + if (json) printJson({ file, written: write && changed.length > 0, results: results.map(r => ({ ...r, candidates: r.candidates.slice(0, 60) })) }); + else { + for (const r of results) { + console.log(`\n== ${r.locale} (storefront ${r.storefront}) · competitors: ${r.competitors ?? 'no snapshot (storebound aso competitors)'} · ${r.ads}`); + const shown = r.candidates.filter(c => c.status === 'candidate').slice(0, 25); + console.log(textTable(['candidate', 'from', 'relevance', 'in names', 'popularity'], shown.map(c => [c.term, c.sources.join('+'), `${c.relevance}/2`, `${c.inNames}/${c.ofApps}`, + c.popularity === null ? 'unknown' : `${c.popularity}${c.popularityFrom === 'phrase' ? ' (phrase)' : ''}`]))); + const skipped = r.candidates.filter(c => c.status !== 'candidate' && c.kind === 'word').slice(0, 12); + if (skipped.length) log(TAG, `left out: ${skipped.map(c => `${c.term} (${c.why})`).join(', ')}`); + const p = r.proposal; + if (p.after === p.before) { log(TAG, `${r.locale}: keyword field unchanged (${p.bytes}/100 bytes)`); continue; } + console.log(`--- ${r.locale} keywords (store/appstore.md)\n- ${p.before || '(empty)'}\n+ ${p.after}\n ${p.bytes}/100 bytes · kept ${p.kept.length} · added ${p.added.join(', ') || 'none'}${p.dropped.length ? ` · dropped ${p.dropped.map(d => `${d.term} (${d.why})`).join(', ')}` : ''}`); + } + log(TAG, 'relevance: in your own text (+1) and in competitors\' names (+1); "in names": top apps that already have the word in their name; popularity only from Apple Ads, never estimated'); + } + if (!changed.length) return; + if (!write) { if (!json) log(TAG, `dry run: nothing written; --write puts the ${changed.length} proposal(s) into ${file} as drafts for review`); return; } + let next = md; + for (const r of changed) next = setKeywords(next, r.locale, r.proposal.after, draftMark(today())); + writeFileSync(file, next); + if (!json) done(TAG, `wrote ${changed.length} draft keyword field(s) to ${file}: review them, delete the draft lines, then storebound check --aso`); +} + +function audit(ctx: Ctx): void { + const { config, resolve } = ctx.loaded; + const a = ctx.args; + const storefront = (a.get('storefront') ?? 'US').toUpperCase(); + const { file, md } = listingOf(ctx); + const apple = config.apple && md ? parseAppStoreListing(md) : undefined; + const playFile = resolve(config.play?.listing ?? 'store/listing.md'); + const play = config.play && existsSync(playFile) ? parsePlayListing(readFileSync(playFile, 'utf8'), config.app.name) : undefined; + const findings = auditAso({ apple, play, appName: appleName(config), storefront }); + const ranks = snapshots(resolve('.storebound/aso')).map(s => ({ date: s.data.date, rows: s.data.rows ?? [] })); + const comp = snapshots(resolve('.storebound/aso/competitors')).at(-1)?.data ?? null; + const analytics = mergeSeries(snapshots(resolve('.storebound/analytics')).map(s => s.data)).apple; + const r = buildAudit({ today: today(), storefront, findings, drafts: md ? draftLocales(md) : [], apple, appName: appleName(config), play, ranks, competitors: comp, analytics, + variants: Object.keys(config.shots?.variants ?? {}) }); + if (a.has('json')) return printJson({ ...r, files: { appstore: apple ? file : null, play: play ? playFile : null } }); + console.log(auditText(r)); +} + +export async function run(ctx: Ctx): Promise { + const sub = ctx.args._[0]; + if (!sub || !SUBS.includes(sub)) throw new Error('usage: storebound aso rank | competitors | suggest | audit (see the aso-basics skill)'); + if (sub === 'rank') return rank(ctx); + if (sub === 'competitors') return competitorsCmd(ctx); + if (sub === 'suggest') return suggest(ctx); + return audit(ctx); +} diff --git a/cli/check.ts b/cli/check.ts index 0c5ccff1..35322013 100644 --- a/cli/check.ts +++ b/cli/check.ts @@ -8,6 +8,7 @@ import { existsSync, readFileSync } from 'node:fs'; import { relative } from 'node:path'; import { appPrivacyMismatches } from './lib/app-privacy'; import { type AsoFinding, auditAso } from './lib/aso'; +import { draftLocales } from './lib/aso-intel'; import { appleName, playCodes } from './lib/config'; import { APPLE_IAP_LIMITS, appleNameIssues, len, parseAppStoreListing, parsePlayListing } from './lib/copy'; import type { Ctx } from './lib/ctx'; @@ -22,9 +23,11 @@ import { type CopyFile, validateCopy } from './shots/lib'; function aso(ctx: Ctx): void { const { config, resolve } = ctx.loaded; - const apple = config.apple ? parseAppStoreListing(readFileSync(resolve(config.apple.listing ?? 'store/appstore.md'), 'utf8')) : undefined; + const appleMd = config.apple ? readFileSync(resolve(config.apple.listing ?? 'store/appstore.md'), 'utf8') : ''; + const apple = config.apple ? parseAppStoreListing(appleMd) : undefined; const play = config.play ? parsePlayListing(readFileSync(resolve(config.play.listing ?? 'store/listing.md'), 'utf8'), config.app.name) : undefined; const f: AsoFinding[] = auditAso({ apple, play, appName: appleName(config), storefront: ctx.args.get('storefront') ?? 'US' }); + for (const l of draftLocales(appleMd)) f.push({ level: 'warn', where: `apple ${l}`, msg: 'keywords: draft from `aso suggest`, not reviewed yet (review, then delete the storebound-aso draft line)' }); if (ctx.args.has('json')) { const errors = f.filter(x => x.level === 'error').length; printJson({ findings: f, errors }); if (errors) process.exitCode = 1; return; } const tag = { error: 'ERROR', warn: 'warn ', info: 'info ' } as const; for (const x of f) console.log(`${tag[x.level]} [${x.where}] ${x.msg}`); diff --git a/cli/console/session.ts b/cli/console/session.ts index 5c4e9e06..867c9628 100644 --- a/cli/console/session.ts +++ b/cli/console/session.ts @@ -168,6 +168,8 @@ export interface OpenOpts { hosts?: string[]; headless?: boolean; platform?: string; + /** Tests: Playwright's launch timeout for modes (b) and (c) (default: Playwright's 30 s). */ + launchTimeoutMs?: number; say: (m: string) => void; } @@ -233,7 +235,7 @@ export async function openConsoleBrowser(root: string, o: OpenOpts): Promise { /* kept on purpose */ }); diff --git a/cli/index.ts b/cli/index.ts index 68c01311..a2f181e3 100755 --- a/cli/index.ts +++ b/cli/index.ts @@ -35,7 +35,7 @@ const COMMANDS: Record Promise, string]> = { 'catalog': [() => import('./catalog'), 'diff: cross-store parity of products + subscriptions (missing / extra / mismatched, prices per region, offers); read-only, exit 1 on mismatches | pull [--write]: store texts of IAPs + subscriptions as a config proposal'], 'reports': [() => import('./reports'), 'apple-sales | apple-finance --month | play-earnings --month | play-sales --month: download to .storebound/reports/, summary table + CSV; read-only'], 'triage': [() => import('./triage'), 'TestFlight crash / screenshot feedback and Play error reports grouped by signature, device, OS version, build; read-only, --json'], - 'aso': [() => import('./aso'), 'rank [--storefronts us,de] [--keywords a,b]: App Store rank per keyword and storefront + competitors from the public iTunes Search API (rate limited) -> .storebound/aso/'], + 'aso': [() => import('./aso'), 'rank | competitors | suggest | audit: App Store ranks, top apps per keyword, keyword field proposals (Apple Ads popularity with credentials) and one ASO report, from the public iTunes Search API -> .storebound/aso/'], 'prices': [() => import('./prices'), 'export | import a CSV of product x store x region prices (diff first, asks before writing; Apple future-dated changes) | ppp --base (purchasing power price sheet, snapped to store price points)'], 'ads apple': [() => import('./ads/apple'), 'Apple Ads (Search Ads): status | campaigns | report (spend, taps, installs, CPA per campaign / keyword, --csv); bid | budget | pause (dry run, asks first; never via MCP)'], '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)'], @@ -49,7 +49,7 @@ const COMMANDS: Record Promise, string]> = { 'play subscriptions': [() => import('./play/subscriptions'), 'auto-renewable subscriptions: listings, base plan, regional prices, intro offer, activate (--csv prices sheet; asks first)'], 'play listing': [() => import('./play/listing'), 'app details + title / short / full description per language; pull [--write]: live listings back into the listing file (diff first)'], 'play images': [() => import('./play/images'), 'icon, feature graphic, phone / 7" / 10" screenshots per language; --variant '], - 'play data-safety': [() => import('./play/data-safety'), 'Data safety form (CSV import through the API)'], + 'play data-safety': [() => import('./play/data-safety'), '[--force] Data safety form (CSV import through the API; skipped when unchanged since the last upload)'], 'play release': [() => import('./play/release'), 'upload an AAB and put it on tracks with release notes'], 'play build': [() => import('./play/build'), 'gradle bundleRelease (Flutter: flutter build appbundle) with the next free versionCode and the upload key from env / .storebound; --dry'], 'play upload': [() => import('./play/upload'), 'upload an AAB to a testing track (--track internal|alpha|beta), versionCode checked first; --dry read-only, asks first'], diff --git a/cli/lib/aso-audit.ts b/cli/lib/aso-audit.ts new file mode 100644 index 00000000..d6cce829 --- /dev/null +++ b/cli/lib/aso-audit.ts @@ -0,0 +1,221 @@ +// `aso audit`: one offline report over everything storebound already keeps, as pure parts. Inputs: the `check --aso` +// findings and the cross-locale free-keyword-room hint (cli/lib/aso.ts), the rank snapshots of `aso rank` +// (.storebound/aso/.json, trend arrows), the latest competitor snapshot of `aso competitors` +// (.storebound/aso/competitors/.json, coverage gaps), the Play listing (keyword density, short description use), +// the App Store analytics snapshots (.storebound/analytics, impressions / downloads / conversion) and the screenshot +// variants of the config. Output: the report, experiment ideas (suggestions only: nothing is started) and the next 3 +// concrete actions. No network, no writes. +import type { AppleDay } from './analytics'; +import type { AsoFinding } from './aso'; +import { words } from './aso'; +import { type CompetitorSnapshot, coverageGaps, type Gap, isStop, tokens } from './aso-intel'; +import type { RankRow } from './aso-rank'; +import type { AppleCopy, PlayCopy } from './copy'; +import { len } from './copy'; +import { textTable } from './table'; + +export interface RankSnap { date: string; rows: RankRow[] } +export type Arrow = '↑' | '↓' | '→' | 'new' | 'lost' | '·'; +export interface TrendRow { storefront: string; keyword: string; rank: number | null; previous: number | null; change: number | null; arrow: Arrow; best: number | null; snapshots: number } + +const k = (r: { storefront: string; keyword: string }) => `${r.storefront}|${r.keyword.toLowerCase()}`; + +/** Latest rank per storefront + keyword against the snapshot before it (positive change = moved up). Pure. */ +export function rankTrend(snaps: RankSnap[]): { rows: TrendRow[]; dates: string[]; series: { storefront: string; keyword: string; ranks: (number | null)[] }[] } { + const sorted = [...snaps].sort((a, b) => a.date.localeCompare(b.date)); + const dates = sorted.map(s => s.date); + const hist = new Map(); + sorted.forEach((s, i) => { + for (const r of s.rows) { + const h = hist.get(k(r)) ?? { storefront: r.storefront, keyword: r.keyword, ranks: Array(sorted.length).fill(undefined) }; + h.ranks[i] = r.rank; + hist.set(k(r), h); + } + }); + const rows: TrendRow[] = []; + for (const h of hist.values()) { + const seen = h.ranks.map((v, i) => ({ v, i })).filter(x => x.v !== undefined) as { v: number | null; i: number }[]; + const last = seen.at(-1)!, prev = seen.at(-2); + const rank = last.v, previous = prev ? prev.v : null; + const arrow: Arrow = !prev ? (rank === null ? '·' : 'new') : rank === null ? (previous === null ? '·' : 'lost') : previous === null ? 'new' + : rank < previous ? '↑' : rank > previous ? '↓' : '→'; + const known = seen.map(x => x.v).filter((v): v is number => v !== null); + rows.push({ storefront: h.storefront, keyword: h.keyword, rank, previous, change: rank !== null && previous !== null ? previous - rank : null, arrow, + best: known.length ? Math.min(...known) : null, snapshots: seen.length }); + } + rows.sort((a, b) => a.storefront.localeCompare(b.storefront) || (a.rank ?? 999) - (b.rank ?? 999) || a.keyword.localeCompare(b.keyword)); + const series = [...hist.values()].map(h => ({ storefront: h.storefront, keyword: h.keyword, ranks: h.ranks.map(v => v ?? null) })); + return { rows, dates, series }; +} + +export interface PlayUse { lang: string; title: string; shortChars: number; shortRoom: number; titleWordsInShort: boolean; shortWordsInOpening: boolean; top: { word: string; count: number; density: number }[]; stuffed: string[] } + +/** Play: how the short description is used and which words the full description leans on (density). Pure. */ +export function playUse(c: PlayCopy): PlayUse { + const L = c.lang; + const full = words(c.full, L); + const counts = new Map(); + for (const w of full) if (w.length > 3 && !isStop(w, L)) counts.set(w, (counts.get(w) ?? 0) + 1); + const top = [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 5) + .map(([word, count]) => ({ word, count, density: full.length ? count / full.length : 0 })); + const titleWords = tokens(c.title, L).filter(w => w.length > 2); + const shortWords = new Set(tokens(c.short, L)); + const opening = new Set(words(c.full.split('\n').slice(0, 3).join(' '), L)); + return { + lang: L, title: c.title, shortChars: len(c.short), shortRoom: 80 - len(c.short), + titleWordsInShort: titleWords.some(w => shortWords.has(w)), + shortWordsInOpening: [...shortWords].some(w => w.length > 3 && opening.has(w)), + top, stuffed: top.filter(t => full.length >= 80 && t.count >= 6 && t.density > 0.03).map(t => t.word), + }; +} + +export interface Experiment { store: 'apple' | 'play'; what: string; why: string; how: string } +export interface Action { what: string; why: string; command?: string } + +export interface AuditInput { + today: string; + storefront: string; + findings: AsoFinding[]; + drafts: string[]; + apple?: Record; + appName: string; + play?: PlayCopy[]; + ranks: RankSnap[]; + competitors: CompetitorSnapshot | null; + analytics: AppleDay[]; + variants: string[]; +} + +export interface AsoAudit { + generated: string; storefront: string; + keywordField: { errors: number; warnings: number; hints: number; findings: AsoFinding[] }; + crossLocale: string | null; + drafts: string[]; + ranks: { snapshots: number; latest: string | null; rows: TrendRow[]; dates: string[]; series: { storefront: string; keyword: string; ranks: (number | null)[] }[] }; + competitors: { date: string | null; gaps: { storefront: string; locale: string; gaps: Gap[] }[] }; + play: PlayUse[]; + /** check --aso findings of the Play listing (stuffing, claims, caps, emoji, short description room). */ + playFindings: AsoFinding[]; + analytics: { days: number; start: string; end: string; impressions: number; pageViews: number; downloads: number; conversion: number | null } | null; + experiments: Experiment[]; + next: Action[]; +} + +const daysBetween = (a: string, b: string) => Math.round((Date.parse(b) - Date.parse(a)) / 86_400_000); + +/** The whole audit. Pure. */ +export function buildAudit(i: AuditInput): AsoAudit { + const kwFindings = i.findings.filter(f => f.where.startsWith('apple ') && !/storefront$/.test(f.where)); + const playFindings = i.findings.filter(f => f.where.startsWith('play ')); + const cross = i.findings.find(f => /storefront$/.test(f.where))?.msg ?? null; + const trend = rankTrend(i.ranks); + const gaps: AsoAudit['competitors']['gaps'] = []; + if (i.competitors) { + const groups = new Map(); + for (const r of i.competitors.rows) groups.set(`${r.storefront}|${r.locale}`, [...(groups.get(`${r.storefront}|${r.locale}`) ?? []), r]); + for (const [g, rows] of groups) { + const [storefront, locale] = g.split('|') as [string, string]; + const c = i.apple?.[locale]; + const covered = [...words(c?.name ?? i.appName, locale), ...words(c?.subtitle ?? '', locale), ...(c?.keywords ?? '').split(',').flatMap(t => words(t, locale))]; + gaps.push({ storefront, locale, gaps: coverageGaps(rows, covered, locale, 8) }); + } + } + const play = (i.play ?? []).map(playUse); + const last = i.analytics.slice(-28); + const sum = (f: (d: AppleDay) => number) => last.reduce((n, d) => n + f(d), 0); + const analytics = last.length ? { days: last.length, start: last[0]!.date, end: last.at(-1)!.date, impressions: sum(d => d.uniqueImpressions || d.impressions), + pageViews: sum(d => d.uniquePageViews || d.pageViews), downloads: sum(d => d.firstTimeDownloads || d.downloads), conversion: null as number | null } : null; + if (analytics) analytics.conversion = analytics.impressions ? analytics.downloads / analytics.impressions : null; + const a: AsoAudit = { + generated: i.today, storefront: i.storefront, + keywordField: { errors: kwFindings.filter(f => f.level === 'error').length, warnings: kwFindings.filter(f => f.level === 'warn').length, hints: kwFindings.filter(f => f.level === 'info').length, findings: kwFindings }, + crossLocale: cross, drafts: i.drafts, + ranks: { snapshots: i.ranks.length, latest: trend.dates.at(-1) ?? null, rows: trend.rows, dates: trend.dates, series: trend.series }, + competitors: { date: i.competitors?.date ?? null, gaps }, + play, playFindings, analytics, experiments: [], next: [], + }; + a.experiments = experimentIdeas(a, i); + a.next = nextActions(a, i); + return a; +} + +/** Product Page Optimization (Apple) and store listing experiment (Play) ideas from the audit. Suggestions only. Pure. */ +export function experimentIdeas(a: AsoAudit, i: AuditInput): Experiment[] { + const out: Experiment[] = []; + if (i.apple) { + const v = i.variants[0]; + out.push({ store: 'apple', what: 'first screenshot caption: lead with the search phrase people use for the app\'s main job', + why: a.analytics?.conversion !== null && a.analytics ? `App Store conversion (first-time downloads / unique impressions, last ${a.analytics.days} days) is ${(a.analytics.conversion! * 100).toFixed(1)}%: the first screenshot is what search results show` : 'the first screenshot is what search results show; PPO measures it against the original', + how: v ? `variant "${v}" exists: storebound shots render --variant ${v}, then storebound apple ppo create --variant ${v} --dry and apple ppo upload --variant ${v} --dry (starting the test is the owner's step: apple ppo start)` + : 'add a shots.variants entry with the new caption, storebound shots render --variant b, then storebound apple ppo create --variant b --dry (starting the test is the owner\'s step: apple ppo start)' }); + out.push({ store: 'apple', what: 'subtitle variant', + why: 'PPO tests only icons, screenshots and app previews: the subtitle cannot be A/B tested on the App Store', + how: 'change it with the next version and compare before / after with storebound analytics compare (one change at a time)' }); + } + for (const p of a.play.slice(0, 1)) { + out.push({ store: 'play', what: `short description variant (${p.lang})`, + why: p.shortRoom > 30 ? `the short description uses ${p.shortChars}/80 characters` : !p.titleWordsInShort ? 'the short description shares no word with the title' : 'the short description is the first text on the listing', + how: 'Play Console > Grow users > Store listing experiments (no API: storebound only prepares the text; the store-screenshots skill has the steps)' }); + if (i.variants.length) out.push({ store: 'play', what: `screenshot variant "${i.variants[0]}"`, why: 'graphics experiments need no new version', + how: `storebound shots render --variant ${i.variants[0]} --size play, then upload it as the experiment's variant in Play Console` }); + } + return out; +} + +/** The next 3 concrete actions, most important first. Pure. */ +export function nextActions(a: AsoAudit, i: AuditInput): Action[] { + const out: Action[] = []; + const f = a.keywordField.findings; + const err = f.find(x => x.level === 'error'); + if (err) out.push({ what: `fix ${err.where}: ${err.msg}`, why: 'App Store Connect refuses the keyword field as it is', command: 'storebound check --aso' }); + if (a.drafts.length) out.push({ what: `review the draft keywords of ${a.drafts.join(', ')} in store/appstore.md and delete the draft line`, why: 'they were proposed by aso suggest, not reviewed yet' }); + const room = f.find(x => /bytes used; fill/.test(x.msg)); + if (room) out.push({ what: `fill the keyword field of ${room.where.replace('apple ', '')} (${room.msg.replace(/^keywords: /, '')})`, why: 'unused bytes are unused search reach', command: `storebound aso suggest --locale ${room.where.replace('apple ', '')}` }); + const rep = f.find(x => /repeat words from the name/.test(x.msg)); + if (rep) out.push({ what: `${rep.where}: replace the words the name / subtitle already index (${rep.msg.split(': ').at(-1)})`, why: 'they take bytes without adding reach', command: `storebound aso suggest --locale ${rep.where.replace('apple ', '')}` }); + const gap = a.competitors.gaps.find(g => g.gaps.length); + if (gap) out.push({ what: `consider "${gap.gaps.slice(0, 3).map(g => g.word).join('", "')}" for ${gap.locale} (in the names of ${gap.gaps[0]!.developers} developers' top apps, not in your name / subtitle / keywords)`, why: 'words the top apps lead with; only if they describe your app', command: `storebound aso suggest --locale ${gap.locale}` }); + const lost = a.ranks.rows.filter(r => r.arrow === '↓' || r.arrow === 'lost'); + if (lost.length) out.push({ what: `look at the keywords that dropped: ${lost.slice(0, 3).map(r => `${r.storefront} "${r.keyword}" ${r.previous ?? '-'} -> ${r.rank ?? '-'}`).join(', ')}`, why: 'a drop after a listing change is the signal to revert or adjust it' }); + if (!a.ranks.latest) out.push({ what: 'take a first rank snapshot', why: 'trends need a baseline before the next listing change', command: 'storebound aso rank --dry, then storebound aso rank' }); + else if (daysBetween(a.ranks.latest, i.today) > 14) out.push({ what: `take a new rank snapshot (the last is from ${a.ranks.latest})`, why: 'trend arrows compare the last two snapshots', command: 'storebound aso rank' }); + if (!a.competitors.date) out.push({ what: 'read the competitors for your keywords', why: 'coverage gaps and suggest need the top apps per term', command: 'storebound aso competitors --dry, then storebound aso competitors' }); + for (const p of a.play) { + if (p.stuffed.length) out.push({ what: `Play ${p.lang}: use "${p.stuffed.join('", "')}" less often in the full description`, why: 'reads as keyword stuffing (Play metadata policy)' }); + else if (p.shortRoom > 30) out.push({ what: `Play ${p.lang}: put the core phrase into the short description (${p.shortChars}/80 used)`, why: 'Play indexes the short description' }); + } + if (!a.analytics) out.push({ what: 'start App Store analytics snapshots', why: 'conversion before / after each listing change is the real measure', command: 'storebound analytics setup --dry, then storebound analytics snapshot' }); + return out.slice(0, 3); +} + +const signed = (n: number | null) => (n === null ? '' : n > 0 ? `+${n}` : String(n)); + +/** The report as text. Pure. */ +export function auditText(a: AsoAudit): string { + const o: string[] = []; + const kf = a.keywordField; + o.push(`ASO audit ${a.generated} (offline: listing files, .storebound/aso snapshots, .storebound/analytics)`, ''); + o.push(`1. Keyword field (check --aso): ${kf.errors} errors, ${kf.warnings} warnings, ${kf.hints} hints`); + for (const f of kf.findings.filter(x => x.level !== 'info').slice(0, 8)) o.push(` ${f.level === 'error' ? 'ERROR' : 'warn '} [${f.where}] ${f.msg}`); + if (a.drafts.length) o.push(` draft keywords (from aso suggest, not reviewed): ${a.drafts.join(', ')}`); + if (a.crossLocale) o.push(` ${a.storefront} storefront: ${a.crossLocale}`); + o.push('', `2. Ranks (aso rank, iTunes Search API order; a trend, not App Store search itself): ${a.ranks.snapshots} snapshot(s)${a.ranks.latest ? `, latest ${a.ranks.latest}` : ''}`); + if (a.ranks.rows.length) o.push(indent(textTable(['store', 'keyword', 'rank', '', 'change', 'best'], a.ranks.rows.map(r => [r.storefront, r.keyword, r.rank ?? '-', r.arrow, signed(r.change), r.best ?? '-'])))); + else o.push(' none yet: storebound aso rank'); + o.push('', `3. Competitor coverage (aso competitors${a.competitors.date ? `, ${a.competitors.date}` : ''}): words in the top apps' names you do not cover`); + if (!a.competitors.date) o.push(' no snapshot yet: storebound aso competitors'); + for (const g of a.competitors.gaps) o.push(` ${g.storefront} ${g.locale}: ${g.gaps.length ? g.gaps.map(x => `${x.word} (${x.apps} apps, ${x.developers} devs)`).join(', ') : 'none'}`); + o.push('', '4. Google Play listing'); + if (!a.play.length) o.push(' no Play listing'); + for (const f of a.playFindings.filter(x => x.level !== 'info')) o.push(` warn [${f.where}] ${f.msg}`); + for (const p of a.play) o.push(` ${p.lang}: short ${p.shortChars}/80${p.titleWordsInShort ? '' : ', no title word in it'}${p.shortWordsInOpening ? '' : ', opening lines share no word with it'}; top words ${p.top.map(t => `${t.word} ${t.count}x (${(t.density * 100).toFixed(1)}%)`).join(', ') || '-'}${p.stuffed.length ? `; STUFFING: ${p.stuffed.join(', ')}` : ''}`); + o.push('', '5. App Store analytics (analytics snapshot)'); + o.push(a.analytics ? ` ${a.analytics.start} .. ${a.analytics.end} (${a.analytics.days} days): ${a.analytics.impressions} unique impressions, ${a.analytics.pageViews} product page views, ${a.analytics.downloads} first-time downloads, conversion ${a.analytics.conversion === null ? 'n/a' : `${(a.analytics.conversion * 100).toFixed(2)}%`}` : ' no snapshots: storebound analytics snapshot'); + o.push('', '6. Experiment ideas (suggestions only; nothing is started)'); + for (const e of a.experiments) o.push(` [${e.store === 'apple' ? 'App Store PPO' : 'Play experiment'}] ${e.what}`, ` why: ${e.why}`, ` how: ${e.how}`); + o.push('', 'Next 3 actions'); + a.next.forEach((x, n) => o.push(` ${n + 1}. ${x.what}`, ` why: ${x.why}${x.command ? `; run: ${x.command}` : ''}`)); + return o.join('\n'); +} + +const indent = (s: string) => s.split('\n').map(l => ` ${l}`).join('\n'); diff --git a/cli/lib/aso-intel.ts b/cli/lib/aso-intel.ts new file mode 100644 index 00000000..6e7ae2e8 --- /dev/null +++ b/cli/lib/aso-intel.ts @@ -0,0 +1,366 @@ +// ASO keyword research from official and public data only, as pure parts. The commands are in cli/aso.ts +// (`aso competitors`, `aso suggest`); the audit report is cli/lib/aso-audit.ts. +// +// Data sources and what each number is (and is not): +// - iTunes Search API (public, no account; https://performance-partners.apple.com/search-api): the top N apps for a +// term in one storefront, with name (trackName), developer, rating count, first release date, last update, genre +// and the genre names localized to that storefront ("genres": "Produktivität" for country=de). Its order is close +// to, not equal to, App Store search. It has no subtitle field, so competitor subtitles are never shown. +// - Apple Ads Platform API, POST /v1/suggestions/keywords/query (only with the owner's Apple Ads credentials): +// keyword suggestions for the app (promotedObjectId = Apple ID, promotedObjectType APPSTORE_APP), seeded with +// `terms` and scoped with `countriesOrRegions`; each KeywordSuggestion is { text, popularity } where popularity is +// "a relative popularity score (not an absolute volume)" on a 0-100 scale. That is the only popularity signal +// storebound shows; without credentials popularity stays "unknown" (never estimated). +// https://developer.apple.com/documentation/apple-ads-platform-api/query-keyword-suggestions +// https://developer.apple.com/documentation/apple-ads-platform-api/keywordsuggestion +// https://developer.apple.com/documentation/apple-ads-platform-api/recommendationqueryrequest (pageSize 1..1000) +// (The Recommendations endpoints are budget / target CPA only; Insights has search term popularity 1-5 by genre, +// not used here.) +// - The app's own listing (store/appstore.md): name, subtitle, keyword field and description. +// Nothing here scrapes a store web page or calls a third-party ASO service. +import { FILLER, words } from './aso'; +import type { SearchApp } from './aso-rank'; + +// --------------------------------------------------------------------------------------------------------------- +// Words + +/** Function words that never make a keyword (a few languages; extend as needed). FILLER (app, game, free ...) too. */ +const STOP: Record = { + en: ['to', 'in', 'on', 'at', 'by', 'or', 'is', 'it', 'its', 'you', 'your', 'our', 'we', 'my', 'me', 'all', 'one', 'new', 'more', 'from', 'that', 'this', 'are', 'be', 'can', 'get', 'up', 'out', 'as', 'so', 'no', 'not', 'any', 'every', 'each', 'just', 'into', 'than', 'then', 'also', 'will', 'has', 'have', 'only', 'when', 'what', 'who', 'how', 'way', 'like', 'use', 'make', 'keep', 'see'], + de: ['der', 'die', 'das', 'und', 'mit', 'für', 'von', 'zu', 'ein', 'eine', 'ist', 'im', 'in', 'auf', 'den', 'dem', 'des', 'sie', 'du', 'dein', 'deine', 'alle', 'oder', 'auch'], + fr: ['le', 'la', 'les', 'et', 'de', 'des', 'du', 'un', 'une', 'pour', 'avec', 'en', 'au', 'aux', 'vos', 'votre', 'est', 'dans', 'sur', 'ou', 'tout', 'tous'], + es: ['el', 'la', 'los', 'las', 'y', 'de', 'del', 'un', 'una', 'para', 'con', 'en', 'tu', 'tus', 'es', 'por', 'o', 'que', 'todo', 'todos'], + pt: ['o', 'a', 'os', 'as', 'e', 'de', 'do', 'da', 'um', 'uma', 'para', 'com', 'em', 'seu', 'sua', 'no', 'na', 'ou', 'que', 'todo', 'todos'], + it: ['il', 'lo', 'la', 'le', 'gli', 'e', 'di', 'del', 'un', 'una', 'per', 'con', 'in', 'tuo', 'tua', 'che', 'tutti'], + tr: ['ve', 'ile', 'için', 'göre', 'kadar', 'sonra', 'önce', 'olan', 'olarak', 'bir', 'bu', 'şu', 'da', 'de', 'mi', 'en', 'çok', 'her', 'tüm', 'gibi', 'daha', 'sen', 'senin'], +}; +/** Words of listing boilerplate (account, settings, privacy ...): they describe the store page, not the app's job. */ +const BOILER = new Set(['account', 'accounts', 'settings', 'sign', 'signin', 'login', 'delete', 'privacy', 'policy', 'terms', 'support', 'contact', 'feature', 'features', + 'update', 'updates', 'version', 'subscription', 'purchase', 'purchases', 'time', 'any', 'back', 'between', 'off', 'next', 'keeps', 'keep', 'item', 'items', + 'change', 'changes', 'show', 'shows', 'work', 'works', 'people', 'phone', 'phones', 'here', 'there', 'about', 'want', 'need', 'help', 'day', 'days', 'even', 'much', 'many']); +const lang = (locale: string): string => locale.split('-')[0]!.toLowerCase(); +export const isStop = (w: string, locale: string): boolean => FILLER.has(w) || BOILER.has(w) || (STOP[lang(locale)] ?? []).includes(w) || STOP.en!.includes(w) || /^\d+$/.test(w); +/** "Ayarlar'dan" -> "Ayarlar", "it's" -> "it": the suffix after an apostrophe is not a word of its own. */ +const unApostrophe = (s: string): string => s.replace(/['’]\p{L}+/gu, ''); + +/** Content words of a text (lowercased for the locale, function words, boilerplate and numbers left out). Pure. */ +export const tokens = (s: string, locale: string): string[] => words(unApostrophe(s), locale).filter(w => !isStop(w, locale)); + +/** Two-word phrases of content words that stand next to each other in the text. Pure. */ +export function bigrams(s: string, locale: string): string[] { + const out: string[] = []; + for (const seg of unApostrophe(s).split(/[.!?\n:;,()"“”«»•·|/–—-]+/)) { + const ws = words(seg, locale); + for (let i = 0; i + 1 < ws.length; i++) if (!isStop(ws[i]!, locale) && !isStop(ws[i + 1]!, locale)) out.push(`${ws[i]} ${ws[i + 1]}`); + } + return out; +} + +/** Plural-insensitive key: languages whose plural is mostly "-s" fold "lists" and "list" together. Pure. */ +export function stem(w: string, locale: string): string { + const l = lang(locale); + if (l === 'en' && w.length > 4 && w.endsWith('ies')) return w.slice(0, -3) + 'y'; // groceries -> grocery + return ['en', 'fr', 'es', 'pt'].includes(l) && w.length > 3 && w.endsWith('s') && !w.endsWith('ss') ? w.slice(0, -1) : w; +} + +/** Languages that add suffixes to a word ("listeler", "listelerini"): one word starts with the other. */ +const SUFFIXING = new Set(['tr', 'fi', 'hu', 'et', 'az', 'kk', 'uz']); +/** The same keyword for search: plural-insensitive, and in suffixing languages a word that only adds a short suffix + * (up to 5 letters) to a word of at least 4. A heuristic: it errs on the side of not repeating a word. Pure. */ +export function sameWord(a: string, b: string, locale: string): boolean { + const x = stem(a, locale), y = stem(b, locale); + if (x === y) return true; + if (!SUFFIXING.has(lang(locale))) return false; + const [s, l] = x.length <= y.length ? [x, y] : [y, x]; + return s.length >= 4 && l.startsWith(s) && l.length - s.length <= 5; +} +const coveredBy = (w: string, set: Iterable, locale: string): boolean => { for (const s of set) if (sameWord(w, s, locale)) return true; return false; }; + +// --------------------------------------------------------------------------------------------------------------- +// Competitors (iTunes Search API) + +/** App Store Connect category id -> iTunes genre id (the "genreIds" of Search API results). Apple's genre ids. */ +export const GENRE_IDS: Record = { + BOOKS: '6018', BUSINESS: '6000', DEVELOPER_TOOLS: '6026', EDUCATION: '6017', ENTERTAINMENT: '6016', FINANCE: '6015', FOOD_AND_DRINK: '6023', GAMES: '6014', + GRAPHICS_AND_DESIGN: '6027', HEALTH_AND_FITNESS: '6013', LIFESTYLE: '6012', MAGAZINES_AND_NEWSPAPERS: '6021', MEDICAL: '6020', MUSIC: '6011', NAVIGATION: '6010', + NEWS: '6009', PHOTO_AND_VIDEO: '6008', PRODUCTIVITY: '6007', REFERENCE: '6006', SHOPPING: '6024', SOCIAL_NETWORKING: '6005', SPORTS: '6004', STICKERS: '6025', + TRAVEL: '6003', UTILITIES: '6002', WEATHER: '6001', + GAMES_ACTION: '7001', GAMES_ADVENTURE: '7002', GAMES_CASUAL: '7003', GAMES_BOARD: '7004', GAMES_CARD: '7005', GAMES_CASINO: '7006', GAMES_FAMILY: '7009', + GAMES_MUSIC: '7011', GAMES_PUZZLE: '7012', GAMES_RACING: '7013', GAMES_ROLE_PLAYING: '7014', GAMES_SIMULATION: '7015', GAMES_SPORTS: '7016', + GAMES_STRATEGY: '7017', GAMES_TRIVIA: '7018', GAMES_WORD: '7019', +}; + +export interface CompetitorApp { + rank: number; id: string; name: string; developer: string; ratings: number; rating: number | null; + /** First release (releaseDate) and the current version's release (currentVersionReleaseDate), YYYY-MM-DD. */ + released: string | null; updated: string | null; + genre: string; + /** Genre ids with their names localized to the storefront. */ + genres: { id: string; name: string }[]; +} +export interface CompetitorRow { storefront: string; locale: string; term: string; results: number; ourRank: number | null; apps: CompetitorApp[] } +export interface CompetitorSnapshot { date: string; app: { appId: string | null; bundleId: string }; top: number; rows: CompetitorRow[] } + +const isUs = (r: SearchApp, app: { appId?: string; bundleId?: string }) => !!((app.appId && String(r.trackId) === app.appId) || (app.bundleId && r.bundleId === app.bundleId)); + +/** One term's Search API results -> the top n other apps (and our own position among the results read). Pure. */ +export function competitorRow(results: SearchApp[], app: { appId?: string; bundleId?: string }, q: { storefront: string; locale: string; term: string }, n: number): CompetitorRow { + const i = results.findIndex(r => isUs(r, app)); + const apps = results.map((r, k) => ({ r, k })).filter(({ r }) => !isUs(r, app)).slice(0, n).map(({ r, k }): CompetitorApp => ({ + rank: k + 1, id: String(r.trackId), name: r.trackName, developer: r.sellerName ?? '', ratings: r.userRatingCount ?? 0, rating: r.averageUserRating ?? null, + released: r.releaseDate?.slice(0, 10) ?? null, updated: r.currentVersionReleaseDate?.slice(0, 10) ?? null, genre: r.primaryGenreName ?? '', + genres: (r.genreIds ?? []).map((id, j) => ({ id: String(id), name: r.genres?.[j] ?? '' })).filter(g => g.name), + })); + return { ...q, results: results.length, ourRank: i >= 0 ? i + 1 : null, apps }; +} + +/** Distinct apps of the rows (one storefront / locale), first seen first. Pure. */ +export function distinctApps(rows: CompetitorRow[]): CompetitorApp[] { + const seen = new Map(); + for (const r of rows) for (const a of r.apps) if (!seen.has(a.id)) seen.set(a.id, a); + return [...seen.values()]; +} + +export interface Gap { word: string; apps: number; developers: number; terms: string[]; examples: string[] } + +/** + * Words in competitors' names that our name, subtitle and keyword field do not cover. A word only counts when apps of at + * least two different developers use it: a word one developer uses is most likely a brand (and other apps' names and + * trademarks must never go into a keyword field). Pure. + */ +export function coverageGaps(rows: CompetitorRow[], covered: Iterable, locale: string, max = 15): Gap[] { + const have = [...covered]; + const by = new Map; devs: Set; terms: Set; examples: string[] }>(); + for (const r of rows) for (const a of r.apps) for (const w of new Set(tokens(a.name, locale))) { + if (w.length < 3 || coveredBy(w, have, locale)) continue; + const k = stem(w, locale); + const g = by.get(k) ?? { apps: new Set(), devs: new Set(), terms: new Set(), examples: [] }; + if (!g.apps.has(a.id) && g.examples.length < 3) g.examples.push(a.name); + g.apps.add(a.id); g.devs.add(a.developer.toLowerCase()); g.terms.add(r.term); + by.set(k, g); + } + return [...by.entries()].filter(([, g]) => g.devs.size >= 2) + .map(([word, g]) => ({ word, apps: g.apps.size, developers: g.devs.size, terms: [...g.terms], examples: g.examples })) + .sort((a, b) => b.developers - a.developers || b.apps - a.apps || a.word.localeCompare(b.word)).slice(0, max); +} + +/** Apps in the top N now that were not there in the previous snapshot, per storefront + term. Pure. */ +export function newEntrants(now: CompetitorRow[], before: CompetitorRow[] | undefined): Map { + const out = new Map(); + if (!before) return out; + const prev = new Map(before.map(r => [`${r.storefront}|${r.term.toLowerCase()}`, new Set(r.apps.map(a => a.id))] as const)); + for (const r of now) { + const p = prev.get(`${r.storefront}|${r.term.toLowerCase()}`); + if (p) out.set(`${r.storefront}|${r.term.toLowerCase()}`, r.apps.filter(a => !p.has(a.id)).map(a => a.name)); + } + return out; +} + +/** The category names of the app in one storefront's language, read from the Search API results' localized genres. Pure. */ +export function categoryNames(rows: CompetitorRow[], categoryIds: string[]): string[] { + const ids = new Set(categoryIds.map(c => GENRE_IDS[c]).filter(Boolean)); + const names = new Set(); + for (const a of distinctApps(rows)) for (const g of a.genres) if (ids.has(g.id)) names.add(g.name); + return [...names]; +} + +// --------------------------------------------------------------------------------------------------------------- +// Apple Ads keyword suggestions + +export const ADS_KEYWORD_SUGGESTIONS = '/suggestions/keywords/query'; + +/** RecommendationQueryRequest for keyword suggestions: the two required filters, seed terms, countries. Pure. */ +export function keywordSuggestionBody(adamId: string, terms: string[], countries: string[], pageSize = 200): Record { + const filters: Record[] = [ + { field: 'promotedObjectId', operator: 'EQUALS', value: [adamId] }, + { field: 'promotedObjectType', operator: 'EQUALS', value: ['APPSTORE_APP'] }, + ]; + if (terms.length) filters.push({ field: 'terms', operator: 'IN', value: terms }); + if (countries.length) filters.push({ field: 'countriesOrRegions', operator: 'IN', value: countries.map(c => c.toUpperCase()) }); + return { filters, sorting: [{ field: 'popularity', order: 'DESC' }], pagination: { offset: 0, pageSize: Math.min(1000, Math.max(1, pageSize)) } }; +} + +export interface AdsSuggestion { text: string; popularity: number } +/** `result` of the keyword suggestions answer -> { text, popularity } (0-100), invalid rows left out. Pure. */ +export function parseKeywordSuggestions(res: unknown): AdsSuggestion[] { + const rows = (res as { result?: unknown })?.result; + if (!Array.isArray(rows)) return []; + return rows.filter((r): r is { text: string; popularity: number } => typeof r?.text === 'string' && typeof r?.popularity === 'number') + .map(r => ({ text: r.text.trim(), popularity: Math.max(0, Math.min(100, Math.round(r.popularity))) })).filter(r => r.text); +} + +// --------------------------------------------------------------------------------------------------------------- +// Candidates and scoring + +export type CandSource = 'name' | 'subtitle' | 'keywords' | 'description' | 'competitors' | 'category' | 'apple-ads'; +export type CandStatus = 'candidate' | 'indexed' | 'category' | 'filler'; +export interface Candidate { + term: string; + kind: 'word' | 'phrase'; + sources: CandSource[]; + /** Times in our own name / subtitle / description. */ + ours: number; + /** relevance 0-2: +1 in our own text (name, subtitle, description, keywords), +1 in competitor names (the top apps). */ + relevance: number; + /** Competition: how many of the distinct top apps already have it in their name, of how many read. */ + inNames: number; ofApps: number; + /** Apple Ads relative popularity 0-100, null = unknown (no credentials, or Apple returned nothing for it). */ + popularity: number | null; + /** exact: Apple Ads suggested this exact word; phrase: the highest score of a suggested phrase that contains it. */ + popularityFrom: 'exact' | 'phrase' | null; + status: CandStatus; + why?: string; +} + +export interface CandidateInput { + locale: string; + name: string; subtitle: string; keywords: string; description: string; + /** The competitor rows of this locale's storefront (latest `aso competitors` snapshot), may be empty. */ + competitors: CompetitorRow[]; + /** Category names in this language (categoryNames); matched by Apple anyway, so never put into the field. */ + categories: string[]; + ads: AdsSuggestion[]; +} + +/** Every keyword candidate of one locale with its signals. Sorted: candidates first, by relevance, popularity (known + * first), lower competition, then how often our own text uses it. Pure. */ +export function candidates(i: CandidateInput): Candidate[] { + const L = i.locale; + const m = new Map(); + const key = (t: string) => t.split(' ').map(w => stem(w, L)).join(' '); + const add = (term: string, kind: Candidate['kind'], src: CandSource, n = 1) => { + const k = key(term); + const c = m.get(k) ?? { term, kind, sources: [], ours: 0, relevance: 0, inNames: 0, ofApps: 0, popularity: null, popularityFrom: null, status: 'candidate' as CandStatus }; + if (!c.sources.includes(src)) c.sources.push(src); + if (src === 'name' || src === 'subtitle' || src === 'description') c.ours += n; + m.set(k, c); + }; + for (const [src, text] of [['name', i.name], ['subtitle', i.subtitle], ['description', i.description]] as const) for (const w of tokens(text, L)) if (w.length > 2) add(w, 'word', src); + for (const w of i.keywords.split(',').flatMap(t => tokens(t, L))) if (w.length > 1) add(w, 'word', 'keywords'); + // phrases: only the ones our own text uses at least twice, or that stand in the name / subtitle + const phraseCount = new Map(); + for (const b of [...bigrams(i.name, L), ...bigrams(i.subtitle, L), ...bigrams(i.subtitle, L), ...bigrams(i.description, L)]) phraseCount.set(b, (phraseCount.get(b) ?? 0) + 1); + for (const [b, n] of phraseCount) if (n >= 2) add(b, 'phrase', 'description', n); + const apps = distinctApps(i.competitors); + const nameWords = apps.map(a => new Set(tokens(a.name, L).map(w => stem(w, L)))); + for (const g of coverageGaps(i.competitors, [], L, 200)) add(g.word, 'word', 'competitors'); + const catWords = [...new Set(i.categories.flatMap(c => words(c, L)))]; + const cats = new Set(catWords.map(w => stem(w, L))); + for (const c of catWords) add(c, 'word', 'category'); + for (const s of i.ads) { + const ws = tokens(s.text, L); + if (ws.length === 1) add(ws[0]!, 'word', 'apple-ads'); + } + const indexed = [...tokens(i.name, L), ...tokens(i.subtitle, L)]; + for (const c of m.values()) { + const ws = c.term.split(' ').map(w => stem(w, L)); + const inOurs = c.ours > 0 || c.sources.includes('keywords'); + c.inNames = nameWords.filter(n => ws.every(w => n.has(w))).length; + c.ofApps = apps.length; + c.relevance = (inOurs ? 1 : 0) + (c.inNames > 0 ? 1 : 0); + const exact = i.ads.find(s => key(s.text.toLocaleLowerCase(L)) === key(c.term)); + const phrases = i.ads.filter(s => ws.every(w => tokens(s.text, L).map(x => stem(x, L)).includes(w))); + if (exact) { c.popularity = exact.popularity; c.popularityFrom = 'exact'; } + else if (phrases.length) { c.popularity = Math.max(...phrases.map(s => s.popularity)); c.popularityFrom = 'phrase'; } + if (ws.some(w => cats.has(w)) && ws.length === 1) { c.status = 'category'; c.why = 'category name: matched by Apple anyway'; } + else if (ws.every(w => coveredBy(w, indexed, L))) { c.status = 'indexed'; c.why = 'already in the name / subtitle (indexed)'; } + else if (ws.some(w => FILLER.has(w))) { c.status = 'filler'; c.why = 'filler word'; } + } + const order = (c: Candidate) => (c.status === 'candidate' ? 0 : 1); + // a word only the description uses once is noise, unless competitors or Apple Ads bring it up too + const weak = (c: Candidate) => c.sources.length === 1 && c.sources[0] === 'description' && c.ours < 2; + return [...m.values()].filter(c => !weak(c)).sort((a, b) => order(a) - order(b) || b.relevance - a.relevance || (b.popularity ?? -1) - (a.popularity ?? -1) + || a.inNames - b.inNames || b.ours - a.ours || a.term.localeCompare(b.term)); +} + +// --------------------------------------------------------------------------------------------------------------- +// The 100-byte keyword field + +export interface FieldProposal { locale: string; before: string; after: string; bytes: number; kept: string[]; added: string[]; dropped: { term: string; why: string }[] } + +const bytes = (s: string) => Buffer.byteLength(s, 'utf8'); + +/** + * A keyword field for one locale that fits 100 bytes (UTF-8) with the existing rules: commas without spaces, no + * duplicates (plural-insensitive), no words of the name / subtitle, no filler or category words, single words. Current + * terms that are still valid are kept first (change a few terms per release, not all), unless `fresh`; then the best + * candidates fill the room. Pure. + */ +export function fitKeywordField(o: { locale: string; current: string; name: string; subtitle: string; ranked: Candidate[]; fresh?: boolean; limit?: number }): FieldProposal { + const L = o.locale, limit = o.limit ?? 100; + const indexed = [...tokens(o.name, L), ...tokens(o.subtitle, L)]; + const blocked = new Map(o.ranked.filter(c => c.status !== 'candidate' && c.kind === 'word').map(c => [stem(c.term, L), c.why ?? c.status] as const)); + const out: string[] = [], kept: string[] = [], added: string[] = [], dropped: { term: string; why: string }[] = []; + const seen: string[] = []; + const fits = (t: string) => bytes([...out, t].join(',')) <= limit; + const tryAdd = (t: string, into: string[]): string | null => { + const ws = words(t, L); + if (!ws.length) return 'empty'; + if (ws.every(w => coveredBy(w, indexed, L))) return 'already in the name / subtitle (indexed)'; + if (ws.some(w => FILLER.has(w))) return 'filler word'; + if (ws.length === 1 ? coveredBy(ws[0]!, seen, L) : seen.includes(ws.join(' '))) return 'duplicate'; + const b = ws.length === 1 ? blocked.get(stem(ws[0]!, L)) : undefined; + if (b) return b; + if (!fits(t)) return 'no room in 100 bytes'; + seen.push(ws.length === 1 ? ws[0]! : ws.join(' ')); out.push(t); into.push(t); + return null; + }; + if (!o.fresh) for (const t of o.current.split(',').map(s => s.trim().toLocaleLowerCase(L)).filter(Boolean)) { + // keep a current phrase as the words it is made of: single words combine on their own and save bytes + const parts = /\s/.test(t) ? tokens(t, L) : [t]; + for (const p of parts) { const why = tryAdd(p, kept); if (why && why !== 'duplicate') dropped.push({ term: p, why }); } + } + for (const c of o.ranked) { + if (c.status !== 'candidate' || c.kind !== 'word') continue; + tryAdd(c.term, added); + } + const after = out.join(','); + return { locale: L, before: o.current, after, bytes: bytes(after), kept, added, dropped }; +} + +// --------------------------------------------------------------------------------------------------------------- +// Writing the proposal into store/appstore.md (only with --write; marked as a draft for review) + +export const DRAFT_RE = /^\s*$/m; +export const draftMark = (date: string): string => ``; + +/** Locales of store/appstore.md whose keywords carry the draft line. Pure. */ +export function draftLocales(md: string): string[] { + const out: string[] = []; + for (const sec of md.split(/^(?=## )/m)) { + if (!sec.startsWith('## ')) continue; + const kw = sec.split(/^(?=### )/m).find(p => /^### keywords\s*$/m.test(p.split('\n')[0]!)); + if (kw && DRAFT_RE.test(kw)) out.push(sec.slice(3).split(/[\s·]/)[0]!.trim()); + } + return out; +} + +/** store/appstore.md with the keywords block of `locale` set to `value` and the draft line above it. Pure. */ +export function setKeywords(md: string, locale: string, value: string, mark: string): string { + const secs = md.split(/^(?=## )/m); + const i = secs.findIndex(s => s.startsWith('## ') && s.slice(3).split(/[\s·]/)[0]!.trim() === locale); + if (i < 0) throw new Error(`no "## ${locale}" section in the App Store listing`); + const parts = secs[i]!.split(/^(?=### )/m); + const block = `### keywords\n${mark}\n\`\`\`\n${value}\n\`\`\`\n`; + const k = parts.findIndex(p => /^### keywords\s*$/.test(p.split('\n')[0]!)); + if (k >= 0) { + const old = parts[k]!; + const fence = /^```[^\n]*\n[\s\S]*?\n```[^\n]*\n?/m.exec(old); + const tail = fence ? old.slice(fence.index + fence[0].length) : old.split('\n').slice(1).join('\n'); + parts[k] = block + tail.replace(DRAFT_RE, '').replace(/^\n+/, '\n'); + if (!/\n$/.test(parts[k]!)) parts[k] += '\n'; + } else { + const last = parts.length - 1; + parts[last] = parts[last]!.replace(/\n*$/, '\n\n') + block + (i < secs.length - 1 ? '\n' : ''); + } + secs[i] = parts.join(''); + return secs.join(''); +} + +/** "us" for en-US, "tr" for tr, "jp" for ja ... : the storefront a locale is most likely meant for. Pure. */ +export function storefrontOf(locale: string): string { + const [l, r] = locale.split('-'); + if (r && /^[A-Za-z]{2}$/.test(r)) return r.toLowerCase(); + const map: Record = { ja: 'jp', ko: 'kr', zh: locale === 'zh-Hant' ? 'tw' : 'cn', el: 'gr', he: 'il', hi: 'in', uk: 'ua', vi: 'vn', cs: 'cz', da: 'dk', sv: 'se', nb: 'no', ms: 'my', ca: 'es', en: 'us', ar: 'sa' }; + return map[l!.toLowerCase()] ?? l!.toLowerCase(); +} diff --git a/cli/lib/aso-rank.ts b/cli/lib/aso-rank.ts index fa0fe594..e213aa61 100644 --- a/cli/lib/aso-rank.ts +++ b/cli/lib/aso-rank.ts @@ -8,14 +8,18 @@ // title (trackName), developer (sellerName), bundleId, rating and description, but no subtitle: competitor subtitles // are not available through a public API, so they are not shown (storebound scrapes nothing). // Result fields used (as the API returns them; Apple's table lists only the general ones): trackId, trackName, -// bundleId, sellerName, averageUserRating, userRatingCount, primaryGenreName. +// bundleId, sellerName, averageUserRating, userRatingCount, primaryGenreName; `aso competitors` also releaseDate, +// currentVersionReleaseDate, genres (localized to the storefront, e.g. "Produktivität" for country=de) and genreIds. export const SEARCH_API = 'https://itunes.apple.com/search'; /** Apple: about 20 calls per minute. One call every 3.5 s stays below it with room for retries. */ export const MIN_DELAY_MS = 3_500; export const MAX_RESULTS = 200; -export interface SearchApp { trackId: number; trackName: string; bundleId?: string; sellerName?: string; averageUserRating?: number; userRatingCount?: number; primaryGenreName?: string } +export interface SearchApp { + trackId: number; trackName: string; bundleId?: string; sellerName?: string; averageUserRating?: number; userRatingCount?: number; primaryGenreName?: string; + releaseDate?: string; currentVersionReleaseDate?: string; genres?: string[]; genreIds?: string[]; primaryGenreId?: number; +} export function searchUrl(term: string, country: string, limit = MAX_RESULTS): string { if (!/^[a-z]{2}$/i.test(country)) throw new Error(`storefront "${country}": a two-letter country code (us, de, tr)`); diff --git a/cli/lib/aso.ts b/cli/lib/aso.ts index d2a33005..dbc754e2 100644 --- a/cli/lib/aso.ts +++ b/cli/lib/aso.ts @@ -16,9 +16,9 @@ export const CROSS_LOCALES: Record = { }; /** Words that add nothing in the keyword field (Apple: the category name and "app" are matched anyway). */ -const FILLER = new Set(['app', 'apps', 'game', 'games', 'free', 'the', 'and', 'for', 'with', 'a', 'an', 'of', 'iphone', 'ipad', 'ios']); +export const FILLER = new Set(['app', 'apps', 'game', 'games', 'free', 'the', 'and', 'for', 'with', 'a', 'an', 'of', 'iphone', 'ipad', 'ios']); -const words = (s: string, locale: string): string[] => +export const words = (s: string, locale: string): string[] => s.toLocaleLowerCase(locale).split(/[^\p{L}\p{N}]+/u).filter(w => w.length > 1); /** One locale of the App Store listing: keyword field rules. */ diff --git a/cli/lib/config.ts b/cli/lib/config.ts index b40c79d1..ed7c5c93 100644 --- a/cli/lib/config.ts +++ b/cli/lib/config.ts @@ -101,6 +101,12 @@ export interface ShotFrame { src: string; x?: number; dy?: number; scale?: numbe export interface Palette { bg: [string, string, string]; glow: string; ink: string; shadow: string } 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`; + * `shots check` warns without one). weight / style: the @font-face descriptors (default: all weights, normal). */ +export interface LocalFontSpec { family?: string; file: string; weight?: number | string; style?: 'normal' | 'italic'; license?: string } +/** A Google Fonts family name, a local font path (relative to the config) or a LocalFontSpec. */ +export type FontSpec = string | LocalFontSpec; + export interface ShotsConfig { /** Look of the rendered screenshots: game (sunburst, sparkles, badges, bold outlined titles) or app (calm gradient, * device frame, headline + subline, no sparkles or badges). Default: app for the app / subscription-app profiles, @@ -114,11 +120,12 @@ export interface ShotsConfig { out: string; /** Optional logo image for the hero scene and the feature graphic. */ logo?: string; - /** Google Fonts families for titles / body text (downloaded and subset by `shots fonts`). Default: game Paytone One + - * Montserrat, app Inter (all cover Latin Extended and Vietnamese). `fallback`: Noto families you accept for - * characters the title / body font lacks (e.g. ['Noto Sans Display']); without it a render that needs an automatic - * fallback is an ERROR in `shots check`. */ - fonts?: { title?: string; body?: string; fallback?: string[] }; + /** Fonts for titles / body text: a Google Fonts family (downloaded and subset by `shots fonts`), or your own font file + * (a path relative to the config, TTF / OTF / WOFF / WOFF2, or { family, file, weight?, style?, license? }). + * Default: game Paytone One + Montserrat, app Inter (all cover Latin Extended and Vietnamese). `fallback`: fonts you + * accept for characters the title / body font lacks, tried in order before the automatic Noto fallbacks (e.g. + * ['Noto Sans Display'] or a local file); a render that needs an automatic fallback is an ERROR in `shots check`. */ + fonts?: { title?: FontSpec; body?: FontSpec; fallback?: FontSpec[] }; scenes: ShotScene[]; feature?: { frame: string; palette?: string | Palette }; /** Phone screen size of the raw frames in CSS px (default 440 x 902 @3x, iPhone 6.9" minus the 54 px status bar). @@ -866,6 +873,19 @@ 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'); + 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) { + if (f === undefined) continue; + if (typeof f === 'string') { if (!f.trim()) e.push(`shots.fonts.${k}: empty`); else if (/[\\/]|\.[a-z0-9]{2,5}$/i.test(f) && !/\.(ttf|otf|woff2?)$/i.test(f)) e.push(`shots.fonts.${k}: ${f}: a font file must be TTF, OTF, WOFF or WOFF2`); continue; } + const o = f as Partial; + if (!o || typeof o !== 'object' || typeof o.file !== 'string') { e.push(`shots.fonts.${k}: a Google Fonts family, a font file path or { family, file, weight?, style?, license? }`); continue; } + if (!/\.(ttf|otf|woff2?)$/i.test(o.file)) e.push(`shots.fonts.${k}.file: ${o.file}: TTF, OTF, WOFF or WOFF2`); + if (o.family !== undefined && (typeof o.family !== 'string' || !o.family.trim())) e.push(`shots.fonts.${k}.family: a name`); + if (o.style !== undefined && o.style !== 'normal' && o.style !== 'italic') e.push(`shots.fonts.${k}.style: normal | italic`); + if (o.weight !== undefined && !/^\d{3}( \d{3})?$/.test(String(o.weight))) e.push(`shots.fonts.${k}.weight: e.g. 400, 800 or "100 900"`); + if (o.license !== undefined && typeof o.license !== 'string') e.push(`shots.fonts.${k}.license: text ('OFL-1.1', 'proprietary', ...)`); + } for (const sc of s.scenes ?? []) if (!sc.frames?.length) e.push(`shots.scenes[${sc.id}].frames: at least one frame`); e.push(...validateCapture(s.capture)); const sceneIds = new Set((s.scenes ?? []).map(x => x.id)); diff --git a/cli/lib/desktop-protocol.ts b/cli/lib/desktop-protocol.ts index 07d7cd3f..34ad445c 100644 --- a/cli/lib/desktop-protocol.ts +++ b/cli/lib/desktop-protocol.ts @@ -322,6 +322,17 @@ export interface AnalyticsCompare { /** Per store with no days in any snapshot: why the newest snapshot has none (no report request yet, no bucket). */ errors?: { apple?: string; play?: string }; } +/** aso.audit (`aso audit --json`, offline, cli/lib/aso-audit.ts AsoAudit): the parts the Growth tab's ASO card shows. */ +export interface AsoTrendRow { storefront: string; keyword: string; rank: number | null; previous: number | null; change: number | null; arrow: '↑' | '↓' | '→' | 'new' | 'lost' | '·'; best: number | null; snapshots: number } +export interface AsoAuditView { + generated: string; + keywordField: { errors: number; warnings: number; hints: number; findings: { level: 'error' | 'warn' | 'info'; where: string; msg: string }[] }; + drafts: string[]; + ranks: { snapshots: number; latest: string | null; rows: AsoTrendRow[]; dates: string[]; series: { storefront: string; keyword: string; ranks: (number | null)[] }[] }; + competitors: { date: string | null; gaps: { storefront: string; locale: string; gaps: { word: string; apps: number; developers: number }[] }[] }; + experiments: { store: 'apple' | 'play'; what: string; why: string; how: string }[]; + next: { what: string; why: string; command?: string }[]; +} /** console.fill (`console fill

--json`, cli/console/fill.ts): the answers it types into one console form. The * dry run has the answers only; the real run (it ends when the owner closes the browser) adds what happened. */ export type ConsoleForm = 'apple-app-record' | 'apple-age-rating' | 'apple-app-privacy' | 'play-app-record' | 'play-content-rating' | 'play-target-audience'; diff --git a/cli/lib/listing-translate.ts b/cli/lib/listing-translate.ts index 795d778c..b6dc55c8 100644 --- a/cli/lib/listing-translate.ts +++ b/cli/lib/listing-translate.ts @@ -129,7 +129,9 @@ export function normalizeKeywords(text: string, o: { name?: string; subtitle?: s return { text: kept.join(','), dropped }; } -export interface FieldCheck { store: 'apple' | 'play'; field: string; chars: number; limit: number; problems: string[] } +/** `chars` is what the store counts: characters, except App Store keywords, which App Store Connect limits in UTF-8 bytes + * (`unit` says which). */ +export interface FieldCheck { store: 'apple' | 'play'; field: string; chars: number; unit: 'chars' | 'bytes'; limit: number; problems: string[] } /** Limits and rules of one translated section. `source` = the source language's fields (identical text is flagged). */ export function checkFields(store: 'apple' | 'play', f: Record, source: Record = {}, status?: TStatus): FieldCheck[] { @@ -139,10 +141,11 @@ export function checkFields(store: 'apple' | 'play', f: Record)[k]!; - const c: FieldCheck = { store, field: k, chars: len(v), limit, problems: [] }; - if (len(v) > limit) c.problems.push(`${len(v)} > ${limit} characters`); - if (store === 'apple' && k === 'keywords') { - if (Buffer.byteLength(v) > limit) c.problems.push(`${Buffer.byteLength(v)} bytes > ${limit}`); + const bytes = store === 'apple' && k === 'keywords'; + const n = bytes ? Buffer.byteLength(v, 'utf8') : len(v); + const c: FieldCheck = { store, field: k, chars: n, unit: bytes ? 'bytes' : 'chars', limit, problems: [] }; + if (n > limit) c.problems.push(`${n} > ${limit} ${bytes ? 'bytes' : 'characters'}`); + if (bytes) { if (/,\s|\s,/.test(v)) c.problems.push('spaces around commas'); const words = v.split(',').map(w => w.trim().toLocaleLowerCase()).filter(Boolean); const dup = words.filter((w, i) => words.indexOf(w) !== i); diff --git a/cli/lib/scan/rules.ts b/cli/lib/scan/rules.ts index 96af1ac2..2e94f497 100644 --- a/cli/lib/scan/rules.ts +++ b/cli/lib/scan/rules.ts @@ -116,7 +116,10 @@ const COMPETITORS = ['instagram', 'tiktok', 'whatsapp', 'facebook', 'snapchat', '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']; const OTHER_PLATFORMS = /\b(Android|Google Play|Play Store|Galaxy Store|AppGallery|Huawei|Windows Phone|BlackBerry|Amazon Appstore)\b/; -const PLACEHOLDER = /lorem ipsum|\bTODO\b|\bTBD\b|\bFIXME\b|\bplaceholder\b|\bXXX\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; +// Developer markers count only in capitals ("TODO:", "FIXME"): "todo" is a real word and keyword (a to-do app). +const PLACEHOLDER_MARKERS = /\bTODO\b|\bTBD\b|\bFIXME\b|\bXXX\b/; +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; +const PLACEHOLDER = { test: (l: string) => PLACEHOLDER_MARKERS.test(l) || PLACEHOLDER_TEXT.test(l) } as RegExp; const FGS_PERMISSION: Record = { camera: 'CAMERA', connectedDevice: 'CONNECTED_DEVICE', dataSync: 'DATA_SYNC', health: 'HEALTH', location: 'LOCATION', mediaPlayback: 'MEDIA_PLAYBACK', mediaProjection: 'MEDIA_PROJECTION', microphone: 'MICROPHONE', phoneCall: 'PHONE_CALL', remoteMessaging: 'REMOTE_MESSAGING', specialUse: 'SPECIAL_USE', diff --git a/cli/listing.ts b/cli/listing.ts index b1d59a18..731ef17d 100644 --- a/cli/listing.ts +++ b/cli/listing.ts @@ -127,7 +127,7 @@ async function translate(ctx: Ctx): Promise { if (a.has('json')) printJson({ source: src.id, dryRun: dry, hook: !!hook, files: { apple: files.apple?.path ?? null, play: files.play?.path ?? null }, results: rows.map(r => ({ ...r, problems: problemsOf(r) })) }); else { console.log(textTable(['language', 'store', 'section', 'fields', 'problems'], rows.map(r => [r.lang, r.store === 'apple' ? 'App Store' : 'Google Play', r.action, - r.checks.map(c => `${c.field} ${c.chars}/${c.limit}`).join(', '), problemsOf(r).join('; ')]))); + r.checks.map(c => `${c.field} ${c.chars}/${c.limit}${c.unit === 'bytes' ? ' B' : ''}`).join(', '), problemsOf(r).join('; ')]))); } const json = a.has('json'); if (dry) { if (!json) done(TAG, 'dry run: listing files not written'); return; } @@ -167,7 +167,7 @@ function check(ctx: Ctx): void { if (ctx.args.has('json')) printJson({ sections: r, ok: !bad.length, drafts: drafts.map(d => `${d.store}:${d.lang}`) }); else { console.log(textTable(['store', 'language', 'status', 'fields', 'problems'], r.map(x => [x.store === 'apple' ? 'App Store' : 'Google Play', x.lang, - x.status === 'draft' ? 'DRAFT (review)' : x.status === 'translate' ? 'TO TRANSLATE' : 'reviewed', x.checks.map(c => `${c.field} ${c.chars}/${c.limit}`).join(', '), + x.status === 'draft' ? 'DRAFT (review)' : x.status === 'translate' ? 'TO TRANSLATE' : 'reviewed', x.checks.map(c => `${c.field} ${c.chars}/${c.limit}${c.unit === 'bytes' ? ' B' : ''}`).join(', '), x.checks.flatMap(c => c.problems.map(p => `${c.field}: ${p}`)).join('; ')]))); if (drafts.length) warn(TAG, `${drafts.length} machine-translated draft(s) not reviewed yet: ${drafts.map(d => `${d.store}:${d.lang}`).join(', ')} (storebound listing reviewed --lang after reading them)`); done(TAG, bad.length ? `${bad.length} section(s) with problems` : `${r.length} section(s) within the store limits`); diff --git a/cli/mcp-tools.ts b/cli/mcp-tools.ts index 0c1ce1b8..b0fac05d 100644 --- a/cli/mcp-tools.ts +++ b/cli/mcp-tools.ts @@ -163,7 +163,8 @@ export const TOOLS: ToolDef[] = [ props: { only, csv: { type: 'string', description: 'Prices CSV with rows for subscription ids' } }, args: i => [...opt('only', i.only), ...opt('csv', i.csv)] }, { name: 'play_data_safety', title: 'Push Play Data safety', command: ['play', 'data-safety'], write: true, destructive: true, network: true, idempotent: true, - description: 'Replace the whole Play Data safety form with the answers from the config (CSV import). dry_run prints the CSV.' }, + description: 'Replace the whole Play Data safety form with the answers from the config (CSV import). Skipped when the CSV equals the last upload of this project (hash in .storebound/; force: true sends it anyway). dry_run prints the CSV.', + props: { force: { type: 'boolean', default: false, description: 'Upload even when the CSV equals the last upload (after a manual change in Play Console)' } }, args: i => flag('force', i.force) }, { name: 'play_release_testing', title: 'Release to a Play testing track', command: ['play', 'release'], write: true, network: true, description: 'Upload an AAB (or reuse a versionCode) to a TESTING track (internal, alpha, beta) with release notes. Production is not available here.', props: { aab: { type: 'string', description: 'Path to the .aab' }, version_code: { type: 'integer', minimum: 1 }, @@ -356,6 +357,20 @@ export const TOOLS: ToolDef[] = [ props: { storefronts: { type: 'string', pattern: '^[a-z]{2}(=[A-Za-z-]+)?(,[a-z]{2}(=[A-Za-z-]+)?)*$', description: 'e.g. us,de=de-DE (default us)' }, keywords: { type: 'string', description: 'Extra keywords, comma-separated' }, competitors: { type: 'integer', minimum: 0, maximum: 10, default: 3 } }, args: i => [...opt('storefronts', i.storefronts), ...opt('keywords', i.keywords), ...opt('competitors', i.competitors), '--json'] }, + { name: 'aso_competitors', title: 'App Store competitors per keyword', command: ['aso', 'competitors'], write: false, network: true, + description: 'Read-only: for each keyword of the locale\'s keyword field (plus terms) and storefront, the top apps in Apple\'s public iTunes Search API (name, developer, rating count, first release, last update, localized genre) and the words in their names that your name / subtitle / keywords do not cover (only words of at least two developers: a one-developer word is likely a brand). One request every 3.5 s. Saves no snapshot (the terminal run `storebound aso competitors` does). Search API order is close to, not equal to, App Store search; competitor subtitles are not in any public API.', + props: { storefront: { type: 'string', pattern: '^[a-z]{2}(=[A-Za-z-]+)?(,[a-z]{2}(=[A-Za-z-]+)?)*$', description: 'e.g. us,tr (default us)' }, + terms: { type: 'string', description: 'Extra terms, comma-separated' }, top: { type: 'integer', minimum: 1, maximum: 50, default: 10 } }, + args: i => [...opt('storefront', i.storefront), ...opt('term', i.terms), ...opt('top', i.top), '--no-save', '--json'] }, + { name: 'aso_suggest', title: 'Keyword field proposal', command: ['aso', 'suggest'], write: false, network: true, + description: 'Read-only proposal: keyword candidates per App Store locale from your own name / subtitle / description, the latest `aso competitors` snapshot, the localized category names and, when Apple Ads credentials exist, Apple Ads keyword suggestions (relative popularity 0-100; without credentials popularity is "unknown", never estimated). Scores relevance (own text, competitor names) and competition (top apps with the word in their name) and returns a 100-byte keyword field per locale as old -> new. Never writes: the owner runs `storebound aso suggest --write` in a terminal, which marks the result as a draft for review.', + props: { locale: { type: 'string', description: 'Comma-separated App Store locales (default: every locale of store/appstore.md)' }, + fresh: { type: 'boolean', default: false, description: 'Do not keep the current keywords first' }, offline: { type: 'boolean', default: false, description: 'Skip Apple Ads' } }, + args: i => [...opt('locale', i.locale), ...flag('fresh', i.fresh), ...flag('offline', i.offline), '--json'] }, + { name: 'aso_audit', title: 'ASO audit', command: ['aso', 'audit'], write: false, network: false, + description: 'Offline ASO report: keyword field findings (check --aso), cross-locale free keyword room, rank trend from the `aso rank` snapshots, competitor coverage gaps, Play short description use and keyword density, App Store analytics conversion from the snapshots, Product Page Optimization / Play experiment ideas (suggestions only) and the next 3 actions.', + props: { storefront: { type: 'string', description: 'App Store storefront for the cross-locale hint', default: 'US' } }, + args: i => [...opt('storefront', i.storefront), '--json'] }, { name: 'ads_scan', title: 'AdAttributionKit scan', command: ['ads', 'scan'], write: false, network: false, description: 'Local scan of an iOS project for AdAttributionKit and SKAdNetwork: ad network ids (SKAdNetworkItems, AdNetworkIdentifiers, lowercase), postback copy endpoints (AttributionCopyEndpoint, re-engagement copies, NSAdvertisingAttributionReportEndpoint), attribution windows and cooldown, conversion value updates in code, ad SDKs without ids.', props: { ios: { type: 'string', description: 'Path of the iOS project folder, e.g. ios/App' } }, required: ['ios'], args: i => [...opt('ios', i.ios), '--json'] }, diff --git a/cli/play/data-safety.ts b/cli/play/data-safety.ts index 43b5499d..10644ded 100644 --- a/cli/play/data-safety.ts +++ b/cli/play/data-safety.ts @@ -1,7 +1,10 @@ // Play Data safety form through applications.dataSafety (CSV import; replaces every earlier answer). -// storebound play data-safety [--csv out.csv] [--dry] +// storebound play data-safety [--csv out.csv] [--dry] [--force] // Answers come from `dataSafety` in storebound.config.ts. --dry only writes / prints the CSV. -import { mkdirSync, writeFileSync } from 'node:fs'; +// Play cannot read the form back, so a run compares with what this project uploaded last: the sha256 of that CSV +// (per package) is kept in .storebound/data-safety.sha256 (gitignored). The same CSV is not sent again; --force sends it +// anyway (e.g. after the form was changed in Play Console by hand). +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import type { Ctx } from '../lib/ctx'; import { need } from '../lib/ctx'; @@ -10,6 +13,27 @@ import { DATA_SAFETY_UPLOADED } from '../lib/declarations'; import { done, log } from '../lib/log'; import { playClient } from './client'; +export const DATA_SAFETY_HASH = '.storebound/data-safety.sha256'; + +/** sha256 of the CSV for one package. Pure. */ +export const dataSafetyHash = (pkg: string, csv: string): string => new Bun.CryptoHasher('sha256').update(`${pkg}\n${csv}`).digest('hex'); + +/** The hash of the last upload of this package, null when none is recorded. */ +export function lastUpload(root: string, pkg: string): { sha256: string; at: string } | null { + const f = join(root, DATA_SAFETY_HASH); + if (!existsSync(f)) return null; + try { return (JSON.parse(readFileSync(f, 'utf8')) as Record)[pkg] ?? null; } catch { return null; } +} + +function rememberUpload(root: string, pkg: string, sha256: string): void { + const f = join(root, DATA_SAFETY_HASH); + let all: Record = {}; + try { if (existsSync(f)) all = JSON.parse(readFileSync(f, 'utf8')); } catch { all = {}; } + all[pkg] = { sha256, at: new Date().toISOString() }; + mkdirSync(join(root, '.storebound'), { recursive: true }); + writeFileSync(f, JSON.stringify(all, null, 2) + '\n'); +} + export async function run(ctx: Ctx): Promise { const { config, root, resolve } = ctx.loaded; const csv = dataSafetyCsv(need(config.dataSafety, 'dataSafety')); @@ -17,10 +41,25 @@ export async function run(ctx: Ctx): Promise { if (out) { writeFileSync(resolve(out), csv); log('play', `wrote ${out}`); } const types = Object.keys(config.dataSafety!.data); log('play', `data safety: ${types.length} data types declared (${types.join(', ') || 'none'})`); - if (ctx.args.has('dry')) { if (!out) process.stdout.write(csv); return; } - const play = await playClient(root, need(config.play?.packageName, 'play.packageName')); + const pkg = need(config.play?.packageName, 'play.packageName'); + const hash = dataSafetyHash(pkg, csv); + const last = lastUpload(root, pkg); + const same = last?.sha256 === hash; + if (ctx.args.has('dry')) { + if (!out) process.stdout.write(csv); + log('play', same ? `the same CSV was uploaded ${last!.at.slice(0, 16).replace('T', ' ')} UTC: a real run sends nothing (--force sends it again)` : 'a real run uploads it (it differs from the last upload, or none is recorded)'); + return; + } + if (same && !ctx.args.has('force')) { + done('play', `data safety unchanged since the upload of ${last!.at.slice(0, 16).replace('T', ' ')} UTC: nothing sent (--force sends it again, e.g. after a change in Play Console)`); + return; + } + const play = await playClient(root, pkg); await play.call('POST', `${play.API}/dataSafety`, { safetyLabels: csv }); - // Play cannot read the form back: keep what went up, so the desktop app can show what changed since (gitignored). - try { mkdirSync(join(root, '.storebound'), { recursive: true }); writeFileSync(join(root, DATA_SAFETY_UPLOADED), csv); } catch { /* the upload itself worked */ } + // keep what went up: the hash skips the next identical upload, the CSV lets the desktop app show what changed since + try { + rememberUpload(root, pkg, hash); + writeFileSync(join(root, DATA_SAFETY_UPLOADED), csv); + } catch { /* the upload itself worked */ } done('play', `data safety updated (${csv.split('\n').length - 2} rows)`); } diff --git a/cli/play/listing.ts b/cli/play/listing.ts index 0af7b4fe..3e7645ba 100644 --- a/cli/play/listing.ts +++ b/cli/play/listing.ts @@ -140,16 +140,24 @@ export async function run(ctx: Ctx): Promise { if (dry) { done('play', `dry run: ${p.changes ? `${p.changes} change(s)` : 'nothing to change'}; read-only, nothing written`); return; } if (!p.changes) { done('play', 'listing already up to date'); return; } if (process.stdin.isTTY && !(await confirm(ctx, `Apply these ${p.changes} change(s) to Google Play (one edit, committed)?`))) { warn('play', 'nothing written'); return; } - const todo = p.listings.filter(l => l.action !== 'same').map(l => bodies.find(b => b.language === l.key)!); - await play.edit(async id => { - if (p.details.action !== 'same') { + // The edit compares again with what it holds (a Console save or another run since the plan): only differing details + // and languages are PUT; nothing left to change = the edit is deleted, not committed. Commit only after every PUT worked. + let sent = 0; + await play.edit(async (id, ctl) => { + const cur = await play.call>('GET', `${play.API}/edits/${id}/details`); + const now = (await play.call<{ listings?: PlayListing[] }>('GET', `${play.API}/edits/${id}/listings`)).listings ?? []; + const q = playPlan(cur, details, now, bodies, { only: a.has('only') }); + const todo = q.listings.filter(l => l.action !== 'same').map(l => bodies.find(b => b.language === l.key)!); + sent = q.changes; + if (!q.changes) { ctl.unchanged(); return; } + if (q.details.action !== 'same') { await play.call('PUT', `${play.API}/edits/${id}/details`, details); - log('play', `details: ${p.details.changes.map(ch => ch.field).join(', ')}`); + log('play', `details: ${q.details.changes.map(ch => ch.field).join(', ')}`); } 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!)); } }); - done('play', 'listing done'); + done('play', sent ? 'listing done' : 'listing already up to date (the edit was deleted, nothing committed)'); } diff --git a/cli/serve.ts b/cli/serve.ts index a36fb1be..d412ba67 100644 --- a/cli/serve.ts +++ b/cli/serve.ts @@ -45,7 +45,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', 'scan', 'validate', 'health', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status', +export const JSON_TOOLS = new Set(['check', 'check_aso', 'aso_audit', 'aso_suggest', 'aso_competitors', 'scan', 'validate', 'health', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status', 'apple_next_build', 'play_status', 'play_next_version_code', 'shots_check', 'apple_testflight_status', 'apple_ppo_status', 'catalog_diff', 'project_icon', 'project_listings', 'reviews_drafts', 'project_declarations', 'project_listing_text', 'project_renders', 'project_render', 'prices_current']); diff --git a/cli/shots/check.ts b/cli/shots/check.ts index 00a64dc9..17dc66c0 100644 --- a/cli/shots/check.ts +++ b/cli/shots/check.ts @@ -6,7 +6,8 @@ // Per set: Play 2-8 phone screenshots, Apple 1-10 per display type, 13" iPad set when apple.ipad, feature graphic. // Per app preview: 886x1920 / 1200x1600, H.264, <= 30 fps, 15-30 s, stereo AAC track, <= 500 MB, <= 3 per set. // Text overflow flags come from the last `shots render` (report.json). Frames: with capture.source "folder" every frame -// the scenes use must exist with the right aspect. Exit 1 on any error (warnings do not fail). +// the scenes use must exist with the right aspect. Local font files (shots.fonts paths) without a license note: warn. +// Exit 1 on any error (warnings do not fail). import { existsSync, readdirSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import type { ShipConfig } from '../lib/config'; @@ -17,6 +18,8 @@ import { defaultSizes, frameDims, SIZES } from './lib'; import type { LocalIssue, RendersCheck } from '../lib/validate-rules'; import { allIssues, requiredSets, type RendersScan, scanRenders, storeOf } from './report'; import { imageInfo } from './spec'; +import { fontsDirOf, readManifest } from './fonts'; +import { localFontIssues } from './local-fonts'; /** Frame files the scenes (and the feature graphic) use, per language and device class. */ export function framesNeeded(config: ShipConfig, langs: string[]): { lang: string; device: 'phone' | 'tablet'; name: string }[] { @@ -58,9 +61,9 @@ export function rendersCheck(config: ShipConfig, dir: string): Record<'apple' | } export async function run(ctx: Ctx): Promise { - const { config, resolve } = ctx.loaded; + const { config, resolve, root } = ctx.loaded; const scan = scanProject(ctx); - const issues = allIssues(scan); + const issues = [...allIssues(scan), ...localFontIssues(readManifest(fontsDirOf(root))).map(issue => ({ where: '.storebound/fonts/fonts.json', issue }))]; const cap = config.shots?.capture; const frameIssues = cap?.source === 'folder' ? checkFrameFolder(config, resolve(cap.folder ?? config.shots!.frames), scan.langs) : []; if (ctx.args.has('json')) { diff --git a/cli/shots/cmap.ts b/cli/shots/cmap.ts index dd7551d7..d4fbc3b7 100644 --- a/cli/shots/cmap.ts +++ b/cli/shots/cmap.ts @@ -8,20 +8,25 @@ const tag = (d: DataView, o: number): string => String.fromCharCode(d.getUint8(o const view = (b: Uint8Array): DataView => new DataView(b.buffer, b.byteOffset, b.byteLength); /** The raw cmap table of a font file (any of the formats above). Throws on anything else. */ -export function cmapTable(file: Uint8Array): Uint8Array { +export const cmapTable = (file: Uint8Array): Uint8Array => fontTable(file, 'cmap'); + +/** One raw (untransformed) table of a font file, e.g. 'cmap' or 'name'. Throws when the file is not a font or the + * table is missing. */ +export function fontTable(file: Uint8Array, want: string): Uint8Array { const d = view(file); + if (file.byteLength < 12) throw new Error('not a font file (too short)'); const sig = tag(d, 0); - if (sig === 'wOF2') return woff2Cmap(file); + if (sig === 'wOF2') return woff2Table(file, want); if (sig === 'wOFF') { const n = d.getUint16(12); for (let i = 0; i < n; i++) { const o = 44 + i * 20; - if (tag(d, o) !== 'cmap') continue; + if (tag(d, o) !== want) continue; const off = d.getUint32(o + 4), comp = d.getUint32(o + 8), orig = d.getUint32(o + 12); const raw = file.subarray(off, off + comp); return comp < orig ? new Uint8Array(inflateSync(raw)) : raw; } - throw new Error('woff: no cmap table'); + throw new Error(`woff: no ${want} table`); } let base = 0; if (sig === 'ttcf') base = d.getUint32(12); @@ -29,9 +34,9 @@ export function cmapTable(file: Uint8Array): Uint8Array { const n = d.getUint16(base + 4); for (let i = 0; i < n; i++) { const o = base + 12 + i * 16; - if (tag(d, o) === 'cmap') { const off = d.getUint32(o + 8); return file.subarray(off, off + d.getUint32(o + 12)); } + if (tag(d, o) === want) { const off = d.getUint32(o + 8); return file.subarray(off, off + d.getUint32(o + 12)); } } - throw new Error('sfnt: no cmap table'); + throw new Error(`sfnt: no ${want} table`); } const WOFF2_TAGS = ['cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'post', 'cvt ', 'fpgm', 'glyf', 'loca', 'prep', 'CFF ', 'VORG', @@ -39,7 +44,7 @@ const WOFF2_TAGS = ['cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'pos 'CBDT', 'CBLC', 'COLR', 'CPAL', 'SVG ', 'sbix', 'acnt', 'avar', 'bdat', 'bloc', 'bsln', 'cvar', 'fdsc', 'feat', 'fmtx', 'fvar', 'gvar', 'hsty', 'just', 'lcar', 'mort', 'morx', 'opbd', 'prop', 'trak', 'Zapf', 'Silf', 'Glat', 'Gloc', 'Feat', 'Sill']; -function woff2Cmap(file: Uint8Array): Uint8Array { +function woff2Table(file: Uint8Array, want: string): Uint8Array { const d = view(file); const n = d.getUint16(12), compLen = d.getUint32(20); let p = 48; @@ -56,10 +61,10 @@ function woff2Cmap(file: Uint8Array): Uint8Array { const version = (flags >> 6) & 3; const transformed = t === 'glyf' || t === 'loca' ? version === 0 : version !== 0; const len = transformed ? base128() : orig; - if (t === 'cmap') found = [off, orig]; + if (t === want) found = [off, orig]; off += len; } - if (!found) throw new Error('woff2: no cmap table'); + if (!found) throw new Error(`woff2: no ${want} table`); if (tag(d, 4) === 'ttcf') { // collection directory: skip it (version, numFonts 255UInt16, per font numTables + indices) p += 4; const u16 = (): number => { const c = d.getUint8(p++); return c === 253 ? (p += 2, d.getUint16(p - 2)) : c === 255 ? 253 + d.getUint8(p++) : c === 254 ? 506 + d.getUint8(p++) : c; }; @@ -110,6 +115,28 @@ function readSub(d: DataView, o: number, out: Set): void { } } +/** Family name from the name table (typographic family 16, else family 1; Windows Unicode, else Mac Roman), or null. */ +export function fontFamilyName(file: Uint8Array): string | null { + let t: Uint8Array; + try { t = fontTable(file, 'name'); } catch { return null; } + const d = view(t); + const count = d.getUint16(2), strings = d.getUint16(4); + const recs: { pid: number; lang: number; id: number; text: string }[] = []; + for (let i = 0; i < count && 6 + i * 12 + 12 <= t.byteLength; i++) { + const o = 6 + i * 12; + const pid = d.getUint16(o), lang = d.getUint16(o + 4), id = d.getUint16(o + 6), len = d.getUint16(o + 8), off = strings + d.getUint16(o + 10); + if ((id !== 1 && id !== 16) || off + len > t.byteLength) continue; + const raw = t.subarray(off, off + len); + let text = ''; + if (pid === 3 || pid === 0) for (let k = 0; k + 1 < raw.length; k += 2) text += String.fromCharCode((raw[k]! << 8) | raw[k + 1]!); + else if (pid === 1) text = String.fromCharCode(...raw); + else continue; + recs.push({ pid, lang, id, text: text.trim() }); + } + const score = (r: { pid: number; lang: number; id: number }): number => (r.id === 16 ? 10 : 0) + (r.pid === 3 ? 4 : r.pid === 0 ? 3 : 1) + (r.lang === 0x409 || r.lang === 0 ? 1 : 0); + return recs.filter(r => r.text).sort((a, b) => score(b) - score(a))[0]?.text ?? null; +} + /** Code points a font file covers. */ export const fontCodepoints = (file: Uint8Array): Set => cmapCodepoints(cmapTable(file)); diff --git a/cli/shots/fonts.ts b/cli/shots/fonts.ts index 13b76fbb..5c128282 100644 --- a/cli/shots/fonts.ts +++ b/cli/shots/fonts.ts @@ -8,14 +8,16 @@ // character no fallback covers fails with the language and the characters. // storebound shots fonts [--json] (re-run after editing the copy or the fonts) // Out: /.storebound/fonts/*.woff2 + fonts.css + fonts.json (faces and the per-language stacks, read by render). -// All of these fonts are SIL Open Font License 1.1. +// The Google fonts are SIL Open Font License 1.1. A local font file in shots.fonts (local-fonts.ts) gets the same cmap +// check, is read in place (never copied) and recorded with its path, sha256 and license note. import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import type { Ctx } from '../lib/ctx'; import { need } from '../lib/ctx'; import { done, log, printJson, warn } from '../lib/log'; import { shotsStyle } from '../lib/config'; -import { type CopyFile, shotFonts } from './lib'; +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'; @@ -54,14 +56,24 @@ export async function run(ctx: Ctx): Promise { const dir = fontsDirOf(root); mkdirSync(dir, { recursive: true }); const style = shotsStyle(config); - const { title, body, titleVariable } = shotFonts(shots, style); + const sf = resolveShotFonts(shots, style, resolve, root); + const { titleVariable } = sf; + 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', - fallbackTitleAxis: style === 'app' ? 'wght@100..900' : 'wght@800', chosen: shots.fonts?.fallback, base: ASCII, + fallbackTitleAxis: style === 'app' ? 'wght@100..900' : 'wght@800', chosen: sf.fallback.map(f => f.family), base: ASCII, local, }, async (job: FaceJob) => { + 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); + const line = `${job.local.path} ${job.family}, ${(bin.byteLength / 1024).toFixed(1)} KB, ${cps.size} in the cmap, sha256 ${job.local.hash}, license: ${job.local.license ?? 'none noted (add license to the shots.fonts entry)'}`; + 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) { if (job.kind !== 'fallback') throw e; @@ -77,12 +89,13 @@ export async function run(ctx: Ctx): Promise { 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 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) { const ok = manifest.faces[f.face]?.chosen; if (!ok) auto++; const base = f.role === 'title' ? title : body; - (ok ? log : warn)('shots', `${lang} ${f.role}: ${[...f.chars].join(' ')} not in ${base} -> ${f.family}${ok ? ' (shots.fonts.fallback)' : ' (automatic fallback)'}`); + (ok ? log : warn)('shots', `${lang} ${f.role}: ${[...f.chars].join(' ')} not in ${base} -> ${f.family}${ok ? ' (shots.fonts.fallback)' : ' (automatic fallback)'}${manifest.faces[f.face]?.local ? ' (local file)' : ''}`); } if (auto) warn('shots', `${auto} automatic fallbacks: renders that use them fail \`shots check\`. Pick title / body fonts that cover them${style === 'game' ? ' (titles: e.g. Paytone One, Baloo 2, Rowdies)' : ''} or accept the fallback with shots.fonts.fallback: ['']`); done('shots', 'fonts done'); diff --git a/cli/shots/glyphs.ts b/cli/shots/glyphs.ts index b31e6878..63f0fb2e 100644 --- a/cli/shots/glyphs.ts +++ b/cli/shots/glyphs.ts @@ -16,6 +16,7 @@ import type { SceneCopy } from './lib'; import { scriptFont } from './lib'; import { needsGlyph } from './cmap'; +import { type LocalFontInfo, localFile, slug } from './local-fonts'; export type Role = 'title' | 'body'; export interface RoleTexts { title: string; body: string } @@ -61,16 +62,16 @@ export function fallbackFamilies(ch: string, lang: string, role: Role): string[] export const FALLBACK_ORDER = ['Noto Sans Display', 'Noto Sans', 'Noto Sans KR', 'Noto Sans JP', 'Noto Sans SC', 'Noto Sans TC', ...NOTO_SCRIPTS.map(s => `Noto Sans ${s}`), ...SYMBOLS]; -const slug = (s: string): string => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, ''); 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 } +export interface FaceJob { face: string; family: string; file: string; kind: FaceKind; role?: Role; axis: string | null; chars: string; local?: LocalFontInfo } export interface LangFonts { title: string[]; body: string[]; fallbacks: { role: Role; face: string; family: string; chars: string }[] } export interface FontManifest { v: 1; - faces: Record; + /** local: a local font file (shots.fonts entry with a path), read in place, never copied; file = its served path. */ + faces: Record; langs: Record; } @@ -81,8 +82,11 @@ export interface PlanInput { titleAxis: string | null; bodyAxis: string | null; /** 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. */ + /** shots.fonts.fallback: families the owner accepts as fallbacks, in order. Families that are not one of the automatic + * Noto fallbacks (another Google family, a local file) are tried first, for every character the stack lacks. */ chosen?: string[]; + /** Local font files by family (title, body or fallback). */ + local?: Record; /** Extra characters for the title / body downloads (ASCII, so later copy edits rarely need a new download). */ base?: string; } @@ -100,6 +104,11 @@ export class GlyphError extends Error { * 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 { 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())); + const order = [...extra, ...FALLBACK_ORDER]; + const fileOf = (family: string, google: string): string => local[family] ? localFile(family, local[family]!) : google; + const loc = (family: string): { local?: LocalFontInfo } => (local[family] ? { local: local[family] } : {}); const base = input.base ?? ''; const scripts = new Map }>(); const langScript = new Map(); @@ -121,13 +130,13 @@ 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 }; + faces[job.face] = { family: job.family, file: job.file, kind: job.kind, ...(job.role ? { role: job.role } : {}), chosen: isChosen, ...(job.local ? { local: job.local } : {}) }; }; - await add({ face: input.title, family: input.title, file: 'title.woff2', kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted(roleChars.title) }, true); - if (input.body !== input.title) await add({ face: input.body, family: input.body, file: 'body.woff2', kind: 'body', role: 'body', axis: input.bodyAxis, chars: sorted(roleChars.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) }, 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); 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]) })); + 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) })); } 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); @@ -139,17 +148,17 @@ export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise langs[lang] = { title: [...(x ? [x] : []), input.title], body: [...(x ? [x] : []), input.body], fallbacks: [] }; for (const role of ['title', 'body'] as const) { const stack = langs[lang]![role].map(f => cps.get(f)!); - for (const ch of uncoveredChars(t[role], stack)) pending.push({ lang, role, ch, tries: fallbackFamilies(ch, lang, role) }); + for (const ch of uncoveredChars(t[role], stack)) pending.push({ lang, role, ch, tries: [...extra, ...fallbackFamilies(ch, lang, role)] }); } } const gaps = new Map(); const hits = new Map>>(); // lang|role -> face -> chars - for (const role of ['title', 'body'] as const) for (const family of FALLBACK_ORDER) { + for (const role of ['title', 'body'] as const) for (const family of order) { const want = pending.filter(p => p.role === role && p.tries.includes(family)); if (!want.length) continue; const face = `Store fb ${slug(family)} ${role}`; const axis = family === 'Noto Color Emoji' ? null : role === 'title' ? input.fallbackTitleAxis : 'wght@100..900'; - await add({ face, family, file: `fb-${slug(family)}-${role}.woff2`, kind: 'fallback', role, axis, chars: sorted(want.map(p => p.ch)) }, chosen.has(family.toLowerCase())); + await add({ face, family, file: fileOf(family, `fb-${slug(family)}-${role}.woff2`), kind: 'fallback', role, axis, chars: sorted(want.map(p => p.ch)), ...loc(family) }, chosen.has(family.toLowerCase())); const got = cps.get(face)!; for (const p of want) { p.tries = p.tries.filter(f => f !== family); @@ -165,14 +174,14 @@ export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise for (const p of pending) { if ((p as { done?: boolean }).done) continue; const k = `${p.lang}|${p.role}`; - const g = gaps.get(k) ?? { lang: p.lang, role: p.role, chars: [], tried: [...langs[p.lang]![p.role].map(f => faces[f]?.family ?? f), ...fallbackFamilies(p.ch, p.lang, p.role)] }; + const g = gaps.get(k) ?? { lang: p.lang, role: p.role, chars: [], tried: [...langs[p.lang]![p.role].map(f => faces[f]?.family ?? f), ...extra, ...fallbackFamilies(p.ch, p.lang, p.role)] }; g.chars.push(p.ch); gaps.set(k, g); } if (gaps.size) throw new GlyphError([...gaps.values()]); for (const [k, m] of hits) { const [lang, role] = k.split('|') as [string, Role]; - for (const face of [...m.keys()].sort((a, b) => FALLBACK_ORDER.indexOf(faces[a]!.family) - FALLBACK_ORDER.indexOf(faces[b]!.family))) { + for (const face of [...m.keys()].sort((a, b) => order.indexOf(faces[a]!.family) - order.indexOf(faces[b]!.family))) { langs[lang]![role].push(face); langs[lang]!.fallbacks.push({ role, face, family: faces[face]!.family, chars: [...m.get(face)!].join('') }); } @@ -187,6 +196,12 @@ export function fontsCss(m: FontManifest): string { for (const [face, f] of Object.entries(m.faces)) { if (seen.has(face)) continue; seen.add(face); + if (f.local) { // the project's own font file, served in place; ?v= changes with its content + const l = f.local; + css += `/* ${f.family}: local file ${l.path} (${l.license ? 'license: ' + l.license.replace(/\*\//g, '') : 'no license note'}) */\n`; + 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; + } 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 5226c698..55d0547a 100644 --- a/cli/shots/lib.ts +++ b/cli/shots/lib.ts @@ -1,4 +1,5 @@ // Pure parts of the screenshot pipeline: store sizes, palettes, per-language script fonts, copy validation, job data. +import { specFamily } from './local-fonts'; 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 @@ -54,7 +55,8 @@ export const palette = (p: string | Palette | undefined, style: 'game' | 'app' = * Cyrillic. The app title is a variable font (bold headline weights). Per-script stack: glyphs.ts. */ export function shotFonts(shots: Pick | undefined, style: 'game' | 'app'): { title: string; body: string; titleVariable: boolean } { const d = style === 'app' ? { title: 'Inter', body: 'Inter' } : { title: 'Paytone One', body: 'Montserrat' }; - return { title: shots?.fonts?.title ?? d.title, body: shots?.fonts?.body ?? d.body, titleVariable: style === 'app' }; + // local files: the family given in the config, else the file name (resolveShotFonts reads the real name table) + return { title: specFamily(shots?.fonts?.title ?? d.title), body: specFamily(shots?.fonts?.body ?? d.body), titleVariable: style === 'app' }; } export interface SceneCopy { eyebrow?: string; title: [string, string]; sub?: string; badges?: [string, string?][] } diff --git a/cli/shots/local-fonts.ts b/cli/shots/local-fonts.ts new file mode 100644 index 00000000..5c4abbaf --- /dev/null +++ b/cli/shots/local-fonts.ts @@ -0,0 +1,130 @@ +// A game's or app's own brand font as a local file, next to the Google Fonts families: +// shots.fonts.title / body / fallback[] = 'Paytone One' (Google Fonts family) +// | 'assets/fonts/er-display.woff2' (local file, family from its name table) +// | { family, file, weight?, style?, license? } +// Paths are relative to the config. TTF / OTF / WOFF / WOFF2 (checked by extension and signature). The file is never +// copied: `shots fonts` reads its cmap and records it in fonts.json (path relative to the project, sha256, license), +// fonts.css points at /fonts/local/.?v= and the render / video servers serve that route from the +// original file. A changed file changes fonts.css (capture cache) and fails render until `shots fonts` runs again. +import { createHash } from 'node:crypto'; +import { existsSync, readFileSync, statSync } from 'node:fs'; +import { basename, join, relative } from 'node:path'; +import { fontFamilyName } from './cmap'; +import type { FontManifest } from './glyphs'; + +import type { FontSpec, LocalFontSpec, ShotsConfig } from '../lib/config'; +export type { FontSpec, LocalFontSpec }; +export type FontFormat = 'truetype' | 'opentype' | 'woff' | 'woff2'; + +/** A local font as fonts.json records it. path: relative to the project root. */ +export interface LocalFontInfo { path: string; format: FontFormat; hash: string; bytes: number; weight?: string; style?: string; license?: string } +/** A resolved font of shots.fonts: the family name the templates use, plus the file for a local font. */ +export interface FontRef { family: string; local?: LocalFontInfo & { abs: string } } + +const EXT: Record = { ttf: 'truetype', otf: 'opentype', woff: 'woff', woff2: 'woff2' }; + +/** A string spec is a local file when it ends in a font extension or contains a path separator. */ +export const isLocalSpec = (s: FontSpec): boolean => typeof s !== 'string' || /\.(ttf|otf|woff2?)$/i.test(s) || /[\\/]/.test(s); + +/** Format from the file signature (null = not a font file storebound reads). */ +export function sniffFormat(bin: Uint8Array): FontFormat | null { + if (bin.byteLength < 12) return null; + const sig = String.fromCharCode(bin[0]!, bin[1]!, bin[2]!, bin[3]!); + if (sig === 'wOF2') return 'woff2'; + if (sig === 'wOFF') return 'woff'; + if (sig === 'OTTO') return 'opentype'; + if (sig === 'true' || (bin[0] === 0 && bin[1] === 1 && bin[2] === 0 && bin[3] === 0)) return 'truetype'; + return null; +} + +export const fileHash = (bin: Uint8Array): string => createHash('sha256').update(bin).digest('hex').slice(0, 16); + +/** Resolves and validates one local font spec (file exists, TTF / OTF / WOFF / WOFF2). Throws with the config key. */ +export function loadLocalFont(spec: FontSpec, key: string, resolve: (p: string) => string, root: string): FontRef { + const o: LocalFontSpec = typeof spec === 'string' ? { file: spec } : spec; + if (!o.file || typeof o.file !== 'string') throw new Error(`${key}: { family, file } needs a file path (relative to the config)`); + const ext = o.file.split('.').pop()!.toLowerCase(); + if (!EXT[ext]) throw new Error(`${key}: ${o.file}: not a font file (TTF, OTF, WOFF or WOFF2)`); + const abs = resolve(o.file); + if (!existsSync(abs) || !statSync(abs).isFile()) throw new Error(`${key}: ${o.file} not found (paths are relative to the config: ${abs})`); + const bin = new Uint8Array(readFileSync(abs)); + const format = sniffFormat(bin); + if (!format) throw new Error(`${key}: ${o.file} is not a TTF / OTF / WOFF / WOFF2 font (unknown signature)`); + const sfnt = (f: FontFormat): boolean => f === 'truetype' || f === 'opentype'; + if (format !== EXT[ext] && !(sfnt(format) && sfnt(EXT[ext]!))) throw new Error(`${key}: ${o.file} is ${format.toUpperCase()} inside, but named .${ext}: rename it`); + const family = (o.family ?? fontFamilyName(bin) ?? basename(o.file).replace(/\.[^.]+$/, '')).trim(); + if (!family) throw new Error(`${key}: ${o.file}: no family name (give { family, file })`); + return { family, local: { abs, path: relative(root, abs), format, hash: fileHash(bin), bytes: bin.byteLength, + ...(o.weight !== undefined ? { weight: String(o.weight) } : {}), ...(o.style ? { style: o.style } : {}), ...(o.license ? { license: o.license } : {}) } }; +} + +/** shots.fonts resolved: Google families as names, local files loaded and validated (throws on a bad file). */ +export function resolveShotFonts(shots: Pick | undefined, style: 'game' | 'app', resolve: (p: string) => string, root: string): { title: FontRef; body: FontRef; fallback: FontRef[]; titleVariable: boolean } { + const d = style === 'app' ? { title: 'Inter', body: 'Inter' } : { title: 'Paytone One', body: 'Montserrat' }; + const ref = (s: FontSpec, key: string): FontRef => isLocalSpec(s) ? loadLocalFont(s, key, resolve, root) : { family: s as string }; + const fallback = (shots?.fonts?.fallback ?? []).map((f, i) => ref(f, `shots.fonts.fallback[${i}]`)); + return { title: ref(shots?.fonts?.title ?? d.title, 'shots.fonts.title'), body: ref(shots?.fonts?.body ?? d.body, 'shots.fonts.body'), fallback, titleVariable: style === 'app' }; +} + +/** Local files by family for planFonts (one family, one file). */ +export function localByFamily(refs: FontRef[]): Record { + const out: Record = {}; + for (const r of refs) if (r.local) { + const { abs: _abs, ...info } = r.local; + if (out[r.family] && out[r.family]!.hash !== info.hash) throw new Error(`shots.fonts: two different files for the family "${r.family}" (give each a distinct family)`); + out[r.family] = info; + } + return out; +} + +/** Family name of a spec without reading files (Google family, { family }, else the file name). For callers that only + * need a name and never a local file's name table. */ +export const specFamily = (s: FontSpec): string => typeof s !== 'string' ? s.family ?? basename(s.file).replace(/\.[^.]+$/, '') + : isLocalSpec(s) ? basename(s).replace(/\.[^.]+$/, '') : s; + +export const slug = (s: string): string => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, ''); + +/** fonts.json file name of a local face: served at /fonts/local/.. */ +export const localFile = (family: string, l: Pick): string => + `local/${slug(family)}.${l.format === 'truetype' ? 'ttf' : l.format === 'opentype' ? 'otf' : l.format}`; + +/** Absolute file of a face: the downloaded subset in .storebound/fonts, or the local font file itself. */ +export function faceFilePath(fontsDir: string, root: string, f: FontManifest['faces'][string]): string { + return f.local ? join(root, f.local.path) : join(fontsDir, f.file); +} + +/** File for a /fonts/ request of the render / video page (null = not ours). */ +export function fontsRoute(rel: string, fontsDir: string, root: string, m: FontManifest | null): string | null { + rel = rel.split('?')[0]!; + if (rel.includes('..')) return null; + if (rel.startsWith('local/')) { + const f = Object.values(m?.faces ?? {}).find(x => x.local && x.file === rel); + return f ? faceFilePath(fontsDir, root, f) : null; + } + return join(fontsDir, rel); +} + +export const FONT_TYPES: Record = { woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', css: 'text/css' }; + +/** Local faces whose file changed (or vanished) since `shots fonts`. */ +export function staleLocalFonts(m: FontManifest, root: string): string[] { + const out: string[] = []; + for (const f of new Map(Object.values(m.faces).filter(x => x.local).map(x => [x.local!.path, x] as const)).values()) { + const abs = join(root, f.local!.path); + if (!existsSync(abs)) out.push(`${f.family}: ${f.local!.path} is gone`); + else if (fileHash(new Uint8Array(readFileSync(abs))) !== f.local!.hash) out.push(`${f.family}: ${f.local!.path} changed`); + } + return out; +} + +/** `shots check` warnings for local fonts without a license note. */ +export function localFontIssues(m: FontManifest | null): { level: 'warn'; code: 'font-license'; msg: string }[] { + const seen = new Set(); + const out: { level: 'warn'; code: 'font-license'; msg: string }[] = []; + for (const f of Object.values(m?.faces ?? {})) { + if (!f.local || f.local.license || seen.has(f.local.path)) continue; + seen.add(f.local.path); + out.push({ level: 'warn', code: 'font-license', msg: `local font ${f.family} (${f.local.path}) has no license note: add license ('OFL-1.1', 'proprietary', or a short note) to its shots.fonts entry, and make sure you may embed it in store graphics` }); + } + return out; +} diff --git a/cli/shots/render.ts b/cli/shots/render.ts index 1992b488..d7b26dbb 100644 --- a/cli/shots/render.ts +++ b/cli/shots/render.ts @@ -8,7 +8,8 @@ // Fonts: the per-language stacks from .storebound/fonts/fonts.json (`shots fonts`). Before rendering, every character // of the copy is checked against the cmaps of the downloaded faces (stale fonts fail with the language and the // characters); while rendering, the page measures which face drew every character, and report.json records it per -// image (`fonts`: faces used, automatic fallbacks, system-font glyphs) for `shots check`. +// image (`fonts`: faces used, automatic fallbacks, system-font glyphs) for `shots check`. Local font files (shots.fonts +// paths) are served from where they are at /fonts/local/... (local-fonts.ts); a file changed since `shots fonts` fails. // Style: shotsStyle() = shots.style, else app for the app / subscription-app profiles (template-app.html, // feature-app.html: calm gradient, device frame, headline + subline), else game (template.html, feature.html). import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'; @@ -22,11 +23,12 @@ import { done, log, warn } from '../lib/log'; import { launch } from './browser'; import { defaultConcurrency, pool, progressLine } from './capture-web'; import { shotsStyle } from '../lib/config'; -import { type CopyFile, SIZES, copyText, defaultSizes, frameDims, mergeCopy, palette, renderDir, scriptFont, sheetLayout, shotFonts, validateCopy, variantScenes } from './lib'; +import { type CopyFile, SIZES, 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 } from './report'; const TYPES: Record = { html: 'text/html; charset=utf-8', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', - webp: 'image/webp', woff2: 'font/woff2', css: 'text/css', svg: 'image/svg+xml' }; + webp: 'image/webp', woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', css: 'text/css', svg: 'image/svg+xml' }; export async function run(ctx: Ctx): Promise { const { config, root, resolve } = ctx.loaded; @@ -62,7 +64,8 @@ export async function run(ctx: Ctx): Promise { const { phone, tablet } = frameDims(config); const rtl = new Map(config.languages.map(l => [l.id, !!l.rtl] as const)); const style = shotsStyle(config); - const sf = shotFonts(shots, style); + const rf = resolveShotFonts(shots, style, resolve, root); + const sf = { title: rf.title.family, body: rf.body.family }; const fonts = { title: sf.title, body: sf.body }; const manifest = existsSync(join(fontsDir, 'fonts.css')) ? readManifest(fontsDir) : null; if (existsSync(join(fontsDir, 'fonts.css')) && !manifest) warn('shots', 'fonts from an older storebound (no fonts.json): run `storebound shots fonts` again for the glyph coverage check'); @@ -79,10 +82,14 @@ export async function run(ctx: Ctx): Promise { const x = stacks(lang, job.copy).script; if (x) faces[x] = { family: x, file: '', kind: 'script', chosen: true }; } + if (manifest) { + const stale = staleLocalFonts(manifest, root); + if (stale.length) throw new Error(`shots render: local font files changed since \`shots fonts\`: run \`storebound shots fonts\`\n ${stale.join('\n ')}`); + } if (manifest) { // glyph coverage of the local font files, before rendering anything const cmaps = new Map>(); const cps = (face: string): Set => { - if (!cmaps.has(face)) { const f = manifest.faces[face]; cmaps.set(face, f && existsSync(join(fontsDir, f.file)) ? fontCodepoints(readFileSync(join(fontsDir, f.file))) : new Set()); } + if (!cmaps.has(face)) { const f = manifest.faces[face]; const file = f && faceFilePath(fontsDir, root, f); cmaps.set(face, file && existsSync(file) ? fontCodepoints(readFileSync(file)) : new Set()); } return cmaps.get(face)!; }; const gaps: string[] = []; @@ -121,7 +128,7 @@ export async function run(ctx: Ctx): Promise { let file = ''; if (p === '/logo' && shots.logo) file = resolve(shots.logo); else if (p.startsWith('/frames/')) file = join(framesDir, p.slice(8)); - else if (p.startsWith('/fonts/')) file = join(fontsDir, p.slice(7)); + else if (p.startsWith('/fonts/')) file = fontsRoute(p.slice(7), fontsDir, root, manifest) ?? ''; else if (p.startsWith('/out/')) file = join(outDir, p.slice(5)); else if (/^\/(template|feature)(-app)?\.html$/.test(p)) file = join(tpl, p.slice(1)); if (!file || file.includes('..')) return new Response('no', { status: 404 }); diff --git a/cli/shots/video.ts b/cli/shots/video.ts index 265c3247..474986fb 100644 --- a/cli/shots/video.ts +++ b/cli/shots/video.ts @@ -17,7 +17,8 @@ import { done, log, warn } from '../lib/log'; import { launch } from './browser'; import { shotsStyle } from '../lib/config'; import { readManifest } from './fonts'; -import { captionsFor, type CopyFile, copyText, palette, renderDir, scriptFont, shotFonts } from './lib'; +import { captionsFor, type CopyFile, copyText, palette, renderDir, scriptFont } from './lib'; +import { FONT_TYPES, fontsRoute, resolveShotFonts } from './local-fonts'; import { ffprobe } from './report'; import { checkVideo, PREVIEW_RULES, VIDEO_TARGETS } from './spec'; @@ -159,12 +160,13 @@ export async function run(ctx: Ctx): Promise { const style = shotsStyle(ctx.loaded.config); const pal = palette(shots.scenes[0]?.palette, style); return Response.json({ text: texts[Number(url.searchParams.get('i'))] ?? '', ink: style === 'app' ? '#111827' : pal.ink, rtl: rtl.get(lang), - fonts: { title: shotFonts(shots, style).title, script: script ? `Store ${script.slug}` : null, titleStack: readManifest(fontsDir)?.langs[lang]?.title } }); + fonts: { title: resolveShotFonts(shots, style, ctx.loaded.resolve, root).title.family, script: script ? `Store ${script.slug}` : null, titleStack: readManifest(fontsDir)?.langs[lang]?.title } }); } if (url.pathname === '/caption.html') return new Response(Bun.file(join(import.meta.dir, 'caption.html')), { headers: { 'content-type': 'text/html; charset=utf-8' } }); - if (url.pathname.startsWith('/fonts/') && !url.pathname.includes('..')) { - const f = Bun.file(join(fontsDir, url.pathname.slice(7))); - if (await f.exists()) return new Response(f, { headers: { 'content-type': url.pathname.endsWith('.css') ? 'text/css' : 'font/woff2' } }); + if (url.pathname.startsWith('/fonts/')) { + const file = fontsRoute(decodeURIComponent(url.pathname.slice(7)), fontsDir, root, readManifest(fontsDir)); + const f = file ? Bun.file(file) : null; + if (f && await f.exists()) return new Response(f, { headers: { 'content-type': FONT_TYPES[file!.split('.').pop()!.toLowerCase()] ?? 'font/woff2' } }); } return new Response('no', { status: 404 }); } }); diff --git a/docs/api-coverage.md b/docs/api-coverage.md index b6686b4c..11832d92 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 | 196 | 166 | +| App Store Connect API 4.5.1 | 1303 | 826 | 477 | 197 | 166 | | Google Play Android Developer API v3 (revision 20261008) | 145 | 45 | 100 | 32 | 49 | | Google Play Developer Reporting API v1beta1 (revision 20261008) | 25 | 15 | 10 | 6 | 0 | @@ -386,7 +386,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co | `appStoreVersions_deleteInstance` | DELETE | `/v1/appStoreVersions/{id}` | owner only (typed confirm) | | | `appStoreVersions_gameCenterAppVersion_getToOneRelated` | GET | `/v1/appStoreVersions/{id}/gameCenterAppVersion` | read | | | `appStoreVersions_gameCenterAppVersion_getToOneRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/gameCenterAppVersion` | read | | -| `appStoreVersions_getInstance` | GET | `/v1/appStoreVersions/{id}` | read | | +| `appStoreVersions_getInstance` | GET | `/v1/appStoreVersions/{id}` | read | apple/listing | | `appStoreVersions_routingAppCoverage_getToOneRelated` | GET | `/v1/appStoreVersions/{id}/routingAppCoverage` | read | | | `appStoreVersions_routingAppCoverage_getToOneRelationship` | GET | `/v1/appStoreVersions/{id}/relationships/routingAppCoverage` | read | | | `appStoreVersions_updateInstance` | PATCH | `/v1/appStoreVersions/{id}` | write (dry by default) | apple/listing | diff --git a/docs/idempotency.md b/docs/idempotency.md index 0ce2047d..8cddf81f 100644 --- a/docs/idempotency.md +++ b/docs/idempotency.md @@ -38,8 +38,9 @@ Tests: `tests/idempotency.test.ts` runs the write commands twice against statefu ## Commands -Status: **ok** = converges, second run writes nothing (tested where marked T). **writes** = converges but sends the -same values again (no duplicate; noted below). **owner** = a public or irreversible step that asks first. +Status: **ok** = converges, second run writes nothing (tested twice where marked T; the rows without T are covered +by the shared helpers, see "Not run twice in the tests" below). **owner** = a public or irreversible step that asks +first. No write path sends the same values again on a second run. | command | key | on re-run | status | |---|---|---|---| @@ -48,9 +49,9 @@ same values again (no duplicate; noted below). **owner** = a public or irreversi | `apple iap-review` | one review screenshot per product (MD5 + not FAILED) | kept when the bytes match, else deleted and uploaded | ok | | `apple subscriptions` | group reference name; product id; locale; promo offer code; campaign name; custom code | groups and subscriptions: findOrCreate + journal; localizations / offers / codes: createOnce; prices compared per territory, only differences sent; a subscription found late is read live (prices, intro) | ok T (twice, lost answer) | | `apple offer-codes` | campaign name per product; custom code; one-time batches by count | campaign: findOrCreate + journal (names not known unique: no blind retry); codes: 409 = exists | ok T | -| `apple win-back` | offer id per subscription | only missing offers; 409 = exists | ok (owner: asks) | -| `apple promoted` | product per promoted purchase | plan from the store; order PATCH only when it differs | ok | -| `apple preorder` | territory | plan from the store | ok (owner) | +| `apple win-back` | offer id per subscription | only missing offers; 409 = exists | ok T (owner: asks) | +| `apple promoted` | product per promoted purchase | plan from the store; order PATCH only when it differs | ok T | +| `apple preorder` | territory | plan from the store; a territory already on pre-order with that date is left | ok T (owner) | | `apple cpp create` | page name; locale | page: findOrCreate + journal; locales from a fresh read, 409 = exists | ok T | | `apple cpp upload` / `apple ppo upload` / `apple screenshots` | display type; position + MD5 | set: findOrCreate (unique, 409 = found); screenshots: matching prefix kept, rest replaced in order | ok T (twice, crash on the 3rd file) | | `apple cpp submit` / `apple events submit` / `apple iap-submit` | the app's draft submission; version id per item | draft reused or created once (journal); an item in the draft is not added again | ok T (iap-submit) (owner: submit asks) | @@ -59,7 +60,7 @@ same values again (no duplicate; noted below). **owner** = a public or irreversi | `apple ppo create` | test name (open tests only); treatment name; locale | findOrCreate + journal for test and treatments | ok T | | `apple previews` | preview type; position + MD5; poster time code | like screenshots; poster PATCH only where it differs | ok | | `apple testflight groups` | group name | findOrCreate + journal, 409 = found | ok T | -| `apple testflight testers` | email (masked) per group | only missing testers / memberships; 409 = exists | ok (owner: asks) | +| `apple testflight testers` | email (masked) per group | only missing testers / memberships; 409 = exists | ok T (owner: asks) | | `apple testflight what-to-test` / `info` | locale; fields | POST missing locales, PATCH changed fields only | ok | | `apple testflight distribute` | group per build | relationship adds (same when sent twice); beta review once per build (409 = exists) | ok (owner) | | `apple testflight expire` | build | only unexpired builds planned | ok (owner) | @@ -70,20 +71,20 @@ same values again (no duplicate; noted below). **owner** = a public or irreversi | `apple adhoc profile` | profile name (+ dated names of earlier runs) | a current profile (also a dated one) ends the run; a new name never collides | ok | | `apple signing ensure` | certificate with a local key (SPKI); profile with that certificate | a lost certificate answer keeps the pending key and finds the certificate by its public key (now or on the next run); profiles: createOnce, re-read | ok | | `apple upload` | build upload per version + build number | a COMPLETE upload is not sent again (only the wait); an unfinished one is resumed; reservations createOnce | ok | -| `apple listing` | version (editable); locale | see "open points" | writes | -| `apple appinfo` | categories, age rating, rights, price, availability | PATCHes every run (same values); price / availability only when missing | writes | +| `apple listing` | version string (editable, iOS); locale; build per version | plan from the store; version: findOrCreate (fresh GET right before the create, journal, unique: a lost answer looks first); localizations: createOnce (409 / lost answer = found, then only differing fields PATCHed); unchanged localizations skipped; the build is not re-attached when it is attached | ok T (twice, changed field, lost answer, 409) | +| `apple appinfo` | categories, age rating, rights, price, availability | each compared with the live value, only what differs is PATCHed; price schedule and availability only when missing (an existing price is never changed here: `prices import`) | ok T (twice, one changed answer) | | `analytics setup` | the ONGOING request | exists = done; createOnce | ok | | `reviews send` | review id (local `sent:` mark) | Apple 409 (already answered) = noted as sent; Play `:reply` replaces | ok (owner) | | `play products` | product id | PATCH `allowMissing` (create or update) only when it differs; activation only when not ACTIVE | ok T | | `play subscriptions` | product id; base plan id; offer id | create: 409 = found (createOnce); PATCH only differences; activation only when needed | ok T (twice, lost answer) | | `play images` | language + image type, sha256 in order | one read edit compares; only changed types are cleared and uploaded, in one edit per language | ok T | -| `play listing` | language | see "open points" | writes | +| `play listing` | language; details | compared like the dry run (`playPlan`), again inside the write edit: only differing details / languages PUT; nothing differs = the edit is deleted, not committed; commit only after every PUT worked | ok T (twice, store current by the time the edit opens) | | `play release` | versionCode; track release | a versionCode Play has is reused, not uploaded; an identical track release is not PUT; nothing changed = edit deleted | ok T | -| `play upload` | versionCode + track | already on that track with that status = done | ok | +| `play upload` | versionCode + track | already on that track with that status = done | ok T | | `play rollout` | track releases | the same releases = edit deleted, not committed | ok T | -| `play data-safety` | the form | Play has no read API for it: the same CSV is sent again (a set, no duplicates) | writes | +| `play data-safety` | sha256 of package + CSV (`.storebound/data-safety.sha256`) | Play cannot read the form back: the hash of the last upload is kept locally, the same CSV is not sent again; `--force` sends it anyway (after a hand edit in Play Console) | ok T | | `play share` | none (a new link each time) | a new internal sharing artifact per run (asks first; links expire in 60 days) | owner | -| `prices import` | product x store x region | diff first; only changed product / store pairs written (`--reconvert` always rewrites Play regions) | ok | +| `prices import` | product x store x region | diff first; only changed product / store pairs written (`--reconvert` always rewrites Play regions) | ok T (Play) | | `revenuecat sync` | store identifier + app; lookup keys | plan from a fresh read; creates through createOnce (409 = found by key); attaches are the same twice | ok | | `ads apple bid / budget / pause` | campaign / keyword | PUT of a value | ok (owner) | | `web init` | file content | unchanged files are not written | ok | @@ -91,13 +92,19 @@ same values again (no duplicate; noted below). **owner** = a public or irreversi | `console fill` | none | fills fields in a visible browser, never presses Save / Submit / Next | ok (never saves) | | `storebound api ` | none (one raw request) | a POST without a clear answer is not retried; check with a GET first | raw | -## Open points (owned by another change) +## Not run twice in the tests -- `apple listing`: the version is matched by "the editable version", not by its version string, and a new one is - created without findOrCreate; localizations are POSTed without `createOnce` (a 409 stops the run), and the build is - re-attached (PATCH) every run. Should use findOrCreate for the version and localizations, and skip the build PATCH - when it is attached already. -- `play listing`: every run opens an edit, PUTs details and every listing and commits, also when nothing changed. Should - compare like its dry run (`listingChanges`, `detailsChanges`) and call `ctl.unchanged()` when nothing differs. -- `apple appinfo`: categories, age rating and content rights are PATCHed every run. Should compare with the current - values first. +No row is open. These write paths are not run twice against the store doubles; they converge through the shared, +tested helpers instead: + +- `apple previews`: the asset-set logic of `apple screenshots` (`keptPrefix`, `syncAssets`), tested with a crash on + the 3rd file. `apple iap-review` and `apple events upload` compare MD5 / size with what is delivered before sending. +- `apple signing ensure`, `apple upload`: reservations and certificates through `createOnce` and lookups by key + (tested in `helpers`); `apple adhoc profile` stops at a current profile. The doubles have no certificate, profile + or build upload pipeline. +- `revenuecat sync`: `createOnce` with RevenueCat's 409 (`isConflict` tested); there is no RevenueCat double. +- `apple testflight what-to-test` / `info` / `distribute` / `expire`, `apple cpp upload` / `ppo upload` (the + screenshot path), `analytics setup`, `reviews send`, `ads apple`, `web init`, `flow run`: plan from the store (or + the file) first, the same helpers. +- `prices import` on the App Store side: the doubles have no manual price list per schedule; the Play side is tested, + and both share `diffPrices` / `sameSchedule`. diff --git a/docs/pitfalls.md b/docs/pitfalls.md index d7097fc1..1e542922 100644 --- a/docs/pitfalls.md +++ b/docs/pitfalls.md @@ -9,8 +9,10 @@ fails without the fix. | # | date | lesson | guard | |---|---|---|---| -| 11 | 2026-10 | App Privacy purposes were over-mapped: Play "advertising" became both Third-Party Advertising and Developer's Advertising or Marketing (Device ID, Coarse Location, Product Interaction, Performance Data). | `applePurpose` maps one Play purpose to one Apple purpose (advertising: third-party only); Developer's Advertising only from `appPrivacy.types`; `check` compares `appPrivacy.types` with Info.plist / PrivacyInfo.xcprivacy (`tests/app-privacy.test.ts`). | -| 10 | 2026-10 | A new Play app has no API: Play Console's "Create app" is the only way, its page-level button carries the same words as the form's final submit, and Free cannot become Paid later. | `console fill play-app-record`: `createAppAllowed` lets the opener through only on the app list, never in a form or dialog (EN + TR); declarations never ticked; Free / Paid outlined as an owner check (`tests/console-fill.test.ts`). | +| 13 | 2026-10 | App Privacy purposes were over-mapped: Play "advertising" became both Third-Party Advertising and Developer's Advertising or Marketing (Device ID, Coarse Location, Product Interaction, Performance Data). | `applePurpose` maps one Play purpose to one Apple purpose (advertising: third-party only); Developer's Advertising only from `appPrivacy.types`; `check` compares `appPrivacy.types` with Info.plist / PrivacyInfo.xcprivacy (`tests/app-privacy.test.ts`). | +| 12 | 2026-10 | A new Play app has no API: Play Console's "Create app" is the only way, its page-level button carries the same words as the form's final submit, and Free cannot become Paid later. | `console fill play-app-record`: `createAppAllowed` lets the opener through only on the app list, never in a form or dialog (EN + TR); declarations never ticked; Free / Paid outlined as an owner check (`tests/console-fill.test.ts`). | +| 11 | 2026-10 | Google Play has no public search API, so there is no Play keyword rank or Play competitor list to read without scraping. | `aso` reads App Store search only (iTunes Search API); `aso audit` covers Play through the listing text (short description, density); the aso-basics skill says so. | +| 10 | 2026-10 | The iTunes Search API order is close to, not equal to, App Store search (no personalisation, no search ads, no in-app event rows) and it has no subtitle field. | `aso rank` / `aso competitors` / `aso audit` label ranks as a trend and show no competitor subtitles; popularity only from Apple Ads, never estimated (`cli/lib/aso-intel.ts`). | | 9 | 2026-10 | A retried or repeated write can duplicate on a live store: a POST create retried after a timeout or 5xx, a re-run during the list lag right after a create, two runs at once, a Play edit redone after an unclear commit, a crash in the middle of a screenshot set. | Every write is an upsert (`cli/lib/upsert.ts`: findOrCreate with a fresh re-check and a journal of recent creates, createOnce treating 409 as found, no blind retry of a create); API clients retry only requests that are safe twice; Play edits are all or nothing; asset sets keep the matching prefix; one lock per app and store (`cli/lib/lock.ts`, `--force-unlock`). Table: `docs/idempotency.md`; `tests/idempotency.test.ts` runs every write twice and asserts zero writes on the second run. | | 8 | 2026-10 | Capacitor plugins in a monorepo live in `apps/native/node_modules`, so `scan` missed them. | `scan` / `privacy-manifest` resolve workspace packages (`cli/lib/scan/project.ts`, `cli/lib/node-packages.ts`). | | 7 | 2026-10 | Console UIs: the App Store Connect sign-in runs in an `idmsa.apple.com` iframe; "User Access" is a plain heading, not a labeled group; Chrome drops session cookies without `--restore-last-session`. | `console` session and fill (`cli/console/`), `tests/console-*.test.ts`. | diff --git a/examples/demo-app/README.md b/examples/demo-app/README.md index 4690d977..cc68e17a 100644 --- a/examples/demo-app/README.md +++ b/examples/demo-app/README.md @@ -15,6 +15,8 @@ bun ../../cli/index.ts shots render --size ios69,play,feature bun ../../cli/index.ts shots gallery # store/renders/index.html bun ../../cli/index.ts check # profile checks: delete-account URL, demo account, terms URL bun ../../cli/index.ts play data-safety --dry # the Data safety CSV Play imports, from dataSafety in the config +bun ../../cli/index.ts aso audit # offline ASO report over store/appstore.md + store/listing.md +bun ../../cli/index.ts aso suggest --offline # keyword field proposals as a diff (nothing written) ``` `bun ../../cli/index.ts scan` (offline rejection-risk scan) finds four things that are true for a fictional app and diff --git a/examples/demo-app/store/appstore.md b/examples/demo-app/store/appstore.md new file mode 100644 index 00000000..77270585 --- /dev/null +++ b/examples/demo-app/store/appstore.md @@ -0,0 +1,72 @@ +# Tidy Lists · App Store listing copy (demo) + +Source for `storebound apple listing` and the ASO commands (`check --aso`, `aso suggest`, `aso audit`). Fictional app: +the text shows the format, it is never uploaded. + +--- + +## en-US · English (U.S.) + +### subtitle +``` +Shared lists for groceries +``` + +### promotionalText +``` +Share a list with the people you live with and see every change as it happens. +``` + +### keywords +``` +tasks,checklist,shopping,family,planner,list +``` + +### description +``` +Tidy Lists keeps grocery lists, packing lists and to-do lists in one calm place. + +Share a list with family or roommates and every change shows up on their phone. Check items off in the store, sort +them by aisle, and reuse a packing list for the next trip. + +FEATURES +• Shared lists that sync between phones +• Grocery lists sorted by aisle +• Packing lists and checklists you can reuse +• Works offline; changes sync when you are back online + +Sign in with an account to share lists. Delete your account any time in Settings. +``` + +## tr · Türkçe + +### subtitle +``` +Market için ortak listeler +``` + +### promotionalText +``` +Bir listeyi evdekilerle paylaş ve her değişikliği anında gör. +``` + +### keywords +``` +yapılacaklar,alışveriş,aile,planlayıcı,kontrol +``` + +### description +``` +Tidy Lists market listelerini, valiz listelerini ve yapılacaklar listelerini tek bir sakin yerde tutar. + +Bir listeyi ailenle ya da ev arkadaşlarınla paylaş; her değişiklik onların telefonunda da görünür. Markette +ürünleri işaretle, reyona göre sırala ve valiz listesini bir sonraki yolculukta yeniden kullan. + +ÖZELLİKLER +• Telefonlar arasında eşitlenen ortak listeler +• Reyona göre sıralı market listeleri +• Yeniden kullanılabilen valiz ve kontrol listeleri +• Çevrimdışı çalışır; değişiklikler bağlantı gelince eşitlenir + +Liste paylaşmak için bir hesapla giriş yap. Hesabını istediğin zaman Ayarlar'dan silebilirsin. +``` diff --git a/examples/demo-app/store/listing.md b/examples/demo-app/store/listing.md new file mode 100644 index 00000000..c8a54f27 --- /dev/null +++ b/examples/demo-app/store/listing.md @@ -0,0 +1,60 @@ +# Tidy Lists · Google Play listing copy (demo) + +Source for `storebound play listing` and the ASO commands. Fictional app: the text shows the format, it is never +uploaded. + +--- + +## English (en-US) + + +### Play title (max 30) +``` +Tidy Lists: Shared Groceries +``` + +### Play short description (max 80) +``` +Shared grocery lists +``` + +### Play full description (max 4000) +``` +Tidy Lists keeps groceries, packing and to-dos in one calm place. + +Share a grocery list with family or roommates and every change shows up on their phone. Check items off in the +store, sort them by aisle, and reuse your packing checklist for the next trip. + +FEATURES +• Shared lists that sync between phones +• Groceries sorted by aisle +• Packing checklists you can reuse +• Works offline; changes sync when you are back online + +Sign in with an account to share lists. Delete your account any time in Settings. +``` + +## Türkçe (tr-TR) + + +### Play title (max 30) +``` +Tidy Lists: Ortak Market +``` + +### Play short description (max 80) +``` +Ailenle ortak market ve yapılacaklar listeleri, her telefonda anında eşitlenir +``` + +### Play full description (max 4000) +``` +Tidy Lists market listelerini, valiz listelerini ve yapılacaklar listelerini tek bir sakin yerde tutar. + +Bir listeyi ailenle ya da ev arkadaşlarınla paylaş; her değişiklik onların telefonunda da görünür. + +ÖZELLİKLER +• Telefonlar arasında eşitlenen ortak listeler +• Reyona göre sıralı market listeleri +• Çevrimdışı çalışır +``` diff --git a/package.json b/package.json index 033663c7..04376382 100644 --- a/package.json +++ b/package.json @@ -59,6 +59,7 @@ "adapters": "bun tools/gen-adapters.ts", "scrub": "bun tools/scrub.ts", "ci": "bun tools/ci.ts", + "ci:quick": "bun tools/ci.ts --quick", "check": "bun run typecheck && bun test" }, "peerDependencies": { diff --git a/skills/aso-basics/SKILL.md b/skills/aso-basics/SKILL.md index 3291eaf5..c6ff213b 100644 --- a/skills/aso-basics/SKILL.md +++ b/skills/aso-basics/SKILL.md @@ -1,6 +1,6 @@ --- name: aso-basics -description: App store optimization basics for a mobile app's or game's text - App Store keyword field rules (100 characters, commas without spaces, no repeats of name / subtitle words, fill 90%+), subtitle and name, cross-localization keyword room per storefront, screenshot captions with real keywords, Google Play title / short / full description keyword placement without stuffing. Keyword rank checks per storefront through the public iTunes Search API. Use when the user writes or improves store listing text, keywords, asks why the app or game is not found in store search, or wants keyword ranks and competitors. +description: App store optimization basics for a mobile app's or game's text - App Store keyword field rules (100 characters, commas without spaces, no repeats of name / subtitle words, fill 90%+), subtitle and name, cross-localization keyword room per storefront, screenshot captions with real keywords, Google Play title / short / full description keyword placement without stuffing. Keyword ranks, competitors per keyword, keyword field proposals and one ASO audit from official / public data (iTunes Search API, Apple Ads popularity with the owner's credentials, App Store analytics snapshots). Use when the user writes or improves store listing text, keywords, asks why the app or game is not found in store search, or wants keyword ranks, competitors, keyword ideas or an ASO review. --- # ASO basics @@ -48,6 +48,44 @@ true; never use competitor or other apps' or games' names, "best / #1", or unrel 429 stops the run with what was read). The table shows the app's position in the first 200 results, the change since the last snapshot (`.storebound/aso/.json`) and the first competitors (title, developer, rating). +6. Competitors: `storebound aso competitors --dry`, then without `--dry` (MCP: `aso_competitors`, read-only, saves no + snapshot). Per keyword (plus `--term`) and storefront the top N apps: name, developer, rating count, first release, + last update, genre in the storefront's language. Then the words in their names your name / subtitle / keywords do + not cover; a word only counts when two or more developers use it (one developer's word is most likely a brand). + Snapshots go to `.storebound/aso/competitors/` and the next run names the apps new in a term's top N. +7. Keyword ideas: `storebound aso suggest --locale en-US` (MCP: `aso_suggest`, never writes). Candidates come from the + own name / subtitle / description, the latest competitor snapshot, the category names in that language and, when + `APPLE_ADS_*` credentials are set (`ads apple status` works), Apple Ads keyword suggestions. For each: relevance + (in your own text +1, in competitor names +1), competition (top apps with the word in their name, "3/16"), + popularity (Apple Ads' relative 0-100 score; "unknown" otherwise). Show the owner the proposed field (old -> new, + bytes) and the left-out words with the reason. Only after a yes: `storebound aso suggest --locale en-US --write` + (terminal); it writes the field with a draft line above it. The owner reviews, deletes the line, runs + `check --aso`. Never put words in that do not describe the app, other apps' names or brands. +8. Review: `storebound aso audit` (MCP: `aso_audit`, offline) puts it together: keyword field findings, free keyword + room in other localizations, rank trend arrows (↑ ↓ → new lost), coverage gaps, Play short description use and word + density, App Store conversion from `analytics snapshot`, experiment ideas and the next 3 actions. Start there. + +## Experiments (suggestions only; nothing starts on its own) +- App Store Product Page Optimization tests the icon, screenshots and app previews only, not the name or subtitle. + To test a first-screenshot caption: a `shots.variants` entry, `shots render --variant b`, `apple ppo create --variant + b --dry`, `apple ppo upload --variant b --dry` (store-screenshots skill). Starting a test (`apple ppo start`) is the + owner's step. +- A subtitle change ships with a version: change one thing, then compare with `analytics compare`. +- Google Play store listing experiments (short / full description, icon, feature graphic, screenshots) have no API: + storebound prepares the text and renders; the owner sets the experiment up in Play Console. + +## Where the numbers come from (say it to the owner) +| number | source | is | is not | +|---|---|---|---| +| rank | iTunes Search API, first 200 results | the app's position in that API's order today | the App Store search position (no personalisation, ads, in-app events) | +| competitors, rating count, release dates, genre | iTunes Search API | what the top apps of that term show publicly | their subtitles (no public API has them), downloads or revenue | +| relevance, competition | own listing + competitor names | how close a word is to your text and how many top apps lead with it | search volume | +| popularity 0-100 | Apple Ads Platform API keyword suggestions (owner's credentials) | Apple's relative score across the chosen countries | an absolute number of searches; never estimated without Apple Ads | +| impressions, downloads, conversion | App Store Connect analytics snapshots | real store numbers for the window read | instant feedback: a change needs days on both sides | + +Google Play has no public search API: there are no Play keyword ranks or Play competitor lists here (that would need +scraping). Use the Play Console acquisition report (search terms) and `analytics snapshot` for Play. + ## Rank check limits (say them to the owner) - The Search API order is close to, not the same as, App Store search (no personalisation, no Search Ads, no in-app event rows). Read ranks as a trend over weeks, not as a promise. diff --git a/skills/store-declarations/SKILL.md b/skills/store-declarations/SKILL.md index 2ece8caa..c9aedb29 100644 --- a/skills/store-declarations/SKILL.md +++ b/skills/store-declarations/SKILL.md @@ -18,6 +18,8 @@ CLI: `storebound` (or `bunx storebound` in a project that has it, or `bun Policy and programs > App content > Data safety. 3. **Play App content (UI).** Policy and programs > App content, each card with `store/declarations.md`: privacy policy, app access, ads, content rating (IARC questionnaire), target audience and content, news, COVID-19, diff --git a/skills/store-pitfalls/SKILL.md b/skills/store-pitfalls/SKILL.md index 33cd0913..10e6a6cb 100644 --- a/skills/store-pitfalls/SKILL.md +++ b/skills/store-pitfalls/SKILL.md @@ -1,6 +1,6 @@ --- name: store-pitfalls -description: Known pitfalls with App Store Connect, Google Play and storebound itself, learned from real releases, and what to do about each - store lists that lag right after a create, dry runs that print a count instead of a plan, App Store names taken on a storefront, keyword limits in bytes, Data safety answers without code evidence, missing font glyphs in screenshots, console sign-in and sessions, Capacitor monorepo plugins, duplicates from retries, re-runs and parallel runs., Play's Create app form (no API, opener and submit share a name, Free is final), App Privacy purposes over-mapped (Play advertising is Third-Party Advertising only). Read it before any store task, and when a store command does something you did not expect. +description: Known pitfalls with App Store Connect, Google Play and storebound itself, learned from real releases, and what to do about each - store lists that lag right after a create, dry runs that print a count instead of a plan, App Store names taken on a storefront, keyword limits in bytes, Data safety answers without code evidence, missing font glyphs in screenshots, console sign-in and sessions, Capacitor monorepo plugins, duplicates from retries, re-runs and parallel runs, App Store search ranks that are only a trend, Play without a search API, Play's Create app form (no API, opener and submit share a name, Free is final), App Privacy purposes over-mapped (Play advertising is Third-Party Advertising only). Read it before any store task, and when a store command does something you did not expect. --- # Store pitfalls @@ -83,7 +83,23 @@ Each entry: **symptom** → cause → what to do → what guards it now. The ful Play edits deleted on every error and never redone after an unclear commit, screenshot / preview sets keep the matching prefix in order, `.storebound/locks/` per app and store. `tests/idempotency.test.ts`. -## 10. A new Play app: "Create app" is both the opener and the submit +## 10. "We rank #4 for this keyword" (from the Search API) +- **Symptom:** `aso rank` says #4, the owner's phone shows the app lower (or higher) in App Store search. +- **Cause:** the iTunes Search API order is close to, not equal to, App Store search: no personalisation, no search + ads, no in-app event rows. It has no subtitle field either. +- **Do:** read ranks as a trend over weeks (`aso audit` arrows), never as a promise; never claim a competitor's + subtitle (no public API has it); a popularity number exists only from Apple Ads, never estimate one. +- **Guard:** `aso rank`, `aso competitors` and `aso audit` say it in their output; `aso suggest` shows popularity + "unknown" without Apple Ads credentials. + +## 11. "Check our Google Play keyword ranks" +- **Symptom:** the owner asks for Play ranks or Play competitors per keyword. +- **Cause:** Google Play has no public search API; reading Play search pages would be scraping. +- **Do:** say so. Measure Play through the Play Console acquisition reports (search terms) and `analytics snapshot` + (store listing visitors, acquisitions); improve the listing text with `aso audit` (short description, density). +- **Guard:** `aso` covers App Store search only; the aso-basics skill states the limit. + +## 12. A new Play app: "Create app" is both the opener and the submit - **Symptom:** an agent cannot create the Play app through the API, or clicks "Create app" without knowing whether it opens the form or submits it; or an app goes out as Free and the owner later wants it paid. - **Cause:** the Play Developer API cannot create apps. Play Console's Home has a "Create app" button that opens the @@ -95,7 +111,7 @@ Each entry: **symptom** → cause → what to do → what guards it now. The ful - **Guard:** `createAppAllowed` lets the opener through only on the app list, never inside a form or dialog (English and Turkish); agreement checkboxes are never ticked; Free or paid is outlined as an owner check. -## 11. App Privacy purposes over-mapped +## 13. App Privacy purposes over-mapped - **Symptom:** App Privacy says Developer's Advertising or Marketing for Device ID, Coarse Location, Product Interaction or Performance Data, although the app only shows an ad SDK's ads. - **Cause:** a Play purpose was turned into two Apple purposes ("advertising" -> Third-Party Advertising AND diff --git a/skills/store-screenshots/SKILL.md b/skills/store-screenshots/SKILL.md index 8b64343d..1f7cc147 100644 --- a/skills/store-screenshots/SKILL.md +++ b/skills/store-screenshots/SKILL.md @@ -92,6 +92,11 @@ in a plain Android tablet body instead of the iPad one. titles; Montserrat, Inter, Nunito for body), or, if the owner accepts mixed glyphs, `shots.fonts.fallback: ['Noto Sans Display']`. Lilita One lacks most of Latin Extended (Turkish ş ğ İ, Polish, Czech, Romanian) and Vietnamese. Re-run after copy or font edits (render refuses fonts that no longer cover the copy). + A game's own brand font: put the file path (relative to the config; TTF / OTF / WOFF / WOFF2) or + `{ family, file, license }` into `shots.fonts.title` / `body` / `fallback`. The same coverage check runs on it, listed + fallbacks are tried before Noto (`pl title: ę ł ą Ł not in ER Display -> Noto Sans Display`), the file is served in + place (never copied) and its hash is in fonts.json, so edits to the font need `shots fonts` again. Ask the owner for + the license ('OFL-1.1', 'proprietary', ...) and put it in `license`; `shots check` warns without one. 5. **Style and scenes.** `shots.style`: `game` (sunburst, sparkles, outlined titles, badges) or `app` (calm gradient, one clean device frame, headline + subline, no sparkles; badges only as quiet chips when the copy has them). Default: `app` for the app / subscription-app profiles, `game` otherwise. `shots.scenes`: palette (game: fire, diff --git a/tests/aso-plus.test.ts b/tests/aso-plus.test.ts new file mode 100644 index 00000000..2f909a0e --- /dev/null +++ b/tests/aso-plus.test.ts @@ -0,0 +1,322 @@ +// aso competitors / suggest / audit: pure parts and the commands against recorded iTunes Search API answers +// (tests/fixtures/aso, real response shape, placeholder apps) and mocked Apple Ads keyword suggestions. +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import { generateKeyPairSync } from 'node:crypto'; +import { existsSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { run as aso } from '../cli/aso'; +import { run as check } from '../cli/check'; +import { auditText, buildAudit, nextActions, playUse, rankTrend } from '../cli/lib/aso-audit'; +import { + bigrams, candidates, categoryNames, competitorRow, coverageGaps, DRAFT_RE, draftLocales, draftMark, fitKeywordField, keywordSuggestionBody, newEntrants, + parseKeywordSuggestions, sameWord, setKeywords, stem, storefrontOf, tokens, +} from '../cli/lib/aso-intel'; +import type { SearchApp } from '../cli/lib/aso-rank'; +import { FORBIDDEN_ARGS, TOOLS, toArgv } from '../cli/mcp-tools'; +import { JSON_TOOLS, methodName } from '../cli/serve'; +import { BASE, capture, jsonOut, mockFetch, project, restore } from './helpers/store-mock'; + +const FIX = join(import.meta.dir, 'fixtures/aso'); +const US = JSON.parse(readFileSync(join(FIX, 'search-grocery-list-us.json'), 'utf8')) as { results: SearchApp[] }; +const DE = JSON.parse(readFileSync(join(FIX, 'search-einkaufsliste-de.json'), 'utf8')) as { results: SearchApp[] }; +const ADS = JSON.parse(readFileSync(join(FIX, 'ads-keyword-suggestions.json'), 'utf8')); +const APP = { appId: '6400000101', bundleId: 'com.example.notes' }; +const ADS_KEYS = ['APPLE_ADS_CLIENT_ID', 'APPLE_ADS_TEAM_ID', 'APPLE_ADS_KEY_ID', 'APPLE_ADS_PRIVATE_KEY', 'APPLE_ADS_ACCOUNT_ID']; +const saved: Record = {}; + +beforeEach(() => { for (const k of ADS_KEYS) { saved[k] = process.env[k]; delete process.env[k]; } }); +afterEach(() => { restore(); for (const k of ADS_KEYS) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; } }); + +const LISTING = `# App Store + +## en-US · English + +### subtitle +\`\`\` +Shared grocery lists +\`\`\` + +### promotionalText +\`\`\` +Promo. +\`\`\` + +### keywords +\`\`\` +todo,checklist,list,family +\`\`\` + +### description +\`\`\` +Example Notes keeps grocery lists and packing lists in one place. Share a packing list with family. + +Sort groceries by aisle and reuse a packing checklist. +\`\`\` + +## de-DE · Deutsch + +### subtitle +\`\`\` +Gemeinsame Listen +\`\`\` + +### promotionalText +\`\`\` +Promo. +\`\`\` + +### keywords +\`\`\` +einkauf,familie +\`\`\` + +### description +\`\`\` +Einkaufslisten für die ganze Familie. +\`\`\` +`; +const PLAY = '# Play\n\n## English\n\n\n### title\n```\nExample Notes: Groceries\n```\n\n### short\n```\nShared lists\n```\n\n### full\n```\nGrocery lists for the family.\n```\n'; + +describe('words', () => { + test('tokens, bigrams, plural-insensitive and suffix-aware sameness', () => { + expect(tokens('The best Grocery Lists for your family app', 'en-US')).toEqual(['best', 'grocery', 'lists', 'family']); + expect(tokens("Ayarlar'dan sil", 'tr')).toEqual(['ayarlar', 'sil']); + expect(bigrams('Grocery lists. Packing lists and more', 'en-US')).toEqual(['grocery lists', 'packing lists']); + expect(stem('groceries', 'en-US')).toBe('grocery'); + expect(stem('lists', 'en-US')).toBe('list'); + expect(stem('lists', 'de-DE')).toBe('lists'); + expect(sameWord('listeler', 'listelerini', 'tr')).toBe(true); + expect(sameWord('list', 'listing', 'en-US')).toBe(false); + expect(storefrontOf('en-US')).toBe('us'); + expect(storefrontOf('tr')).toBe('tr'); + expect(storefrontOf('ja')).toBe('jp'); + }); +}); + +describe('competitors (recorded Search API answers)', () => { + const row = competitorRow(US.results, APP, { storefront: 'us', locale: 'en-US', term: 'grocery list' }, 4); + test('top N other apps with release dates and localized genres; our own position', () => { + expect(row.ourRank).toBe(3); + expect(row.apps.map(a => a.rank)).toEqual([1, 2, 4, 5]); + expect(row.apps[0]).toMatchObject({ name: 'Basket: Grocery Shopping List', developer: 'Example Studio A', ratings: 80000, released: '2012-05-11', updated: '2026-09-11', genre: 'Productivity' }); + expect(row.apps[0]!.genres).toEqual([{ id: '6007', name: 'Productivity' }, { id: '6024', name: 'Shopping' }]); + }); + test('coverage gaps: words of two or more developers that we do not cover; one-developer words (brands) left out', () => { + const all = competitorRow(US.results, APP, { storefront: 'us', locale: 'en-US', term: 'grocery list' }, 10); + const gaps = coverageGaps([all], ['list', 'todo'], 'en-US'); + expect(gaps.map(g => g.word)).toEqual(['grocery', 'shopping']); + expect(gaps[0]).toMatchObject({ apps: 3, developers: 3 }); + expect(gaps.some(g => g.word === 'cartful')).toBe(false); // one developer, two apps: a brand + expect(coverageGaps([all], ['groceries', 'lists', 'shopping'], 'en-US')).toEqual([]); + }); + test('new entrants and localized category names', () => { + const before = { ...row, apps: row.apps.slice(1) }; + expect(newEntrants([row], [before]).get('us|grocery list')).toEqual(['Basket: Grocery Shopping List']); + expect(newEntrants([row], undefined).size).toBe(0); + const de = competitorRow(DE.results, APP, { storefront: 'de', locale: 'de-DE', term: 'einkaufsliste' }, 10); + expect(categoryNames([de], ['PRODUCTIVITY'])).toEqual(['Produktivität']); + expect(categoryNames([de], ['FOOD_AND_DRINK'])).toEqual(['Essen und Trinken']); + }); +}); + +describe('Apple Ads keyword suggestions', () => { + test('request body: required filters, terms, countries, popularity order', () => { + const b = keywordSuggestionBody('6400000101', ['grocery'], ['us']) as { filters: { field: string; value: string[] }[]; sorting: unknown; pagination: unknown }; + expect(b.filters.map(f => f.field)).toEqual(['promotedObjectId', 'promotedObjectType', 'terms', 'countriesOrRegions']); + expect(b.filters[1]!.value).toEqual(['APPSTORE_APP']); + expect(b.filters[3]!.value).toEqual(['US']); + expect(b.sorting).toEqual([{ field: 'popularity', order: 'DESC' }]); + expect(b.pagination).toEqual({ offset: 0, pageSize: 200 }); + }); + test('parse: text + popularity 0-100, junk left out', () => { + expect(parseKeywordSuggestions(ADS)).toHaveLength(4); + expect(parseKeywordSuggestions({ result: [{ text: 'x', popularity: 140 }, { text: 'y' }, null] })).toEqual([{ text: 'x', popularity: 100 }]); + expect(parseKeywordSuggestions({})).toEqual([]); + }); +}); + +describe('candidates and the 100-byte field', () => { + const comp = [competitorRow(US.results, APP, { storefront: 'us', locale: 'en-US', term: 'grocery list' }, 10)]; + const base = { locale: 'en-US', name: 'Example Notes', subtitle: 'Shared grocery lists', keywords: 'todo,checklist,list,family', description: 'Grocery lists and packing lists. Share a packing list with family. Sort by aisle, reuse a packing checklist. Aisle sorting.', competitors: comp, categories: ['Productivity'] }; + test('no popularity without Apple Ads; relevance and competition from own text and competitor names', () => { + const c = candidates({ ...base, ads: [] }); + expect(c.every(x => x.popularity === null)).toBe(true); + const packing = c.find(x => x.term === 'packing')!; + expect(packing).toMatchObject({ status: 'candidate', relevance: 2, inNames: 1, ofApps: 5 }); + expect(c.find(x => x.term === 'grocery')!.status).toBe('indexed'); + expect(c.find(x => x.term === 'productivity')!.status).toBe('category'); + expect(c.find(x => x.term === 'cartful')).toBeUndefined(); + }); + test('Apple Ads popularity: exact word, or the best phrase that contains it', () => { + const c = candidates({ ...base, ads: parseKeywordSuggestions(ADS) }); + expect(c.find(x => x.term === 'packing')).toMatchObject({ popularity: 41, popularityFrom: 'exact' }); + expect(c.find(x => x.term === 'shopping')).toMatchObject({ popularity: 64, popularityFrom: 'exact', sources: ['competitors', 'apple-ads'] }); + expect(c.find(x => x.term === 'aisle')!.popularity).toBeNull(); + }); + test('fit: <= 100 bytes, current terms kept, indexed and duplicate words dropped', () => { + const ranked = candidates({ ...base, ads: [] }); + const p = fitKeywordField({ locale: 'en-US', current: base.keywords, name: base.name, subtitle: base.subtitle, ranked }); + expect(p.kept).toEqual(['todo', 'checklist', 'family']); + expect(p.dropped).toEqual([{ term: 'list', why: 'already in the name / subtitle (indexed)' }]); + expect(p.added).toContain('packing'); + expect(p.after).not.toMatch(/,\s|\s,/); + expect(p.bytes).toBeLessThanOrEqual(100); + expect(new Set(p.after.split(',')).size).toBe(p.after.split(',').length); + // bytes, not characters: Turkish letters take two + const many = Array.from({ length: 30 }, (_, i) => ({ term: `şğü${i}`, kind: 'word' as const, sources: ['description' as const], ours: 2, relevance: 1, inNames: 0, ofApps: 0, popularity: null, popularityFrom: null, status: 'candidate' as const })); + const t = fitKeywordField({ locale: 'tr', current: '', name: 'X', subtitle: '', ranked: many }); + expect(t.bytes).toBeLessThanOrEqual(100); + expect(Buffer.byteLength(t.after)).toBe(t.bytes); + expect(fitKeywordField({ locale: 'en-US', current: 'todo', name: 'X', subtitle: '', ranked, fresh: true }).kept).toEqual([]); + }); + test('write: keywords block replaced, draft line above it, found again, then removable', () => { + const md = setKeywords(LISTING, 'en-US', 'todo,packing', draftMark('2026-10-12')); + expect(md).toContain('### keywords\n\n```\ntodo,packing\n```\n'); + expect(md).toContain('### description\n```\nExample Notes keeps'); + expect(draftLocales(md)).toEqual(['en-US']); + expect(setKeywords(md, 'en-US', 'a,b', draftMark('2026-10-13')).match(/storebound-aso/g)).toHaveLength(1); + expect(draftLocales(md.replace(DRAFT_RE, ''))).toEqual([]); + expect(() => setKeywords(LISTING, 'fr-FR', 'x', 'm')).toThrow('no "## fr-FR"'); + const noKw = '## ja · 日本語\n\n### subtitle\n```\nx\n```\n'; + expect(setKeywords(noKw, 'ja', 'リスト', draftMark('2026-10-12'))).toContain('### subtitle\n```\nx\n```\n\n### keywords\n