Merge growth-extras: PPP pricing, Apple Ads, web presence, ad-hoc and internal sharing, RevenueCat, console autofill

This commit is contained in:
CRTkafa 2026-10-12 00:21:32 +08:00
commit 657bfdc35e
75 changed files with 6463 additions and 47 deletions

View file

@ -41,21 +41,26 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
## Skills ## Skills
- `skills/account-deletion/SKILL.md`: Make account deletion pass App Store and Google Play review for an app with sign-up or sign-in - `skills/account-deletion/SKILL.md`: Make account deletion pass App Store and Google Play review for an app with sign-up or sign-in
- `skills/adhoc-distribution/SKILL.md`: Get a test build of a mobile app or game onto specific devices without a store review
- `skills/ads-levelplay-checks/SKILL.md`: Renamed to ads-mediation-checks (AdMob, AppLovin MAX and Unity LevelPlay / ironSource). Kept so existing installs and links keep working. Use ads-mediation-checks for any ad mediation, app-ads.txt, SKAdNetwork or "no fill" question - `skills/ads-levelplay-checks/SKILL.md`: Renamed to ads-mediation-checks (AdMob, AppLovin MAX and Unity LevelPlay / ironSource). Kept so existing installs and links keep working. Use ads-mediation-checks for any ad mediation, app-ads.txt, SKAdNetwork or "no fill" question
- `skills/ads-mediation-checks/SKILL.md`: Diagnose and verify ad mediation in a mobile app or game before and after store release - `skills/ads-mediation-checks/SKILL.md`: Diagnose and verify ad mediation in a mobile app or game before and after store release
- `skills/app-icons/SKILL.md`: Generate every icon a mobile app or game needs from one artwork - `skills/app-icons/SKILL.md`: Generate every icon a mobile app or game needs from one artwork
- `skills/app-previews/SKILL.md`: Make App Store app preview videos and a Google Play promo video for a mobile app or game from real footage (gameplay or app flows) - `skills/app-previews/SKILL.md`: Make App Store app preview videos and a Google Play promo video for a mobile app or game from real footage (gameplay or app flows)
- `skills/app-store-promotion/SKILL.md`: App Store promotion tools for a mobile app or game through the App Store Connect API - `skills/app-store-promotion/SKILL.md`: App Store promotion tools for a mobile app or game through the App Store Connect API
- `skills/apple-ads/SKILL.md`: Read Apple Ads (formerly Apple Search Ads) results for a mobile app or game and make small, owner-approved bid, daily budget and pause changes
- `skills/appstore-first-release/SKILL.md`: Step-by-step first (and later) App Store release of a mobile app or game - `skills/appstore-first-release/SKILL.md`: Step-by-step first (and later) App Store release of a mobile app or game
- `skills/aso-basics/SKILL.md`: App store optimization basics for a mobile app's or game's text - `skills/aso-basics/SKILL.md`: App store optimization basics for a mobile app's or game's text
- `skills/build-and-sign/SKILL.md`: Sign, build and upload a mobile app or game from the terminal - `skills/build-and-sign/SKILL.md`: Sign, build and upload a mobile app or game from the terminal
- `skills/console-autofill/SKILL.md`: AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible Chromium the owner signs in to. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes
- `skills/export-compliance/SKILL.md`: Answer App Store export compliance (encryption) for a mobile app or game correctly - `skills/export-compliance/SKILL.md`: Answer App Store export compliance (encryption) for a mobile app or game correctly
- `skills/migrate-from-fastlane/SKILL.md`: Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` - `skills/migrate-from-fastlane/SKILL.md`: Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane`
- `skills/play-first-release/SKILL.md`: Step-by-step first (and later) Google Play release of a mobile app or game - `skills/play-first-release/SKILL.md`: Step-by-step first (and later) Google Play release of a mobile app or game
- `skills/portfolio-originality/SKILL.md`: Originality gate for studios and developers that ship many similar mobile apps or games (templates, white-label apps, reskins) - `skills/portfolio-originality/SKILL.md`: Originality gate for studios and developers that ship many similar mobile apps or games (templates, white-label apps, reskins)
- `skills/ppp-pricing/SKILL.md`: Propose purchasing power parity (PPP) prices for a mobile app's or game's in-app products in every App Store territory and Google Play region with `storebound prices ppp`
- `skills/privacy-manifest/SKILL.md`: Add and check Apple privacy manifests (PrivacyInfo.xcprivacy) for an iOS app or game - `skills/privacy-manifest/SKILL.md`: Add and check Apple privacy manifests (PrivacyInfo.xcprivacy) for an iOS app or game
- `skills/privacy-policy/SKILL.md`: Write and host one studio-wide privacy policy page for all of a developer's mobile apps and games - `skills/privacy-policy/SKILL.md`: Write and host one studio-wide privacy policy page for all of a developer's mobile apps and games
- `skills/release-management/SKILL.md`: Ship updates safely after the first release - `skills/release-management/SKILL.md`: Ship updates safely after the first release
- `skills/revenuecat-sync/SKILL.md`: Optional adapter that keeps a RevenueCat project's catalog in step with the storebound config
- `skills/review-access/SKILL.md`: Give App Store and Google Play reviewers working access to an app behind a sign-in - `skills/review-access/SKILL.md`: Give App Store and Google Play reviewers working access to an app behind a sign-in
- `skills/review-rejections/SKILL.md`: Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile app or game - `skills/review-rejections/SKILL.md`: Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile app or game
- `skills/review-replies/SKILL.md`: Reply to App Store and Google Play reviews of a mobile app or game the safe way - `skills/review-replies/SKILL.md`: Reply to App Store and Google Play reviews of a mobile app or game the safe way
@ -68,4 +73,5 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
- `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages - `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages
- `skills/store-subscriptions/SKILL.md`: Set up auto-renewable subscriptions on the App Store and Google Play from one config - `skills/store-subscriptions/SKILL.md`: Set up auto-renewable subscriptions on the App Store and Google Play from one config
- `skills/testflight/SKILL.md`: Run TestFlight for a mobile app or game through the App Store Connect API - `skills/testflight/SKILL.md`: Run TestFlight for a mobile app or game through the App Store Connect API
- `skills/web-presence/SKILL.md`: Set up the web side of a mobile app or game
- `skills/whats-new/SKILL.md`: Write user-facing release notes ("What's new") for a mobile app or game update from the git log since the last tag - `skills/whats-new/SKILL.md`: Write user-facing release notes ("What's new") for a mobile app or game update from the git log since the last tag

View file

@ -43,21 +43,26 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
| skill | for | | skill | for |
|---|---| |---|---|
| `account-deletion` | Make account deletion pass App Store and Google Play review for an app with sign-up or sign-in | | `account-deletion` | Make account deletion pass App Store and Google Play review for an app with sign-up or sign-in |
| `adhoc-distribution` | Get a test build of a mobile app or game onto specific devices without a store review |
| `ads-levelplay-checks` | Renamed to ads-mediation-checks (AdMob, AppLovin MAX and Unity LevelPlay / ironSource). Kept so existing installs and links keep working. Use ads-mediation-checks for any ad mediation, app-ads.txt, SKAdNetwork or "no fill" question | | `ads-levelplay-checks` | Renamed to ads-mediation-checks (AdMob, AppLovin MAX and Unity LevelPlay / ironSource). Kept so existing installs and links keep working. Use ads-mediation-checks for any ad mediation, app-ads.txt, SKAdNetwork or "no fill" question |
| `ads-mediation-checks` | Diagnose and verify ad mediation in a mobile app or game before and after store release | | `ads-mediation-checks` | Diagnose and verify ad mediation in a mobile app or game before and after store release |
| `app-icons` | Generate every icon a mobile app or game needs from one artwork | | `app-icons` | Generate every icon a mobile app or game needs from one artwork |
| `app-previews` | Make App Store app preview videos and a Google Play promo video for a mobile app or game from real footage (gameplay or app flows) | | `app-previews` | Make App Store app preview videos and a Google Play promo video for a mobile app or game from real footage (gameplay or app flows) |
| `app-store-promotion` | App Store promotion tools for a mobile app or game through the App Store Connect API | | `app-store-promotion` | App Store promotion tools for a mobile app or game through the App Store Connect API |
| `apple-ads` | Read Apple Ads (formerly Apple Search Ads) results for a mobile app or game and make small, owner-approved bid, daily budget and pause changes |
| `appstore-first-release` | Step-by-step first (and later) App Store release of a mobile app or game | | `appstore-first-release` | Step-by-step first (and later) App Store release of a mobile app or game |
| `aso-basics` | App store optimization basics for a mobile app's or game's text | | `aso-basics` | App store optimization basics for a mobile app's or game's text |
| `build-and-sign` | Sign, build and upload a mobile app or game from the terminal | | `build-and-sign` | Sign, build and upload a mobile app or game from the terminal |
| `console-autofill` | AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible Chromium the owner signs in to. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes |
| `export-compliance` | Answer App Store export compliance (encryption) for a mobile app or game correctly | | `export-compliance` | Answer App Store export compliance (encryption) for a mobile app or game correctly |
| `migrate-from-fastlane` | Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` | | `migrate-from-fastlane` | Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` |
| `play-first-release` | Step-by-step first (and later) Google Play release of a mobile app or game | | `play-first-release` | Step-by-step first (and later) Google Play release of a mobile app or game |
| `portfolio-originality` | Originality gate for studios and developers that ship many similar mobile apps or games (templates, white-label apps, reskins) | | `portfolio-originality` | Originality gate for studios and developers that ship many similar mobile apps or games (templates, white-label apps, reskins) |
| `ppp-pricing` | Propose purchasing power parity (PPP) prices for a mobile app's or game's in-app products in every App Store territory and Google Play region with `storebound prices ppp` |
| `privacy-manifest` | Add and check Apple privacy manifests (PrivacyInfo.xcprivacy) for an iOS app or game | | `privacy-manifest` | Add and check Apple privacy manifests (PrivacyInfo.xcprivacy) for an iOS app or game |
| `privacy-policy` | Write and host one studio-wide privacy policy page for all of a developer's mobile apps and games | | `privacy-policy` | Write and host one studio-wide privacy policy page for all of a developer's mobile apps and games |
| `release-management` | Ship updates safely after the first release | | `release-management` | Ship updates safely after the first release |
| `revenuecat-sync` | Optional adapter that keeps a RevenueCat project's catalog in step with the storebound config |
| `review-access` | Give App Store and Google Play reviewers working access to an app behind a sign-in | | `review-access` | Give App Store and Google Play reviewers working access to an app behind a sign-in |
| `review-rejections` | Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile app or game | | `review-rejections` | Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile app or game |
| `review-replies` | Reply to App Store and Google Play reviews of a mobile app or game the safe way | | `review-replies` | Reply to App Store and Google Play reviews of a mobile app or game the safe way |
@ -70,4 +75,5 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
| `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages | | `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages |
| `store-subscriptions` | Set up auto-renewable subscriptions on the App Store and Google Play from one config | | `store-subscriptions` | Set up auto-renewable subscriptions on the App Store and Google Play from one config |
| `testflight` | Run TestFlight for a mobile app or game through the App Store Connect API | | `testflight` | Run TestFlight for a mobile app or game through the App Store Connect API |
| `web-presence` | Set up the web side of a mobile app or game |
| `whats-new` | Write user-facing release notes ("What's new") for a mobile app or game update from the git log since the last tag | | `whats-new` | Write user-facing release notes ("What's new") for a mobile app or game update from the git log since the last tag |

View file

@ -42,21 +42,26 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
## Skills ## Skills
- `skills/account-deletion/SKILL.md`: Make account deletion pass App Store and Google Play review for an app with sign-up or sign-in - `skills/account-deletion/SKILL.md`: Make account deletion pass App Store and Google Play review for an app with sign-up or sign-in
- `skills/adhoc-distribution/SKILL.md`: Get a test build of a mobile app or game onto specific devices without a store review
- `skills/ads-levelplay-checks/SKILL.md`: Renamed to ads-mediation-checks (AdMob, AppLovin MAX and Unity LevelPlay / ironSource). Kept so existing installs and links keep working. Use ads-mediation-checks for any ad mediation, app-ads.txt, SKAdNetwork or "no fill" question - `skills/ads-levelplay-checks/SKILL.md`: Renamed to ads-mediation-checks (AdMob, AppLovin MAX and Unity LevelPlay / ironSource). Kept so existing installs and links keep working. Use ads-mediation-checks for any ad mediation, app-ads.txt, SKAdNetwork or "no fill" question
- `skills/ads-mediation-checks/SKILL.md`: Diagnose and verify ad mediation in a mobile app or game before and after store release - `skills/ads-mediation-checks/SKILL.md`: Diagnose and verify ad mediation in a mobile app or game before and after store release
- `skills/app-icons/SKILL.md`: Generate every icon a mobile app or game needs from one artwork - `skills/app-icons/SKILL.md`: Generate every icon a mobile app or game needs from one artwork
- `skills/app-previews/SKILL.md`: Make App Store app preview videos and a Google Play promo video for a mobile app or game from real footage (gameplay or app flows) - `skills/app-previews/SKILL.md`: Make App Store app preview videos and a Google Play promo video for a mobile app or game from real footage (gameplay or app flows)
- `skills/app-store-promotion/SKILL.md`: App Store promotion tools for a mobile app or game through the App Store Connect API - `skills/app-store-promotion/SKILL.md`: App Store promotion tools for a mobile app or game through the App Store Connect API
- `skills/apple-ads/SKILL.md`: Read Apple Ads (formerly Apple Search Ads) results for a mobile app or game and make small, owner-approved bid, daily budget and pause changes
- `skills/appstore-first-release/SKILL.md`: Step-by-step first (and later) App Store release of a mobile app or game - `skills/appstore-first-release/SKILL.md`: Step-by-step first (and later) App Store release of a mobile app or game
- `skills/aso-basics/SKILL.md`: App store optimization basics for a mobile app's or game's text - `skills/aso-basics/SKILL.md`: App store optimization basics for a mobile app's or game's text
- `skills/build-and-sign/SKILL.md`: Sign, build and upload a mobile app or game from the terminal - `skills/build-and-sign/SKILL.md`: Sign, build and upload a mobile app or game from the terminal
- `skills/console-autofill/SKILL.md`: AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible Chromium the owner signs in to. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes
- `skills/export-compliance/SKILL.md`: Answer App Store export compliance (encryption) for a mobile app or game correctly - `skills/export-compliance/SKILL.md`: Answer App Store export compliance (encryption) for a mobile app or game correctly
- `skills/migrate-from-fastlane/SKILL.md`: Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` - `skills/migrate-from-fastlane/SKILL.md`: Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane`
- `skills/play-first-release/SKILL.md`: Step-by-step first (and later) Google Play release of a mobile app or game - `skills/play-first-release/SKILL.md`: Step-by-step first (and later) Google Play release of a mobile app or game
- `skills/portfolio-originality/SKILL.md`: Originality gate for studios and developers that ship many similar mobile apps or games (templates, white-label apps, reskins) - `skills/portfolio-originality/SKILL.md`: Originality gate for studios and developers that ship many similar mobile apps or games (templates, white-label apps, reskins)
- `skills/ppp-pricing/SKILL.md`: Propose purchasing power parity (PPP) prices for a mobile app's or game's in-app products in every App Store territory and Google Play region with `storebound prices ppp`
- `skills/privacy-manifest/SKILL.md`: Add and check Apple privacy manifests (PrivacyInfo.xcprivacy) for an iOS app or game - `skills/privacy-manifest/SKILL.md`: Add and check Apple privacy manifests (PrivacyInfo.xcprivacy) for an iOS app or game
- `skills/privacy-policy/SKILL.md`: Write and host one studio-wide privacy policy page for all of a developer's mobile apps and games - `skills/privacy-policy/SKILL.md`: Write and host one studio-wide privacy policy page for all of a developer's mobile apps and games
- `skills/release-management/SKILL.md`: Ship updates safely after the first release - `skills/release-management/SKILL.md`: Ship updates safely after the first release
- `skills/revenuecat-sync/SKILL.md`: Optional adapter that keeps a RevenueCat project's catalog in step with the storebound config
- `skills/review-access/SKILL.md`: Give App Store and Google Play reviewers working access to an app behind a sign-in - `skills/review-access/SKILL.md`: Give App Store and Google Play reviewers working access to an app behind a sign-in
- `skills/review-rejections/SKILL.md`: Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile app or game - `skills/review-rejections/SKILL.md`: Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile app or game
- `skills/review-replies/SKILL.md`: Reply to App Store and Google Play reviews of a mobile app or game the safe way - `skills/review-replies/SKILL.md`: Reply to App Store and Google Play reviews of a mobile app or game the safe way
@ -69,6 +74,7 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
- `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages - `skills/store-screenshots/SKILL.md`: Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages
- `skills/store-subscriptions/SKILL.md`: Set up auto-renewable subscriptions on the App Store and Google Play from one config - `skills/store-subscriptions/SKILL.md`: Set up auto-renewable subscriptions on the App Store and Google Play from one config
- `skills/testflight/SKILL.md`: Run TestFlight for a mobile app or game through the App Store Connect API - `skills/testflight/SKILL.md`: Run TestFlight for a mobile app or game through the App Store Connect API
- `skills/web-presence/SKILL.md`: Set up the web side of a mobile app or game
- `skills/whats-new/SKILL.md`: Write user-facing release notes ("What's new") for a mobile app or game update from the git log since the last tag - `skills/whats-new/SKILL.md`: Write user-facing release notes ("What's new") for a mobile app or game update from the git log since the last tag
## Working on storebound itself ## Working on storebound itself

View file

@ -2,6 +2,29 @@
## Unreleased ## Unreleased
- Growth extras, each with `--dry`, `--json`, tests on sanitized fixtures and a skill:
- `prices ppp`: purchasing power price sheets from a bundled, dated World Bank ICP PPP dataset (CC BY 4.0,
`tools/update-ppp.ts` refreshes it), the Big Mac index or a CSV; clamped, snapped to store price points, written
in the `prices import` format with a diff.
- `ads apple status | campaigns | report`: Apple Ads reports (spend, taps, installs, CPA per campaign / keyword,
CSV export); `bid | budget | pause` are dry first and ask in a terminal, never over MCP.
- `web init | check`: apple-app-site-association, assetlinks.json (Play app signing SHA-256, also read from the
Play API with `--version-code`), the Smart App Banner tag and a minimal landing page; `web check` verifies the
live files (content type, no redirects, JSON, ids match).
- `apple adhoc devices | register | profile | options | export` (release-testing / ad-hoc ExportOptions.plist,
devices with masked UDIDs, registration asks first) and `play share` (internal app sharing upload, prints the link).
- `revenuecat diff | sync`: optional RevenueCat REST API v2 adapter for products, entitlements and the default
offering; sync only creates and attaches, asks first, never over MCP.
- `console fill <form>`: AI-assisted Playwright autofill for the App Store app record, age rating, App Privacy and
the Play content rating and target audience forms. A visible Chromium with a profile the owner signs in to; it
never types passwords and never clicks Save / Submit / Publish / Next; UI changes fall back to guidance. Desktop:
"Fill in console" on the App info tab (dry run, native confirm, then the browser). Never over MCP.
- New config: `prices.ppp`, `web`, `apple.teamId`, `apple.adhoc`, `revenuecat`, `console`. New MCP tools (safe
parts only): `prices_ppp`, `web_init`, `web_check`, `apple_adhoc_devices`, `apple_adhoc_options`,
`ads_apple_status`, `ads_apple_campaigns`, `ads_apple_report`, `revenuecat_diff`.
- `apple appinfo` answers the new `socialMedia` / `socialMediaAgeRestricted` age rating questions with false
unless `apple.info.ageRating` says otherwise.
- `storebound scan` on Google Play now matches the App Store side: rejections, blocked updates, suspensions and - `storebound scan` on Google Play now matches the App Store side: rejections, blocked updates, suspensions and
policy strikes that the project files can prove, each verified against the live Play Policy Center / Play Console policy strikes that the project files can prove, each verified against the live Play Policy Center / Play Console
Help page (cited with the date in `cli/lib/scan/play-rules.ts`). New rules: the restricted permissions and their Help page (cited with the date in `cli/lib/scan/play-rules.ts`). New rules: the restricted permissions and their

View file

@ -42,21 +42,26 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
| skill | for | | skill | for |
|---|---| |---|---|
| `account-deletion` | Make account deletion pass App Store and Google Play review for an app with sign-up or sign-in | | `account-deletion` | Make account deletion pass App Store and Google Play review for an app with sign-up or sign-in |
| `adhoc-distribution` | Get a test build of a mobile app or game onto specific devices without a store review |
| `ads-levelplay-checks` | Renamed to ads-mediation-checks (AdMob, AppLovin MAX and Unity LevelPlay / ironSource). Kept so existing installs and links keep working. Use ads-mediation-checks for any ad mediation, app-ads.txt, SKAdNetwork or "no fill" question | | `ads-levelplay-checks` | Renamed to ads-mediation-checks (AdMob, AppLovin MAX and Unity LevelPlay / ironSource). Kept so existing installs and links keep working. Use ads-mediation-checks for any ad mediation, app-ads.txt, SKAdNetwork or "no fill" question |
| `ads-mediation-checks` | Diagnose and verify ad mediation in a mobile app or game before and after store release | | `ads-mediation-checks` | Diagnose and verify ad mediation in a mobile app or game before and after store release |
| `app-icons` | Generate every icon a mobile app or game needs from one artwork | | `app-icons` | Generate every icon a mobile app or game needs from one artwork |
| `app-previews` | Make App Store app preview videos and a Google Play promo video for a mobile app or game from real footage (gameplay or app flows) | | `app-previews` | Make App Store app preview videos and a Google Play promo video for a mobile app or game from real footage (gameplay or app flows) |
| `app-store-promotion` | App Store promotion tools for a mobile app or game through the App Store Connect API | | `app-store-promotion` | App Store promotion tools for a mobile app or game through the App Store Connect API |
| `apple-ads` | Read Apple Ads (formerly Apple Search Ads) results for a mobile app or game and make small, owner-approved bid, daily budget and pause changes |
| `appstore-first-release` | Step-by-step first (and later) App Store release of a mobile app or game | | `appstore-first-release` | Step-by-step first (and later) App Store release of a mobile app or game |
| `aso-basics` | App store optimization basics for a mobile app's or game's text | | `aso-basics` | App store optimization basics for a mobile app's or game's text |
| `build-and-sign` | Sign, build and upload a mobile app or game from the terminal | | `build-and-sign` | Sign, build and upload a mobile app or game from the terminal |
| `console-autofill` | AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible Chromium the owner signs in to. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes |
| `export-compliance` | Answer App Store export compliance (encryption) for a mobile app or game correctly | | `export-compliance` | Answer App Store export compliance (encryption) for a mobile app or game correctly |
| `migrate-from-fastlane` | Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` | | `migrate-from-fastlane` | Move a mobile app or game from fastlane (deliver, supply, snapshot / screengrab, Appfile, Deliverfile) to storebound with `storebound import fastlane` |
| `play-first-release` | Step-by-step first (and later) Google Play release of a mobile app or game | | `play-first-release` | Step-by-step first (and later) Google Play release of a mobile app or game |
| `portfolio-originality` | Originality gate for studios and developers that ship many similar mobile apps or games (templates, white-label apps, reskins) | | `portfolio-originality` | Originality gate for studios and developers that ship many similar mobile apps or games (templates, white-label apps, reskins) |
| `ppp-pricing` | Propose purchasing power parity (PPP) prices for a mobile app's or game's in-app products in every App Store territory and Google Play region with `storebound prices ppp` |
| `privacy-manifest` | Add and check Apple privacy manifests (PrivacyInfo.xcprivacy) for an iOS app or game | | `privacy-manifest` | Add and check Apple privacy manifests (PrivacyInfo.xcprivacy) for an iOS app or game |
| `privacy-policy` | Write and host one studio-wide privacy policy page for all of a developer's mobile apps and games | | `privacy-policy` | Write and host one studio-wide privacy policy page for all of a developer's mobile apps and games |
| `release-management` | Ship updates safely after the first release | | `release-management` | Ship updates safely after the first release |
| `revenuecat-sync` | Optional adapter that keeps a RevenueCat project's catalog in step with the storebound config |
| `review-access` | Give App Store and Google Play reviewers working access to an app behind a sign-in | | `review-access` | Give App Store and Google Play reviewers working access to an app behind a sign-in |
| `review-rejections` | Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile app or game | | `review-rejections` | Triage and answer an App Store or Google Play rejection, policy warning or strike for a mobile app or game |
| `review-replies` | Reply to App Store and Google Play reviews of a mobile app or game the safe way | | `review-replies` | Reply to App Store and Google Play reviews of a mobile app or game the safe way |
@ -69,4 +74,5 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
| `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages | | `store-screenshots` | Produce store screenshots and the Play feature graphic for a mobile app or game in every required size and many languages |
| `store-subscriptions` | Set up auto-renewable subscriptions on the App Store and Google Play from one config | | `store-subscriptions` | Set up auto-renewable subscriptions on the App Store and Google Play from one config |
| `testflight` | Run TestFlight for a mobile app or game through the App Store Connect API | | `testflight` | Run TestFlight for a mobile app or game through the App Store Connect API |
| `web-presence` | Set up the web side of a mobile app or game |
| `whats-new` | Write user-facing release notes ("What's new") for a mobile app or game update from the git log since the last tag | | `whats-new` | Write user-facing release notes ("What's new") for a mobile app or game update from the git log since the last tag |

View file

@ -449,6 +449,41 @@ run in the background with a log (`storebound shots render > .storebound/render.
</details> </details>
## Growth extras
Optional commands for after (or around) the first release. Each has `--dry` and `--json`; store and API writes ask in
a terminal first and are never offered over MCP.
- **Purchasing power prices:** `storebound prices ppp [--base 4.99] [--source worldbank|bigmac|file]` proposes a price
per region from the bundled World Bank ICP PPP conversion factors (`cli/data/ppp-worldbank.json`, CC BY 4.0, dated
and cited; refresh with `bun tools/update-ppp.ts`), clamped to `prices.ppp.floor`..`ceiling` of the US price and
snapped to each store's price points. It writes a sheet in the `prices import` format (default
`store/prices-ppp.csv`) and shows the diff; `storebound prices import --csv store/prices-ppp.csv --dry` applies it.
Skill: `ppp-pricing`.
- **Apple Ads:** `storebound ads apple status | campaigns | report [--by campaign|keyword] [--csv out.csv]`: spend,
taps, installs, CPA, read-only (OAuth client credentials from env / `.storebound/`, never printed). `bid`, `budget`
and `pause` print old -> new and ask first. Skill: `apple-ads`.
- **Web presence:** `storebound web init [--landing]` writes `apple-app-site-association`,
`.well-known/assetlinks.json` (Play app signing SHA-256), the Smart App Banner tag and an optional minimal landing
page (store marks from simple-icons, privacy / support links from the config). `storebound web check <domain>`
verifies the live files: 200 without redirects, JSON content type, valid JSON, ids match the config. Skill: `web-presence`.
- **Ad-hoc and internal sharing:** `storebound apple adhoc devices | register | profile | options | export` (UDIDs
masked; registering asks first) and `storebound play share --aab app.aab` (Play internal app sharing; asks first,
prints the install link). Skill: `adhoc-distribution`.
- **RevenueCat (optional):** `storebound revenuecat diff | sync` mirrors products, subscriptions, entitlements and a
default offering into a RevenueCat project (REST API v2, secret key from env / `.storebound/`). sync only creates and
attaches, never deletes. Runtime entitlements, receipts and paywalls stay RevenueCat's job. Skill: `revenuecat-sync`.
- **Console autofill for forms without an API:** `storebound console fill <form>` (`apple-app-record`,
`apple-age-rating`, `apple-app-privacy`, `play-content-rating`, `play-target-audience`) opens a visible Chromium
with a profile you sign in to yourself, fills what the config proves, highlights the rest and stops before any
Save / Submit / Publish: you click. When the page has changed it falls back to step-by-step guidance with copyable
answers. **Console pages change; this is AI-assisted: review every field and save it yourself.** Desktop: "Fill in
console" on the App info tab. Never over MCP. Skill: `console-autofill`.
MCP gets only the safe parts: `prices_ppp`, `web_init`, `apple_adhoc_options` (local files, dry run by default) and
the reads `ads_apple_status`, `ads_apple_campaigns`, `ads_apple_report`, `web_check`, `apple_adhoc_devices`,
`revenuecat_diff`.
## Many apps and studios ## Many apps and studios
A studio with twenty games, or a developer with apps under two store accounts, works from one folder above the app A studio with twenty games, or a developer with apps under two store accounts, works from one folder above the app

View file

@ -257,6 +257,39 @@ pub fn dialog_labels(kind: Kind, title: &str) -> (String, String) {
} }
} }
/// Dialog of `console.fill` (title, text, button): the answers of its dry run (`data` of `console fill --dry --json`),
/// the uncertain ones marked for the owner, and the note that the owner reviews and saves in the browser.
pub fn console_fill_dialog(project: &str, data: &Value) -> (String, String, String) {
let title = data["title"].as_str().unwrap_or("Console form");
let mut s = format!("{title} · {project}\n\nA browser window opens on the console page. Sign in there yourself; storebound fills the fields below and marks the ones you answer.\n\n{}\n", policy::CONSOLE_FILL_NOTE);
let answers = data["answers"].as_array().cloned().unwrap_or_default();
let mut lines: Vec<String> = answers
.iter()
.map(|a| {
let label = a["label"].as_str().unwrap_or_default();
if a["certain"].as_bool() == Some(true) {
format!("- {label}: {}", a["value"].as_str().unwrap_or_default())
} else {
format!("- {label}: you answer this")
}
})
.collect();
if lines.is_empty() {
lines.push("- (no answers from the config: every field is yours)".into());
}
let mut list = String::new();
for (i, l) in lines.iter().enumerate() {
if list.chars().count() + l.chars().count() > DIALOG_CHARS {
list.push_str(&format!("({} more in the app)\n", lines.len() - i));
break;
}
list.push_str(l);
list.push('\n');
}
s.push_str(&format!("\nAnswers ({} for you):\n{list}", data["uncertain"].as_u64().unwrap_or(0)));
(format!("Fill in console: {title}"), s, "Open the browser".to_string())
}
/// Native Apply / Cancel dialog; true on Apply. /// Native Apply / Cancel dialog; true on Apply.
async fn confirm_dialog(window: &WebviewWindow, title: String, text: String) -> Res<bool> { async fn confirm_dialog(window: &WebviewWindow, title: String, text: String) -> Res<bool> {
confirm_dialog_with(window, title, text, "Apply".into()).await confirm_dialog_with(window, title, text, "Apply".into()).await
@ -304,10 +337,15 @@ pub async fn write_with_confirm(window: WebviewWindow, app: AppHandle, state: St
if dry["ok"] != Value::Bool(true) { if dry["ok"] != Value::Bool(true) {
return Ok(json!({ "confirmed": false, "stage": "dry-run", "dryRun": dry })); return Ok(json!({ "confirmed": false, "stage": "dry-run", "dryRun": dry }));
} }
let summary = if kind == Kind::Owner { owner_summary(&d.title, &d.description, &proj.name) } else { dialog_summary(&d.title, &d.description, &proj.name, d.network, d.destructive) }; let (title, text, ok) = if method == policy::CONSOLE_FILL {
let text = format!("{summary}\n\nDry run ({}):\n{}", dry["command"].as_str().unwrap_or_default(), dialog_excerpt(dry["output"].as_str().unwrap_or_default())); console_fill_dialog(&proj.name, &dry["data"])
} else {
let summary = if kind == Kind::Owner { owner_summary(&d.title, &d.description, &proj.name) } else { dialog_summary(&d.title, &d.description, &proj.name, d.network, d.destructive) };
let text = format!("{summary}\n\nDry run ({}):\n{}", dry["command"].as_str().unwrap_or_default(), dialog_excerpt(dry["output"].as_str().unwrap_or_default()));
let (title, ok) = dialog_labels(kind, &d.title);
(title, text, ok)
};
let home = app.path().home_dir().ok().map(|h| h.to_string_lossy().to_string()); let home = app.path().home_dir().ok().map(|h| h.to_string_lossy().to_string());
let (title, ok) = dialog_labels(kind, &d.title);
if !confirm_dialog_with(&window, title, tilde(&text, home.as_deref()), ok).await? { if !confirm_dialog_with(&window, title, tilde(&text, home.as_deref()), ok).await? {
return Ok(json!({ "confirmed": false, "stage": "dialog", "dryRun": dry })); return Ok(json!({ "confirmed": false, "stage": "dialog", "dryRun": dry }));
} }

View file

@ -110,6 +110,12 @@ pub fn sanitize_js_call(method: &str, kind: Option<Kind>, params: &Value) -> Res
/// in its own commands: `project_init`, `project_import_fastlane`); `write_with_confirm` never runs them. /// in its own commands: `project_init`, `project_import_fastlane`); `write_with_confirm` never runs them.
pub const NEW_FOLDER_METHODS: &[&str] = &["project.init", "import.fastlane"]; pub const NEW_FOLDER_METHODS: &[&str] = &["project.init", "import.fastlane"];
/// `console.fill`: a write whose real run opens a visible browser on a store console form and lasts until the owner
/// closes it. `write_with_confirm` shows its answers and this note instead of a dry-run log; a cancel (`job_cancel`)
/// stops the command, which closes the browser.
pub const CONSOLE_FILL: &str = "console.fill";
pub const CONSOLE_FILL_NOTE: &str = "Console pages change. This is AI-assisted: review every field in the browser and press Save yourself. storebound never saves, submits or publishes.";
/// Reads that are never kept in the offline cache (big: one rendered image as a data: URL). /// Reads that are never kept in the offline cache (big: one rendered image as a data: URL).
pub const NO_CACHE_METHODS: &[&str] = &["project.render"]; pub const NO_CACHE_METHODS: &[&str] = &["project.render"];

View file

@ -2,9 +2,9 @@
//! after a dialog that names the action on its button and says users see it at once. Tokens are bound to exactly the //! after a dialog that names the action on its button and says users see it at once. Tokens are bound to exactly the
//! method and the { project, args } sent (the same vector as the TypeScript side checks). //! method and the { project, args } sent (the same vector as the TypeScript side checks).
use serde_json::json; use serde_json::json;
use storebound_desktop::commands::{dialog_labels, dialog_summary, owner_summary}; use storebound_desktop::commands::{console_fill_dialog, dialog_labels, dialog_summary, owner_summary};
use storebound_desktop::confirm::{canonical, mac, mint}; use storebound_desktop::confirm::{canonical, mac, mint};
use storebound_desktop::policy::{sanitize_js_call, Kind}; use storebound_desktop::policy::{sanitize_js_call, Kind, CONSOLE_FILL, CONSOLE_FILL_NOTE};
#[test] #[test]
fn owner_actions_are_dry_runs_from_the_window() { fn owner_actions_are_dry_runs_from_the_window() {
@ -58,3 +58,24 @@ fn tokens_bind_method_project_and_args_of_each_write() {
assert!(canonical(&json!({ "percent": 50 })).is_ok()); assert!(canonical(&json!({ "percent": 50 })).is_ok());
assert!(canonical(&json!({ "fraction": 0.5 })).is_err()); assert!(canonical(&json!({ "fraction": 0.5 })).is_err());
} }
#[test]
fn console_fill_is_a_dry_run_from_the_window_and_its_dialog_lists_the_answers() {
let p = sanitize_js_call(CONSOLE_FILL, Some(Kind::Write), &json!({ "args": { "form": "apple-age-rating" } })).unwrap();
assert_eq!(p["dryRun"], json!(true));
assert!(sanitize_js_call(CONSOLE_FILL, Some(Kind::Write), &json!({ "dryRun": false })).is_err());
let data = json!({ "title": "Age rating", "uncertain": 1, "answers": [
{ "id": "violence", "label": "Cartoon violence", "value": "None", "certain": true, "source": "apple.ageRating" },
{ "id": "gambling", "label": "Simulated gambling", "value": "", "certain": false, "source": "" },
] });
let (title, text, ok) = console_fill_dialog("Prism Puddle", &data);
assert_eq!(title, "Fill in console: Age rating");
assert_eq!(ok, "Open the browser");
assert!(text.contains("Prism Puddle") && text.contains(CONSOLE_FILL_NOTE));
assert!(text.contains("- Cartoon violence: None") && text.contains("- Simulated gambling: you answer this"));
let (_, empty, _) = console_fill_dialog("A", &json!(null));
assert!(empty.contains("every field is yours"));
let many: Vec<_> = (0..400).map(|i| json!({ "label": format!("Question {i}"), "value": "Yes", "certain": true })).collect();
let (_, long, _) = console_fill_dialog("A", &json!({ "title": "T", "answers": many }));
assert!(long.contains("more in the app") && long.chars().count() < 3_200);
}

View file

@ -10,7 +10,7 @@ import type { Overrides } from './lib/identity';
export type { export type {
AccountCheck, AppIdentity, AppsListResult, AppStatus, CatalogParity, DraftsResult, StoreApp, IconResult, ListingField, ListingLocale, ListingsResult, MethodDescriptor, PortfolioResult, AccountCheck, AppIdentity, AppsListResult, AppStatus, CatalogParity, DraftsResult, StoreApp, IconResult, ListingField, ListingLocale, ListingsResult, MethodDescriptor, PortfolioResult,
ProgressParams, ProjectSummary, ReleasePhase, ReleaseTrain, ReplyDraft, StoreRelease, ToolResult, ProgressParams, ProjectSummary, ReleasePhase, ReleaseTrain, ReplyDraft, StoreRelease, ToolResult,
AnalyticsCompare, DeclAsk, DeclarationsResult, ListingText, PpoStatus, PpoTest, PriceDiffRow, PriceRowData, PricesCurrent, PricesDiff, RenderImage, RenderTile, RendersResult, AnalyticsCompare, ConsoleAnswer, ConsoleFillResult, ConsoleForm, DeclAsk, DeclarationsResult, ListingText, PpoStatus, PpoTest, PriceDiffRow, PriceRowData, PricesCurrent, PricesDiff, RenderImage, RenderTile, RendersResult,
} from '../../../cli/lib/desktop-protocol'; } from '../../../cli/lib/desktop-protocol';
export interface AppInfo { version: string; identifier: string; platform: string; debug: boolean; home: string | null } export interface AppInfo { version: string; identifier: string; platform: string; debug: boolean; home: string | null }

View file

@ -3,7 +3,7 @@
// screenshotted without store accounts, in a browser or in `tauri dev`. Nothing here is real store data; the window // screenshotted without store accounts, in a browser or in `tauri dev`. Nothing here is real store data; the window
// shows a "DEV FIXTURES" badge. src/api.ts only imports this module behind import.meta.env.DEV, so release builds do // shows a "DEV FIXTURES" badge. src/api.ts only imports this module behind import.meta.env.DEV, so release builds do
// not contain it (tests/webview.test.ts checks the built files for FIXTURE_MARKER). // not contain it (tests/webview.test.ts checks the built files for FIXTURE_MARKER).
import { type Account, type AccountCheck, type AppsListResult, type AppStatus, type CacheEntry, DEFAULT_SETTINGS, type DownloadEvent, type DraftsResult, type ListingField, type ListingsResult, import { type Account, type AccountCheck, type ConsoleFillResult, type ConsoleForm, type AppsListResult, type AppStatus, type CacheEntry, DEFAULT_SETTINGS, type DownloadEvent, type DraftsResult, type ListingField, type ListingsResult,
type PortfolioResult, type Project, type ProjectSummary, type Settings, type StoreApp, type StoreRelease, type Studio, type ToolResult } from '../api'; 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 { buildApps, type Overrides } from '../lib/identity';
import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult, ScanResult } from '../lib/model'; import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult, ScanResult } from '../lib/model';
@ -434,6 +434,7 @@ function read(method: string, id: string, args: Record<string, unknown> = {}): T
case 'project.renders': return ok(method, RENDERS[id]); case 'project.renders': return ok(method, RENDERS[id]);
case 'project.render': return ok(method, { file: String(args.file), dataUrl: renderArt(String(args.file)), bytes: 1_200_000 }); case 'project.render': return ok(method, { file: String(args.file), dataUrl: renderArt(String(args.file)), bytes: 1_200_000 });
case 'prices.current': return ok(method, PRICES[id]); case 'prices.current': return ok(method, PRICES[id]);
case 'console.fill': return { ...ok(method, CONSOLE_FILL[args.form as ConsoleForm]), dryRun: true, command: `storebound console fill ${String(args.form)} --dry --json` };
case 'prices.diff': return ok(method, PRICE_DIFF[id]); case 'prices.diff': return ok(method, PRICE_DIFF[id]);
case 'apple.ppo_status': return ok(method, PPO[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 '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)` };
@ -442,6 +443,24 @@ function read(method: string, id: string, args: Record<string, unknown> = {}): T
} }
} }
// ---- console.fill: the answers `console fill <form> --dry --json` would type (made up, from the demo configs) ----
const CF = (form: ConsoleForm, title: string, url: string, answers: [string, string, string | null, string][], guidance: string[]): ConsoleFillResult => {
const list = answers.map(([id, label, value, source]) => ({ id, label, value: value ?? '', certain: value !== null, source, ...(value === null ? { note: 'Only you know this: answer it in the console' } : {}) }));
return { form, store: form.startsWith('apple') ? 'apple' : 'play', title, url, answers: list, uncertain: list.filter(a => !a.certain).length, guidance };
};
const ASC = 'https://appstoreconnect.apple.com/apps', PLAY = 'https://play.google.com/console';
const CONSOLE_FILL: Record<ConsoleForm, ConsoleFillResult> = {
'apple-app-record': CF('apple-app-record', 'New App', ASC, [['platform', 'Platforms', 'iOS', 'app.platforms'], ['name', 'Name', 'Prism Puddle', 'app.name'], ['language', 'Primary language', 'English (U.S.)', 'languages[0].apple'],
['bundleId', 'Bundle ID', 'com.example.prismpuddle', 'apple.bundleId'], ['sku', 'SKU', 'prismpuddle', 'apple.sku'], ['access', 'User access', 'Full access', 'default']], ['After Create, copy the Apple ID into apple.appId.']),
'apple-age-rating': CF('apple-age-rating', 'Age rating', ASC, [['violenceCartoonOrFantasy', 'Cartoon or fantasy violence', 'Infrequent/Mild', 'apple.ageRating'], ['gamblingSimulated', 'Simulated gambling', 'None', 'apple.ageRating'],
['messagingAndChat', 'Messaging and chat', null, ''], ['advertising', 'Advertising', 'Yes', 'ads.enabled']], ['The age rating follows from your answers; check it before you save.']),
'apple-app-privacy': CF('apple-app-privacy', 'App Privacy', ASC, [['collects', 'Do you collect data from this app?', 'Yes', 'play.dataSafety'], ['deviceId', 'Device ID', 'Third-party advertising, Analytics', 'play.dataSafety'],
['linked', 'Device ID linked to the user', null, ''], ['tracking', 'Device ID used for tracking', null, '']], ['App Privacy has no API: publish the answers in App Store Connect yourself.']),
'play-content-rating': CF('play-content-rating', 'Content rating', PLAY, [['category', 'Category', 'Game', 'app.profile'], ['violence', 'Violence', 'No', 'play.contentRating'], ['userInteraction', 'Users can interact', 'No', 'play.contentRating'],
['ads', 'Contains ads', 'Yes', 'ads.enabled'], ['purchases', 'Digital purchases', 'Yes', 'products']], ['Submitting the questionnaire is yours; storebound stops before it.']),
'play-target-audience': CF('play-target-audience', 'Target audience and content', PLAY, [['ages', 'Target age groups', '13-15, 16-17, 18 and over', 'play.targetAudience'], ['appeal', 'Could appeal to children', null, '']], []),
};
const CACHED_AGO: Record<string, number> = { health: 60 * 3, 'reviews.list': 45, 'apple.testflight_status': 60 * 5, 'catalog.diff': 60 * 26, validate: 60 * 2, 'prices.current': 60 * 4, 'apple.ppo_status': 60 * 6 }; const CACHED_AGO: Record<string, number> = { health: 60 * 3, 'reviews.list': 45, 'apple.testflight_status': 60 * 5, 'catalog.diff': 60 * 26, validate: 60 * 2, 'prices.current': 60 * 4, 'apple.ppo_status': 60 * 6 };
const NETWORK = new Set(['health', 'reviews.list', 'apple.testflight_status', 'catalog.diff', 'validate', 'prices.current', 'prices.diff', 'apple.ppo_status']); const NETWORK = new Set(['health', 'reviews.list', 'apple.testflight_status', 'catalog.diff', 'validate', 'prices.current', 'prices.diff', 'apple.ppo_status']);
@ -522,6 +541,15 @@ async function answer(cmd: string, a: Record<string, unknown>): Promise<unknown>
case 'job_cancel': cancelled.add(a.job as string); return true; case 'job_cancel': cancelled.add(a.job as string); return true;
case 'write_with_confirm': { case 'write_with_confirm': {
const method = a.method as string, args = (a.args ?? {}) as Record<string, unknown>; const method = a.method as string, args = (a.args ?? {}) as Record<string, unknown>;
if (method === 'console.fill') {
// the real run lasts until the owner closes the browser: here a few seconds, or until Cancel
const r = CONSOLE_FILL[args.form as ConsoleForm];
await progressLines(job, ['[console] opening Chromium (profile in ~/.storebound/console-profile/apple)', '[console] waiting for you to sign in', `[console] ${r.title}: filling ${r.answers.length - r.uncertain} fields`, `[console] ${r.uncertain} fields marked for you`]);
for (let i = 0; i < 20 && !(job && cancelled.has(job)); i++) await sleep(250);
if (job && cancelled.has(job)) throw { code: -32800, message: 'Request cancelled' };
const res: ToolResult = { method, ok: true, exitCode: 0, dryRun: false, command: `storebound console fill ${String(args.form)} --json`, output: '[console] browser closed', data: { ...r, filled: r.answers.length - r.uncertain, highlighted: r.uncertain, fallback: false, stoppedAt: null } };
return { confirmed: true, stage: 'done', dryRun: { ...res, dryRun: true, data: r }, result: res };
}
await progressLines(job, [`[${method}] dry run`, `[${method}] confirmed in the dialog`, `[${method}] applying`]); await progressLines(job, [`[${method}] dry run`, `[${method}] confirmed in the dialog`, `[${method}] applying`]);
if (job && cancelled.has(job)) throw { code: -32800, message: 'Request cancelled' }; if (job && cancelled.has(job)) throw { code: -32800, message: 'Request cancelled' };
const d = DRAFTS[a.projectId as string]?.drafts.find(x => x.file.endsWith(`/${String(args.file)}`)); const d = DRAFTS[a.projectId as string]?.drafts.find(x => x.file.endsWith(`/${String(args.file)}`));

View file

@ -1264,4 +1264,37 @@ export const en = {
'folder.locateFailed': 'Could not use that folder', 'folder.locateFailed': 'Could not use that folder',
'folder.remove': 'Remove from list', 'folder.remove': 'Remove from list',
'folder.removed': '{name} removed from the list', 'folder.removed': '{name} removed from the list',
'cf.button': 'Fill in console',
'cf.hint': 'Fill in {form} in the console from your config: you review every field and press Save yourself',
'cf.appleAppRecord': 'App Store app record',
'cf.appleAgeRating': 'App Store age rating',
'cf.appleAppPrivacy': 'App Privacy',
'cf.playContentRating': 'Play content rating',
'cf.playTargetAudience': 'Play target audience and content',
'cf.dryFailed': 'Could not prepare {form}',
'cf.panelTitle': 'Fill in console: {form}',
'cf.disclaimer': 'Console pages change. This is AI-assisted: review every field in the browser and press Save yourself. storebound never saves, submits or publishes.',
'cf.notOpened': 'You chose Cancel in the dialog: no browser was opened.',
'cf.runningText': 'The browser is open. Sign in there yourself; storebound fills the fields and marks the ones you answer. Review every field, press Save yourself, then close the browser.',
'cf.doneText': 'Browser closed. Filled: {filled}, marked for you: {highlighted}. Check in the console that your answers are saved.',
'cf.closed': 'Browser closed.',
'cf.cancelled': 'Stopped: the browser was closed.',
'cf.failed': 'The browser run stopped',
'cf.fallback': 'The page did not look as expected, so storebound only marked the fields. Enter the answers yourself.',
'cf.answers': '{count} answers from your config',
'cf.answers_one': '1 answer from your config',
'cf.uncertain': '{count} for you',
'cf.noAnswers': 'The config has no answers for this form: every field is yours.',
'cf.youAnswer': 'You answer this',
'cf.foot': 'A native dialog asks once more before the browser opens.',
'cf.cancelRun': 'Cancel: close the browser',
'cf.open': 'Open the browser',
'cf.waiting': 'Waiting until you close the browser',
'cf.playTitle': 'Play Console questionnaires',
'cf.playSub': 'No API: storebound fills them in the console, you save',
'cf.playContentRatingText': 'The IARC questionnaire that gives the app its age ratings.',
'cf.playTargetAudienceText': 'Target age groups and whether the app appeals to children.',
'cf.noRecordTitle': 'No App Store app record yet',
'cf.noRecordText': 'App Store Connect has no API to create the app record. storebound fills the New App form from your config; you press Create yourself, then put the Apple ID into apple.appId.',
} as const; } as const;

View file

@ -1266,4 +1266,37 @@ export const tr: Record<keyof typeof en, string> = {
'folder.locateFailed': 'Bu klasör kullanılamadı', 'folder.locateFailed': 'Bu klasör kullanılamadı',
'folder.remove': 'Listeden kaldır', 'folder.remove': 'Listeden kaldır',
'folder.removed': '{name} listeden kaldırıldı', 'folder.removed': '{name} listeden kaldırıldı',
'cf.button': 'Konsolda doldur',
'cf.hint': '{form} formunu yapılandırmanızdan konsolda doldurur: her alanı siz kontrol eder, Kaydet\'e kendiniz basarsınız',
'cf.appleAppRecord': 'App Store uygulama kaydı',
'cf.appleAgeRating': 'App Store yaş derecelendirmesi',
'cf.appleAppPrivacy': 'Uygulama Gizliliği',
'cf.playContentRating': 'Play içerik derecelendirmesi',
'cf.playTargetAudience': 'Play hedef kitle ve içerik',
'cf.dryFailed': '{form} hazırlanamadı',
'cf.panelTitle': 'Konsolda doldur: {form}',
'cf.disclaimer': 'Konsol sayfaları değişebilir. Bu, yapay zekâ destekli bir yardımdır: tarayıcıda her alanı kontrol edin ve Kaydet\'e kendiniz basın. storebound hiçbir zaman kaydetmez, göndermez veya yayınlamaz.',
'cf.notOpened': 'İletişim kutusunda Vazgeç\'i seçtiniz: tarayıcı açılmadı.',
'cf.runningText': 'Tarayıcı açık. Orada kendiniz oturum açın; storebound alanları doldurur ve yanıtı size kalanları işaretler. Her alanı kontrol edin, Kaydet\'e kendiniz basın ve ardından tarayıcıyı kapatın.',
'cf.doneText': 'Tarayıcı kapandı. Doldurulan: {filled}, sizin için işaretlenen: {highlighted}. Yanıtlarınızın kaydedildiğini konsolda kontrol edin.',
'cf.closed': 'Tarayıcı kapandı.',
'cf.cancelled': 'Durduruldu: tarayıcı kapatıldı.',
'cf.failed': 'Tarayıcı çalışması durdu',
'cf.fallback': 'Sayfa beklendiği gibi görünmedi, bu yüzden storebound yalnızca alanları işaretledi. Yanıtları kendiniz girin.',
'cf.answers': 'Yapılandırmanızdan {count} yanıt',
'cf.answers_one': 'Yapılandırmanızdan 1 yanıt',
'cf.uncertain': '{count} tanesi sizde',
'cf.noAnswers': 'Yapılandırmada bu form için yanıt yok: tüm alanlar size kalıyor.',
'cf.youAnswer': 'Bunu siz yanıtlayın',
'cf.foot': 'Tarayıcı açılmadan önce bir sistem iletişim kutusu bir kez daha sorar.',
'cf.cancelRun': 'Vazgeç: tarayıcıyı kapat',
'cf.open': 'Tarayıcıyı aç',
'cf.waiting': 'Tarayıcıyı kapatmanız bekleniyor',
'cf.playTitle': 'Play Console anketleri',
'cf.playSub': 'API yok: storebound bunları konsolda doldurur, siz kaydedersiniz',
'cf.playContentRatingText': 'Uygulamanın yaş derecelendirmelerini belirleyen IARC anketi.',
'cf.playTargetAudienceText': 'Hedef yaş grupları ve uygulamanın çocuklara hitap edip etmediği.',
'cf.noRecordTitle': 'Henüz App Store uygulama kaydı yok',
'cf.noRecordText': 'App Store Connect\'te uygulama kaydı oluşturmak için bir API yok. storebound Yeni Uygulama formunu yapılandırmanızdan doldurur; Oluştur\'a kendiniz basar, ardından Apple kimliğini apple.appId alanına yazarsınız.',
}; };

View file

@ -2,6 +2,8 @@
// question only the owner can answer at the top. Google Play Data safety (upload: dry run, native dialog, real run; // question only the owner can answer at the top. Google Play Data safety (upload: dry run, native dialog, real run;
// Play cannot read the form back, so the tab compares with the CSV storebound uploaded last), App Store App Privacy // Play cannot read the form back, so the tab compares with the CSV storebound uploaded last), App Store App Privacy
// (no API: the answers to enter in App Store Connect), app info, export compliance and the App Review details. // (no API: the answers to enter in App Store Connect), app info, export compliance and the App Review details.
// The forms without an API (App Privacy, age rating, the Play questionnaires, a missing App Store app record) have a
// "Fill in console" button (ui/ConsoleFill.tsx): storebound fills them in a visible browser, the owner saves.
import { useState } from 'react'; import { useState } from 'react';
import { api, type DeclarationsResult, type DeclAsk, type Project } from '../../api'; import { api, type DeclarationsResult, type DeclAsk, type Project } from '../../api';
import { type Key, t } from '../../i18n'; import { type Key, t } from '../../i18n';
@ -10,6 +12,7 @@ import { ago, num } from '../../lib/format';
import { useData, useRead, useWrite } from '../../store'; import { useData, useRead, useWrite } from '../../store';
import { useExports, useRunExport } from '../../ui/Exports'; import { useExports, useRunExport } from '../../ui/Exports';
import { Icon, StoreGlyph } from '../../ui/icons'; import { Icon, StoreGlyph } from '../../ui/icons';
import { ConsoleFillButton } from '../../ui/ConsoleFill';
import { Bar, Card, Chip, Empty, ErrorNotice, Notice, Skeleton } from '../../ui/kit'; import { Bar, Card, Chip, Empty, ErrorNotice, Notice, Skeleton } from '../../ui/kit';
import { WriteButton } from '../../ui/WriteButton'; import { WriteButton } from '../../ui/WriteButton';
import { ascUrl } from '../AppView'; import { ascUrl } from '../AppView';
@ -93,12 +96,15 @@ function DataSafety({ project, d, onDone }: { project: Project; d: DeclarationsR
); );
} }
function AppPrivacy({ d, appId }: { d: DeclarationsResult; appId: string | null | undefined }) { function AppPrivacy({ project, d, appId }: { project: Project; d: DeclarationsResult; appId: string | null | undefined }) {
const ap = d.appPrivacy; const ap = d.appPrivacy;
if (!ap) return null; if (!ap) return null;
return ( return (
<Card title={t('ai.apTitle')} icon="lock" sub={<span className="row" style={{ gap: 6 }}><StoreGlyph store="ios" className="ic13" />{t('ai.apSub')}</span>} pad={false} <Card title={t('ai.apTitle')} icon="lock" sub={<span className="row" style={{ gap: 6 }}><StoreGlyph store="ios" className="ic13" />{t('ai.apSub')}</span>} pad={false}
actions={<button className="btn btn-sm" onClick={() => api.openExternal(ascUrl(appId).replace(/\/distribution$/, '/distribution/privacy')).catch(() => {})}><Icon name="external" />{t('ai.apOpen')}</button>}> actions={<>
<button className="btn btn-sm" onClick={() => api.openExternal(ascUrl(appId).replace(/\/distribution$/, '/distribution/privacy')).catch(() => {})}><Icon name="external" />{t('ai.apOpen')}</button>
<ConsoleFillButton project={project} form="apple-app-privacy" />
</>}>
<div className="card-body"><Notice tone="info" icon="info">{t('ai.apNote')}</Notice></div> <div className="card-body"><Notice tone="info" icon="info">{t('ai.apNote')}</Notice></div>
{!ap.items.length ? <Empty compact illo="shield" title={ap.fromDataSafety ? t('ai.apNoneTitle') : t('ai.apUnknownTitle')}>{ap.fromDataSafety ? t('ai.apNoneText') : t('ai.apUnknownText')}</Empty> : ( {!ap.items.length ? <Empty compact illo="shield" title={ap.fromDataSafety ? t('ai.apNoneTitle') : t('ai.apUnknownTitle')}>{ap.fromDataSafety ? t('ai.apNoneText') : t('ai.apUnknownText')}</Empty> : (
<table className="table"> <table className="table">
@ -138,14 +144,22 @@ export function AppInfoTab({ project }: { project: Project }) {
return ( return (
<> <>
<AskCard ask={d.ask} /> <AskCard ask={d.ask} />
{d.stores.apple && e?.app?.platforms.ios && !e.app.platforms.ios.ascAppId && (
<Notice tone="warn" icon="alert" action={<ConsoleFillButton project={project} form="apple-app-record" primary />}>
<div className="stack" style={{ gap: 2 }}><b>{t('cf.noRecordTitle')}</b><span className="small">{t('cf.noRecordText')}</span></div>
</Notice>
)}
<div className="grid g2" style={{ alignItems: 'start' }}> <div className="grid g2" style={{ alignItems: 'start' }}>
{d.stores.play ? <DataSafety project={project} d={d} onDone={r.refresh} /> : <Card title={t('ai.dsTitle')} icon="shield" pad={false}><Empty compact illo="shield" title={t('ai.noPlay')}>{t('ai.noPlayText')}</Empty></Card>} {d.stores.play ? <DataSafety project={project} d={d} onDone={r.refresh} /> : <Card title={t('ai.dsTitle')} icon="shield" pad={false}><Empty compact illo="shield" title={t('ai.noPlay')}>{t('ai.noPlayText')}</Empty></Card>}
{d.stores.apple ? <AppPrivacy d={d} appId={e?.app?.platforms.ios?.ascAppId} /> : <Card title={t('ai.apTitle')} icon="lock" pad={false}><Empty compact illo="shield" title={t('ai.noApple')}>{t('ai.noAppleText')}</Empty></Card>} {d.stores.apple ? <AppPrivacy project={project} d={d} appId={e?.app?.platforms.ios?.ascAppId} /> : <Card title={t('ai.apTitle')} icon="lock" pad={false}><Empty compact illo="shield" title={t('ai.noApple')}>{t('ai.noAppleText')}</Empty></Card>}
</div> </div>
{d.stores.apple && ( {d.stores.apple && (
<div className="grid g3" style={{ alignItems: 'start' }}> <div className="grid g3" style={{ alignItems: 'start' }}>
<Card title={t('ai.infoTitle')} icon="clipboard" sub={t('ai.infoSub')} <Card title={t('ai.infoTitle')} icon="clipboard" sub={t('ai.infoSub')}
actions={<WriteButton run={w} icon="upload" w={{ method: 'apple.appinfo', args: {}, title: t('ai.infoPush'), done: t('ai.pushed') }}>{t('ai.push')}</WriteButton>}> actions={<>
<WriteButton run={w} icon="upload" w={{ method: 'apple.appinfo', args: {}, title: t('ai.infoPush'), done: t('ai.pushed') }}>{t('ai.push')}</WriteButton>
<ConsoleFillButton project={project} form="apple-age-rating" />
</>}>
<dl className="kv"> <dl className="kv">
<dt>{t('ai.category')}</dt><dd>{cat ?? <Chip tone="warn" icon="question">{t('ai.notSet')}</Chip>}</dd> <dt>{t('ai.category')}</dt><dd>{cat ?? <Chip tone="warn" icon="question">{t('ai.notSet')}</Chip>}</dd>
<dt>{t('ai.age')}</dt><dd>{info!.ageRating.length ? <span className="small">{info!.ageRating.map(a => `${a.question} = ${a.value}`).join(', ')}</span> : <Chip tone="warn" icon="question">{t('ai.ageAllNone')}</Chip>}</dd> <dt>{t('ai.age')}</dt><dd>{info!.ageRating.length ? <span className="small">{info!.ageRating.map(a => `${a.question} = ${a.value}`).join(', ')}</span> : <Chip tone="warn" icon="question">{t('ai.ageAllNone')}</Chip>}</dd>
@ -178,6 +192,19 @@ export function AppInfoTab({ project }: { project: Project }) {
</Card> </Card>
</div> </div>
)} )}
{d.stores.play && (
<Card title={t('cf.playTitle')} icon="clipboard" sub={<span className="row" style={{ gap: 6 }}><StoreGlyph store="android" className="ic13" />{t('cf.playSub')}</span>} pad={false}>
<div className="list">
{([['play-content-rating', 'cf.playContentRating', 'cf.playContentRatingText'], ['play-target-audience', 'cf.playTargetAudience', 'cf.playTargetAudienceText']] as const).map(([form, title, text]) => (
<div className="li" key={form}>
<span className="li-icon tone-bg-info"><Icon name="clipboard" /></span>
<div className="li-main"><span className="li-title">{t(title)}</span><span className="li-sub">{t(text)}</span></div>
<ConsoleFillButton project={project} form={form} />
</div>
))}
</div>
</Card>
)}
<p className="small muted">{t('ai.foot', { when: ago(r.at) })}</p> <p className="small muted">{t('ai.foot', { when: ago(r.at) })}</p>
</> </>
); );

View file

@ -878,6 +878,13 @@ textarea.input { height: auto; padding: 8px 10px; line-height: 1.45; resize: ver
.lb-img .stack { width: 320px; } .lb-img .stack { width: 320px; }
.lb-foot { display: flex; align-items: center; gap: 8px; padding: 12px 16px; border-top: 1px solid var(--line); } .lb-foot { display: flex; align-items: center; gap: 8px; padding: 12px 16px; border-top: 1px solid var(--line); }
.lb-foot .grow { flex: 1; min-width: 0; display: grid; gap: 2px; } .lb-foot .grow { flex: 1; min-width: 0; display: grid; gap: 2px; }
/* "Fill in console" panel (ui/ConsoleFill.tsx): the answers of the dry run, then the run's progress */
.cf-panel { width: min(680px, 100%); }
.cf-body { min-height: 0; overflow: auto; padding: 20px 22px; gap: 14px; }
.cf-body h2 { font-size: var(--t-section); font-weight: 660; }
.cf-table td:first-child { padding-left: 0; }
.cf-table td:last-child { padding-right: 0; text-align: right; }
.cf-guidance { font-size: var(--t-meta); }
/* growth chart */ /* growth chart */
.lchart { display: grid; gap: 8px; } .lchart { display: grid; gap: 8px; }

View file

@ -0,0 +1,130 @@
// "Fill in console": the store forms without an API (App Store app record, age rating, App Privacy; Play content
// rating, target audience). Click -> dry run of `console.fill` (the answers from the config, nothing opens) -> this
// panel lists them, the uncertain ones marked for the owner, with the disclaimer -> "Open the browser" goes through
// write_with_confirm (the host shows the answers again in a native dialog and mints the token only on its button) ->
// a visible browser the owner signs in to; storebound fills the fields and never saves, submits or publishes. The run
// lasts until the owner closes that browser; Cancel here stops the command, which closes it.
import { type KeyboardEvent, useEffect, useRef, useState } from 'react';
import { api, type ConsoleFillResult, type ConsoleForm, errorText, newJob, onProgress, type Project, type ToolResult } from '../api';
import { type Key, t } from '../i18n';
import { useData } from '../store';
import { Icon, StoreGlyph } from './icons';
import { Chip, Notice } from './kit';
export const CONSOLE_FORM_NAME: Record<ConsoleForm, Key> = {
'apple-app-record': 'cf.appleAppRecord', 'apple-age-rating': 'cf.appleAgeRating', 'apple-app-privacy': 'cf.appleAppPrivacy',
'play-content-rating': 'cf.playContentRating', 'play-target-audience': 'cf.playTargetAudience',
};
type Stage =
| { s: 'idle' }
| { s: 'dry' }
| { s: 'review'; data: ConsoleFillResult; note?: string }
| { s: 'running'; data: ConsoleFillResult; job: string; lines: string[] }
| { s: 'done'; data: ConsoleFillResult; result: ConsoleFillResult | null; ok: boolean; detail?: string };
const tail = (out: string): string => out.trim().split('\n').filter(Boolean).at(-1)?.replace(/^error:\s*/, '') ?? '';
export function ConsoleFillButton({ project, form, small = true, primary }: { project: Project; form: ConsoleForm; small?: boolean; primary?: boolean }) {
const d = useData();
const [st, setSt] = useState<Stage>({ s: 'idle' });
const name = t(CONSOLE_FORM_NAME[form]);
const start = async () => {
setSt({ s: 'dry' });
try {
const r = await api.call<ToolResult & { data?: ConsoleFillResult }>('console.fill', project.id, { args: { form } }, newJob('console.fill-dry'));
if (!r.ok || !r.data) { setSt({ s: 'idle' }); d.toast({ kind: 'bad', title: t('cf.dryFailed', { form: name }), detail: tail(r.output) || undefined }); return; }
setSt({ s: 'review', data: r.data });
} catch (e) {
setSt({ s: 'idle' });
d.toast({ kind: 'bad', title: t('cf.dryFailed', { form: name }), detail: errorText(e) });
}
};
const open = async (data: ConsoleFillResult) => {
const job = newJob('console.fill');
setSt({ s: 'running', data, job, lines: [] });
const un = onProgress(p => {
if (p.job !== job || !p.line?.trim()) return;
setSt(x => (x.s === 'running' && x.job === job ? { ...x, lines: [...x.lines, p.line!].slice(-12) } : x));
});
try {
const o = await api.writeWithConfirm('console.fill', project.id, { form }, job);
if (o.stage === 'dialog') setSt({ s: 'review', data, note: t('cf.notOpened') });
else if (o.stage === 'dry-run') setSt({ s: 'done', data, result: null, ok: false, detail: tail(o.dryRun.output) });
else {
const res = (o.result?.data ?? null) as ConsoleFillResult | null;
setSt({ s: 'done', data, result: res, ok: !!o.result?.ok, detail: o.result?.ok ? undefined : tail(o.result?.output ?? '') });
}
} catch (e) {
const msg = errorText(e);
setSt({ s: 'done', data, result: null, ok: /cancel/i.test(msg), detail: /cancel/i.test(msg) ? t('cf.cancelled') : msg });
} finally { un.then(f => f()); }
};
const busy = st.s === 'dry';
return (
<>
<button className={`btn${small ? ' btn-sm' : ''}${primary ? ' btn-primary' : ''}`} disabled={busy || st.s === 'running'} aria-busy={busy || undefined}
title={t('cf.hint', { form: name })} onClick={() => { start(); }}>
<Icon name={busy ? 'refresh' : 'wand'} className={busy ? 'spin' : undefined} />{t('cf.button')}
</button>
{(st.s === 'review' || st.s === 'running' || st.s === 'done') && (
<FillPanel st={st} name={name} onOpen={() => { open(st.data); }} onCancel={() => { if (st.s === 'running') api.cancel(st.job).catch(() => {}); }} onClose={() => setSt({ s: 'idle' })} />
)}
</>
);
}
function FillPanel({ st, name, onOpen, onCancel, onClose }: {
st: Extract<Stage, { s: 'review' | 'running' | 'done' }>; name: string; onOpen: () => void; onCancel: () => void; onClose: () => void;
}) {
const root = useRef<HTMLDivElement>(null);
useEffect(() => { root.current?.focus(); }, []);
const running = st.s === 'running';
const data = st.data;
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape' && !running) { e.preventDefault(); onClose(); } };
return (
<div className="scrim lightbox" onMouseDown={e => { if (e.target === e.currentTarget && !running) onClose(); }}>
<div className="lb cf-panel" role="dialog" aria-modal="true" aria-labelledby="cf-title" tabIndex={-1} ref={root} onKeyDown={onKey}>
<div className="cf-body stack">
<div className="stack" style={{ gap: 4 }}>
<h2 id="cf-title" className="row" style={{ gap: 8 }}><Icon name="wand" />{t('cf.panelTitle', { form: data.title || name })}</h2>
<span className="small muted row" style={{ gap: 6 }}><StoreGlyph store={data.store === 'apple' ? 'ios' : 'android'} className="ic13" />{data.store === 'apple' ? 'App Store Connect' : 'Google Play Console'}</span>
</div>
<Notice tone="warn" icon="alert">{t('cf.disclaimer')}</Notice>
{st.s === 'review' && st.note && <Notice tone="info">{st.note}</Notice>}
{running && <Notice tone="info" icon="globe">{t('cf.runningText')}</Notice>}
{st.s === 'done' && (st.ok
? <Notice tone="ok">{st.result ? t('cf.doneText', { filled: st.result.filled ?? 0, highlighted: st.result.highlighted ?? 0 }) : st.detail ?? t('cf.closed')}</Notice>
: <Notice tone="bad">{t('cf.failed')}{st.detail ? `: ${st.detail}` : ''}</Notice>)}
{st.s === 'done' && st.result?.fallback ? <Notice tone="warn">{t('cf.fallback')}</Notice> : null}
<div className="stack" style={{ gap: 6 }}>
<div className="row between small"><b>{t('cf.answers', { count: data.answers.length })}</b>{data.uncertain > 0 && <Chip tone="warn" icon="question">{t('cf.uncertain', { count: data.uncertain })}</Chip>}</div>
{!data.answers.length ? <span className="small muted">{t('cf.noAnswers')}</span> : (
<table className="table cf-table">
<tbody>
{data.answers.map(a => (
<tr key={a.id}>
<td><div className="strong">{a.label}</div>{(a.note || a.source) && <div className="small muted">{a.note ?? a.source}</div>}</td>
<td>{a.certain ? <span>{a.value}</span> : <Chip tone="warn" icon="question">{t('cf.youAnswer')}</Chip>}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
{data.guidance.length > 0 && <ul className="note-list cf-guidance">{data.guidance.map((g, i) => <li key={i}>{g}</li>)}</ul>}
{running && st.lines.length > 0 && <pre className="log" aria-live="polite">{st.lines.join('\n')}</pre>}
</div>
<div className="lb-foot">
<div className="grow small muted">{st.s === 'review' ? t('cf.foot') : null}</div>
{running ? <button className="btn btn-sm btn-danger" onClick={onCancel}><Icon name="x" />{t('cf.cancelRun')}</button> : <button className="btn btn-sm btn-ghost" onClick={onClose}>{st.s === 'done' ? t('common.close') : t('common.cancel')}</button>}
{st.s === 'review' && <button className="btn btn-sm btn-primary" onClick={onOpen}><Icon name="external" />{t('cf.open')}</button>}
{running && <span className="small muted row" style={{ gap: 6 }}><Icon name="refresh" className="spin ic13" />{t('cf.waiting')}</span>}
</div>
</div>
</div>
);
}

202
cli/ads/apple.ts Normal file
View file

@ -0,0 +1,202 @@
// Apple Ads (formerly Apple Search Ads) for the app's App Store campaigns.
// storebound ads apple status [--json] token works?, ad accounts and roles (GET /v1/acls), the one used
// storebound ads apple campaigns [--all] [--json] App Store campaigns: status, daily budget, countries, adamId
// storebound ads apple report [--days 7 | --start YYYY-MM-DD --end YYYY-MM-DD] [--by campaign|keyword] [--campaign <id>]
// [--adgroup <id>] [--all] [--csv <file>] [--dry] [--json]
// spend, impressions, taps, installs, TTR, conversion rate, CPA (spend / installs), avg CPT; totals. Read-only.
// storebound ads apple bid --keyword <id> --bid <amount> [--campaign <id>] [--adgroup <id>] [--dry] [--yes]
// storebound ads apple budget --campaign <id> --daily <amount> [--dry] [--yes]
// storebound ads apple pause --campaign <id> [--adgroup <id>] [--dry] [--yes]
// Writes read the current value first, print "old -> new", and only without --dry ask in the terminal (confirm) before
// the PUT. They are the owner's decisions (money): never offered over MCP, refused under `storebound serve`.
// Report and campaign lists default to the campaigns of config apple.appId (when set); --all shows every app's.
// Credentials and API: cli/ads/client.ts. API: Apple Ads Platform API (https://api.ads.apple.com/v1), which replaces
// the Campaign Management API v5 (sunset January 26, 2027).
// Sources (checked October 2026): the doc URLs in cli/lib/apple-ads.ts, plus
// https://developer.apple.com/documentation/apple-ads-platform-api/post-campaigns-query (pageSize cap 1000)
// https://developer.apple.com/documentation/apple-ads-platform-api/put-campaigns-_id_ (status / dailyBudget examples)
// https://developer.apple.com/documentation/apple-ads-platform-api/put-keywords-_id_ (bid example; bid null is an error)
// https://developer.apple.com/documentation/apple-ads-platform-api/put-adgroups-_id_ (status)
import { writeFileSync } from 'node:fs';
import { type AclRow, aclRows, campaignQuery, campaignRow, type CampaignRow, canWrite, changeLine, dailyBudgetBody, flattenRows, type J, keywordBidBody,
nextOffset, parseAmount, pauseBody, reportBody, reportCsv, type ReportRow, reportTable, reportWindow, totals } from '../lib/apple-ads';
import { confirm, type Ctx } from '../lib/ctx';
import { done, log, printJson, warn } from '../lib/log';
import { textTable } from '../lib/table';
import { adsClient, type Ads } from './client';
const TAG = 'ads apple';
const SUBS = ['status', 'campaigns', 'report', 'bid', 'budget', 'pause'];
const idArg = (ctx: Ctx, name: string, required: boolean): string | undefined => {
const v = ctx.args.get(name);
if (v === undefined || v === 'true') { if (required) throw new Error(`--${name} <id> is required`); return undefined; }
if (!/^\d+$/.test(v)) throw new Error(`--${name}: a numeric id`);
return v;
};
async function allCampaigns(ads: Ads): Promise<J[]> {
const out: J[] = [];
for (let offset: number | null = 0; offset !== null;) {
const page: J = await ads.post('/campaigns/query', campaignQuery(offset));
out.push(...(page.result ?? []));
offset = (page.result ?? []).length ? nextOffset(page) : null;
}
return out;
}
/** The campaigns a report / list covers: one by id, else the app's (config apple.appId) unless --all or none match. */
async function pickCampaigns(ctx: Ctx, ads: Ads, quiet: boolean): Promise<J[]> {
const id = idArg(ctx, 'campaign', false);
if (id) return [(await ads.get(`/campaigns/${id}`)).result];
const all = await allCampaigns(ads);
const appId = ctx.loaded.config.apple?.appId;
if (!appId || ctx.args.has('all')) return all;
const mine = all.filter(c => String(c.promotedObjectId) === String(appId));
if (!mine.length && all.length && !quiet) warn(TAG, `no campaign promotes apple.appId ${appId}: showing all ${all.length}`);
return mine.length ? mine : all;
}
async function status(ctx: Ctx, ads: Ads, json: boolean): Promise<void> {
await ads.token();
const accounts: AclRow[] = aclRows(await ads.get('/acls', false), ads.accountId);
const used = accounts.find(a => a.used) ?? null;
const account = ads.accountId ? (await ads.get(`/ad-accounts/${ads.accountId}`)).result ?? null : null;
const out = {
token: true, accountId: ads.accountId ?? null, accounts,
account: account && { id: String(account.id), name: account.name, currency: account.currency, timezone: account.timezone, systemStatus: account.systemStatus,
systemStatusReasons: account.systemStatusReasons ?? [], productFeatures: account.productFeatures ?? [] },
canWrite: used ? canWrite(used.roles) : false,
};
if (json) return printJson(out);
log(TAG, 'token: ok (OAuth client credentials)');
if (!accounts.length) warn(TAG, 'no ad accounts for this API user (Apple Ads > Account Settings > User Management: give it an API role on an account)');
else console.log(textTable(['', 'ad account', 'id', 'org', 'roles'], accounts.map(a => [a.used ? '*' : '', a.name, a.accountId, a.orgId, a.roles.join(', ')])));
if (!ads.accountId) { log(TAG, 'APPLE_ADS_ACCOUNT_ID is not set: put one of the ids above in the env or .storebound/credentials.json'); return; }
if (!used) warn(TAG, `APPLE_ADS_ACCOUNT_ID ${ads.accountId} is not in the list above: this API user has no role on it`);
if (out.account) {
const a = out.account;
log(TAG, `using ${a.name} (${a.id}): ${a.currency}, ${a.timezone}, ${a.systemStatus}${a.systemStatusReasons.length ? ' ' + a.systemStatusReasons.join(', ') : ''}, ${a.productFeatures.join(', ') || 'no product features'}`);
if (!a.productFeatures.includes('APPSTORE_APP_MANUAL')) warn(TAG, 'this ad account is not an App Store account (APPSTORE_APP_MANUAL)');
}
log(TAG, out.canWrite ? 'role allows bid / budget / pause changes (each one still asks first)' : 'read-only role: reports and lists only');
}
async function campaigns(ctx: Ctx, ads: Ads, json: boolean): Promise<void> {
const appId = ctx.loaded.config.apple?.appId;
const rows: CampaignRow[] = (await pickCampaigns(ctx, ads, json)).map(c => campaignRow(c, appId));
if (json) return printJson({ accountId: ads.accountId, appId: appId ?? null, campaigns: rows });
if (!rows.length) return log(TAG, 'no App Store campaigns in this ad account');
console.log(textTable(['', 'id', 'campaign', 'status', 'display', 'daily budget', 'bidding', 'countries', 'adamId'],
rows.map(r => [r.thisApp ? '*' : '', r.id, r.name, r.status, r.displayStatus, r.dailyBudget ? `${r.dailyBudget} ${r.currency}` : '', r.bidStrategy, r.countries.join(' '), r.adamId])));
if (appId) log(TAG, `* = promotes apple.appId ${appId}`);
}
async function report(ctx: Ctx, ads: Ads, json: boolean): Promise<void> {
const by = ctx.args.str('by', 'campaign');
if (by !== 'campaign' && by !== 'keyword') throw new Error('--by campaign | keyword');
const w = reportWindow({ days: ctx.args.has('days') ? ctx.args.num('days', 7) : undefined, start: ctx.args.get('start'), end: ctx.args.get('end') });
const adGroupId = idArg(ctx, 'adgroup', false);
const camps = await pickCampaigns(ctx, ads, json);
const names = new Map(camps.map(c => [String(c.id), String(c.name ?? '')] as const));
const rows: ReportRow[] = [];
for (const c of camps) {
for (let offset: number | null = 0; offset !== null;) {
const res: J = await ads.post(`/reports/apps/${by === 'campaign' ? 'campaigns' : 'keywords'}/query`, reportBody({ ...w, campaignId: String(c.id), adGroupId: by === 'keyword' ? adGroupId : undefined, offset }));
const got = flattenRows(by, res, names);
rows.push(...got);
offset = got.length ? nextOffset(res) : null;
}
}
rows.sort((a, b) => b.spend - a.spend);
const t = totals(rows);
const csv = ctx.args.get('csv');
if (csv === 'true') throw new Error('--csv <file>');
if (csv) {
const path = ctx.loaded.resolve(csv);
if (ctx.args.has('dry')) { if (!json) log(TAG, `dry run: would write ${rows.length} row(s) to ${path}`); }
else { writeFileSync(path, reportCsv(rows)); if (!json) log(TAG, `wrote ${rows.length} row(s) to ${path}`); }
}
if (json) return printJson({ accountId: ads.accountId, by, start: w.start, end: w.end, timeZone: 'UTC', campaigns: camps.length, rows, totals: t });
log(TAG, `${by} report ${w.start} .. ${w.end} (UTC), ${camps.length} campaign(s), ${rows.length} row(s) with activity`);
if (!rows.length) return log(TAG, 'no spend, impressions or taps in this window');
console.log(reportTable(rows, t));
if (t.installs === 0 && t.spend > 0) log(TAG, 'CPA n/a: no installs in this window');
}
interface Plan { action: 'bid' | 'budget' | 'pause'; target: string; path: string; body: J; old: string | null; new: string; currency: string; applied: boolean }
async function apply(ctx: Ctx, ads: Ads, json: boolean, p: Plan, unchanged: boolean): Promise<void> {
const say = (m: string) => { if (!json) log(TAG, m); };
say(`${p.action}: ${p.target}: ${p.action === 'pause' ? `${p.old} -> ${p.new}` : changeLine(p.old, p.new, p.currency)}`);
if (unchanged) { say('already at that value: nothing to change'); return json ? printJson(p) : undefined; }
if (ctx.args.has('dry')) { say(`dry run: would PUT ${p.path} ${JSON.stringify(p.body)}`); return json ? printJson(p) : undefined; }
if (!(await confirm(ctx, `Apply this ${p.action} change in Apple Ads (${p.target})?`))) { say('not changed'); return json ? printJson(p) : undefined; }
await ads.put(p.path, p.body);
p.applied = true;
if (json) return printJson(p);
done(TAG, `${p.action} applied`);
}
async function bid(ctx: Ctx, ads: Ads, json: boolean): Promise<void> {
const kid = idArg(ctx, 'keyword', true)!;
const amount = parseAmount(ctx.args.get('bid'), '--bid');
const kw = (await ads.get(`/keywords/${kid}`)).result;
if (!kw || kw.deleted) throw new Error(`keyword ${kid} not found or deleted`);
const camp = idArg(ctx, 'campaign', false), group = idArg(ctx, 'adgroup', false);
if (camp && String(kw.campaignId) !== camp) throw new Error(`keyword ${kid} belongs to campaign ${kw.campaignId}, not ${camp}`);
if (group && String(kw.adGroupId) !== group) throw new Error(`keyword ${kid} belongs to ad group ${kw.adGroupId}, not ${group}`);
const c = (await ads.get(`/campaigns/${kw.campaignId}`)).result;
if (c?.bidStrategy?.bidStrategyType === 'MAX_CONVERSIONS') throw new Error(`campaign ${kw.campaignId} uses Maximize Conversions: keyword bids are not used there`);
const currency = String(kw.bid?.currency ?? c?.dailyBudget?.value?.currency ?? '');
if (!currency) throw new Error('could not tell the account currency from the keyword or its campaign');
const old = kw.bid?.amount != null ? String(kw.bid.amount) : null;
await apply(ctx, ads, json, { action: 'bid', target: `keyword "${kw.text}" (${kw.matchType}, ${kid}) in "${c?.name ?? kw.campaignId}"`, path: `/keywords/${kid}`,
body: keywordBidBody(amount, currency), old, new: amount, currency, applied: false }, old !== null && Number(old) === Number(amount));
}
async function budget(ctx: Ctx, ads: Ads, json: boolean): Promise<void> {
const id = idArg(ctx, 'campaign', true)!;
const amount = parseAmount(ctx.args.get('daily'), '--daily');
const c = (await ads.get(`/campaigns/${id}`)).result;
if (!c || c.deleted) throw new Error(`campaign ${id} not found or deleted`);
const currency = String(c.dailyBudget?.value?.currency ?? '');
if (!currency) throw new Error(`campaign ${id} has no daily budget currency`);
const old = c.dailyBudget?.value?.amount != null ? String(c.dailyBudget.value.amount) : null;
await apply(ctx, ads, json, { action: 'budget', target: `daily budget of "${c.name}" (${id})`, path: `/campaigns/${id}`, body: dailyBudgetBody(amount, currency),
old, new: amount, currency, applied: false }, old !== null && Number(old) === Number(amount));
}
async function pause(ctx: Ctx, ads: Ads, json: boolean): Promise<void> {
const id = idArg(ctx, 'campaign', true)!;
const group = idArg(ctx, 'adgroup', false);
const c = (await ads.get(`/campaigns/${id}`)).result;
if (!c || c.deleted) throw new Error(`campaign ${id} not found or deleted`);
let target = `campaign "${c.name}" (${id})`, path = `/campaigns/${id}`, old = String(c.status ?? '');
if (group) {
const g = (await ads.get(`/adgroups/${group}`)).result;
if (!g || g.deleted) throw new Error(`ad group ${group} not found or deleted`);
if (String(g.campaignId) !== id) throw new Error(`ad group ${group} belongs to campaign ${g.campaignId}, not ${id}`);
target = `ad group "${g.name}" (${group}) in "${c.name}"`; path = `/adgroups/${group}`; old = String(g.status ?? '');
}
await apply(ctx, ads, json, { action: 'pause', target, path, body: pauseBody(), old, new: 'PAUSED', currency: '', applied: false }, old === 'PAUSED');
}
export async function run(ctx: Ctx): Promise<void> {
const sub = ctx.args._[0];
const json = ctx.args.has('json');
if (!sub || ctx.args.has('help') || !SUBS.includes(sub)) {
console.log(`usage: storebound ads apple ${SUBS.join(' | ')} (see the apple-ads skill)`);
if (sub && !SUBS.includes(sub) && !ctx.args.has('help')) process.exitCode = 2;
return;
}
const ads = adsClient(ctx.loaded.root);
switch (sub) {
case 'status': return status(ctx, ads, json);
case 'campaigns': return campaigns(ctx, ads, json);
case 'report': return report(ctx, ads, json);
case 'bid': return bid(ctx, ads, json);
case 'budget': return budget(ctx, ads, json);
case 'pause': return pause(ctx, ads, json);
}
}

71
cli/ads/client.ts Normal file
View file

@ -0,0 +1,71 @@
// Apple Ads Platform API client: OAuth client credentials (an ES256 client secret signed with the key uploaded in
// Apple Ads > Account Settings > API), Bearer calls with X-AP-Context: adAccountId=<id>, retries on 429 / 5xx.
// The access token lives in memory for this process only (never written to disk, never printed).
// Credentials (env, else .storebound/credentials.json): APPLE_ADS_CLIENT_ID, APPLE_ADS_TEAM_ID, APPLE_ADS_KEY_ID,
// APPLE_ADS_PRIVATE_KEY (path to the PEM, or the PEM itself), APPLE_ADS_ACCOUNT_ID (optional for `status`).
// Sources (checked October 2026): see cli/lib/apple-ads.ts; retries per
// https://developer.apple.com/documentation/apple-ads-platform-api/rate-limits (Retry-After on 429).
import { createPrivateKey, type KeyObject } from 'node:crypto';
import { credentialValue, inline } from '../lib/credentials';
import { ADS_API, adsHeaders, type AdsCreds, clientSecret, type J, TOKEN_URL, tokenForm } from '../lib/apple-ads';
import { errorBody } from '../lib/http';
export const CRED_NAMES = ['APPLE_ADS_CLIENT_ID', 'APPLE_ADS_TEAM_ID', 'APPLE_ADS_KEY_ID', 'APPLE_ADS_PRIVATE_KEY'] as const;
export function adsCreds(root: string): AdsCreds {
// the template's placeholders (templates/credentials.example.json, copied by `storebound init`) count as not set
const v = (n: string) => { const x = credentialValue(root, n); return x && !/00000000-0000-0000|\/absolute\/path\/to\//.test(x) ? x : undefined; };
const missing = CRED_NAMES.filter(n => !v(n));
if (missing.length) throw new Error(`${missing.join(', ')} not set (env, or .storebound/credentials.json); see the apple-ads skill`);
let pem: string;
try { pem = inline(v('APPLE_ADS_PRIVATE_KEY')!, /BEGIN (EC )?PRIVATE KEY/); } catch { throw new Error('APPLE_ADS_PRIVATE_KEY: the private key file could not be read (set a path to the PEM, or the PEM itself)'); }
return { clientId: v('APPLE_ADS_CLIENT_ID')!, teamId: v('APPLE_ADS_TEAM_ID')!, keyId: v('APPLE_ADS_KEY_ID')!, pem, accountId: v('APPLE_ADS_ACCOUNT_ID') };
}
/** Seconds to wait before retry `attempt` (1-based): Retry-After when the server sends it, else 2, 4, 8, 16. */
export const retryWait = (retryAfter: string | null, attempt: number): number => {
const s = Number(retryAfter);
return Number.isFinite(s) && s >= 0 && retryAfter !== null && retryAfter !== '' ? Math.min(s, 60) : Math.min(2 ** attempt, 16);
};
export type Ads = ReturnType<typeof adsClient>;
export function adsClient(root: string, o: { sleep?: (ms: number) => Promise<unknown> } = {}) {
const c = adsCreds(root);
let key: KeyObject;
try { key = createPrivateKey(c.pem); } catch { throw new Error('APPLE_ADS_PRIVATE_KEY is not a valid EC private key (PEM)'); }
const sleep = o.sleep ?? ((ms: number) => Bun.sleep(ms));
let cached = { token: '', until: 0 };
async function token(): Promise<string> {
if (cached.token && Date.now() < cached.until) return cached.token;
const r = await fetch(TOKEN_URL, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: tokenForm(c.clientId, clientSecret(c, key)).toString() });
const t = await r.text();
// the answer may echo the request; only the status and Apple's error code are shown
if (!r.ok) { let code = ''; try { code = String(JSON.parse(t).error ?? ''); } catch { /* not JSON */ } throw new Error(`Apple Ads token request -> ${r.status}${code ? ' ' + code : ''} (check APPLE_ADS_CLIENT_ID / TEAM_ID / KEY_ID and that the uploaded public key matches APPLE_ADS_PRIVATE_KEY)`); }
const j = JSON.parse(t) as { access_token?: string; expires_in?: number };
if (!j.access_token) throw new Error('Apple Ads token request: no access_token in the answer');
cached = { token: j.access_token, until: Date.now() + Math.max(60, (j.expires_in ?? 3600) - 120) * 1000 };
return cached.token;
}
async function call(method: string, path: string, body?: unknown, scoped = true): Promise<J> {
if (scoped && !c.accountId) throw new Error('APPLE_ADS_ACCOUNT_ID is not set: run `storebound ads apple status` to list your ad accounts');
for (let attempt = 1; ; attempt++) {
const r = await fetch(ADS_API + path, { method, headers: adsHeaders(await token(), scoped ? c.accountId : undefined), body: body === undefined ? undefined : JSON.stringify(body) });
const t = await r.text();
if ((r.status === 429 || r.status >= 500) && attempt < 5) { await sleep(retryWait(r.headers.get('Retry-After'), attempt) * 1000); continue; }
if (r.status === 401 && attempt === 1) { cached = { token: '', until: 0 }; continue; }
if (!r.ok) throw new Error(`${method} ${path} -> ${r.status} ${errorBody(t, 800)}`);
return t ? JSON.parse(t) : {};
}
}
return {
accountId: c.accountId,
token,
get: (path: string, scoped = true) => call('GET', path, undefined, scoped),
post: (path: string, body: unknown) => call('POST', path, body),
put: (path: string, body: unknown) => call('PUT', path, body),
};
}

View file

@ -112,11 +112,13 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'builds_updateInstance': 'apple/encryption lib/build-ops', 'builds_updateInstance': 'apple/encryption lib/build-ops',
'bundleIdCapabilities_createInstance': 'lib/signing', 'bundleIdCapabilities_createInstance': 'lib/signing',
'bundleIds_createInstance': 'apple/bundle', 'bundleIds_createInstance': 'apple/bundle',
'bundleIds_getCollection': 'apple/bundle apple/signing', 'bundleIds_getCollection': 'apple/adhoc apple/bundle apple/signing',
'bundleIds_profiles_getToManyRelated': 'apple/signing', 'bundleIds_profiles_getToManyRelated': 'apple/adhoc apple/signing',
'certificates_createInstance': 'apple/signing lib/signing', 'certificates_createInstance': 'apple/signing lib/signing',
'certificates_getCollection': 'apple/signing', 'certificates_getCollection': 'apple/adhoc apple/signing',
'customerReviewResponses_createInstance': 'lib/reviews', 'customerReviewResponses_createInstance': 'lib/reviews',
'devices_createInstance': 'apple/adhoc',
'devices_getCollection': 'apple/adhoc',
'endAppAvailabilityPreOrders_createInstance': 'lib/offers', 'endAppAvailabilityPreOrders_createInstance': 'lib/offers',
'financeReports_getCollection': 'lib/reports', 'financeReports_getCollection': 'lib/reports',
'inAppPurchaseAppStoreReviewScreenshots_createInstance': 'apple/iap-review', 'inAppPurchaseAppStoreReviewScreenshots_createInstance': 'apple/iap-review',
@ -142,10 +144,11 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'inAppPurchasesV2_inAppPurchaseAvailability_getToOneRelated': 'apple/iap', 'inAppPurchasesV2_inAppPurchaseAvailability_getToOneRelated': 'apple/iap',
'inAppPurchasesV2_inAppPurchaseLocalizations_getToManyRelated': 'apple/iap catalog', 'inAppPurchasesV2_inAppPurchaseLocalizations_getToManyRelated': 'apple/iap catalog',
'inAppPurchasesV2_offerCodes_getToManyRelated': 'apple/offer-codes', 'inAppPurchasesV2_offerCodes_getToManyRelated': 'apple/offer-codes',
'inAppPurchasesV2_pricePoints_getToManyRelated': 'apple/iap apple/offer-codes prices', 'inAppPurchasesV2_pricePoints_getToManyRelated': 'apple/iap apple/offer-codes prices prices-ppp',
'inAppPurchasesV2_versions_getToManyRelated': 'apple/iap-submit', 'inAppPurchasesV2_versions_getToManyRelated': 'apple/iap-submit',
'profiles_certificates_getToManyRelationship': 'apple/signing', 'profiles_certificates_getToManyRelationship': 'apple/signing',
'profiles_createInstance': 'lib/signing', 'profiles_createInstance': 'apple/adhoc lib/signing',
'profiles_devices_getToManyRelated': 'apple/adhoc',
'profiles_getInstance': 'apple/signing', 'profiles_getInstance': 'apple/signing',
'promotedPurchases_createInstance': 'lib/offers', 'promotedPurchases_createInstance': 'lib/offers',
'promotedPurchases_updateInstance': 'lib/offers', 'promotedPurchases_updateInstance': 'lib/offers',
@ -205,7 +208,8 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'androidpublisher.edits.tracks.list': 'play/next-version-code play/status validate', 'androidpublisher.edits.tracks.list': 'play/next-version-code play/status validate',
'androidpublisher.edits.tracks.update': 'play/release play/rollout play/upload', 'androidpublisher.edits.tracks.update': 'play/release play/rollout play/upload',
'androidpublisher.edits.validate': 'play/client', 'androidpublisher.edits.validate': 'play/client',
'androidpublisher.monetization.convertRegionPrices': 'play/products play/subscriptions prices', 'androidpublisher.generatedapks.list': 'web',
'androidpublisher.monetization.convertRegionPrices': 'play/products play/subscriptions prices prices-ppp',
'androidpublisher.monetization.onetimeproducts.get': 'prices', 'androidpublisher.monetization.onetimeproducts.get': 'prices',
'androidpublisher.monetization.onetimeproducts.list': 'play/products', 'androidpublisher.monetization.onetimeproducts.list': 'play/products',
'androidpublisher.monetization.onetimeproducts.patch': 'play/products prices', 'androidpublisher.monetization.onetimeproducts.patch': 'play/products prices',

200
cli/apple/adhoc.ts Normal file
View file

@ -0,0 +1,200 @@
// Ad-hoc / release-testing distribution: register test devices, an ad-hoc provisioning profile, ExportOptions.plist
// and the IPA export.
// storebound apple adhoc devices [--platform IOS|MAC_OS] [--json] registered devices, UDIDs masked
// storebound apple adhoc register [--csv .storebound/devices.csv] [--name n --udid u --platform IOS] [--dry] [--yes]
// storebound apple adhoc profile [--name "<profile name>"] [--dry] [--yes] IOS_APP_ADHOC profile with every enabled iOS device
// storebound apple adhoc options [--method release-testing|ad-hoc] [--out build/ExportOptions.plist] [--dry]
// storebound apple adhoc export --archive <App.xcarchive> [--plist build/ExportOptions.plist] [--out build/adhoc] [--dry]
// The devices CSV (name, udid, platform) is personal data: keep it in .storebound/ (gitignored). Full UDIDs are never
// printed, also not in --json or in API errors. register only adds devices: it never disables, enables or deletes one
// (that is the owner's call, on the Apple Developer website). Each registration uses one of the 100 yearly slots of
// its product family, and disabling a device does not give the slot back, so register asks first.
// --json of devices: { devices: [{ id, name, platform, deviceClass, model, status, udid (masked) }], usage: [{ deviceClass, registered, limit }] }.
// Sources (checked October 2026):
// https://developer.apple.com/documentation/appstoreconnectapi/get-v1-devices (filter[platform] IOS|MAC_OS|UNIVERSAL, limit <= 200)
// https://developer.apple.com/documentation/appstoreconnectapi/post-v1-devices (name, platform, udid)
// https://developer.apple.com/documentation/appstoreconnectapi/post-v1-profiles (profileType IOS_APP_ADHOC)
// .../get-v1-bundleids (filter[identifier]), .../get-v1-certificates (filter[certificateType] DISTRIBUTION | IOS_DISTRIBUTION),
// .../get-v1-bundleids-_id_-profiles, .../get-v1-profiles-_id_-devices
// https://developer.apple.com/help/account/devices/devices-overview (100 per product family per membership year)
// `xcodebuild -help` (Xcode 27) for the ExportOptions keys and -exportArchive / -allowProvisioningUpdates.
// Not verified from a document: the UDID shapes (see cli/lib/adhoc.ts) and whether App Store Connect accepts a second
// profile with the same name; `profile` therefore gives a changed profile a new, dated name.
import { spawnSync } from 'node:child_process';
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, relative } from 'node:path';
import {
deviceCreateReq, deviceFromApi, type DevicePlatform, exportArgv, type ExportMethod, exportOptionsPlist, maskedDevice, maskUdid,
parseDevicesCsv, parsePlatform, planRegister, profileCreateReq, profileCurrent, profileDevices, type RegisteredDevice, scrubUdids,
shellLine, slotUsage, usableCertificates, validUdid, type WantedDevice, YEARLY_LIMIT,
} from '../lib/adhoc';
import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { done, log, printJson, warn } from '../lib/log';
import { textTable } from '../lib/table';
import { type Asc, ascClient, type J } from './asc';
const TAG = 'adhoc';
const USAGE = 'usage: storebound apple adhoc devices | register [--csv f | --name n --udid u] | profile | options | export --archive <App.xcarchive>';
const METHODS: ExportMethod[] = ['release-testing', 'ad-hoc'];
async function registered(c: Asc, platform?: DevicePlatform): Promise<RegisteredDevice[]> {
return (await c.all(`/v1/devices?limit=200${platform ? `&filter[platform]=${platform}` : ''}`)).map(deviceFromApi);
}
function usageLines(devs: RegisteredDevice[]): void {
for (const u of slotUsage(devs)) log(TAG, `${u.deviceClass}: ${u.registered} registered of ${u.limit} per membership year`);
}
function wantedDevices(ctx: Ctx): WantedDevice[] {
const a = ctx.args;
const udid = a.get('udid');
if (udid !== undefined) {
const name = a.get('name');
const platform = parsePlatform(a.get('platform'));
if (!name || name === 'true') throw new Error('--udid needs --name "<device name>"');
if (!platform) throw new Error('--platform: IOS or MAC_OS');
if (!validUdid(udid, platform)) throw new Error(`--udid ${maskUdid(udid)}: not a device UDID (40 hex digits, or 8 hex - 16 hex)`);
return [{ name, udid: udid.trim(), platform }];
}
const rel = a.get('csv') ?? ctx.loaded.config.apple?.adhoc?.devices ?? '.storebound/devices.csv';
const file = ctx.loaded.resolve(rel);
if (!existsSync(file)) throw new Error(`${rel}: no devices file. Create it with the header line "name,udid,platform" and one device per line (platform IOS or MAC_OS); see skills/adhoc-distribution`);
if (!relative(ctx.loaded.root, file).startsWith('.storebound')) warn(TAG, `${rel} is outside .storebound/: device UDIDs are personal data, keep the file gitignored`);
const { devices, errors } = parseDevicesCsv(readFileSync(file, 'utf8'));
if (errors.length) throw new Error(`${rel}:\n ${errors.join('\n ')}`);
if (!devices.length) throw new Error(`${rel}: no devices`);
return devices;
}
async function register(ctx: Ctx, c: () => Promise<Asc>): Promise<void> {
const wanted = wantedDevices(ctx);
const api = await c();
const all = await registered(api);
const plan = planRegister(wanted, all);
log(TAG, `${wanted.length} in the list: ${plan.add.length} new, ${plan.present.length} already registered, ${plan.disabled.length} disabled`);
for (const d of plan.disabled) warn(TAG, `${d.name} (${maskUdid(d.udid)}) is registered but disabled; enable it on the Apple Developer website if it should test (storebound does not)`);
usageLines(all);
if (!plan.add.length) { done(TAG, 'nothing to register'); return; }
console.log(textTable(['name', 'platform', 'udid'], plan.add.map(d => [d.name, d.platform, maskUdid(d.udid)])));
if (ctx.args.has('dry')) { log(TAG, `dry run: would register ${plan.add.length} device(s); nothing sent`); return; }
if (!(await confirm(ctx, `Register ${plan.add.length} device(s)? Each uses one of the ${YEARLY_LIMIT} yearly slots of its product family, also if it is disabled later.`))) {
log(TAG, 'not confirmed, nothing registered');
return;
}
const udids = plan.add.map(d => d.udid);
let failed = 0;
for (const d of plan.add) {
try {
await api.asc('POST', '/v1/devices', deviceCreateReq(d));
log(TAG, `registered ${d.name} (${maskUdid(d.udid)})`);
} catch (e) {
failed++;
warn(TAG, `${d.name} (${maskUdid(d.udid)}) not registered: ${scrubUdids((e as Error).message, udids)}`);
}
}
if (failed) throw new Error(`${failed} of ${plan.add.length} device(s) not registered`);
done(TAG, `${plan.add.length} device(s) registered; run \`storebound apple adhoc profile\` (or export with automatic signing) so the builds include them`);
}
async function profile(ctx: Ctx, c: () => Promise<Asc>): Promise<void> {
const { config, resolve } = ctx.loaded;
const bundleId = need(config.apple?.bundleId, 'apple.bundleId');
const name = ctx.args.get('name') ?? config.apple?.adhoc?.profile ?? `${bundleId} AdHoc`;
const api = await c();
const bids = await api.asc('GET', `/v1/bundleIds?filter[identifier]=${encodeURIComponent(bundleId)}&limit=200`);
const bid = (bids.data as J[]).find(b => b.attributes?.identifier === bundleId && ['IOS', 'UNIVERSAL'].includes(b.attributes?.platform));
if (!bid) throw new Error(`no iOS bundle id ${bundleId} on the Apple Developer account (Certificates, Identifiers & Profiles > Identifiers)`);
const certs = usableCertificates(await api.all('/v1/certificates?filter[certificateType]=DISTRIBUTION,IOS_DISTRIBUTION&limit=200'));
if (!certs.length) throw new Error('no valid Apple Distribution certificate: create one in Xcode (Settings > Accounts > Manage Certificates) or on the developer website');
const devices = profileDevices(await registered(api, 'IOS'));
if (!devices.length) throw new Error('no enabled iOS devices: register them first (storebound apple adhoc register)');
const want = devices.map(d => d.id);
const existing = (await api.all(`/v1/bundleIds/${bid.id}/profiles?limit=200`)).filter((p: J) => p.attributes?.profileType === 'IOS_APP_ADHOC' && p.attributes?.name === name);
let newName = name;
for (const p of existing) {
const has = (await api.all(`/v1/profiles/${p.id}/devices?limit=200`)).map((d: J) => d.id as string);
const st = profileCurrent(p.attributes.profileState, has, want);
if (st.current) { done(TAG, `profile "${name}" is current (${has.length} devices, expires ${String(p.attributes.expirationDate ?? '').slice(0, 10)})`); return; }
log(TAG, `profile "${name}" is ${p.attributes.profileState === 'ACTIVE' ? `missing ${st.missing} device(s)` : 'invalid'}; profiles cannot be changed, so a new one is created`);
newName = `${name} ${new Date().toISOString().slice(0, 10)}`;
}
const classes = new Map<string, number>();
for (const d of devices) classes.set(d.deviceClass ?? 'UNKNOWN', (classes.get(d.deviceClass ?? 'UNKNOWN') ?? 0) + 1);
log(TAG, `plan: create IOS_APP_ADHOC "${newName}" for ${bundleId}: ${devices.length} devices (${[...classes].map(([k, v]) => `${v} ${k}`).join(', ')}), ${certs.length} distribution certificate(s)`);
if (ctx.args.has('dry')) { log(TAG, 'dry run: nothing created'); return; }
if (!(await confirm(ctx, `Create the ad-hoc provisioning profile "${newName}"?`))) { log(TAG, 'not confirmed, nothing created'); return; }
const res = (await api.asc('POST', '/v1/profiles', profileCreateReq(newName, bid.id, certs, want))).data;
const content = res?.attributes?.profileContent as string | undefined;
if (content) {
const out = resolve(`build/adhoc/${newName.replace(/[^\w.-]+/g, '_')}.mobileprovision`);
mkdirSync(dirname(out), { recursive: true });
writeFileSync(out, Buffer.from(content, 'base64'));
log(TAG, `saved ${relative(ctx.loaded.root, out)} (double-click to install it for manual signing)`);
}
if (newName !== name) warn(TAG, `the new profile is "${newName}": set apple.adhoc.profile to it for manual signing; the old one can be deleted on the Apple Developer website (owner)`);
done(TAG, `profile "${newName}" created (uuid ${res?.attributes?.uuid ?? '?'})`);
}
function plistFor(ctx: Ctx): string {
const { config } = ctx.loaded;
const method = (ctx.args.get('method') ?? config.apple?.adhoc?.method ?? 'release-testing') as ExportMethod;
if (!METHODS.includes(method)) throw new Error(`--method: ${METHODS.join(' | ')} (ad-hoc is the name before Xcode 15.3)`);
return exportOptionsPlist({ method, teamId: need(config.apple?.teamId, 'apple.teamId'), bundleId: config.apple?.bundleId, profile: config.apple?.adhoc?.profile });
}
function options(ctx: Ctx): void {
const rel = ctx.args.str('out', 'build/ExportOptions.plist');
const xml = plistFor(ctx);
if (ctx.args.has('dry')) { log(TAG, `dry run: would write ${rel}`); console.log(xml); return; }
const out = ctx.loaded.resolve(rel);
mkdirSync(dirname(out), { recursive: true });
writeFileSync(out, xml);
done(TAG, `wrote ${rel}`);
}
function exportIpa(ctx: Ctx): void {
const a = ctx.args;
const archive = a.get('archive');
if (!archive || archive === 'true') throw new Error('usage: storebound apple adhoc export --archive <App.xcarchive> [--out build/adhoc] [--dry]');
if (!existsSync(archive)) throw new Error(`${archive}: no such archive (Xcode: Product > Archive, or xcodebuild archive)`);
const plistRel = a.str('plist', 'build/ExportOptions.plist');
const plist = ctx.loaded.resolve(plistRel);
const out = ctx.loaded.resolve(a.str('out', 'build/adhoc'));
const dry = a.has('dry');
if (!existsSync(plist)) {
const xml = plistFor(ctx);
if (dry) { log(TAG, `dry run: would write ${plistRel}`); console.log(xml); }
else { mkdirSync(dirname(plist), { recursive: true }); writeFileSync(plist, xml); log(TAG, `wrote ${plistRel}`); }
}
const argv = exportArgv(archive, plist, out);
if (dry) { log(TAG, 'dry run: would run'); console.log(shellLine(argv)); return; }
log(TAG, 'running xcodebuild -exportArchive; -allowProvisioningUpdates lets Xcode contact Apple to create or update signing assets');
const r = spawnSync(argv[0]!, argv.slice(1), { stdio: 'inherit' });
if (r.error) throw new Error(`xcodebuild: ${r.error.message} (Xcode installed? xcode-select -p)`);
if (r.status !== 0) throw new Error(`xcodebuild -exportArchive failed (exit ${r.status})`);
const ipas = existsSync(out) ? readdirSync(out).filter(f => f.endsWith('.ipa')) : [];
done(TAG, ipas.length ? `exported ${ipas.map(f => join(relative(ctx.loaded.root, out), f)).join(', ')}` : `export finished in ${relative(ctx.loaded.root, out)}`);
}
export async function run(ctx: Ctx): Promise<void> {
const a = ctx.args;
const sub = a._[0];
let client: Asc | null = null;
const c = async (): Promise<Asc> => (client ??= await ascClient(ctx.loaded.root, ctx.loaded.config.apple?.bundleId ?? '', ctx.loaded.config.apple?.appId));
if (sub === 'devices') {
const p = a.get('platform');
const platform = p ? parsePlatform(p) : undefined;
if (p && !platform) throw new Error('--platform: IOS or MAC_OS');
const devs = await registered(await c(), platform ?? undefined);
if (a.has('json')) { printJson({ devices: devs.map(maskedDevice), usage: slotUsage(devs) }); return; }
console.log(textTable(['name', 'platform', 'class', 'model', 'status', 'udid'], devs.map(maskedDevice).map(d => [d.name, d.platform, d.deviceClass ?? '', d.model ?? '', d.status, d.udid])));
usageLines(devs);
return;
}
if (sub === 'register') return register(ctx, c);
if (sub === 'profile') return profile(ctx, c);
if (sub === 'options') return options(ctx);
if (sub === 'export') return exportIpa(ctx);
throw new Error(USAGE);
}

View file

@ -15,7 +15,7 @@ export const AGE_RATING_NONE: Record<string, string | boolean | null> = {
advertising: false, ageAssurance: false, alcoholTobaccoOrDrugUseOrReferences: 'NONE', contests: 'NONE', gambling: false, advertising: false, ageAssurance: false, alcoholTobaccoOrDrugUseOrReferences: 'NONE', contests: 'NONE', gambling: false,
gamblingSimulated: 'NONE', gunsOrOtherWeapons: 'NONE', healthOrWellnessTopics: false, horrorOrFearThemes: 'NONE', lootBox: false, gamblingSimulated: 'NONE', gunsOrOtherWeapons: 'NONE', healthOrWellnessTopics: false, horrorOrFearThemes: 'NONE', lootBox: false,
matureOrSuggestiveThemes: 'NONE', medicalOrTreatmentInformation: 'NONE', messagingAndChat: false, parentalControls: false, matureOrSuggestiveThemes: 'NONE', medicalOrTreatmentInformation: 'NONE', messagingAndChat: false, parentalControls: false,
profanityOrCrudeHumor: 'NONE', sexualContentGraphicAndNudity: 'NONE', sexualContentOrNudity: 'NONE', unrestrictedWebAccess: false, profanityOrCrudeHumor: 'NONE', socialMedia: false, socialMediaAgeRestricted: false, sexualContentGraphicAndNudity: 'NONE', sexualContentOrNudity: 'NONE', unrestrictedWebAccess: false,
userGeneratedContent: false, violenceCartoonOrFantasy: 'NONE', violenceRealistic: 'NONE', userGeneratedContent: false, violenceCartoonOrFantasy: 'NONE', violenceRealistic: 'NONE',
violenceRealisticProlongedGraphicOrSadistic: 'NONE', kidsAgeBand: null, violenceRealisticProlongedGraphicOrSadistic: 'NONE', kidsAgeBand: null,
}; };

282
cli/console/fill.ts Normal file
View file

@ -0,0 +1,282 @@
// AI-assisted autofill of console forms that have no API, in a visible Chromium the owner signs in to:
// storebound console fill lists the forms
// storebound console fill <form> --dry [--json] the answers and the step-by-step guidance; opens no browser
// storebound console fill <form> [--store apple|play] [--json] [--profile <dir>]
// Forms: apple-app-record, apple-age-rating (guide only: `storebound apple appinfo` sets it), apple-app-privacy,
// play-content-rating, play-target-audience. Answers come from the config only (cli/lib/console-answers.ts); anything
// it does not prove stays EMPTY and highlighted (AGENTS.md rule 5).
// Safety: storebound never types passwords, never touches sign-in pages (it waits while the owner signs in), never reads
// cookies or storage, and never clicks Save / Submit / Publish / Create / Next: every click goes through safeClick and
// its gate. The owner reviews each page, clicks Next, and presses the final button; the command ends when the window
// is closed. Locators are accessible names only (cli/lib/console-forms.ts); a missing or ambiguous field means the UI
// changed: filling stops and the guidance is printed instead. Not exposed over MCP.
// Profile: ~/.storebound/console-profile/<store> (or --profile / STOREBOUND_CONSOLE_PROFILE), so the sign-in is kept.
// Sources (checked October 2026): see cli/lib/console-answers.ts; Playwright launchPersistentContext, getByRole,
// getByLabel: https://playwright.dev/docs/api/class-browsertype#browser-type-launch-persistent-context ,
// https://playwright.dev/docs/locators
import { mkdirSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import type { Ctx } from '../lib/ctx';
import { type Answer, type ConsoleResult, consoleResult, DISCLAIMER, FORM_IDS, fillValue, formMeta, isForm, valueText } from '../lib/console-answers';
import { consoleReached, type FieldDef, type FormDef, formDef, forbiddenControl, isSignInUrl, type Name } from '../lib/console-forms';
import { log, printJson, warn } from '../lib/log';
import { launchPersistent } from '../shots/browser';
/* eslint-disable @typescript-eslint/no-explicit-any */
type Page = any;
type Locator = any;
const TAG = 'console';
const CHECK = 'storebound: check this';
/** Locators with only the visible matches (hidden earlier pages stay in many consoles' DOM). */
const vis = (l: Locator): Locator => { try { return l.filter({ visible: true }); } catch { return l; } };
const nameOpts = (n: Name) => (typeof n === 'string' ? { name: n, exact: true } : { name: n });
type Found = { state: 'ok'; loc: Locator } | { state: 'none' | 'ambiguous' };
async function first(tries: Locator[]): Promise<Found> {
for (const t of tries) {
const l = vis(t);
const n = await l.count();
if (n === 1) return { state: 'ok', loc: l };
if (n > 1) return { state: 'ambiguous' };
}
return { state: 'none' };
}
async function find(root: Locator, role: string, names: Name[], label = false): Promise<Found> {
for (const n of names) {
const tries = [root.getByRole(role, nameOpts(n))];
if (label) tries.push(root.getByLabel(n, typeof n === 'string' ? { exact: true } : {}));
const f = await first(tries);
if (f.state !== 'none') return f;
}
return { state: 'none' };
}
interface Resolved { field: FieldDef; ok: boolean; seen: boolean; loc?: Locator; options?: Record<string, Locator> }
async function resolve(root: Locator, f: FieldDef): Promise<Resolved> {
if (f.kind !== 'radio') {
const role = f.kind === 'text' ? 'textbox' : f.kind === 'select' ? 'combobox' : 'checkbox';
const r = await find(root, role, f.names ?? [], f.kind !== 'checkbox');
return { field: f, ok: r.state === 'ok', seen: r.state !== 'none', ...(r.state === 'ok' ? { loc: r.loc } : {}) };
}
let scope = root, seen = false;
if (f.names?.length) {
let g = await find(root, 'radiogroup', f.names);
if (g.state === 'none') g = await find(root, 'group', f.names);
if (g.state !== 'ok') return { field: f, ok: false, seen: g.state !== 'none' };
scope = g.loc; seen = true;
}
const options: Record<string, Locator> = {};
let ok = true;
for (const [v, names] of Object.entries(f.options ?? {})) {
const r = await find(scope, 'radio', names);
if (r.state === 'ok') { options[v] = r.loc; seen = true; } else { ok = false; if (r.state === 'ambiguous') seen = true; }
}
return { field: f, ok, seen, ...(f.names?.length ? { loc: scope } : {}), options };
}
/** The accessible name of a control as the page labels it (what the click gate checks). */
async function accName(loc: Locator): Promise<string> {
return (await loc.evaluate((el: any) => {
const by = el.getAttribute('aria-labelledby');
const ref = by ? by.split(/\s+/).map((id: string) => el.ownerDocument.getElementById(id)?.textContent ?? '').join(' ') : '';
const labels = el.labels ? [...el.labels].map((l: any) => l.textContent).join(' ') : '';
return el.getAttribute('aria-label') || ref || labels || el.textContent || '';
})).trim().replace(/\s+/g, ' ');
}
/**
* The single click gate: refuses any control whose name says save, submit, publish, create, next ... (English and
* Turkish). Every click storebound makes, checkboxes and radio buttons included, goes through here.
*/
export async function safeClick(loc: Locator, name: string, action: 'click' | 'check' | 'uncheck' = 'click'): Promise<boolean> {
if (forbiddenControl(name)) { warn(TAG, `not clicking "${name}": storebound never presses save, submit, publish, next or similar`); return false; }
if (action === 'click') await loc.click();
else await loc.setChecked(action === 'check');
return true;
}
/** Outline + a small "storebound: check this" label next to the element (no SVG). */
export async function highlight(loc: Locator, text = CHECK): Promise<void> {
await loc.evaluate((el: any, t: string) => {
const box = (el.tagName === 'INPUT' && el.closest('label')) || el;
if (box.getAttribute('data-storebound-check')) return;
box.setAttribute('data-storebound-check', '1');
box.style.outline = '3px solid #d93025';
box.style.outlineOffset = '2px';
const s = el.ownerDocument.createElement('span');
s.textContent = t;
s.setAttribute('data-storebound-label', '1');
s.style.cssText = 'display:inline-block;margin:2px 6px;padding:1px 6px;border-radius:4px;background:#d93025;color:#fff;font:600 12px/18px system-ui,sans-serif';
box.insertAdjacentElement('afterend', s);
}, text);
}
async function setField(r: Resolved, v: string | boolean): Promise<boolean> {
const f = r.field;
if (f.kind === 'text') { await r.loc.fill(String(v)); return true; }
if (f.kind === 'checkbox') return safeClick(r.loc, await accName(r.loc), v ? 'check' : 'uncheck');
if (f.kind === 'radio') {
const o = r.options?.[String(v)];
return o ? safeClick(o, await accName(o), 'check') : false;
}
// select: only a native <select>; a custom dropdown is left to the owner (highlighted)
const idx: number = await r.loc.evaluate((el: any, want: string) => {
if (el.tagName !== 'SELECT') return -1;
const labels: string[] = [...el.options].map((o: any) => (o.label || o.textContent || '').trim());
const exact = labels.indexOf(want);
if (exact >= 0) return exact;
const near = labels.map((l, i) => [l, i] as const).filter(([l]) => l.endsWith(` - ${want}`) || l.endsWith(`(${want})`) || l.includes(want));
return near.length === 1 ? near[0]![1] : -1;
}, String(v));
if (idx < 0) return false;
await r.loc.selectOption({ index: idx });
return true;
}
async function mark(r: Resolved): Promise<void> {
if (r.loc) return highlight(r.loc);
for (const o of Object.values(r.options ?? {})) await highlight(o);
}
export interface FillStep {
/** Index of the section filled (or that triggered the fallback); null when no unfilled section is on the page. */
section: number | null;
title?: string;
filled: string[];
highlighted: string[];
/** Fields of the section that could not be located (UI change) -> fallback. */
missing: string[];
fallback: boolean;
}
/**
* Fills the first section of the form that is on the page and not done yet: locate every field first; any missing or
* ambiguous field -> fallback (nothing of that section is touched). Certain answers are set, the rest is highlighted
* and left empty. Never clicks Next / Save. `answers` carry the values the page gets (fillValue).
*/
export async function fillPage(page: Page, def: FormDef, answers: Answer[], done: Set<number> = new Set()): Promise<FillStep> {
const byId = new Map(answers.map(a => [a.id, a]));
for (const [i, sec] of def.sections.entries()) {
if (done.has(i)) continue;
let root: Locator = page;
if (sec.dialog) {
const d = await find(page, 'dialog', sec.dialog);
if (d.state === 'none') continue;
if (d.state !== 'ok') return { section: i, title: sec.title, filled: [], highlighted: [], missing: [`dialog ${sec.title}`], fallback: true };
root = d.loc;
}
const rs: Resolved[] = [];
for (const f of sec.fields) rs.push(await resolve(root, f));
if (!sec.dialog && !rs.some(r => r.seen)) continue;
const missing = rs.filter(r => !r.ok).map(r => r.field.id);
if (missing.length) return { section: i, title: sec.title, filled: [], highlighted: [], missing, fallback: true };
const filled: string[] = [], highlighted: string[] = [];
for (const r of rs) {
const a = byId.get(r.field.id);
if (!a) continue;
const set = a.certain && a.value !== null ? await setField(r, a.value) : false;
if (set) filled.push(a.id); else { await mark(r); highlighted.push(a.id); }
}
done.add(i);
return { section: i, title: sec.title, filled, highlighted, missing: [], fallback: false };
}
return { section: null, filled: [], highlighted: [], missing: [], fallback: false };
}
/** A sign-in page: Apple ID / Google accounts hosts, a sign-in frame, or any password field. Read-only check. */
export async function signInPage(page: Page): Promise<boolean> {
if (isSignInUrl(page.url())) return true;
if (page.frames().some((f: any) => isSignInUrl(f.url()))) return true;
try { return (await page.locator('input[type="password"]').count()) > 0; } catch { return false; }
}
const active = (context: any): Page | undefined => { const ps = context.pages(); return ps[ps.length - 1]; };
function printText(res: ConsoleResult): void {
console.log(`${res.title}\n${res.url}\n`);
for (const a of res.answers) console.log(` ${a.certain ? '[ok] ' : '[check]'} ${a.label}: ${valueText(a)} (${a.source})${a.certain || !a.note ? '' : `\n ${a.note}`}`);
console.log(`\n${res.uncertain} answer(s) to check yourself.\n\nSteps:\n${res.guidance.map(g => ` - ${g}`).join('\n')}`);
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded;
const args = ctx.args, json = args.has('json'), dry = args.has('dry');
const form = args._[0];
if (!form) {
const forms = FORM_IDS.map(id => { const m = formMeta(id, config); return { id, store: m.store, title: m.title, fillable: m.fillable }; });
if (json) return printJson({ forms });
console.log('storebound console fill <form> [--store apple|play] [--dry] [--json] [--profile <dir>]\n');
for (const f of forms) console.log(` ${f.id.padEnd(22)} ${f.store.padEnd(6)} ${f.title}${f.fillable ? '' : ' (guide only)'}`);
return;
}
if (!isForm(form)) throw new Error(`console fill: unknown form "${form}" (one of ${FORM_IDS.join(', ')})`);
const meta = formMeta(form, config);
const store = args.get('store');
if (store && store !== 'apple' && store !== 'play') throw new Error('--store: apple | play');
if (store && store !== meta.store) throw new Error(`console fill: ${form} is a ${meta.store} form, not ${store}`);
const res = consoleResult(form, config);
if (dry || !meta.fillable) {
if (json) return printJson(dry ? res : { ...res, filled: 0, highlighted: 0, fallback: false, stoppedAt: null });
return printText(res);
}
const say = (m: string) => (json ? console.error(`[${TAG}] ${m}`) : log(TAG, m));
for (const d of DISCLAIMER) say(d);
const startUrl = args.get('start-url');
if (startUrl && !/^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(startUrl)) throw new Error('--start-url: only a local test page (http://127.0.0.1:<port>/...)');
const dir = args.get('profile') ?? process.env.STOREBOUND_CONSOLE_PROFILE ?? join(homedir(), '.storebound', 'console-profile', meta.store);
mkdirSync(dir, { recursive: true });
const context = await launchPersistent(root, dir, { headless: false, viewport: null });
let closed = false;
const closing = new Promise<void>(r => context.on('close', () => { closed = true; r(); }));
const page = context.pages()[0] ?? await context.newPage();
await page.goto(startUrl ?? meta.url).catch(() => { /* the owner can navigate */ });
// 1. sign-in: the owner does it; storebound only watches the URL
const deadline = Date.now() + 10 * 60_000;
let told = false;
while (!closed && Date.now() < deadline) {
const p = active(context);
if (p && !(await signInPage(p).catch(() => false)) && consoleReached(meta.store, p.url(), startUrl)) break;
if (p && !told && await signInPage(p).catch(() => false)) { say('sign in in the browser window, storebound waits'); told = true; }
await Bun.sleep(1000);
}
// 2. fill section by section as the owner moves through the form
const def = formDef(form, res.answers);
const pageAnswers = res.answers.map(a => ({ ...a, value: fillValue(form, a, config) }));
const labels = new Map(res.answers.map(a => [a.id, a.label]));
const done = new Set<number>();
let filled = 0, highlighted = 0, fallback = false;
for (const o of meta.open) say(`open the form: ${o}`);
const last = def.sections.length - 1;
const finished = () => done.size === def.sections.length || (form !== 'apple-app-privacy' && done.has(last));
while (!closed && !finished()) {
const p = active(context);
if (!p || await signInPage(p).catch(() => true)) { await Bun.sleep(1500); continue; }
let s: FillStep;
try { s = await fillPage(p, def, pageAnswers, done); } catch { await Bun.sleep(1500); continue; } // navigating
if (s.section !== null) {
if (s.fallback) {
fallback = true;
warn(TAG, `the page does not match what storebound expects (${s.missing.join(', ')}): the console UI changed. Nothing more is filled; follow these steps:`);
for (const g of res.guidance) say(` ${g}`);
break;
}
filled += s.filled.length; highlighted += s.highlighted.length;
say(`${s.title}: filled ${s.filled.length}, check ${s.highlighted.length}${s.highlighted.length ? `: ${s.highlighted.map(id => labels.get(id) ?? id).join('; ')}` : ''}`);
if (!finished()) say('review this page, then click Next (or open the next part) yourself; storebound fills it when it appears');
}
await Bun.sleep(1500);
}
if (!closed && !fallback) say(`review every field and press ${meta.stopBefore} yourself. storebound never saves, submits or publishes. Close the window when done.`);
else if (!closed) say('close the browser window when done');
await closing;
if (json) printJson({ ...res, filled, highlighted, fallback, stoppedAt: meta.stopBefore });
}

196
cli/data/ppp-worldbank.json Normal file
View file

@ -0,0 +1,196 @@
{
"name": "worldbank",
"source": "World Bank, World Development Indicators: PPP conversion factor, GDP (LCU per international $) [PA.NUS.PPP] (International Comparison Program) and Official exchange rate (LCU per US$, period average) [PA.NUS.FCRF]",
"url": "https://data.worldbank.org/indicator/PA.NUS.PPP",
"urls": [
"https://data.worldbank.org/indicator/PA.NUS.PPP",
"https://data.worldbank.org/indicator/PA.NUS.FCRF",
"https://api.worldbank.org/v2/country/all/indicator/PA.NUS.PPP?format=json&per_page=20000&date=2018:2026",
"https://api.worldbank.org/v2/country/all/indicator/PA.NUS.FCRF?format=json&per_page=20000&date=2018:2026"
],
"license": "CC BY 4.0",
"attribution": "The World Bank: World Development Indicators, PA.NUS.PPP and PA.NUS.FCRF (CC BY 4.0, https://creativecommons.org/licenses/by/4.0/). Values used unchanged except the euro rate note below.",
"retrieved": "2026-10-11",
"year": 2025,
"notes": [
"Latest available year per country (2018 onwards); fxYear is set when the exchange rate is from another year than the PPP factor.",
"Every EUR region (euro area members, Montenegro, Kosovo) uses the euro area rate (XC, 0.88496896 EUR per USD, 2025): per-country FCRF is missing for most members and still in BGN for Bulgaria, whose PPP factor is already in EUR.",
"Only App Store territories are kept; aggregates (regions, income groups) are excluded.",
"Dropped as a unit mismatch (PPP / fx outside 0.05..3): LR (0.002).",
"Missing countries (no recent World Bank data, e.g. Taiwan, Venezuela) get no proposal; set them by hand or with --source file."
],
"eur": {
"fx": 0.88496896,
"year": 2025
},
"countries": {
"AE": {"ppp":2.3269559,"fx":3.6725,"year":2024,"fxYear":2025,"currency":"AED"},
"AF": {"ppp":13.232057,"fx":76.813536,"year":2024,"fxYear":2020,"currency":"AFN"},
"AG": {"ppp":1.8701458,"fx":2.7,"year":2025,"currency":"XCD"},
"AL": {"ppp":39.980538,"fx":86.803333,"year":2025,"currency":"ALL"},
"AM": {"ppp":148.11782,"fx":387.01015,"year":2025,"currency":"AMD"},
"AO": {"ppp":322.96596,"fx":911.99304,"year":2025,"currency":"AOA"},
"AR": {"ppp":567.29742,"fx":1240.8512,"year":2025,"currency":"ARS"},
"AT": {"ppp":0.725357,"fx":0.88496896,"year":2025,"currency":"EUR"},
"AU": {"ppp":1.398943,"fx":1.5519979,"year":2025,"currency":"AUD"},
"AZ": {"ppp":0.48245913,"fx":1.7,"year":2025,"currency":"AZN"},
"BA": {"ppp":0.69764696,"fx":1.735929,"year":2025,"currency":"BAM"},
"BB": {"ppp":2.1908522,"fx":2,"year":2025,"currency":"BBD"},
"BE": {"ppp":0.719942,"fx":0.88496896,"year":2025,"currency":"EUR"},
"BF": {"ppp":217.41076,"fx":581.92848,"year":2025,"currency":"XOF"},
"BG": {"ppp":0.4057046,"fx":0.88496896,"year":2025,"currency":"EUR"},
"BH": {"ppp":0.16203993,"fx":0.376,"year":2025,"currency":"BHD"},
"BJ": {"ppp":200.3366,"fx":581.92848,"year":2025,"currency":"XOF"},
"BM": {"ppp":1.1981206,"fx":1,"year":2024,"fxYear":2025,"currency":"BMD"},
"BN": {"ppp":0.4560196,"fx":1.3075951,"year":2025,"currency":"BND"},
"BO": {"ppp":2.7632458,"fx":6.91,"year":2025,"currency":"BOB"},
"BR": {"ppp":2.5544084,"fx":5.5872862,"year":2025,"currency":"BRL"},
"BS": {"ppp":0.95631566,"fx":1,"year":2024,"fxYear":2025,"currency":"BSD"},
"BT": {"ppp":19.984895,"fx":87.158448,"year":2025,"currency":"BTN"},
"BW": {"ppp":5.0740914,"fx":13.502383,"year":2025,"currency":"BWP"},
"BY": {"ppp":0.90876978,"fx":3.069175,"year":2025,"currency":"BYN"},
"BZ": {"ppp":1.0511305,"fx":2,"year":2025,"currency":"BZD"},
"CA": {"ppp":1.166683,"fx":1.3981057,"year":2025,"currency":"CAD"},
"CD": {"ppp":1124.8543,"fx":2693.2406,"year":2025,"currency":"CDF"},
"CG": {"ppp":201.89095,"fx":581.92848,"year":2025,"currency":"XAF"},
"CH": {"ppp":0.930746,"fx":0.83135583,"year":2025,"currency":"CHF"},
"CI": {"ppp":216.22133,"fx":581.92848,"year":2025,"currency":"XOF"},
"CL": {"ppp":453.18856,"fx":951.32945,"year":2025,"currency":"CLP"},
"CM": {"ppp":198.30924,"fx":581.92848,"year":2025,"currency":"XAF"},
"CN": {"ppp":3.3976859,"fx":7.1898474,"year":2025,"currency":"CNY"},
"CO": {"ppp":1532.7193,"fx":4053.1358,"year":2025,"currency":"COP"},
"CR": {"ppp":297.35177,"fx":503.49683,"year":2025,"currency":"CRC"},
"CV": {"ppp":46.629436,"fx":97.863152,"year":2025,"currency":"CVE"},
"CY": {"ppp":0.57262027,"fx":0.88496896,"year":2025,"currency":"EUR"},
"CZ": {"ppp":12.993503,"fx":21.882,"year":2025,"currency":"CZK"},
"DE": {"ppp":0.709983,"fx":0.88496896,"year":2025,"currency":"EUR"},
"DK": {"ppp":6.124666,"fx":6.6218251,"year":2025,"currency":"DKK"},
"DM": {"ppp":1.3063113,"fx":2.7,"year":2025,"currency":"XCD"},
"DO": {"ppp":23.868251,"fx":61.986567,"year":2025,"currency":"DOP"},
"DZ": {"ppp":42.846051,"fx":131.60593,"year":2025,"currency":"DZD"},
"EC": {"ppp":0.4252207,"fx":1,"year":2025,"currency":"USD"},
"EE": {"ppp":0.584555,"fx":0.88496896,"year":2025,"currency":"EUR"},
"EG": {"ppp":7.5837097,"fx":49.227756,"year":2025,"currency":"EGP"},
"ES": {"ppp":0.570991,"fx":0.88496896,"year":2025,"currency":"EUR"},
"FI": {"ppp":0.754195,"fx":0.88496896,"year":2025,"currency":"EUR"},
"FJ": {"ppp":0.93466687,"fx":2.2990333,"year":2025,"currency":"FJD"},
"FM": {"ppp":0.95865081,"fx":1,"year":2025,"currency":"USD"},
"FR": {"ppp":0.677618,"fx":0.88496896,"year":2025,"currency":"EUR"},
"GA": {"ppp":216.42004,"fx":581.92848,"year":2025,"currency":"XAF"},
"GB": {"ppp":0.677133,"fx":0.75947396,"year":2025,"currency":"GBP"},
"GD": {"ppp":1.5313701,"fx":2.7,"year":2025,"currency":"XCD"},
"GE": {"ppp":0.90351418,"fx":2.7426417,"year":2025,"currency":"GEL"},
"GH": {"ppp":4.7500898,"fx":12.556825,"year":2025,"currency":"GHS"},
"GM": {"ppp":17.793532,"fx":71.289382,"year":2025,"currency":"GMD"},
"GR": {"ppp":0.526872,"fx":0.88496896,"year":2025,"currency":"EUR"},
"GT": {"ppp":3.3345116,"fx":7.6801246,"year":2025,"currency":"GTQ"},
"GW": {"ppp":198.58274,"fx":581.92848,"year":2025,"currency":"XOF"},
"GY": {"ppp":69.033137,"fx":208.5,"year":2025,"currency":"GYD"},
"HK": {"ppp":5.524573,"fx":7.7970833,"year":2025,"currency":"HKD"},
"HN": {"ppp":11.864084,"fx":25.952675,"year":2025,"currency":"HNL"},
"HR": {"ppp":0.47081305,"fx":0.88496896,"year":2025,"currency":"EUR"},
"HU": {"ppp":183.57556,"fx":353.14,"year":2025,"currency":"HUF"},
"ID": {"ppp":4720.9975,"fx":16477.865,"year":2025,"currency":"IDR"},
"IE": {"ppp":0.750891,"fx":0.88496896,"year":2025,"currency":"EUR"},
"IL": {"ppp":3.487723,"fx":3.4518917,"year":2025,"currency":"ILS"},
"IN": {"ppp":20.088629,"fx":87.158448,"year":2025,"currency":"INR"},
"IQ": {"ppp":492.93355,"fx":1300,"year":2025,"currency":"IQD"},
"IS": {"ppp":151.36799,"fx":128.44149,"year":2025,"currency":"ISK"},
"IT": {"ppp":0.610275,"fx":0.88496896,"year":2025,"currency":"EUR"},
"JM": {"ppp":95.795037,"fx":159.09643,"year":2025,"currency":"JMD"},
"JO": {"ppp":0.30058844,"fx":0.71,"year":2025,"currency":"JOD"},
"JP": {"ppp":97.08005,"fx":149.65793,"year":2025,"currency":"JPY"},
"KE": {"ppp":43.547148,"fx":129.30257,"year":2025,"currency":"KES"},
"KG": {"ppp":29.193566,"fx":87.359832,"year":2025,"currency":"KGS"},
"KH": {"ppp":1349.4922,"fx":4013.4331,"year":2025,"currency":"KHR"},
"KN": {"ppp":1.8517466,"fx":2.7,"year":2025,"currency":"XCD"},
"KR": {"ppp":816.32927,"fx":1422.4408,"year":2025,"currency":"KRW"},
"KW": {"ppp":0.17536157,"fx":0.30645478,"year":2025,"currency":"KWD"},
"KY": {"ppp":0.94261799,"fx":0.83333,"year":2024,"fxYear":2025,"currency":"KYD"},
"KZ": {"ppp":172.82713,"fx":521.035,"year":2025,"currency":"KZT"},
"LA": {"ppp":4577.462,"fx":20444.137,"year":2025,"currency":"LAK"},
"LB": {"ppp":33594.248,"fx":89500,"year":2024,"fxYear":2025,"currency":"LBP"},
"LC": {"ppp":1.3885027,"fx":2.7,"year":2025,"currency":"XCD"},
"LK": {"ppp":88.213772,"fx":300.85196,"year":2025,"currency":"LKR"},
"LT": {"ppp":0.513169,"fx":0.88496896,"year":2025,"currency":"EUR"},
"LU": {"ppp":0.832451,"fx":0.88496896,"year":2025,"currency":"EUR"},
"LV": {"ppp":0.504702,"fx":0.88496896,"year":2025,"currency":"EUR"},
"LY": {"ppp":2.070745,"fx":5.3025667,"year":2025,"currency":"LYD"},
"MA": {"ppp":3.9317968,"fx":9.350277,"year":2025,"currency":"MAD"},
"MD": {"ppp":7.4897651,"fx":17.377847,"year":2025,"currency":"MDL"},
"ME": {"ppp":0.37017116,"fx":0.88496896,"year":2025,"currency":"EUR"},
"MG": {"ppp":1390.2917,"fx":4529.7513,"year":2025,"currency":"MGA"},
"MK": {"ppp":20.45322,"fx":54.654967,"year":2025,"currency":"MKD"},
"ML": {"ppp":198.24397,"fx":581.92848,"year":2025,"currency":"XOF"},
"MM": {"ppp":520.10645,"fx":1381.6192,"year":2025,"fxYear":2020,"currency":"MMK"},
"MN": {"ppp":1211.6536,"fx":3545.1436,"year":2025,"currency":"MNT"},
"MO": {"ppp":4.4477383,"fx":8.0298103,"year":2025,"currency":"MOP"},
"MR": {"ppp":11.391686,"fx":36.489167,"year":2025,"fxYear":2023,"currency":"MRU"},
"MT": {"ppp":0.58711979,"fx":0.88496896,"year":2025,"currency":"EUR"},
"MU": {"ppp":17.749322,"fx":45.996967,"year":2025,"currency":"MUR"},
"MV": {"ppp":7.8899199,"fx":15.415678,"year":2025,"currency":"MVR"},
"MW": {"ppp":619.00555,"fx":1161.0944,"year":2025,"fxYear":2023,"currency":"MWK"},
"MX": {"ppp":10.328951,"fx":19.237508,"year":2025,"currency":"MXN"},
"MY": {"ppp":1.3550436,"fx":4.2844242,"year":2025,"currency":"MYR"},
"MZ": {"ppp":23.662004,"fx":63.905,"year":2025,"fxYear":2024,"currency":"MZN"},
"NA": {"ppp":7.2773376,"fx":17.888733,"year":2025,"currency":"NAD"},
"NE": {"ppp":207.23405,"fx":581.92848,"year":2025,"currency":"XOF"},
"NG": {"ppp":195.02255,"fx":1518.3809,"year":2025,"currency":"NGN"},
"NI": {"ppp":12.51855,"fx":36.6243,"year":2025,"currency":"NIO"},
"NL": {"ppp":0.746769,"fx":0.88496896,"year":2025,"currency":"EUR"},
"NO": {"ppp":9.451661,"fx":10.395833,"year":2025,"currency":"NOK"},
"NP": {"ppp":33.8982,"fx":139.11544,"year":2025,"currency":"NPR"},
"NR": {"ppp":1.5928709,"fx":1.5519979,"year":2025,"currency":"AUD"},
"NZ": {"ppp":1.472957,"fx":1.7201083,"year":2025,"currency":"NZD"},
"OM": {"ppp":0.18133921,"fx":0.3845,"year":2025,"currency":"OMR"},
"PA": {"ppp":0.45076892,"fx":1,"year":2025,"currency":"PAB"},
"PE": {"ppp":1.8359229,"fx":3.5670638,"year":2025,"currency":"PEN"},
"PG": {"ppp":2.3871996,"fx":4.1227237,"year":2025,"currency":"PGK"},
"PH": {"ppp":19.06958,"fx":57.505097,"year":2025,"currency":"PHP"},
"PK": {"ppp":67.836812,"fx":281.143,"year":2025,"currency":"PKR"},
"PL": {"ppp":1.969559,"fx":3.7605417,"year":2025,"currency":"PLN"},
"PT": {"ppp":0.534218,"fx":0.88496896,"year":2025,"currency":"EUR"},
"PW": {"ppp":0.847329,"fx":1,"year":2025,"currency":"USD"},
"PY": {"ppp":2627.1179,"fx":7545.4468,"year":2025,"currency":"PYG"},
"QA": {"ppp":2.048298,"fx":3.64,"year":2025,"currency":"QAR"},
"RO": {"ppp":1.9796789,"fx":4.4705333,"year":2025,"currency":"RON"},
"RS": {"ppp":46.797068,"fx":103.9754,"year":2025,"currency":"RSD"},
"RU": {"ppp":29.612263,"fx":83.6525,"year":2025,"currency":"RUB"},
"RW": {"ppp":385.46304,"fx":1428.4783,"year":2025,"currency":"RWF"},
"SA": {"ppp":1.7553023,"fx":3.75,"year":2025,"currency":"SAR"},
"SB": {"ppp":6.2316213,"fx":8.3268423,"year":2025,"currency":"SBD"},
"SC": {"ppp":7.9879739,"fx":14.725456,"year":2025,"currency":"SCR"},
"SE": {"ppp":8.548493,"fx":9.8207057,"year":2025,"currency":"SEK"},
"SG": {"ppp":0.79088571,"fx":1.30745,"year":2025,"currency":"SGD"},
"SI": {"ppp":0.558308,"fx":0.88496896,"year":2025,"currency":"EUR"},
"SK": {"ppp":0.512288,"fx":0.88496896,"year":2025,"currency":"EUR"},
"SL": {"ppp":5.1588367,"fx":21.304875,"year":2025,"fxYear":2023,"currency":"SLE"},
"SN": {"ppp":208.21105,"fx":581.92848,"year":2025,"currency":"XOF"},
"SR": {"ppp":11.629,"fx":37.260179,"year":2025,"currency":"SRD"},
"ST": {"ppp":13.867256,"fx":21.745052,"year":2025,"currency":"STN"},
"SV": {"ppp":0.40895349,"fx":1,"year":2025,"currency":"USD"},
"SZ": {"ppp":5.8656364,"fx":17.888921,"year":2025,"currency":"SZL"},
"TC": {"ppp":0.98677362,"fx":1,"year":2024,"fxYear":2025,"currency":"USD"},
"TD": {"ppp":204.95328,"fx":581.92848,"year":2025,"currency":"XAF"},
"TH": {"ppp":10.092256,"fx":32.882809,"year":2025,"currency":"THB"},
"TJ": {"ppp":2.7689058,"fx":10.017708,"year":2025,"currency":"TJS"},
"TM": {"ppp":1.5731522,"year":2025,"currency":"TMT"},
"TN": {"ppp":0.91601355,"fx":2.9973667,"year":2025,"currency":"TND"},
"TO": {"ppp":1.807921,"fx":2.4105269,"year":2025,"currency":"TOP"},
"TR": {"ppp":16.203626,"fx":39.454813,"year":2025,"currency":"TRY"},
"TT": {"ppp":3.448334,"fx":6.7488466,"year":2025,"currency":"TTD"},
"TZ": {"ppp":749.53349,"fx":2597.9004,"year":2025,"fxYear":2024,"currency":"TZS"},
"UA": {"ppp":12.935398,"fx":41.689072,"year":2025,"currency":"UAH"},
"UG": {"ppp":1271.5153,"fx":3602.9899,"year":2025,"currency":"UGX"},
"US": {"ppp":1,"fx":1,"year":2025,"currency":"USD"},
"UY": {"ppp":27.108347,"fx":41.190979,"year":2025,"currency":"UYU"},
"UZ": {"ppp":3670.1263,"fx":12579.394,"year":2025,"currency":"UZS"},
"VC": {"ppp":1.487617,"fx":2.7,"year":2025,"currency":"XCD"},
"VN": {"ppp":6990.8707,"fx":24164.886,"year":2025,"fxYear":2024,"currency":"VND"},
"VU": {"ppp":107.38904,"fx":120.32429,"year":2025,"currency":"VUV"},
"XK": {"ppp":0.36290409,"fx":0.88496896,"year":2025,"currency":"EUR"},
"ZA": {"ppp":7.4202966,"fx":17.888749,"year":2025,"currency":"ZAR"},
"ZM": {"ppp":7.5613927,"fx":25.275689,"year":2025,"currency":"ZMW"},
"ZW": {"ppp":14.847786,"fx":26.596194,"year":2025,"currency":"ZWG"}
}
}

View file

@ -35,7 +35,11 @@ const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
'reports': [() => import('./reports'), 'apple-sales | apple-finance --month | play-earnings --month | play-sales --month: download to .storebound/reports/, summary table + CSV; read-only'], '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'], '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 [--storefronts us,de] [--keywords a,b]: App Store rank per keyword and storefront + competitors from the public iTunes Search API (rate limited) -> .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)'], '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 <USD> (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 <domain> (live files: content type, no redirects, ids match)'],
'revenuecat': [() => import('./revenuecat'), 'diff (catalog vs RevenueCat products, entitlements, default offering) | sync (dry run, asks first; never via MCP)'],
'console fill': [() => import('./console/fill'), '<form> [--store apple|play]: AI-assisted autofill of console forms without an API in a visible Chromium you sign in to yourself; stops before Save / Submit'],
'reviews': [() => import('./reviews'), 'list | draft (local reply drafts in .storebound/replies) | send (approved drafts only, asks first)'], 'reviews': [() => import('./reviews'), 'list | draft (local reply drafts in .storebound/replies) | send (approved drafts only, asks first)'],
'originality': [() => import('./originality'), 'Guideline 4.3 check vs your other apps (--against <folders>): listing text, name, icon and screenshot perceptual hashes, project structure; scores, flags, suggestions; offline, exit 1 on a near-duplicate'], 'originality': [() => import('./originality'), 'Guideline 4.3 check vs your other apps (--against <folders>): listing text, name, icon and screenshot perceptual hashes, project structure; scores, flags, suggestions; offline, exit 1 on a near-duplicate'],
'whats-new': [() => import('./whats-new'), 'draft user-facing release notes from git log into the listing files (--since <tag>); --languages a,b: one file per language to translate | check | apply'], 'whats-new': [() => import('./whats-new'), 'draft user-facing release notes from git log into the listing files (--since <tag>); --languages a,b: one file per language to translate | check | apply'],
@ -49,6 +53,7 @@ const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
'play upload': [() => import('./play/upload'), 'upload an AAB to a testing track (--track internal|alpha|beta), versionCode checked first; --dry read-only, asks first'], 'play upload': [() => import('./play/upload'), 'upload an AAB to a testing track (--track internal|alpha|beta), versionCode checked first; --dry read-only, asks first'],
'play status': [() => import('./play/status'), 'tracks, listings, products (read-only)'], 'play status': [() => import('./play/status'), 'tracks, listings, products (read-only)'],
'play rollout': [() => import('./play/rollout'), 'staged rollout: --fraction x | --halt | --resume | --complete (asks first)'], 'play rollout': [() => import('./play/rollout'), 'staged rollout: --fraction x | --halt | --resume | --complete (asks first)'],
'play share': [() => import('./play/share'), 'internal app sharing: upload an AAB / APK, print the share link (asks first; --dry)'],
'play next-version-code': [() => import('./play/next-version-code'), 'next free versionCode (prints the number)'], 'play next-version-code': [() => import('./play/next-version-code'), 'next free versionCode (prints the number)'],
'apple bundle': [() => import('./apple/bundle'), 'register the bundle id; finds the app record'], 'apple bundle': [() => import('./apple/bundle'), 'register the bundle id; finds the app record'],
'apple iap': [() => import('./apple/iap'), 'in-app purchases, localizations, price schedules, availability'], 'apple iap': [() => import('./apple/iap'), 'in-app purchases, localizations, price schedules, availability'],
@ -71,6 +76,7 @@ const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
'apple signing': [() => import('./apple/signing'), 'status | ensure: bundle id capabilities, distribution certificate (key kept in .storebound/signing), App Store profiles installed for Xcode; --dry, asks first'], 'apple signing': [() => import('./apple/signing'), 'status | ensure: bundle id capabilities, distribution certificate (key kept in .storebound/signing), App Store profiles installed for Xcode; --dry, asks first'],
'apple build': [() => import('./apple/build'), 'xcodebuild archive + exportArchive (ExportOptions.plist generated, next build number, API key signing); Capacitor, React Native, Flutter, Unity; --dry'], 'apple build': [() => import('./apple/build'), 'xcodebuild archive + exportArchive (ExportOptions.plist generated, next build number, API key signing); Capacitor, React Native, Flutter, Unity; --dry'],
'apple upload': [() => import('./apple/upload'), 'upload an IPA (App Store Connect API build upload, or --via altool), build number checked, waits for processing; --dry, asks first'], 'apple upload': [() => import('./apple/upload'), 'upload an IPA (App Store Connect API build upload, or --via altool), build number checked, waits for processing; --dry, asks first'],
'apple adhoc': [() => import('./apple/adhoc'), 'ad-hoc / release-testing: devices (list) | register (dry run, asks first) | options (ExportOptions.plist) | export --archive <x.xcarchive>'],
'apple next-build': [() => import('./apple/next-build'), 'next safe build number (prints the number)'], 'apple next-build': [() => import('./apple/next-build'), 'next safe build number (prints the number)'],
'apple encryption': [() => import('./apple/encryption'), 'export compliance answer for builds, from the config'], 'apple encryption': [() => import('./apple/encryption'), 'export compliance answer for builds, from the config'],
'apple ppo': [() => import('./apple/ppo'), 'Product Page Optimization: status | create --variant b | upload --variant b | start | stop (asks first)'], 'apple ppo': [() => import('./apple/ppo'), 'Product Page Optimization: status | create --variant b | upload --variant b | start | stop (asks first)'],

177
cli/lib/adhoc.ts Normal file
View file

@ -0,0 +1,177 @@
// Ad-hoc / release-testing distribution: device list parsing, UDID checks and masking, the register plan, the
// provisioning profile request, ExportOptions.plist and the xcodebuild argv. Pure (no IO), used by cli/apple/adhoc.ts.
// Sources (checked October 2026):
// App Store Connect API, Devices: https://developer.apple.com/documentation/appstoreconnectapi/devices
// Device.Attributes: deviceClass APPLE_VISION_PRO | APPLE_WATCH | IPAD | IPHONE | IPOD | APPLE_TV | MAC,
// status ENABLED | DISABLED, platform BundleIdPlatform (IOS | MAC_OS | UNIVERSAL), name, model, udid, addedDate.
// DeviceCreateRequest.Data.Attributes: name, platform, udid (all required). Devices can only be removed on the
// Apple Developer website.
// Profiles: https://developer.apple.com/documentation/appstoreconnectapi/profiles
// ProfileCreateRequest: attributes name + profileType (IOS_APP_ADHOC, ...), relationships bundleId + certificates
// (required), devices.
// Devices overview (Developer Account Help): up to 100 devices per product family per membership year; disabling a
// device does not give the slot back. https://developer.apple.com/help/account/devices/devices-overview
// `xcodebuild -help` (Xcode 27): -exportOptionsPlist keys method (app-store-connect, release-testing, enterprise,
// debugging, developer-id, mac-application, validation; ad-hoc / development / app-store are the deprecated names),
// teamID, signingStyle (manual | automatic), provisioningProfiles (bundle id -> profile name or UUID), destination
// (export | upload), thinning (<none> ...). compileBitcode is no longer listed (bitcode was removed in Xcode 14),
// so it is not written.
// UDID shapes: Apple documents no format. Accepted here, from what devices report: the legacy 40 hex digits, the
// 8-16 hex form of newer iPhones / iPads and Apple silicon Macs (the "Provisioning UDID"), and for MAC_OS also the
// 8-4-4-4-12 hardware UUID of Intel Macs. This shape check is not from an Apple document.
import { parseCsvRecords } from './csv';
export type DevicePlatform = 'IOS' | 'MAC_OS';
export const DEVICE_PLATFORMS: DevicePlatform[] = ['IOS', 'MAC_OS'];
export const DEVICE_CLASSES = ['IPHONE', 'IPAD', 'IPOD', 'APPLE_WATCH', 'APPLE_TV', 'APPLE_VISION_PRO', 'MAC'] as const;
/** Devices per product family per membership year (Devices overview). */
export const YEARLY_LIMIT = 100;
export type ExportMethod = 'release-testing' | 'ad-hoc';
/** Deprecated ExportOptions method names -> the current ones (`xcodebuild -help`, Xcode 15.3+). */
export const MODERN_METHOD: Record<string, string> = { 'ad-hoc': 'release-testing', development: 'debugging', 'app-store': 'app-store-connect' };
export interface WantedDevice { name: string; udid: string; platform: DevicePlatform }
export interface RegisteredDevice { id: string; name: string; udid: string; platform: string; deviceClass?: string; model?: string | null; status: string }
const LEGACY = /^[0-9a-f]{40}$/i;
const MODERN = /^[0-9a-f]{8}-[0-9a-f]{16}$/i;
const MAC_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export function validUdid(udid: string, platform: DevicePlatform = 'IOS'): boolean {
const u = udid.trim();
return LEGACY.test(u) || MODERN.test(u) || (platform === 'MAC_OS' && MAC_UUID.test(u));
}
/** First 4 + "…" + last 4. Never print a full UDID anywhere (logs, JSON, errors). */
export function maskUdid(udid: string): string {
const u = udid.trim();
return u.length <= 8 ? '…' : `${u.slice(0, 4)}…${u.slice(-4)}`;
}
/** Replaces every UDID-shaped string (and every given UDID) in a message with its masked form: API errors can echo them. */
export function scrubUdids(text: string, known: string[] = []): string {
let s = text;
for (const u of known) if (u.length > 8) s = s.split(u).join(maskUdid(u));
return s.replace(/\b[0-9a-fA-F]{40}\b|\b[0-9a-fA-F]{8}-[0-9a-fA-F]{16}\b|\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b/g, m => maskUdid(m));
}
export function parsePlatform(p: string | undefined): DevicePlatform | null {
const v = (p ?? '').trim().toUpperCase().replace(/[\s-]/g, '_');
if (!v || v === 'IOS' || v === 'IPADOS') return 'IOS';
if (v === 'MAC_OS' || v === 'MACOS' || v === 'MAC') return 'MAC_OS';
return null;
}
/** devices.csv (name, udid, platform; platform optional, default IOS). Errors name the row and the masked UDID. */
export function parseDevicesCsv(text: string): { devices: WantedDevice[]; errors: string[] } {
const devices: WantedDevice[] = [];
const errors: string[] = [];
const seen = new Set<string>();
parseCsvRecords(text).forEach((r, i) => {
const row = i + 2;
const name = (r.name ?? r.device_name ?? '').trim();
const udid = (r.udid ?? r.device_id ?? r.identifier ?? '').trim();
const platform = parsePlatform(r.platform);
if (!udid && !name) return;
if (!name) errors.push(`row ${row}: name is empty`);
if (!platform) errors.push(`row ${row}: platform must be IOS or MAC_OS`);
if (!validUdid(udid, platform ?? 'IOS')) errors.push(`row ${row}: "${maskUdid(udid)}" is not a device UDID (40 hex digits, or 8 hex - 16 hex)`);
const key = udid.toLowerCase();
if (seen.has(key)) errors.push(`row ${row}: ${maskUdid(udid)} is listed twice`);
seen.add(key);
if (name && platform && validUdid(udid, platform)) devices.push({ name, udid, platform });
});
return { devices, errors: [...new Set(errors)] };
}
export interface RegisterPlan {
add: WantedDevice[];
/** Already registered and enabled. */
present: WantedDevice[];
/** Registered but disabled: storebound never enables devices; the owner does it on the developer website. */
disabled: WantedDevice[];
}
/** What a register run would POST: the wanted devices whose UDID is not registered yet (case-insensitive). */
export function planRegister(wanted: WantedDevice[], registered: RegisteredDevice[]): RegisterPlan {
const by = new Map(registered.map(d => [d.udid.toLowerCase(), d] as const));
const plan: RegisterPlan = { add: [], present: [], disabled: [] };
for (const w of wanted) {
const r = by.get(w.udid.toLowerCase());
if (!r) plan.add.push(w);
else if (r.status === 'DISABLED') plan.disabled.push(w);
else plan.present.push(w);
}
return plan;
}
/** Registered devices per device class (enabled and disabled both use a slot of the yearly 100). */
export function slotUsage(registered: RegisteredDevice[]): { deviceClass: string; registered: number; limit: number }[] {
const n = new Map<string, number>();
for (const d of registered) n.set(d.deviceClass ?? 'UNKNOWN', (n.get(d.deviceClass ?? 'UNKNOWN') ?? 0) + 1);
return [...n].sort((a, b) => a[0].localeCompare(b[0])).map(([deviceClass, registered]) => ({ deviceClass, registered, limit: YEARLY_LIMIT }));
}
export function deviceFromApi(d: { id: string; attributes: Record<string, unknown> }): RegisteredDevice {
const a = d.attributes;
return { id: d.id, name: String(a.name ?? ''), udid: String(a.udid ?? ''), platform: String(a.platform ?? ''), deviceClass: a.deviceClass ? String(a.deviceClass) : undefined, model: (a.model as string | null) ?? null, status: String(a.status ?? '') };
}
/** One device as printed (table and --json): the UDID masked. */
export function maskedDevice(d: RegisteredDevice): { id: string; name: string; platform: string; deviceClass: string | null; model: string | null; status: string; udid: string } {
return { id: d.id, name: d.name, platform: d.platform, deviceClass: d.deviceClass ?? null, model: d.model ?? null, status: d.status, udid: maskUdid(d.udid) };
}
export const deviceCreateReq = (d: WantedDevice) => ({ data: { type: 'devices', attributes: { name: d.name, udid: d.udid, platform: d.platform } } });
/** Devices an iOS ad-hoc profile takes: enabled, platform IOS, not Apple TV (tvOS has its own TVOS_APP_ADHOC profiles). */
export const profileDevices = (registered: RegisteredDevice[]): RegisteredDevice[] =>
registered.filter(d => d.status === 'ENABLED' && d.platform === 'IOS' && d.deviceClass !== 'APPLE_TV');
export function profileCreateReq(name: string, bundleIdId: string, certificateIds: string[], deviceIds: string[]) {
return { data: { type: 'profiles', attributes: { name, profileType: 'IOS_APP_ADHOC' },
relationships: {
bundleId: { data: { type: 'bundleIds', id: bundleIdId } },
certificates: { data: certificateIds.map(id => ({ type: 'certificates', id })) },
devices: { data: deviceIds.map(id => ({ type: 'devices', id })) },
} } };
}
/** Distribution certificates usable for an ad-hoc profile: Apple Distribution (DISTRIBUTION) or the older
* iOS Distribution (IOS_DISTRIBUTION), not expired. */
export function usableCertificates(certs: { id: string; attributes: Record<string, unknown> }[], now = new Date()): string[] {
return certs.filter(c => ['DISTRIBUTION', 'IOS_DISTRIBUTION'].includes(String(c.attributes.certificateType))
&& (!c.attributes.expirationDate || new Date(String(c.attributes.expirationDate)) > now)).map(c => c.id);
}
/** An existing profile is current when it is ACTIVE and holds every wanted device. */
export function profileCurrent(state: string | undefined, has: string[], want: string[]): { current: boolean; missing: number } {
const s = new Set(has);
const missing = want.filter(id => !s.has(id)).length;
return { current: state === 'ACTIVE' && missing === 0, missing };
}
export const escapeXml = (s: string): string => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');
export interface ExportOptions { method: string; teamId: string; bundleId?: string; profile?: string }
/** ExportOptions.plist (XML plist, keys sorted like Xcode writes them). Manual signing only with a profile name. */
export function exportOptionsPlist(o: ExportOptions): string {
const str = (k: string, v: string) => `\t<key>${escapeXml(k)}</key>\n\t<string>${escapeXml(v)}</string>\n`;
let body = str('destination', 'export') + str('method', o.method);
if (o.profile) {
if (!o.bundleId) throw new Error('a manual-signing profile needs apple.bundleId');
body += `\t<key>provisioningProfiles</key>\n\t<dict>\n\t\t<key>${escapeXml(o.bundleId)}</key>\n\t\t<string>${escapeXml(o.profile)}</string>\n\t</dict>\n`;
}
body += str('signingStyle', o.profile ? 'manual' : 'automatic') + str('teamID', o.teamId) + str('thinning', '<none>');
return '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n'
+ `<plist version="1.0">\n<dict>\n${body}</dict>\n</plist>\n`;
}
export const exportArgv = (archive: string, plist: string, out: string): string[] =>
['xcodebuild', '-exportArchive', '-archivePath', archive, '-exportOptionsPlist', plist, '-exportPath', out, '-allowProvisioningUpdates'];
/** A command line to print: arguments with shell-special characters single-quoted. */
export const shellLine = (argv: string[]): string => argv.map(a => (/^[\w@%+=:,./-]+$/.test(a) ? a : `'${a.replace(/'/g, `'\\''`)}'`)).join(' ');

251
cli/lib/apple-ads.ts Normal file
View file

@ -0,0 +1,251 @@
// Apple Ads (formerly Apple Search Ads), pure parts: the OAuth client secret (ES256 JWT), request bodies, report row
// flattening, CPA math, the text table and CSV. No IO; the network side is cli/ads/client.ts, the command cli/ads/apple.ts.
//
// storebound targets the Apple Ads Platform API (https://api.ads.apple.com/v1, released August 2026). It supersedes the
// Apple Ads Campaign Management API v5 (api.searchads.apple.com/api/v5), which Apple sunsets on January 26, 2027.
// Same OAuth credentials for both; the Platform API scopes calls by ad account (X-AP-Context: adAccountId=<id>)
// instead of org (orgId=<id>), queries with POST .../query, and wraps every payload in `result`.
//
// Sources (checked October 2026):
// https://developer.apple.com/documentation/apple-ads-platform-api/implementing-oauth-for-the-apple-ads-platform-api
// client secret: header alg ES256 + kid = keyId; claims sub = clientId, iss = teamId, aud https://appleid.apple.com,
// iat, exp (> now, < iat + 180 days). Token: POST https://appleid.apple.com/auth/oauth2/token,
// application/x-www-form-urlencoded grant_type=client_credentials, client_id, client_secret, scope=searchadsorg;
// answer { access_token, token_type: Bearer, expires_in: 3600 }.
// https://developer.apple.com/documentation/apple-ads-platform-api/calling-apple-ads-platform-api (headers, QueryRequest,
// `result` + `pagination` envelope, error codes)
// https://developer.apple.com/documentation/apple-ads-platform-api/access-overview (GET /v1/acls, GET /v1/ad-accounts/{id})
// https://developer.apple.com/documentation/apple-ads-platform-api/useracl (roles)
// https://developer.apple.com/documentation/apple-ads-platform-api/campaign, .../campaignupdate, .../dailybudgetupdate,
// .../money (amounts are decimal strings, currency = the ad account's), .../keyword, .../keywordupdate, .../adgroupupdate
// https://developer.apple.com/documentation/apple-ads-platform-api/reports, .../appsreportingrequest, .../timerange,
// .../appsoptions, .../appsmetrics (localSpend, impressions, taps, ttr, tapInstalls, viewInstalls, totalInstalls,
// totalNewDownloads, totalRedownloads), .../get-app-campaign-reports, .../get-app-keyword-reports, .../reportingkeyword
// https://developer.apple.com/documentation/apple-ads-platform-api/rate-limits (429 + Retry-After)
// https://developer.apple.com/documentation/apple_ads/implementing-oauth-for-the-apple-search-ads-api (v5, deprecation note)
import { createPrivateKey, sign, type KeyObject } from 'node:crypto';
import { toCsv } from './csv';
import { pct, textTable } from './table';
export const ADS_API = 'https://api.ads.apple.com/v1';
export const TOKEN_URL = 'https://appleid.apple.com/auth/oauth2/token';
export const ADS_SCOPE = 'searchadsorg';
export const SECRET_AUDIENCE = 'https://appleid.apple.com';
/** Apple's limit for a client secret's lifetime. storebound signs a fresh one per run with a much shorter one. */
export const MAX_SECRET_TTL = 180 * 86400;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type J = any;
export interface AdsCreds { clientId: string; teamId: string; keyId: string; pem: string; accountId?: string }
const b64 = (b: Buffer | string): string => Buffer.from(b).toString('base64url');
/** The client secret: an ES256 JWT signed with the private key whose public half is uploaded in Apple Ads
* (Account Settings > API). `ttl` seconds, at most 180 days. */
export function clientSecret(c: Pick<AdsCreds, 'clientId' | 'teamId' | 'keyId'>, key: KeyObject | string, now = Math.floor(Date.now() / 1000), ttl = 86400): string {
if (!(ttl > 0 && ttl <= MAX_SECRET_TTL)) throw new Error('client secret lifetime must be 1 s .. 180 days');
const k = typeof key === 'string' ? createPrivateKey(key) : key;
const h = b64(JSON.stringify({ alg: 'ES256', kid: c.keyId }));
const p = b64(JSON.stringify({ sub: c.clientId, iss: c.teamId, aud: SECRET_AUDIENCE, iat: now, exp: now + ttl }));
return `${h}.${p}.${b64(sign('sha256', Buffer.from(`${h}.${p}`), { key: k, dsaEncoding: 'ieee-p1363' }))}`;
}
/** Form body of the token request (client credentials grant). */
export const tokenForm = (clientId: string, secret: string): URLSearchParams =>
new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: secret, scope: ADS_SCOPE });
/** Headers of an API call. GET /v1/acls, /v1/me and /v1/orgs/{id} work without the ad account context. */
export function adsHeaders(token: string, accountId?: string): Record<string, string> {
const h: Record<string, string> = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', Accept: 'application/json' };
if (accountId) h['X-AP-Context'] = `adAccountId=${accountId}`;
return h;
}
// ---------------------------------------------------------------------------------------------------------------------
// Accounts and campaigns
export interface AclRow { accountId: string; name: string; orgId: string; roles: string[]; used: boolean }
/** GET /v1/acls -> rows; `used` marks the configured APPLE_ADS_ACCOUNT_ID. */
export function aclRows(res: J, accountId?: string): AclRow[] {
const acls: J[] = res?.result?.acls ?? [];
return acls.map(a => ({ accountId: String(a.adAccount?.id ?? ''), name: String(a.adAccount?.name ?? ''), orgId: String(a.adAccount?.orgId ?? ''),
roles: (a.roles ?? []).map(String), used: !!accountId && String(a.adAccount?.id) === accountId }));
}
/** Roles that may change bids, budgets and status (useracl roles reference). */
export const canWrite = (roles: string[]): boolean => roles.some(r => r === 'Admin' || r === 'API Account Manager' || r === 'Limited Access: API Read & Write');
export interface CampaignRow {
id: string; name: string; status: string; displayStatus: string; systemStatus: string; dailyBudget: string; currency: string;
countries: string[]; adamId: string; bidStrategy: string; thisApp: boolean;
}
export function campaignRow(c: J, appId?: string): CampaignRow {
const adamId = c.promotedObjectType === 'APPSTORE_APP' || c.promotedObjectType === undefined ? String(c.promotedObjectId ?? '') : '';
return {
id: String(c.id), name: String(c.name ?? ''), status: String(c.status ?? ''), displayStatus: String(c.displayStatus ?? ''),
systemStatus: String(c.systemStatus ?? ''), dailyBudget: String(c.dailyBudget?.value?.amount ?? ''), currency: String(c.dailyBudget?.value?.currency ?? ''),
countries: (c.targeting?.countryOrRegion?.include ?? []).map(String), adamId, bidStrategy: String(c.bidStrategy?.bidStrategyType ?? ''),
thisApp: !!appId && adamId === String(appId),
};
}
/** POST /v1/campaigns/query body: App Store campaigns only, by id, one page (the endpoint caps pageSize at 1000). */
export const campaignQuery = (offset = 0, pageSize = 1000): J => ({
filters: [{ field: 'promotedObjectType', operator: 'EQUALS', value: 'APPSTORE_APP' }],
sorting: [{ field: 'id', order: 'ASC' }],
pagination: { offset, pageSize, fetchTotalCount: true },
});
// ---------------------------------------------------------------------------------------------------------------------
// Reports
const DAY = /^\d{4}-\d{2}-\d{2}$/;
const iso = (d: Date) => d.toISOString().slice(0, 10);
/** --days N (ending yesterday, UTC: today is still incomplete) or --start / --end (inclusive). */
export function reportWindow(o: { days?: number; start?: string; end?: string }, today = new Date()): { start: string; end: string } {
if (o.start || o.end) {
if (!o.start || !o.end || !DAY.test(o.start) || !DAY.test(o.end)) throw new Error('--start and --end: both, as YYYY-MM-DD');
if (o.start > o.end) throw new Error('--start is after --end');
return { start: o.start, end: o.end };
}
const days = o.days ?? 7;
if (!Number.isInteger(days) || days < 1 || days > 365) throw new Error('--days: 1..365');
const end = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate() - 1));
const start = new Date(end.getTime() - (days - 1) * 86400_000);
return { start: iso(start), end: iso(end) };
}
/**
* AppsReportingRequest for POST /v1/reports/apps/{campaigns|keywords}/query. Every apps report needs a campaignId
* filter (scalar EQUALS, as in Apple's payload examples); keywords can be narrowed by adGroupId. No granularity: one
* total per row over the window. UTC, sorted by spend.
*/
export function reportBody(o: { start: string; end: string; campaignId: string; adGroupId?: string; offset?: number; pageSize?: number }): J {
const filters: J[] = [{ field: 'campaignId', operator: 'EQUALS', value: String(o.campaignId) }];
if (o.adGroupId) filters.push({ field: 'adGroupId', operator: 'EQUALS', value: String(o.adGroupId) });
return {
pagination: { offset: o.offset ?? 0, pageSize: o.pageSize ?? 1000 },
sorting: [{ field: 'localSpend', order: 'DESC' }],
filters,
timeRange: { start: o.start, end: o.end, timeZone: 'UTC' },
options: { includeRows: ['GRAND_TOTAL'] },
};
}
export interface ReportRow {
level: 'campaign' | 'keyword';
campaignId: string; campaign: string;
adGroupId: string; adGroup: string;
keywordId: string; keyword: string; matchType: string;
currency: string; spend: number;
impressions: number; taps: number; installs: number; tapInstalls: number; viewInstalls: number; newDownloads: number; redownloads: number;
/** taps / impressions */ ttr: number | null;
/** installs / taps */ conversionRate: number | null;
/** spend / installs; null with 0 installs */ cpa: number | null;
/** spend / taps */ avgCpt: number | null;
}
const num = (x: unknown): number => { const n = Number(x ?? 0); return Number.isFinite(n) ? n : 0; };
const ratio = (a: number, b: number): number | null => (b > 0 ? a / b : null);
const cents = (x: number): number => Math.round(x * 100) / 100;
/** Derived metrics from the counts (the same definitions Apple documents for ttr / totalInstallRate). */
export function derive<T extends { spend: number; impressions: number; taps: number; installs: number }>(r: T): T & Pick<ReportRow, 'ttr' | 'conversionRate' | 'cpa' | 'avgCpt'> {
return { ...r, ttr: ratio(r.taps, r.impressions), conversionRate: ratio(r.installs, r.taps), cpa: ratio(r.spend, r.installs), avgCpt: ratio(r.spend, r.taps) };
}
function metrics(m: J): Pick<ReportRow, 'currency' | 'spend' | 'impressions' | 'taps' | 'installs' | 'tapInstalls' | 'viewInstalls' | 'newDownloads' | 'redownloads'> {
const tapInstalls = num(m?.tapInstalls), viewInstalls = num(m?.viewInstalls);
return {
currency: String(m?.localSpend?.currency ?? ''), spend: cents(num(m?.localSpend?.amount)),
impressions: num(m?.impressions), taps: num(m?.taps),
// totalInstalls = tap + view installs; older rows may only carry the two parts
installs: m?.totalInstalls !== undefined ? num(m.totalInstalls) : tapInstalls + viewInstalls,
tapInstalls, viewInstalls, newDownloads: num(m?.totalNewDownloads), redownloads: num(m?.totalRedownloads),
};
}
/** Report response rows -> flat rows. `campaignNames` fills the campaign name of keyword rows. */
export function flattenRows(level: ReportRow['level'], res: J, campaignNames: Map<string, string> = new Map()): ReportRow[] {
const rows: J[] = res?.result?.rows ?? [];
return rows.map(r => {
const md = r.metadata ?? {};
const campaignId = String(level === 'campaign' ? md.id ?? '' : md.campaignId ?? '');
return derive({
level, campaignId,
campaign: level === 'campaign' ? String(md.name ?? '') : campaignNames.get(campaignId) ?? '',
adGroupId: level === 'keyword' ? String(md.adGroupId ?? '') : '', adGroup: level === 'keyword' ? String(md.adGroup?.name ?? '') : '',
keywordId: level === 'keyword' ? String(md.id ?? '') : '', keyword: level === 'keyword' ? String(md.text ?? '') : '', matchType: level === 'keyword' ? String(md.matchType ?? '') : '',
...metrics(r.totalMetrics),
});
});
}
/** Offset of the next page, or null on the last one (offset paging). */
export const nextOffset = (res: J): number | null => {
const p = res?.pagination;
if (!p || typeof p.totalCount !== 'number') return null;
const next = num(p.offset) + num(p.pageSize);
return next < p.totalCount && num(p.pageSize) > 0 ? next : null;
};
export type ReportTotals = Omit<ReportRow, 'level' | 'campaignId' | 'campaign' | 'adGroupId' | 'adGroup' | 'keywordId' | 'keyword' | 'matchType'>;
export function totals(rows: ReportRow[]): ReportTotals {
const cur = [...new Set(rows.map(r => r.currency).filter(Boolean))];
const sum = (k: 'spend' | 'impressions' | 'taps' | 'installs' | 'tapInstalls' | 'viewInstalls' | 'newDownloads' | 'redownloads') => rows.reduce((a, r) => a + r[k], 0);
return derive({
currency: cur.length === 1 ? cur[0]! : cur.length ? 'mixed' : '', spend: cents(sum('spend')),
impressions: sum('impressions'), taps: sum('taps'), installs: sum('installs'), tapInstalls: sum('tapInstalls'), viewInstalls: sum('viewInstalls'),
newDownloads: sum('newDownloads'), redownloads: sum('redownloads'),
});
}
const money = (x: number | null, cur = ''): string => (x === null ? 'n/a' : `${x.toFixed(2)}${cur ? ' ' + cur : ''}`);
export function reportTable(rows: ReportRow[], t: ReportTotals): string {
const kw = rows.some(r => r.level === 'keyword');
const head = [...(kw ? ['keyword', 'match', 'ad group'] : []), 'campaign', 'spend', 'impr', 'taps', 'installs', 'TTR', 'CR', 'CPA', 'avg CPT'];
const line = (r: ReportRow | ReportTotals, lead: string[]) => [...lead, money(r.spend, r.currency), r.impressions, r.taps, r.installs, pct(r.ttr), pct(r.conversionRate), money(r.cpa), money(r.avgCpt)];
return textTable(head, [
...rows.map(r => line(r, [...(kw ? [r.keyword, r.matchType, r.adGroup || r.adGroupId] : []), r.campaign || r.campaignId])),
line(t, [...(kw ? ['', '', ''] : []), 'TOTAL']),
]);
}
export const CSV_HEAD = ['level', 'campaign_id', 'campaign', 'ad_group_id', 'ad_group', 'keyword_id', 'keyword', 'match_type', 'currency', 'spend', 'impressions', 'taps',
'installs', 'tap_installs', 'view_installs', 'new_downloads', 'redownloads', 'ttr', 'conversion_rate', 'cpa', 'avg_cpt'];
const dec = (x: number | null, d: number): string => (x === null ? '' : x.toFixed(d));
/** One CSV line per row (empty cells for "no value": CPA with 0 installs). Rates as fractions (0.0123). */
export function reportCsv(rows: ReportRow[]): string {
return toCsv([CSV_HEAD, ...rows.map(r => [r.level, r.campaignId, r.campaign, r.adGroupId, r.adGroup, r.keywordId, r.keyword, r.matchType, r.currency, r.spend.toFixed(2),
r.impressions, r.taps, r.installs, r.tapInstalls, r.viewInstalls, r.newDownloads, r.redownloads, dec(r.ttr, 6), dec(r.conversionRate, 6), dec(r.cpa, 2), dec(r.avgCpt, 2)])]);
}
// ---------------------------------------------------------------------------------------------------------------------
// Writes (bid, budget, pause): the bodies and the "old -> new" line. The command reads first, prints, asks.
/** An amount as the API wants it: a positive decimal string, no leading zeros, at most 2 decimals ("5.00", not "05.00"). */
export function parseAmount(v: string | undefined, what: string): string {
const s = (v ?? '').trim();
if (!/^(0|[1-9]\d*)(\.\d{1,2})?$/.test(s) || !(Number(s) > 0)) throw new Error(`${what}: a positive amount like 1.25 (account currency, max 2 decimals)`);
return s;
}
/** "1.50 -> 2.00 USD (+33%)" */
export function changeLine(oldAmount: string | null, newAmount: string, currency: string): string {
if (oldAmount === null) return `(default) -> ${newAmount} ${currency}`;
const o = Number(oldAmount), n = Number(newAmount);
const d = o > 0 ? ` (${n >= o ? '+' : ''}${Math.round(((n - o) / o) * 100)}%)` : '';
return `${oldAmount} -> ${newAmount} ${currency}${d}`;
}
export const keywordBidBody = (amount: string, currency: string): J => ({ bid: { amount, currency } });
export const dailyBudgetBody = (amount: string, currency: string): J => ({ dailyBudget: { value: { amount, currency } } });
export const pauseBody = (): J => ({ status: 'PAUSED' });

View file

@ -475,6 +475,10 @@ export interface ShipConfig {
}; };
apple?: { apple?: {
bundleId: string; appId?: string; primaryLocale?: string; listing?: string; info?: AppleAppInfo; reviewShots?: string; bundleId: string; appId?: string; primaryLocale?: string; listing?: string; info?: AppleAppInfo; reviewShots?: string;
/** Apple Developer Team ID (10 characters, Membership details). apple-app-site-association and ad-hoc export use it. */
teamId?: string;
/** Ad-hoc / release-testing export (`storebound apple adhoc`). */
adhoc?: AdhocConfig;
/** /**
* Export compliance answer for every build (`storebound apple encryption`, `validate`). false ONLY when the app uses * Export compliance answer for every build (`storebound apple encryption`, `validate`). false ONLY when the app uses
* no encryption beyond what the OS provides (HTTPS / TLS through the system, standard auth). Never set it to false * no encryption beyond what the OS provides (HTTPS / TLS through the system, standard auth). Never set it to false
@ -510,6 +514,8 @@ export interface ShipConfig {
subscriptions?: SubscriptionGroup[]; subscriptions?: SubscriptionGroup[];
/** Price sheet for `storebound prices export | import` (product x store x region). */ /** Price sheet for `storebound prices export | import` (product x store x region). */
prices?: { prices?: {
/** Purchasing power parity proposals (`storebound prices ppp`). */
ppp?: PppConfig;
/** CSV path. Default store/prices.csv. */ /** CSV path. Default store/prices.csv. */
csv?: string; csv?: string;
/** App Store base territory of every price schedule (alpha-3). Default: the current one, else USA. */ /** App Store base territory of every price schedule (alpha-3). Default: the current one, else USA. */
@ -530,6 +536,132 @@ export interface ShipConfig {
/** `storebound originality`: the owner's other apps to compare with (folders with a storebound.config.ts, or a /** `storebound originality`: the owner's other apps to compare with (folders with a storebound.config.ts, or a
* workspace folder holding several), and the score above which a pair is flagged. */ * workspace folder holding several), and the score above which a pair is flagged. */
originality?: OriginalityConfig; originality?: OriginalityConfig;
/** Universal links / app links files, Smart App Banner and a landing page (`storebound web init | check`). */
web?: WebConfig;
/** Optional RevenueCat project the catalog is mirrored into (`storebound revenuecat diff | sync`). */
revenuecat?: RevenueCatConfig;
/** Owner answers for console forms that have no API (`storebound console fill`); only what the rest of the config
* cannot prove. Anything left out stays empty and highlighted in the page. */
console?: ConsoleConfig;
}
// ---- growth extras ----
export interface PppConfig {
/** Dataset: worldbank (bundled World Bank ICP PPP factors, default), bigmac (The Economist Big Mac index, downloaded to .storebound/ by `prices ppp --update-bigmac`) or file (`file`). */
source?: 'worldbank' | 'bigmac' | 'file';
/** CSV for source "file": region (ISO alpha-2), factor (local currency per US dollar at PPP), currency, fx (market rate, optional). */
file?: string;
/** Lowest price as a share of the US price after the PPP adjustment (default 0.3). */
floor?: number;
/** Highest share of the US price (default 1.2). */
ceiling?: number;
/** Price sheet the proposal is written to (default store/prices-ppp.csv). */
out?: string;
}
export interface WebConfig {
/** Domain that serves the files, e.g. "example.com" (no scheme, no path). */
domain: string;
/** Paths the apps open as universal links / app links (AASA components, Android intent filter). Default ["/*"]. */
paths?: string[];
/** Paths that must stay in the browser (AASA "exclude": true components). */
exclude?: string[];
/** Folder the generated files are written to (default "web"); deploy its contents to the domain root. */
out?: string;
/** Play app signing certificate SHA-256 fingerprints (AB:CD:... ; Play Console > Test and release > App signing). */
androidSha256?: string[];
/** Also list the app under "webcredentials" (password AutoFill) in apple-app-site-association. */
webcredentials?: boolean;
/** Write the minimal landing page template (index.html with store badges, privacy and support links). */
landing?: boolean;
}
export interface AdhocConfig {
/** ExportOptions.plist method: release-testing (Xcode 15.3+ name) or ad-hoc (older Xcode). Default release-testing. */
method?: 'release-testing' | 'ad-hoc';
/** Devices CSV (name, udid, platform) in .storebound/ (gitignored: device ids are personal data). Default .storebound/devices.csv. */
devices?: string;
/** Provisioning profile name for manual signing (default: automatic signing). */
profile?: string;
}
export interface RevenueCatConfig {
/** RevenueCat project id (Project settings), e.g. "proj1ab2c3d4". */
projectId: string;
/** RevenueCat app ids of the App Store and Play Store apps in that project (Project settings > Apps). */
apps?: { apple?: string; play?: string };
/** Entitlement lookup key -> product / subscription ids that unlock it. Default: "pro" with every non-consumable,
* non-renewing product and subscription. */
entitlements?: Record<string, string[]>;
/** Lookup key of the offering storebound keeps in sync (default "default"). */
offering?: string;
}
/** IARC questionnaire topics storebound knows (Play Console > Policy > App content > Content rating). */
export const IARC_QUESTIONS = ['violence', 'fear', 'sexuality', 'language', 'controlledSubstances', 'crudeHumor', 'gambling', 'simulatedGambling',
'lootBoxes', 'userInteraction', 'sharesLocation', 'digitalPurchases', 'unrestrictedInternet'] as const;
export type IarcQuestion = typeof IARC_QUESTIONS[number];
/** IARC app categories (the first page of the questionnaire). */
export const RATING_CATEGORIES = ['game', 'social', 'other'] as const;
/** Play target age groups (Target audience and content > Target age). */
export const AGE_GROUPS = ['5-under', '6-8', '9-12', '13-15', '16-17', '18-over'] as const;
export type AgeGroup = typeof AGE_GROUPS[number];
export interface ConsoleConfig {
/** App Store Connect > Apps > + > New App: the SKU (internal, never shown) and who in the team sees the app. */
appRecord?: { sku?: string; userAccess?: 'full' | 'limited' };
/** Play IARC questionnaire: the category and the answers you decided (true = Yes). */
contentRating?: { category?: typeof RATING_CATEGORIES[number]; answers?: Partial<Record<IarcQuestion, boolean>> };
/** Play Target audience and content, and the Ads declaration. */
targetAudience?: { ages?: AgeGroup[]; appealsToChildren?: boolean; containsAds?: boolean };
}
const DOMAIN_RE = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
const SHA256_RE = /^([0-9A-F]{2}:){31}[0-9A-F]{2}$/;
/** Problems of the growth-extras sections (web, revenuecat, prices.ppp, apple.teamId / adhoc). Pure. */
export function validateExtras(cfg: Partial<ShipConfig>): string[] {
const e: string[] = [];
if (cfg.apple?.teamId !== undefined && !/^[A-Z0-9]{10}$/.test(cfg.apple.teamId)) e.push('apple.teamId: the 10-character Team ID (Membership details)');
const ad = cfg.apple?.adhoc;
if (ad?.method !== undefined && ad.method !== 'release-testing' && ad.method !== 'ad-hoc') e.push('apple.adhoc.method: release-testing | ad-hoc');
const ppp = cfg.prices?.ppp;
if (ppp) {
if (ppp.source !== undefined && !['worldbank', 'bigmac', 'file'].includes(ppp.source)) e.push('prices.ppp.source: worldbank | bigmac | file');
if (ppp.source === 'file' && !ppp.file) e.push('prices.ppp.file: needed with source "file"');
for (const k of ['floor', 'ceiling'] as const) if (ppp[k] !== undefined && !(typeof ppp[k] === 'number' && ppp[k]! > 0 && ppp[k]! <= 5)) e.push(`prices.ppp.${k}: a share of the US price, e.g. 0.3`);
if (ppp.floor !== undefined && ppp.ceiling !== undefined && ppp.floor > ppp.ceiling) e.push('prices.ppp: floor is above ceiling');
}
const w = cfg.web;
if (w) {
if (!DOMAIN_RE.test(w.domain ?? '')) e.push('web.domain: a domain name like example.com (no https://, no path)');
for (const p of [...(w.paths ?? []), ...(w.exclude ?? [])]) if (typeof p !== 'string' || !p.startsWith('/')) e.push(`web.paths: "${p}" must start with /`);
for (const f of w.androidSha256 ?? []) if (!SHA256_RE.test(f)) e.push(`web.androidSha256: "${f}" is not a SHA-256 fingerprint (32 hex pairs, AB:CD:...)`);
}
const rc = cfg.revenuecat;
if (rc) {
if (!/^[A-Za-z0-9_-]{4,64}$/.test(rc.projectId ?? '')) e.push('revenuecat.projectId: the RevenueCat project id (Project settings)');
for (const [k, ids] of Object.entries(rc.entitlements ?? {})) {
if (!/^[A-Za-z0-9._-]{1,200}$/.test(k)) e.push(`revenuecat.entitlements.${k}: letters, digits, ".", "_", "-"`);
if (!Array.isArray(ids) || !ids.length) e.push(`revenuecat.entitlements.${k}: at least one product id`);
}
if (rc.offering !== undefined && !/^[A-Za-z0-9._-]{1,200}$/.test(rc.offering)) e.push('revenuecat.offering: letters, digits, ".", "_", "-"');
}
if (cfg.console) e.push(...validateConsole(cfg.console));
return e;
}
function validateConsole(c: ConsoleConfig): string[] {
const e: string[] = [];
const r = c.appRecord, cr = c.contentRating, ta = c.targetAudience;
if (r?.sku !== undefined && !/^[A-Za-z0-9._-]{1,100}$/.test(r.sku)) e.push('console.appRecord.sku: letters, digits, ".", "_", "-" (it can never change)');
if (r?.userAccess !== undefined && r.userAccess !== 'full' && r.userAccess !== 'limited') e.push('console.appRecord.userAccess: full | limited');
if (cr?.category !== undefined && !RATING_CATEGORIES.includes(cr.category)) e.push(`console.contentRating.category: one of ${RATING_CATEGORIES.join(', ')}`);
for (const [k, v] of Object.entries(cr?.answers ?? {})) if (!(IARC_QUESTIONS as readonly string[]).includes(k) || typeof v !== 'boolean') e.push(`console.contentRating.answers.${k}: one of ${IARC_QUESTIONS.join(', ')}, true | false`);
for (const a of ta?.ages ?? []) if (!AGE_GROUPS.includes(a)) e.push(`console.targetAudience.ages: "${a}" is not one of ${AGE_GROUPS.join(', ')}`);
for (const k of ['appealsToChildren', 'containsAds'] as const) if (ta?.[k] !== undefined && typeof ta[k] !== 'boolean') e.push(`console.targetAudience.${k}: true | false`);
return e;
} }
/** Platforms of the app (app identity): app.platforms, else from the store sections. */ /** Platforms of the app (app identity): app.platforms, else from the store sections. */
@ -683,6 +815,7 @@ export function validateConfig(c: unknown): string[] {
if (v.record) e.push(...validateRecord(v.record, s.capture)); if (v.record) e.push(...validateRecord(v.record, s.capture));
} }
} }
e.push(...validateExtras(cfg));
if (cfg.icons) { if (cfg.icons) {
if (!cfg.icons.composite) e.push('icons.composite: missing'); if (!cfg.icons.composite) e.push('icons.composite: missing');
if (!cfg.icons.out) e.push('icons.out: missing'); if (!cfg.icons.out) e.push('icons.out: missing');

231
cli/lib/console-answers.ts Normal file
View file

@ -0,0 +1,231 @@
// Answers for console forms that have no API (`storebound console fill <form>`), built from the config only. Pure.
// AGENTS.md rule 5: an answer is `certain` only when the config proves it; everything else has value null, stays EMPTY
// in the page, is highlighted and is listed for the owner. Forms:
// apple-app-record App Store Connect > Apps > + > New App
// apple-age-rating guide only: `storebound apple appinfo` sets every question through the API
// apple-app-privacy App Store Connect > the app > App Privacy (no API)
// play-content-rating Play Console > Policy > App content > Content rating (IARC questionnaire)
// play-target-audience Play Console > Policy > App content > Target audience and content (+ the Ads declaration)
// Sources (checked October 2026):
// https://developer.apple.com/help/app-store-connect/create-an-app-record/add-a-new-app
// https://developer.apple.com/help/app-store-connect/manage-app-information/manage-app-privacy
// https://developer.apple.com/app-store/app-privacy-details/ (data types, purposes)
// https://developer.apple.com/tutorials/data/documentation/appstoreconnectapi/ageratingdeclaration/attributes-data.dictionary.json
// https://support.google.com/googleplay/android-developer/answer/9859655 (content ratings)
// https://support.google.com/googleplay/android-developer/answer/9867159 (target audience and content)
import { AGE_RATING_NONE } from '../apple/appinfo';
import { type AgeGroup, AGE_GROUPS, IARC_QUESTIONS, type IarcQuestion, profileOf, type ShipConfig } from './config';
import { APPLE_PRIVACY, applePurpose } from './declarations';
import { maskUser } from './credentials';
export const FORM_IDS = ['apple-app-record', 'apple-age-rating', 'apple-app-privacy', 'play-content-rating', 'play-target-audience'] as const;
export type FormId = typeof FORM_IDS[number];
export type Store = 'apple' | 'play';
export type AnswerValue = string | boolean | null;
export interface Answer { id: string; label: string; value: AnswerValue; certain: boolean; source: string; note?: string }
export interface FormMeta {
id: FormId; store: Store; title: string; url: string;
/** What the owner clicks to open the form (no deep link exists, or it needs ids the config does not have). */
open: string[];
/** The control storebound stops before; the owner presses it. */
stopBefore: string;
/** false: no page filling at all, guidance only (the API covers it). */
fillable: boolean;
}
/** The `--dry --json` result (and the head of a fill run's result). */
export interface ConsoleResult { form: FormId; store: Store; title: string; url: string; answers: Answer[]; uncertain: number; guidance: string[] }
export const DISCLAIMER = [
'storebound console fill is AI-assisted autofill. Console pages change without notice and it may misplace an answer.',
'Review every field yourself. storebound never saves, submits or publishes: you press the final button.',
'storebound never types passwords or touches sign-in pages: you sign in in the browser window yourself.',
];
const ASC = 'https://appstoreconnect.apple.com';
const PLAY = 'https://play.google.com/console';
export const isForm = (s: string | undefined): s is FormId => !!s && (FORM_IDS as readonly string[]).includes(s);
export function formMeta(id: FormId, config: ShipConfig): FormMeta {
const app = config.apple?.appId ? `${ASC}/apps/${config.apple.appId}` : `${ASC}/apps`;
const pickApp = 'Pick the developer account and the app if Play Console asks';
switch (id) {
case 'apple-app-record': return { id, store: 'apple', title: 'App Store Connect: New App', url: `${ASC}/apps`, stopBefore: 'Create', fillable: true,
open: ['Apps > the add button (+) at the top left > New App'] };
case 'apple-age-rating': return { id, store: 'apple', title: 'App Store Connect: Age Ratings', url: app, stopBefore: 'Save', fillable: false,
open: ['General > App Information > Age Ratings > Set Up Age Ratings (only to look: `storebound apple appinfo` sets it)'] };
case 'apple-app-privacy': return { id, store: 'apple', title: 'App Store Connect: App Privacy', url: app, stopBefore: 'Publish', fillable: true,
open: [...(config.apple?.appId ? [] : ['Open the app (apple.appId is not in the config, so storebound cannot open it for you)']), 'App Privacy in the sidebar > Get Started (or Edit next to Data Types)'] };
case 'play-content-rating': return { id, store: 'play', title: 'Play Console: Content rating (IARC)', url: PLAY, stopBefore: 'Submit', fillable: true,
open: [pickApp, 'Policy > App content > Content rating > Start (or Start new questionnaire)'] };
case 'play-target-audience': return { id, store: 'play', title: 'Play Console: Target audience and content', url: PLAY, stopBefore: 'Save', fillable: true,
open: [pickApp, 'Policy > App content > Target audience and content > Start (or Manage); the Ads declaration is App content > Ads'] };
}
}
const ok = (id: string, label: string, value: AnswerValue, source: string, note?: string): Answer => ({ id, label, value, certain: true, source, ...(note ? { note } : {}) });
const ask = (id: string, label: string, source: string, note: string): Answer => ({ id, label, value: null, certain: false, source, note });
/** App Store Connect primary language names for the common locales (the dialog shows names, not codes). */
const LANGUAGE_NAMES: Record<string, string> = {
'en-US': 'English (U.S.)', 'en-GB': 'English (U.K.)', 'en-AU': 'English (Australia)', 'en-CA': 'English (Canada)', 'de-DE': 'German', 'fr-FR': 'French',
'fr-CA': 'French (Canada)', 'es-ES': 'Spanish (Spain)', 'es-MX': 'Spanish (Mexico)', 'it': 'Italian', 'ja': 'Japanese', 'ko': 'Korean', 'pt-BR': 'Portuguese (Brazil)',
'pt-PT': 'Portuguese (Portugal)', 'nl-NL': 'Dutch', 'ru': 'Russian', 'tr': 'Turkish', 'zh-Hans': 'Chinese (Simplified)', 'zh-Hant': 'Chinese (Traditional)',
};
function appRecord(config: ShipConfig): Answer[] {
const a = config.apple, r = config.console?.appRecord;
const locale = a?.primaryLocale ?? config.languages.find(l => l.apple)?.apple;
const lang = locale ? LANGUAGE_NAMES[locale] : undefined;
return [
a ? ok('platform:ios', 'Platforms: iOS', true, 'apple section') : ask('platform:ios', 'Platforms: iOS', 'config', 'The config has no apple section.'),
ok('name', 'Name', config.app.name, 'app.name', 'Must be unique on the App Store; App Store Connect says so when it is taken.'),
lang ? ok('language', 'Primary Language', lang, a?.primaryLocale ? 'apple.primaryLocale' : 'languages[0].apple')
: ask('language', 'Primary Language', 'apple.primaryLocale', locale ? `Pick the language of locale "${locale}".` : 'Set apple.primaryLocale (e.g. en-US).'),
a?.bundleId ? ok('bundleId', 'Bundle ID', a.bundleId, 'apple.bundleId', 'Register it first if it is not in the list: storebound apple bundle.')
: ask('bundleId', 'Bundle ID', 'apple.bundleId', 'Set apple.bundleId.'),
r?.sku ? ok('sku', 'SKU', r.sku, 'console.appRecord.sku')
: ask('sku', 'SKU', 'console.appRecord.sku', `Your internal id, never shown and never changeable (for example ${a?.bundleId ?? 'the bundle id'}). Set console.appRecord.sku to have it filled.`),
r?.userAccess ? ok('access', 'User Access', r.userAccess, 'console.appRecord.userAccess')
: ask('access', 'User Access', 'console.appRecord.userAccess', 'Full Access (everyone in your team) or Limited Access (pick the users).'),
];
}
/** Every question of the API's ageRatingDeclarations (checked October 2026); appinfo.ts AGE_RATING_NONE plus the newer ones. */
export const AGE_RATING_API = [...new Set([...Object.keys(AGE_RATING_NONE), 'socialMedia', 'socialMediaAgeRestricted'])];
function ageRating(config: ShipConfig): Answer[] {
const o = config.apple?.info?.ageRating;
return AGE_RATING_API.map(q => {
if (o && q in o) return ok(q, q, o[q] ?? 'none', `apple.info.ageRating.${q}`);
if (!(q in AGE_RATING_NONE)) return ask(q, q, `apple.info.ageRating.${q}`, 'storebound apple appinfo does not send this one unless you set it in apple.info.ageRating; App Store Connect asks it.');
const none = AGE_RATING_NONE[q] ?? 'none';
return o ? ok(q, q, none, 'apple.info.ageRating (not overridden)')
: ask(q, q, 'apple.info.ageRating', `storebound apple appinfo answers ${String(none)} unless you set apple.info.ageRating; confirm that is true.`);
});
}
/** App Privacy data types (App privacy details on the App Store), in Apple's order: [category, type]. */
export const APPLE_DATA_TYPES: [string, string][] = [
['Contact Info', 'Name'], ['Contact Info', 'Email Address'], ['Contact Info', 'Phone Number'], ['Contact Info', 'Physical Address'], ['Contact Info', 'Other User Contact Info'],
['Health & Fitness', 'Health'], ['Health & Fitness', 'Fitness'], ['Financial Info', 'Payment Info'], ['Financial Info', 'Credit Info'], ['Financial Info', 'Other Financial Info'],
['Location', 'Precise Location'], ['Location', 'Coarse Location'], ['Sensitive Info', 'Sensitive Info'], ['Contacts', 'Contacts'],
['User Content', 'Emails or Text Messages'], ['User Content', 'Photos or Videos'], ['User Content', 'Audio Data'], ['User Content', 'Gameplay Content'],
['User Content', 'Customer Support'], ['User Content', 'Other User Content'], ['Browsing History', 'Browsing History'], ['Search History', 'Search History'],
['Identifiers', 'User ID'], ['Identifiers', 'Device ID'], ['Purchases', 'Purchase History'], ['Usage Data', 'Product Interaction'], ['Usage Data', 'Advertising Data'],
['Usage Data', 'Other Usage Data'], ['Diagnostics', 'Crash Data'], ['Diagnostics', 'Performance Data'], ['Diagnostics', 'Other Diagnostic Data'],
['Surroundings', 'Environment Scanning'], ['Body', 'Hands'], ['Body', 'Head'], ['Other Data', 'Other Data Types'],
];
export const APPLE_PURPOSES = ['Third-Party Advertising', 'Developer\'s Advertising or Marketing', 'Analytics', 'Product Personalization', 'App Functionality', 'Other Purposes'];
/** Apple data types the config's Data safety answers say are collected: type -> { from, purposes }. */
export function privacyTypes(config: ShipConfig): Map<string, { from: string[]; purposes: Set<string> }> {
const m = new Map<string, { from: string[]; purposes: Set<string> }>();
for (const [id, u] of Object.entries(config.dataSafety?.data ?? {})) {
const name = APPLE_PRIVACY[id]?.[1] ?? 'Other Data Types';
const e = m.get(name) ?? { from: [], purposes: new Set<string>() };
e.from.push(id);
for (const p of u.collect) e.purposes.add(applePurpose(p, false));
for (const p of u.shared ? u.share ?? [] : []) e.purposes.add(applePurpose(p, true));
m.set(name, e);
}
return m;
}
function appPrivacy(config: ShipConfig): Answer[] {
const ds = config.dataSafety;
const label = 'Do you or your third-party partners collect data from this app?';
if (!ds) return [ask('collects', label, 'dataSafety', 'The config has no dataSafety answers: answer what the app and every SDK collect (store-declarations skill), then rerun.')];
const out: Answer[] = [ok('collects', label, ds.collectsData, 'dataSafety.collectsData')];
if (!ds.collectsData) return out;
const got = privacyTypes(config);
const mapped = new Set(Object.values(APPLE_PRIVACY).map(([, n]) => n));
for (const [cat, name] of APPLE_DATA_TYPES) {
const g = got.get(name), id = `type:${name}`, l = `Data type: ${cat} > ${name}`;
if (g && name === 'Other Data Types') out.push(ask(id, l, `dataSafety.data.${g.from.join(', ')}`, `${g.from.join(', ')} has no exact App Store type: decide where it belongs.`));
else if (g) out.push(ok(id, l, true, `dataSafety.data.${g.from.join(', ')}`));
else if (mapped.has(name)) out.push(ok(id, l, false, 'dataSafety.data (not listed)'));
else out.push(ask(id, l, 'none', name === 'Advertising Data' ? 'No Play Data safety equivalent; ad SDKs usually collect it: check each SDK\'s privacy disclosure.' : 'No Play Data safety equivalent: decide from the app and its SDKs.'));
}
for (const [name, g] of got) {
if (name === 'Other Data Types') continue;
for (const p of APPLE_PURPOSES) out.push(ok(`purpose:${name}:${p}`, `${name}: purpose ${p}`, g.purposes.has(p), `dataSafety.data.${g.from.join(', ')}`));
out.push(ask(`linked:${name}`, `${name}: linked to the user's identity?`, 'none', 'Only you know whether you or a partner tie it to an account, device or other identity details.'));
out.push(ask(`tracking:${name}`, `${name}: used for tracking?`, 'none', 'Yes when it is combined with other companies\' data for ads or shared with data brokers; tracking also needs App Tracking Transparency.'));
}
return out;
}
export const IARC_LABELS: Record<IarcQuestion, string> = {
violence: 'Violence', fear: 'Fear / horror', sexuality: 'Sexuality or nudity', language: 'Language (profanity)', controlledSubstances: 'Controlled substances (drugs, alcohol, tobacco)',
crudeHumor: 'Crude humour', gambling: 'Gambling with real money', simulatedGambling: 'Simulated gambling', lootBoxes: 'Random paid items (loot boxes)',
userInteraction: 'Users can interact or exchange content', sharesLocation: 'Shares the user\'s location with other users', digitalPurchases: 'Digital purchases',
unrestrictedInternet: 'Unrestricted internet access (browser)',
};
const CATEGORY_LABELS = { game: 'Game', social: 'Social or communication', other: 'All other app types' } as const;
function contentRating(config: ShipConfig): Answer[] {
const cr = config.console?.contentRating;
const out: Answer[] = [ok('email', 'Email address', maskUser(config.app.contactEmail), 'app.contactEmail', 'IARC writes to this address; the page gets the full address from the config.')];
const cat = cr?.category ?? (profileOf(config) === 'game' && config.app.profile ? 'game' : undefined);
out.push(cat ? ok('category', 'Category', CATEGORY_LABELS[cat], cr?.category ? 'console.contentRating.category' : 'app.profile')
: ask('category', 'Category', 'console.contentRating.category', 'Pick the category; set console.contentRating.category to have it filled.'));
const sells = (config.products?.length ?? 0) > 0 || (config.subscriptions?.length ?? 0) > 0;
for (const q of IARC_QUESTIONS) {
const v = cr?.answers?.[q];
if (v !== undefined) out.push(ok(`q:${q}`, IARC_LABELS[q], v, `console.contentRating.answers.${q}`));
else if (q === 'digitalPurchases' && sells) out.push(ok(`q:${q}`, IARC_LABELS[q], true, config.products?.length ? 'products' : 'subscriptions'));
else out.push(ask(`q:${q}`, IARC_LABELS[q], `console.contentRating.answers.${q}`, 'Answer from the app\'s real content; set console.contentRating.answers to have it filled.'));
}
return out;
}
export const AGE_LABELS: Record<AgeGroup, string> = { '5-under': 'Ages 5 and under', '6-8': 'Ages 6-8', '9-12': 'Ages 9-12', '13-15': 'Ages 13-15', '16-17': 'Ages 16-17', '18-over': 'Ages 18 and over' };
function targetAudience(config: ShipConfig): Answer[] {
const ta = config.console?.targetAudience;
const out: Answer[] = AGE_GROUPS.map(g => ta?.ages ? ok(`age:${g}`, `Target age: ${AGE_LABELS[g]}`, ta.ages.includes(g), 'console.targetAudience.ages')
: ask(`age:${g}`, `Target age: ${AGE_LABELS[g]}`, 'console.targetAudience.ages', 'Choose the ages you really target; any group under 13 brings the Families policy.'));
const kids = ta?.ages?.some(g => ['5-under', '6-8', '9-12'].includes(g));
if (!kids) out.push(ta?.appealsToChildren !== undefined ? ok('appeal', 'Could your app unintentionally appeal to children?', ta.appealsToChildren, 'console.targetAudience.appealsToChildren')
: ask('appeal', 'Could your app unintentionally appeal to children?', 'console.targetAudience.appealsToChildren', 'Look at your art style, characters and store listing honestly.'));
const ads = ta?.containsAds ?? (config.ads?.appAdsTxt?.length ? true : undefined);
out.push(ads !== undefined ? ok('ads', 'Ads: does your app contain ads?', ads, ta?.containsAds !== undefined ? 'console.targetAudience.containsAds' : 'ads.appAdsTxt')
: ask('ads', 'Ads: does your app contain ads?', 'console.targetAudience.containsAds', profileOf(config) === 'game' ? 'The game profile usually ships ads; confirm and set console.targetAudience.containsAds.' : 'Set console.targetAudience.containsAds.'));
return out;
}
export function consoleAnswers(id: FormId, config: ShipConfig): Answer[] {
switch (id) {
case 'apple-app-record': return appRecord(config);
case 'apple-age-rating': return ageRating(config);
case 'apple-app-privacy': return appPrivacy(config);
case 'play-content-rating': return contentRating(config);
case 'play-target-audience': return targetAudience(config);
}
}
/** The value the page gets: the same as the printed one, except the IARC email (printed masked, filled in full). */
export const fillValue = (form: FormId, a: Answer, config: ShipConfig): AnswerValue =>
form === 'play-content-rating' && a.id === 'email' && a.certain ? config.app.contactEmail : a.value;
export const valueText = (a: Answer): string => a.value === null ? '(you decide)' : a.value === true ? 'Yes' : a.value === false ? 'No' : a.value;
/** Step-by-step lines the owner can follow (and copy from) without any autofill. */
export function guidance(meta: FormMeta, answers: Answer[]): string[] {
const g: string[] = [];
if (!meta.fillable) g.push('Nothing to fill here: `storebound apple appinfo --dry`, then `storebound apple appinfo` sets every age rating answer through the App Store Connect API.');
g.push(...meta.open.map(o => `Open: ${o}`));
for (const a of answers) g.push(`${a.label}: ${valueText(a)}${a.certain ? '' : ` (check: ${a.note ?? 'not in the config'})`}`);
g.push(meta.fillable ? `Review every field, then press ${meta.stopBefore} yourself. storebound never saves, submits or publishes.` : 'Answers marked "check" are yours to confirm in storebound.config.ts (apple.info.ageRating).');
return g;
}
export function consoleResult(id: FormId, config: ShipConfig): ConsoleResult {
const meta = formMeta(id, config);
const answers = consoleAnswers(id, config);
return { form: id, store: meta.store, title: meta.title, url: meta.url, answers, uncertain: answers.filter(a => !a.certain).length, guidance: guidance(meta, answers) };
}

130
cli/lib/console-forms.ts Normal file
View file

@ -0,0 +1,130 @@
// Where each answer of a console form lives on the page, as accessible names only (role + name / label), never CSS
// paths: `storebound console fill` locates every field of a section first and falls back to printed guidance when one
// is missing or ambiguous (the console UI changed). Several candidate names per field absorb small wording drift.
// Also the click gate (no Save / Submit / Publish / Next ... ever) and the sign-in page detector. Pure.
// The names are modeled on Apple's and Google's public help pages (sources in console-answers.ts), not recorded from a
// signed-in console: the exact App Privacy dialog titles, the IARC question wording and the Play category names could
// not be verified without an account, which is why every field has candidates and the engine falls back on a miss.
import { AGE_GROUPS } from './config';
import { AGE_LABELS, type Answer, APPLE_PURPOSES, type FormId } from './console-answers';
/** An accessible name: a string matches exactly, a RegExp matches the name. */
export type Name = string | RegExp;
export interface FieldDef {
/** Answer id. */
id: string;
kind: 'text' | 'select' | 'checkbox' | 'radio';
/** text / select / checkbox: candidate names of the control. radio: candidate names of the radiogroup (optional). */
names?: Name[];
/** radio: answer value (String(value)) -> candidate names of that radio button. */
options?: Record<string, Name[]>;
}
export interface SectionDef {
/** Shown to the owner ("page 2/3: Questionnaire"). */
title: string;
/** Candidate names of the dialog the section lives in; it is present when that dialog is visible. */
dialog?: Name[];
fields: FieldDef[];
}
export interface FormDef { id: FormId; sections: SectionDef[] }
const esc = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const yesNo = (yes: Name[] = ['Yes'], no: Name[] = ['No']): Record<string, Name[]> => ({ true: yes, false: no });
/** IARC topics -> candidate radiogroup names (modeled; see the header). */
const IARC_NAMES: Record<string, Name[]> = {
violence: [/^Does the app contain (any )?violen/i, /violen/i],
fear: [/^Does the app contain .*(scary|fear|horror)/i, /(fear|horror)/i],
sexuality: [/^Does the app contain .*(sexual|nudity)/i, /(sexual|nudity)/i],
language: [/^Does the app contain .*(profan|language)/i, /profanit/i],
controlledSubstances: [/^Does the app contain .*(drug|alcohol|tobacco|controlled substance)/i, /controlled substance/i],
crudeHumor: [/crude humou?r/i],
gambling: [/^Does the app (allow|let) .*gambl.*real (money|currency)/i, /real[- ]money gambling/i],
simulatedGambling: [/simulated gambling/i],
lootBoxes: [/(random|randomi[sz]ed) (paid )?items/i, /loot box/i],
userInteraction: [/(users|players) .*(interact|communicate|exchange)/i],
sharesLocation: [/share .*(physical )?location/i],
digitalPurchases: [/digital (goods|purchases)/i, /purchase digital/i],
unrestrictedInternet: [/unrestricted (internet|web)/i, /web browser/i],
};
/** Field definitions for the answers of one form (App Privacy has one section per collected data type). */
export function formDef(id: FormId, answers: Answer[]): FormDef {
const has = (aid: string) => answers.some(a => a.id === aid);
switch (id) {
case 'apple-app-record': return { id, sections: [{ title: 'New App', fields: [
{ id: 'platform:ios', kind: 'checkbox', names: ['iOS'] },
{ id: 'name', kind: 'text', names: ['Name', 'App Name'] },
{ id: 'language', kind: 'select', names: ['Primary Language', 'Primary language'] },
{ id: 'bundleId', kind: 'select', names: ['Bundle ID', 'Bundle Id'] },
{ id: 'sku', kind: 'text', names: ['SKU'] },
{ id: 'access', kind: 'radio', names: ['User Access'], options: { limited: ['Limited Access'], full: ['Full Access'] } },
] }] };
case 'apple-age-rating': return { id, sections: [] };
case 'apple-app-privacy': {
const sections: SectionDef[] = [{ title: 'Data collection', fields: [
{ id: 'collects', kind: 'radio', options: yesNo([/^Yes, we collect data/i], [/^No, we do not collect data/i]) },
] }];
const types = answers.filter(a => a.id.startsWith('type:'));
if (types.length) sections.push({ title: 'Data types', fields: types.map(a => ({ id: a.id, kind: 'checkbox', names: [a.id.slice(5)] })) });
for (const a of types.filter(t => t.value === true && has(`linked:${t.id.slice(5)}`))) {
const n = a.id.slice(5);
sections.push({ title: n, dialog: [n, new RegExp(`^${esc(n)}\\b`, 'i')], fields: [
...APPLE_PURPOSES.map(p => ({ id: `purpose:${n}:${p}`, kind: 'checkbox' as const, names: [p] })),
{ id: `linked:${n}`, kind: 'radio', options: yesNo([/^Yes,.*\blinked to the user/i], [/^No,.*\blinked to the user/i]) },
{ id: `tracking:${n}`, kind: 'radio', options: yesNo([/^Yes,.*\btracking/i], [/^No,.*\btracking/i]) },
] });
}
return { id, sections };
}
case 'play-content-rating': return { id, sections: [
{ title: 'Email address and category', fields: [
{ id: 'email', kind: 'text', names: ['Email address', 'Email'] },
{ id: 'category', kind: 'radio', options: { 'Game': [/^Game\b/i], 'Social or communication': [/^Social/i], 'All other app types': [/^All other app types/i, /^Utility/i] } },
] },
{ title: 'Questionnaire', fields: answers.filter(a => a.id.startsWith('q:')).map(a => ({ id: a.id, kind: 'radio' as const, names: IARC_NAMES[a.id.slice(2)], options: yesNo() })) },
] };
case 'play-target-audience': return { id, sections: [
{ title: 'Target age', fields: AGE_GROUPS.map(g => ({ id: `age:${g}`, kind: 'checkbox' as const, names: [AGE_LABELS[g], AGE_LABELS[g].replace(/^Ages /, '')] })) },
...(has('appeal') ? [{ title: 'Appeal to children', fields: [{ id: 'appeal', kind: 'radio' as const, names: [/appeal to children/i], options: yesNo() }] }] : []),
{ title: 'Ads', fields: [{ id: 'ads', kind: 'radio', options: yesNo([/^Yes, my app contains ads/i], [/^No, my app does not contain ads/i]) }] },
] };
}
}
/**
* The click gate: a control whose name says save, submit, publish, next... is never clicked by storebound (English and
* Turkish console wording). English words match whole words; Turkish stems match word starts (agglutinative suffixes).
*/
const EN = ['save', 'saved', 'submit', 'publish', 'create', 'send', 'apply', 'confirm', 'done', 'release', 'rollout', 'roll out', 'start', 'delete',
'remove', 'next', 'continue', 'finish', 'agree', 'accept', 'upload', 'deploy', 'discard', 'update', 'add for review', 'review', 'sign', 'log in', 'login'];
const TR = ['kaydet', 'gönder', 'yayınla', 'yayımla', 'oluştur', 'uygula', 'onayla', 'tamam', 'bitti', 'bitir', 'sil', 'kaldır', 'başlat', 'sürüm',
'ileri', 'devam', 'sonraki', 'kabul', 'yükle', 'güncelle', 'incelemeye', 'giriş'];
const L = '\\p{L}\\p{N}';
const FORBIDDEN = new RegExp(`(?<![${L}])(?:(?:${EN.map(esc).join('|')})(?![${L}])|(?:${TR.map(esc).join('|')}))`, 'iu');
/** true when storebound must not click a control with this accessible name. */
export const forbiddenControl = (name: string): boolean => FORBIDDEN.test(name.toLocaleLowerCase('tr').normalize('NFC')) || FORBIDDEN.test(name.toLowerCase());
const SIGN_IN_HOSTS = ['appleid.apple.com', 'idmsa.apple.com', 'accounts.google.com'];
/** A sign-in page (storebound never touches those; the owner signs in). */
export function isSignInUrl(url: string): boolean {
try {
const u = new URL(url);
return SIGN_IN_HOSTS.includes(u.hostname) || (u.hostname === 'appstoreconnect.apple.com' && u.pathname.startsWith('/login'));
} catch { return false; }
}
/** The console itself is open (signed in). `base` overrides the console origin (tests only, 127.0.0.1). */
export function consoleReached(store: 'apple' | 'play', url: string, base?: string): boolean {
try {
const u = new URL(url);
if (base) return u.origin === new URL(base).origin;
return store === 'apple' ? u.hostname === 'appstoreconnect.apple.com' && !u.pathname.startsWith('/login')
: u.hostname === 'play.google.com' && u.pathname.startsWith('/console') && !u.pathname.includes('signup');
} catch { return false; }
}

View file

@ -27,6 +27,8 @@ function fileStore(root: string): Store {
try { return JSON.parse(readFileSync(p, 'utf8')) as Store; } catch (e) { throw new Error(`${p}: ${(e as Error).message}`); } try { return JSON.parse(readFileSync(p, 'utf8')) as Store; } catch (e) { throw new Error(`${p}: ${(e as Error).message}`); }
} }
/** One credential by name: env first, then .storebound/credentials.json. Never print the value. */
export function credentialValue(root: string, name: string): string | undefined { return value(root, name); }
/** The store credential names a profile holds (the same as the env names): per developer account, so the vendor number /** The store credential names a profile holds (the same as the env names): per developer account, so the vendor number
* for reports too; an app's Android upload keystore stays in the project. */ * for reports too; an app's Android upload keystore stays in the project. */
export const PROFILE_KEYS = ['PLAY_SERVICE_ACCOUNT', 'ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8', 'ASC_VENDOR_NUMBER'] as const; export const PROFILE_KEYS = ['PLAY_SERVICE_ACCOUNT', 'ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8', 'ASC_VENDOR_NUMBER'] as const;
@ -80,7 +82,7 @@ function value(root: string, name: string): string | undefined {
} }
/** A path or the inline content itself. */ /** A path or the inline content itself. */
const inline = (v: string, marker: RegExp): string => (marker.test(v) ? v : readFileSync(v.replace(/^~(?=\/)/, homedir()), 'utf8')); export const inline = (v: string, marker: RegExp): string => (marker.test(v) ? v : readFileSync(v.replace(/^~(?=\/)/, homedir()), 'utf8'));
export function parseServiceAccount(text: string): ServiceAccount { export function parseServiceAccount(text: string): ServiceAccount {
const j = JSON.parse(text) as Partial<ServiceAccount>; const j = JSON.parse(text) as Partial<ServiceAccount>;

View file

@ -322,3 +322,15 @@ export interface AnalyticsCompare {
/** Per store with no days in any snapshot: why the newest snapshot has none (no report request yet, no bucket). */ /** 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 }; errors?: { apple?: string; play?: string };
} }
/** console.fill (`console fill <form> --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-content-rating' | 'play-target-audience';
export interface ConsoleAnswer { id: string; label: string; value: string; certain: boolean; source: string; note?: string }
export interface ConsoleFillResult {
form: ConsoleForm; store: 'apple' | 'play'; title: string; url: string; answers: ConsoleAnswer[];
/** Answers only the owner can give (highlighted in the browser). */
uncertain: number;
guidance: string[];
/** Real run only: fields filled, fields highlighted, whether it fell back to highlighting only, where it stopped. */
filled?: number; highlighted?: number; fallback?: unknown; stoppedAt?: string | null;
}

41
cli/lib/play-share.ts Normal file
View file

@ -0,0 +1,41 @@
// Google Play internal app sharing: upload URL, limits and the response. Pure, used by cli/play/share.ts.
// Sources (checked October 2026):
// internalappsharingartifacts.uploadbundle / uploadapk:
// https://developers.google.com/android-publisher/api-ref/rest/v3/internalappsharingartifacts
// POST https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/internalappsharing/{packageName}/artifacts/bundle (and /apk)
// Not under applications/{packageName} like the edit calls. Scope https://www.googleapis.com/auth/androidpublisher.
// Response InternalAppSharingArtifact { downloadUrl, certificateFingerprint, sha256 (lowercase hex, as sha256sum) }.
// Discovery document (androidpublisher v3): mediaUpload.maxSize bundle 10737418240 (10 GiB), apk 1073741824 (1 GiB);
// accept application/octet-stream (apk also application/vnd.android.package-archive).
// Internal app sharing (Play Console Help, https://support.google.com/googleplay/android-developer/answer/9844679):
// uploaders need "Release apps to testing tracks" or to be on the uploader list; testers turn on internal app
// sharing in the Play Store app (Settings > About > tap the Play Store version 7 times > Internal app sharing);
// links expire 60 days after the upload; up to 100 users per link; Google re-signs with an internal sharing key.
export type ShareKind = 'bundle' | 'apk';
export const SHARE_LIMIT: Record<ShareKind, number> = { bundle: 10737418240, apk: 1073741824 };
export const shareUrl = (packageName: string, kind: ShareKind): string =>
`https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/internalappsharing/${encodeURIComponent(packageName)}/artifacts/${kind}?uploadType=media`;
export const SHARE_HEADERS = { 'Content-Type': 'application/octet-stream' } as const;
export interface ShareArtifact { downloadUrl: string; certificateFingerprint: string; sha256: string }
export function parseShareArtifact(r: unknown): ShareArtifact {
const o = (r ?? {}) as Record<string, unknown>;
if (typeof o.downloadUrl !== 'string' || !o.downloadUrl.startsWith('https://')) throw new Error('internal app sharing: the answer has no downloadUrl');
return { downloadUrl: o.downloadUrl, certificateFingerprint: String(o.certificateFingerprint ?? ''), sha256: String(o.sha256 ?? '').toLowerCase() };
}
/** Checks the file kind against the flag and the size against the API limit. Returns problems (empty = fine). */
export function shareProblems(kind: ShareKind, file: string, bytes: number): string[] {
const e: string[] = [];
if (kind === 'bundle' && !/\.aab$/i.test(file)) e.push(`--aab ${file}: expected an .aab file`);
if (kind === 'apk' && !/\.apk$/i.test(file)) e.push(`--apk ${file}: expected an .apk file`);
if (bytes <= 0) e.push(`${file} is empty`);
if (bytes > SHARE_LIMIT[kind]) e.push(`${file} is ${mb(bytes)}, above the ${mb(SHARE_LIMIT[kind])} internal app sharing limit for ${kind === 'bundle' ? 'app bundles' : 'APKs'}`);
return e;
}
export const mb = (b: number): string => `${(b / 1048576).toFixed(1)} MB`;

342
cli/lib/ppp.ts Normal file
View file

@ -0,0 +1,342 @@
// Purchasing power parity (PPP) price proposals for `storebound prices ppp`, as pure parts: datasets, the math, the
// clamp, the snapping rules and the rows for the price sheet (the same CSV `storebound prices import` reads).
//
// The math, per product, store and region:
// factor = PPP conversion factor (local currency units per international dollar; the international dollar has the
// US dollar's purchasing power in the US, so the US factor is 1)
// fx = market exchange rate (local currency units per US dollar, period average)
// usd = base x factor / fx (the USD value of the PPP price at the market rate)
// usd = clamp(usd, floor x base, ceiling x base) (floor 0.3, ceiling 1.2 unless the config or flags say)
// target = usd x fx(store currency) (the store may price a region in USD or EUR instead of the local currency)
// price = snap(target)
// Snapping (storebound's own rules, not a store rule):
// - Apple, online: the nearest real price point of that product in that territory (GET pricePoints). Apple only
// accepts its own price points; offline values below are a proposal and `prices import` checks them.
// - Play (and Apple offline): a clean local ending. Whole-number currencies (ISO 4217 zero-decimal ones such as
// JPY, KRW, VND, CLP, plus currencies stores show without decimals such as IDR, HUF, TWD, COP, KZT) and any
// value >= 1000: two significant digits (480, 1200, 46000; under 100 the nearest whole number). Two-decimal
// currencies: under 1 -> x.x9 (0.29), under 100 -> x.99 (1.99, 49.99), under 1000 -> whole numbers ending in 9
// (129, 249). The US row is always the base itself.
// - Play takes any price in the region's currency within its limits; per-currency limits are not checked here
// (not verified against a Play doc; Play rejects an out-of-range price on import).
// Currency per region: CURRENCY (ISO 3166 alpha-2 -> ISO 4217) for the App Store territories. Stores price some
// regions in USD or EUR instead; online the stores' answer wins (Apple: the price point's territory currency; Play:
// convertRegionPrices). Offline, Apple uses APPLE_CURRENCY_HINT (from Apple's "Financial Report regions and
// currencies" page: regions with their own report currency use it, the Euro-Zone group EUR, the USD groups USD) and
// Play the local currency; `prices import` rejects a currency the store does not use.
// Sources (checked October 2026):
// World Bank indicators PA.NUS.PPP and PA.NUS.FCRF (CC BY 4.0): https://data.worldbank.org/indicator/PA.NUS.PPP,
// https://data.worldbank.org/indicator/PA.NUS.FCRF, API https://api.worldbank.org/v2/country/all/indicator/PA.NUS.PPP?format=json
// The Economist Big Mac index data (data CC BY 4.0, code MIT; not bundled, see tools/update-ppp.ts):
// https://github.com/TheEconomist/big-mac-data
// Apple price points: https://developer.apple.com/documentation/appstoreconnectapi/get-v2-inapppurchases-_id_-pricepoints
// (filter[territory], include=territory, limit <= 8000; customerPrice; territory.currency)
// Apple report currencies: https://developer.apple.com/help/app-store-connect/reference/reporting/financial-report-regions-and-currencies
// Play convertRegionPrices (input tax exclusive, converted regional prices tax inclusive):
// https://developers.google.com/android-publisher/api-ref/rest/v3/monetization/convertRegionPrices
import { parseCsvRecords } from './csv';
import { ALPHA3, nearestPrices } from './money';
import { type PriceRow, pricesCsv } from './prices';
export interface PppEntry {
/** Local currency units per international dollar (PPP conversion factor). */
ppp: number;
/** Market rate, local currency units per US dollar. */
fx?: number;
/** Year of the PPP value (fxYear when the rate is from another year). */
year?: number;
fxYear?: number;
/** ISO 4217 currency the two values are in. */
currency?: string;
}
export interface PppDataset {
name: 'worldbank' | 'bigmac' | 'file';
source: string;
url: string;
urls?: string[];
license: string;
attribution?: string;
/** YYYY-MM-DD the data was downloaded. */
retrieved: string;
/** Latest data year in the file. */
year?: number;
notes?: string[];
/** Euro rate (EUR per USD) for regions a store prices in EUR. */
eur?: { fx: number; year?: number };
/** ISO 3166 alpha-2 -> values. */
countries: Record<string, PppEntry>;
}
const C = `AE AED AF AFN AG XCD AI XCD AL ALL AM AMD AO AOA AR ARS AT EUR AU AUD AZ AZN BA BAM BB BBD BE EUR BF XOF BG EUR
BH BHD BJ XOF BM BMD BN BND BO BOB BR BRL BS BSD BT BTN BW BWP BY BYN BZ BZD CA CAD CD CDF CG XAF CH CHF CI XOF CL CLP CM XAF
CN CNY CO COP CR CRC CV CVE CY EUR CZ CZK DE EUR DK DKK DM XCD DO DOP DZ DZD EC USD EE EUR EG EGP ES EUR FI EUR FJ FJD FM USD
FR EUR GA XAF GB GBP GD XCD GE GEL GH GHS GM GMD GR EUR GT GTQ GW XOF GY GYD HK HKD HN HNL HR EUR HU HUF ID IDR IE EUR IL ILS
IN INR IQ IQD IS ISK IT EUR JM JMD JO JOD JP JPY KE KES KG KGS KH KHR KN XCD KR KRW KW KWD KY KYD KZ KZT LA LAK LB LBP LC XCD
LK LKR LR LRD LT EUR LU EUR LV EUR LY LYD MA MAD MD MDL ME EUR MG MGA MK MKD ML XOF MM MMK MN MNT MO MOP MR MRU MS XCD MT EUR
MU MUR MV MVR MW MWK MX MXN MY MYR MZ MZN NA NAD NE XOF NG NGN NI NIO NL EUR NO NOK NP NPR NR AUD NZ NZD OM OMR PA PAB PE PEN
PG PGK PH PHP PK PKR PL PLN PT EUR PW USD PY PYG QA QAR RO RON RS RSD RU RUB RW RWF SA SAR SB SBD SC SCR SE SEK SG SGD SI EUR
SK EUR SL SLE SN XOF SR SRD ST STN SV USD SZ SZL TC USD TD XAF TH THB TJ TJS TM TMT TN TND TO TOP TR TRY TT TTD TW TWD TZ TZS
UA UAH UG UGX US USD UY UYU UZ UZS VC XCD VE VES VG USD VN VND VU VUV XK EUR YE YER ZA ZAR ZM ZMW ZW ZWG`.split(/\s+/);
/** ISO 3166 alpha-2 -> ISO 4217 local currency, for every App Store territory (ALPHA3 keys). Bulgaria: EUR since 2026-01-01. */
export const CURRENCY: Record<string, string> = Object.fromEntries(Array.from({ length: C.length / 2 }, (_, i) => [C[2 * i]!, C[2 * i + 1]!]));
// Apple "Financial Report regions and currencies": regions with their own report currency.
const APPLE_OWN = new Set('US AU BR BG CA CL CN CO CZ HR DK EG HK HU IN ID IL JP KZ KR MY MX NZ NG NO PK PE PH PL QA RO RU SA SG ZA SE CH TW TH TR AE GB TZ VN'.split(' '));
// The Euro-Zone report group (countries that also have their own report region above keep that one).
const APPLE_EUROZONE = new Set('AT BE BA BG CY CZ EE FI FR DE GR HU IE IT LV LT LU MT ME NL PL PT RO RS SK SI ES'.split(' '));
/** Offline guess of the currency the App Store prices a territory in (online: the price point's territory currency). */
export function appleCurrencyHint(region: string): string {
if (APPLE_OWN.has(region)) return CURRENCY[region] ?? 'USD';
if (APPLE_EUROZONE.has(region)) return 'EUR';
return 'USD';
}
/** Currencies priced in whole numbers (ISO 4217 zero-decimal, plus ones stores show without decimals). */
export const WHOLE = new Set('BIF CLP DJF GNF ISK JPY KMF KRW PYG RWF UGX VND VUV XAF XOF XPF HUF IDR TWD COP KZT TZS UZS MMK LAK KHR MNT IQD LBP AMD'.split(' '));
const r2 = (n: number) => Math.round(n * 100) / 100;
/** A clean price near `v` in `currency` (see the header). */
export function snapEnding(v: number, currency: string): number {
if (!(v > 0)) throw new Error(`bad price ${v}`);
if (WHOLE.has(currency) || v >= 1000) {
if (v < 100) return Math.max(1, Math.round(v));
const step = 10 ** (Math.floor(Math.log10(v)) - 1);
return Math.round(v / step) * step;
}
if (v < 1) return r2(Math.max(0.09, Math.round(v * 10) / 10 - 0.01));
if (v < 100) return r2(Math.max(0.99, Math.round(v + 0.01) - 0.01));
return Math.round((v + 1) / 10) * 10 - 1;
}
/** Nearest Apple price point (customer prices of one territory). */
export function snapApple(points: number[], v: number): number | null {
return points.length ? nearestPrices(points, v, 1)[0]! : null;
}
/** Local currency units per US dollar of `currency`, from the dataset (USD = 1, EUR = the euro rate). */
export function fxOf(ds: PppDataset, currency: string): number | null {
if (currency === 'USD') return 1;
if (currency === 'EUR' && ds.eur?.fx) return ds.eur.fx;
for (const [region, e] of Object.entries(ds.countries)) if ((e.currency ?? CURRENCY[region]) === currency && e.fx) return e.fx;
return null;
}
export interface Proposal { usdRaw: number; usd: number; clamped: 'floor' | 'ceiling' | null }
/** PPP-adjusted USD value of `base`, clamped to floor..ceiling of the base. */
export function propose(base: number, factor: number, fx: number, floor: number, ceiling: number): Proposal {
if (!(factor > 0) || !(fx > 0)) throw new Error('PPP factor and exchange rate must be positive');
const usdRaw = (base * factor) / fx;
const lo = base * floor, hi = base * ceiling;
return usdRaw < lo ? { usdRaw, usd: lo, clamped: 'floor' } : usdRaw > hi ? { usdRaw, usd: hi, clamped: 'ceiling' } : { usdRaw, usd: usdRaw, clamped: null };
}
export interface PppRow extends PriceRow {
factor: number;
fx: number;
/** USD value of the final (snapped) price at the market rate. */
usdEquivalent: number;
clamped: 'floor' | 'ceiling' | null;
/** Unsnapped price in the store currency. */
snappedFrom: number;
/** apple-point: a real Apple price point; ending: storebound's clean-ending rule. */
snap: 'apple-point' | 'ending' | 'base';
}
/** What one store says about one region (online), or nothing (offline). */
export interface StoreRegion { currency: string; points?: number[] }
export interface PlanInput {
product: string;
base: number;
store: 'apple' | 'play';
dataset: PppDataset;
floor: number;
ceiling: number;
/** Online: the store's regions (Apple territories with price points, Play convertRegionPrices). Offline: undefined. */
regions?: Map<string, StoreRegion>;
}
/** Rows of one product on one store, plus the regions skipped and why. */
export function planRows(i: PlanInput): { rows: PppRow[]; skipped: { region: string; why: string }[] } {
const rows: PppRow[] = [];
const skipped: { region: string; why: string }[] = [];
const regions = i.regions ? [...i.regions.keys()] : Object.keys(ALPHA3);
for (const region of regions.sort()) {
const known = i.regions?.get(region);
const currency = known?.currency || (i.store === 'apple' ? appleCurrencyHint(region) : i.dataset.countries[region]?.currency ?? CURRENCY[region]);
if (!currency) { skipped.push({ region, why: 'no currency known' }); continue; }
const storeFx = fxOf(i.dataset, currency);
if (region === 'US' && currency === 'USD') {
const price = known?.points?.length ? snapApple(known.points, i.base)! : i.base;
rows.push({ product: i.product, store: i.store, region, ...(i.store === 'apple' ? { territory: 'USA' } : {}), currency, price, factor: 1, fx: 1, usdEquivalent: price, clamped: null, snappedFrom: i.base, snap: known?.points?.length ? 'apple-point' : 'base' });
continue;
}
const e = i.dataset.countries[region];
if (!e) { skipped.push({ region, why: `no PPP factor in ${i.dataset.name}` }); continue; }
if (!e.fx) { skipped.push({ region, why: 'no exchange rate' }); continue; }
if (!storeFx) { skipped.push({ region, why: `no exchange rate for ${currency}` }); continue; }
const p = propose(i.base, e.ppp, e.fx, i.floor, i.ceiling);
const target = p.usd * storeFx;
const point = known?.points ? snapApple(known.points, target) : null;
if (known?.points && point === null) { skipped.push({ region, why: 'no Apple price points' }); continue; }
const price = point ?? snapEnding(target, currency);
rows.push({ product: i.product, store: i.store, region, ...(i.store === 'apple' ? { territory: ALPHA3[region] } : {}), currency, price,
factor: e.ppp, fx: e.fx, usdEquivalent: r2(price / storeFx), clamped: p.clamped, snappedFrom: r2(target), snap: point !== null ? 'apple-point' : 'ending' });
}
return { rows, skipped };
}
/** The price sheet (`prices import` format) of the proposal. */
export const pppCsv = (rows: PppRow[]): string => pricesCsv(rows.map(r => ({ product: r.product, store: r.store, region: r.region, currency: r.currency, price: r.price })));
// ---- datasets ----
/** --source file: CSV region, factor, currency, fx (fx optional: then the bundled rate of that region when the currency matches). */
export function parseFactorCsv(text: string, fallback?: PppDataset, path = 'file'): PppDataset {
const countries: Record<string, PppEntry> = {};
const errors: string[] = [];
for (const [i, r] of parseCsvRecords(text).entries()) {
const at = `row ${i + 2}`;
const region = (r.region ?? '').trim().toUpperCase();
const currency = (r.currency ?? '').trim().toUpperCase();
const factor = Number((r.factor ?? '').replace(',', '.'));
const fxText = (r.fx ?? '').trim();
if (!/^[A-Z]{2}$/.test(region)) { errors.push(`${at}: region "${r.region}" must be ISO alpha-2`); continue; }
if (!/^[A-Z]{3}$/.test(currency)) errors.push(`${at}: currency "${r.currency}" must be ISO 4217`);
if (!(factor > 0)) errors.push(`${at}: factor must be a positive number`);
let fx = fxText ? Number(fxText.replace(',', '.')) : undefined;
if (fxText && !(fx! > 0)) errors.push(`${at}: fx must be a positive number`);
if (fx === undefined) {
const fb = fallback?.countries[region];
fx = currency === 'USD' ? 1 : fb?.fx && (fb.currency ?? CURRENCY[region]) === currency ? fb.fx : undefined;
}
if (countries[region]) errors.push(`${at}: ${region} listed twice`);
countries[region] = { ppp: factor, ...(fx ? { fx } : {}), currency };
}
if (errors.length) throw new Error(`PPP factor CSV: ${errors.join('; ')}`);
return { name: 'file', source: `factor CSV ${path}`, url: path, license: 'owner supplied', retrieved: '', eur: fallback?.eur, countries };
}
/** Problems with a dataset's shape (used by tests and the update tool). */
export function datasetProblems(ds: PppDataset): string[] {
const e: string[] = [];
for (const k of ['source', 'url', 'license', 'retrieved'] as const) if (!ds[k]) e.push(`${k} missing`);
if (!Object.keys(ds.countries ?? {}).length) e.push('no countries');
for (const [r, v] of Object.entries(ds.countries ?? {})) {
if (!/^[A-Z]{2}$/.test(r)) e.push(`${r}: not alpha-2`);
if (!(v.ppp > 0)) e.push(`${r}: ppp`);
if (v.fx !== undefined && !(v.fx > 0)) e.push(`${r}: fx`);
}
return e;
}
/** Dataset file text: header fields pretty, one line per country (small diffs on update). */
export function datasetJson(ds: PppDataset): string {
const { countries, ...head } = ds;
const top = JSON.stringify(head, null, 2).replace(/\n}$/, '');
const lines = Object.keys(countries).sort().map(k => ` ${JSON.stringify(k)}: ${JSON.stringify(countries[k])}`);
return `${top},\n "countries": {\n${lines.join(',\n')}\n }\n}\n`;
}
export const WB = {
ppp: 'PA.NUS.PPP',
fx: 'PA.NUS.FCRF',
api: (ind: string, from = 2018, to = new Date().getFullYear()) => `https://api.worldbank.org/v2/country/all/indicator/${ind}?format=json&per_page=20000&date=${from}:${to}`,
countries: 'https://api.worldbank.org/v2/country?format=json&per_page=400',
};
interface WbObs { country?: { id?: string }; countryiso3code?: string; date?: string; value?: number | null }
type WbResp = [unknown, WbObs[] | null];
const latest = (resp: WbResp, keep: (iso2: string) => boolean): Map<string, { v: number; y: number }> => {
const m = new Map<string, { v: number; y: number }>();
for (const o of resp[1] ?? []) {
const id = o.country?.id ?? '', y = Number(o.date);
if (o.value === null || o.value === undefined || !keep(id)) continue;
const cur = m.get(id);
if (!cur || cur.y < y) m.set(id, { v: o.value, y });
}
return m;
};
/**
* World Bank API responses -> dataset. Aggregates (regions, income groups) are dropped; only App Store territories
* (CURRENCY keys) are kept. Every EUR region uses the euro area rate (XC), since per-country FCRF is missing or still
* in the old currency for new members (Bulgaria 2025: PPP already in EUR, FCRF in BGN).
*/
export function worldBankDataset(pppResp: WbResp, fxResp: WbResp, countriesResp: [unknown, { id: string; iso2Code: string; region?: { value?: string } }[]], retrieved: string): PppDataset {
const real = new Set((countriesResp[1] ?? []).filter(c => (c.region?.value ?? '').trim() !== 'Aggregates').map(c => c.iso2Code));
const ppp = latest(pppResp, id => real.has(id) && !!CURRENCY[id]);
const fx = latest(fxResp, id => (real.has(id) && !!CURRENCY[id]) || id === 'XC');
const eur = fx.get('XC');
const countries: Record<string, PppEntry> = {};
const dropped: string[] = [];
for (const [id, p] of [...ppp.entries()].sort(([a], [b]) => a.localeCompare(b))) {
const currency = CURRENCY[id]!;
const f = currency === 'EUR' ? eur : fx.get(id);
if (!f) { countries[id] = { ppp: sig8(p.v), year: p.y, currency }; continue; }
const ratio = p.v / f.v;
// a price level under 5 % or over 300 % of the US is a unit mismatch (redenomination), not a price level
if (ratio < 0.05 || ratio > 3) { dropped.push(`${id} (${ratio.toFixed(3)})`); continue; }
countries[id] = { ppp: sig8(p.v), fx: sig8(f.v), year: p.y, ...(f.y !== p.y ? { fxYear: f.y } : {}), currency };
}
return {
name: 'worldbank',
source: 'World Bank, World Development Indicators: PPP conversion factor, GDP (LCU per international $) [PA.NUS.PPP] (International Comparison Program) and Official exchange rate (LCU per US$, period average) [PA.NUS.FCRF]',
url: 'https://data.worldbank.org/indicator/PA.NUS.PPP',
urls: ['https://data.worldbank.org/indicator/PA.NUS.PPP', 'https://data.worldbank.org/indicator/PA.NUS.FCRF', WB.api(WB.ppp), WB.api(WB.fx)],
license: 'CC BY 4.0',
attribution: 'The World Bank: World Development Indicators, PA.NUS.PPP and PA.NUS.FCRF (CC BY 4.0, https://creativecommons.org/licenses/by/4.0/). Values used unchanged except the euro rate note below.',
retrieved,
year: Math.max(...[...ppp.values()].map(v => v.y)),
notes: [
'Latest available year per country (2018 onwards); fxYear is set when the exchange rate is from another year than the PPP factor.',
`Every EUR region (euro area members, Montenegro, Kosovo) uses the euro area rate (XC, ${eur ? `${sig8(eur.v)} EUR per USD, ${eur.y}` : 'missing'}): per-country FCRF is missing for most members and still in BGN for Bulgaria, whose PPP factor is already in EUR.`,
'Only App Store territories are kept; aggregates (regions, income groups) are excluded.',
...(dropped.length ? [`Dropped as a unit mismatch (PPP / fx outside 0.05..3): ${dropped.join(', ')}.`] : []),
'Missing countries (no recent World Bank data, e.g. Taiwan, Venezuela) get no proposal; set them by hand or with --source file.',
],
...(eur ? { eur: { fx: sig8(eur.v), year: eur.y } } : {}),
countries,
};
}
const sig8 = (n: number) => Number(n.toPrecision(8));
/** The Economist big-mac-raw-index.csv -> dataset (latest date). Implied PPP = local price / US price; fx = dollar_ex. */
export function bigMacDataset(csv: string, retrieved: string): PppDataset {
const recs = parseCsvRecords(csv);
const date = recs.map(r => r.date ?? '').sort().at(-1) ?? '';
const rows = recs.filter(r => r.date === date);
const us = rows.find(r => r.iso_a3 === 'USA');
if (!us) throw new Error(`Big Mac data: no USA row on ${date}`);
const usPrice = Number(us.local_price);
const a2 = Object.fromEntries(Object.entries(ALPHA3).map(([k, v]) => [v, k] as const));
const countries: Record<string, PppEntry> = {};
const year = Number(date.slice(0, 4));
let eur: PppEntry | undefined;
for (const r of rows) {
const e: PppEntry = { ppp: sig8(Number(r.local_price) / usPrice), fx: sig8(Number(r.dollar_ex)), year, currency: r.currency_code };
if (!(e.ppp > 0) || !(e.fx! > 0)) continue;
if (r.iso_a3 === 'EUZ') { eur = e; continue; }
const id = a2[r.iso_a3 ?? ''];
if (id) countries[id] = e;
}
if (eur) for (const [id, c] of Object.entries(CURRENCY)) if (c === 'EUR' && !countries[id]) countries[id] = { ...eur };
return {
name: 'bigmac',
source: `The Economist, The Big Mac index (big-mac-raw-index.csv, ${date})`,
url: 'https://github.com/TheEconomist/big-mac-data',
license: 'CC BY 4.0 (data), MIT (code); third-party data not covered',
attribution: 'The Economist, big-mac-data (https://github.com/TheEconomist/big-mac-data). Implied PPP = local Big Mac price / US price.',
retrieved,
year,
notes: ['Euro area members without their own row use the euro area (EUZ) row.', 'Downloaded on this machine; not redistributed by storebound.'],
...(eur ? { eur: { fx: eur.fx!, year } } : {}),
countries,
};
}

307
cli/lib/revenuecat.ts Normal file
View file

@ -0,0 +1,307 @@
// RevenueCat catalog mirror, as pure parts: the config catalog (products + subscriptions) -> the RevenueCat project
// state it implies (products per store app, entitlements with attached products, one offering with packages), the
// parity diff against what RevenueCat has, and the create / attach plan `storebound revenuecat sync` runs. No IO.
// storebound only mirrors the catalog. Runtime entitlements, receipt and purchase token validation, customer info,
// webhooks, paywalls, store server notifications and the store credentials inside RevenueCat stay RevenueCat's job.
// Sources (checked October 2026):
// REST API v2 overview (base URL, Bearer v2 secret keys, pagination: items / next_page / starting_after / limit,
// rate limits: 429 + Retry-After seconds, 60 requests per minute for project configuration)
// https://www.revenuecat.com/docs/api-v2
// Products: store_identifier (Apple: product id; Play: "<productId>:<basePlanId>" for subscriptions, the product id
// for one-time products), app_id, type (subscription | one_time | consumable | non_consumable |
// non_renewing_subscription), display_name https://www.revenuecat.com/docs/api-v2/product
// Entitlements: lookup_key, display_name, actions/attach_products { product_ids }, GET .../{id}/products
// https://www.revenuecat.com/docs/api-v2/entitlement
// Offerings: lookup_key, display_name; is_current only on update (POST /offerings/{id})
// https://www.revenuecat.com/docs/api-v2/offering
// Packages: lookup_key, display_name, position; actions/attach_products { products: [{ product_id,
// eligibility_criteria: all | google_sdk_lt_6 | google_sdk_ge_6 }] } https://www.revenuecat.com/docs/api-v2/package
// Apps: type app_store (app_store.bundle_id) | play_store (play_store.package_name)
// https://www.revenuecat.com/docs/api-v2/app
// Reserved package identifiers ($rc_weekly ... $rc_annual, $rc_lifetime): PackageType of the RevenueCat SDK
// https://github.com/RevenueCat/purchases-ios/blob/main/Sources/Purchasing/PackageType.swift
import { type ProductType, sellsOn, type ShipConfig, type SubscriptionPeriod } from './config';
import { allSubscriptions, basePlanId } from './subscriptions';
export type RcStore = 'apple' | 'play';
export type RcProductType = 'subscription' | 'one_time' | 'consumable' | 'non_consumable' | 'non_renewing_subscription';
/** What stays outside storebound (command header, diff footer, skill). */
export const RC_SCOPE = 'storebound mirrors the catalog only (products, entitlements, one offering). RevenueCat keeps: runtime entitlements, ' +
'receipt / purchase token validation, customer info, webhooks, paywalls, store server notifications setup, and the App Store / Play ' +
'credentials inside RevenueCat (in-app purchase key, service account).';
/** Reserved package identifiers by billing period (RevenueCat SDK PackageType). */
export const RC_PACKAGE: Record<SubscriptionPeriod, string> = {
P1W: '$rc_weekly', P1M: '$rc_monthly', P2M: '$rc_two_month', P3M: '$rc_three_month', P6M: '$rc_six_month', P1Y: '$rc_annual',
};
export const RC_LIFETIME = '$rc_lifetime';
const PACKAGE_NAME: Record<string, string> = {
$rc_weekly: 'Weekly', $rc_monthly: 'Monthly', $rc_two_month: 'Two months', $rc_three_month: 'Three months',
$rc_six_month: 'Six months', $rc_annual: 'Annual', $rc_lifetime: 'Lifetime',
};
/** RevenueCat product type per store. Play has no non-renewing type: config.ts sells it as a one-time product the
* app consumes when the access ends, so it is a consumable there. */
export function rcType(kind: ProductType | 'subscription', store: RcStore): RcProductType {
if (kind === 'subscription') return 'subscription';
if (kind === 'non_renewing') return store === 'apple' ? 'non_renewing_subscription' : 'consumable';
return kind;
}
export interface WantProduct { key: string; configId: string; store: RcStore; storeIdentifier: string; type: RcProductType; displayName: string }
export interface WantEntitlement { lookupKey: string; displayName: string; products: string[] }
export interface WantPackage { lookupKey: string; displayName: string; position: number; configId: string; products: string[] }
export interface RcWanted {
products: WantProduct[];
entitlements: WantEntitlement[];
offering: { lookupKey: string; displayName: string; packages: WantPackage[] };
problems: string[];
}
/** Product key used across the plan: "<store>:<store_identifier>". */
export const productKey = (store: RcStore, storeIdentifier: string): string => `${store}:${storeIdentifier}`;
/** The RevenueCat state the config implies. `platforms` on an item and app.platforms are respected. */
export function wantedRevenueCat(config: ShipConfig): RcWanted {
const rc = config.revenuecat;
const problems: string[] = [];
const products: WantProduct[] = [];
const byConfigId = new Map<string, { kind: ProductType | 'subscription'; keys: string[]; title: string; period?: SubscriptionPeriod }>();
const add = (id: string, kind: ProductType | 'subscription', title: string, item: { platforms?: ('ios' | 'android')[] }, playId: string, period?: SubscriptionPeriod) => {
const keys: string[] = [];
for (const store of ['apple', 'play'] as const) {
if (!sellsOn(config, item, store)) continue;
const storeIdentifier = store === 'apple' ? id : playId;
const key = productKey(store, storeIdentifier);
products.push({ key, configId: id, store, storeIdentifier, type: rcType(kind, store), displayName: title });
keys.push(key);
}
byConfigId.set(id, { kind, keys, title, period });
};
const firstTitle = (l: Record<string, { title: string }>, id: string) => Object.values(l)[0]?.title || id;
for (const p of config.products ?? []) add(p.id, p.type, firstTitle(p.listings, p.id), p, p.id);
const subs = allSubscriptions(config.subscriptions).map(x => x.sub);
for (const s of subs) add(s.id, 'subscription', firstTitle(s.listings, s.id), s, `${s.id}:${basePlanId(s)}`, s.period);
const unlocks = [...(config.products ?? []).filter(p => p.type !== 'consumable').map(p => p.id), ...subs.map(s => s.id)];
const ents = rc?.entitlements ?? (unlocks.length ? { pro: unlocks } : {});
const entitlements: WantEntitlement[] = [];
const inEntitlement = new Set<string>();
for (const [lookupKey, ids] of Object.entries(ents)) {
const keys: string[] = [];
for (const id of ids) {
const it = byConfigId.get(id);
if (!it) { problems.push(`revenuecat.entitlements.${lookupKey}: "${id}" is not a product or subscription in the config`); continue; }
if (it.kind === 'consumable') { problems.push(`revenuecat.entitlements.${lookupKey}: "${id}" is a consumable; consumables do not unlock an entitlement`); continue; }
inEntitlement.add(id);
keys.push(...it.keys);
}
entitlements.push({ lookupKey, displayName: lookupKey, products: keys });
}
const packages: WantPackage[] = [];
const used = new Set<string>();
const pkg = (lookupKey: string, configId: string) => {
const it = byConfigId.get(configId)!;
if (!it.keys.length) return;
used.add(lookupKey);
packages.push({ lookupKey, displayName: PACKAGE_NAME[lookupKey] ?? it.title, position: packages.length + 1, configId, products: it.keys });
};
for (const s of subs) pkg(used.has(RC_PACKAGE[s.period]) ? s.id : RC_PACKAGE[s.period], s.id);
for (const p of config.products ?? []) {
const lifetime = p.type === 'non_consumable' && inEntitlement.has(p.id) && !used.has(RC_LIFETIME) && byConfigId.get(p.id)!.keys.length > 0;
pkg(lifetime ? RC_LIFETIME : p.id, p.id);
}
const lk = rc?.offering ?? 'default';
return { products, entitlements, offering: { lookupKey: lk, displayName: lk === 'default' ? 'Default' : lk, packages }, problems };
}
// ---- RevenueCat side (as read by the command) ----
export interface RcApp { id: string; name?: string; type: string; app_store?: { bundle_id?: string } | null; play_store?: { package_name?: string } | null }
export interface RcProduct { id: string; store_identifier: string; type: string; app_id: string; display_name?: string | null; state?: string }
export interface RcEntitlement { id: string; lookup_key: string; display_name?: string; state?: string; productIds: string[] }
export interface RcPackage { id: string; lookup_key: string; display_name?: string; position?: number | null; products: { product_id: string; eligibility_criteria?: string }[] }
export interface RcOffering { id: string; lookup_key: string; display_name?: string; is_current?: boolean; state?: string; packages: RcPackage[] }
export interface RcState { products: RcProduct[]; entitlements: RcEntitlement[]; offerings: RcOffering[] }
export type RcAppIds = Partial<Record<RcStore, string>>;
/** App ids from revenuecat.apps, else the project's App Store app with the bundle id / Play app with the package name. */
export function resolveApps(config: ShipConfig, apps: RcApp[] | null): { ids: RcAppIds; problems: string[] } {
const ids: RcAppIds = {};
const problems: string[] = [];
const set = config.revenuecat?.apps ?? {};
const want: [RcStore, string | undefined, string, (a: RcApp) => boolean][] = [
['apple', config.apple?.bundleId, 'App Store', a => a.type === 'app_store' && a.app_store?.bundle_id === config.apple?.bundleId],
['play', config.play?.packageName, 'Play Store', a => a.type === 'play_store' && a.play_store?.package_name === config.play?.packageName],
];
for (const [store, ident, label, match] of want) {
if (!sellsOn(config, {}, store)) continue;
if (set[store]) { ids[store] = set[store]; continue; }
const hit = (apps ?? []).filter(match);
if (hit.length === 1) ids[store] = hit[0]!.id;
else if (hit.length > 1) problems.push(`${hit.length} ${label} apps in the project for ${ident}: set revenuecat.apps.${store}`);
else problems.push(`no ${label} app for ${ident ?? '(no id in the config)'} in the RevenueCat project: add it in RevenueCat (Project settings > Apps) or set revenuecat.apps.${store}`);
}
return { ids, problems };
}
// ---- diff ----
export type RcSection = 'app' | 'config' | 'product' | 'entitlement' | 'offering' | 'package';
export type RcStatus = 'ok' | 'missing' | 'mismatch' | 'extra' | 'info';
export interface RcRow { section: RcSection; key: string; status: RcStatus; msg: string }
/** Rows that make the project out of sync (exit 1): missing and mismatched. Extras are left alone and do not count. */
export const outOfSync = (rows: RcRow[]): number => rows.filter(r => r.status === 'missing' || r.status === 'mismatch').length;
interface Index { byKey: Map<string, RcProduct>; keyOf: Map<string, string>; storeOfApp: Map<string, RcStore> }
function index(state: RcState, apps: RcAppIds): Index {
const storeOfApp = new Map<string, RcStore>(Object.entries(apps).map(([s, id]) => [id!, s as RcStore]));
const byKey = new Map<string, RcProduct>();
const keyOf = new Map<string, string>();
for (const p of state.products) {
const s = storeOfApp.get(p.app_id);
if (!s) continue;
const k = productKey(s, p.store_identifier);
byKey.set(k, p); keyOf.set(p.id, k);
}
return { byKey, keyOf, storeOfApp };
}
const isSub = (t: string) => t === 'subscription';
/** RevenueCat type vs wanted: "one_time" (the generic one-time type) fits any one-time kind. */
const typeFits = (want: RcProductType, have: string) => have === want || (have === 'one_time' && !isSub(want));
/** Config vs RevenueCat. Products are only compared on the resolved store apps (other apps, e.g. web, are ignored). */
export function rcDiff(want: RcWanted, state: RcState, apps: RcAppIds, appProblems: string[] = []): RcRow[] {
const rows: RcRow[] = [];
const row = (section: RcSection, key: string, status: RcStatus, msg: string) => rows.push({ section, key, status, msg });
for (const p of appProblems) row('app', '-', 'missing', p);
for (const p of want.problems) row('config', '-', 'mismatch', p);
const ix = index(state, apps);
const wantedKeys = new Set(want.products.map(p => p.key));
for (const w of want.products) {
if (!apps[w.store]) continue;
const h = ix.byKey.get(w.key);
if (!h) row('product', w.key, 'missing', `${w.type} "${w.displayName}" is not in RevenueCat`);
else if (!typeFits(w.type, h.type)) row('product', w.key, 'mismatch', `type ${h.type} in RevenueCat, ${w.type} in the config (change it in RevenueCat; sync never updates)`);
else if (h.state === 'inactive') row('product', w.key, 'mismatch', 'archived in RevenueCat (unarchive it there)');
else row('product', w.key, 'ok', `${h.type}, ${h.id}`);
}
for (const [k, h] of ix.byKey) if (!wantedKeys.has(k)) row('product', k, 'extra', `in RevenueCat but not in the config (${h.type}), left alone`);
const ents = new Map(state.entitlements.map(e => [e.lookup_key, e] as const));
for (const w of want.entitlements) {
const keys = w.products.filter(k => apps[k.split(':')[0] as RcStore]);
const h = ents.get(w.lookupKey);
if (!h) { row('entitlement', w.lookupKey, 'missing', `not in RevenueCat; would unlock ${keys.length} product(s): ${keys.join(', ') || '-'}`); continue; }
if (h.state === 'inactive') row('entitlement', w.lookupKey, 'mismatch', 'archived in RevenueCat (unarchive it there)');
const attached = new Set(h.productIds.map(id => ix.keyOf.get(id)).filter((x): x is string => !!x));
const missing = keys.filter(k => !attached.has(k));
for (const k of missing) row('entitlement', `${w.lookupKey} <- ${k}`, 'missing', 'product not attached');
for (const k of attached) if (!w.products.includes(k)) row('entitlement', `${w.lookupKey} <- ${k}`, 'extra', 'attached in RevenueCat but not in the config, left alone');
if (!missing.length && h.state !== 'inactive') row('entitlement', w.lookupKey, 'ok', `${attached.size} product(s) attached`);
}
const wantedEnts = new Set(want.entitlements.map(e => e.lookupKey));
for (const e of state.entitlements) if (!wantedEnts.has(e.lookup_key)) row('entitlement', e.lookup_key, 'extra', 'in RevenueCat but not in the config, left alone');
const o = want.offering;
const ho = state.offerings.find(x => x.lookup_key === o.lookupKey);
if (!ho) row('offering', o.lookupKey, 'missing', `not in RevenueCat; ${o.packages.length} package(s): ${o.packages.map(p => p.lookupKey).join(', ') || '-'}`);
else {
if (ho.state === 'inactive') row('offering', o.lookupKey, 'mismatch', 'archived in RevenueCat (unarchive it there)');
row('offering', o.lookupKey, ho.is_current ? 'ok' : 'info', ho.is_current ? 'the current offering' : 'not the current offering (choose it in RevenueCat, or run sync --current)');
const pk = new Map(ho.packages.map(p => [p.lookup_key, p] as const));
for (const w of o.packages) {
const h = pk.get(w.lookupKey);
if (!h) { row('package', w.lookupKey, 'missing', `not in the offering; would hold ${w.products.filter(k => apps[k.split(':')[0] as RcStore]).join(', ') || '-'}`); continue; }
let bad = 0;
for (const k of w.products) {
const store = k.split(':')[0] as RcStore;
if (!apps[store]) continue;
const want = ix.byKey.get(k);
const same = h.products.map(x => state.products.find(p => p.id === x.product_id)).filter((p): p is RcProduct => !!p && p.app_id === apps[store]);
if (want && same.some(p => p.id === want.id)) continue;
bad++;
if (same.length) row('package', `${w.lookupKey} <- ${k}`, 'mismatch', `holds ${same.map(p => p.store_identifier).join(', ')} for ${store} (change it in RevenueCat; sync never detaches)`);
else row('package', `${w.lookupKey} <- ${k}`, 'missing', 'product not attached');
}
if (!bad) row('package', w.lookupKey, 'ok', `${h.products.length} product(s)`);
}
const wantedPk = new Set(o.packages.map(p => p.lookupKey));
for (const h of ho.packages) if (!wantedPk.has(h.lookup_key)) row('package', h.lookup_key, 'extra', 'in the offering but not in the config, left alone');
}
const rank: Record<RcStatus, number> = { mismatch: 0, missing: 1, extra: 2, info: 3, ok: 4 };
const order: Record<RcSection, number> = { app: 0, config: 1, product: 2, entitlement: 3, offering: 4, package: 5 };
return rows.map((r, i) => ({ r, i })).sort((a, b) => rank[a.r.status] - rank[b.r.status] || order[a.r.section] - order[b.r.section] || a.i - b.i).map(x => x.r);
}
// ---- sync plan ----
export type RcStep =
| { op: 'create-product'; key: string; body: { store_identifier: string; app_id: string; type: RcProductType; display_name: string }; what: string }
| { op: 'create-entitlement'; lookupKey: string; body: { lookup_key: string; display_name: string }; what: string }
| { op: 'attach-entitlement'; lookupKey: string; products: string[]; what: string }
| { op: 'create-offering'; lookupKey: string; body: { lookup_key: string; display_name: string }; what: string }
| { op: 'create-package'; lookupKey: string; body: { lookup_key: string; display_name: string; position: number }; what: string }
| { op: 'attach-package'; lookupKey: string; products: string[]; what: string }
| { op: 'set-current'; lookupKey: string; what: string };
/** The API takes at most 50 products per attach call. */
const chunks = <T>(a: T[], n = 50): T[][] => Array.from({ length: Math.ceil(a.length / n) }, (_, i) => a.slice(i * n, i * n + n));
/**
* Creates and attaches only, in dependency order: products, entitlements, entitlement attachments, the offering, its
* packages, package attachments, and (only with `current`) making the offering the current one. Nothing RevenueCat has
* beyond the config is deleted, detached, archived or changed. Products on a store without a resolved app are skipped.
*/
export function rcPlan(want: RcWanted, state: RcState, apps: RcAppIds, o: { current?: boolean } = {}): RcStep[] {
const ix = index(state, apps);
const steps: RcStep[] = [];
const onApp = (k: string) => !!apps[k.split(':')[0] as RcStore];
for (const w of want.products) {
if (!apps[w.store] || ix.byKey.has(w.key)) continue;
steps.push({ op: 'create-product', key: w.key, body: { store_identifier: w.storeIdentifier, app_id: apps[w.store]!, type: w.type, display_name: w.displayName },
what: `create product ${w.key} (${w.type}, "${w.displayName}")` });
}
const ents = new Map(state.entitlements.map(e => [e.lookup_key, e] as const));
const attachE: RcStep[] = [];
for (const w of want.entitlements) {
const h = ents.get(w.lookupKey);
if (!h) steps.push({ op: 'create-entitlement', lookupKey: w.lookupKey, body: { lookup_key: w.lookupKey, display_name: w.displayName }, what: `create entitlement ${w.lookupKey}` });
const attached = new Set((h?.productIds ?? []).map(id => ix.keyOf.get(id)));
const add = w.products.filter(k => onApp(k) && !attached.has(k));
for (const c of chunks(add)) attachE.push({ op: 'attach-entitlement', lookupKey: w.lookupKey, products: c, what: `attach to entitlement ${w.lookupKey}: ${c.join(', ')}` });
}
steps.push(...attachE);
const ow = want.offering;
const ho = state.offerings.find(x => x.lookup_key === ow.lookupKey);
if (ow.packages.length || ho) {
if (!ho) steps.push({ op: 'create-offering', lookupKey: ow.lookupKey, body: { lookup_key: ow.lookupKey, display_name: ow.displayName }, what: `create offering ${ow.lookupKey}` });
const pk = new Map((ho?.packages ?? []).map(p => [p.lookup_key, p] as const));
const taken = new Set((ho?.packages ?? []).map(p => p.position).filter((x): x is number => typeof x === 'number'));
let next = Math.max(0, ...taken) + 1;
const attachP: RcStep[] = [];
for (const w of ow.packages) {
const h = pk.get(w.lookupKey);
if (!h) {
const position = taken.has(w.position) ? next++ : w.position;
taken.add(position); next = Math.max(next, position + 1);
steps.push({ op: 'create-package', lookupKey: w.lookupKey, body: { lookup_key: w.lookupKey, display_name: w.displayName, position }, what: `create package ${w.lookupKey} ("${w.displayName}", position ${position})` });
}
const add = w.products.filter(k => {
if (!onApp(k)) return false;
if (!h) return true;
const app = apps[k.split(':')[0] as RcStore];
// one product per store app in a package: never attach next to (or instead of) one the owner put there
return !h.products.some(x => state.products.find(p => p.id === x.product_id)?.app_id === app);
});
for (const c of chunks(add)) attachP.push({ op: 'attach-package', lookupKey: w.lookupKey, products: c, what: `attach to package ${w.lookupKey}: ${c.join(', ')}` });
}
steps.push(...attachP);
if (o.current && !ho?.is_current) steps.push({ op: 'set-current', lookupKey: ow.lookupKey, what: `make offering ${ow.lookupKey} the current offering (changes what the apps show by default)` });
}
return steps;
}

View file

@ -23,6 +23,9 @@ import t18 from '../../templates/profiles/subscription-app/storebound.config.ts'
import t19 from '../../templates/shots-copy.json' with { type: 'text' }; import t19 from '../../templates/shots-copy.json' with { type: 'text' };
import t20 from '../../templates/storebound.config.ts' with { type: 'text' }; import t20 from '../../templates/storebound.config.ts' with { type: 'text' };
import t21 from '../../templates/testers.csv' with { type: 'text' }; import t21 from '../../templates/testers.csv' with { type: 'text' };
import tWebAppstore from '../../templates/web/appstore.svg' with { type: 'text' };
import tWebGoogleplay from '../../templates/web/googleplay.svg' with { type: 'text' };
import tWebLanding from '../../templates/web/landing.html' with { type: 'text' };
/** Template text by its path under templates/ (forward slashes). */ /** Template text by its path under templates/ (forward slashes). */
export const TEMPLATE_TEXT: Record<string, string> = { export const TEMPLATE_TEXT: Record<string, string> = {
@ -48,4 +51,7 @@ export const TEMPLATE_TEXT: Record<string, string> = {
'shots-copy.json': t19 as unknown as string, 'shots-copy.json': t19 as unknown as string,
'storebound.config.ts': t20 as unknown as string, 'storebound.config.ts': t20 as unknown as string,
'testers.csv': t21 as unknown as string, 'testers.csv': t21 as unknown as string,
'web/appstore.svg': tWebAppstore as unknown as string,
'web/googleplay.svg': tWebGoogleplay as unknown as string,
'web/landing.html': tWebLanding as unknown as string,
}; };

294
cli/lib/web.ts Normal file
View file

@ -0,0 +1,294 @@
// Web presence for an app: universal links (apple-app-site-association), Android App Links (Digital Asset Links
// assetlinks.json), the Smart App Banner tag and a minimal landing page. Pure: builders and validators, no IO.
// Sources (checked October 2026):
// https://developer.apple.com/documentation/xcode/supporting-associated-domains (AASA format: applinks.details[]
// .appIDs + components with "/", "?", "#", "exclude", "comment"; webcredentials.apps; served at
// https://<domain>/.well-known/apple-app-site-association, no extension, HTTPS with a valid certificate, no
// redirects; since iOS 14 / macOS 11 Apple's CDN fetches it, devices recheck about once a week)
// https://developer.apple.com/documentation/technotes/tn3155-debugging-universal-links (no 301/302, reachable from
// every IP, every user agent; legacy appID + paths format still read, do not mix the two)
// Content type application/json and the 128 KB limit (uncompressed) come from Apple's archived "Support Universal
// Links" guide; the current pages do not restate them, so check treats a non-JSON type and > 128 KB as problems.
// https://developer.apple.com/documentation/webkit/promoting-apps-with-smart-app-banners
// (<meta name="apple-itunes-app" content="app-id=..., app-argument=...">, in the head of each page)
// https://developer.android.com/training/app-links/configure-assetlinks (statement list: relation
// ["delegate_permission/common.handle_all_urls"], target { namespace "android_app", package_name,
// sha256_cert_fingerprints ["AB:CD:..."] }; https://<domain>/.well-known/assetlinks.json, content-type
// application/json, HTTPS, no redirects; relation_extensions.dynamic_app_link_components on Android 15+)
// https://developer.android.com/training/app-links/verify-android-applinks (autoVerify, per-host lookup)
import type { ShipConfig } from './config';
export const AASA_PATH = '/.well-known/apple-app-site-association';
export const AASA_LEGACY_PATH = '/apple-app-site-association';
export const ASSETLINKS_PATH = '/.well-known/assetlinks.json';
export const HANDLE_ALL_URLS = 'delegate_permission/common.handle_all_urls';
export const AASA_MAX_BYTES = 128 * 1024;
export type Level = 'ok' | 'problem' | 'info';
export interface Finding { level: Level; message: string; fix?: string }
type Cfg = Pick<ShipConfig, 'app' | 'apple' | 'play' | 'web'>;
const appIdOf = (c: Cfg): string | null => (c.apple?.teamId && c.apple.bundleId ? `${c.apple.teamId}.${c.apple.bundleId}` : null);
const pathsOf = (c: Cfg): string[] => (c.web?.paths?.length ? c.web.paths : ['/*']);
/** apple-app-site-association for the config, null without an apple section with a teamId. Excluded paths come
* first: the system stops at the first component that matches. */
export function aasaFor(c: Cfg): Record<string, unknown> | null {
const id = appIdOf(c);
if (!id) return null;
const components = [
...(c.web?.exclude ?? []).map(p => ({ '/': p, exclude: true, comment: 'stays in the browser' })),
...pathsOf(c).map(p => ({ '/': p })),
];
return {
applinks: { details: [{ appIDs: [id], components }] },
...(c.web?.webcredentials ? { webcredentials: { apps: [id] } } : {}),
};
}
/** assetlinks.json for the config, null without a play section or without a fingerprint. With web.exclude it adds
* dynamic rules (Android 15+; older versions ignore them and use the intent filters only). */
export function assetLinksFor(c: Cfg, fingerprints = c.web?.androidSha256 ?? []): Record<string, unknown>[] | null {
if (!c.play?.packageName || !fingerprints.length) return null;
const st: Record<string, unknown> = {
relation: [HANDLE_ALL_URLS],
target: { namespace: 'android_app', package_name: c.play.packageName, sha256_cert_fingerprints: fingerprints },
};
if (c.web?.exclude?.length) st.relation_extensions = {
[HANDLE_ALL_URLS]: { dynamic_app_link_components: [...c.web.exclude.map(p => ({ '/': p, exclude: true })), ...pathsOf(c).map(p => ({ '/': p }))] },
};
return [st];
}
const esc = (s: string): string => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
/** The Smart App Banner meta tag, null without apple.appId. */
export function smartBannerTag(c: Cfg, appArgument?: string): string | null {
if (!c.apple?.appId) return null;
return `<meta name="apple-itunes-app" content="app-id=${esc(c.apple.appId)}${appArgument ? `, app-argument=${esc(appArgument)}` : ''}">`;
}
export const appStoreUrl = (appId: string): string => `https://apps.apple.com/app/id${appId}`;
export const playUrl = (pkg: string): string => `https://play.google.com/store/apps/details?id=${pkg}`;
/** templates/web/landing.html with the config filled in. Blocks between <!--x--> and <!--/x--> (apple, play, terms)
* are dropped when the config has nothing for them. */
export function fillLanding(template: string, c: Cfg): string {
const keep: Record<string, boolean> = { apple: !!c.apple?.appId, play: !!c.play?.packageName, terms: !!c.app.termsUrl };
let s = template.replace(/<!--(\w+)-->([\s\S]*?)<!--\/\1-->/g, (_, k: string, body: string) => (keep[k] ? body : ''));
s = s.replace(/^[ \t]*\n/gm, '');
const tag = smartBannerTag(c);
s = s.replace(/^([ \t]*)<!--\{\{SMART_BANNER\}\}-->\n/m, (_, ind: string) => (tag ? `${ind}${tag}\n` : ''));
const vals: Record<string, string> = {
APP_NAME: c.app.name,
APP_STORE_URL: c.apple?.appId ? appStoreUrl(c.apple.appId) : '',
PLAY_URL: c.play?.packageName ? playUrl(c.play.packageName) : '',
PRIVACY_URL: c.app.privacyPolicyUrl,
SUPPORT_URL: c.app.supportUrl,
TERMS_URL: c.app.termsUrl ?? '',
};
return s.replace(/\{\{([A-Z_]+)\}\}/g, (m, k: string) => (k in vals ? esc(vals[k]!) : m));
}
/** Any SHA-256 form (AB:CD:.. , plain hex in any case, base64 / base64url of the 32 bytes) -> "AB:CD:..." or null.
* The Play Developer API documents certificateSha256Hash only as "SHA256 hash of the APK signing public key
* certificate" (type string, encoding not stated), so both hex and base64 are accepted. */
export function normalizeFingerprint(s: string): string | null {
const t = s.trim();
const plain = t.replace(/[:\s]/g, '');
let hex: string | undefined;
if (/^[0-9a-fA-F]{64}$/.test(plain)) hex = plain;
else if (/^[A-Za-z0-9+/_-]{43}=?$/.test(t)) {
const b = Buffer.from(t.replace(/-/g, '+').replace(/_/g, '/'), 'base64');
if (b.length === 32) hex = b.toString('hex');
}
return hex ? hex.toUpperCase().match(/../g)!.join(':') : null;
}
const isObj = (x: unknown): x is Record<string, unknown> => !!x && typeof x === 'object' && !Array.isArray(x);
const strs = (x: unknown): x is string[] => Array.isArray(x) && x.every(v => typeof v === 'string');
const COMPONENT_KEYS = new Set(['/', '?', '#', 'exclude', 'comment', 'caseSensitive', 'percentEncoded']);
const REGEN = 'regenerate with `storebound web init` and deploy the file again';
/** Shape and ids of an apple-app-site-association document. ids missing = shape only. */
export function validateAasa(json: unknown, ids: { teamId?: string; bundleId?: string; webcredentials?: boolean }): Finding[] {
const f: Finding[] = [];
const bad = (message: string, fix = REGEN) => f.push({ level: 'problem', message, fix });
if (!isObj(json)) { bad('not a JSON object'); return f; }
const al = json.applinks;
if (!isObj(al)) { bad('no "applinks" object'); return f; }
if (!Array.isArray(al.details) || !al.details.length) { bad('"applinks.details" is not a non-empty list'); return f; }
const found: string[] = [];
for (const [i, d] of al.details.entries()) {
const at = `applinks.details[${i}]`;
if (!isObj(d)) { bad(`${at} is not an object`); continue; }
const modern = 'appIDs' in d || 'components' in d, legacy = 'appID' in d || 'paths' in d;
if (modern && legacy) bad(`${at} mixes appIDs/components with the legacy appID/paths keys`);
if (modern) {
if (!strs(d.appIDs) || !d.appIDs.length) bad(`${at}.appIDs is not a non-empty list of strings`);
else found.push(...d.appIDs);
if (!Array.isArray(d.components) || !d.components.length) bad(`${at}.components is not a non-empty list: no URL opens the app`);
else {
for (const [j, c] of d.components.entries()) {
const cat = `${at}.components[${j}]`;
if (!isObj(c)) { bad(`${cat} is not an object`); continue; }
if ('/' in c && typeof c['/'] !== 'string') bad(`${cat}["/"] is not a string`);
if ('#' in c && typeof c['#'] !== 'string') bad(`${cat}["#"] is not a string`);
if ('?' in c && !(typeof c['?'] === 'string' || (isObj(c['?']) && Object.values(c['?']).every(v => typeof v === 'string')))) bad(`${cat}["?"] is not an object of strings`);
if ('exclude' in c && typeof c.exclude !== 'boolean') bad(`${cat}.exclude is not true / false`);
const odd = Object.keys(c).filter(k => !COMPONENT_KEYS.has(k));
if (odd.length) f.push({ level: 'info', message: `${cat}: unknown keys ${odd.join(', ')} (ignored by the system)` });
}
if (d.components.every(c => isObj(c) && c.exclude === true)) bad(`${at}: every component is excluded, no URL opens the app`);
}
} else if (legacy) {
if (typeof d.appID !== 'string') bad(`${at}.appID is not a string`); else found.push(d.appID);
if (!strs(d.paths)) bad(`${at}.paths is not a list of strings`);
f.push({ level: 'info', message: `${at} uses the legacy appID / paths format (iOS 12 and earlier); iOS 13+ reads appIDs / components`, fix: REGEN });
} else bad(`${at} has neither appIDs nor appID`);
}
for (const id of found) if (!/^[A-Z0-9]{10}\.[A-Za-z0-9.*-]+$/.test(id)) bad(`app id "${id}" is not <Team ID>.<bundle id>`);
const want = ids.teamId && ids.bundleId ? `${ids.teamId}.${ids.bundleId}` : '';
if (want) {
if (found.includes(want)) f.push({ level: 'ok', message: `applinks lists ${want}` });
else bad(`applinks does not list ${want} (found: ${found.join(', ') || 'none'})`, 'check apple.teamId (Membership details) and apple.bundleId, then ' + REGEN);
} else f.push({ level: 'info', message: 'apple.teamId or apple.bundleId not in the config: app ids not compared', fix: 'set apple.teamId (developer.apple.com > Account > Membership details)' });
if ('webcredentials' in json) {
const wc = json.webcredentials;
if (!isObj(wc) || !strs(wc.apps)) bad('"webcredentials.apps" is not a list of strings');
else if (want && ids.webcredentials && !wc.apps.includes(want)) bad(`webcredentials.apps does not list ${want}`);
} else if (want && ids.webcredentials) bad('web.webcredentials is on but the file has no "webcredentials" section');
return f;
}
/** Shape and ids of an assetlinks.json statement list. */
export function validateAssetLinks(json: unknown, ids: { packageName?: string; fingerprints?: string[] }): Finding[] {
const f: Finding[] = [];
const bad = (message: string, fix = REGEN) => f.push({ level: 'problem', message, fix });
if (!Array.isArray(json)) { bad(isObj(json) ? 'a JSON object, not a list of statements ([{ relation, target }])' : 'not a list of statements'); return f; }
if (!json.length) { bad('empty statement list'); return f; }
const mine: Record<string, unknown>[] = [];
for (const [i, s] of json.entries()) {
const at = `statement ${i}`;
if (!isObj(s) || !strs(s.relation) || !isObj(s.target)) { bad(`${at}: needs "relation" (list of strings) and "target" (object)`); continue; }
const t = s.target;
if (t.namespace === 'android_app') {
if (typeof t.package_name !== 'string') bad(`${at}: target.package_name missing`);
if (!strs(t.sha256_cert_fingerprints) || !t.sha256_cert_fingerprints.length) bad(`${at}: target.sha256_cert_fingerprints is not a non-empty list`);
else for (const fp of t.sha256_cert_fingerprints) if (!/^([0-9A-F]{2}:){31}[0-9A-F]{2}$/.test(fp)) bad(`${at}: fingerprint "${fp.slice(0, 20)}..." is not in the AB:CD:... form (32 upper-case hex pairs)`);
if (!ids.packageName || t.package_name === ids.packageName) mine.push(s);
} else if (t.namespace !== 'web') bad(`${at}: target.namespace "${String(t.namespace)}" is not android_app or web`);
}
if (!ids.packageName) { f.push({ level: 'info', message: 'play.packageName not in the config: package not compared' }); return f; }
if (!mine.length) { bad(`no android_app statement for ${ids.packageName}`); return f; }
const linked = mine.filter(s => (s.relation as string[]).includes(HANDLE_ALL_URLS));
if (!linked.length) { bad(`the statement for ${ids.packageName} has relation ${JSON.stringify(mine[0]!.relation)}, not ${HANDLE_ALL_URLS}`); return f; }
f.push({ level: 'ok', message: `${ids.packageName} has ${HANDLE_ALL_URLS}` });
const live = new Set(linked.flatMap(s => ((s.target as Record<string, unknown>).sha256_cert_fingerprints as string[] | undefined) ?? []).map(x => normalizeFingerprint(x) ?? x));
const want = (ids.fingerprints ?? []).map(x => normalizeFingerprint(x) ?? x);
if (!want.length) { f.push({ level: 'info', message: 'web.androidSha256 not in the config: fingerprints not compared', fix: 'copy the SHA-256 from Play Console > App integrity > Play app signing' }); return f; }
const missing = want.filter(x => !live.has(x)), extra = [...live].filter(x => !want.includes(x));
for (const m of missing) bad(`fingerprint ${m.slice(0, 11)}... from web.androidSha256 is missing: app links do not verify for builds signed with it`);
if (!missing.length) f.push({ level: 'ok', message: `all ${want.length} fingerprint(s) from web.androidSha256 are listed` });
for (const x of extra) f.push({ level: 'info', message: `extra fingerprint ${x.slice(0, 11)}... (not in web.androidSha256; fine for a debug or upload key)` });
return f;
}
/** What a fetch of one of the files returned (the command fills it in; tests build it by hand). */
export interface Fetched { url: string; status: number; location?: string; contentType: string; body: string; bytes: number }
export interface Check { id: string; url: string; ok: boolean; level: Level; message: string; fix?: string }
const check = (id: string, url: string, x: Finding): Check => ({ id, url, ok: x.level !== 'problem', level: x.level, message: x.message, ...(x.fix ? { fix: x.fix } : {}) });
/** Transport checks shared by both files: status, redirects, content type, size, JSON. Returns the parsed JSON (or
* undefined when it could not be read). */
function transport(id: string, r: Fetched, o: { anyJsonType: boolean; maxBytes?: number; host: string }): { checks: Check[]; json?: unknown } {
const out: Check[] = [];
const add = (level: Level, message: string, fix?: string) => out.push(check(id, r.url, { level, message, fix }));
if (r.status >= 300 && r.status < 400) {
add('problem', `HTTP ${r.status} redirect to ${r.location ?? '(no Location)'}`, `serve the file directly at ${r.url} with status 200 (no http->https, apex->www or trailing-slash redirect for this path)`);
return { checks: out };
}
if (r.status !== 200) { add('problem', `HTTP ${r.status}`, `upload the file from your web init output folder to ${o.host}${new URL(r.url).pathname}; it must be public (no login, no IP or bot blocking)`); return { checks: out }; }
add('ok', 'HTTP 200, no redirect');
const ct = r.contentType.toLowerCase();
const jsonType = o.anyJsonType ? /^application\/([\w.+-]*\+)?json\b/.test(ct) : /^application\/json\b/.test(ct);
if (jsonType) add('ok', `content-type ${r.contentType}`);
else add('problem', `content-type is "${r.contentType || 'missing'}", not application/json`, 'set Content-Type: application/json for this path on the web server or host (e.g. a headers rule)');
if (o.maxBytes !== undefined) {
if (r.bytes > o.maxBytes) add('problem', `${r.bytes} bytes, over the ${o.maxBytes / 1024} KB limit`, 'shorten the file (fewer components, no comments)');
else add('ok', `${r.bytes} bytes (limit ${o.maxBytes / 1024} KB)`);
}
if (/^\s*</.test(r.body)) { add('problem', 'the body is an HTML page, not JSON (a single-page-app fallback or a custom 404 page?)', 'make the host serve the real file for this path before any rewrite rules'); return { checks: out }; }
try { return { checks: out, json: JSON.parse(r.body) }; } catch (e) {
add('problem', `not valid JSON: ${(e as Error).message.slice(0, 120)}`, REGEN);
return { checks: out };
}
}
export interface WebIds { teamId?: string; bundleId?: string; webcredentials?: boolean; packageName?: string; fingerprints?: string[]; appId?: string }
export const webIdsOf = (c: Cfg): WebIds => ({
teamId: c.apple?.teamId, bundleId: c.apple?.bundleId, webcredentials: c.web?.webcredentials, appId: c.apple?.appId,
packageName: c.play?.packageName, fingerprints: c.web?.androidSha256 ?? [],
});
/** Every check of the AASA response. */
export function checkAasa(r: Fetched, ids: WebIds, host: string): Check[] {
const t = transport('aasa', r, { anyJsonType: true, maxBytes: AASA_MAX_BYTES, host });
if (t.json === undefined) return t.checks;
return [...t.checks, ...validateAasa(t.json, ids).map(x => check('aasa', r.url, x))];
}
/** The legacy root path: informational only (Apple reads /.well-known first). */
export function checkAasaLegacy(r: Fetched): Check[] {
const msg = r.status === 200 ? 'also served at the legacy root path (fine; /.well-known is the one that counts)'
: r.status >= 300 && r.status < 400 ? `legacy root path redirects (HTTP ${r.status}); fine as long as /.well-known serves the file`
: `legacy root path not served (HTTP ${r.status}); fine, /.well-known is the one that counts`;
return [check('aasa-legacy', r.url, { level: 'info', message: msg })];
}
export function checkAssetLinks(r: Fetched, ids: WebIds, host: string): Check[] {
const t = transport('assetlinks', r, { anyJsonType: false, host });
if (t.json === undefined) return t.checks;
return [...t.checks, ...validateAssetLinks(t.json, ids).map(x => check('assetlinks', r.url, x))];
}
/** The landing page carries the Smart App Banner tag with the config's app-id. */
export function checkLanding(r: Fetched, ids: WebIds): Check[] {
if (r.status !== 200) return [check('landing', r.url, { level: 'problem', message: `HTTP ${r.status}`, fix: 'deploy index.html from the web init output folder' })];
const m = /<meta\s+[^>]*name=["']apple-itunes-app["'][^>]*>/i.exec(r.body) ?? /<meta\s+[^>]*content=["'][^"']*app-id=[^>]*name=["']apple-itunes-app["'][^>]*>/i.exec(r.body);
if (!m) return [check('landing', r.url, { level: ids.appId ? 'problem' : 'info', message: 'no apple-itunes-app meta tag (Smart App Banner)', fix: 'add the tag from smart-app-banner.html to the <head>' })];
const id = /app-id=(\d+)/.exec(m[0])?.[1];
if (ids.appId && id !== ids.appId) return [check('landing', r.url, { level: 'problem', message: `Smart App Banner app-id is ${id ?? 'missing'}, the config says ${ids.appId}`, fix: 'regenerate with `storebound web init` and redeploy index.html' })];
return [check('landing', r.url, { level: 'ok', message: `Smart App Banner app-id=${id}` })];
}
export interface PlannedFile { path: string; content: string }
/** Files web init writes (paths relative to the output folder) and what it skipped, with why and how to fix. */
export function planWeb(c: Cfg, o: { landing: boolean; template?: string; marks?: Record<string, string>; fingerprints?: string[] }): { files: PlannedFile[]; skipped: string[] } {
const files: PlannedFile[] = [], skipped: string[] = [];
const aasa = aasaFor(c);
if (aasa) files.push({ path: '.well-known/apple-app-site-association', content: JSON.stringify(aasa, null, 2) + '\n' });
else if (c.apple) skipped.push('.well-known/apple-app-site-association: apple.teamId is not set (developer.apple.com > Account > Membership details > Team ID)');
const fps = o.fingerprints ?? c.web?.androidSha256 ?? [];
const links = assetLinksFor(c, fps);
if (links) files.push({ path: '.well-known/assetlinks.json', content: JSON.stringify(links, null, 2) + '\n' });
else if (c.play) skipped.push('.well-known/assetlinks.json: no app signing fingerprint: copy the SHA-256 from Play Console > Test and release > App integrity > Play app signing into web.androidSha256, or run `storebound web init --version-code <uploaded versionCode>` to read it from the Play Developer API');
const tag = smartBannerTag(c);
if (tag) files.push({ path: 'smart-app-banner.html', content: `<!-- Smart App Banner: paste this tag into the <head> of every page that should show it (Safari on iPhone and iPad). -->\n${tag}\n` });
else if (c.apple) skipped.push('smart-app-banner.html: apple.appId is not set (App Store Connect > App Information > Apple ID)');
if (o.landing) {
if (!o.template) skipped.push('index.html: landing template not found');
else {
files.push({ path: 'index.html', content: fillLanding(o.template, c) });
if (c.apple?.appId && o.marks?.appstore) files.push({ path: 'appstore.svg', content: o.marks.appstore });
if (c.play?.packageName && o.marks?.googleplay) files.push({ path: 'googleplay.svg', content: o.marks.googleplay });
if (!c.apple?.appId && c.apple) skipped.push('index.html: App Store link left out (apple.appId is not set)');
}
}
return { files, skipped };
}

View file

@ -73,6 +73,37 @@ export const TOOLS: ToolDef[] = [
description: 'Read-only: compare the prices CSV (product, store, region, currency, price, start_date) with the current App Store and Google Play prices and print the diff table. Applying it is an owner-only terminal command (storebound prices import, asks first).', description: 'Read-only: compare the prices CSV (product, store, region, currency, price, start_date) with the current App Store and Google Play prices and print the diff table. Applying it is an owner-only terminal command (storebound prices import, asks first).',
props: { csv: { type: 'string', description: 'CSV path (default prices.csv in the config, else store/prices.csv)' }, store: { type: 'string', enum: ['apple', 'play'] }, only, all: { type: 'boolean', default: false, description: 'Also list unchanged rows' } }, props: { csv: { type: 'string', description: 'CSV path (default prices.csv in the config, else store/prices.csv)' }, store: { type: 'string', enum: ['apple', 'play'] }, only, all: { type: 'boolean', default: false, description: 'Also list unchanged rows' } },
args: i => [...opt('csv', i.csv), ...opt('store', i.store), ...opt('only', i.only), ...flag('all', i.all), '--dry'] }, args: i => [...opt('csv', i.csv), ...opt('store', i.store), ...opt('only', i.only), ...flag('all', i.all), '--dry'] },
{ name: 'prices_ppp', title: 'Purchasing power price sheet', command: ['prices', 'ppp'], write: true, network: true, idempotent: true,
description: 'Proposes per-region prices adjusted for purchasing power (bundled World Bank ICP PPP factors, CC BY 4.0, or the Big Mac index / a CSV), clamped to floor..ceiling of the US price and snapped to store price points, and writes a price sheet in the prices import format (default store/prices-ppp.csv) with a diff against the current store prices. Writes only that local file; nothing goes to a store (prices import does, after the owner confirms in a terminal).',
props: { base: { type: 'number', minimum: 0.01, description: 'USD base price for every selected product (default: each product\'s usd)' }, source: { type: 'string', enum: ['worldbank', 'bigmac', 'file'] },
store: { type: 'string', enum: ['apple', 'play'] }, only, floor: { type: 'number', minimum: 0.01, maximum: 5 }, ceiling: { type: 'number', minimum: 0.01, maximum: 5 },
offline: { type: 'boolean', default: false, description: 'No store reads: snap with the local ending rules only' } },
args: i => [...opt('base', i.base), ...opt('source', i.source), ...opt('store', i.store), ...opt('only', i.only), ...opt('floor', i.floor), ...opt('ceiling', i.ceiling), ...flag('offline', i.offline)] },
{ name: 'ads_apple_status', title: 'Apple Ads access', command: ['ads', 'apple', 'status'], write: false, network: true,
description: 'Read-only: does the Apple Ads API key work, which ad accounts and roles it has, and which one storebound uses.' },
{ name: 'ads_apple_campaigns', title: 'Apple Ads campaigns', command: ['ads', 'apple', 'campaigns'], write: false, network: true,
description: 'Read-only list of Apple Ads campaigns (status, daily budget, countries, app) for the config\'s app, or every app with all.',
props: { all: { type: 'boolean', default: false } }, args: i => flag('all', i.all) },
{ name: 'ads_apple_report', title: 'Apple Ads report', command: ['ads', 'apple', 'report'], write: false, network: true,
description: 'Read-only Apple Ads report per campaign or keyword: spend, impressions, taps, installs, TTR, conversion rate, CPA, average CPT and totals. Bids, budgets and pausing are owner decisions in a terminal, never here.',
props: { days: { type: 'integer', minimum: 1, maximum: 90, default: 7 }, by: { type: 'string', enum: ['campaign', 'keyword'], default: 'campaign' },
campaign: { type: 'string', pattern: '^\\d{1,20}$' }, all: { type: 'boolean', default: false } },
args: i => [...opt('days', i.days), ...opt('by', i.by), ...opt('campaign', i.campaign), ...flag('all', i.all)] },
{ name: 'web_init', title: 'Universal / app links files', command: ['web', 'init'], write: true, network: false, idempotent: true,
description: 'Writes apple-app-site-association, .well-known/assetlinks.json, the Smart App Banner tag and optionally a minimal landing page (store badges, privacy and support links) into a local folder (default web/) from the config. Local files only; deploying them is the owner\'s step.',
props: { out: { type: 'string', pattern: '^[A-Za-z0-9._/-]{1,200}$', description: 'Output folder (default web.out or web)' }, landing: { type: 'boolean', default: false } },
args: i => [...opt('out', i.out), ...flag('landing', i.landing)] },
{ name: 'web_check', title: 'Check the live link files', command: ['web', 'check'], write: false, network: true,
description: 'Read-only check of https://<domain>/.well-known/apple-app-site-association and assetlinks.json: HTTP 200 without redirects, JSON content type, valid JSON, team / bundle id and package / signing fingerprint match the config.',
props: { domain: { type: 'string', pattern: '^[a-z0-9.-]{1,253}$', description: 'Default: web.domain of the config' } }, args: i => (i.domain ? [String(i.domain)] : []) },
{ name: 'apple_adhoc_devices', title: 'Registered test devices', command: ['apple', 'adhoc', 'devices'], write: false, network: true,
description: 'Read-only list of the devices registered for ad-hoc / development builds (UDIDs masked) and the yearly slots used. Registering devices stays a terminal command.',
props: { platform: { type: 'string', enum: ['IOS', 'MAC_OS'] } }, args: i => opt('platform', i.platform) },
{ name: 'apple_adhoc_options', title: 'Ad-hoc ExportOptions.plist', command: ['apple', 'adhoc', 'options'], write: true, network: false, idempotent: true,
description: 'Writes an ExportOptions.plist for an ad-hoc / release-testing export (method, team id, signing style) to build/ExportOptions.plist. Local file only.',
props: { method: { type: 'string', enum: ['release-testing', 'ad-hoc'] } }, args: i => opt('method', i.method) },
{ name: 'revenuecat_diff', title: 'RevenueCat parity', command: ['revenuecat', 'diff'], write: false, network: true,
description: 'Read-only parity report between the config catalog and the RevenueCat project: products, entitlements and their products, the default offering and its packages. Syncing is a terminal command the owner confirms.' },
{ name: 'prices_export', title: 'Export prices to CSV', command: ['prices', 'export'], write: true, network: true, idempotent: true, { name: 'prices_export', title: 'Export prices to CSV', command: ['prices', 'export'], write: true, network: true, idempotent: true,
description: 'Read the current prices of every product on both stores and write them as the prices CSV (local file only; Apple equalized prices with with_automatic, marked kind=auto). dry_run prints the CSV.', description: 'Read the current prices of every product on both stores and write them as the prices CSV (local file only; Apple equalized prices with with_automatic, marked kind=auto). dry_run prints the CSV.',
props: { out: { type: 'string', description: 'CSV path' }, store: { type: 'string', enum: ['apple', 'play'] }, only, with_automatic: { type: 'boolean', default: false } }, props: { out: { type: 'string', description: 'CSV path' }, store: { type: 'string', enum: ['apple', 'play'] }, only, with_automatic: { type: 'boolean', default: false } },
@ -365,7 +396,7 @@ export function validateInput(t: ToolDef, input: unknown): string[] {
for (const [k, v] of Object.entries(i)) { for (const [k, v] of Object.entries(i)) {
const p = s.properties[k]; const p = s.properties[k];
if (!p) { e.push(`${k}: unknown argument`); continue; } if (!p) { e.push(`${k}: unknown argument`); continue; }
const ok = p.type === 'integer' ? Number.isInteger(v) : p.type === 'boolean' ? typeof v === 'boolean' : p.type === 'string' ? typeof v === 'string' const ok = p.type === 'integer' ? Number.isInteger(v) : p.type === 'number' ? typeof v === 'number' && Number.isFinite(v) : p.type === 'boolean' ? typeof v === 'boolean' : p.type === 'string' ? typeof v === 'string'
: p.type === 'object' ? typeof v === 'object' && v !== null && !Array.isArray(v) && Object.entries(v).every(([pk, pv]) => /^[A-Za-z][A-Za-z0-9_.[\]+-]{0,100}$/.test(pk) && ['string', 'number', 'boolean'].includes(typeof pv) && !/[\n\r]/.test(String(pv))) : p.type === 'object' ? typeof v === 'object' && v !== null && !Array.isArray(v) && Object.entries(v).every(([pk, pv]) => /^[A-Za-z][A-Za-z0-9_.[\]+-]{0,100}$/.test(pk) && ['string', 'number', 'boolean'].includes(typeof pv) && !/[\n\r]/.test(String(pv)))
: true; : true;
if (!ok) { e.push(`${k}: must be ${p.type === 'object' ? 'an object of name -> string / number / boolean' : p.type}`); continue; } if (!ok) { e.push(`${k}: must be ${p.type === 'object' ? 'an object of name -> string / number / boolean' : p.type}`); continue; }

74
cli/play/share.ts Normal file
View file

@ -0,0 +1,74 @@
// Google Play internal app sharing: upload an app bundle or APK and get an install link for testers, with no track,
// no review and no version code rules.
// storebound play share --aab app.aab | --apk app.apk [--dry] [--yes] [--json]
// Prints file, size, sha256 and package; --dry stops there. Otherwise it asks (the build becomes installable by anyone
// allowed to use the link, for 60 days), uploads, and prints the share link and the certificate fingerprint of the
// re-signed build. --json: { downloadUrl, certificateFingerprint, sha256 } (dry: { dry, packageName, file, kind, bytes, sha256 }).
// Testers must turn on internal app sharing in the Play Store app; uploaders need "Release apps to testing tracks"
// or a place on the Console's uploader list. See skills/adhoc-distribution/SKILL.md.
// Sources (checked October 2026): https://developers.google.com/android-publisher/api-ref/rest/v3/internalappsharingartifacts
// and https://support.google.com/googleplay/android-developer/answer/9844679 (details in cli/lib/play-share.ts).
import { createHash } from 'node:crypto';
import { createReadStream, existsSync, readFileSync, statSync } from 'node:fs';
import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { done, log, printJson, warn } from '../lib/log';
import { mb, parseShareArtifact, SHARE_HEADERS, type ShareKind, shareProblems, shareUrl } from '../lib/play-share';
import { playClient } from './client';
const TAG = 'share';
const USAGE = 'usage: storebound play share --aab <app.aab> | --apk <app.apk> [--dry] [--yes] [--json]';
async function sha256File(file: string): Promise<string> {
const h = createHash('sha256');
for await (const chunk of createReadStream(file)) h.update(chunk as Buffer);
return h.digest('hex');
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root } = ctx.loaded;
const a = ctx.args;
const pkg = need(config.play?.packageName, 'play.packageName');
const aab = a.get('aab'), apk = a.get('apk');
if ((!aab && !apk) || (aab && apk) || aab === 'true' || apk === 'true') throw new Error(USAGE);
const kind: ShareKind = aab ? 'bundle' : 'apk';
const file = (aab ?? apk)!;
if (!existsSync(file)) throw new Error(`${file}: no such file`);
const bytes = statSync(file).size;
const problems = shareProblems(kind, file, bytes);
if (problems.length) throw new Error(problems.join('\n'));
const sha256 = await sha256File(file);
const json = a.has('json');
const info = (m: string): void => { if (!json) log(TAG, m); };
info(`${pkg}: ${kind === 'bundle' ? 'app bundle' : 'APK'} ${file}, ${mb(bytes)}, sha256 ${sha256}`);
if (a.has('dry')) {
info(`dry run: would POST it to internal app sharing (${shareUrl(pkg, kind).replace(/\?.*/, '')}); nothing sent`);
if (json) printJson({ dry: true, packageName: pkg, file, kind, bytes, sha256 });
return;
}
if (!(await confirm(ctx, `Upload ${file} to Google Play internal app sharing for ${pkg}? Anyone allowed to use the link can install it for 60 days.`))) {
console.error('not confirmed, nothing uploaded');
return;
}
const play = await playClient(root, pkg);
info(`uploading ${mb(bytes)}, this can take minutes`);
const t0 = Date.now();
const beat = setInterval(() => info(`still uploading (${Math.round((Date.now() - t0) / 1000)}s)`), 15_000);
let res: unknown;
try {
res = await play.call('POST', shareUrl(pkg, kind), new Uint8Array(readFileSync(file)), { ...SHARE_HEADERS });
} catch (e) {
const m = (e as Error).message;
if (/-> 403/.test(m)) throw new Error(`${m}\n\nThe service account needs "Release apps to testing tracks" for this app, or a place on the internal app sharing uploader list (Play Console > Internal app sharing).`);
throw e;
} finally { clearInterval(beat); }
const art = parseShareArtifact(res);
if (art.sha256 && art.sha256 !== sha256) warn(TAG, `Play reports sha256 ${art.sha256}, the local file is ${sha256}`);
if (json) { printJson(art); return; }
done(TAG, 'uploaded');
console.log(`share link: ${art.downloadUrl}`);
console.log(`certificate fingerprint (re-signed by Google): ${art.certificateFingerprint}`);
console.log('Testers: Play Store > Settings > About > tap "Play Store version" 7 times > turn on Internal app sharing, then open the link. The link expires in 60 days.');
}

174
cli/prices-ppp.ts Normal file
View file

@ -0,0 +1,174 @@
// Purchasing power parity price proposals: one price sheet for every product, store and region.
// storebound prices ppp [--base <USD>] [--source worldbank|bigmac|file] [--file <csv>] [--only ids] [--store apple|play]
// [--floor 0.3] [--ceiling 1.2] [--out store/prices-ppp.csv] [--offline] [--dry] [--json]
// storebound prices ppp --update-bigmac [--dry] download The Economist Big Mac index to .storebound/ppp-bigmac.json
// It writes a CSV in the `prices import` format (nothing is sent to a store), prints the diff against the stores'
// current prices and the next step (`storebound prices import --csv <out> --dry`). --dry prints the CSV and the diff
// and writes nothing. --json prints { source, base, rows, skipped, diff, out, written } (with --dry: written false).
// Online (credentials set, no --offline): Apple prices snap to the product's real price points per territory
// (GET /v2/inAppPurchases/{id}/pricePoints?filter[territory]=...&include=territory, read-only) and the territory's
// currency comes from Apple; Play regions and currencies come from pricing:convertRegionPrices of the base (a
// read-only conversion). A product missing on a store falls back to offline snapping for that store. Math and
// snapping rules: lib/ppp.ts.
// Sources (checked October 2026):
// https://developer.apple.com/documentation/appstoreconnectapi/get-v2-inapppurchases-_id_-pricepoints
// https://developers.google.com/android-publisher/api-ref/rest/v3/monetization/convertRegionPrices
// https://data.worldbank.org/indicator/PA.NUS.PPP, https://data.worldbank.org/indicator/PA.NUS.FCRF
// https://github.com/TheEconomist/big-mac-data (output-data/big-mac-raw-index.csv)
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import worldbank from './data/ppp-worldbank.json' with { type: 'json' };
import { ascClient, type Asc, type J } from './apple/asc';
import { sellsOn } from './lib/config';
import { credentialValue } from './lib/credentials';
import type { Ctx } from './lib/ctx';
import { need } from './lib/ctx';
import { done, log, printJson, step, warn } from './lib/log';
import { ALPHA3, toMoney } from './lib/money';
import { bigMacDataset, datasetJson, datasetProblems, parseFactorCsv, planRows, type PppDataset, pppCsv, type PppRow, type StoreRegion } from './lib/ppp';
import { alpha2, diffPrices, diffTable, playPriceRows, type PriceRow } from './lib/prices';
import { playClient, type PlayClient } from './play/client';
import { appleCurrent, iapId, pages, playProduct } from './prices';
const TAG = 'ppp';
const BIGMAC_URL = 'https://raw.githubusercontent.com/TheEconomist/big-mac-data/master/output-data/big-mac-raw-index.csv';
export const bundled = worldbank as unknown as PppDataset;
/** Downloads the Big Mac index and writes <root>/.storebound/ppp-bigmac.json (also used by tools/update-ppp.ts). */
export async function updateBigMac(root: string, dry: boolean): Promise<void> {
const r = await fetch(BIGMAC_URL);
if (!r.ok) throw new Error(`${BIGMAC_URL} -> ${r.status}`);
const ds = bigMacDataset(await r.text(), new Date().toISOString().slice(0, 10));
const p = join(root, '.storebound', 'ppp-bigmac.json');
if (dry) { done(TAG, `dry run: would write ${Object.keys(ds.countries).length} countries (${ds.source}) to ${p}`); return; }
mkdirSync(dirname(p), { recursive: true });
writeFileSync(p, datasetJson(ds));
done(TAG, `${Object.keys(ds.countries).length} countries (${ds.source}) -> ${p}`);
}
export function loadDataset(source: string, root: string, file: string | undefined): PppDataset {
if (source === 'worldbank') return bundled;
if (source === 'bigmac') {
const p = join(root, '.storebound', 'ppp-bigmac.json');
if (!existsSync(p)) throw new Error(`no Big Mac data at ${p}: run storebound prices ppp --update-bigmac (downloads The Economist's data to your machine; it is not bundled)`);
const ds = JSON.parse(readFileSync(p, 'utf8')) as PppDataset;
const e = datasetProblems(ds);
if (e.length) throw new Error(`${p}: ${e.join('; ')} (run storebound prices ppp --update-bigmac again)`);
return ds;
}
if (source === 'file') {
if (!file) throw new Error('--source file needs --file <csv> (or prices.ppp.file in the config)');
if (!existsSync(file)) throw new Error(`no PPP factor CSV at ${file} (columns: region, factor, currency, fx)`);
return parseFactorCsv(readFileSync(file, 'utf8'), bundled, file);
}
throw new Error('--source worldbank | bigmac | file');
}
/** Apple price points of one IAP in the given territories (alpha-3), batched: region (alpha-2) -> currency + points. */
export async function applePoints(c: Asc, id: string, territories: string[]): Promise<Map<string, StoreRegion>> {
const out = new Map<string, StoreRegion>();
for (let i = 0; i < territories.length; i += 10) {
const batch = territories.slice(i, i + 10);
const r = await pages(c, `/v2/inAppPurchases/${id}/pricePoints?filter[territory]=${batch.join(',')}&include=territory&fields[territories]=currency&limit=8000`);
const curr = new Map(r.included.filter((x: J) => x.type === 'territories').map((x: J) => [x.id, x.attributes?.currency] as const));
for (const p of r.data) {
const t: string | undefined = p.relationships?.territory?.data?.id;
if (!t) continue;
const region = alpha2(t);
const e: StoreRegion = out.get(region) ?? { currency: curr.get(t) ?? '', points: [] };
e.points!.push(Number(p.attributes?.customerPrice));
out.set(region, e);
}
}
return out;
}
type Converted = { convertedRegionPrices?: Record<string, { regionCode: string; price: { currencyCode: string } }> };
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const a = ctx.args;
const pc = config.prices?.ppp ?? {};
const dry = a.has('dry');
if (a.has('update-bigmac')) return updateBigMac(root, dry);
const store = a.get('store');
if (store && store !== 'apple' && store !== 'play') throw new Error('--store apple | play');
const source = a.get('source') ?? pc.source ?? 'worldbank';
const fileArg = a.get('file') ?? pc.file;
const ds = loadDataset(source, root, fileArg ? resolve(fileArg) : undefined);
const floor = a.num('floor', pc.floor ?? 0.3), ceiling = a.num('ceiling', pc.ceiling ?? 1.2);
if (!(floor > 0) || !(ceiling > 0) || floor > ceiling) throw new Error('--floor and --ceiling: shares of the base price, 0 < floor <= ceiling (e.g. 0.3 and 1.2)');
const baseArg = a.get('base') !== undefined ? a.num('base', 0) : undefined;
if (baseArg !== undefined && !(baseArg > 0)) throw new Error('--base: a USD price, e.g. 4.99');
const only = a.list('only');
const products = need(config.products, 'products').filter(p => !only.length || only.includes(p.id));
if (!products.length) throw new Error(only.length ? `--only ${only.join(',')}: no such product in products[]` : 'products[] is empty');
const out = resolve(a.get('out') ?? pc.out ?? 'store/prices-ppp.csv');
const offline = a.has('offline');
const stores = (['apple', 'play'] as const).filter(s => (!store || store === s) && !!config[s]);
if (!stores.length) throw new Error('no store configured for this run (apple / play in storebound.config.ts)');
const online = {
apple: !offline && stores.includes('apple') && !!credentialValue(root, 'ASC_KEY_ID') && !!credentialValue(root, 'ASC_ISSUER_ID'),
play: !offline && stores.includes('play') && !!credentialValue(root, 'PLAY_SERVICE_ACCOUNT'),
};
for (const s of stores) if (!offline && !online[s]) warn(TAG, `${s}: no credentials, offline snapping (storebound doctor shows what is missing)`);
const c = online.apple ? await ascClient(root, config.apple!.bundleId, config.apple?.appId) : null;
const appId = c ? await c.app() : '';
const play: PlayClient | null = online.play ? await playClient(root, config.play!.packageName) : null;
log(TAG, `${ds.name}: ${ds.source}; retrieved ${ds.retrieved || '-'}; floor ${floor}, ceiling ${ceiling}; ${stores.map(s => `${s} ${online[s] ? 'online' : 'offline'}`).join(', ')}`);
const rows: PppRow[] = [];
const current: PriceRow[] = [];
const skipped: { product: string; store: string; region: string; why: string }[] = [];
const offlineApple = new Set<string>();
const converted = new Map<number, Converted>();
const base: Record<string, number> = {};
for (const [i, p] of products.entries()) {
const usd = baseArg ?? p.usd;
base[p.id] = usd;
log(TAG, `${step(i + 1, products.length, p.id)}: base ${usd} USD`);
for (const s of stores) {
if (!sellsOn(config, p, s)) continue;
let regions: Map<string, StoreRegion> | undefined;
if (s === 'apple' && c) {
const id = await iapId(c, appId, p.id);
if (!id) warn(TAG, `${p.id}: not on App Store Connect (storebound apple iap creates it); offline snapping for Apple`);
else {
current.push(...(await appleCurrent(c, id, p.id, true)).rows);
const want = Object.keys(ALPHA3).filter(r => r === 'US' || ds.countries[r]).map(r => ALPHA3[r]!);
regions = await applePoints(c, id, want);
}
}
if (s === 'play' && play) {
const pp = await playProduct(play, p.id);
if (!pp) warn(TAG, `${p.id}: not on Google Play (storebound play products creates it); proposal against no current prices`);
else current.push(...playPriceRows(pp));
if (!converted.has(usd)) converted.set(usd, await play.call<Converted>('POST', `${play.API}/pricing:convertRegionPrices`, { price: toMoney('USD', usd) }));
regions = new Map(Object.values(converted.get(usd)!.convertedRegionPrices ?? {}).map(r => [r.regionCode, { currency: r.price.currencyCode }] as const));
}
if (s === 'apple' && !regions) offlineApple.add(p.id);
const plan = planRows({ product: p.id, base: usd, store: s, dataset: ds, floor, ceiling, regions });
rows.push(...plan.rows);
skipped.push(...plan.skipped.map(k => ({ product: p.id, store: s, ...k })));
}
}
const csv = pppCsv(rows);
const diff = diffPrices(current, rows.map(({ product, store, region, territory, currency, price }) => ({ product, store, region, territory, currency, price })));
const sourceInfo = { name: ds.name, year: ds.year ?? null, retrieved: ds.retrieved, url: ds.url, license: ds.license };
if (!dry) { mkdirSync(dirname(out), { recursive: true }); writeFileSync(out, csv); }
if (a.has('json')) {
printJson({ source: sourceInfo, base, floor, ceiling, online, rows: rows.map(({ territory: _t, ...r }) => r), skipped, diff, out, written: !dry });
return;
}
if (dry) console.log(csv);
console.log(diffTable(diff));
const clamped = rows.filter(r => r.clamped).length;
log(TAG, `${rows.length} rows (${clamped} clamped to the floor / ceiling), ${skipped.length} region(s) without a proposal${skipped.length ? ` (${[...new Set(skipped.map(k => k.region))].slice(0, 12).join(', ')}${skipped.length > 12 ? ', ...' : ''})` : ''}`);
if (offlineApple.size) warn(TAG, `Apple values for ${[...offlineApple].join(', ')} are offline proposals: each must still match an App Store price point (prices import checks it and lists the neighbours)`);
log(TAG, `source: ${ds.attribution ?? ds.source} (${ds.license})`);
log(TAG, 'a proposal: review the sheet (remove rows you do not want, round to your own price ladder); nothing was sent to a store');
done(TAG, dry ? `dry run: would write ${rows.length} rows to ${out}` : `${rows.length} rows -> ${out}; next: storebound prices import --csv ${a.get('out') ?? pc.out ?? 'store/prices-ppp.csv'} --dry`);
}

View file

@ -1,6 +1,7 @@
// In-app product prices for many products and regions from one CSV (both stores). // In-app product prices for many products and regions from one CSV (both stores).
// storebound prices export [--out store/prices.csv] [--store apple|play] [--only ids] [--with-automatic] [--dry] [--json] // storebound prices export [--out store/prices.csv] [--store apple|play] [--only ids] [--with-automatic] [--dry] [--json]
// storebound prices import [--csv store/prices.csv] [--store apple|play] [--only ids] [--reconvert] [--all] [--dry] [--yes] // storebound prices import [--csv store/prices.csv] [--store apple|play] [--only ids] [--reconvert] [--all] [--dry] [--yes]
// storebound prices ppp [--base <USD>] [...] purchasing power price sheet (prices-ppp.ts)
// CSV columns: product, store (apple | play | both), region (ISO alpha-2), currency, price, start_date (App Store // CSV columns: product, store (apple | play | both), region (ISO alpha-2), currency, price, start_date (App Store
// only, a future YYYY-MM-DD = scheduled change), kind (manual | auto; auto rows are Apple's equalized prices, exported // only, a future YYYY-MM-DD = scheduled change), kind (manual | auto; auto rows are Apple's equalized prices, exported
// for reference and ignored on import). // for reference and ignored on import).
@ -23,7 +24,7 @@ import { playClient, type PlayClient } from './play/client';
const TAG = 'prices'; const TAG = 'prices';
async function iapId(c: Asc, appId: string, productId: string): Promise<string | null> { export async function iapId(c: Asc, appId: string, productId: string): Promise<string | null> {
return (await c.asc('GET', `/v1/apps/${appId}/inAppPurchasesV2?filter[productId]=${encodeURIComponent(productId)}`)).data?.[0]?.id ?? null; return (await c.asc('GET', `/v1/apps/${appId}/inAppPurchasesV2?filter[productId]=${encodeURIComponent(productId)}`)).data?.[0]?.id ?? null;
} }
@ -52,7 +53,8 @@ export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded; const { config, root, resolve } = ctx.loaded;
const a = ctx.args; const a = ctx.args;
const sub = a._[0]; const sub = a._[0];
if (sub !== 'export' && sub !== 'import') throw new Error('usage: storebound prices export | import [--csv store/prices.csv] [--dry]'); if (sub === 'ppp') return (await import('./prices-ppp')).run(ctx);
if (sub !== 'export' && sub !== 'import') throw new Error('usage: storebound prices export | import [--csv store/prices.csv] [--dry] | ppp [--base <USD>] [--dry]');
const store = a.get('store'); const store = a.get('store');
if (store && store !== 'apple' && store !== 'play') throw new Error('--store apple | play'); if (store && store !== 'apple' && store !== 'play') throw new Error('--store apple | play');
const useApple = (!store || store === 'apple') && !!config.apple; const useApple = (!store || store === 'apple') && !!config.apple;

189
cli/revenuecat.ts Normal file
View file

@ -0,0 +1,189 @@
// Optional RevenueCat adapter: keep a RevenueCat project's catalog in step with the config.
// storebound revenuecat diff [--json] read-only parity report; exit 1 when out of sync
// storebound revenuecat sync [--dry] [--yes] [--current] [--json]
// sync creates and attaches only (products, entitlements, their products, the offering, its packages and their
// products), in dependency order, after a confirmation. It never deletes, detaches, archives or updates anything:
// what RevenueCat has beyond the config is listed as "extra, left alone". --current also makes the offering the
// current one (that changes what the apps show by default, so it is opt-in). Re-running is safe: the plan is
// computed from a fresh read every time.
// Out of scope (RevenueCat's job): runtime entitlements, receipt / purchase token validation, customer info,
// webhooks, paywalls, store server notifications setup, the App Store / Play credentials inside RevenueCat.
// Key: REVENUECAT_SECRET_KEY (env or .storebound/credentials.json), a v2 secret key with project configuration
// permissions (apps read; products, entitlements, offerings, packages read, or read_write for sync). Never printed.
// Config: revenuecat { projectId, apps?: { apple, play }, entitlements?, offering? }. Pure parts: lib/revenuecat.ts.
// Sources (checked October 2026):
// https://www.revenuecat.com/docs/api-v2 (auth, pagination, rate limits: 429 + Retry-After seconds)
// https://www.revenuecat.com/docs/api-v2/app GET /projects/{project_id}/apps
// https://www.revenuecat.com/docs/api-v2/product GET / POST /projects/{project_id}/products
// https://www.revenuecat.com/docs/api-v2/entitlement GET / POST .../entitlements, GET .../entitlements/{id}/products,
// POST .../entitlements/{id}/actions/attach_products
// https://www.revenuecat.com/docs/api-v2/offering GET / POST .../offerings, POST .../offerings/{id} (is_current)
// https://www.revenuecat.com/docs/api-v2/package GET / POST .../offerings/{id}/packages, GET .../packages/{id}/products,
// POST .../packages/{id}/actions/attach_products
import { credentialValue } from './lib/credentials';
import { confirm, type Ctx, need } from './lib/ctx';
import { errorBody } from './lib/http';
import { done, log, printJson, warn } from './lib/log';
import {
outOfSync, RC_SCOPE, type RcApp, type RcEntitlement, type RcOffering, type RcPackage, rcDiff, rcPlan, type RcProduct, type RcRow,
type RcState, type RcStep, resolveApps, wantedRevenueCat,
} from './lib/revenuecat';
import { textTable } from './lib/table';
const TAG = 'revenuecat';
const ORIGIN = 'https://api.revenuecat.com';
const BASE = `${ORIGIN}/v2`;
const USAGE = 'usage: storebound revenuecat diff [--json] | sync [--dry] [--yes] [--current] [--json]';
type J = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
export interface RcClient { get(path: string): Promise<J>; all(path: string): Promise<J[]>; post(path: string, body: unknown): Promise<J> }
/** Small v2 client: Bearer auth, next_page pagination (only ever followed on api.revenuecat.com), 429 retries with
* Retry-After. Errors name the method, path and status; the key never appears in them. */
export function rcClient(key: string, o: { retries?: number } = {}): RcClient {
const redact = (s: string) => (key ? s.split(key).join('***') : s);
async function call(method: 'GET' | 'POST', url: string, body?: unknown): Promise<J> {
const u = new URL(url, ORIGIN);
if (u.origin !== ORIGIN) throw new Error(`RevenueCat: refusing to send the key to ${u.origin}`);
for (let attempt = 0; ; attempt++) {
const r = await fetch(u, {
method, signal: AbortSignal.timeout(30_000),
headers: { 'Authorization': `Bearer ${key}`, 'Accept': 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },
body: body === undefined ? undefined : JSON.stringify(body),
});
if (r.status === 429 && attempt < (o.retries ?? 3)) {
const s = Math.min(60, Math.max(0, Number(r.headers.get('retry-after') ?? '5') || 0));
warn(TAG, `rate limited, waiting ${s}s`);
await r.body?.cancel();
await Bun.sleep(s * 1000);
continue;
}
const text = await r.text();
if (!r.ok) {
const hint = r.status === 401 || r.status === 403 ? ' (REVENUECAT_SECRET_KEY: a v2 secret key with project configuration permissions for this project)' : '';
throw new Error(redact(`RevenueCat ${method} ${u.pathname}: ${r.status} ${errorBody(text, 500)}${hint}`));
}
return text ? JSON.parse(text) as J : {};
}
}
const abs = (p: string) => (p.startsWith('http') ? p : p.startsWith('/v2/') ? ORIGIN + p : BASE + p);
return {
get: p => call('GET', abs(p)),
post: (p, b) => call('POST', abs(p), b),
async all(p) {
const out: J[] = [];
for (let url: string | null = abs(p); url;) {
const r = await call('GET', url);
out.push(...(r.items ?? []));
url = typeof r.next_page === 'string' && r.next_page ? abs(r.next_page) : null;
}
return out;
},
};
}
/** Everything the diff and the plan need, read-only. Attachments are read only for the configured entitlements and
* the configured offering. */
export async function readState(c: RcClient, projectId: string, want: { entitlements: string[]; offering: string }): Promise<RcState> {
const P = `/projects/${encodeURIComponent(projectId)}`;
const products = (await c.all(`${P}/products?limit=100`)) as RcProduct[];
log(TAG, `${products.length} product(s)`);
const entitlements: RcEntitlement[] = [];
for (const e of await c.all(`${P}/entitlements?limit=100`)) {
const productIds = want.entitlements.includes(e.lookup_key) ? (await c.all(`${P}/entitlements/${encodeURIComponent(e.id)}/products?limit=100`)).map(p => p.id as string) : [];
entitlements.push({ id: e.id, lookup_key: e.lookup_key, display_name: e.display_name, state: e.state, productIds });
}
log(TAG, `${entitlements.length} entitlement(s)`);
const offerings: RcOffering[] = [];
for (const o of await c.all(`${P}/offerings?limit=100`)) {
const packages: RcPackage[] = [];
if (o.lookup_key === want.offering) {
for (const p of await c.all(`${P}/offerings/${encodeURIComponent(o.id)}/packages?limit=100`)) {
const items = await c.all(`${P}/packages/${encodeURIComponent(p.id)}/products?limit=100`);
packages.push({ id: p.id, lookup_key: p.lookup_key, display_name: p.display_name, position: p.position,
products: items.map(i => ({ product_id: typeof i.product === 'string' ? i.product : i.product?.id, eligibility_criteria: i.eligibility_criteria })) });
}
}
offerings.push({ id: o.id, lookup_key: o.lookup_key, display_name: o.display_name, is_current: o.is_current, state: o.state, packages });
}
log(TAG, `${offerings.length} offering(s)`);
return { products, entitlements, offerings };
}
export function formatRows(rows: RcRow[]): string {
if (!rows.length) return 'nothing to compare';
return textTable(['status', 'what', 'key', 'detail'], rows.map(r => [r.status, r.section, r.key, r.msg]));
}
async function load(ctx: Ctx) {
const { config, root } = ctx.loaded;
const rc = need(config.revenuecat, 'revenuecat');
const key = credentialValue(root, 'REVENUECAT_SECRET_KEY');
if (!key) throw new Error('REVENUECAT_SECRET_KEY is not set (env, or .storebound/credentials.json): a RevenueCat v2 secret key with project configuration permissions');
const c = rcClient(key);
const want = wantedRevenueCat(config);
const needApps = (['apple', 'play'] as const).some(s => !rc.apps?.[s]);
const apps = needApps ? (await c.all(`/projects/${encodeURIComponent(rc.projectId)}/apps?limit=100`)) as RcApp[] : null;
const resolved = resolveApps(config, apps);
const state = await readState(c, rc.projectId, { entitlements: want.entitlements.map(e => e.lookupKey), offering: want.offering.lookupKey });
return { rc, c, want, resolved, state };
}
export async function run(ctx: Ctx): Promise<void> {
const a = ctx.args;
const sub = a._[0];
if (sub !== 'diff' && sub !== 'sync') throw new Error(USAGE);
const { rc, c, want, resolved, state } = await load(ctx);
const rows = rcDiff(want, state, resolved.ids, resolved.problems);
const bad = outOfSync(rows);
if (sub === 'diff') {
if (a.has('json')) printJson({ projectId: rc.projectId, apps: resolved.ids, outOfSync: bad, rows, scope: RC_SCOPE });
else console.log(`${formatRows(rows)}\n\n${RC_SCOPE}`);
done(TAG, `${bad ? `${bad} difference(s): run storebound revenuecat sync --dry` : 'in sync'}; ${rows.filter(r => r.status === 'extra').length} extra (left alone)`);
if (bad) process.exitCode = 1;
return;
}
// sync
const plan = rcPlan(want, state, resolved.ids, { current: a.has('current') });
const blockers = rows.filter(r => r.section === 'config' || r.section === 'app');
for (const b of blockers) warn(TAG, b.msg);
const left = rows.filter(r => r.status === 'extra' || (r.status === 'mismatch' && r.section !== 'config'));
if (a.has('json') && a.has('dry')) { printJson({ projectId: rc.projectId, apps: resolved.ids, plan, leftAlone: left }); return; }
console.log(plan.length ? plan.map((s, i) => `${String(i + 1).padStart(String(plan.length).length)}. ${s.what}`).join('\n') : 'nothing to create or attach');
if (left.length) console.log(`\nleft alone (sync never deletes, detaches or changes):\n${left.map(r => ` ${r.status} ${r.section} ${r.key}: ${r.msg}`).join('\n')}`);
console.log(`\n${RC_SCOPE}`);
if (!plan.length) { done(TAG, 'nothing to do'); return; }
if (a.has('dry')) { done(TAG, `dry run: ${plan.length} step(s), nothing sent`); return; }
if (!(await confirm(ctx, `Run these ${plan.length} step(s) on RevenueCat project ${rc.projectId}?`))) { log(TAG, 'not confirmed, nothing sent'); return; }
await execute(c, rc.projectId, plan, state, resolved.ids, want.offering.lookupKey);
done(TAG, `${plan.length} step(s) done; run storebound revenuecat diff to check`);
}
/** Runs the plan in order, resolving product / entitlement / offering / package ids from the state and what it creates. */
export async function execute(c: RcClient, projectId: string, plan: RcStep[], state: RcState, apps: Partial<Record<'apple' | 'play', string>>, offeringKey: string): Promise<void> {
const P = `/projects/${encodeURIComponent(projectId)}`;
const storeOf = new Map(Object.entries(apps).map(([s, id]) => [id, s] as const));
const productId = new Map<string, string>();
for (const p of state.products) { const s = storeOf.get(p.app_id); if (s) productId.set(`${s}:${p.store_identifier}`, p.id); }
const entId = new Map(state.entitlements.map(e => [e.lookup_key, e.id] as const));
const current = state.offerings.find(o => o.lookup_key === offeringKey);
let offering = current?.id ?? '';
const pkgId = new Map((current?.packages ?? []).map(p => [p.lookup_key, p.id] as const));
const pid = (k: string) => { const id = productId.get(k); if (!id) throw new Error(`RevenueCat product ${k} was not created`); return id; };
for (const [i, s] of plan.entries()) {
log(TAG, `${i + 1}/${plan.length} ${s.what}`);
switch (s.op) {
case 'create-product': productId.set(s.key, (await c.post(`${P}/products`, s.body)).id); break;
case 'create-entitlement': entId.set(s.lookupKey, (await c.post(`${P}/entitlements`, s.body)).id); break;
case 'attach-entitlement':
await c.post(`${P}/entitlements/${encodeURIComponent(entId.get(s.lookupKey)!)}/actions/attach_products`, { product_ids: s.products.map(pid) }); break;
case 'create-offering': offering = (await c.post(`${P}/offerings`, s.body)).id; break;
case 'create-package': pkgId.set(s.lookupKey, (await c.post(`${P}/offerings/${encodeURIComponent(offering)}/packages`, s.body)).id); break;
case 'attach-package':
await c.post(`${P}/packages/${encodeURIComponent(pkgId.get(s.lookupKey)!)}/actions/attach_products`, { products: s.products.map(k => ({ product_id: pid(k), eligibility_criteria: 'all' })) }); break;
case 'set-current': await c.post(`${P}/offerings/${encodeURIComponent(offering)}`, { is_current: true }); break;
}
}
}

View file

@ -49,9 +49,19 @@ export const JSON_TOOLS = new Set(['check', 'check_aso', 'scan', 'validate', 'he
'apple_next_build', 'play_status', 'play_next_version_code', 'shots_check', 'apple_testflight_status', 'apple_ppo_status', 'catalog_diff', 'apple_next_build', 'play_status', 'play_next_version_code', 'shots_check', 'apple_testflight_status', 'apple_ppo_status', 'catalog_diff',
'project_icon', 'project_listings', 'reviews_drafts', 'project_declarations', 'project_listing_text', 'project_renders', 'project_render', 'prices_current']); 'project_icon', 'project_listings', 'reviews_drafts', 'project_declarations', 'project_listing_text', 'project_renders', 'project_render', 'prices_current']);
/** Console forms `storebound console fill` knows (cli/console/fill.ts). */
export const CONSOLE_FORMS = ['apple-app-record', 'apple-age-rating', 'apple-app-privacy', 'play-content-rating', 'play-target-audience'];
/** Write tools that print a structured result with --json in the dry run and the real run (console.fill: the answers). */
export const JSON_WRITES = new Set(['console_fill']);
/** Write tools whose command may ask its own question (confirm()): a verified host token answers it, as for owner actions. */
const TOKEN_ANSWERS = new Set(['console_fill']);
/** /**
* Methods only the desktop profile has (not MCP tools): offline reads of the project's own files, and two local * Methods only the desktop profile has (not MCP tools): offline reads of the project's own files, local writes the
* writes the owner confirms in a native dialog. Approving a reply draft is the owner's decision, so AI tools do not get * owner confirms in a native dialog, and `console.fill`. That one is a write: its dry run returns the answers it would
* type (data, for the window's panel); the real run opens a visible browser only with the host's confirm token, minted
* after the owner confirmed a native dialog showing those answers. It runs until the owner closes the browser (no
* timeout here, in the runner or in the host); a cancel kills the command, which closes its browser. Approving a reply draft is the owner's decision, so AI tools do not get
* it; `project.init` writes the templates into a new folder (the host passes that folder, it has no config yet). * it; `project.init` writes the templates into a new folder (the host passes that folder, it has no config yet).
*/ */
export const DESKTOP_ONLY: ToolDef[] = [ export const DESKTOP_ONLY: ToolDef[] = [
@ -84,6 +94,10 @@ export const DESKTOP_ONLY: ToolDef[] = [
description: 'One rendered image of the renders folder as a data: URL (at most 12 MB), for the desktop gallery.', description: 'One rendered image of the renders folder as a data: URL (at most 12 MB), for the desktop gallery.',
props: { file: { type: 'string', pattern: RENDER_FILE_RE.source, description: 'Path relative to the renders folder, as project.renders names it' } }, props: { file: { type: 'string', pattern: RENDER_FILE_RE.source, description: 'Path relative to the renders folder, as project.renders names it' } },
required: ['file'], args: i => ['--render', String(i.file)] }, required: ['file'], args: i => ['--render', String(i.file)] },
{ name: 'console_fill', title: 'Fill in a console form', command: ['console', 'fill'], write: true, network: true,
description: 'Fills one store console form that has no API (App Store app record, age rating, App Privacy; Play content rating, target audience) from the config in a visible Chromium the owner signs in to; uncertain fields are highlighted. It never saves, submits or publishes: the owner reviews every field and presses Save. The dry run lists the answers; the real run lasts until the owner closes the browser.',
props: { form: { type: 'string', enum: CONSOLE_FORMS, description: 'The console form' }, store: { type: 'string', enum: ['apple', 'play'], description: 'Default: from the form' } },
required: ['form'], args: i => [String(i.form), ...opt('store', i.store)] },
{ name: 'prices_current', title: 'Current prices', command: ['prices', 'export'], write: false, network: true, { name: 'prices_current', title: 'Current prices', command: ['prices', 'export'], write: false, network: true,
description: 'Read-only: the current price of every product on both stores per region (Apple manual prices, with with_automatic also the equalized ones). Writes nothing.', description: 'Read-only: the current price of every product on both stores per region (Apple manual prices, with with_automatic also the equalized ones). Writes nothing.',
props: { store: { type: 'string', enum: ['apple', 'play'] }, with_automatic: { type: 'boolean', default: false } }, props: { store: { type: 'string', enum: ['apple', 'play'] }, with_automatic: { type: 'boolean', default: false } },
@ -176,7 +190,7 @@ const BUNDLE_RE = /^[A-Za-z0-9][A-Za-z0-9.-]{0,154}$/;
export function describeMethods(): MethodDescriptor[] { export function describeMethods(): MethodDescriptor[] {
return [...SYSTEM, ...[...DESKTOP_TOOLS, ...OWNER_TOOLS].map(t => ({ return [...SYSTEM, ...[...DESKTOP_TOOLS, ...OWNER_TOOLS].map(t => ({
method: methodName(t.name), title: t.title, description: t.description, kind: OWNER.has(t.name) ? 'owner' as const : t.write ? 'write' as const : 'read' as const, method: methodName(t.name), title: t.title, description: t.description, kind: OWNER.has(t.name) ? 'owner' as const : t.write ? 'write' as const : 'read' as const,
network: t.network, destructive: !!t.destructive, json: !t.write && JSON_TOOLS.has(t.name), args: argsSchema(t), network: t.network, destructive: !!t.destructive, json: t.write ? JSON_WRITES.has(t.name) : JSON_TOOLS.has(t.name), args: argsSchema(t),
}))]; }))];
} }
@ -364,14 +378,14 @@ export class Session {
} else if (params.dryRun !== undefined && params.dryRun !== true) throw new RpcError(ERR.invalidParams, 'dryRun must be a boolean'); } else if (params.dryRun !== undefined && params.dryRun !== true) throw new RpcError(ERR.invalidParams, 'dryRun must be a boolean');
if (!t.write) dryRun = false; if (!t.write) dryRun = false;
const built = toArgv(t, { ...args, ...(t.write ? { dry_run: dryRun } : {}) }); const built = toArgv(t, { ...args, ...(t.write ? { dry_run: dryRun } : {}) });
const json = !t.write && JSON_TOOLS.has(t.name); const json = t.write ? JSON_WRITES.has(t.name) : JSON_TOOLS.has(t.name);
const argv = json ? [...built.argv, '--json'] : built.argv; const argv = json ? [...built.argv, '--json'] : built.argv;
if (OWNER.has(t.name)) { if (OWNER.has(t.name)) {
const allowed = OWNER_ALLOWED_ARGS[t.name] ?? []; const allowed = OWNER_ALLOWED_ARGS[t.name] ?? [];
if (argv.some(a => OWNER_FORBIDDEN_ARGS.includes(a) && !allowed.includes(a))) throw new RpcError(ERR.invalidParams, `${method}: not an owner action from here`); if (argv.some(a => OWNER_FORBIDDEN_ARGS.includes(a) && !allowed.includes(a))) throw new RpcError(ERR.invalidParams, `${method}: not an owner action from here`);
// the verified token is the owner's answer to the command's own question; nothing else can set it // the verified token is the owner's answer to the command's own question; nothing else can set it
if (!dryRun) env.STOREBOUND_OWNER_CONFIRMED = '1'; if (!dryRun) env.STOREBOUND_OWNER_CONFIRMED = '1';
} } else if (TOKEN_ANSWERS.has(t.name) && !dryRun) env.STOREBOUND_OWNER_CONFIRMED = '1';
const r = this.track(id, this.run(argv, { cwd: project, env, machine: true, onLine: (line, stream) => this.progress(id, { line, stream }) })); const r = this.track(id, this.run(argv, { cwd: project, env, machine: true, onLine: (line, stream) => this.progress(id, { line, stream }) }));
const res = await r.result; const res = await r.result;
if (res.cancelled || this.cancelled.has(id)) throw new RpcError(ERR.cancelled, 'Request cancelled'); if (res.cancelled || this.cancelled.has(id)) throw new RpcError(ERR.cancelled, 'Request cancelled');

View file

@ -29,3 +29,17 @@ export async function launch(root: string, opts: Record<string, unknown>): Promi
try { return await c.launch({ ...opts, channel: 'chrome' }); } catch { throw e; } try { return await c.launch({ ...opts, channel: 'chrome' }); } catch { throw e; }
} }
} }
/**
* A persistent browser profile (cookies of a console sign-in the owner did by hand stay there between runs; storebound
* never reads them). Same resolution and launch order as `launch`. Used by `storebound console fill` (visible window).
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function launchPersistent(root: string, userDataDir: string, opts: Record<string, unknown>): Promise<any> {
const c = await chromium(root);
const exe = process.env.STOREBOUND_CHROME;
if (exe) { try { return await c.launchPersistentContext(userDataDir, { ...opts, executablePath: exe }); } catch { /* fall back below */ } }
try { return await c.launchPersistentContext(userDataDir, opts); } catch (e) {
try { return await c.launchPersistentContext(userDataDir, { ...opts, channel: 'chrome' }); } catch { throw e; }
}
}

View file

@ -2,3 +2,4 @@
declare module '*.md' { const text: string; export default text; } declare module '*.md' { const text: string; export default text; }
declare module '*.csv' { const text: string; export default text; } declare module '*.csv' { const text: string; export default text; }
declare module '*.html' { const text: string; export default text; } declare module '*.html' { const text: string; export default text; }
declare module '*.svg' { const text: string; export default text; }

127
cli/web.ts Normal file
View file

@ -0,0 +1,127 @@
// Web presence: the files a domain serves so links open the app, and a check of the live files.
// storebound web init [--out web] [--landing] [--version-code N] [--dry] [--json]
// writes <out>/.well-known/apple-app-site-association (apple.teamId), <out>/.well-known/assetlinks.json (play +
// web.androidSha256, or the Play app signing key read with --version-code), <out>/smart-app-banner.html
// (apple.appId) and with --landing / web.landing <out>/index.html + the two store marks. Local writes only;
// unchanged files are left alone. Deploy the folder to the domain root yourself.
// storebound web check [<domain>] [--json] read-only, no credentials: the live files on https://<domain>
// Sources (checked October 2026): see cli/lib/web.ts, plus the Play Developer API
// https://developers.google.com/android-publisher/api-ref/rest/v3/generatedapks/list
// (GET applications/{packageName}/generatedApks/{versionCode} -> generatedApks[].certificateSha256Hash, the app
// signing key's certificate SHA-256; its encoding is not documented, normalizeFingerprint takes hex and base64).
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, relative } from 'node:path';
import type { Ctx } from './lib/ctx';
import { done, log, printJson, warn } from './lib/log';
import { textTable } from './lib/table';
import { TEMPLATE_TEXT } from './lib/template-files';
import {
AASA_LEGACY_PATH, AASA_PATH, ASSETLINKS_PATH, type Check, checkAasa, checkAasaLegacy, checkAssetLinks, checkLanding,
type Fetched, normalizeFingerprint, planWeb, type WebIds, webIdsOf,
} from './lib/web';
export async function run(ctx: Ctx): Promise<void> {
const sub = ctx.args._[0];
if (sub === 'init') return init(ctx);
if (sub === 'check') return check(ctx);
throw new Error('usage: storebound web init [--out web] [--landing] [--version-code N] [--dry] [--json] | web check [<domain>] [--json]');
}
/** Play app signing certificate SHA-256 from the generated APKs of one uploaded bundle (read-only). */
async function playFingerprints(root: string, packageName: string, versionCode: number): Promise<string[]> {
const { playClient } = await import('./play/client');
const play = await playClient(root, packageName);
const r = await play.call<{ generatedApks?: { certificateSha256Hash?: string }[] }>('GET', `${play.API}/generatedApks/${versionCode}`);
const out = new Set<string>();
for (const g of r.generatedApks ?? []) {
const fp = g.certificateSha256Hash ? normalizeFingerprint(g.certificateSha256Hash) : null;
if (fp) out.add(fp); else if (g.certificateSha256Hash) warn('web', 'certificateSha256Hash in an unexpected form, skipped');
}
return [...out];
}
async function init(ctx: Ctx): Promise<void> {
const { config: c, root } = ctx.loaded;
const a = ctx.args, dry = a.has('dry'), json = a.has('json');
const out = ctx.loaded.resolve(a.str('out', c.web?.out ?? 'web'));
let fingerprints = c.web?.androidSha256 ?? [];
const vc = a.get('version-code');
if (!fingerprints.length && c.play && vc !== undefined) {
const n = Number(vc);
if (!Number.isInteger(n) || n <= 0) throw new Error('--version-code: the versionCode of a bundle you uploaded, e.g. 42');
fingerprints = await playFingerprints(root, c.play.packageName, n);
log('web', fingerprints.length ? `Play app signing key: ${fingerprints.length} fingerprint(s) from versionCode ${n}; add them to web.androidSha256 to keep them` : `no generated APKs for versionCode ${n}`);
}
const plan = planWeb(c, {
landing: a.has('landing') || !!c.web?.landing,
template: TEMPLATE_TEXT['web/landing.html'],
marks: { appstore: TEMPLATE_TEXT['web/appstore.svg'] ?? '', googleplay: TEMPLATE_TEXT['web/googleplay.svg'] ?? '' },
fingerprints,
});
const files = plan.files.map(f => {
const at = join(out, f.path);
const old = existsSync(at) ? readFileSync(at, 'utf8') : undefined;
const status = old === undefined ? 'new' : old === f.content ? 'unchanged' : 'updated';
if (!dry && status !== 'unchanged') { mkdirSync(dirname(at), { recursive: true }); writeFileSync(at, f.content); }
return { path: relative(root, at), status, bytes: Buffer.byteLength(f.content), content: f.content };
});
if (json) return printJson({ dry, out: relative(root, out) || '.', files: files.map(({ path, status, bytes }) => ({ path, status, bytes })), skipped: plan.skipped });
for (const f of files) {
log('web', `${dry ? 'would write' : f.status.padEnd(9)} ${f.path} (${f.bytes} bytes)${dry ? ` [${f.status}]` : ''}`);
if (dry) console.log(f.content.replace(/\n?$/, '\n'));
}
for (const s of plan.skipped) log('web', `skipped: ${s}`);
if (!files.length) warn('web', 'nothing to write: add apple.teamId, web.androidSha256 or apple.appId (see skills/web-presence)');
else done('web', dry ? `dry run: ${files.length} file(s), nothing written` : `${files.length} file(s) in ${relative(root, out) || '.'}; deploy its contents to the root of https://${c.web?.domain ?? '<your domain>'}, then run storebound web check`);
}
/** GET without following redirects; never throws (a network error becomes status 0). */
async function grab(url: string, follow = false): Promise<Fetched> {
try {
const r = await fetch(url, { redirect: follow ? 'follow' : 'manual', headers: { 'User-Agent': 'storebound-web-check' } });
const buf = new Uint8Array(await r.arrayBuffer());
return { url, status: r.status, location: r.headers.get('location') ?? undefined, contentType: r.headers.get('content-type') ?? '', body: new TextDecoder().decode(buf), bytes: buf.length };
} catch (e) {
return { url, status: 0, contentType: '', body: '', bytes: 0, location: `network error: ${(e as Error).message.slice(0, 120)}` };
}
}
/** All checks of one site. `base` is https://<domain> in real runs (tests pass a local http server). */
export async function checkSite(base: string, ids: WebIds, o: { landing?: boolean; apple?: boolean; play?: boolean } = {}): Promise<Check[]> {
const host = new URL(base).host;
const out: Check[] = [];
const net = (r: Fetched, id: string): Check[] | null => (r.status === 0 ? [{ id, url: r.url, ok: false, level: 'problem', message: r.location ?? 'network error', fix: `make https://${host} reachable from the public internet with a valid certificate` }] : null);
if (o.apple !== false) {
const r = await grab(base + AASA_PATH);
out.push(...(net(r, 'aasa') ?? checkAasa(r, ids, host)));
const l = await grab(base + AASA_LEGACY_PATH);
if (l.status !== 0) out.push(...checkAasaLegacy(l));
}
if (o.play !== false) {
const r = await grab(base + ASSETLINKS_PATH);
out.push(...(net(r, 'assetlinks') ?? checkAssetLinks(r, ids, host)));
}
if (o.landing) {
const r = await grab(base + '/', true);
out.push(...(net(r, 'landing') ?? checkLanding(r, ids)));
}
return out;
}
async function check(ctx: Ctx): Promise<void> {
const { config: c } = ctx.loaded;
const a = ctx.args;
const domain = (a._[1] ?? c.web?.domain ?? '').replace(/^https?:\/\//, '').replace(/\/.*$/, '');
// --base-url is for tests only (a local http server); real runs always use https://<domain>
const base = (a.get('base-url') ?? '').replace(/\/$/, '') || (domain ? `https://${domain}` : '');
if (!base) throw new Error('usage: storebound web check <domain> (or set web.domain in storebound.config.ts)');
if (!/^[a-z0-9.-]+(:\d+)?$/i.test(new URL(base).host)) throw new Error(`not a domain: ${domain}`);
const checks = await checkSite(base, webIdsOf(c), { landing: !!c.web?.landing, apple: !!c.apple, play: !!c.play });
const problems = checks.filter(x => x.level === 'problem').length;
if (a.has('json')) printJson({ domain: domain || new URL(base).host, checks });
else {
console.log(textTable(['', 'check', 'result', 'fix'], checks.map(x => [x.level === 'ok' ? 'ok' : x.level === 'problem' ? 'PROBLEM' : 'info', x.id, x.message, x.fix && x.level !== 'ok' ? x.fix : ''])));
log('web', problems ? `${problems} problem(s) on ${new URL(base).host}` : `no problems on ${new URL(base).host} (Apple's CDN refreshes within about a day; Android verifies at install)`);
}
if (problems) process.exitCode = 1;
}

View file

@ -12,8 +12,8 @@ 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 | | API | operations | GET | other | wrapped by a command | owner only |
|---|---:|---:|---:|---:|---:| |---|---:|---:|---:|---:|---:|
| App Store Connect API 4.5.1 | 1303 | 826 | 477 | 183 | 166 | | App Store Connect API 4.5.1 | 1303 | 826 | 477 | 186 | 166 |
| Google Play Android Developer API v3 (revision 20261008) | 145 | 45 | 100 | 32 | 49 | | Google Play Android Developer API v3 (revision 20261008) | 145 | 45 | 100 | 33 | 49 |
| Google Play Developer Reporting API v1beta1 (revision 20261008) | 25 | 15 | 10 | 6 | 0 | | Google Play Developer Reporting API v1beta1 (revision 20261008) | 25 | 15 | 10 | 6 | 0 |
## App Store Connect API 4.5.1 ## App Store Connect API 4.5.1
@ -674,15 +674,15 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co
| `bundleIds_bundleIdCapabilities_getToManyRelationship` | GET | `/v1/bundleIds/{id}/relationships/bundleIdCapabilities` | read | | | `bundleIds_bundleIdCapabilities_getToManyRelationship` | GET | `/v1/bundleIds/{id}/relationships/bundleIdCapabilities` | read | |
| `bundleIds_createInstance` | POST | `/v1/bundleIds` | write (dry by default) | apple/bundle | | `bundleIds_createInstance` | POST | `/v1/bundleIds` | write (dry by default) | apple/bundle |
| `bundleIds_deleteInstance` | DELETE | `/v1/bundleIds/{id}` | owner only (typed confirm) | | | `bundleIds_deleteInstance` | DELETE | `/v1/bundleIds/{id}` | owner only (typed confirm) | |
| `bundleIds_getCollection` | GET | `/v1/bundleIds` | read | apple/bundle, apple/signing | | `bundleIds_getCollection` | GET | `/v1/bundleIds` | read | apple/adhoc, apple/bundle, apple/signing |
| `bundleIds_getInstance` | GET | `/v1/bundleIds/{id}` | read | | | `bundleIds_getInstance` | GET | `/v1/bundleIds/{id}` | read | |
| `bundleIds_profiles_getToManyRelated` | GET | `/v1/bundleIds/{id}/profiles` | read | apple/signing | | `bundleIds_profiles_getToManyRelated` | GET | `/v1/bundleIds/{id}/profiles` | read | apple/adhoc, apple/signing |
| `bundleIds_profiles_getToManyRelationship` | GET | `/v1/bundleIds/{id}/relationships/profiles` | read | | | `bundleIds_profiles_getToManyRelationship` | GET | `/v1/bundleIds/{id}/relationships/profiles` | read | |
| `bundleIds_updateInstance` | PATCH | `/v1/bundleIds/{id}` | write (dry by default) | | | `bundleIds_updateInstance` | PATCH | `/v1/bundleIds/{id}` | write (dry by default) | |
| **certificates** (7) | | | | | | **certificates** (7) | | | | |
| `certificates_createInstance` | POST | `/v1/certificates` | write (dry by default) | apple/signing, lib/signing | | `certificates_createInstance` | POST | `/v1/certificates` | write (dry by default) | apple/signing, lib/signing |
| `certificates_deleteInstance` | DELETE | `/v1/certificates/{id}` | owner only (typed confirm) | | | `certificates_deleteInstance` | DELETE | `/v1/certificates/{id}` | owner only (typed confirm) | |
| `certificates_getCollection` | GET | `/v1/certificates` | read | apple/signing | | `certificates_getCollection` | GET | `/v1/certificates` | read | apple/adhoc, apple/signing |
| `certificates_getInstance` | GET | `/v1/certificates/{id}` | read | | | `certificates_getInstance` | GET | `/v1/certificates/{id}` | read | |
| `certificates_passTypeId_getToOneRelated` | GET | `/v1/certificates/{id}/passTypeId` | read | | | `certificates_passTypeId_getToOneRelated` | GET | `/v1/certificates/{id}/passTypeId` | read | |
| `certificates_passTypeId_getToOneRelationship` | GET | `/v1/certificates/{id}/relationships/passTypeId` | read | | | `certificates_passTypeId_getToOneRelationship` | GET | `/v1/certificates/{id}/relationships/passTypeId` | read | |
@ -752,8 +752,8 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co
| `customerReviews_response_getToOneRelated` | GET | `/v1/customerReviews/{id}/response` | read | | | `customerReviews_response_getToOneRelated` | GET | `/v1/customerReviews/{id}/response` | read | |
| `customerReviews_response_getToOneRelationship` | GET | `/v1/customerReviews/{id}/relationships/response` | read | | | `customerReviews_response_getToOneRelationship` | GET | `/v1/customerReviews/{id}/relationships/response` | read | |
| **devices** (4) | | | | | | **devices** (4) | | | | |
| `devices_createInstance` | POST | `/v1/devices` | write (dry by default) | | | `devices_createInstance` | POST | `/v1/devices` | write (dry by default) | apple/adhoc |
| `devices_getCollection` | GET | `/v1/devices` | read | | | `devices_getCollection` | GET | `/v1/devices` | read | apple/adhoc |
| `devices_getInstance` | GET | `/v1/devices/{id}` | read | | | `devices_getInstance` | GET | `/v1/devices/{id}` | read | |
| `devices_updateInstance` | PATCH | `/v1/devices/{id}` | write (dry by default) | | | `devices_updateInstance` | PATCH | `/v1/devices/{id}` | write (dry by default) | |
| **diagnosticSignatures** (1) | | | | | | **diagnosticSignatures** (1) | | | | |
@ -1241,7 +1241,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co
| `inAppPurchasesV2_inAppPurchaseLocalizations_getToManyRelationship` | GET | `/v2/inAppPurchases/{id}/relationships/inAppPurchaseLocalizations` | read | | | `inAppPurchasesV2_inAppPurchaseLocalizations_getToManyRelationship` | GET | `/v2/inAppPurchases/{id}/relationships/inAppPurchaseLocalizations` | read | |
| `inAppPurchasesV2_offerCodes_getToManyRelated` | GET | `/v2/inAppPurchases/{id}/offerCodes` | read | apple/offer-codes | | `inAppPurchasesV2_offerCodes_getToManyRelated` | GET | `/v2/inAppPurchases/{id}/offerCodes` | read | apple/offer-codes |
| `inAppPurchasesV2_offerCodes_getToManyRelationship` | GET | `/v2/inAppPurchases/{id}/relationships/offerCodes` | read | | | `inAppPurchasesV2_offerCodes_getToManyRelationship` | GET | `/v2/inAppPurchases/{id}/relationships/offerCodes` | read | |
| `inAppPurchasesV2_pricePoints_getToManyRelated` | GET | `/v2/inAppPurchases/{id}/pricePoints` | read | apple/iap, apple/offer-codes, prices | | `inAppPurchasesV2_pricePoints_getToManyRelated` | GET | `/v2/inAppPurchases/{id}/pricePoints` | read | apple/iap, apple/offer-codes, prices, prices-ppp |
| `inAppPurchasesV2_pricePoints_getToManyRelationship` | GET | `/v2/inAppPurchases/{id}/relationships/pricePoints` | read | | | `inAppPurchasesV2_pricePoints_getToManyRelationship` | GET | `/v2/inAppPurchases/{id}/relationships/pricePoints` | read | |
| `inAppPurchasesV2_promotedPurchase_getToOneRelated` | GET | `/v2/inAppPurchases/{id}/promotedPurchase` | read | | | `inAppPurchasesV2_promotedPurchase_getToOneRelated` | GET | `/v2/inAppPurchases/{id}/promotedPurchase` | read | |
| `inAppPurchasesV2_promotedPurchase_getToOneRelationship` | GET | `/v2/inAppPurchases/{id}/relationships/promotedPurchase` | read | | | `inAppPurchasesV2_promotedPurchase_getToOneRelationship` | GET | `/v2/inAppPurchases/{id}/relationships/promotedPurchase` | read | |
@ -1292,9 +1292,9 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co
| `profiles_bundleId_getToOneRelationship` | GET | `/v1/profiles/{id}/relationships/bundleId` | read | | | `profiles_bundleId_getToOneRelationship` | GET | `/v1/profiles/{id}/relationships/bundleId` | read | |
| `profiles_certificates_getToManyRelated` | GET | `/v1/profiles/{id}/certificates` | read | | | `profiles_certificates_getToManyRelated` | GET | `/v1/profiles/{id}/certificates` | read | |
| `profiles_certificates_getToManyRelationship` | GET | `/v1/profiles/{id}/relationships/certificates` | read | apple/signing | | `profiles_certificates_getToManyRelationship` | GET | `/v1/profiles/{id}/relationships/certificates` | read | apple/signing |
| `profiles_createInstance` | POST | `/v1/profiles` | write (dry by default) | lib/signing | | `profiles_createInstance` | POST | `/v1/profiles` | write (dry by default) | apple/adhoc, lib/signing |
| `profiles_deleteInstance` | DELETE | `/v1/profiles/{id}` | owner only (typed confirm) | | | `profiles_deleteInstance` | DELETE | `/v1/profiles/{id}` | owner only (typed confirm) | |
| `profiles_devices_getToManyRelated` | GET | `/v1/profiles/{id}/devices` | read | | | `profiles_devices_getToManyRelated` | GET | `/v1/profiles/{id}/devices` | read | apple/adhoc |
| `profiles_devices_getToManyRelationship` | GET | `/v1/profiles/{id}/relationships/devices` | read | | | `profiles_devices_getToManyRelationship` | GET | `/v1/profiles/{id}/relationships/devices` | read | |
| `profiles_getCollection` | GET | `/v1/profiles` | read | | | `profiles_getCollection` | GET | `/v1/profiles` | read | |
| `profiles_getInstance` | GET | `/v1/profiles/{id}` | read | apple/signing | | `profiles_getInstance` | GET | `/v1/profiles/{id}` | read | apple/signing |
@ -1617,7 +1617,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co
| `androidpublisher.externaltransactions.refundexternaltransaction` | POST | `androidpublisher/v3/{+name}:refund` | owner only (typed confirm) | | | `androidpublisher.externaltransactions.refundexternaltransaction` | POST | `androidpublisher/v3/{+name}:refund` | owner only (typed confirm) | |
| **androidpublisher.generatedapks** (2) | | | | | | **androidpublisher.generatedapks** (2) | | | | |
| `androidpublisher.generatedapks.download` | GET | `androidpublisher/v3/applications/{packageName}/generatedApks/{versionCode}/downloads/{downloadId}:download` | read | | | `androidpublisher.generatedapks.download` | GET | `androidpublisher/v3/applications/{packageName}/generatedApks/{versionCode}/downloads/{downloadId}:download` | read | |
| `androidpublisher.generatedapks.list` | GET | `androidpublisher/v3/applications/{packageName}/generatedApks/{versionCode}` | read | | | `androidpublisher.generatedapks.list` | GET | `androidpublisher/v3/applications/{packageName}/generatedApks/{versionCode}` | read | web |
| **androidpublisher.grants** (3) | | | | | | **androidpublisher.grants** (3) | | | | |
| `androidpublisher.grants.create` | POST | `androidpublisher/v3/{+parent}/grants` | owner only (typed confirm) | | | `androidpublisher.grants.create` | POST | `androidpublisher/v3/{+parent}/grants` | owner only (typed confirm) | |
| `androidpublisher.grants.delete` | DELETE | `androidpublisher/v3/{+name}` | owner only (typed confirm) | | | `androidpublisher.grants.delete` | DELETE | `androidpublisher/v3/{+name}` | owner only (typed confirm) | |
@ -1636,7 +1636,7 @@ Specs: Apple [App Store Connect API 4.5.1](https://developer.apple.com/sample-co
| `androidpublisher.internalappsharingartifacts.uploadapk` | POST | `androidpublisher/v3/applications/internalappsharing/{packageName}/artifacts/apk` | write (dry by default) | | | `androidpublisher.internalappsharingartifacts.uploadapk` | POST | `androidpublisher/v3/applications/internalappsharing/{packageName}/artifacts/apk` | write (dry by default) | |
| `androidpublisher.internalappsharingartifacts.uploadbundle` | POST | `androidpublisher/v3/applications/internalappsharing/{packageName}/artifacts/bundle` | write (dry by default) | | | `androidpublisher.internalappsharingartifacts.uploadbundle` | POST | `androidpublisher/v3/applications/internalappsharing/{packageName}/artifacts/bundle` | write (dry by default) | |
| **androidpublisher.monetization** (1) | | | | | | **androidpublisher.monetization** (1) | | | | |
| `androidpublisher.monetization.convertRegionPrices` | POST | `androidpublisher/v3/applications/{packageName}/pricing:convertRegionPrices` | read | play/products, play/subscriptions, prices | | `androidpublisher.monetization.convertRegionPrices` | POST | `androidpublisher/v3/applications/{packageName}/pricing:convertRegionPrices` | read | play/products, play/subscriptions, prices, prices-ppp |
| **androidpublisher.monetization.onetimeproducts** (7) | | | | | | **androidpublisher.monetization.onetimeproducts** (7) | | | | |
| `androidpublisher.monetization.onetimeproducts.batchDelete` | POST | `androidpublisher/v3/applications/{packageName}/oneTimeProducts:batchDelete` | owner only (typed confirm) | | | `androidpublisher.monetization.onetimeproducts.batchDelete` | POST | `androidpublisher/v3/applications/{packageName}/oneTimeProducts:batchDelete` | owner only (typed confirm) | |
| `androidpublisher.monetization.onetimeproducts.batchGet` | GET | `androidpublisher/v3/applications/{packageName}/oneTimeProducts:batchGet` | read | | | `androidpublisher.monetization.onetimeproducts.batchGet` | GET | `androidpublisher/v3/applications/{packageName}/oneTimeProducts:batchGet` | read | |

View file

@ -178,6 +178,28 @@ workspace file (the keychain is never read; the profiles to create are listed);
--apply` adds a workspace to `state.json` while the app is closed (backup kept, nothing removed, new accounts get --apply` adds a workspace to `state.json` while the app is closed (backup kept, nothing removed, new accounts get
their keys in the Accounts screen). Project ids in an exported state are stable per folder path (16 hex). their keys in the Accounts screen). Project ids in an exported state are stable per folder path (16 hex).
### Fill in console
Some store forms have no API: the App Store app record (New App), the age rating, App Privacy, and the Play content
rating and target audience questionnaires. The App info tab has a **Fill in console** button for each (App Privacy
card, App info card for the age rating, a "Play Console questionnaires" card, and a notice when the config has no
App Store app id yet). It runs `storebound console fill <form>` through the desktop-only method `console.fill` (a
write, never an MCP tool):
1. The click runs the dry run (`console fill <form> --dry --json`): nothing opens. A panel lists the answers from
the config; the ones only the owner knows are marked "You answer this". It shows the note: "Console pages
change. This is AI-assisted: review every field in the browser and press Save yourself. storebound never saves,
submits or publishes."
2. **Open the browser** goes through `write_with_confirm`: the host repeats the dry run and shows the answers and the
note in a native dialog ("Open the browser" / Cancel). Only that button mints the confirm token.
3. The real run opens a visible Chromium with its own profile. The owner signs in (storebound never types passwords);
storebound fills the fields, highlights the uncertain ones and never clicks Save, Submit, Publish or Next. The
run lasts until the owner closes the browser: no timeout in serve, the runner or the host. Progress lines show in
the panel; **Cancel: close the browser** sends `$/cancelRequest`, which stops the command and its browser.
The browser is the desktop's Chrome for Testing (`STOREBOUND_CHROME`, passed to the sidecar like for screenshot
renders) with the bundled playwright-core; without it, the same fallbacks as `shots render`.
## Every CLI area in the window ## Every CLI area in the window
| CLI | where in the window | | CLI | where in the window |
@ -188,6 +210,7 @@ their keys in the Accounts screen). Project ids in an exported state are stable
| `inspect --declarations --json` (new) | App info: Data safety, App Privacy suggestions, app info, encryption, review details, "ask the owner" items | | `inspect --declarations --json` (new) | App info: Data safety, App Privacy suggestions, app info, encryption, review details, "ask the owner" items |
| `play data-safety` | App info: Upload (keeps `.storebound/data-safety.uploaded.csv`, so the tab shows changes since; Play cannot read the form back) | | `play data-safety` | App info: Upload (keeps `.storebound/data-safety.uploaded.csv`, so the tab shows changes since; Play cannot read the form back) |
| `apple appinfo`, `apple encryption`, `apple review-details` | App info: Push buttons (confirm flow) | | `apple appinfo`, `apple encryption`, `apple review-details` | App info: Push buttons (confirm flow) |
| `console fill <form> --dry --json` / `console fill <form> --json` (desktop-only `console.fill`) | App info: "Fill in console" (answers panel, native dialog, visible browser the owner saves in) |
| `apple ppo status / create / upload / start / stop` | Growth: tests table, create, upload, Start / Stop owner actions | | `apple ppo status / create / upload / start / stop` | Growth: tests table, create, upload, Start / Stop owner actions |
| Play store listing experiments | no API: Growth links Play Console and the variant renders | | Play store listing experiments | no API: Growth links Play Console and the variant renders |
| `analytics compare --json`, `snapshot`, `setup` | Growth: chart (reach, installs, conversion, listing changes as markers), before / after table, snapshot and setup buttons | | `analytics compare --json`, `snapshot`, `setup` | Growth: chart (reach, installs, conversion, listing changes as markers), before / after table, snapshot and setup buttons |

View file

@ -0,0 +1,76 @@
---
name: adhoc-distribution
description: Get a test build of a mobile app or game onto specific devices without a store review - Apple ad-hoc / release-testing (register device UDIDs, an ad-hoc provisioning profile, ExportOptions.plist, xcodebuild -exportArchive) and Google Play internal app sharing (upload an AAB or APK, get a share link). Explains when to use ad-hoc vs TestFlight vs Play internal testing vs internal app sharing, the 100 devices per year limit, and the tester setup. Use when the user wants an IPA for a few devices, asks how to register a device or UDID, needs an ExportOptions.plist, or wants a quick Play install link for a build.
---
# Ad-hoc builds and internal app sharing
CLI: `storebound` (or `bunx storebound` in a project that has it, or `bun <toolchain>/cli/index.ts`).
## Which channel
| Channel | Who installs | Review | Limits | Use it for |
|---|---|---|---|---|
| TestFlight internal (`testflight` skill) | up to 100 App Store Connect users | none | 90-day builds | the team, every build |
| TestFlight external | up to 10,000 testers, by email or public link | Beta App Review for the first build of a version | 90-day builds | wider beta |
| Apple ad-hoc / release-testing | registered devices only | none | 100 devices per product family per membership year | a client demo, a device lab, testers without App Store Connect access |
| Play internal testing track (`play-first-release` skill) | up to 100 testers by email list | none | needs a track release | the team, every build |
| Play internal app sharing | anyone allowed to use the link (default: anyone with it) | none | 100 users per link, link valid 60 days | a quick build for one person, any version code, debuggable builds |
Prefer TestFlight and Play internal testing. Ad-hoc costs device slots you only get back at the start of a
membership year; internal app sharing builds cannot be promoted to any track.
## Apple ad-hoc
Config: `apple.teamId` (Membership details), `apple.bundleId`, optional `apple.adhoc`:
`method` (`release-testing`, the name since Xcode 15.3, default; `ad-hoc` for older Xcode), `devices` (default
`.storebound/devices.csv`), `profile` (a profile name: manual signing; unset: automatic signing).
1. **The owner collects the devices.** UDIDs are personal data: they stay in `.storebound/devices.csv` (gitignored),
never in chat, issues or commits. Header line `name,udid,platform`, one device per line, platform `IOS` or `MAC_OS`.
The tester finds the UDID in Finder (iPhone connected, click the line under the device name) or Xcode Devices;
an Apple silicon Mac needs its Provisioning UDID (System Information > Hardware).
2. `storebound apple adhoc devices` (read-only): what is registered, UDIDs masked, and the slots used per device class.
3. `storebound apple adhoc register --dry`: validates the CSV (40 hex digits, or 8 hex - 16 hex), compares with the
registered devices and lists the new ones. Show it to the owner. Every new device uses one of the 100 yearly slots
of its product family, also if it is disabled later. Then `storebound apple adhoc register` asks and registers.
One device: `--name "Test iPhone" --udid <udid> --platform IOS`. It never disables, enables or deletes a device:
that is the owner's call on the Apple Developer website.
4. Signing, either:
- automatic (no `apple.adhoc.profile`): Xcode creates the profile during export (`-allowProvisioningUpdates`), or
- manual: `storebound apple adhoc profile --dry`, then `storebound apple adhoc profile`. It creates an
IOS_APP_ADHOC profile for the bundle id with every enabled iOS device and the valid Apple Distribution
certificates, and saves `build/adhoc/<name>.mobileprovision` (double-click to install). A profile cannot be
changed: when devices were added, a new profile with a dated name is created; set `apple.adhoc.profile` to it.
Deleting the old one is the owner's step on the developer website.
5. Archive in Xcode (Product > Archive) or `xcodebuild archive`.
6. `storebound apple adhoc options --dry` shows the ExportOptions.plist (method, teamID, signingStyle, thinning
`<none>`, destination export); without `--dry` it writes `build/ExportOptions.plist`.
7. `storebound apple adhoc export --archive build/App.xcarchive --dry` prints the exact `xcodebuild -exportArchive`
command; without `--dry` it runs it and lists the `.ipa` in `build/adhoc/`. With `-allowProvisioningUpdates`
Xcode may contact Apple to create or refresh signing assets.
8. Install: Apple Configurator, Finder (drag the IPA onto the device) or Xcode Devices. A device that is not in the
profile cannot install the build: re-run steps 3, 4 and 7.
## Google Play internal app sharing
1. Owner, once in Play Console > Internal app sharing (under Test and release): who may upload (the service account
needs "Release apps to testing tracks" for the app, or a place on the uploader list) and who may download
(an email list, or "Anyone you shared the link with can download", the default).
2. `storebound play share --aab app-release.aab --dry` (or `--apk`): file, size, sha256 and package; nothing sent.
3. `storebound play share --aab app-release.aab` asks, uploads and prints the share link and the certificate
fingerprint (Google re-signs the build with an internal app sharing key). `--json`:
`{ downloadUrl, certificateFingerprint, sha256 }`. Limits: app bundles up to 10 GiB, APKs up to 1 GiB.
4. Each tester, once per device: Play Store > Settings > About > tap "Play Store version" 7 times > turn on Internal
app sharing. Then open the link on the device. Testers must be able to see the app's store listing on Google Play
(country and track access). The link expires 60 days after the upload; re-upload for a new one.
## The owner decides
- Which devices to register (yearly slots) and removing or disabling any device.
- Who may download internal app sharing links, and sharing a link at all (anyone with it can install the build).
- Deleting old provisioning profiles.
## Out of scope
- Enterprise (in-house) distribution, Developer ID / notarized Mac apps, over-the-air install pages (the
ExportOptions `manifest` key).
- Firebase App Distribution and other third-party beta services.

66
skills/apple-ads/SKILL.md Normal file
View file

@ -0,0 +1,66 @@
---
name: apple-ads
description: Read Apple Ads (formerly Apple Search Ads) results for a mobile app or game and make small, owner-approved bid, daily budget and pause changes - API user setup (role, key pair, client id / team id / key id), ad account check, campaign list, spend / taps / installs / CPA reports per campaign or keyword with CSV export, and keyword bid, campaign daily budget and pause changes that always show old -> new and ask first. Use when the user asks how their Apple Ads / Search Ads campaigns perform, what an install costs, wants a spend report or CSV, or wants to raise or lower a bid or budget or pause a campaign.
---
# Apple Ads: reports and small changes
CLI: `storebound ads apple <status | campaigns | report | bid | budget | pause>`. storebound uses the **Apple Ads
Platform API** (`api.ads.apple.com/v1`). It replaces the Campaign Management API v5, which Apple turns off on
January 26, 2027. Both use the same API credentials, so a key you made for v5 keeps working.
Reports and lists are read-only. Bid, budget and pause spend or stop money: they are the owner's decisions.
## Setup (once, by the owner, in the Apple Ads web UI)
1. An account admin invites the API user: ads.apple.com > Sign In > Advanced > Account Settings > User Management >
Invite Users, with an API role on the ad account:
- `API Account Read Only`: reports and lists only. Enough for `status`, `campaigns`, `report`.
- `API Account Manager` (or `Limited Access: API Read & Write`): needed for `bid`, `budget`, `pause`.
Start read-only unless the owner wants to change bids from the terminal.
2. The API user makes a key pair on their own machine (the private key never leaves it):
`openssl ecparam -genkey -name prime256v1 -noout -out apple-ads-private-key.pem`
`openssl ec -in apple-ads-private-key.pem -pubout -out apple-ads-public-key.pem`
3. Apple Ads > Account Settings > API: paste the public key, Save. Apple shows `clientId`, `teamId`, `keyId`.
4. The owner puts them into `.storebound/credentials.json` (gitignored) or the environment. Never paste them in chat:
- `APPLE_ADS_CLIENT_ID` (`SEARCHADS.…`), `APPLE_ADS_TEAM_ID` (`SEARCHADS.…`), `APPLE_ADS_KEY_ID`
- `APPLE_ADS_PRIVATE_KEY`: path to the private key PEM (or the PEM itself)
- `APPLE_ADS_ACCOUNT_ID`: the ad account id. Leave it empty at first; step 5 lists the ids.
5. `storebound ads apple status`: checks the token, lists the ad accounts with your roles (`*` = the one used), the
account's currency, time zone and status, and whether the role can write. Set `APPLE_ADS_ACCOUNT_ID` to the App Store
account (product feature `APPSTORE_APP_MANUAL`) and run it again.
6. Set `apple.appId` in `storebound.config.ts` (the App Store app id, the number in the app's store URL). Lists and
reports then show only this app's campaigns (`--all` for every app in the account).
storebound signs a short-lived client secret per run and keeps the access token in memory only.
## Read
- `storebound ads apple campaigns [--all] [--json]`: id, name, status, display status, daily budget, bid strategy,
countries, adamId (`*` = this app).
- `storebound ads apple report [--days 7 | --start 2026-10-01 --end 2026-10-07] [--by campaign|keyword]
[--campaign <id>] [--adgroup <id>] [--csv store/ads.csv] [--json]`
- Window: `--days N` ends yesterday (UTC; today is still incomplete), or `--start` / `--end` inclusive.
- Columns: spend (account currency), impressions, taps, installs (tap + view-through), TTR (taps / impressions),
CR (installs / taps), CPA (spend / installs, `n/a` with 0 installs), average CPT (spend / taps), and a TOTAL line.
- `--by keyword` lists every keyword of the chosen campaigns (narrow with `--campaign`, `--adgroup`).
- `--csv <file>` writes the rows (rates as fractions, empty CPA cell with 0 installs); `--dry` writes nothing.
- Only rows with activity are returned. Apple's numbers can still change for a day or two.
- Read the report with the owner: high spend with 0 installs, a CPA above what a user is worth (compare with
revenue or LTV), keywords with many impressions and a low TTR (weak relevance or creative).
## Change (owner only, in a terminal)
- `storebound ads apple bid --keyword <id> --bid 1.25 [--campaign <id>] [--adgroup <id>] --dry`
- `storebound ads apple budget --campaign <id> --daily 50.00 --dry`
- `storebound ads apple pause --campaign <id> [--adgroup <id>] --dry`
Each reads the current value first and prints `old -> new` with the change in percent, in the account currency.
Show the dry run to the owner. Only the owner runs it without `--dry`; it asks `[y/N]` before the change. Without a
terminal it changes nothing (unless `--yes`), and under the desktop app or MCP it is always refused. An agent never
adds `--yes` on its own. Keyword bids do nothing in Maximize Conversions campaigns: the command refuses those.
To resume a paused campaign, use the Apple Ads web UI.
## Out of scope
- Creating or deleting campaigns, ad groups, keywords, ads, creatives, custom product pages, budget orders:
use the Apple Ads web UI.
- Search Ads attribution in the app (AdServices framework / Apple Ads attribution API), SKAdNetwork, MMPs.
- Apple Maps (brand) campaigns.
- Any automatic bidding rules: storebound makes one change at a time, and only when the owner says so.

View file

@ -0,0 +1,63 @@
---
name: console-autofill
description: AI-assisted autofill of App Store Connect and Google Play Console forms that have no API (the New App dialog, App Privacy, the Play IARC content rating questionnaire, Target audience and content plus the Ads declaration; the App Store age rating is shown as guidance because the API sets it) in a visible Chromium the owner signs in to. Answers come only from storebound.config.ts; anything the config does not prove stays empty and highlighted. storebound never signs in, never saves, submits or publishes. Use when the user wants help filling one of these console forms, asks what to answer in them, or wants the answers as a checklist.
---
# Console autofill (forms without an API)
CLI: `storebound` (or `bunx storebound` in a project that has it, or `bun <toolchain>/cli/index.ts`).
**Read this to the owner first.** Console pages change without notice. This is AI-assisted autofill and it may put an
answer in the wrong place. The owner reviews every field and presses the final button. storebound never types a
password, never touches a sign-in page, never reads cookies, and never clicks Save, Submit, Publish, Create, Next or
any similar control (English or Turkish console). It is not available over MCP.
## Forms
| form | where | filled from |
|---|---|---|
| `apple-app-record` | App Store Connect > Apps > + > New App | app.name, apple.primaryLocale, apple.bundleId, console.appRecord (SKU, user access) |
| `apple-age-rating` | App Information > Age Ratings | guide only: `storebound apple appinfo` sets every question through the API |
| `apple-app-privacy` | the app > App Privacy | dataSafety (types and purposes); linked to identity and tracking are always the owner's |
| `play-content-rating` | Policy > App content > Content rating | app.contactEmail, app.profile, products, console.contentRating |
| `play-target-audience` | Policy > App content > Target audience and content (+ Ads) | console.targetAudience, ads.appAdsTxt |
## Steps
1. `storebound console fill` lists the forms. `storebound console fill <form> --dry` prints every answer with its
source; `[check]` lines are not proven by the config. Show them to the owner.
2. For each `[check]` line, ask the owner (AGENTS.md rule 5: never guess a compliance answer). If they want it filled
next time, add it to the config, for example:
```ts
console: {
appRecord: { sku: 'com.example.game', userAccess: 'full' },
contentRating: { category: 'game', answers: { violence: false, lootBoxes: false, userInteraction: false } },
targetAudience: { ages: ['13-15', '16-17', '18-over'], appealsToChildren: false, containsAds: true },
},
```
Age rating answers live in `apple.info.ageRating` (also `socialMedia`, `socialMediaAgeRestricted`).
3. The owner runs `storebound console fill <form>` in a terminal (or presses the button in the desktop app). A Chromium
window opens with its own profile (`~/.storebound/console-profile/<store>`, or `--profile <dir>` /
`STOREBOUND_CONSOLE_PROFILE`). If a sign-in page shows, storebound prints "sign in in the browser window, storebound
waits" and waits up to 10 minutes. The sign-in stays in that profile for the next run.
4. storebound prints what to click to open the form (Play Console has no deep link; App Store Connect opens the app
when `apple.appId` is set). When the form appears it fills the certain answers, outlines every unproven or
unfillable field with a "storebound: check this" label, and lists them in the terminal.
5. Multi-page forms: the owner reviews the page and clicks Next; storebound fills the next page when it appears.
6. On the last page storebound prints "review every field and press <Save | Submit | Publish | Create> yourself". The
command ends when the owner closes the window (`--json` then prints the result with `filled`, `highlighted`,
`fallback`, `stoppedAt`).
7. If a field cannot be found or matches twice, the console UI changed: storebound stops filling and prints the
step-by-step list ("label: answer") for the owner to copy. That is the expected safe behavior, not an error.
## The owner decides
Every `[check]` answer, linked-to-identity and tracking for each App Privacy data type, the IARC answers, the target
ages, and pressing the final button (App Privacy Publish, IARC Submit, Target audience Save, New App Create).
## Out of scope
- Signing in, two-factor codes, accepting agreements, choosing a developer account.
- Forms with an API: Data safety (`storebound play data-safety`), age rating, categories and content rights
(`storebound apple appinfo`), export compliance (`storebound apple encryption`).
- Recording or reading console data: storebound only fills the visible form.

View file

@ -0,0 +1,69 @@
---
name: ppp-pricing
description: Propose purchasing power parity (PPP) prices for a mobile app's or game's in-app products in every App Store territory and Google Play region with `storebound prices ppp` - World Bank ICP PPP factors (bundled, CC BY 4.0), The Economist Big Mac index (downloaded on the owner's machine) or the owner's own factor CSV, clamped to a floor and ceiling of the US price, snapped to real App Store price points and clean local Play prices, written as a price sheet that `storebound prices import` applies after its own diff and confirmation. Use when the user asks for regional pricing, PPP or purchasing power pricing, cheaper prices in emerging markets, localized price tiers, or "price by country".
---
# PPP pricing (proposal sheet, both stores)
CLI: `storebound` (or `bunx storebound`, or `bun <toolchain>/cli/index.ts`). This command only proposes. It writes a
CSV and prints a diff; nothing reaches a store until the owner runs `storebound prices import` and confirms there.
## What it computes
Per product, store and region:
- `usd = base x PPP factor / exchange rate` (the PPP price, back in US dollars at the market rate).
- Clamped to `floor..ceiling` of the base (defaults 0.3 and 1.2): no region below 30 % or above 120 % of the US price.
- Converted to the currency the store uses there (some App Store storefronts are priced in USD or EUR) and snapped:
- App Store, online: the nearest real price point of that product in that territory (Apple takes nothing else).
- Google Play, and the App Store offline: a clean local ending (x.99, 0.x9, whole numbers ending in 9; round
numbers for JPY, KRW, VND, IDR, HUF, CLP, TWD and every value over 1000). Snapping can move a price a little past
the floor or ceiling.
- The US row is always the base itself.
## Data sources (the owner picks one)
- `worldbank` (default, bundled `cli/data/ppp-worldbank.json`): World Bank PA.NUS.PPP (PPP conversion factor, GDP)
and PA.NUS.FCRF (official exchange rate), latest year per country, CC BY 4.0. Euro regions use the euro area rate.
Countries without recent data (Taiwan, Venezuela, a few small territories) get no row.
- `bigmac`: The Economist Big Mac index (implied PPP = local Big Mac price / US price). Not bundled (its licence
leaves third-party data out). Download it on the owner's machine first: `storebound prices ppp --update-bigmac`
(writes `.storebound/ppp-bigmac.json`, gitignored).
- `file`: the owner's own CSV, `region,factor,currency,fx` (`fx` optional: then the bundled rate when the currency
matches). `--file <csv>` or `prices.ppp.file` in the config.
Config (optional): `prices: { ppp: { source, file, floor, ceiling, out } }`.
## Steps
1. `storebound check`. Products must be in `products[]` with a `usd` base. For real App Store price points the
products must exist on App Store Connect (`storebound apple iap`); otherwise those rows are offline proposals.
2. Dry run and show it to the owner:
`storebound prices ppp --dry` (all products; `--only id1,id2`, `--store apple|play`, `--base 4.99` to try another
US price, `--floor 0.4 --ceiling 1.1`, `--source bigmac|file`, `--offline` to skip every store read).
It prints the sheet, the diff against the stores' current prices (offline: every row "new") and the regions
without a proposal.
3. The owner decides: base price, floor and ceiling, and which regions to keep. Then write the sheet:
`storebound prices ppp` (default `store/prices-ppp.csv`, `--out` to change it).
4. The owner reviews and edits the CSV (delete rows to keep a store's own conversion, round to a house price ladder).
5. Apply through the normal price sheet flow: `storebound prices import --csv store/prices-ppp.csv --dry`, then
without `--dry` in a terminal after the owner says yes (see store-iap-setup). Import checks Apple price points
(the error lists the neighbours) and Play's region currencies.
## Read before applying
- PPP is a proposal, not a rule. Cheaper prices can cannibalize, invite VPN arbitrage on web checkouts and change
revenue; the owner decides region by region.
- Taxes: App Store and Play customer prices are tax-inclusive in most regions (EU VAT, UK VAT, many others), while
the US base is tax-exclusive. PPP factors describe consumer price levels including taxes, so the sheet is a
customer price; proceeds per region differ by the local tax. Play's convertRegionPrices also returns tax-inclusive
prices.
- Offline values: Apple only accepts its own price points and its own storefront currency (USD or EUR in many
smaller storefronts). An offline sheet is a starting point; `prices import --dry` shows what does not fit.
- An App Store price increase cannot be undone once it starts.
- Data age: `--json` and the log show the dataset's year and retrieval date. Maintainers refresh the bundled file
with `bun tools/update-ppp.ts` (`--check` prints its age).
## Output
`--json` prints `{ source: {name, year, retrieved, url, license}, base: {product: usd}, floor, ceiling, online:
{apple, play}, rows: [{product, store, region, currency, price, factor, fx, usdEquivalent, clamped, snappedFrom,
snap}], skipped: [{product, store, region, why}], diff, out, written }`. Use `--json --dry` for a read-only run.
## Out of scope
- Writing prices to a store (that is `storebound prices import`, after the owner's yes).
- Subscriptions (their prices go through `storebound apple subscriptions` / `play subscriptions` with a prices CSV).
- Choosing the base price or deciding which markets to discount: the owner's call.

View file

@ -0,0 +1,68 @@
---
name: revenuecat-sync
description: Optional adapter that keeps a RevenueCat project's catalog in step with the storebound config - one RevenueCat product per store item (Apple product id, Play one-time id or subscriptionId:basePlanId), entitlements with their products attached, one offering with packages ($rc_monthly, $rc_annual, $rc_lifetime, custom). Read-only parity report first (storebound revenuecat diff), then a create-and-attach-only sync after the owner agrees. Use when the app uses RevenueCat (Purchases SDK) and the user wants the RevenueCat products, entitlements or default offering to match the store catalog, asks why a product is missing in RevenueCat, or sets up RevenueCat after creating products with storebound. Not for runtime entitlements, receipts, customers, webhooks or paywalls.
---
# Mirror the catalog into RevenueCat
CLI: `storebound` (or `bunx storebound` in a project that has it, or `bun <toolchain>/cli/index.ts`). Optional: only
for apps that use RevenueCat. The source of truth stays the config (`products[]`, `subscriptions[]`); the store side
is made by `play products / subscriptions` and `apple iap / subscriptions` (skills `store-iap-setup`,
`store-subscriptions`). This adapter only copies that catalog into RevenueCat.
## What stays RevenueCat's job (out of scope)
storebound mirrors the catalog only. It never touches: runtime entitlements per user, receipt and purchase token
validation, customer info and history, webhooks and integrations, paywalls and experiments, App Store Server
Notifications / Play real-time notifications setup, and the store credentials inside RevenueCat (the App Store
in-app purchase key, the Play service account). Set those up in the RevenueCat dashboard.
## Prerequisites (owner)
1. A RevenueCat project with an App Store app and / or a Play Store app (Project settings > Apps), each connected to
its store in RevenueCat.
2. A v2 secret API key: Project settings > API keys > + New secret API key, version V2, permissions:
- Project configuration > Apps: read.
- Products, Entitlements, Offerings, Packages: read (enough for `diff`), or read & write (for `sync`).
Leave Customer information and Charts & metrics without access: storebound does not use them.
3. The owner puts the key in the environment or `.storebound/credentials.json` (gitignored) as
`REVENUECAT_SECRET_KEY` (`sk_...`). Never ask for it in chat, never print it, never commit it.
## Config
```ts
revenuecat: {
projectId: 'proj1ab2c3d4', // Project settings
apps: { apple: 'app...', play: 'app...' }, // optional: else matched by bundle id / package name
entitlements: { pro: ['com.example.app.pro_monthly', 'com.example.app.lifetime'] }, // optional
offering: 'default', // optional lookup key, default "default"
}
```
- Default entitlement: `pro` with every non-consumable, non-renewing product and subscription. Consumables never
unlock an entitlement.
- Products: Apple uses the product id; Play subscriptions are `<subscriptionId>:<basePlanId>` (the base plan id from
the config, else the default by period: monthly, yearly, ...); Play one-time products use the product id. A
`non_renewing` product is a non-renewing subscription on Apple and a consumable on Play (the app tracks the expiry).
- Packages of the offering: subscriptions by period `$rc_weekly`, `$rc_monthly`, `$rc_two_month`, `$rc_three_month`,
`$rc_six_month`, `$rc_annual` (first subscription per period; others get a custom package named by product id), a
non-consumable in an entitlement `$rc_lifetime`, every other item a custom package named by its product id.
## Steps
1. `storebound revenuecat diff` (read-only; `--json` for `{ projectId, apps, outOfSync, rows[], scope }`). Rows are
`missing`, `mismatch`, `extra` (in RevenueCat, not in the config), `info` or `ok`. Exit 1 when anything is missing
or mismatched; extras do not fail it.
2. `storebound revenuecat sync --dry`: the numbered plan (create products, create entitlements, attach products,
create the offering, create packages, attach products) and what is left alone. Show it to the owner.
3. After a clear yes: `storebound revenuecat sync` (asks in a terminal; `--yes` skips the question). Without a
terminal and without `--yes` nothing is sent. Re-running is safe: the plan comes from a fresh read.
4. `storebound revenuecat diff` again: expect 0 differences.
## The owner's decisions
- `--current` makes the configured offering the current (default) one. That changes what every app shows by default,
so it is never part of a plain sync. Ask first.
- Mismatches sync never fixes: a product with another type, an archived product / entitlement / offering, a package
that already holds another product for the same store app. The owner changes these in RevenueCat.
- Extras (products, entitlements, packages, attachments RevenueCat has but the config lacks) are left alone. Deleting,
archiving or detaching is the owner's job in the dashboard.
## Notes
- Rate limit: 60 requests per minute for project configuration; on HTTP 429 the CLI waits for `Retry-After`.
- 401 / 403: the key is wrong, is a v1 key, or lacks a permission listed above.
- Never via MCP for `sync`. `diff` is read-only.

View file

@ -0,0 +1,86 @@
---
name: web-presence
description: Set up the web side of a mobile app or game - iOS universal links (apple-app-site-association, Associated Domains entitlement), Android App Links (Digital Asset Links assetlinks.json with the Play app signing SHA-256, intent filter autoVerify), the Safari Smart App Banner meta tag and a minimal landing page with App Store and Google Play links - then check the live files (HTTPS, no redirects, application/json, ids match). Use when the user wants links to open the app, sets up a domain or landing page for an app, sees universal links or app links not opening the app, gets "assetlinks" / "apple-app-site-association" errors, or asks for a Smart App Banner.
---
# Web presence: universal links, app links, Smart App Banner, landing page
CLI: `storebound` (or `bunx storebound` in a project that has it, or `bun <toolchain>/cli/index.ts`).
- `storebound web init [--out web] [--landing] [--version-code N] [--dry] [--json]`: writes the files into a local
folder (default `web/`). Local writes only; nothing is uploaded.
- `storebound web check [<domain>] [--json]`: read-only, no credentials. Fetches the live files from
`https://<domain>` without following redirects and lists every check as ok / problem / info with the fix. Exit code
1 when there is a problem.
Config (`storebound.config.ts`):
- `apple.teamId` (10 characters, developer.apple.com > Account > Membership details), `apple.bundleId`,
`apple.appId` (App Store Connect > App Information > Apple ID, for the banner and the landing link).
- `play.packageName`.
- `web.domain` (`links.example.com`, no scheme or path), `web.paths` (default `["/*"]`), `web.exclude` (paths that stay
in the browser), `web.androidSha256` (Play app signing SHA-256, `AB:CD:...`), `web.webcredentials` (password
AutoFill), `web.landing`, `web.out`.
- `app.name`, `app.privacyPolicyUrl`, `app.supportUrl`, `app.termsUrl` fill the landing page.
## Steps
1. Pick the domain with the owner. A subdomain only for links (`links.example.com`) is the simplest: then
`web.paths: ["/*"]` is fine. On a domain that also has a normal website, list only the app paths
(`["/invite/*", "/open/*"]`) so the rest of the site stays in the browser.
2. Fingerprint for Android. With Play App Signing the key on users' devices is Google's, not the local keystore:
- Play Console > Test and release > App integrity > Play app signing: copy "SHA-256 certificate fingerprint" of the
app signing key into `web.androidSha256`. Add the upload key too if you install locally signed builds and want
links to verify there (an extra fingerprint is fine).
- Or `storebound web init --version-code <a versionCode you uploaded>`: reads it read-only from the Play Developer
API (generatedapks.list, `certificateSha256Hash`) and prints it; then put it in `web.androidSha256`.
3. `storebound web init --dry`, show the output, then `storebound web init` (add `--landing` for `index.html`). Missing
inputs are listed as `skipped: <why, how to fix>`; unchanged files are left alone.
4. Owner step: deploy the folder contents to the domain root over HTTPS. Requirements the host must meet:
- `/.well-known/apple-app-site-association` (no extension) and `/.well-known/assetlinks.json`, status 200,
`Content-Type: application/json`, no redirect (no http -> https, apex -> www or trailing-slash redirect for these
paths), public (no login, no IP or bot blocking, any user agent), valid certificate.
- Many static hosts skip dot-folders or serve extension-less files as `application/octet-stream`: add a headers
rule for the AASA path, and make sure a single-page-app fallback does not answer these paths with `index.html`.
- The files go on every host the app handles (`example.com` and `www.example.com` are two hosts).
5. App side (the code; storebound does not edit it):
- iOS: Signing & Capabilities > Associated Domains: `applinks:<domain>` (and `webcredentials:<domain>` with
`web.webcredentials`). The App ID needs the Associated Domains capability. Handle the URL in
`onOpenURL` / `scene(_:continue:)`. While developing against a server that is not public, use
`applinks:<domain>?mode=developer` (developer mode on the device) to bypass Apple's CDN.
- Android: in the activity, an intent filter with `android:autoVerify="true"`, action `VIEW`, categories `DEFAULT`
and `BROWSABLE`, `<data android:scheme="https" android:host="<domain>" />` plus the same paths as `web.paths`
(`android:pathPattern` / `pathPrefix`). `web.exclude` is also written as dynamic rules in assetlinks.json
(Android 15+); older versions only use the intent filter, so keep excluded paths out of it.
6. `storebound web check` until there are no problems. Then test on devices: Apple's CDN fetches the AASA within about
a day after install and rechecks about weekly; Android verifies at install (`adb shell pm get-app-links
<package>`, re-verify with `adb shell pm verify-app-links --re-verify <package>`).
7. Smart App Banner: `smart-app-banner.html` holds the `<meta name="apple-itunes-app" content="app-id=...">` tag. Put
it in the `<head>` of each page that should show it (the landing page already has it). Add
`app-argument=<url>` by hand to pass a deep link. It shows in Safari on iPhone and iPad, not in the simulator or
inside frames, and not again after the user closes it.
## Landing page
`index.html` is a small, responsive page with no external requests: the app name, an App Store link
(`https://apps.apple.com/app/id<appId>`), a Google Play link (`https://play.google.com/store/apps/details?id=<package>`)
and privacy / terms / support links. The store marks are the simple-icons files (`appstore.svg`, `googleplay.svg`,
copied unchanged next to it) shown in the text colour, with the trademark note in the footer. They only name the
store; for Apple's and Google's official badges, download them from Apple's marketing resources and Google Play's
badge page and follow their guidelines. Edit the page freely after the first write; `web init` reports it as
`updated` when it would replace your edits, so run `--dry` first.
## Owner decisions
- The domain, which paths open the app, and whether a landing page replaces an existing site.
- Hosting and DNS changes: storebound writes files, the owner deploys them.
## Out of scope
- Deploying or hosting the files, DNS, certificates.
- Editing the Xcode entitlements or AndroidManifest.xml.
- Deferred deep links (install then open the right screen) and link attribution: that needs a link service.
- App Clips (`appclips` in the AASA): not generated.
## Gotchas
- A redirect on the AASA or assetlinks path breaks verification even when the browser shows the file fine.
- `text/plain` or `application/octet-stream` on assetlinks.json fails Android verification; Apple wants
`application/json` and an AASA of at most 128 KB.
- Lower-case or colon-less fingerprints: assetlinks.json uses upper-case `AB:CD:...`; `web init` writes that form.
- The local keystore fingerprint usually differs from the Play app signing one: links that work in debug builds can
fail in the Play build.
- iOS caches the AASA: after a fix, reinstall the app or wait for the CDN (developer mode skips it while testing).

View file

@ -3,6 +3,12 @@
"ASC_KEY_ID": "YOUR_KEY_ID", "ASC_KEY_ID": "YOUR_KEY_ID",
"ASC_ISSUER_ID": "00000000-0000-0000-0000-000000000000", "ASC_ISSUER_ID": "00000000-0000-0000-0000-000000000000",
"ASC_P8": "/absolute/path/to/AuthKey_<KEY_ID>.p8", "ASC_P8": "/absolute/path/to/AuthKey_<KEY_ID>.p8",
"APPLE_ADS_CLIENT_ID": "SEARCHADS.00000000-0000-0000-0000-000000000000",
"APPLE_ADS_TEAM_ID": "SEARCHADS.00000000-0000-0000-0000-000000000000",
"APPLE_ADS_KEY_ID": "00000000-0000-0000-0000-000000000000",
"APPLE_ADS_PRIVATE_KEY": "/absolute/path/to/apple-ads-private-key.pem",
"APPLE_ADS_ACCOUNT_ID": "",
"REVENUECAT_SECRET_KEY": "sk_your_revenuecat_v2_secret_key",
"ANDROID_KEYSTORE": "/absolute/path/to/upload.p12", "ANDROID_KEYSTORE": "/absolute/path/to/upload.p12",
"ANDROID_KEYSTORE_PASSWORD": "", "ANDROID_KEYSTORE_PASSWORD": "",
"ANDROID_KEY_ALIAS": "upload", "ANDROID_KEY_ALIAS": "upload",

View file

@ -0,0 +1 @@
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>App Store</title><path d="M8.8086 14.9194l6.1107-11.0368c.0837-.1513.1682-.302.2437-.4584.0685-.142.1267-.2854.1646-.4403.0803-.3259.0588-.6656-.066-.9767-.1238-.3095-.3417-.5678-.6201-.7355a1.4175 1.4175 0 0 0-.921-.1924c-.3207.043-.6135.1935-.8443.4288-.1094.1118-.1996.2361-.2832.369-.092.1463-.175.2979-.259.4492l-.3864.6979-.3865-.6979c-.0837-.1515-.1667-.303-.2587-.4492-.0837-.1329-.1739-.2572-.2835-.369-.2305-.2353-.5233-.3857-.844-.429a1.4181 1.4181 0 0 0-.921.1926c-.2784.1677-.4964.426-.6203.7355-.1246.311-.1461.6508-.066.9767.038.155.0962.2984.1648.4403.0753.1564.1598.307.2437.4584l1.248 2.2543-4.8625 8.7825H2.0295c-.1676 0-.3351-.0007-.5026.0092-.1522.009-.3004.0284-.448.0714-.3108.0906-.5822.2798-.7783.548-.195.2665-.3006.5929-.3006.9279 0 .3352.1057.6612.3006.9277.196.2683.4675.4575.7782.548.1477.043.296.0623.4481.0715.1675.01.335.009.5026.009h13.0974c.0171-.0357.059-.1294.1-.2697.415-1.4151-.6156-2.843-2.0347-2.843zM3.113 18.5418l-.7922 1.5008c-.0818.1553-.1644.31-.2384.4705-.067.1458-.124.293-.1611.452-.0785.3346-.0576.6834.0645 1.0029.1212.3175.3346.583.607.7549.2727.172.5891.2416.9013.1975.3139-.044.6005-.1986.8263-.4402.1072-.1148.1954-.2424.2772-.3787.0902-.1503.1714-.3059.2535-.4612L6 19.4636c-.0896-.149-.9473-1.4704-2.887-.9218m20.5861-3.0056a1.4707 1.4707 0 0 0-.779-.5407c-.1476-.0425-.2961-.0616-.4483-.0705-.1678-.0099-.3352-.0091-.503-.0091H18.648l-4.3891-7.817c-.6655.7005-.9632 1.485-1.0773 2.1976-.1655 1.0333.0367 2.0934.546 3.0004l5.2741 9.3933c.084.1494.167.299.2591.4435.0837.131.1739.2537.2836.364.231.2323.5238.3809.8449.4232.3192.0424.643-.0244.9217-.1899.2784-.1653.4968-.4204.621-.7257.1246-.3072.146-.6425.0658-.9641-.0381-.1529-.0962-.2945-.165-.4346-.0753-.1543-.1598-.303-.2438-.4524l-1.216-2.1662h1.596c.1677 0 .3351.0009.5029-.009.1522-.009.3007-.028.4483-.0705a1.4707 1.4707 0 0 0 .779-.5407A1.5386 1.5386 0 0 0 24 16.452a1.539 1.539 0 0 0-.3009-.9158Z"/></svg>

After

Width:  |  Height:  |  Size: 2 KiB

View file

@ -0,0 +1 @@
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Google Play</title><path d="M22.018 13.298l-3.919 2.218-3.515-3.493 3.543-3.521 3.891 2.202a1.49 1.49 0 0 1 0 2.594zM1.337.924a1.486 1.486 0 0 0-.112.568v21.017c0 .217.045.419.124.6l11.155-11.087L1.337.924zm12.207 10.065l3.258-3.238L3.45.195a1.466 1.466 0 0 0-.946-.179l11.04 10.973zm0 2.067l-11 10.933c.298.036.612-.016.906-.183l13.324-7.54-3.23-3.21z"/></svg>

After

Width:  |  Height:  |  Size: 439 B

View file

@ -0,0 +1,50 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{APP_NAME}}</title>
<!--{{SMART_BANNER}}-->
<!--
Minimal landing page written by `storebound web init --landing` from templates/web/landing.html. Deploy the whole
output folder to the domain root: index.html, appstore.svg, googleplay.svg and .well-known/. No external requests.
The store marks are the simple-icons files (CC0 data), shown as a mask in the text colour; they only name the store.
-->
<style>
:root { color-scheme: light dark; --fg: #1b1c20; --bg: #ffffff; --muted: #5d6170; --line: #d5d8e0; --card: #f4f5f8; --accent: #1d4ed8; }
@media (prefers-color-scheme: dark) { :root { --fg: #eceef3; --bg: #15161a; --muted: #a3a8b6; --line: #343744; --card: #1f2127; --accent: #8fb0ff; } }
* { box-sizing: border-box; }
body { margin: 0; min-height: 100vh; display: flex; flex-direction: column; background: var(--bg); color: var(--fg); font: 16px/1.6 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
main { flex: 1; width: 100%; max-width: 640px; margin: 0 auto; padding: 64px 16px 32px; text-align: center; }
h1 { font-size: clamp(2rem, 7vw, 3rem); line-height: 1.15; margin: 0 0 32px; overflow-wrap: anywhere; }
.stores { display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; margin: 0; padding: 0; list-style: none; }
.store { display: inline-flex; align-items: center; gap: 10px; min-height: 48px; padding: 10px 18px; border: 1px solid var(--line); border-radius: 12px; background: var(--card); color: var(--fg); font-weight: 600; text-decoration: none; }
.store:hover { border-color: var(--fg); }
.store:focus-visible, footer a:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
.mark { display: inline-block; flex: none; width: 22px; height: 22px; background-color: currentColor; -webkit-mask: none center / contain no-repeat; mask: none center / contain no-repeat; }
.mark-appstore { -webkit-mask-image: url(appstore.svg); mask-image: url(appstore.svg); }
.mark-googleplay { -webkit-mask-image: url(googleplay.svg); mask-image: url(googleplay.svg); }
footer { width: 100%; max-width: 640px; margin: 0 auto; padding: 24px 16px 32px; border-top: 1px solid var(--line); color: var(--muted); font-size: .875rem; text-align: center; }
footer nav { display: flex; flex-wrap: wrap; gap: 8px 20px; justify-content: center; margin-bottom: 12px; }
footer a { color: var(--accent); }
footer p { margin: 0; }
</style>
</head>
<body>
<main>
<h1>{{APP_NAME}}</h1>
<ul class="stores" aria-label="Get the app">
<!--apple--><li><a class="store" href="{{APP_STORE_URL}}"><span class="mark mark-appstore" aria-hidden="true"></span>App Store</a></li><!--/apple-->
<!--play--><li><a class="store" href="{{PLAY_URL}}"><span class="mark mark-googleplay" aria-hidden="true"></span>Google Play</a></li><!--/play-->
</ul>
</main>
<footer>
<nav aria-label="Legal and support">
<a href="{{PRIVACY_URL}}">Privacy Policy</a>
<!--terms--><a href="{{TERMS_URL}}">Terms of Use</a><!--/terms-->
<a href="{{SUPPORT_URL}}">Support</a>
</nav>
<p>App Store is a trademark of Apple Inc.; Google Play is a trademark of Google LLC.</p>
</footer>
</body>
</html>

347
tests/adhoc.test.ts Normal file
View file

@ -0,0 +1,347 @@
// Ad-hoc distribution (apple adhoc) and Google Play internal app sharing (play share). No network: fetch is mocked,
// xcodebuild is never run. Response shapes are written from the App Store Connect API and androidpublisher v3 docs.
import { afterEach, describe, expect, test } from 'bun:test';
import { generateKeyPairSync } from 'node:crypto';
import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { run as adhocRun } from '../cli/apple/adhoc';
import {
deviceFromApi, exportArgv, exportOptionsPlist, maskUdid, MODERN_METHOD, parseDevicesCsv, parsePlatform, planRegister, profileCreateReq,
profileCurrent, type RegisteredDevice, scrubUdids, shellLine, slotUsage, usableCertificates, validUdid,
} from '../cli/lib/adhoc';
import { parseArgs } from '../cli/lib/args';
import type { Loaded, ShipConfig } from '../cli/lib/config';
import { parseShareArtifact, SHARE_HEADERS, SHARE_LIMIT, shareProblems, shareUrl } from '../cli/lib/play-share';
import { run as shareRun } from '../cli/play/share';
const PKG = 'com.example.game';
const NEW = '00008101-000A1B2C3D4E5F60';
const OLD = 'a'.repeat(39) + 'b';
const OTHER = '00008030-0011223344556677';
const GONE = '00008110-00AABBCCDDEEFF00';
// ----- fetch / env / console doubles -----
const realFetch = globalThis.fetch;
const savedEnv = { ...process.env };
const tty = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY');
afterEach(() => {
globalThis.fetch = realFetch;
for (const k of ['ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8', 'PLAY_SERVICE_ACCOUNT', 'STOREBOUND_SERVE']) { if (savedEnv[k] === undefined) delete process.env[k]; else process.env[k] = savedEnv[k]; }
if (tty) Object.defineProperty(process.stdin, 'isTTY', tty); else delete (process.stdin as { isTTY?: boolean }).isTTY;
});
const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status, headers: { 'content-type': 'application/json' } });
interface Call { method: string; url: string; body?: unknown; headers: Record<string, string> }
function fake(route: (c: Call) => Response): Call[] {
const calls: Call[] = [];
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
const url = String(input);
if (url === 'https://oauth2.googleapis.com/token') return json({ access_token: 'tok', expires_in: 3600 });
const c: Call = { method: (init?.method ?? 'GET').toUpperCase(), url, body: init?.body, headers: { ...(init?.headers as Record<string, string>) } };
calls.push(c);
return route(c);
}) as typeof fetch;
return calls;
}
function ascKey(): void {
const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
process.env.ASC_KEY_ID = 'test-key';
process.env.ASC_ISSUER_ID = '00000000-0000-0000-0000-000000000000';
process.env.ASC_P8 = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
}
function playKey(): void {
const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
process.env.PLAY_SERVICE_ACCOUNT = JSON.stringify({ client_email: 'sb@example.com', private_key: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), token_uri: 'https://oauth2.googleapis.com/token' });
}
function noTty(): void { Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }); delete process.env.STOREBOUND_SERVE; }
async function captured(fn: () => Promise<void>): Promise<string> {
const lines: string[] = [];
const o = { log: console.log, warn: console.warn, error: console.error };
console.log = console.warn = console.error = (...a: unknown[]) => { lines.push(a.map(String).join(' ')); };
try { await fn(); } finally { Object.assign(console, o); }
return lines.join('\n');
}
function project(extra: Partial<ShipConfig> = {}, files: Record<string, string> = {}): Loaded {
const root = mkdtempSync(join(tmpdir(), 'sb-adhoc-'));
for (const [p, t] of Object.entries(files)) { mkdirSync(join(root, p, '..'), { recursive: true }); writeFileSync(join(root, p), t); }
const config = { app: { name: 'Example Game' }, languages: [{ id: 'en', apple: 'en-US', play: 'en-US' }],
apple: { bundleId: PKG, teamId: 'ABCDEFGHIJ' }, play: { packageName: PKG }, ...extra } as unknown as ShipConfig;
return { config, root, path: join(root, 'storebound.config.ts'), resolve: p => join(root, p) };
}
// One page of GET /v1/devices (DevicesResponse), as documented: Device.Attributes.
const DEVICE = (id: string, udid: string, deviceClass: string, status = 'ENABLED', platform = 'IOS') =>
({ type: 'devices', id, attributes: { name: `Test ${deviceClass.toLowerCase()} ${id}`, platform, udid, deviceClass, status, model: 'iPhone 15', addedDate: '2026-01-02T00:00:00.000+0000' } });
const DEVICES = { data: [DEVICE('D1', OTHER, 'IPHONE'), DEVICE('D2', GONE, 'IPAD', 'DISABLED'), DEVICE('D3', 'c'.repeat(40), 'APPLE_TV')], links: { self: 'https://api.appstoreconnect.apple.com/v1/devices' } };
const CSV = `name,udid,platform\nNew phone,${NEW},IOS\nOld pad,${OLD},ios\nKnown phone,${OTHER.toLowerCase()},IOS\nDisabled pad,${GONE},IOS\n`;
const ALL_UDIDS = [NEW, OLD, OTHER, GONE, 'c'.repeat(40)];
const leaks = (s: string) => ALL_UDIDS.filter(u => s.toLowerCase().includes(u.toLowerCase()));
describe('UDIDs: validation and masking', () => {
test('legacy 40-hex and the 8-16 form; Mac hardware UUIDs only for MAC_OS', () => {
expect(validUdid(NEW)).toBe(true);
expect(validUdid(OLD)).toBe(true);
expect(validUdid(' ' + NEW + ' ')).toBe(true);
expect(validUdid('00008101-000A1B2C3D4E5F6')).toBe(false);
expect(validUdid('g'.repeat(40))).toBe(false);
expect(validUdid('0000-1111')).toBe(false);
const mac = '00000000-0000-0000-0000-000000000000';
expect(validUdid(mac, 'IOS')).toBe(false);
expect(validUdid(mac, 'MAC_OS')).toBe(true);
});
test('mask keeps 4 + 4; scrub masks UDID-shaped strings in any text', () => {
expect(maskUdid(NEW)).toBe('0000…5F60');
expect(maskUdid('short')).toBe('…');
const msg = `POST /v1/devices -> 409 {"detail":"A device with number '${NEW}' already exists; also ${OLD}"}`;
const s = scrubUdids(msg, [NEW]);
expect(leaks(s)).toEqual([]);
expect(s).toContain('0000…5F60');
expect(s).toContain('aaaa…aaab');
});
test('platform names', () => {
expect([parsePlatform(undefined), parsePlatform('ios'), parsePlatform('macOS'), parsePlatform('MAC_OS'), parsePlatform('tvos')]).toEqual(['IOS', 'IOS', 'MAC_OS', 'MAC_OS', null]);
});
test('CSV: rows parsed; errors name the row and never hold a full UDID', () => {
expect(parseDevicesCsv(CSV).devices.map(d => d.platform)).toEqual(['IOS', 'IOS', 'IOS', 'IOS']);
const bad = parseDevicesCsv(`name,udid,platform\nA,${NEW}x,IOS\n,${OLD},IOS\nB,${NEW},TVOS\nC,${OTHER},IOS\nD,${OTHER},IOS\n`);
expect(bad.errors).toEqual([
'row 2: "0000…F60x" is not a device UDID (40 hex digits, or 8 hex - 16 hex)',
'row 3: name is empty',
'row 4: platform must be IOS or MAC_OS',
'row 6: 0000…6677 is listed twice',
]);
expect(leaks(bad.errors.join('\n'))).toEqual([]);
});
});
describe('register plan', () => {
const reg = DEVICES.data.map(deviceFromApi);
test('new vs registered (case-insensitive) vs disabled', () => {
const p = planRegister(parseDevicesCsv(CSV).devices, reg);
expect(p.add.map(d => d.name)).toEqual(['New phone', 'Old pad']);
expect(p.present.map(d => d.name)).toEqual(['Known phone']);
expect(p.disabled.map(d => d.name)).toEqual(['Disabled pad']);
});
test('slots per device class count disabled devices too', () => {
expect(slotUsage(reg)).toEqual([
{ deviceClass: 'APPLE_TV', registered: 1, limit: 100 }, { deviceClass: 'IPAD', registered: 1, limit: 100 }, { deviceClass: 'IPHONE', registered: 1, limit: 100 }]);
});
});
describe('ExportOptions.plist', () => {
test('automatic signing, exact XML', () => {
expect(exportOptionsPlist({ method: 'release-testing', teamId: 'ABCDEFGHIJ', bundleId: PKG })).toBe(`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
\t<key>destination</key>
\t<string>export</string>
\t<key>method</key>
\t<string>release-testing</string>
\t<key>signingStyle</key>
\t<string>automatic</string>
\t<key>teamID</key>
\t<string>ABCDEFGHIJ</string>
\t<key>thinning</key>
\t<string>&lt;none&gt;</string>
</dict>
</plist>
`);
});
test('manual signing with a profile; XML escaped', () => {
const x = exportOptionsPlist({ method: 'ad-hoc', teamId: 'ABCDEFGHIJ', bundleId: 'com.example.a&b', profile: `Ad <Hoc> "Q" & 'x'` });
expect(x).toContain('\t<key>provisioningProfiles</key>\n\t<dict>\n\t\t<key>com.example.a&amp;b</key>\n\t\t<string>Ad &lt;Hoc&gt; &quot;Q&quot; &amp; &apos;x&apos;</string>\n\t</dict>\n');
expect(x).toContain('<key>signingStyle</key>\n\t<string>manual</string>');
expect(x).toContain('<string>ad-hoc</string>');
expect(() => exportOptionsPlist({ method: 'ad-hoc', teamId: 'ABCDEFGHIJ', profile: 'P' })).toThrow('apple.bundleId');
});
test('deprecated method names map to the current ones', () => {
expect(MODERN_METHOD).toEqual({ 'ad-hoc': 'release-testing', development: 'debugging', 'app-store': 'app-store-connect' });
});
test('xcodebuild argv and the printed line', () => {
const argv = exportArgv('build/My App.xcarchive', '/p/build/ExportOptions.plist', '/p/build/adhoc');
expect(argv).toEqual(['xcodebuild', '-exportArchive', '-archivePath', 'build/My App.xcarchive', '-exportOptionsPlist', '/p/build/ExportOptions.plist', '-exportPath', '/p/build/adhoc', '-allowProvisioningUpdates']);
expect(shellLine(argv)).toBe(`xcodebuild -exportArchive -archivePath 'build/My App.xcarchive' -exportOptionsPlist /p/build/ExportOptions.plist -exportPath /p/build/adhoc -allowProvisioningUpdates`);
});
});
describe('profile pieces', () => {
test('request shape, certificates, freshness', () => {
expect(profileCreateReq('P', 'B1', ['C1'], ['D1', 'D3'])).toEqual({ data: { type: 'profiles', attributes: { name: 'P', profileType: 'IOS_APP_ADHOC' }, relationships: {
bundleId: { data: { type: 'bundleIds', id: 'B1' } }, certificates: { data: [{ type: 'certificates', id: 'C1' }] },
devices: { data: [{ type: 'devices', id: 'D1' }, { type: 'devices', id: 'D3' }] } } } });
const certs = [
{ id: 'C1', attributes: { certificateType: 'DISTRIBUTION', expirationDate: '2027-05-01T00:00:00.000+0000' } },
{ id: 'C2', attributes: { certificateType: 'IOS_DISTRIBUTION', expirationDate: '2025-01-01T00:00:00.000+0000' } },
{ id: 'C3', attributes: { certificateType: 'DEVELOPMENT', expirationDate: '2027-05-01T00:00:00.000+0000' } }];
expect(usableCertificates(certs, new Date('2026-10-11'))).toEqual(['C1']);
expect(profileCurrent('ACTIVE', ['D1', 'D3'], ['D1'])).toEqual({ current: true, missing: 0 });
expect(profileCurrent('ACTIVE', ['D1'], ['D1', 'D4'])).toEqual({ current: false, missing: 1 });
expect(profileCurrent('INVALID', ['D1'], ['D1']).current).toBe(false);
});
});
describe('apple adhoc runs (mocked App Store Connect)', () => {
const route = (c: Call) => {
if (c.method === 'GET' && c.url.startsWith('https://api.appstoreconnect.apple.com/v1/devices')) return json(DEVICES);
if (c.method === 'POST' && c.url.endsWith('/v1/devices')) {
const b = JSON.parse(String(c.body));
if (b.data.attributes.udid === OLD) return json({ errors: [{ status: '409', code: 'ENTITY_ERROR', detail: `A device with number '${OLD}' already exists on this team.` }] }, 409);
return json({ data: { type: 'devices', id: 'D9', attributes: { ...b.data.attributes, status: 'ENABLED' } } }, 201);
}
return json({ errors: [{ status: '400' }] }, 400);
};
const files = { '.storebound/devices.csv': CSV };
test('devices --json: every UDID masked', async () => {
ascKey();
const calls = fake(route);
const out = await captured(() => adhocRun({ loaded: project(), args: parseArgs(['devices', '--platform', 'IOS', '--json']) }));
expect(calls.map(c => c.url)).toEqual(['https://api.appstoreconnect.apple.com/v1/devices?limit=200&filter[platform]=IOS']);
const j = JSON.parse(out);
expect(j.devices[0]).toEqual({ id: 'D1', name: 'Test iphone D1', platform: 'IOS', deviceClass: 'IPHONE', model: 'iPhone 15', status: 'ENABLED', udid: '0000…6677' });
expect(j.usage.length).toBe(3);
expect(leaks(out)).toEqual([]);
});
test('register --dry: reads, lists masked, sends no POST', async () => {
ascKey();
const calls = fake(route);
const out = await captured(() => adhocRun({ loaded: project({}, files), args: parseArgs(['register', '--dry']) }));
expect(calls.every(c => c.method === 'GET')).toBe(true);
expect(out).toContain('4 in the list: 2 new, 1 already registered, 1 disabled');
expect(out).toContain('IPHONE: 1 registered of 100 per membership year');
expect(out).toContain('0000…5F60');
expect(out).toContain('dry run: would register 2 device(s)');
expect(leaks(out)).toEqual([]);
});
test('register without a terminal and without --yes: no POST', async () => {
ascKey(); noTty();
const calls = fake(route);
const out = await captured(() => adhocRun({ loaded: project({}, files), args: parseArgs(['register']) }));
expect(calls.some(c => c.method !== 'GET')).toBe(false);
expect(out).toContain('re-run with --yes');
expect(leaks(out)).toEqual([]);
});
test('register --yes: one POST per new device; an API error echoing the UDID is masked', async () => {
ascKey();
const calls = fake(route);
let err = '';
const out = await captured(async () => {
try { await adhocRun({ loaded: project({}, files), args: parseArgs(['register', '--yes']) }); } catch (e) { err = (e as Error).message; }
});
const posts = calls.filter(c => c.method === 'POST');
expect(posts.map(c => JSON.parse(String(c.body)))).toEqual([
{ data: { type: 'devices', attributes: { name: 'New phone', udid: NEW, platform: 'IOS' } } },
{ data: { type: 'devices', attributes: { name: 'Old pad', udid: OLD, platform: 'IOS' } } }]);
expect(out).toContain('registered New phone (0000…5F60)');
expect(out).toContain('Old pad (aaaa…aaab) not registered');
expect(err).toBe('1 of 2 device(s) not registered');
expect(leaks(out + err)).toEqual([]);
});
test('register --udid with a bad UDID fails before any call, masked', async () => {
ascKey();
const calls = fake(route);
await expect(adhocRun({ loaded: project(), args: parseArgs(['register', '--name', 'X', '--udid', NEW + 'zz']) })).rejects.toThrow('--udid 0000…60zz: not a device UDID');
expect(calls.length).toBe(0);
});
test('profile --dry plans, profile --yes creates the IOS_APP_ADHOC profile with enabled iOS devices only', async () => {
ascKey();
const prof = (c: Call) => {
if (c.url.includes('/v1/bundleIds?')) return json({ data: [{ type: 'bundleIds', id: 'B1', attributes: { identifier: PKG, platform: 'IOS', name: 'Example' } }, { type: 'bundleIds', id: 'B2', attributes: { identifier: PKG + '.widget', platform: 'IOS' } }] });
if (c.url.includes('/v1/certificates?')) return json({ data: [{ type: 'certificates', id: 'C1', attributes: { certificateType: 'DISTRIBUTION', expirationDate: '2099-01-01T00:00:00.000+0000' } }] });
if (c.url.includes('/v1/bundleIds/B1/profiles')) return json({ data: [] });
if (c.method === 'POST' && c.url.endsWith('/v1/profiles')) return json({ data: { type: 'profiles', id: 'P1', attributes: { name: 'x', uuid: '00000000-0000-0000-0000-000000000000', profileContent: Buffer.from('profile').toString('base64') } } }, 201);
return route(c);
};
let calls = fake(prof);
const loaded = project({ apple: { bundleId: PKG, teamId: 'ABCDEFGHIJ', adhoc: { profile: 'Example AdHoc' } } } as Partial<ShipConfig>);
const dryOut = await captured(() => adhocRun({ loaded, args: parseArgs(['profile', '--dry']) }));
expect(calls.every(c => c.method === 'GET')).toBe(true);
expect(calls.map(c => c.url)).toContain('https://api.appstoreconnect.apple.com/v1/certificates?filter[certificateType]=DISTRIBUTION,IOS_DISTRIBUTION&limit=200');
expect(dryOut).toContain('plan: create IOS_APP_ADHOC "Example AdHoc" for com.example.game: 1 devices (1 IPHONE), 1 distribution certificate(s)');
calls = fake(prof);
await captured(() => adhocRun({ loaded, args: parseArgs(['profile', '--yes']) }));
const post = calls.find(c => c.method === 'POST')!;
expect(JSON.parse(String(post.body))).toEqual(profileCreateReq('Example AdHoc', 'B1', ['C1'], ['D1']));
expect(existsSync(join(loaded.root, 'build/adhoc/Example_AdHoc.mobileprovision'))).toBe(true);
});
test('options --dry prints the plist and writes nothing; options writes it', async () => {
const loaded = project();
const out = await captured(() => adhocRun({ loaded, args: parseArgs(['options', '--dry', '--method', 'ad-hoc']) }));
expect(out).toContain('<string>ad-hoc</string>');
expect(existsSync(join(loaded.root, 'build/ExportOptions.plist'))).toBe(false);
await captured(() => adhocRun({ loaded, args: parseArgs(['options']) }));
expect(existsSync(join(loaded.root, 'build/ExportOptions.plist'))).toBe(true);
await expect(adhocRun({ loaded, args: parseArgs(['options', '--method', 'enterprise']) })).rejects.toThrow('--method');
});
test('export --dry prints the exact command; nothing written or run', async () => {
const loaded = project({}, { 'build/App.xcarchive/Info.plist': '<plist/>' });
const archive = join(loaded.root, 'build/App.xcarchive');
const out = await captured(() => adhocRun({ loaded, args: parseArgs(['export', '--archive', archive, '--dry']) }));
expect(out).toContain(shellLine(exportArgv(archive, join(loaded.root, 'build/ExportOptions.plist'), join(loaded.root, 'build/adhoc'))));
expect(out).toContain('would write build/ExportOptions.plist');
expect(existsSync(join(loaded.root, 'build/ExportOptions.plist'))).toBe(false);
expect(existsSync(join(loaded.root, 'build/adhoc'))).toBe(false);
});
});
describe('play internal app sharing', () => {
const ART = { downloadUrl: 'https://play.google.com/apps/test/com.example.game/placeholder', certificateFingerprint: 'AB:CD:EF', sha256: '' };
test('URL is not under applications/{packageName}; limits; response parsing', () => {
expect(shareUrl(PKG, 'bundle')).toBe('https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/internalappsharing/com.example.game/artifacts/bundle?uploadType=media');
expect(shareUrl(PKG, 'apk')).toEndWith('/internalappsharing/com.example.game/artifacts/apk?uploadType=media');
expect(SHARE_HEADERS).toEqual({ 'Content-Type': 'application/octet-stream' });
expect(SHARE_LIMIT).toEqual({ bundle: 10 * 1024 ** 3, apk: 1024 ** 3 });
expect(shareProblems('bundle', 'a.apk', 10)).toEqual(['--aab a.apk: expected an .aab file']);
expect(shareProblems('apk', 'a.apk', SHARE_LIMIT.apk + 1)[0]).toContain('above the 1024.0 MB internal app sharing limit');
expect(parseShareArtifact({ ...ART, sha256: 'ABC' })).toEqual({ ...ART, sha256: 'abc' });
expect(() => parseShareArtifact({})).toThrow('no downloadUrl');
});
test('share --dry sends nothing (not even a token request)', async () => {
let n = 0;
globalThis.fetch = (async () => { n++; return json({}); }) as unknown as typeof fetch;
const loaded = project({}, { 'app.aab': 'bundle bytes' });
const out = await captured(() => shareRun({ loaded, args: parseArgs(['--aab', join(loaded.root, 'app.aab'), '--dry', '--json']) }));
expect(n).toBe(0);
expect(JSON.parse(out)).toMatchObject({ dry: true, packageName: PKG, kind: 'bundle', bytes: 12, sha256: expect.stringMatching(/^[0-9a-f]{64}$/) });
});
test('share without --yes and no terminal: nothing sent', async () => {
noTty();
let n = 0;
globalThis.fetch = (async () => { n++; return json({}); }) as unknown as typeof fetch;
const loaded = project({}, { 'app.apk': 'apk bytes' });
await captured(() => shareRun({ loaded, args: parseArgs(['--apk', join(loaded.root, 'app.apk')]) }));
expect(n).toBe(0);
});
test('share --yes --json: one POST of the raw bytes, octet-stream, the link printed', async () => {
playKey();
const calls = fake(() => json(ART));
const loaded = project({}, { 'app.aab': 'bundle bytes' });
const out = await captured(() => shareRun({ loaded, args: parseArgs(['--aab', join(loaded.root, 'app.aab'), '--yes', '--json']) }));
expect(calls.length).toBe(1);
expect(calls[0]!.method).toBe('POST');
expect(calls[0]!.url).toBe(shareUrl(PKG, 'bundle'));
expect(calls[0]!.headers['Content-Type']).toBe('application/octet-stream');
expect(calls[0]!.headers.Authorization).toBe('Bearer tok');
expect(new TextDecoder().decode(calls[0]!.body as Uint8Array)).toBe('bundle bytes');
expect(JSON.parse(out.slice(out.indexOf('{')))).toEqual(ART);
});
});

277
tests/apple-ads.test.ts Normal file
View file

@ -0,0 +1,277 @@
// Apple Ads: client secret, token request, headers, report bodies and rows, CSV, and the write guards. No network:
// fetch is replaced per test and restored after. Response shapes follow Apple's documented examples (placeholder ids).
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { generateKeyPairSync, verify } from 'node:crypto';
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { adsClient, retryWait } from '../cli/ads/client';
import { run } from '../cli/ads/apple';
import {
aclRows, adsHeaders, campaignRow, changeLine, clientSecret, CSV_HEAD, flattenRows, nextOffset, parseAmount, reportBody, reportCsv, reportTable, reportWindow, tokenForm, totals,
} from '../cli/lib/apple-ads';
import { parseArgs } from '../cli/lib/args';
import { parseCsv } from '../cli/lib/csv';
import type { Ctx } from '../cli/lib/ctx';
const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
const PEM = privateKey.export({ type: 'sec1', format: 'pem' }).toString();
const CREDS = { clientId: 'SEARCHADS.client-placeholder', teamId: 'SEARCHADS.team-placeholder', keyId: 'key-placeholder' };
const dec = (s: string) => JSON.parse(Buffer.from(s, 'base64url').toString());
const ENV = { APPLE_ADS_CLIENT_ID: CREDS.clientId, APPLE_ADS_TEAM_ID: CREDS.teamId, APPLE_ADS_KEY_ID: CREDS.keyId, APPLE_ADS_PRIVATE_KEY: PEM, APPLE_ADS_ACCOUNT_ID: '123456789' };
let saved: Record<string, string | undefined> = {};
let realFetch: typeof fetch;
let root = '';
let tty: PropertyDescriptor | undefined;
beforeEach(() => {
realFetch = globalThis.fetch;
saved = Object.fromEntries([...Object.keys(ENV), 'STOREBOUND_SERVE', 'STOREBOUND_MACHINE'].map(k => [k, process.env[k]]));
Object.assign(process.env, ENV);
delete process.env.STOREBOUND_SERVE; delete process.env.STOREBOUND_MACHINE;
root = mkdtempSync(join(tmpdir(), 'sb-ads-'));
tty = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY');
Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true });
});
afterEach(() => {
globalThis.fetch = realFetch;
for (const [k, v] of Object.entries(saved)) { if (v === undefined) delete process.env[k]; else process.env[k] = v; }
rmSync(root, { recursive: true, force: true });
if (tty) Object.defineProperty(process.stdin, 'isTTY', tty); else delete (process.stdin as { isTTY?: boolean }).isTTY;
});
interface Call { url: string; method: string; headers: Record<string, string>; body: string }
function mockFetch(handler: (c: Call) => { status?: number; json?: unknown; headers?: Record<string, string> }): Call[] {
const calls: Call[] = [];
globalThis.fetch = (async (url: string | URL, init?: RequestInit) => {
const c: Call = { url: String(url), method: init?.method ?? 'GET', headers: (init?.headers ?? {}) as Record<string, string>, body: String(init?.body ?? '') };
calls.push(c);
const r = handler(c);
return new Response(r.json === undefined ? '' : JSON.stringify(r.json), { status: r.status ?? 200, headers: r.headers });
}) as typeof fetch;
return calls;
}
const TOKEN = { access_token: 'token-placeholder', token_type: 'Bearer', expires_in: 3600, scope: 'searchadsorg' };
const CAMPAIGN = {
id: 444555666, adAccountId: 123456789, name: 'Example - US', promotedObjectType: 'APPSTORE_APP', promotedObjectId: '987654321', status: 'ENABLED',
systemStatus: 'RUNNING', displayStatus: 'RUNNING', dailyBudget: { value: { amount: '100.00', currency: 'USD' } },
targeting: { countryOrRegion: { include: ['US', 'CA'] } }, bidStrategy: { bidStrategyType: 'MANUAL_CPT', bidStrategyGoal: 'TAP', bid: { amount: '1.50', currency: 'USD' } }, deleted: false,
};
const KEYWORD = { id: 888999000, adAccountId: 123456789, campaignId: 444555666, adGroupId: 555666777, text: 'photo editor', matchType: 'EXACT', bid: { amount: '2.50', currency: 'USD' }, status: 'ENABLED', deleted: false };
const CAMPAIGN_REPORT = {
result: {
rows: [
{ metadata: { id: 444555666, name: 'Example - US', promotedObjectId: '987654321' },
totalMetrics: { localSpend: { amount: '500.00', currency: 'USD' }, impressions: 50000, taps: 2500, ttr: 0.05, tapInstalls: 600, viewInstalls: 120, totalInstalls: 720, totalNewDownloads: 650, totalRedownloads: 70 } },
{ metadata: { id: 444555667, name: 'Example - Brand' },
totalMetrics: { localSpend: { amount: '12.34', currency: 'USD' }, impressions: 900, taps: 10, ttr: 0.0111, tapInstalls: 0, viewInstalls: 0, totalInstalls: 0 } },
],
summary: { grandTotal: { localSpend: { amount: '512.34', currency: 'USD' } } },
},
pagination: { offset: 0, pageSize: 1000, totalCount: 2 },
};
function ctx(argv: string[], appId?: string): Ctx {
return { args: parseArgs(argv), loaded: { config: { apple: { bundleId: 'com.example.app', appId } } as never, root, path: join(root, 'storebound.config.ts'), resolve: p => join(root, p) } };
}
async function quiet<T>(f: () => Promise<T>): Promise<{ out: string; value: T }> {
const lines: string[] = [];
const log = console.log, warn = console.warn, err = console.error;
console.log = (...a: unknown[]) => { lines.push(a.join(' ')); };
console.warn = console.log; console.error = console.log;
try { return { value: await f(), out: lines.join('\n') }; } finally { console.log = log; console.warn = warn; console.error = err; }
}
describe('client secret (ES256 JWT)', () => {
test('header, claims and a valid P-256 signature', () => {
const now = 1_800_000_000;
const jwt = clientSecret(CREDS, PEM, now);
const [h, p, s] = jwt.split('.') as [string, string, string];
expect(dec(h)).toEqual({ alg: 'ES256', kid: CREDS.keyId });
expect(dec(p)).toEqual({ sub: CREDS.clientId, iss: CREDS.teamId, aud: 'https://appleid.apple.com', iat: now, exp: now + 86400 });
expect(Buffer.from(s, 'base64url').length).toBe(64);
expect(verify('sha256', Buffer.from(`${h}.${p}`), { key: publicKey, dsaEncoding: 'ieee-p1363' }, Buffer.from(s, 'base64url'))).toBe(true);
});
test('lifetime capped at 180 days', () => {
expect(() => clientSecret(CREDS, PEM, 0, 181 * 86400)).toThrow(/180 days/);
expect(dec(clientSecret(CREDS, PEM, 0, 180 * 86400).split('.')[1]!).exp).toBe(180 * 86400);
});
});
describe('requests', () => {
test('token form and headers', () => {
expect(Object.fromEntries(tokenForm('cid', 'sec'))).toEqual({ grant_type: 'client_credentials', client_id: 'cid', client_secret: 'sec', scope: 'searchadsorg' });
expect(adsHeaders('t', '42')).toMatchObject({ Authorization: 'Bearer t', 'X-AP-Context': 'adAccountId=42' });
expect(adsHeaders('t')['X-AP-Context']).toBeUndefined();
});
test('report body: campaignId filter, UTC window, grand total, no granularity', () => {
const b = reportBody({ start: '2026-10-01', end: '2026-10-07', campaignId: '444555666', adGroupId: '555666777' });
expect(b).toEqual({
pagination: { offset: 0, pageSize: 1000 }, sorting: [{ field: 'localSpend', order: 'DESC' }],
filters: [{ field: 'campaignId', operator: 'EQUALS', value: '444555666' }, { field: 'adGroupId', operator: 'EQUALS', value: '555666777' }],
timeRange: { start: '2026-10-01', end: '2026-10-07', timeZone: 'UTC' }, options: { includeRows: ['GRAND_TOTAL'] },
});
});
test('window: --days ends yesterday, --start/--end checked', () => {
expect(reportWindow({ days: 7 }, new Date('2026-10-11T12:00:00Z'))).toEqual({ start: '2026-10-04', end: '2026-10-10' });
expect(reportWindow({ start: '2026-09-01', end: '2026-09-30' })).toEqual({ start: '2026-09-01', end: '2026-09-30' });
expect(() => reportWindow({ start: '2026-09-30', end: '2026-09-01' })).toThrow(/after/);
expect(() => reportWindow({ start: '2026-09-01' })).toThrow(/both/);
});
test('amounts and change lines', () => {
expect(parseAmount('2.5', '--bid')).toBe('2.5');
for (const bad of ['05.00', '-1', '0', '1.234', 'abc', undefined]) expect(() => parseAmount(bad, '--bid')).toThrow();
expect(changeLine('1.50', '2.00', 'USD')).toBe('1.50 -> 2.00 USD (+33%)');
expect(changeLine(null, '2.00', 'USD')).toBe('(default) -> 2.00 USD');
});
test('retry wait: Retry-After first, else exponential to 16 s', () => {
expect(retryWait('7', 1)).toBe(7);
expect([1, 2, 3, 4, 5].map(a => retryWait(null, a))).toEqual([2, 4, 8, 16, 16]);
});
});
describe('rows', () => {
test('flatten, CPA null with 0 installs, totals', () => {
const rows = flattenRows('campaign', CAMPAIGN_REPORT);
expect(rows[0]).toMatchObject({ campaignId: '444555666', campaign: 'Example - US', currency: 'USD', spend: 500, installs: 720, tapInstalls: 600, viewInstalls: 120, newDownloads: 650 });
expect(rows[0]!.cpa).toBeCloseTo(500 / 720, 10);
expect(rows[0]!.avgCpt).toBeCloseTo(0.2, 10);
expect(rows[0]!.ttr).toBeCloseTo(0.05, 10);
expect(rows[0]!.conversionRate).toBeCloseTo(720 / 2500, 10);
expect(rows[1]!.cpa).toBeNull();
const t = totals(rows);
expect(t).toMatchObject({ currency: 'USD', spend: 512.34, impressions: 50900, taps: 2510, installs: 720 });
expect(reportTable(rows, t)).toContain('TOTAL');
expect(reportTable(rows, t)).toContain('n/a');
expect(nextOffset(CAMPAIGN_REPORT)).toBeNull();
expect(nextOffset({ pagination: { offset: 0, pageSize: 2, totalCount: 5 } })).toBe(2);
});
test('keyword rows carry ids, text and the campaign name', () => {
const res = { result: { rows: [{ metadata: { id: 888999000, text: 'photo editor', matchType: 'EXACT', campaignId: 444555666, adGroupId: 555666777, adGroup: { name: 'Exact' } },
totalMetrics: { localSpend: { amount: '75.00', currency: 'USD' }, impressions: 5000, taps: 250, tapInstalls: 60, totalInstalls: 72 } }] } };
const [r] = flattenRows('keyword', res, new Map([['444555666', 'Example - US']]));
expect(r).toMatchObject({ level: 'keyword', keywordId: '888999000', keyword: 'photo editor', adGroup: 'Exact', campaign: 'Example - US', installs: 72 });
});
test('CSV: header, one line per row, empty CPA cell with 0 installs', () => {
const csv = parseCsv(reportCsv(flattenRows('campaign', CAMPAIGN_REPORT)));
expect(csv[0]).toEqual(CSV_HEAD);
expect(csv.length).toBe(3);
const cpa = CSV_HEAD.indexOf('cpa');
expect(csv[1]![cpa]).toBe('0.69');
expect(csv[2]![cpa]).toBe('');
expect(csv[1]![CSV_HEAD.indexOf('spend')]).toBe('500.00');
});
test('acls and campaigns', () => {
const acl = aclRows({ result: { acls: [{ adAccount: { id: 123456789, name: 'Example', orgId: 1 }, roles: ['API Account Read Only'] }] } }, '123456789');
expect(acl).toEqual([{ accountId: '123456789', name: 'Example', orgId: '1', roles: ['API Account Read Only'], used: true }]);
expect(campaignRow(CAMPAIGN, '987654321')).toMatchObject({ id: '444555666', dailyBudget: '100.00', currency: 'USD', countries: ['US', 'CA'], adamId: '987654321', thisApp: true });
});
});
describe('client (mocked fetch)', () => {
test('token request then X-AP-Context; token cached in memory', async () => {
const calls = mockFetch(c => (c.url.includes('appleid.apple.com') ? { json: TOKEN } : { json: { result: CAMPAIGN } }));
const ads = adsClient(root);
await ads.get('/campaigns/444555666');
await ads.get('/campaigns/444555666');
expect(calls.length).toBe(3);
const tok = calls[0]!;
expect(tok.url).toBe('https://appleid.apple.com/auth/oauth2/token');
expect(tok.method).toBe('POST');
expect(tok.headers['Content-Type']).toBe('application/x-www-form-urlencoded');
const form = new URLSearchParams(tok.body);
expect([form.get('grant_type'), form.get('client_id'), form.get('scope')]).toEqual(['client_credentials', CREDS.clientId, 'searchadsorg']);
expect(dec(form.get('client_secret')!.split('.')[1]!)).toMatchObject({ sub: CREDS.clientId, iss: CREDS.teamId, aud: 'https://appleid.apple.com' });
expect(calls[1]!.url).toBe('https://api.ads.apple.com/v1/campaigns/444555666');
expect(calls[1]!.headers).toMatchObject({ Authorization: 'Bearer token-placeholder', 'X-AP-Context': 'adAccountId=123456789' });
});
test('429 retried after Retry-After; errors never carry the token', async () => {
let n = 0;
const waits: number[] = [];
mockFetch(c => (c.url.includes('appleid') ? { json: TOKEN } : ++n === 1 ? { status: 429, json: { error: { code: 'rate_limit_exceeded' } }, headers: { 'Retry-After': '3' } } : { status: 403, json: { error: { code: 'forbidden' } } }));
const ads = adsClient(root, { sleep: async ms => { waits.push(ms); } });
const e = await ads.get('/acls', false).catch(x => x as Error);
expect(waits).toEqual([3000]);
expect(String(e)).toContain('403');
expect(String(e)).not.toContain('token-placeholder');
});
test('a failed token request names the status, not the secret', async () => {
mockFetch(() => ({ status: 401, json: { error: 'invalid_client' } }));
const e = await adsClient(root).token().catch(x => x as Error);
expect(String(e)).toContain('401 invalid_client');
expect(String(e)).not.toMatch(/eyJ/);
});
test('missing credentials and template placeholders are reported by name', () => {
delete process.env.APPLE_ADS_KEY_ID;
process.env.APPLE_ADS_CLIENT_ID = 'SEARCHADS.00000000-0000-0000-0000-000000000000';
expect(() => adsClient(root)).toThrow(/APPLE_ADS_CLIENT_ID, APPLE_ADS_KEY_ID not set/);
});
});
describe('command (mocked fetch)', () => {
const api = (c: Call) => {
if (c.url.includes('appleid.apple.com')) return { json: TOKEN };
const path = c.url.replace('https://api.ads.apple.com/v1', '');
if (path === '/keywords/888999000' && c.method === 'GET') return { json: { result: KEYWORD } };
if (path === '/campaigns/444555666' && c.method === 'GET') return { json: { result: CAMPAIGN } };
if (path === '/campaigns/query') return { json: { result: [CAMPAIGN], pagination: { offset: 0, pageSize: 1000, totalCount: 1 } } };
if (path === '/reports/apps/campaigns/query') return { json: CAMPAIGN_REPORT };
if (c.method === 'PUT') return { json: { result: {} } };
return { status: 404, json: { error: { code: 'not_found' } } };
};
test('bid --dry reads, prints old -> new, sends no PUT', async () => {
const calls = mockFetch(api);
const { out } = await quiet(() => run(ctx(['bid', '--keyword', '888999000', '--bid', '3.75', '--dry'])));
expect(calls.some(c => c.method === 'PUT')).toBe(false);
expect(out).toContain('2.50 -> 3.75 USD (+50%)');
expect(out).toContain('dry run: would PUT /keywords/888999000 {"bid":{"amount":"3.75","currency":"USD"}}');
});
test('budget without a terminal and without --yes sends no PUT', async () => {
const calls = mockFetch(api);
const { out } = await quiet(() => run(ctx(['budget', '--campaign', '444555666', '--daily', '150.00'])));
expect(out).toContain('100.00 -> 150.00 USD (+50%)');
expect(out).toContain('not a terminal');
expect(calls.some(c => c.method === 'PUT')).toBe(false);
});
test('pause under storebound serve is refused even with --yes', async () => {
process.env.STOREBOUND_SERVE = '1';
const calls = mockFetch(api);
await quiet(() => run(ctx(['pause', '--campaign', '444555666', '--yes'])));
expect(calls.some(c => c.method === 'PUT')).toBe(false);
});
test('budget with --yes in a terminal-less run sends the documented body', async () => {
const calls = mockFetch(api);
await quiet(() => run(ctx(['budget', '--campaign', '444555666', '--daily', '150.00', '--yes'])));
const put = calls.find(c => c.method === 'PUT')!;
expect(put.url).toBe('https://api.ads.apple.com/v1/campaigns/444555666');
expect(JSON.parse(put.body)).toEqual({ dailyBudget: { value: { amount: '150.00', currency: 'USD' } } });
});
test('bid rejects a keyword from another ad group', async () => {
mockFetch(api);
await expect(quiet(() => run(ctx(['bid', '--keyword', '888999000', '--adgroup', '1', '--bid', '1.00', '--dry'])))).rejects.toThrow(/belongs to ad group/);
});
test('report --csv writes the rows; with --dry it writes nothing', async () => {
const calls = mockFetch(api);
await quiet(() => run(ctx(['report', '--days', '7', '--csv', 'dry.csv', '--dry'])));
expect(() => readFileSync(join(root, 'dry.csv'))).toThrow();
const { out } = await quiet(() => run(ctx(['report', '--start', '2026-10-01', '--end', '2026-10-07', '--csv', 'ads.csv'], '987654321')));
const csv = parseCsv(readFileSync(join(root, 'ads.csv'), 'utf8'));
expect(csv.length).toBe(3);
expect(out).toContain('TOTAL');
const rep = calls.filter(c => c.url.endsWith('/reports/apps/campaigns/query')).at(-1)!;
expect(rep.method).toBe('POST');
expect(JSON.parse(rep.body)).toMatchObject({ filters: [{ field: 'campaignId', operator: 'EQUALS', value: '444555666' }], timeRange: { start: '2026-10-01', end: '2026-10-07', timeZone: 'UTC' } });
expect(calls.some(c => c.method === 'PUT')).toBe(false);
});
test('report --json: stable shape', async () => {
mockFetch(api);
const { out } = await quiet(() => run(ctx(['report', '--start', '2026-10-01', '--end', '2026-10-07', '--json'])));
const j = JSON.parse(out);
expect(Object.keys(j)).toEqual(['accountId', 'by', 'start', 'end', 'timeZone', 'campaigns', 'rows', 'totals']);
expect(j.rows[1].cpa).toBeNull();
});
});

295
tests/console-fill.test.ts Normal file
View file

@ -0,0 +1,295 @@
// storebound console fill: pure answer building (rule 5: only what the config proves is certain), the click gate, the
// sign-in detector, and the engine run headless against MODELED console pages (tests/fixtures/console, written from
// the public help pages, not recorded) served on 127.0.0.1. No network. Browser tests skip when no Chromium launches.
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { join } from 'node:path';
import { fillPage, run, safeClick, signInPage } from '../cli/console/fill';
import { parseArgs } from '../cli/lib/args';
import { type ShipConfig, validateExtras } from '../cli/lib/config';
import { AGE_RATING_API, consoleAnswers, consoleResult, fillValue, FORM_IDS, type FormId } from '../cli/lib/console-answers';
import { consoleReached, formDef, forbiddenControl, isSignInUrl } from '../cli/lib/console-forms';
const config: ShipConfig = {
app: { name: 'Example Game', profile: 'game', privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', website: 'https://example.com', contactEmail: 'support@example.com' },
languages: [{ id: 'en', play: 'en-US', apple: 'en-US' }],
apple: { bundleId: 'com.example.game', primaryLocale: 'en-US' },
play: { packageName: 'com.example.game' },
products: [{ id: 'com.example.game.no_ads', type: 'non_consumable', usd: 2.99, listings: { en: { title: 'No ads', description: 'Removes ads' } } }],
ads: { appAdsTxt: ['example-network.com, pub-0000, DIRECT, abc123'] },
dataSafety: {
collectsData: true, encryptedInTransit: true, deletionRequest: false,
data: { PSL_DEVICE_ID: { shared: true, collect: ['advertising', 'analytics'], share: ['advertising'] }, PSL_CRASH_LOGS: { shared: false, collect: ['analytics'] } },
},
console: { contentRating: { answers: { violence: false } }, targetAudience: { ages: ['13-15', '16-17', '18-over'] } },
} as ShipConfig;
const byId = (id: FormId, c: ShipConfig = config) => new Map(consoleAnswers(id, c).map(a => [a.id, a]));
describe('click gate', () => {
test('refuses save / submit / publish / next and the like, English and Turkish', () => {
for (const n of ['Save', 'Save draft', 'Submit', 'Publish', 'Create', 'Next', 'Send', 'Apply', 'Confirm', 'Done', 'Start rollout', 'Release to production',
'Delete', 'Remove', 'Continue', 'Add for Review', 'Sign in', 'Kaydet', 'KAYDET', 'Gönder', 'Yayınla', 'Oluştur', 'İleri', 'Sonraki', 'Devam et', 'Onayla', 'Tamam', 'Sil', 'Kaldır', 'Başlat', 'Uygula'])
expect(forbiddenControl(n)).toBe(true);
});
test('allows the answers themselves', () => {
for (const n of ['Yes', 'No', 'Evet', 'Hayır', 'iOS', 'Full Access', 'Ages 13-15', 'Purchase History', 'Device ID', 'Third-Party Advertising', 'Help',
'Yes, we collect data from this app', 'No, we do not use Device ID for tracking purposes', 'Yes, my app contains ads', 'Game'])
expect(forbiddenControl(n)).toBe(false);
});
});
describe('sign-in and console detection', () => {
test('urls', () => {
expect(isSignInUrl('https://appleid.apple.com/auth/authorize')).toBe(true);
expect(isSignInUrl('https://idmsa.apple.com/appleauth/auth/signin')).toBe(true);
expect(isSignInUrl('https://accounts.google.com/v3/signin/identifier')).toBe(true);
expect(isSignInUrl('https://appstoreconnect.apple.com/login')).toBe(true);
expect(isSignInUrl('https://appstoreconnect.apple.com/apps')).toBe(false);
expect(consoleReached('apple', 'https://appstoreconnect.apple.com/apps')).toBe(true);
expect(consoleReached('apple', 'https://appstoreconnect.apple.com/login')).toBe(false);
expect(consoleReached('play', 'https://play.google.com/console/u/0/developers')).toBe(true);
expect(consoleReached('play', 'https://accounts.google.com/')).toBe(false);
expect(consoleReached('play', 'http://127.0.0.1:1234/x.html', 'http://127.0.0.1:1234/')).toBe(true);
});
});
describe('answers (only what the config proves is certain)', () => {
test('app record', () => {
const a = byId('apple-app-record');
expect(a.get('name')).toMatchObject({ value: 'Example Game', certain: true });
expect(a.get('language')).toMatchObject({ value: 'English (U.S.)', certain: true });
expect(a.get('bundleId')).toMatchObject({ value: 'com.example.game', certain: true });
expect(a.get('sku')).toMatchObject({ value: null, certain: false });
expect(a.get('access')).toMatchObject({ value: null, certain: false });
});
test('age rating is guide only and lists every API question', () => {
const r = consoleResult('apple-age-rating', config);
expect(r.answers.map(a => a.id)).toEqual(AGE_RATING_API);
expect(AGE_RATING_API).toContain('socialMedia');
expect(r.answers.every(a => !a.certain)).toBe(true);
expect(r.guidance[0]).toContain('storebound apple appinfo');
expect(formDef('apple-age-rating', r.answers).sections).toEqual([]);
const set = consoleResult('apple-age-rating', { ...config, apple: { ...config.apple!, info: { ageRating: { advertising: true } } } });
expect(set.answers.find(a => a.id === 'advertising')).toMatchObject({ value: true, certain: true });
expect(set.answers.find(a => a.id === 'violenceRealistic')).toMatchObject({ value: 'NONE', certain: true });
expect(set.answers.find(a => a.id === 'socialMedia')).toMatchObject({ value: false, certain: true });
});
test('app privacy from dataSafety; linked and tracking are never guessed', () => {
const a = byId('apple-app-privacy');
expect(a.get('collects')).toMatchObject({ value: true, certain: true });
expect(a.get('type:Device ID')).toMatchObject({ value: true, certain: true });
expect(a.get('type:Name')).toMatchObject({ value: false, certain: true });
expect(a.get('type:Advertising Data')).toMatchObject({ value: null, certain: false });
expect(a.get('purpose:Device ID:Third-Party Advertising')?.value).toBe(true);
expect(a.get('purpose:Device ID:Analytics')?.value).toBe(true);
expect(a.get('purpose:Device ID:App Functionality')?.value).toBe(false);
expect(a.get('linked:Device ID')).toMatchObject({ value: null, certain: false });
expect(a.get('tracking:Crash Data')).toMatchObject({ value: null, certain: false });
const none = consoleAnswers('apple-app-privacy', { ...config, dataSafety: undefined });
expect(none).toHaveLength(1);
expect(none[0]!.certain).toBe(false);
});
test('content rating: purchases from products, owner answers, the rest asked; email masked in output', () => {
const a = byId('play-content-rating');
expect(a.get('email')?.value).toBe('s***@example.com');
expect(fillValue('play-content-rating', a.get('email')!, config)).toBe('support@example.com');
expect(a.get('category')).toMatchObject({ value: 'Game', certain: true });
expect(a.get('q:digitalPurchases')).toMatchObject({ value: true, certain: true });
expect(a.get('q:violence')).toMatchObject({ value: false, certain: true });
expect(a.get('q:lootBoxes')).toMatchObject({ value: null, certain: false });
const noProfile = byId('play-content-rating', { ...config, app: { ...config.app, profile: undefined } });
expect(noProfile.get('category')?.certain).toBe(false);
});
test('target audience', () => {
const a = byId('play-target-audience');
expect(a.get('age:13-15')).toMatchObject({ value: true, certain: true });
expect(a.get('age:6-8')).toMatchObject({ value: false, certain: true });
expect(a.get('appeal')).toMatchObject({ value: null, certain: false });
expect(a.get('ads')).toMatchObject({ value: true, certain: true, source: 'ads.appAdsTxt' });
const bare = byId('play-target-audience', { ...config, console: undefined, ads: undefined });
expect([...bare.values()].every(x => !x.certain)).toBe(true);
});
test('every answer of a fillable form has a field', () => {
for (const f of FORM_IDS) {
const ans = consoleAnswers(f, config);
const ids = new Set(formDef(f, ans).sections.flatMap(s => s.fields.map(x => x.id)));
if (f !== 'apple-age-rating') for (const a of ans) expect(ids.has(a.id)).toBe(true);
}
});
test('config validation', () => {
expect(validateExtras({ console: { contentRating: { category: 'game', answers: { violence: false } }, targetAudience: { ages: ['13-15'] } } })).toEqual([]);
const e = validateExtras({ console: { appRecord: { sku: 'a b', userAccess: 'some' as 'full' }, contentRating: { category: 'x' as 'game', answers: { nope: true } as never },
targetAudience: { ages: ['3-4' as '6-8'], containsAds: 'yes' as unknown as boolean } } }).join('\n');
for (const k of ['appRecord.sku', 'appRecord.userAccess', 'contentRating.category', 'answers.nope', 'targetAudience.ages', 'containsAds']) expect(e).toContain(k);
});
});
describe('--dry --json', () => {
test('prints exactly one result and opens no browser', async () => {
const out: string[] = [];
const orig = console.log;
console.log = (s: string) => { out.push(s); };
try {
await run({ loaded: { config, root: '/tmp/none', path: '', resolve: p => p }, args: parseArgs(['play-target-audience', '--dry', '--json']) });
} finally { console.log = orig; }
expect(out).toHaveLength(1);
const r = JSON.parse(out[0]!);
expect(Object.keys(r)).toEqual(['form', 'store', 'title', 'url', 'answers', 'uncertain', 'guidance']);
expect(r).toMatchObject({ form: 'play-target-audience', store: 'play', uncertain: 1 });
expect(r.answers[0]).toMatchObject({ id: 'age:5-under', certain: true, source: 'console.targetAudience.ages' });
expect(r.guidance.at(-1)).toContain('press Save yourself');
await expect(run({ loaded: { config, root: '/tmp/none', path: '', resolve: p => p }, args: parseArgs(['play-target-audience', '--store', 'apple', '--dry']) })).rejects.toThrow('play form');
});
});
// ---- the engine against the modeled pages ----
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let browser: any = null;
let skipWhy = '';
try {
const { chromium } = await import('playwright');
try { browser = await chromium.launch({ headless: true }); } catch { browser = await chromium.launch({ headless: true, channel: 'chrome' }); }
} catch (e) { skipWhy = (e as Error).message.split('\n')[0]!; }
if (!browser) console.warn(`console-fill browser tests skipped: no Chromium could launch (${skipWhy}). Run \`bunx playwright install chromium\`.`);
const FIX = join(import.meta.dir, 'fixtures', 'console');
let server: ReturnType<typeof Bun.serve> | null = null;
let base = '';
beforeAll(() => {
server = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch: req => {
const name = new URL(req.url).pathname.slice(1);
if (!/^[a-z_-]+\.(html|js)$/.test(name)) return new Response('not found', { status: 404 });
return new Response(Bun.file(join(FIX, name)));
} });
base = `http://127.0.0.1:${server.port}/`;
});
afterAll(async () => { server?.stop(true); await browser?.close(); });
async function open(file: string) {
const page = await browser.newPage();
await page.goto(base + file);
return page;
}
const pageAnswers = (f: FormId) => consoleAnswers(f, config).map(a => ({ ...a, value: fillValue(f, a, config) }));
const checked = (page: any, name: string | RegExp, role = 'checkbox') => page.getByRole(role, { name, exact: typeof name === 'string' }).filter({ visible: true }).isChecked();
const flagged = (page: any) => page.evaluate(() => document.querySelectorAll('[data-storebound-label]').length);
const clicks = (page: any) => page.evaluate(() => (window as any).__clicks);
describe.skipIf(!browser)('engine (headless, modeled pages)', () => {
test('app record: certain fields filled, uncertain empty + highlighted, Create never clicked', async () => {
const page = await open('apple-app-record.html');
const def = formDef('apple-app-record', pageAnswers('apple-app-record'));
const s = await fillPage(page, def, pageAnswers('apple-app-record'));
expect(s.fallback).toBe(false);
expect(s.filled.sort()).toEqual(['bundleId', 'language', 'name', 'platform:ios']);
expect(s.highlighted.sort()).toEqual(['access', 'sku']);
expect(await page.getByRole('textbox', { name: 'Name', exact: true }).inputValue()).toBe('Example Game');
expect(await page.getByRole('textbox', { name: 'SKU', exact: true }).inputValue()).toBe('');
expect(await page.getByRole('combobox', { name: 'Bundle ID' }).evaluate((e: HTMLSelectElement) => e.selectedOptions[0]!.textContent)).toBe('Example Game - com.example.game');
expect(await page.getByRole('combobox', { name: 'Primary Language' }).evaluate((e: HTMLSelectElement) => e.value)).toBe('English (U.S.)');
expect(await checked(page, 'iOS')).toBe(true);
expect(await checked(page, 'macOS')).toBe(false);
expect(await checked(page, 'Full Access', 'radio')).toBe(false);
expect(await flagged(page)).toBe(2); // SKU + the User Access group
expect(await clicks(page)).toEqual([]);
// the next poll finds nothing left to do
expect((await fillPage(page, def, pageAnswers('apple-app-record'), new Set([0]))).section).toBeNull();
await page.close();
});
test('a renamed label stops filling and falls back to guidance', async () => {
const page = await open('apple-app-record-renamed.html');
const s = await fillPage(page, formDef('apple-app-record', pageAnswers('apple-app-record')), pageAnswers('apple-app-record'));
expect(s.fallback).toBe(true);
expect(s.missing).toEqual(['name']);
expect(s.filled).toEqual([]);
expect(await checked(page, 'iOS')).toBe(false);
expect(await clicks(page)).toEqual([]);
expect(consoleResult('apple-app-record', config).guidance).toContain('Name: Example Game');
await page.close();
});
test('app privacy: section by section as the owner moves on; Next / Save / Publish never clicked', async () => {
const page = await open('apple-app-privacy.html');
const ans = pageAnswers('apple-app-privacy');
const def = formDef('apple-app-privacy', ans);
const done = new Set<number>();
let s = await fillPage(page, def, ans, done);
expect(s).toMatchObject({ section: 0, filled: ['collects'], fallback: false });
expect(await checked(page, /^Yes, we collect data/, 'radio')).toBe(true);
expect((await fillPage(page, def, ans, done)).section).toBeNull(); // waits for the owner
await page.evaluate(() => (window as any).__next());
s = await fillPage(page, def, ans, done);
expect(s.section).toBe(1);
expect(await checked(page, 'Device ID')).toBe(true);
expect(await checked(page, 'Crash Data')).toBe(true);
expect(await checked(page, 'Purchase History')).toBe(false);
expect(s.highlighted).toContain('type:Advertising Data');
expect(await checked(page, 'Advertising Data')).toBe(false);
await page.evaluate(() => (window as any).__next());
s = await fillPage(page, def, ans, done);
expect(s.title).toBe('Device ID');
expect(s.fallback).toBe(false);
expect(await checked(page, 'Third-Party Advertising')).toBe(true);
expect(await checked(page, 'App Functionality')).toBe(false);
expect(s.highlighted.sort()).toEqual(['linked:Device ID', 'tracking:Device ID']);
expect(await page.getByRole('radio').filter({ visible: true }).evaluateAll((els: HTMLInputElement[]) => els.filter(e => e.checked).length)).toBe(0);
await page.evaluate(() => (window as any).__type('Crash Data'));
s = await fillPage(page, def, ans, done);
expect(s.title).toBe('Crash Data');
expect(done.size).toBe(def.sections.length);
expect(await clicks(page)).toEqual([]);
await page.close();
});
test('content rating: full email in the page, Game, purchases yes, the rest empty + highlighted', async () => {
const page = await open('play-content-rating.html');
const ans = pageAnswers('play-content-rating');
const def = formDef('play-content-rating', ans);
const done = new Set<number>();
let s = await fillPage(page, def, ans, done);
expect(s.filled.sort()).toEqual(['category', 'email']);
expect(await page.getByRole('textbox', { name: 'Email address' }).inputValue()).toBe('support@example.com');
expect(await checked(page, 'Game', 'radio')).toBe(true);
await page.evaluate(() => (window as any).__next());
s = await fillPage(page, def, ans, done);
expect(s.fallback).toBe(false);
expect(s.filled.sort()).toEqual(['q:digitalPurchases', 'q:violence']);
expect(s.highlighted).toHaveLength(11);
const yes = await page.getByRole('radiogroup', { name: /purchase digital goods/ }).getByRole('radio', { name: 'Yes' }).isChecked();
expect(yes).toBe(true);
expect(await page.getByRole('radiogroup', { name: /loot boxes/ }).getByRole('radio').evaluateAll((els: HTMLInputElement[]) => els.some(e => e.checked))).toBe(false);
expect(await clicks(page)).toEqual([]);
await page.close();
});
test('target audience: ages, appeal highlighted, ads yes', async () => {
const page = await open('play-target-audience.html');
const ans = pageAnswers('play-target-audience');
const def = formDef('play-target-audience', ans);
const done = new Set<number>();
expect((await fillPage(page, def, ans, done)).filled).toHaveLength(6);
expect(await checked(page, 'Ages 13-15')).toBe(true);
expect(await checked(page, 'Ages 9-12')).toBe(false);
await page.evaluate(() => (window as any).__next());
expect((await fillPage(page, def, ans, done)).highlighted).toEqual(['appeal']);
await page.evaluate(() => (window as any).__next());
expect((await fillPage(page, def, ans, done)).filled).toEqual(['ads']);
expect(await checked(page, /^Yes, my app contains ads/, 'radio')).toBe(true);
expect(await clicks(page)).toEqual([]);
await page.close();
});
test('sign-in detector and safeClick', async () => {
const signin = await open('signin.html');
expect(await signInPage(signin)).toBe(true);
await signin.close();
const page = await open('apple-app-record.html');
expect(await signInPage(page)).toBe(false);
expect(await safeClick(page.getByRole('button', { name: 'Create' }), 'Create')).toBe(false);
expect(await safeClick(page.getByRole('button', { name: 'Cancel' }), 'Cancel')).toBe(true);
expect(await clicks(page)).toEqual(['Cancel']);
await page.close();
});
});

10
tests/fixtures/console/_common.js vendored Normal file
View file

@ -0,0 +1,10 @@
// Shared by the console fixtures (modeled pages, not recorded): records every button click (the engine must never click
// one) and lets a test act as the owner (window.__next() shows the next step, like the owner pressing Next).
window.__clicks = [];
document.addEventListener('click', e => { const b = e.target.closest('button'); if (b) window.__clicks.push(b.textContent.trim()); }, true);
window.__step = 0;
window.__next = () => {
const steps = [...document.querySelectorAll('[data-step]')];
window.__step = Math.min(window.__step + 1, steps.length - 1);
steps.forEach((s, i) => { s.hidden = i !== window.__step; });
};

View file

@ -0,0 +1,35 @@
<!doctype html>
<!-- MODELED, not recorded: a sanitized stand-in for App Store Connect > App Privacy, written from Apple's public help
pages "Manage app privacy" and "App privacy details on the App Store" (collect yes / no, data types, per type:
purposes, linked to the user, tracking; Next / Save / Publish). The console's exact wording may differ. -->
<html lang="en"><head><meta charset="utf-8"><title>App Privacy - App Store Connect</title><script src="_common.js"></script></head>
<body>
<h1>App Privacy</h1> <button type="button">Publish</button>
<div role="dialog" aria-label="Data Collection" data-step>
<label><input type="radio" name="c"> Yes, we collect data from this app</label>
<label><input type="radio" name="c"> No, we do not collect data from this app</label>
<button type="button">Cancel</button> <button type="button">Next</button>
</div>
<div role="dialog" aria-label="Data Collection" data-step hidden><div id="types"></div><button type="button">Back</button> <button type="button">Save</button></div>
<div data-step hidden id="per"></div>
<script>
const TYPES = ['Name', 'Email Address', 'Phone Number', 'Physical Address', 'Other User Contact Info', 'Health', 'Fitness', 'Payment Info', 'Credit Info',
'Other Financial Info', 'Precise Location', 'Coarse Location', 'Sensitive Info', 'Contacts', 'Emails or Text Messages', 'Photos or Videos', 'Audio Data',
'Gameplay Content', 'Customer Support', 'Other User Content', 'Browsing History', 'Search History', 'User ID', 'Device ID', 'Purchase History',
'Product Interaction', 'Advertising Data', 'Other Usage Data', 'Crash Data', 'Performance Data', 'Other Diagnostic Data', 'Environment Scanning', 'Hands',
'Head', 'Other Data Types'];
for (const t of TYPES) { const l = document.createElement('label'); l.innerHTML = '<input type="checkbox"> '; l.append(t); document.getElementById('types').append(l); }
const PURPOSES = ['Third-Party Advertising', "Developer's Advertising or Marketing", 'Analytics', 'Product Personalization', 'App Functionality', 'Other Purposes'];
for (const t of ['Device ID', 'Crash Data']) {
const d = document.createElement('div'); d.setAttribute('role', 'dialog'); d.setAttribute('aria-label', t);
d.innerHTML = PURPOSES.map(p => `<label><input type="checkbox"> ${p}</label>`).join('') +
`<label><input type="radio" name="l${t}"> Yes, ${t} collected from this app is linked to the user's identity</label>` +
`<label><input type="radio" name="l${t}"> No, ${t} collected from this app is not linked to the user's identity</label>` +
`<label><input type="radio" name="t${t}"> Yes, we use ${t} for tracking purposes</label>` +
`<label><input type="radio" name="t${t}"> No, we do not use ${t} for tracking purposes</label><button type="button">Save</button>`;
d.hidden = t !== 'Device ID'; document.getElementById('per').append(d);
}
// the owner opens another data type
window.__type = t => document.querySelectorAll('#per [role=dialog]').forEach(d => { d.hidden = d.getAttribute('aria-label') !== t; });
</script>
</body></html>

View file

@ -0,0 +1,21 @@
<!doctype html>
<!-- MODELED, not recorded: the New App stand-in with the Name field renamed ("Title"), as if the console UI changed;
the engine must stop and fall back to printed guidance. Placeholder data only. -->
<html lang="en"><head><meta charset="utf-8"><title>Apps - App Store Connect</title><script src="_common.js"></script></head>
<body>
<h1>Apps</h1>
<div role="dialog" aria-labelledby="t" data-step>
<h2 id="t">New App</h2>
<fieldset><legend>Platforms</legend>
<label><input type="checkbox"> iOS</label> <label><input type="checkbox"> macOS</label>
</fieldset>
<p><label>Title <input type="text" maxlength="30"></label></p>
<p><label>Primary Language <select><option value="">Choose</option><option>English (U.S.)</option></select></label></p>
<p><label>Bundle ID <select><option value="">Choose</option><option>Example Game - com.example.game</option></select></label></p>
<p><label>SKU <input type="text"></label></p>
<fieldset><legend>User Access</legend>
<label><input type="radio" name="access"> Limited Access</label> <label><input type="radio" name="access"> Full Access</label>
</fieldset>
<button type="button">Cancel</button> <button type="button">Create</button>
</div>
</body></html>

View file

@ -0,0 +1,23 @@
<!doctype html>
<!-- MODELED, not recorded: a sanitized stand-in for App Store Connect > Apps > + > New App, written from Apple's public
help page "Add a new app" (platforms, Name, Primary Language, Bundle ID, SKU, User Access, Create).
Placeholder data only. -->
<html lang="en"><head><meta charset="utf-8"><title>Apps - App Store Connect</title><script src="_common.js"></script></head>
<body>
<h1>Apps</h1>
<div role="dialog" aria-labelledby="t" data-step>
<h2 id="t">New App</h2>
<fieldset><legend>Platforms</legend>
<label><input type="checkbox"> iOS</label> <label><input type="checkbox"> macOS</label>
<label><input type="checkbox"> tvOS</label> <label><input type="checkbox"> visionOS</label>
</fieldset>
<p><label>Name <input type="text" maxlength="30"></label></p>
<p><label>Primary Language <select><option value="">Choose</option><option>English (U.K.)</option><option>English (U.S.)</option><option>Turkish</option></select></label></p>
<p><label>Bundle ID <select><option value="">Choose</option><option>Other App - com.example.other</option><option>Example Game - com.example.game</option></select></label></p>
<p><label>SKU <input type="text"></label></p>
<fieldset><legend>User Access</legend>
<label><input type="radio" name="access"> Limited Access</label> <label><input type="radio" name="access"> Full Access</label>
</fieldset>
<button type="button">Help</button> <button type="button">Cancel</button> <button type="button">Create</button>
</div>
</body></html>

View file

@ -0,0 +1,32 @@
<!doctype html>
<!-- MODELED, not recorded: a sanitized stand-in for Play Console > Policy > App content > Content rating (IARC), written
from Google's public help page "Content ratings" (email address, category, questionnaire, Save draft / Next /
Submit). The question wording is modeled on the IARC topics, not copied from the console. -->
<html lang="en"><head><meta charset="utf-8"><title>Content rating - Play Console</title><script src="_common.js"></script></head>
<body>
<h1>Content rating</h1>
<section data-step>
<p><label>Email address <input type="email"></label></p>
<fieldset><legend>Category</legend>
<label><input type="radio" name="cat"> Game</label>
<label><input type="radio" name="cat"> Social or communication</label>
<label><input type="radio" name="cat"> All other app types</label>
</fieldset>
<button type="button">Save draft</button> <button type="button">Next</button>
</section>
<section data-step hidden id="q"><button type="button">Save draft</button> <button type="button">Next</button></section>
<script>
const Q = ['Does the app contain any violence?', 'Does the app contain content that might scare or frighten (fear or horror)?',
'Does the app contain sexual content or nudity?', 'Does the app contain profanity or crude language?',
'Does the app contain references to drugs, alcohol or tobacco?', 'Does the app contain crude humour?',
'Does the app let users gamble with real money?', 'Does the app contain simulated gambling?',
'Does the app offer randomized paid items (loot boxes)?', 'Can users interact or exchange content with other users?',
"Does the app share the user's current physical location with other users?", 'Does the app allow users to purchase digital goods?',
'Does the app give unrestricted internet access, such as a web browser?'];
Q.forEach((q, i) => {
const d = document.createElement('div'); d.setAttribute('role', 'radiogroup'); d.setAttribute('aria-label', q);
d.innerHTML = `<p>${q}</p><label><input type="radio" name="q${i}"> Yes</label><label><input type="radio" name="q${i}"> No</label>`;
document.getElementById('q').prepend(d);
});
</script>
</body></html>

View file

@ -0,0 +1,17 @@
<!doctype html>
<!-- MODELED, not recorded: a sanitized stand-in for Play Console > Policy > App content > Target audience and content
(and the Ads declaration), written from Google's public help page "Target audience and content" (target age
groups, appeal to children, ads; Next / Save). -->
<html lang="en"><head><meta charset="utf-8"><title>Target audience and content - Play Console</title><script src="_common.js"></script></head>
<body>
<h1>Target audience and content</h1>
<section data-step><fieldset><legend>Target age</legend>
<label><input type="checkbox"> Ages 5 and under</label><label><input type="checkbox"> Ages 6-8</label><label><input type="checkbox"> Ages 9-12</label>
<label><input type="checkbox"> Ages 13-15</label><label><input type="checkbox"> Ages 16-17</label><label><input type="checkbox"> Ages 18 and over</label>
</fieldset><button type="button">Next</button></section>
<section data-step hidden><div role="radiogroup" aria-label="Could your app unintentionally appeal to children?">
<label><input type="radio" name="a"> Yes</label><label><input type="radio" name="a"> No</label></div><button type="button">Next</button></section>
<section data-step hidden><h2>Ads</h2>
<label><input type="radio" name="ads"> Yes, my app contains ads</label><label><input type="radio" name="ads"> No, my app does not contain ads</label>
<button type="button">Save</button></section>
</body></html>

4
tests/fixtures/console/signin.html vendored Normal file
View file

@ -0,0 +1,4 @@
<!doctype html>
<!-- MODELED, not recorded: a generic sign-in page; the engine must detect it and never type into it. -->
<html lang="en"><head><meta charset="utf-8"><title>Sign in</title></head>
<body><label>Email or phone <input type="text"></label> <label>Password <input type="password"></label> <button type="button">Sign in</button></body></html>

View file

@ -0,0 +1,52 @@
// Config validation of the growth extras: web, revenuecat, prices.ppp, apple.teamId / adhoc.
import { describe, expect, test } from 'bun:test';
import { type ShipConfig, validateConfig, validateExtras } from '../cli/lib/config';
import { TOOLS, toArgv } from '../cli/mcp-tools';
const base: ShipConfig = {
app: { name: 'Example', privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', website: 'https://example.com', contactEmail: 'hi@example.com' },
languages: [{ id: 'en', play: 'en-US', apple: 'en-US' }],
apple: { bundleId: 'com.example.app' },
play: { packageName: 'com.example.app' },
};
const fp = Array.from({ length: 32 }, (_, i) => (i * 7 % 256).toString(16).toUpperCase().padStart(2, '0')).join(':');
describe('growth extras config', () => {
test('a full, valid set passes', () => {
const c: ShipConfig = { ...base, apple: { ...base.apple!, teamId: 'ABCDEFGHIJ', adhoc: { method: 'ad-hoc' } },
prices: { ppp: { source: 'worldbank', floor: 0.25, ceiling: 1 } },
web: { domain: 'links.example.com', paths: ['/invite/*'], exclude: ['/admin/*'], androidSha256: [fp], landing: true },
revenuecat: { projectId: 'proj0example', entitlements: { pro: ['com.example.app.pro'] }, offering: 'default' } };
expect(validateExtras(c)).toEqual([]);
expect(validateConfig(c)).toEqual([]);
});
test('each mistake is named', () => {
const c = { ...base, apple: { ...base.apple!, teamId: 'abc', adhoc: { method: 'enterprise' } },
prices: { ppp: { source: 'file', floor: 2, ceiling: 1 } },
web: { domain: 'https://example.com/x', paths: ['invite'], androidSha256: ['ab:cd'] },
revenuecat: { projectId: '', entitlements: { pro: [] }, offering: 'a b' } } as unknown as ShipConfig;
const e = validateExtras(c).join('\n');
for (const s of ['apple.teamId', 'apple.adhoc.method', 'prices.ppp.file', 'floor is above ceiling', 'web.domain', 'must start with /', 'web.androidSha256', 'revenuecat.projectId', 'revenuecat.entitlements.pro', 'revenuecat.offering'])
expect(e).toContain(s);
});
test('no extras, no problems', () => expect(validateExtras(base)).toEqual([]));
});
describe('growth extras over MCP', () => {
test('no console tool exists in MCP', () => {
expect(TOOLS.filter(t => t.command[0] === 'console' || /console/.test(t.name))).toEqual([]);
});
test('Apple Ads, RevenueCat, device registration and internal sharing are read-only in MCP', () => {
const risky = TOOLS.filter(t => (t.command[0] === 'ads' && t.command[1] === 'apple') || t.command[0] === 'revenuecat' || (t.command[0] === 'play' && t.command[1] === 'share')
|| (t.command[0] === 'apple' && t.command[1] === 'adhoc' && !['devices', 'options'].includes(t.command[2]!)));
expect(risky.filter(t => t.write)).toEqual([]);
for (const t of TOOLS.filter(x => (x.command[0] === 'ads' && x.command[1] === 'apple') || x.command[0] === 'revenuecat')) expect(['status', 'campaigns', 'report', 'diff']).toContain(t.command.at(-1)!);
});
test('local writes default to a dry run', () => {
for (const n of ['prices_ppp', 'web_init', 'apple_adhoc_options']) {
const t = TOOLS.find(x => x.name === n)!;
expect(toArgv(t, {}).argv).toContain('--dry');
}
expect(toArgv(TOOLS.find(x => x.name === 'prices_ppp')!, { base: 4.99, source: 'worldbank' }).argv).toEqual(['prices', 'ppp', '--base', '4.99', '--source', 'worldbank', '--dry']);
});
});

View file

@ -3,13 +3,13 @@
// the desktop webview, the site and the teaser video (media/teaser), and on any SVG file that is not a known asset. // the desktop webview, the site and the teaser video (media/teaser), and on any SVG file that is not a known asset.
// The brand mark is a PNG (tools/brand-assets.py from brand/master/logo-mark.png): no inline brand SVG anywhere. // The brand mark is a PNG (tools/brand-assets.py from brand/master/logo-mark.png): no inline brand SVG anywhere.
// Allowed: the <svg> root a visx chart renders into (files that import @visx/*), the vendored icon // Allowed: the <svg> root a visx chart renders into (files that import @visx/*), the vendored icon
// files (site/img/icons: Phosphor and simple-icons; apps/desktop/src/ui/store-marks: simple-icons; media/teaser/icons: // files (site/img/icons: Phosphor and simple-icons; apps/desktop/src/ui/store-marks and templates/web: simple-icons;
// Phosphor), each byte-equal to // media/teaser/icons: Phosphor), each byte-equal to
// its package (tools/site-icons.ts), and the Mermaid output (docs/img, site/img journey*.svg). // its package (tools/site-icons.ts), and the Mermaid output (docs/img, site/img journey*.svg).
import { describe, expect, test } from 'bun:test'; import { describe, expect, test } from 'bun:test';
import { readdirSync, readFileSync, statSync } from 'node:fs'; import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join, relative } from 'node:path'; import { join, relative } from 'node:path';
import { checkSiteIcons, ICON_DIR, MARK_DIR, SITE_ICONS, STORE_MARKS, TEASER_DIR, TEASER_ICONS } from '../tools/site-icons'; import { checkSiteIcons, ICON_DIR, MARK_DIR, SITE_ICONS, STORE_MARKS, TEASER_DIR, TEASER_ICONS, WEB_DIR } from '../tools/site-icons';
const ROOT = join(import.meta.dir, '..'); const ROOT = join(import.meta.dir, '..');
const walk = (dir: string, keep: (f: string) => boolean): string[] => readdirSync(join(ROOT, dir)).flatMap(n => { const walk = (dir: string, keep: (f: string) => boolean): string[] => readdirSync(join(ROOT, dir)).flatMap(n => {
@ -73,11 +73,18 @@ describe('no hand-written SVG', () => {
for (const n of used) expect(vendored, n).toContain(n ?? ''); for (const n of used) expect(vendored, n).toContain(n ?? '');
}); });
test('templates (the web init landing page): store marks are the vendored simple-icons files, no inline SVG', () => {
const files = walk('templates', n => /\.(html|css|js)$/.test(n));
expect(files).toContain('templates/web/landing.html');
expect(files.flatMap(f => svgHits(f, read(f)))).toEqual([]);
});
test('SVG files: vendored Phosphor / simple-icons files and Mermaid diagrams only', () => { test('SVG files: vendored Phosphor / simple-icons files and Mermaid diagrams only', () => {
const svgs = ['site', 'docs', 'apps/desktop/src', 'media'].flatMap(d => walk(d, n => n.endsWith('.svg'))).map(f => relative(ROOT, join(ROOT, f))); const svgs = ['site', 'docs', 'apps/desktop/src', 'media', 'templates'].flatMap(d => walk(d, n => n.endsWith('.svg'))).map(f => relative(ROOT, join(ROOT, f)));
const vendored = new Set([ const vendored = new Set([
...[...SITE_ICONS, ...STORE_MARKS].map(n => relative(ROOT, join(ICON_DIR, `${n}.svg`))), ...[...SITE_ICONS, ...STORE_MARKS].map(n => relative(ROOT, join(ICON_DIR, `${n}.svg`))),
...STORE_MARKS.map(n => relative(ROOT, join(MARK_DIR, `${n}.svg`))), ...STORE_MARKS.map(n => relative(ROOT, join(MARK_DIR, `${n}.svg`))),
...STORE_MARKS.map(n => relative(ROOT, join(WEB_DIR, `${n}.svg`))),
...TEASER_ICONS.map(([w, n]) => relative(ROOT, join(TEASER_DIR, `${n}-${w}.svg`))), ...TEASER_ICONS.map(([w, n]) => relative(ROOT, join(TEASER_DIR, `${n}-${w}.svg`))),
]); ]);
// byte equality with the packages is checked by checkSiteIcons (above); here: no other SVG file sneaks in // byte equality with the packages is checked by checkSiteIcons (above); here: no other SVG file sneaks in

247
tests/ppp.test.ts Normal file
View file

@ -0,0 +1,247 @@
import { describe, expect, test } from 'bun:test';
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve as pathResolve } from 'node:path';
import bundledJson from '../cli/data/ppp-worldbank.json';
import { parseArgs } from '../cli/lib/args';
import { ALPHA3 } from '../cli/lib/money';
import {
appleCurrencyHint, bigMacDataset, CURRENCY, datasetJson, datasetProblems, fxOf, parseFactorCsv, planRows, type PppDataset, pppCsv, propose, snapApple,
snapEnding, worldBankDataset,
} from '../cli/lib/ppp';
import { parsePriceCsv } from '../cli/lib/prices';
import { applePoints, run } from '../cli/prices-ppp';
const P = 'com.example.game.remove_ads';
const ds: PppDataset = {
name: 'worldbank', source: 'test', url: 'https://example.com', license: 'CC BY 4.0', retrieved: '2026-10-11', eur: { fx: 0.9 },
countries: {
US: { ppp: 1, fx: 1, year: 2025, currency: 'USD' },
DE: { ppp: 0.72, fx: 0.9, year: 2025, currency: 'EUR' },
TR: { ppp: 16, fx: 40, year: 2025, currency: 'TRY' },
IN: { ppp: 20, fx: 87, year: 2025, currency: 'INR' },
CH: { ppp: 1.2, fx: 0.8, year: 2025, currency: 'CHF' },
JP: { ppp: 97, fx: 150, year: 2025, currency: 'JPY' },
BA: { ppp: 0.7, fx: 1.75, year: 2025, currency: 'BAM' },
AF: { ppp: 13, year: 2024, currency: 'AFN' },
},
};
describe('ppp math', () => {
test('usd = base x factor / fx, clamped to floor..ceiling', () => {
expect(propose(10, 0.72, 0.9, 0.3, 1.2)).toMatchObject({ clamped: null });
expect(propose(10, 0.72, 0.9, 0.3, 1.2).usd).toBeCloseTo(8, 9);
const lo = propose(10, 20, 87, 0.3, 1.2);
expect(lo.clamped).toBe('floor');
expect(lo.usd).toBe(3);
expect(lo.usdRaw).toBeCloseTo(2.299, 3);
expect(propose(10, 1.2, 0.8, 0.3, 1.2)).toMatchObject({ usd: 12, clamped: 'ceiling' });
expect(() => propose(10, 0, 1, 0.3, 1.2)).toThrow();
});
test('fxOf: USD 1, EUR the euro rate, else a country with that currency', () => {
expect(fxOf(ds, 'USD')).toBe(1);
expect(fxOf(ds, 'EUR')).toBe(0.9);
expect(fxOf(ds, 'TRY')).toBe(40);
expect(fxOf(ds, 'XYZ')).toBeNull();
});
});
describe('snapping', () => {
test('two-decimal currencies: x.x9 under 1, x.99 under 100, ...9 under 1000', () => {
expect(snapEnding(2.4, 'USD')).toBe(1.99);
expect(snapEnding(2.6, 'USD')).toBe(2.99);
expect(snapEnding(0.3, 'GBP')).toBe(0.29);
expect(snapEnding(0.02, 'GBP')).toBe(0.09);
expect(snapEnding(1.2, 'EUR')).toBe(0.99);
expect(snapEnding(49.6, 'TRY')).toBe(49.99);
expect(snapEnding(129.4, 'TRY')).toBe(129);
expect(snapEnding(135, 'INR')).toBe(139);
});
test('zero-decimal and large-unit currencies: round numbers', () => {
expect(snapEnding(478, 'JPY')).toBe(480);
expect(snapEnding(80.4, 'JPY')).toBe(80);
expect(snapEnding(3456, 'KRW')).toBe(3500);
expect(snapEnding(45678, 'IDR')).toBe(46000);
expect(snapEnding(56789, 'VND')).toBe(57000);
expect(snapEnding(2345, 'CLP')).toBe(2300);
expect(snapEnding(923, 'HUF')).toBe(920);
expect(snapEnding(1234.5, 'PKR')).toBe(1200);
});
test('Apple: nearest real price point', () => {
expect(snapApple([49.99, 59.99, 64.99, 69.99], 62)).toBe(59.99);
expect(snapApple([], 62)).toBeNull();
});
});
describe('planRows', () => {
test('offline Play: local currency, US row is the base, clamp flags, skipped regions', () => {
const { rows, skipped } = planRows({ product: P, base: 4.99, store: 'play', dataset: ds, floor: 0.3, ceiling: 1.2 });
const by = new Map(rows.map(r => [r.region, r] as const));
expect(by.get('US')).toMatchObject({ currency: 'USD', price: 4.99, snap: 'base' });
expect(by.get('DE')).toMatchObject({ currency: 'EUR', price: 3.99, clamped: null, snap: 'ending' });
expect(by.get('IN')).toMatchObject({ currency: 'INR', clamped: 'floor', price: 129 });
expect(by.get('CH')).toMatchObject({ clamped: 'ceiling', price: 4.99 });
expect(by.get('JP')).toMatchObject({ currency: 'JPY', price: 480 });
expect(by.get('BA')!.currency).toBe('BAM');
expect(skipped.find(s => s.region === 'AF')!.why).toBe('no exchange rate');
expect(skipped.find(s => s.region === 'FR')!.why).toMatch(/no PPP factor/);
expect(rows.every(r => r.territory === undefined)).toBe(true);
});
test('offline Apple: the currency hint (Euro-Zone group EUR, USD groups USD), alpha-3 territory', () => {
const { rows } = planRows({ product: P, base: 4.99, store: 'apple', dataset: ds, floor: 0.3, ceiling: 1.2 });
const ba = rows.find(r => r.region === 'BA')!;
expect(ba).toMatchObject({ currency: 'EUR', territory: 'BIH' });
expect(ba.snappedFrom).toBeCloseTo((4.99 * 0.7 / 1.75) * 0.9, 2);
expect(appleCurrencyHint('TR')).toBe('TRY');
expect(appleCurrencyHint('AF')).toBe('USD');
expect(appleCurrencyHint('RS')).toBe('EUR');
});
test('online Apple: snaps to the mocked price points and takes the store currency', () => {
const regions = new Map([
['US', { currency: 'USD', points: [3.99, 4.99, 5.99] }],
['TR', { currency: 'TRY', points: [49.99, 59.99, 64.99, 69.99, 79.99] }],
['AF', { currency: 'USD', points: [0.99, 1.99] }],
['JP', { currency: 'JPY', points: [] as number[] }],
]);
const { rows, skipped } = planRows({ product: P, base: 4.99, store: 'apple', dataset: ds, floor: 0.3, ceiling: 1.2, regions });
expect(rows.map(r => `${r.region} ${r.currency} ${r.price} ${r.snap}`)).toEqual(['TR TRY 79.99 apple-point', 'US USD 4.99 apple-point']);
expect(rows[0]!.snappedFrom).toBeCloseTo(4.99 * 0.4 * 40, 1);
expect(skipped.map(s => `${s.region}: ${s.why}`)).toEqual(['AF: no exchange rate', 'JP: no Apple price points']);
});
test('CSV round trip through parsePriceCsv (the prices import parser)', () => {
const rows = [...planRows({ product: P, base: 4.99, store: 'apple', dataset: ds, floor: 0.3, ceiling: 1.2 }).rows,
...planRows({ product: P, base: 4.99, store: 'play', dataset: ds, floor: 0.3, ceiling: 1.2 }).rows];
const back = parsePriceCsv(pppCsv(rows), { products: [P], today: '2026-10-11' });
const k = (r: { store: string; region: string; currency: string; price: number }) => `${r.store} ${r.region} ${r.currency} ${r.price}`;
expect(back.map(k).sort()).toEqual(rows.map(k).sort());
expect(back.find(r => r.store === 'apple' && r.region === 'DE')!.territory).toBe('DEU');
expect(pppCsv(rows).split('\n')[0]).toBe('product,store,region,currency,price,start_date,kind');
});
});
describe('datasets', () => {
const bundled = bundledJson as unknown as PppDataset;
test('bundled World Bank file: shape, citation, licence, euro rate', () => {
expect(datasetProblems(bundled)).toEqual([]);
expect(bundled.name).toBe('worldbank');
expect(bundled.license).toBe('CC BY 4.0');
expect(bundled.attribution).toMatch(/World Bank/);
expect(bundled.source).toMatch(/PA\.NUS\.PPP/);
expect(bundled.source).toMatch(/PA\.NUS\.FCRF/);
expect(bundled.retrieved).toMatch(/^\d{4}-\d{2}-\d{2}$/);
expect(bundled.urls!.some(u => u.startsWith('https://api.worldbank.org/'))).toBe(true);
expect(bundled.year).toBeGreaterThanOrEqual(2023);
expect(Object.keys(bundled.countries).length).toBeGreaterThan(120);
for (const [r, e] of Object.entries(bundled.countries)) {
expect(ALPHA3[r]).toBeDefined();
expect(e.currency).toBe(CURRENCY[r]!);
if (e.currency === 'EUR') expect(e.fx).toBe(bundled.eur!.fx);
}
expect(bundled.countries.US).toMatchObject({ ppp: 1, fx: 1 });
expect(JSON.parse(datasetJson(bundled))).toEqual(bundled);
});
test('CURRENCY covers every App Store territory', () => {
expect(Object.keys(ALPHA3).filter(k => !CURRENCY[k])).toEqual([]);
});
test('worldBankDataset: latest year, aggregates out, euro rate, unit mismatch dropped', () => {
const obs = (id: string, date: string, value: number | null) => ({ country: { id }, countryiso3code: '', date, value });
const ppp: [unknown, ReturnType<typeof obs>[]] = [{}, [obs('ZH', '2025', 5), obs('DE', '2024', 0.7), obs('DE', '2025', 0.71), obs('TR', '2025', null), obs('TR', '2024', 15), obs('LR', '2025', 0.4), obs('US', '2025', 1)]];
const fx: [unknown, ReturnType<typeof obs>[]] = [{}, [obs('XC', '2025', 0.88), obs('TR', '2025', 39), obs('LR', '2025', 190), obs('US', '2025', 1)]];
const countries: [unknown, { id: string; iso2Code: string; region?: { value?: string } }[]] = [{}, [
{ id: 'AFE', iso2Code: 'ZH', region: { value: 'Aggregates' } }, { id: 'DEU', iso2Code: 'DE', region: { value: 'Europe & Central Asia' } },
{ id: 'TUR', iso2Code: 'TR' }, { id: 'LBR', iso2Code: 'LR' }, { id: 'USA', iso2Code: 'US' }]];
const d = worldBankDataset(ppp, fx, countries, '2026-10-11');
expect(Object.keys(d.countries)).toEqual(['DE', 'TR', 'US']);
expect(d.countries.DE).toEqual({ ppp: 0.71, fx: 0.88, year: 2025, currency: 'EUR' });
expect(d.countries.TR).toEqual({ ppp: 15, fx: 39, year: 2024, fxYear: 2025, currency: 'TRY' });
expect(d.eur).toEqual({ fx: 0.88, year: 2025 });
expect(d.notes!.join(' ')).toMatch(/LR/);
expect(datasetProblems(d)).toEqual([]);
});
test('bigMacDataset: implied PPP = local / US price, latest date, euro area row for EUR members', () => {
const csv = `date,iso_a3,currency_code,name,local_price,dollar_ex,dollar_price
2025-07-01,USA,USD,United States,5.5,1,5.5
2026-07-01,USA,USD,United States,6,1,6
2026-07-01,TUR,TRY,Turkey,240,40,6
2026-07-01,EUZ,EUR,Euro area,5.4,0.9,6
`;
const d = bigMacDataset(csv, '2026-10-11');
expect(d.countries.TR).toEqual({ ppp: 40, fx: 40, year: 2026, currency: 'TRY' });
expect(d.countries.DE).toEqual({ ppp: 0.9, fx: 0.9, year: 2026, currency: 'EUR' });
expect(d.countries.US!.ppp).toBe(1);
expect(d.eur!.fx).toBe(0.9);
expect(d.license).toMatch(/CC BY 4\.0/);
});
test('factor CSV: fx falls back to the bundled rate when the currency matches; errors at once', () => {
const fb: PppDataset = { ...ds };
const d = parseFactorCsv('region,factor,currency,fx\nTR,15,TRY,\nDE,0.7,EUR,0.92\nUS,1,USD,\nAF,13,AFN,\n', fb, 'f.csv');
expect(d.countries.TR).toEqual({ ppp: 15, fx: 40, currency: 'TRY' });
expect(d.countries.DE!.fx).toBe(0.92);
expect(d.countries.US!.fx).toBe(1);
expect(d.countries.AF!.fx).toBeUndefined();
expect(() => parseFactorCsv('region,factor,currency\nTUR,0,tr\n')).toThrow(/region "TUR"/);
expect(() => parseFactorCsv('region,factor,currency\nTR,0,tr\n')).toThrow(/currency.*factor/);
});
});
describe('command', () => {
test('applePoints: batched GET with include=territory -> region, currency, points', async () => {
const urls: string[] = [];
const fake = { asc: async (_m: string, url: string) => {
urls.push(url);
return { data: [
{ id: 'pp1', attributes: { customerPrice: '59.99' }, relationships: { territory: { data: { type: 'territories', id: 'TUR' } } } },
{ id: 'pp2', attributes: { customerPrice: '64.99' }, relationships: { territory: { data: { type: 'territories', id: 'TUR' } } } },
{ id: 'pp3', attributes: { customerPrice: '4.99' }, relationships: { territory: { data: { type: 'territories', id: 'USA' } } } }],
included: [{ type: 'territories', id: 'TUR', attributes: { currency: 'TRY' } }, { type: 'territories', id: 'USA', attributes: { currency: 'USD' } }] };
} };
const m = await applePoints(fake as never, 'iap-1', ['TUR', 'USA']);
expect(urls).toEqual(['/v2/inAppPurchases/iap-1/pricePoints?filter[territory]=TUR,USA&include=territory&fields[territories]=currency&limit=8000']);
expect(m.get('TR')).toEqual({ currency: 'TRY', points: [59.99, 64.99] });
expect(m.get('US')).toEqual({ currency: 'USD', points: [4.99] });
});
async function runIn(argv: string[]): Promise<{ out: string; dir: string }> {
const dir = mkdtempSync(join(tmpdir(), 'ppp-'));
const config = { app: { name: 'Example' }, apple: { bundleId: 'com.example.game' }, play: { packageName: 'com.example.game' },
products: [{ id: P, type: 'non_consumable', usd: 2.99, listings: {} }] };
const lines: string[] = [];
const orig = console.log;
const fetchOrig = globalThis.fetch;
console.log = (...x: unknown[]) => { lines.push(x.join(' ')); };
globalThis.fetch = (() => { throw new Error('no network in tests'); }) as never;
try {
await run({ loaded: { config, root: dir, path: join(dir, 'storebound.config.ts'), resolve: (p: string) => pathResolve(dir, p) }, args: parseArgs(argv) } as never);
} finally { console.log = orig; globalThis.fetch = fetchOrig; }
return { out: lines.join('\n'), dir };
}
test('offline --dry --json: the documented shape, nothing written', async () => {
const { out, dir } = await runIn(['--offline', '--dry', '--json', '--base', '4.99']);
const j = JSON.parse(out.slice(out.indexOf('{')));
expect(Object.keys(j)).toEqual(['source', 'base', 'floor', 'ceiling', 'online', 'rows', 'skipped', 'diff', 'out', 'written']);
expect(j.source).toMatchObject({ name: 'worldbank', license: 'CC BY 4.0' });
expect(j.base).toEqual({ [P]: 4.99 });
expect(j.written).toBe(false);
expect(j.rows.find((r: { store: string; region: string }) => r.store === 'play' && r.region === 'US')).toMatchObject({ price: 4.99, factor: 1, usdEquivalent: 4.99 });
expect(j.diff.every((d: { change: string }) => d.change === 'new')).toBe(true);
expect(() => readFileSync(join(dir, 'store/prices-ppp.csv'))).toThrow();
});
test('offline write: the sheet parses back with the import parser', async () => {
const { out, dir } = await runIn(['--offline', '--store', 'play', '--floor', '0.4']);
const csv = readFileSync(join(dir, 'store/prices-ppp.csv'), 'utf8');
const rows = parsePriceCsv(csv, { products: [P] });
expect(rows.length).toBeGreaterThan(100);
expect(rows.every(r => r.store === 'play')).toBe(true);
expect(out).toMatch(/storebound prices import --csv store\/prices-ppp\.csv --dry/);
});
test('source file and bad bounds', async () => {
const dir = mkdtempSync(join(tmpdir(), 'ppp-f-'));
writeFileSync(join(dir, 'f.csv'), 'region,factor,currency,fx\nTR,16,TRY,40\n');
await expect(runIn(['--offline', '--floor', '2', '--ceiling', '1'])).rejects.toThrow(/floor/);
await expect(runIn(['--offline', '--source', 'bigmac'])).rejects.toThrow(/--update-bigmac/);
const { out } = await runIn(['--offline', '--dry', '--json', '--source', 'file', '--file', join(dir, 'f.csv'), '--store', 'play']);
const j = JSON.parse(out.slice(out.indexOf('{')));
expect(j.rows.map((r: { region: string }) => r.region)).toEqual(['TR', 'US']);
});
});

331
tests/revenuecat.test.ts Normal file
View file

@ -0,0 +1,331 @@
// RevenueCat adapter: config -> wanted RevenueCat state, package identifiers, diff, sync plan order, and the command
// against a mocked fetch (paginated reads, --dry and no-TTY send no POST, the key never shows up). Response shapes are
// written by hand from https://www.revenuecat.com/docs/api-v2 (placeholder ids, no real project).
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { parseArgs } from '../cli/lib/args';
import type { Loaded, ShipConfig } from '../cli/lib/config';
import { outOfSync, RC_PACKAGE, rcDiff, rcPlan, type RcState, resolveApps, wantedRevenueCat } from '../cli/lib/revenuecat';
import { rcClient, run } from '../cli/revenuecat';
const KEY = 'sk_test_placeholder_secret_value';
const PROJECT = 'proj_example1';
const APPS = { apple: 'app_apple1', play: 'app_play1' };
const listing = (title: string) => ({ en: { title, description: 'd' } });
function config(over: Partial<ShipConfig> = {}): ShipConfig {
return {
app: { name: 'Example', privacyPolicyUrl: 'https://example.com/privacy' },
languages: [{ id: 'en', apple: 'en-US', play: 'en-US' }],
apple: { bundleId: 'com.example.app' },
play: { packageName: 'com.example.app' },
products: [
{ id: 'com.example.app.lifetime', type: 'non_consumable', usd: 29.99, listings: listing('Lifetime') },
{ id: 'com.example.app.coins_100', type: 'consumable', usd: 0.99, listings: listing('100 coins') },
{ id: 'com.example.app.pass_30d', type: 'non_renewing', usd: 4.99, listings: listing('30-day pass'), platforms: ['ios'] },
],
subscriptions: [{ name: 'Pro', listings: { en: { name: 'Pro' } }, subscriptions: [
{ id: 'com.example.app.pro_monthly', period: 'P1M', level: 2, usd: 4.99, listings: listing('Pro monthly') },
{ id: 'com.example.app.pro_yearly', period: 'P1Y', level: 1, usd: 39.99, listings: listing('Pro yearly'), basePlanId: 'annual' },
{ id: 'com.example.app.pro_monthly_b', period: 'P1M', level: 3, usd: 5.99, listings: listing('Pro monthly B'), platforms: ['android'] },
] }],
revenuecat: { projectId: PROJECT, apps: APPS },
...over,
} as unknown as ShipConfig;
}
describe('wantedRevenueCat', () => {
const w = wantedRevenueCat(config());
test('one product per store item; Play subscriptions are productId:basePlanId', () => {
expect(w.products.map(p => `${p.key} ${p.type}`)).toEqual([
'apple:com.example.app.lifetime non_consumable', 'play:com.example.app.lifetime non_consumable',
'apple:com.example.app.coins_100 consumable', 'play:com.example.app.coins_100 consumable',
'apple:com.example.app.pass_30d non_renewing_subscription',
'apple:com.example.app.pro_monthly subscription', 'play:com.example.app.pro_monthly:monthly subscription',
'apple:com.example.app.pro_yearly subscription', 'play:com.example.app.pro_yearly:annual subscription',
'play:com.example.app.pro_monthly_b:monthly subscription',
]);
expect(w.problems).toEqual([]);
});
test('default entitlement "pro" = every non-consumable, non-renewing and subscription; no consumables', () => {
expect(w.entitlements).toHaveLength(1);
expect(w.entitlements[0]!.lookupKey).toBe('pro');
expect(w.entitlements[0]!.products.some(k => k.includes('coins'))).toBe(false);
expect(w.entitlements[0]!.products).toContain('apple:com.example.app.pass_30d');
expect(w.entitlements[0]!.products).toHaveLength(8);
});
test('package identifiers: reserved by period, first wins; lifetime; the rest custom', () => {
expect(w.offering.lookupKey).toBe('default');
expect(w.offering.packages.map(p => [p.lookupKey, p.position])).toEqual([
['$rc_monthly', 1], ['$rc_annual', 2], ['com.example.app.pro_monthly_b', 3],
['$rc_lifetime', 4], ['com.example.app.coins_100', 5], ['com.example.app.pass_30d', 6],
]);
expect(w.offering.packages[0]!.products).toEqual(['apple:com.example.app.pro_monthly', 'play:com.example.app.pro_monthly:monthly']);
expect(RC_PACKAGE).toEqual({ P1W: '$rc_weekly', P1M: '$rc_monthly', P2M: '$rc_two_month', P3M: '$rc_three_month', P6M: '$rc_six_month', P1Y: '$rc_annual' });
});
test('platforms: an android-only app has only Play products; non_renewing is a Play consumable', () => {
const c = config({ app: { name: 'E', privacyPolicyUrl: 'https://example.com/p', platforms: ['android'] } as ShipConfig['app'] });
const x = wantedRevenueCat(c);
expect(x.products.every(p => p.store === 'play')).toBe(true);
expect(x.offering.packages.find(p => p.configId === 'com.example.app.pass_30d')).toBeUndefined();
const y = wantedRevenueCat(config({ products: [{ id: 'com.example.app.pass', type: 'non_renewing', usd: 1, listings: listing('Pass') }], subscriptions: [] } as Partial<ShipConfig>));
expect(y.products.map(p => p.type)).toEqual(['non_renewing_subscription', 'consumable']);
});
test('configured entitlements; unknown ids and consumables are problems; offering key', () => {
const c = config();
c.revenuecat = { projectId: PROJECT, apps: APPS, offering: 'main', entitlements: { premium: ['com.example.app.pro_yearly', 'com.example.app.coins_100', 'com.example.app.nope'] } };
const x = wantedRevenueCat(c);
expect(x.entitlements.map(e => [e.lookupKey, e.products])).toEqual([['premium', ['apple:com.example.app.pro_yearly', 'play:com.example.app.pro_yearly:annual']]]);
expect(x.problems).toHaveLength(2);
expect(x.offering.lookupKey).toBe('main');
// the lifetime product is in no entitlement: a custom package, not $rc_lifetime
expect(x.offering.packages.map(p => p.lookupKey)).not.toContain('$rc_lifetime');
});
});
test('resolveApps: config ids, else match by bundle id / package name', () => {
const c = config();
c.revenuecat = { projectId: PROJECT };
const apps = [
{ id: 'app_a', type: 'app_store', app_store: { bundle_id: 'com.example.app' } },
{ id: 'app_p', type: 'play_store', play_store: { package_name: 'com.example.other' } },
];
const r = resolveApps(c, apps);
expect(r.ids).toEqual({ apple: 'app_a' });
expect(r.problems[0]).toContain('no Play Store app for com.example.app');
});
// Full RevenueCat state for config(): everything in place.
function synced(): RcState {
const w = wantedRevenueCat(config());
const products = w.products.map((p, i) => ({ id: `prod_${i}`, store_identifier: p.storeIdentifier, type: p.type, app_id: APPS[p.store], state: 'active' }));
const id = (k: string) => products[w.products.findIndex(p => p.key === k)]!.id;
return {
products,
entitlements: [{ id: 'entl_1', lookup_key: 'pro', state: 'active', productIds: w.entitlements[0]!.products.map(id) }],
offerings: [{ id: 'ofrng_1', lookup_key: 'default', is_current: true, state: 'active',
packages: w.offering.packages.map((p, i) => ({ id: `pkge_${i}`, lookup_key: p.lookupKey, position: p.position, products: p.products.map(k => ({ product_id: id(k), eligibility_criteria: 'all' })) })) }],
};
}
describe('rcDiff', () => {
const w = wantedRevenueCat(config());
test('in sync', () => {
const rows = rcDiff(w, synced(), APPS);
expect(outOfSync(rows)).toBe(0);
expect(rows.every(r => r.status === 'ok')).toBe(true);
});
test('missing, extra and mismatched', () => {
const s = synced();
s.products = s.products.filter(p => p.store_identifier !== 'com.example.app.pro_yearly');
s.products.push({ id: 'prod_x', store_identifier: 'com.example.app.old', type: 'consumable', app_id: APPS.apple, state: 'active' });
s.products.push({ id: 'prod_web', store_identifier: 'prod_stripe', type: 'subscription', app_id: 'app_web', state: 'active' });
s.products.find(p => p.store_identifier === 'com.example.app.lifetime' && p.app_id === APPS.play)!.type = 'subscription';
s.entitlements.push({ id: 'entl_2', lookup_key: 'legacy', productIds: [] });
s.offerings[0]!.packages = s.offerings[0]!.packages.filter(p => p.lookup_key !== '$rc_annual');
s.offerings[0]!.packages.push({ id: 'pkge_x', lookup_key: 'promo', products: [] });
s.offerings[0]!.is_current = false;
const rows = rcDiff(w, s, APPS);
const find = (status: string, key: string) => rows.find(r => r.status === status && r.key === key);
expect(find('missing', 'apple:com.example.app.pro_yearly')).toBeTruthy();
expect(find('missing', 'pro <- apple:com.example.app.pro_yearly')).toBeTruthy();
expect(find('missing', '$rc_annual')).toBeTruthy();
expect(find('mismatch', 'play:com.example.app.lifetime')?.msg).toContain('type subscription');
expect(find('extra', 'apple:com.example.app.old')).toBeTruthy();
expect(find('extra', 'legacy')).toBeTruthy();
expect(find('extra', 'promo')).toBeTruthy();
expect(find('info', 'default')).toBeTruthy();
expect(rows.some(r => r.key.includes('prod_stripe'))).toBe(false); // other apps are ignored
expect(outOfSync(rows)).toBe(4);
expect(rows[0]!.status).toBe('mismatch');
});
test('a package holding another product for the same app is a mismatch, not an attach', () => {
const s = synced();
s.products.push({ id: 'prod_other', store_identifier: 'com.example.app.other_monthly', type: 'subscription', app_id: APPS.apple, state: 'active' });
const pk = s.offerings[0]!.packages.find(p => p.lookup_key === '$rc_monthly')!;
pk.products = pk.products.filter(x => s.products.find(p => p.id === x.product_id)!.app_id !== APPS.apple).concat({ product_id: 'prod_other' });
const rows = rcDiff(w, s, APPS);
expect(rows.find(r => r.key === '$rc_monthly <- apple:com.example.app.pro_monthly')?.status).toBe('mismatch');
expect(rcPlan(w, s, APPS).filter(x => x.op === 'attach-package')).toEqual([]);
});
});
describe('rcPlan', () => {
const w = wantedRevenueCat(config());
test('empty project: creates in dependency order, attaches with chunks, no set-current by default', () => {
const plan = rcPlan(w, { products: [], entitlements: [], offerings: [] }, APPS);
const ops = plan.map(s => s.op);
const first = (op: string) => ops.indexOf(op as never), last = (op: string) => ops.lastIndexOf(op as never);
expect(last('create-product')).toBeLessThan(first('create-entitlement'));
expect(first('create-entitlement')).toBeLessThan(first('attach-entitlement'));
expect(last('attach-entitlement')).toBeLessThan(first('create-offering'));
expect(first('create-offering')).toBeLessThan(first('create-package'));
expect(last('create-package')).toBeLessThan(first('attach-package'));
expect(ops.filter(o => o === 'create-product')).toHaveLength(10);
expect(ops).not.toContain('set-current');
expect(rcPlan(w, { products: [], entitlements: [], offerings: [] }, APPS, { current: true }).at(-1)!.op).toBe('set-current');
});
test('in sync: empty plan (idempotent); never deletes or detaches', () => {
expect(rcPlan(w, synced(), APPS)).toEqual([]);
const s = synced();
s.products.push({ id: 'prod_x', store_identifier: 'com.example.app.old', type: 'consumable', app_id: APPS.apple });
expect(rcPlan(w, s, APPS)).toEqual([]);
});
test('a store without a resolved app is skipped', () => {
const plan = rcPlan(w, { products: [], entitlements: [], offerings: [] }, { apple: APPS.apple });
expect(plan.some(s => JSON.stringify(s).includes('play:'))).toBe(false);
});
test('new package positions avoid taken ones', () => {
const s = synced();
s.offerings[0]!.packages = [{ id: 'pkge_x', lookup_key: 'promo', position: 1, products: [] }];
const pos = rcPlan(w, s, APPS).filter(x => x.op === 'create-package').map(x => (x as { body: { position: number } }).body.position);
expect(new Set(pos).size).toBe(pos.length);
expect(pos).not.toContain(1);
});
});
// ---- the command against a mocked fetch ----
interface Call { method: string; url: string; auth: string | null; body?: string }
const realFetch = globalThis.fetch;
const savedKey = process.env.REVENUECAT_SECRET_KEY;
let out: string[] = [];
const saved = { log: console.log, warn: console.warn, error: console.error };
const tty = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY');
beforeEach(() => {
out = [];
console.log = (...a: unknown[]) => { out.push(a.join(' ')); };
console.warn = console.log; console.error = console.log;
process.env.REVENUECAT_SECRET_KEY = KEY;
});
afterEach(() => {
globalThis.fetch = realFetch;
Object.assign(console, saved);
if (savedKey === undefined) delete process.env.REVENUECAT_SECRET_KEY; else process.env.REVENUECAT_SECRET_KEY = savedKey;
if (tty) Object.defineProperty(process.stdin, 'isTTY', tty); else delete (process.stdin as { isTTY?: boolean }).isTTY;
process.exitCode = 0;
});
const json = (o: unknown, status = 200, headers: Record<string, string> = {}) => new Response(JSON.stringify(o), { status, headers: { 'content-type': 'application/json', ...headers } });
const list = (items: unknown[], next: string | null = null) => ({ object: 'list', items, next_page: next, url: '/v2/x' });
function fake(route: (c: Call) => Response): Call[] {
const calls: Call[] = [];
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const c: Call = { method: init?.method ?? 'GET', url: String(input), auth: new Headers(init?.headers).get('authorization'), body: init?.body as string | undefined };
calls.push(c);
return route(c);
}) as typeof fetch;
return calls;
}
const ctx = (argv: string[], cfg = config()) => {
const root = mkdtempSync(join(tmpdir(), 'sb-rc-'));
return { loaded: { config: cfg, root, path: join(root, 'storebound.config.ts'), resolve: (p: string) => join(root, p) } as Loaded, args: parseArgs(argv) };
};
/** A RevenueCat project as GET answers it, products split over two pages. */
function project(s: RcState): (c: Call) => Response {
const P = `https://api.revenuecat.com/v2/projects/${PROJECT}`;
return c => {
if (c.method !== 'GET') return json({ id: `new_${c.url.split('/').at(-1)}` }, 201);
const u = new URL(c.url);
const path = u.origin + u.pathname;
if (path === `${P}/products`) {
const half = Math.ceil(s.products.length / 2);
return u.searchParams.get('starting_after') ? json(list(s.products.slice(half))) : json(list(s.products.slice(0, half), `/v2/projects/${PROJECT}/products?limit=100&starting_after=${s.products[half - 1]?.id}`));
}
if (path === `${P}/entitlements`) return json(list(s.entitlements.map(e => ({ object: 'entitlement', id: e.id, lookup_key: e.lookup_key, display_name: e.lookup_key, state: 'active' }))));
const ent = path.match(/entitlements\/([^/]+)\/products$/);
if (ent) return json(list(s.entitlements.find(e => e.id === ent[1])!.productIds.map(id => s.products.find(p => p.id === id))));
if (path === `${P}/offerings`) return json(list(s.offerings.map(o => ({ object: 'offering', id: o.id, lookup_key: o.lookup_key, is_current: o.is_current, state: 'active' }))));
const pk = path.match(/offerings\/([^/]+)\/packages$/);
if (pk) return json(list(s.offerings.find(o => o.id === pk[1])!.packages.map(p => ({ object: 'package', id: p.id, lookup_key: p.lookup_key, position: p.position }))));
const pp = path.match(/packages\/([^/]+)\/products$/);
if (pp) return json(list(s.offerings.flatMap(o => o.packages).find(p => p.id === pp[1])!.products.map(x => ({ product: s.products.find(p => p.id === x.product_id), eligibility_criteria: 'all' }))));
return json({ type: 'resource_missing', message: 'not found' }, 404);
};
}
describe('revenuecat command (mocked fetch)', () => {
test('diff reads every page, sends the Bearer key, in sync -> exit 0 and the scope footer', async () => {
const calls = fake(project(synced()));
await run(ctx(['diff']));
expect(calls.filter(c => c.url.includes('/products?')).length).toBeGreaterThanOrEqual(2);
expect(calls.some(c => c.url.includes('starting_after=prod_4'))).toBe(true);
expect(calls.every(c => c.auth === `Bearer ${KEY}` && c.url.startsWith('https://api.revenuecat.com/v2/'))).toBe(true);
expect(calls.every(c => c.method === 'GET')).toBe(true);
expect(process.exitCode).toBe(0);
expect(out.join('\n')).toContain('receipt / purchase token validation');
expect(out.join('\n')).not.toContain(KEY);
});
test('diff --json: stable shape; out of sync -> exit 1', async () => {
fake(project({ products: [], entitlements: [], offerings: [] }));
await run(ctx(['diff', '--json']));
const j = JSON.parse(out.find(l => l.startsWith('{'))!);
expect(Object.keys(j)).toEqual(['projectId', 'apps', 'outOfSync', 'rows', 'scope']);
expect(j.outOfSync).toBeGreaterThan(0);
expect(process.exitCode).toBe(1);
});
test('apps are looked up by bundle id / package name when not configured', async () => {
const cfg = config(); cfg.revenuecat = { projectId: PROJECT };
const base = project(synced());
const calls = fake(c => c.url.includes('/apps?') ? json(list([
{ object: 'app', id: APPS.apple, type: 'app_store', app_store: { bundle_id: 'com.example.app' } },
{ object: 'app', id: APPS.play, type: 'play_store', play_store: { package_name: 'com.example.app' } },
])) : base(c));
await run(ctx(['diff'], cfg));
expect(calls[0]!.url).toContain(`/projects/${PROJECT}/apps`);
expect(process.exitCode).toBe(0);
});
test('sync --dry sends no POST', async () => {
const calls = fake(project({ products: [], entitlements: [], offerings: [] }));
await run(ctx(['sync', '--dry']));
expect(calls.some(c => c.method !== 'GET')).toBe(false);
expect(out.join('\n')).toContain('create product apple:com.example.app.lifetime');
expect(out.join('\n')).toContain('dry run');
});
test('sync without a terminal and without --yes sends no POST', async () => {
Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true });
const calls = fake(project({ products: [], entitlements: [], offerings: [] }));
await run(ctx(['sync']));
expect(calls.some(c => c.method !== 'GET')).toBe(false);
expect(out.join('\n')).toContain('re-run with --yes');
});
test('sync --yes: POSTs in order with resolved ids and the documented bodies', async () => {
const calls = fake(project({ products: [], entitlements: [], offerings: [] }));
await run(ctx(['sync', '--yes']));
const posts = calls.filter(c => c.method === 'POST').map(c => new URL(c.url).pathname.replace(`/v2/projects/${PROJECT}`, ''));
expect(posts.slice(0, 10).every(p => p === '/products')).toBe(true);
expect(posts).toContain('/entitlements');
expect(posts).toContain('/entitlements/new_entitlements/actions/attach_products');
expect(posts).toContain('/offerings/new_offerings/packages');
expect(posts).toContain('/packages/new_packages/actions/attach_products');
const attach = calls.find(c => c.url.endsWith('/packages/new_packages/actions/attach_products'))!;
expect(JSON.parse(attach.body!).products[0]).toEqual({ product_id: 'new_products', eligibility_criteria: 'all' });
const prod = JSON.parse(calls.find(c => c.method === 'POST')!.body!);
expect(prod).toEqual({ store_identifier: 'com.example.app.lifetime', app_id: APPS.apple, type: 'non_consumable', display_name: 'Lifetime' });
});
test('a 401 names the key variable but never contains the key', async () => {
fake(() => json({ object: 'error', type: 'authentication_error', message: `Invalid API key ${KEY}`, retryable: false }, 401));
const err = await run(ctx(['diff'])).then(() => null, (e: Error) => e);
expect(err?.message).toContain('401');
expect(err?.message).toContain('REVENUECAT_SECRET_KEY');
expect(err?.message).not.toContain(KEY);
expect(out.join('\n')).not.toContain(KEY);
});
test('429 waits for Retry-After and retries; next_page off api.revenuecat.com is refused', async () => {
let n = 0;
fake(() => (n++ === 0 ? json({ object: 'error', type: 'rate_limit_error', backoff_ms: 0 }, 429, { 'retry-after': '0' }) : json(list([{ id: 'a' }]))));
expect(await rcClient(KEY).all('/projects/p/apps')).toEqual([{ id: 'a' }]);
expect(n).toBe(2);
fake(() => json(list([{ id: 'a' }], 'https://elsewhere.example.com/v2/x')));
await expect(rcClient(KEY).all('/projects/p/apps')).rejects.toThrow('refusing');
});
test('missing key: a clear error, no request', async () => {
delete process.env.REVENUECAT_SECRET_KEY;
const calls = fake(() => json({}));
await expect(run(ctx(['diff']))).rejects.toThrow('REVENUECAT_SECRET_KEY is not set');
expect(calls).toHaveLength(0);
});
});

View file

@ -202,6 +202,35 @@ describe('serve --stdio: session', () => {
await s.handle({ jsonrpc: '2.0', method: '$/cancelRequest', params: { id } }); await s.handle({ jsonrpc: '2.0', method: '$/cancelRequest', params: { id } });
expect(errOf(await pending).code).toBe(ERR.cancelled); expect(errOf(await pending).code).toBe(ERR.cancelled);
}); });
test('console.fill: desktop only (never MCP), answers as data in the dry run, browser only with a host token, cancel kills it', async () => {
expect(describeMethods().find(m => m.method === 'console.fill')).toMatchObject({ kind: 'write', json: true, network: true, destructive: false });
expect(DESKTOP_ONLY.some(t => t.name === 'console_fill')).toBe(true);
expect(TOOLS.some(t => t.name.startsWith('console') || t.command[0] === 'console')).toBe(false);
expect('console.fill').not.toMatch(FORBIDDEN_METHOD_WORDS);
let now = 9_000_000;
const answers = { form: 'apple-age-rating', store: 'apple', title: 'Age rating', url: 'https://appstoreconnect.apple.com/', answers: [{ id: 'violence', label: 'Cartoon violence', value: 'None', certain: true, source: 'apple.ageRating' }], uncertain: 0, guidance: [] };
const { s, call, calls, nextId } = await session(argv => (argv.includes('--dry') ? { data: answers } : { wait: new Promise(() => {}) }), () => now);
const p = { project: DEMO, args: { form: 'apple-age-rating' } };
expect(resOf(await call('console.fill', p))).toMatchObject({ dryRun: true, data: { answers: [{ id: 'violence' }] } });
expect(calls.at(-1)!.argv).toEqual(['console', 'fill', 'apple-age-rating', '--dry', '--json']);
expect(calls.at(-1)!.o.env?.STOREBOUND_OWNER_CONFIRMED).toBeUndefined();
await call('console.fill', { project: DEMO, args: { form: 'play-content-rating', store: 'play' } });
expect(calls.at(-1)!.argv).toEqual(['console', 'fill', 'play-content-rating', '--store', 'play', '--dry', '--json']);
for (const args of [{ form: 'apple-submit' }, { form: 'apple-age-rating', store: 'web' }, {}, { form: '--yes' }])
expect(errOf(await call('console.fill', { project: DEMO, args })).code).toBe(ERR.invalidParams);
expect(errOf(await call('console.fill', { ...p, dryRun: false })).code).toBe(ERR.confirmRequired);
const n = calls.length;
// real run: waits for the owner (no timeout), the token answers the command's own question, a cancel stops it
const id = nextId();
const pending = call('console.fill', { ...p, dryRun: false, confirmToken: mint(SECRET, 'console.fill', p, { now }) });
await Bun.sleep(5);
expect(calls.length).toBe(n + 1);
expect(calls.at(-1)!.argv).toEqual(['console', 'fill', 'apple-age-rating', '--json']);
expect(calls.at(-1)!.o.env?.STOREBOUND_OWNER_CONFIRMED).toBe('1');
now += 600_000;
await s.handle({ jsonrpc: '2.0', method: '$/cancelRequest', params: { id } });
expect(errOf(await pending).code).toBe(ERR.cancelled);
});
test('portfolio.status: apps across platforms, release trains, catalog parity, per-app errors, progress n/total', async () => { test('portfolio.status: apps across platforms, release trains, catalog parity, per-app errors, progress n/total', async () => {
const summary = { dir: DEMO, name: 'Demo', apple: { bundleId: 'com.example.demo', appId: null }, play: { packageName: 'com.example.demo' }, platforms: ['ios', 'android'], products: 2, productIds: ['coins', 'no_ads'], subscriptions: 0, subscriptionIds: [], catalog: { ios: ['coins', 'no_ads'], android: ['coins', 'no_ads'] } }; const summary = { dir: DEMO, name: 'Demo', apple: { bundleId: 'com.example.demo', appId: null }, play: { packageName: 'com.example.demo' }, platforms: ['ios', 'android'], products: 2, productIds: ['coins', 'no_ads'], subscriptions: 0, subscriptionIds: [], catalog: { ios: ['coins', 'no_ads'], android: ['coins', 'no_ads'] } };
const { call, sent } = await session(argv => argv[0] === 'inspect' ? { data: summary } const { call, sent } = await session(argv => argv[0] === 'inspect' ? { data: summary }

215
tests/web.test.ts Normal file
View file

@ -0,0 +1,215 @@
// web init / web check: builders (exact JSON), validators, live checks against a local server, init into a temp dir.
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { ShipConfig } from '../cli/lib/config';
import { TEMPLATE_TEXT } from '../cli/lib/template-files';
import {
aasaFor, assetLinksFor, checkLanding, fillLanding, HANDLE_ALL_URLS, normalizeFingerprint, planWeb, smartBannerTag,
validateAasa, validateAssetLinks, webIdsOf,
} from '../cli/lib/web';
import { checkSite } from '../cli/web';
const ROOT = join(import.meta.dir, '..');
const fp = Array.from({ length: 32 }, (_, i) => (i * 7 % 256).toString(16).toUpperCase().padStart(2, '0')).join(':');
const fp2 = Array.from({ length: 32 }, (_, i) => (255 - i).toString(16).toUpperCase().padStart(2, '0')).join(':');
const cfg: ShipConfig = {
app: { name: 'Example & Co', privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', termsUrl: 'https://example.com/terms', website: 'https://example.com', contactEmail: 'hi@example.com' },
languages: [{ id: 'en', play: 'en-US', apple: 'en-US' }],
apple: { bundleId: 'com.example.app', teamId: 'ABCDEFGHIJ', appId: '123456789' },
play: { packageName: 'com.example.app' },
web: { domain: 'links.example.com', paths: ['/invite/*'], exclude: ['/admin/*'], androidSha256: [fp], webcredentials: true },
};
const ids = webIdsOf(cfg);
const problems = (f: { level: string; message: string }[]) => f.filter(x => x.level === 'problem').map(x => x.message);
describe('builders', () => {
test('apple-app-site-association: exact JSON, excludes first', () => {
expect(aasaFor(cfg)).toEqual({
applinks: { details: [{ appIDs: ['ABCDEFGHIJ.com.example.app'], components: [{ '/': '/admin/*', exclude: true, comment: 'stays in the browser' }, { '/': '/invite/*' }] }] },
webcredentials: { apps: ['ABCDEFGHIJ.com.example.app'] },
});
expect(aasaFor({ ...cfg, web: undefined })).toEqual({ applinks: { details: [{ appIDs: ['ABCDEFGHIJ.com.example.app'], components: [{ '/': '/*' }] }] } });
expect(aasaFor({ ...cfg, apple: { bundleId: 'com.example.app' } })).toBeNull();
});
test('assetlinks.json: exact JSON, dynamic rules only with excludes', () => {
expect(assetLinksFor({ ...cfg, web: { domain: 'links.example.com', androidSha256: [fp] } })).toEqual([
{ relation: [HANDLE_ALL_URLS], target: { namespace: 'android_app', package_name: 'com.example.app', sha256_cert_fingerprints: [fp] } },
]);
expect(assetLinksFor(cfg)![0]!.relation_extensions).toEqual({ [HANDLE_ALL_URLS]: { dynamic_app_link_components: [{ '/': '/admin/*', exclude: true }, { '/': '/invite/*' }] } });
expect(assetLinksFor({ ...cfg, web: { domain: 'links.example.com' } })).toBeNull();
});
test('Smart App Banner tag and landing page', () => {
expect(smartBannerTag(cfg)).toBe('<meta name="apple-itunes-app" content="app-id=123456789">');
expect(smartBannerTag(cfg, 'https://links.example.com/invite/1')).toBe('<meta name="apple-itunes-app" content="app-id=123456789, app-argument=https://links.example.com/invite/1">');
expect(smartBannerTag({ ...cfg, apple: { bundleId: 'com.example.app' } })).toBeNull();
const html = fillLanding(TEMPLATE_TEXT['web/landing.html']!, cfg);
expect(html).toContain('<meta name="apple-itunes-app" content="app-id=123456789">');
expect(html).toContain('<title>Example &amp; Co</title>');
expect(html).toContain('href="https://apps.apple.com/app/id123456789"');
expect(html).toContain('href="https://play.google.com/store/apps/details?id=com.example.app"');
expect(html).toContain('href="https://example.com/terms"');
expect(html).toContain('App Store is a trademark of Apple Inc.; Google Play is a trademark of Google LLC.');
expect(html).not.toMatch(/\{\{|<!--\/?(apple|play|terms)-->/);
expect(html).not.toMatch(/https?:\/\/(?!apps\.apple\.com|play\.google\.com|example\.com)/);
const playOnly = fillLanding(TEMPLATE_TEXT['web/landing.html']!, { ...cfg, apple: undefined, app: { ...cfg.app, termsUrl: undefined } });
expect(playOnly).not.toContain('apple-itunes-app');
expect(playOnly).not.toContain('apps.apple.com');
expect(playOnly).not.toContain('Terms of Use');
expect(playOnly).toContain('Google Play</a>');
});
test('fingerprints from the Play API: hex, colon hex, base64, base64url', () => {
const hex = fp.replace(/:/g, '');
const b64 = Buffer.from(hex, 'hex').toString('base64');
expect(normalizeFingerprint(hex.toLowerCase())).toBe(fp);
expect(normalizeFingerprint(fp.toLowerCase())).toBe(fp);
expect(normalizeFingerprint(b64)).toBe(fp);
expect(normalizeFingerprint(b64.replace(/=$/, '').replace(/\+/g, '-').replace(/\//g, '_'))).toBe(fp);
expect(normalizeFingerprint('abcd')).toBeNull();
});
test('plan: missing inputs are skipped with the fix, not errors', () => {
const p = planWeb({ ...cfg, apple: { bundleId: 'com.example.app' }, web: { domain: 'links.example.com' } }, { landing: false });
expect(p.files).toEqual([]);
expect(p.skipped.join('\n')).toContain('apple.teamId');
expect(p.skipped.join('\n')).toContain('Play app signing');
expect(p.skipped.join('\n')).toContain('apple.appId');
const full = planWeb(cfg, { landing: true, template: TEMPLATE_TEXT['web/landing.html'], marks: { appstore: 'a', googleplay: 'g' } });
expect(full.files.map(f => f.path)).toEqual(['.well-known/apple-app-site-association', '.well-known/assetlinks.json', 'smart-app-banner.html', 'index.html', 'appstore.svg', 'googleplay.svg']);
expect(full.skipped).toEqual([]);
});
});
describe('validators', () => {
const aasa = aasaFor(cfg)!;
const links = assetLinksFor(cfg)!;
test('good files pass', () => {
expect(problems(validateAasa(aasa, ids))).toEqual([]);
expect(problems(validateAssetLinks(links, ids))).toEqual([]);
});
test('AASA: wrong team id, empty components, legacy format, missing webcredentials', () => {
const wrong = aasaFor({ ...cfg, apple: { ...cfg.apple!, teamId: 'ZYXWVUTSRQ' } });
expect(problems(validateAasa(wrong, ids)).join()).toContain('does not list ABCDEFGHIJ.com.example.app');
expect(problems(validateAasa({ applinks: { details: [{ appIDs: ['ABCDEFGHIJ.com.example.app'], components: [] }] } }, ids)).join()).toContain('no URL opens the app');
expect(problems(validateAasa({ applinks: { details: [{ appIDs: ['ABCDEFGHIJ.com.example.app'], components: [{ '/': '/*', exclude: true }] }] } }, ids)).join()).toContain('every component is excluded');
const legacy = validateAasa({ applinks: { apps: [], details: [{ appID: 'ABCDEFGHIJ.com.example.app', paths: ['*'] }] } }, { teamId: 'ABCDEFGHIJ', bundleId: 'com.example.app' });
expect(problems(legacy)).toEqual([]);
expect(legacy.some(x => x.level === 'info' && /legacy/.test(x.message))).toBe(true);
expect(problems(validateAasa({ applinks: { details: [{ appIDs: ['ABCDEFGHIJ.com.example.app'], components: [{ '/': '/*' }] }] } }, ids)).join()).toContain('no "webcredentials" section');
expect(problems(validateAasa([], ids))).toEqual(['not a JSON object']);
});
test('assetlinks: missing fingerprint, extra fingerprint, wrong relation, wrong package, object instead of list', () => {
const extra = validateAssetLinks(assetLinksFor(cfg, [fp, fp2]), ids);
expect(problems(extra)).toEqual([]);
expect(extra.some(x => x.level === 'info' && /extra fingerprint/.test(x.message))).toBe(true);
expect(problems(validateAssetLinks(assetLinksFor(cfg, [fp2]), ids)).join()).toContain('is missing');
const rel = [{ relation: ['delegate_permission/common.get_login_creds'], target: { namespace: 'android_app', package_name: 'com.example.app', sha256_cert_fingerprints: [fp] } }];
expect(problems(validateAssetLinks(rel, ids)).join()).toContain(`not ${HANDLE_ALL_URLS}`);
expect(problems(validateAssetLinks(assetLinksFor({ ...cfg, play: { packageName: 'com.example.other' } }), ids)).join()).toContain('no android_app statement for com.example.app');
expect(problems(validateAssetLinks(links[0], ids)).join()).toContain('not a list of statements');
const lower = [{ relation: [HANDLE_ALL_URLS], target: { namespace: 'android_app', package_name: 'com.example.app', sha256_cert_fingerprints: [fp.toLowerCase()] } }];
expect(problems(validateAssetLinks(lower, ids)).join()).toContain('AB:CD');
});
test('landing: Smart App Banner app-id', () => {
const page = (body: string) => ({ url: 'https://links.example.com/', status: 200, contentType: 'text/html', body, bytes: body.length });
expect(checkLanding(page('<head><meta name="apple-itunes-app" content="app-id=123456789"></head>'), ids)[0]!.level).toBe('ok');
expect(checkLanding(page('<head><meta name="apple-itunes-app" content="app-id=1"></head>'), ids)[0]!.level).toBe('problem');
expect(checkLanding(page('<head></head>'), ids)[0]!.level).toBe('problem');
});
});
describe('web check against a local server', () => {
type Route = { status?: number; type?: string; body?: string; location?: string };
let routes: Record<string, Route> = {};
let server: ReturnType<typeof Bun.serve>;
let base = '';
beforeAll(() => {
server = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch(req) {
const r = routes[new URL(req.url).pathname];
if (!r) return new Response('<html>not found</html>', { status: 404, headers: { 'content-type': 'text/html' } });
return new Response(r.body ?? '', { status: r.status ?? 200, headers: { ...(r.type ? { 'content-type': r.type } : {}), ...(r.location ? { location: r.location } : {}) } });
} });
base = `http://127.0.0.1:${server.port}`;
});
afterAll(() => server.stop(true));
const good = (): Record<string, Route> => ({
'/.well-known/apple-app-site-association': { type: 'application/json', body: JSON.stringify(aasaFor(cfg)) },
'/.well-known/assetlinks.json': { type: 'application/json', body: JSON.stringify(assetLinksFor(cfg)) },
'/': { type: 'text/html', body: fillLanding(TEMPLATE_TEXT['web/landing.html']!, cfg) },
});
test('good site: no problems, legacy path is informational', async () => {
routes = good();
const c = await checkSite(base, ids, { landing: true });
expect(c.filter(x => !x.ok)).toEqual([]);
expect(c.find(x => x.id === 'aasa-legacy')!.level).toBe('info');
expect(c.find(x => x.id === 'landing')!.level).toBe('ok');
expect(c.every(x => typeof x.url === 'string' && typeof x.message === 'string')).toBe(true);
});
test('redirect is a problem and is not followed', async () => {
routes = { ...good(), '/.well-known/apple-app-site-association': { status: 301, location: 'https://www.links.example.com/.well-known/apple-app-site-association' } };
const c = await checkSite(base, ids);
const bad = c.filter(x => x.id === 'aasa' && !x.ok);
expect(bad).toHaveLength(1);
expect(bad[0]!.message).toContain('HTTP 301 redirect to https://www.links.example.com');
});
test('text/plain content type and an HTML fallback page are problems', async () => {
routes = { ...good(), '/.well-known/assetlinks.json': { type: 'text/plain', body: JSON.stringify(assetLinksFor(cfg)) }, '/.well-known/apple-app-site-association': { type: 'application/json', body: '<!doctype html><html></html>' } };
const c = await checkSite(base, ids);
expect(c.filter(x => !x.ok).map(x => `${x.id}: ${x.message}`)).toEqual([
'aasa: the body is an HTML page, not JSON (a single-page-app fallback or a custom 404 page?)',
'assetlinks: content-type is "text/plain", not application/json',
]);
});
test('missing files and wrong ids', async () => {
routes = { '/.well-known/apple-app-site-association': { type: 'application/json', body: JSON.stringify(aasaFor({ ...cfg, apple: { ...cfg.apple!, teamId: 'ZYXWVUTSRQ' } })) } };
const c = await checkSite(base, ids);
expect(c.filter(x => !x.ok).map(x => x.id)).toEqual(['aasa', 'aasa', 'assetlinks']); // appIDs and webcredentials.apps
expect(c.find(x => x.id === 'assetlinks')!.message).toBe('HTTP 404');
});
});
describe('web init (CLI)', () => {
const project = () => {
const d = mkdtempSync(join(tmpdir(), 'sb-web-'));
const c = { ...cfg, web: { ...cfg.web!, landing: true } };
writeFileSync(join(d, 'storebound.config.json'), JSON.stringify(c));
return d;
};
const cli = (d: string, ...args: string[]) => Bun.spawnSync(['bun', join(ROOT, 'cli/index.ts'), 'web', 'init', ...args], { cwd: d, env: { ...process.env, NO_COLOR: '1' } });
test('--dry prints the files and writes nothing', () => {
const d = project();
try {
const r = cli(d, '--dry');
expect(r.exitCode).toBe(0);
const out = r.stdout.toString();
expect(out).toContain('would write web/.well-known/apple-app-site-association');
expect(out).toContain('"ABCDEFGHIJ.com.example.app"');
expect(out).toContain('<meta name="apple-itunes-app" content="app-id=123456789">');
expect(readdirSync(d)).toEqual(['storebound.config.json']);
} finally { rmSync(d, { recursive: true, force: true }); }
}, 30_000);
test('writes the files, then reports unchanged / updated', () => {
const d = project();
try {
const first = cli(d, '--json');
expect(first.exitCode).toBe(0);
const j = JSON.parse(first.stdout.toString());
expect(j.files.map((f: { path: string; status: string }) => `${f.status} ${f.path}`)).toEqual([
'new web/.well-known/apple-app-site-association', 'new web/.well-known/assetlinks.json', 'new web/smart-app-banner.html',
'new web/index.html', 'new web/appstore.svg', 'new web/googleplay.svg',
]);
expect(j.skipped).toEqual([]);
expect(JSON.parse(readFileSync(join(d, 'web/.well-known/assetlinks.json'), 'utf8'))).toEqual(assetLinksFor(cfg));
expect(readFileSync(join(d, 'web/appstore.svg'), 'utf8')).toBe(readFileSync(join(ROOT, 'templates/web/appstore.svg'), 'utf8'));
writeFileSync(join(d, 'web/smart-app-banner.html'), 'old');
const second = JSON.parse(cli(d, '--json').stdout.toString());
expect(second.files.filter((f: { status: string }) => f.status !== 'unchanged').map((f: { path: string; status: string }) => `${f.status} ${f.path}`)).toEqual(['updated web/smart-app-banner.html']);
mkdirSync(join(d, 'site'));
expect(cli(d, '--out', 'site', '--json').exitCode).toBe(0);
expect(existsSync(join(d, 'site/.well-known/apple-app-site-association'))).toBe(true);
} finally { rmSync(d, { recursive: true, force: true }); }
}, 30_000);
});

View file

@ -5,6 +5,7 @@
// apps/desktop/src/ui/store-marks the same two store marks for the desktop app (the other desktop icons come from // apps/desktop/src/ui/store-marks the same two store marks for the desktop app (the other desktop icons come from
// @phosphor-icons/react) // @phosphor-icons/react)
// media/teaser/icons Phosphor icons for the teaser video (the mouse cursor, the inbox, finding and fix icons) // media/teaser/icons Phosphor icons for the teaser video (the mouse cursor, the inbox, finding and fix icons)
// templates/web the two store marks for the landing page `storebound web init --landing` writes
// Both show them as CSS masks (site/style.css .ic-*, desktop styles.css .store-mark), so they take the text colour in // Both show them as CSS masks (site/style.css .ic-*, desktop styles.css .store-mark), so they take the text colour in
// both themes and nothing is loaded from outside. The store marks only name the store next to its name; they are // both themes and nothing is loaded from outside. The store marks only name the store next to its name; they are
// trademarks of Apple Inc. and Google LLC (docs/desktop.md, the site footer). // trademarks of Apple Inc. and Google LLC (docs/desktop.md, the site footer).
@ -25,6 +26,7 @@ const simple = join(root, 'node_modules/simple-icons');
export const ICON_DIR = join(root, 'site/img/icons'); export const ICON_DIR = join(root, 'site/img/icons');
export const MARK_DIR = join(root, 'apps/desktop/src/ui/store-marks'); export const MARK_DIR = join(root, 'apps/desktop/src/ui/store-marks');
export const TEASER_DIR = join(root, 'media/teaser/icons'); export const TEASER_DIR = join(root, 'media/teaser/icons');
export const WEB_DIR = join(root, 'templates/web');
/** [vendored dir, file name, package file] for every vendored icon. */ /** [vendored dir, file name, package file] for every vendored icon. */
function plan(): [string, string, string][] { function plan(): [string, string, string][] {
@ -33,6 +35,7 @@ function plan(): [string, string, string][] {
...SITE_ICONS.map(n => [ICON_DIR, `${n}.svg`, join(phosphor, 'assets/regular', `${n}.svg`)] as [string, string, string]), ...SITE_ICONS.map(n => [ICON_DIR, `${n}.svg`, join(phosphor, 'assets/regular', `${n}.svg`)] as [string, string, string]),
...marks.map(([f, src]) => [ICON_DIR, f, src] as [string, string, string]), ...marks.map(([f, src]) => [ICON_DIR, f, src] as [string, string, string]),
...marks.map(([f, src]) => [MARK_DIR, f, src] as [string, string, string]), ...marks.map(([f, src]) => [MARK_DIR, f, src] as [string, string, string]),
...marks.map(([f, src]) => [WEB_DIR, f, src] as [string, string, string]),
...TEASER_ICONS.map(([w, n]) => [TEASER_DIR, `${n}-${w}.svg`, join(phosphor, 'assets', w, `${n}-${w}.svg`)] as [string, string, string]), ...TEASER_ICONS.map(([w, n]) => [TEASER_DIR, `${n}-${w}.svg`, join(phosphor, 'assets', w, `${n}-${w}.svg`)] as [string, string, string]),
]; ];
} }
@ -48,7 +51,7 @@ export function checkSiteIcons(): string[] {
if (!existsSync(at)) out.push(`${rel(at)} missing (bun tools/site-icons.ts)`); if (!existsSync(at)) out.push(`${rel(at)} missing (bun tools/site-icons.ts)`);
else if (readFileSync(at, 'utf8') !== readFileSync(src, 'utf8')) out.push(`${rel(at)} is not ${rel(src).replace('node_modules/', '')}`); else if (readFileSync(at, 'utf8') !== readFileSync(src, 'utf8')) out.push(`${rel(at)} is not ${rel(src).replace('node_modules/', '')}`);
} }
for (const dir of [ICON_DIR, MARK_DIR, TEASER_DIR]) { for (const dir of [ICON_DIR, MARK_DIR, TEASER_DIR, WEB_DIR]) {
if (!existsSync(dir)) continue; if (!existsSync(dir)) continue;
for (const f of readdirSync(dir)) if (f.endsWith('.svg') && !p.some(([d, n]) => d === dir && n === f)) out.push(`${rel(join(dir, f))} is not a vendored icon`); for (const f of readdirSync(dir)) if (f.endsWith('.svg') && !p.some(([d, n]) => d === dir && n === f)) out.push(`${rel(join(dir, f))} is not a vendored icon`);
} }
@ -65,10 +68,10 @@ if (import.meta.main) {
for (const b of bad) console.error(`site-icons: ${b}`); for (const b of bad) console.error(`site-icons: ${b}`);
process.exit(bad.length ? 1 : 0); process.exit(bad.length ? 1 : 0);
} }
for (const dir of [ICON_DIR, MARK_DIR, TEASER_DIR]) mkdirSync(dir, { recursive: true }); for (const dir of [ICON_DIR, MARK_DIR, TEASER_DIR, WEB_DIR]) mkdirSync(dir, { recursive: true });
for (const [dir, f, src] of plan()) writeFileSync(join(dir, f), readFileSync(src)); for (const [dir, f, src] of plan()) writeFileSync(join(dir, f), readFileSync(src));
writeFileSync(join(ICON_DIR, 'LICENSE.txt'), `Icons in this folder, copied unchanged by tools/site-icons.ts:\n\nPhosphor ${version(phosphor)} (https://phosphoricons.com), regular weight, from the @phosphor-icons/core\npackage.\n\n${readFileSync(join(phosphor, 'LICENSE'), 'utf8')}\n\n${simpleNote()}`); writeFileSync(join(ICON_DIR, 'LICENSE.txt'), `Icons in this folder, copied unchanged by tools/site-icons.ts:\n\nPhosphor ${version(phosphor)} (https://phosphoricons.com), regular weight, from the @phosphor-icons/core\npackage.\n\n${readFileSync(join(phosphor, 'LICENSE'), 'utf8')}\n\n${simpleNote()}`);
writeFileSync(join(TEASER_DIR, 'LICENSE.txt'), `Icons in this folder, copied unchanged by tools/site-icons.ts:\n\nPhosphor ${version(phosphor)} (https://phosphoricons.com), from the @phosphor-icons/core package.\n\n${readFileSync(join(phosphor, 'LICENSE'), 'utf8')}`); writeFileSync(join(TEASER_DIR, 'LICENSE.txt'), `Icons in this folder, copied unchanged by tools/site-icons.ts:\n\nPhosphor ${version(phosphor)} (https://phosphoricons.com), from the @phosphor-icons/core package.\n\n${readFileSync(join(phosphor, 'LICENSE'), 'utf8')}`);
writeFileSync(join(MARK_DIR, 'LICENSE.txt'), `Store marks in this folder, copied unchanged by tools/site-icons.ts.\n\n${simpleNote()}`); writeFileSync(join(MARK_DIR, 'LICENSE.txt'), `Store marks in this folder, copied unchanged by tools/site-icons.ts.\n\n${simpleNote()}`);
console.log(`site-icons: ${SITE_ICONS.length} Phosphor icons ${version(phosphor)} and ${STORE_MARKS.length} simple-icons ${version(simple)} store marks and ${TEASER_ICONS.length} teaser icons -> site/img/icons/, apps/desktop/src/ui/store-marks/, media/teaser/icons/`); console.log(`site-icons: ${SITE_ICONS.length} Phosphor icons ${version(phosphor)} and ${STORE_MARKS.length} simple-icons ${version(simple)} store marks and ${TEASER_ICONS.length} teaser icons -> site/img/icons/, apps/desktop/src/ui/store-marks/, media/teaser/icons/, templates/web/`);
} }

44
tools/update-ppp.ts Normal file
View file

@ -0,0 +1,44 @@
#!/usr/bin/env bun
// Refreshes the bundled PPP dataset of `storebound prices ppp` from the World Bank API (read-only public API, no key).
// bun tools/update-ppp.ts fetch PA.NUS.PPP + PA.NUS.FCRF, rewrite cli/data/ppp-worldbank.json (retrieved = today)
// bun tools/update-ppp.ts --check print the bundled file's age and data year, write nothing
// bun tools/update-ppp.ts --bigmac [--project <dir>] [--dry]
// download The Economist Big Mac index into <dir>/.storebound/ppp-bigmac.json
// (not bundled: the repo's licence leaves third-party data out; same as
// `storebound prices ppp --update-bigmac`)
// Not run in CI (network). Sources: https://data.worldbank.org/indicator/PA.NUS.PPP,
// https://data.worldbank.org/indicator/PA.NUS.FCRF, https://github.com/TheEconomist/big-mac-data
import { readFileSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { parseArgs } from '../cli/lib/args';
import { datasetJson, datasetProblems, type PppDataset, WB, worldBankDataset } from '../cli/lib/ppp';
import { updateBigMac } from '../cli/prices-ppp';
const FILE = join(import.meta.dir, '..', 'cli', 'data', 'ppp-worldbank.json');
const a = parseArgs(process.argv.slice(2), ['check', 'bigmac']);
const today = new Date().toISOString().slice(0, 10);
async function json(url: string): Promise<never> {
const r = await fetch(url);
if (!r.ok) throw new Error(`${url} -> ${r.status}`);
return (await r.json()) as never;
}
if (a.has('check')) {
const ds = JSON.parse(readFileSync(FILE, 'utf8')) as PppDataset;
const days = Math.round((Date.parse(today) - Date.parse(ds.retrieved)) / 86_400_000);
console.log(`ppp-worldbank.json: retrieved ${ds.retrieved} (${days} days ago), data up to ${ds.year}, ${Object.keys(ds.countries).length} countries${days > 365 ? ' - older than a year: run bun tools/update-ppp.ts' : ''}`);
const p = datasetProblems(ds);
if (p.length) { console.error(p.join('\n')); process.exit(1); }
} else if (a.has('bigmac')) {
await updateBigMac(resolve(a.str('project', process.cwd())), a.has('dry'));
} else {
const to = new Date().getFullYear();
const [ppp, fx, countries] = await Promise.all([json(WB.api(WB.ppp, 2018, to)), json(WB.api(WB.fx, 2018, to)), json(WB.countries)]);
const ds = worldBankDataset(ppp, fx, countries, today);
const p = datasetProblems(ds);
if (p.length) throw new Error(p.join('; '));
writeFileSync(FILE, datasetJson(ds));
console.log(`wrote ${FILE}: ${Object.keys(ds.countries).length} countries, data up to ${ds.year}, retrieved ${today}`);
for (const n of ds.notes ?? []) console.log(` note: ${n}`);
}