Merge remote-tracking branch 'origin/main' into growth-extras
# Conflicts: # cli/index.ts # cli/lib/config.ts # cli/lib/credentials.ts # docs/desktop.md # templates/credentials.example.json # tools/site-icons.ts
This commit is contained in:
commit
743fd0ddc6
271 changed files with 296378 additions and 1375 deletions
|
|
@ -14,9 +14,10 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
|||
chat). storebound's MCP server does not offer these at all.
|
||||
2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run, then run it
|
||||
for real only after the owner agrees.
|
||||
3. **Read before you write.** `storebound check` (offline) and `storebound validate` (read-only, both stores) tell you
|
||||
what is missing and in which order to fix it.
|
||||
4. **Credentials only from the environment or `.storebound/`** in the project (gitignored). Never ask for keys,
|
||||
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
|
||||
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
|
||||
4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
|
||||
(`~/.storebound/credentials/<profile>.json`, named by `--account <profile>` or a workspace). Never ask for keys,
|
||||
passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes
|
||||
for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there.
|
||||
5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating,
|
||||
|
|
@ -34,7 +35,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
|||
|
||||
- CLI: `storebound <command>` (`storebound help`); config `storebound.config.ts`, credentials in env or `.storebound/`.
|
||||
- MCP: `storebound mcp` (stdio). MCP 2026-07-28 + 2025-11-25. Write tools default to `dry_run: true`; submit / release / cancel / delete / send are not exposed.
|
||||
- Readiness: `storebound check` (offline), `storebound validate` (read-only, both stores).
|
||||
- Readiness: `storebound scan` (offline rejection risks in the project files), `storebound check` (offline), `storebound validate` (read-only, both stores).
|
||||
- Every endpoint: `storebound api apple|play <operationId>` (skill store-api). GETs run; writes are dry unless the owner adds `--yes` in a terminal; MCP has the read-only `api_get`.
|
||||
|
||||
## Skills
|
||||
|
||||
|
|
@ -43,8 +45,10 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
|||
- `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-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/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/build-and-sign/SKILL.md`: Sign, build and upload a mobile app or game from the terminal
|
||||
- `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/play-first-release/SKILL.md`: Step-by-step first (and later) Google Play release of a mobile app or game
|
||||
|
|
@ -55,7 +59,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
|||
- `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-replies/SKILL.md`: Reply to App Store and Google Play reviews of a mobile app or game the safe way
|
||||
- `skills/store-analytics/SKILL.md`: Take store analytics snapshots for a mobile app or game (App Store impressions, product page views, downloads and conversion through the Analytics Reports API; Google Play store listing visitors, acquisitions and installs from the Play reports bucket) and compare them with listing, screenshot and experiment changes from git
|
||||
- `skills/store-analytics/SKILL.md`: Take store analytics snapshots for a mobile app or game (App Store impressions, product page views, downloads and conversion through the Analytics Reports API; Google Play store listing visitors, acquisitions and installs from the Play reports bucket) and compare them with listing, screenshot and experiment changes from git; download App Store sales / finance reports and Play earnings / sales reports with a summary per product and currency
|
||||
- `skills/store-api/SKILL.md`: Call any App Store Connect API or Google Play Developer API operation that storebound's commands do not wrap, safely
|
||||
- `skills/store-declarations/SKILL.md`: Answer the store compliance forms for a mobile app or game
|
||||
- `skills/store-health/SKILL.md`: Watch a released mobile app's or game's crash and ANR health on both stores
|
||||
- `skills/store-iap-setup/SKILL.md`: Create and price in-app purchases (consumables, non-consumables like "remove ads" or a Pro unlock, non-renewing passes, coin/gem packs, starter packs) on Google Play and App Store Connect from one product list
|
||||
|
|
|
|||
15
.github/copilot-instructions.md
vendored
15
.github/copilot-instructions.md
vendored
|
|
@ -14,9 +14,10 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
|||
chat). storebound's MCP server does not offer these at all.
|
||||
2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run, then run it
|
||||
for real only after the owner agrees.
|
||||
3. **Read before you write.** `storebound check` (offline) and `storebound validate` (read-only, both stores) tell you
|
||||
what is missing and in which order to fix it.
|
||||
4. **Credentials only from the environment or `.storebound/`** in the project (gitignored). Never ask for keys,
|
||||
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
|
||||
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
|
||||
4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
|
||||
(`~/.storebound/credentials/<profile>.json`, named by `--account <profile>` or a workspace). Never ask for keys,
|
||||
passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes
|
||||
for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there.
|
||||
5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating,
|
||||
|
|
@ -34,7 +35,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
|||
|
||||
- CLI: `storebound <command>` (`storebound help`); config `storebound.config.ts`, credentials in env or `.storebound/`.
|
||||
- MCP: `storebound mcp` (stdio). MCP 2026-07-28 + 2025-11-25. Write tools default to `dry_run: true`; submit / release / cancel / delete / send are not exposed.
|
||||
- Readiness: `storebound check` (offline), `storebound validate` (read-only, both stores).
|
||||
- Readiness: `storebound scan` (offline rejection risks in the project files), `storebound check` (offline), `storebound validate` (read-only, both stores).
|
||||
- Every endpoint: `storebound api apple|play <operationId>` (skill store-api). GETs run; writes are dry unless the owner adds `--yes` in a terminal; MCP has the read-only `api_get`.
|
||||
|
||||
## Skills
|
||||
|
||||
|
|
@ -45,8 +47,10 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
|||
| `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-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 |
|
||||
| `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 |
|
||||
| `build-and-sign` | Sign, build and upload a mobile app or game from the terminal |
|
||||
| `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` |
|
||||
| `play-first-release` | Step-by-step first (and later) Google Play release of a mobile app or game |
|
||||
|
|
@ -57,7 +61,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
|||
| `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-replies` | Reply to App Store and Google Play reviews of a mobile app or game the safe way |
|
||||
| `store-analytics` | Take store analytics snapshots for a mobile app or game (App Store impressions, product page views, downloads and conversion through the Analytics Reports API; Google Play store listing visitors, acquisitions and installs from the Play reports bucket) and compare them with listing, screenshot and experiment changes from git |
|
||||
| `store-analytics` | Take store analytics snapshots for a mobile app or game (App Store impressions, product page views, downloads and conversion through the Analytics Reports API; Google Play store listing visitors, acquisitions and installs from the Play reports bucket) and compare them with listing, screenshot and experiment changes from git; download App Store sales / finance reports and Play earnings / sales reports with a summary per product and currency |
|
||||
| `store-api` | Call any App Store Connect API or Google Play Developer API operation that storebound's commands do not wrap, safely |
|
||||
| `store-declarations` | Answer the store compliance forms for a mobile app or game |
|
||||
| `store-health` | Watch a released mobile app's or game's crash and ANR health on both stores |
|
||||
| `store-iap-setup` | Create and price in-app purchases (consumables, non-consumables like "remove ads" or a Pro unlock, non-renewing passes, coin/gem packs, starter packs) on Google Play and App Store Connect from one product list |
|
||||
|
|
|
|||
15
AGENTS.md
15
AGENTS.md
|
|
@ -15,9 +15,10 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
|||
chat). storebound's MCP server does not offer these at all.
|
||||
2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run, then run it
|
||||
for real only after the owner agrees.
|
||||
3. **Read before you write.** `storebound check` (offline) and `storebound validate` (read-only, both stores) tell you
|
||||
what is missing and in which order to fix it.
|
||||
4. **Credentials only from the environment or `.storebound/`** in the project (gitignored). Never ask for keys,
|
||||
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
|
||||
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
|
||||
4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
|
||||
(`~/.storebound/credentials/<profile>.json`, named by `--account <profile>` or a workspace). Never ask for keys,
|
||||
passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes
|
||||
for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there.
|
||||
5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating,
|
||||
|
|
@ -35,7 +36,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
|||
|
||||
- CLI: `storebound <command>` (`storebound help`); config `storebound.config.ts`, credentials in env or `.storebound/`.
|
||||
- MCP: `storebound mcp` (stdio). MCP 2026-07-28 + 2025-11-25. Write tools default to `dry_run: true`; submit / release / cancel / delete / send are not exposed.
|
||||
- Readiness: `storebound check` (offline), `storebound validate` (read-only, both stores).
|
||||
- Readiness: `storebound scan` (offline rejection risks in the project files), `storebound check` (offline), `storebound validate` (read-only, both stores).
|
||||
- Every endpoint: `storebound api apple|play <operationId>` (skill store-api). GETs run; writes are dry unless the owner adds `--yes` in a terminal; MCP has the read-only `api_get`.
|
||||
|
||||
## Skills
|
||||
|
||||
|
|
@ -44,8 +46,10 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
|||
- `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-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/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/build-and-sign/SKILL.md`: Sign, build and upload a mobile app or game from the terminal
|
||||
- `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/play-first-release/SKILL.md`: Step-by-step first (and later) Google Play release of a mobile app or game
|
||||
|
|
@ -56,7 +60,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
|||
- `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-replies/SKILL.md`: Reply to App Store and Google Play reviews of a mobile app or game the safe way
|
||||
- `skills/store-analytics/SKILL.md`: Take store analytics snapshots for a mobile app or game (App Store impressions, product page views, downloads and conversion through the Analytics Reports API; Google Play store listing visitors, acquisitions and installs from the Play reports bucket) and compare them with listing, screenshot and experiment changes from git
|
||||
- `skills/store-analytics/SKILL.md`: Take store analytics snapshots for a mobile app or game (App Store impressions, product page views, downloads and conversion through the Analytics Reports API; Google Play store listing visitors, acquisitions and installs from the Play reports bucket) and compare them with listing, screenshot and experiment changes from git; download App Store sales / finance reports and Play earnings / sales reports with a summary per product and currency
|
||||
- `skills/store-api/SKILL.md`: Call any App Store Connect API or Google Play Developer API operation that storebound's commands do not wrap, safely
|
||||
- `skills/store-declarations/SKILL.md`: Answer the store compliance forms for a mobile app or game
|
||||
- `skills/store-health/SKILL.md`: Watch a released mobile app's or game's crash and ANR health on both stores
|
||||
- `skills/store-iap-setup/SKILL.md`: Create and price in-app purchases (consumables, non-consumables like "remove ads" or a Pro unlock, non-renewing passes, coin/gem packs, starter packs) on Google Play and App Store Connect from one product list
|
||||
|
|
|
|||
145
CHANGELOG.md
145
CHANGELOG.md
|
|
@ -2,6 +2,151 @@
|
|||
|
||||
## Unreleased
|
||||
|
||||
- `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
|
||||
Help page (cited with the date in `cli/lib/scan/play-rules.ts`). New rules: the restricted permissions and their
|
||||
Console declarations (background location, READ_MEDIA_IMAGES / READ_MEDIA_VIDEO, MANAGE_EXTERNAL_STORAGE,
|
||||
AccessibilityService with or without isAccessibilityTool, REQUEST_INSTALL_PACKAGES, Health Connect,
|
||||
USE_FULL_SCREEN_INTENT, VpnService), prominent disclosure and the in-app privacy policy (User Data), Data safety
|
||||
answers narrower than the SDKs' disclosures, Families (`play.targetAges`: ad SDKs not on Google's self-certified list
|
||||
or older than their certified version, AD_ID and location in child-only apps, mixed audiences), the AD_ID permission
|
||||
on targetSdk 33+, 16 KB page sizes (Unity before 6000.0.38f1 / 2022.3.56f1 / 2021.3.48f1, React Native before 0.77,
|
||||
NDK before r28 without the flags, AGP before 8.5.1 with uncompressed libraries, prebuilt .so files; updates blocked
|
||||
from 2027-02-01), the closed-testing requirement of new personal accounts (`play.accountType`,
|
||||
`play.accountCreated`: 12 testers for 14 days), Play metadata (title over 30 characters, emoji, ALL CAPS, rank /
|
||||
price / promotion terms, other apps, repeated keywords and keyword lists), interstitials shown from the launcher
|
||||
activity's onCreate, card / PayPal SDKs or "buy on our website" next to in-app products (`play.billingPrograms`),
|
||||
and brand names in the package or app name (low). Detection reads activities, services and receivers with their
|
||||
intent filters, accessibility-service configs, strings.xml, the NDK / AGP versions, CMake / ndk-build files,
|
||||
extractNativeLibs, useLegacyPackaging, Unity ProjectVersion.txt, .so files, and the merged manifest under
|
||||
build/intermediates when the project was built locally. Device admin has no Play policy page and gets no rule. The
|
||||
App Store rules are unchanged. New fixtures (play-android, play-native, play-families, play-listing) and Android parts
|
||||
in the clean fixture; the README rule table has a column per store.
|
||||
- `storebound scan` (MCP tool `scan`, desktop Checks tab): an offline, read-only scan of the project itself for App
|
||||
Store and Google Play rejection risks before you submit. Detects the stack (native iOS / Android, React Native,
|
||||
Expo, Capacitor, Cordova, Flutter, Unity, Godot) and the SDKs from a maintained table (`cli/lib/scan/sdks.ts`: ads,
|
||||
analytics, attribution, crash, sign-in, payments, push, with versions, file:line and each vendor's data disclosure
|
||||
page) and reports each risk with the guideline, evidence, fix, severity and skill: 2.1(a) demo account and
|
||||
placeholder text, 5.1.1(v) account deletion, 4.8 login services, 3.1.1 Restore Purchases and outside payments,
|
||||
3.1.2(c) subscription information, 5.1.2(i) App Tracking Transparency, 5.1.1(ii) / (iv) purpose strings, 5.1.1(i)
|
||||
privacy link, privacy manifests (ITMS-91053 / 91061), 2.3.10 other platforms, 2.3.7 keywords, 2.3.8 "For Kids", 4.2
|
||||
web wrappers, 2.5.1 UIWebView and private URL schemes, 2.5.5 IPv6, ATS, export compliance, 1.3 kids ads, 5.6.1 /
|
||||
3.2.2(x) review prompts, privacy labels vs SDKs, and on Play the API 36 target SDK requirement (since 2026-08-31),
|
||||
the delete-account URL, App access, foreground service types, exact alarms, QUERY_ALL_PACKAGES, SMS / call log and
|
||||
the reserved com.example package name. It also proposes the Data safety / App Privacy / ATT / privacy manifest
|
||||
answers, each "detected (file:line)" or "ask owner", as a diff against the config; `--write` adds only the detected
|
||||
answers (new `appPrivacy` block for tracking). `scan.ignore` records findings the owner accepts, with the reason.
|
||||
`validate` includes the open findings (`--no-scan` skips), `check` now asks for unanswered dataSafety booleans.
|
||||
Fixtures for iOS, Android, Capacitor, Unity, Flutter, a clean project and the teaser under `tests/fixtures/scan/`.
|
||||
- CLI workspace for many apps and studios (until now only in the desktop app): `storebound.workspace.json` (or `.ts`)
|
||||
in a folder above the app folders names the app folders (globs), studios with their store accounts by credential
|
||||
profile (never a key), an ignore list and the desktop's pairing overrides. Commands: `ws init`, `ws list`,
|
||||
`ws status` (apps x stores, read in parallel with a concurrency limit), `ws check`, `ws validate`,
|
||||
`ws run <command> --apps a,b|--all` (read commands; writes as dry runs unless `--apply`; submit, release, rollout,
|
||||
send, start / stop never), `ws apps import --account <profile>` (store apps paired with the folders by the desktop's
|
||||
rules) and `ws desktop export | import` (the same model as the desktop's `state.json`; keys stay in the keychain or
|
||||
the profiles). MCP: `workspace_list`, `workspace_status` (read-only).
|
||||
- Credential profiles: `~/.storebound/credentials/<profile>.json` (or env `STOREBOUND_PROFILE_<NAME>_<KEY>`), picked
|
||||
with `--account <profile>` on any command or by the workspace, so many store accounts work from one terminal.
|
||||
- Release trains in the CLI: `release status` (both stores on one train per version: build > testing > review > live
|
||||
> rollout %) and `release plan <version>` (what is left on each store in fix order, from check, validate and the
|
||||
store state; owner steps named, never done), as tables or `--json`. MCP: `release_status`, `release_plan`.
|
||||
- Shared code instead of copies: the pairing rules (`cli/lib/identity.ts`) and the release lanes (`cli/lib/train.ts`)
|
||||
moved out of the desktop's webview into `cli/lib/`, and the per-app status read behind `portfolio.status`
|
||||
(`cli/lib/app-status.ts`) is the one `ws status` and `release` use. The desktop re-exports them unchanged.
|
||||
- Every endpoint: `storebound api` calls any operation of the App Store Connect API (1303 operations, OpenAPI 4.5.1)
|
||||
and the Google Play Developer APIs (Android Publisher v3: 145 methods, Play Developer Reporting v1beta1: 25; v1alpha1
|
||||
has no methods of its own), from the official specs pinned in `specs/` (URLs, dates, SHA-256 in
|
||||
`specs/SOURCES.json`). `tools/gen-api.ts` turns them into one row per operation (`cli/api/apple.gen.ts`,
|
||||
`cli/api/play.gen.ts`) plus generic helpers (`cli/api/client.ts`: URL and parameter building, retries on 429 / 5xx
|
||||
with Retry-After, `--all-pages` over Apple's `links.next` and Google's page tokens), typed from the rows
|
||||
(`cli/api/types.ts`: path and required parameters, loosely typed JSON:API requests and responses). About 44 KB more
|
||||
in the npm tarball. Same credentials as every other command (`ascJwt` is now shared from `cli/apple/asc.ts`).
|
||||
- `storebound api apple|play <operationId | METHOD path> [--param k=v ...] [--body file.json] [--upload file]
|
||||
[--out file] [--all-pages] [--json] [--dry] [--yes]`: GETs (and the read-only Reporting `:query` POSTs) run;
|
||||
every write prints the exact request and is only sent with `--yes` in an interactive terminal; owner-only
|
||||
operations (`cli/api/gate.ts`: deletes, submissions, releases, phased release changes, product page tests, prices,
|
||||
testers and users, review replies, Play `edits.commit`, activation, refunds, app signing) also need the operation
|
||||
id typed. Under MCP or the desktop app no write is sent at all.
|
||||
- `storebound api list [--store] [--search]` and `storebound api coverage`: every operation, counts per API and
|
||||
resource, and which ones storebound's commands already call (a scan of `cli/`, `cli/api/wrapped.gen.ts`); the full
|
||||
table is `docs/api-coverage.md`. CI fails when the tables, the scan or the doc are stale against `specs/`.
|
||||
- MCP: one new read-only tool, `api_get` (GET operations only; not in the desktop profile). New skill `store-api`.
|
||||
- Signing through the App Store Connect API: `apple signing status` (read-only; also an MCP tool) and
|
||||
`apple signing ensure` (dry first, asks once). Bundle id capabilities from `apple.signing.capabilities` (added,
|
||||
never removed), an Apple Distribution certificate when this machine holds no key for a valid one (RSA 2048 key
|
||||
and CSR made in TypeScript, key kept 0600 in `.storebound/signing/`, never printed; `--keychain` imports key and
|
||||
certificate), App Store profiles per bundle id (app + `apple.signing.extraBundleIds`) reused while active or
|
||||
created, installed for Xcode 16+ (`~/Library/Developer/Xcode/UserData/Provisioning Profiles`) and older Xcode
|
||||
(`~/Library/MobileDevice/Provisioning Profiles`). A 403 on a Developer ID certificate is explained (Account Holder
|
||||
only), as are the certificate limit and a key without the Admin role.
|
||||
- `apple build`: finds the workspace / project and scheme (native, Capacitor, React Native, Flutter with
|
||||
`flutter build ios --config-only`, Unity-iPhone), takes the next free build number from App Store Connect,
|
||||
writes ExportOptions.plist (`method` app-store-connect, `destination` export, team, signing style, profiles) and
|
||||
runs xcodebuild archive and -exportArchive with the API key; full logs in `build/ios/`, the IPA checked at the end.
|
||||
- `apple upload`: the IPA through the App Store Connect API build upload (Build Uploads, API 4.1: reserve, upload
|
||||
parts, commit with the MD5, poll) or `--via altool` (`altool --upload-package` with the API key); the build number
|
||||
is checked against App Store Connect first, then storebound waits until the build is VALID (exit 0), INVALID /
|
||||
FAILED (1) or the timeout (7). Dry first, asks.
|
||||
- `play build`: Gradle `bundleRelease` (Flutter: `flutter build appbundle`; Capacitor / React Native `android/`,
|
||||
Unity exports with `launcher/`) with the next free versionCode and the upload key from `ANDROID_KEYSTORE*` (env or
|
||||
`.storebound/credentials.json`), handed to Gradle as injected signing properties through the environment, never on
|
||||
the command line. The versionCode is read back from the AAB's manifest. `play upload --track internal|alpha|beta`:
|
||||
versionCode checked, `--dry` read-only, a real run asks; production stays `play release --production draft`.
|
||||
- `originality --against <folders>` (also an MCP tool): offline Guideline 4.3 check against the owner's other apps:
|
||||
name and listing text similarity, icon and screenshot perceptual hashes (dHash + pHash; PNG decoded in TypeScript,
|
||||
JPEG / WebP through ffmpeg when installed), project structure (file layout, identical files), an overall score,
|
||||
near-duplicate flags and suggestions; exit 1 when a pair is flagged. The portfolio-originality skill uses it.
|
||||
- New skill `build-and-sign`; appstore-first-release and play-first-release use the new commands. Zero new
|
||||
dependencies: plist (XML + binary), ZIP, aapt2 manifest and PNG readers are small TypeScript modules.
|
||||
- Store operations. Every new command has `--dry` and `--json`; what customers can see, redeem or lose (submitting,
|
||||
codes, offers, pre-orders, expiring builds, making a page visible) asks first in the terminal and is not an MCP
|
||||
tool. API details come from the App Store Connect API 4.5.1 OpenAPI spec, Apple's and Google's reference pages and
|
||||
App Store Connect Help (cited at the top of each `cli/lib/*.ts`); tests run the commands against recorded,
|
||||
sanitized answers (`tests/store-ops-*.test.ts`, harness in `tests/helpers/store-mock.ts`).
|
||||
- TestFlight: `apple testflight wait --build N` (polls until VALID / FAILED, progress lines, `--timeout`, exit 0 /
|
||||
1 / 7) and `apple testflight expire --keep N | --older-than D` (newest, attached and processing builds stay;
|
||||
`PATCH /v1/builds/{id}` `expired: true`). `apple upload` waits for processing with the same loop
|
||||
(`waitForBuild` in `cli/apple/testflight.ts`) instead of a copy of its own.
|
||||
- `apple iap-submit`: IAP, subscription and subscription group versions into a review submission
|
||||
(`reviewSubmissionItems` with `inAppPurchaseVersion` / `subscriptionVersion` / `subscriptionGroupVersion`, API
|
||||
4.4.1+; the deprecated `inAppPurchaseSubmissions` are not used). It applies Apple's rules: the first item of each
|
||||
type only together with a new app version (`--with-version`), later ones alone once the app has an approved
|
||||
version, a new subscription with its unapproved group, at most 200 items; `--no-submit` stops at the draft,
|
||||
`--new-version` makes a new draft version of an approved or rejected product. MCP: the read-only plan
|
||||
`apple_iap_review_plan`.
|
||||
- Pulls: `apple listing pull`, `play listing pull` (live texts back into `store/*.md`, diff first, `--write` to
|
||||
write) and `catalog pull` (IAP and subscription texts as a proposal diff; the config is never rewritten,
|
||||
`--write` saves `.storebound/pull/catalog.json`).
|
||||
- `whats-new --languages a,b,c`: one file per language in `store/whats-new/`, translated by your agent (skill) or a
|
||||
`--translate "<command>"` hook of yours (no translation service or key in the CLI); `whats-new check` (Play 500,
|
||||
App Store 4000, untranslated or identical to the source) and `whats-new apply`.
|
||||
- Offers: `apple offer-codes` (offer codes for one-time purchases, `inAppPurchaseOfferCodes`; custom and one-time-use
|
||||
codes only with `--codes`, saved to `.storebound/offer-codes/`), `apple win-back` (win-back offers,
|
||||
`winBackOffers`), `apple promoted` (promoted purchases: create disabled, order, `--enable`), `apple preorder
|
||||
status | enable | end` (territory availabilities, `endAppAvailabilityPreOrders`). Google Play pre-registration and
|
||||
promo codes have no API: console guide in the new `app-store-promotion` skill.
|
||||
- `apple cpp list | create | upload | submit | visible` (custom product pages, screenshots from a shots variant) and
|
||||
`apple events list | create | upload | submit` (in-app events with schedule, localizations, card and details
|
||||
images checked against Apple's sizes).
|
||||
- `reports apple-sales | apple-finance | play-earnings | play-sales`: Apple `salesReports` / `financeReports`
|
||||
(vendor number from `ASC_VENDOR_NUMBER` in env or `.storebound/credentials.json`) and the Play earnings / sales
|
||||
zips from the reports bucket into `.storebound/reports/`, with a summary per product and currency and a CSV.
|
||||
Zero dependencies: the same small ZIP reader (`cli/lib/zip.ts`, on `node:zlib`) that reads IPAs and AABs.
|
||||
- `triage`: TestFlight crash reports (signature from each crash log, text and `.ips`), TestFlight screenshot feedback
|
||||
and Play error reports of the top issues, grouped by signature with devices, OS versions and builds; tester emails
|
||||
are never requested.
|
||||
- `aso rank`: the app's rank per keyword and storefront in the public iTunes Search API results plus the first
|
||||
competitors, one request every 3.5 s (Apple allows about 20 a minute), snapshots in `.storebound/aso/`. Subtitles
|
||||
are not in any public API and are not shown.
|
||||
- `ads scan --ios <path>`: AdAttributionKit / SKAdNetwork checks of Info.plist and sources (ad network ids and their
|
||||
case, `AttributionCopyEndpoint`, re-engagement copies, `NSAdvertisingAttributionReportEndpoint`, attribution
|
||||
windows and cooldown ranges, conversion value updates); the ads-mediation-checks skill explains each finding.
|
||||
- New MCP tools (dry by default where they write local files): `apple_testflight_wait`, `apple_iap_review_plan`,
|
||||
`apple_listing_pull`, `play_listing_pull`, `catalog_pull`, `whats_new_languages`, `whats_new_check`,
|
||||
`whats_new_apply`, `reports`, `triage`, `aso_rank`, `ads_scan`, `apple_cpp_list | create | upload`,
|
||||
`apple_events_list | create | upload`, `apple_preorder_status`.
|
||||
|
||||
- New logo: a glossy indigo box with an upward arrow (`brand/master/logo-mark.png`, `brand/README.md`). Every logo
|
||||
file comes from it through `tools/brand-assets.py`: desktop app icons (PNG sizes, `.icns`, a `.ico` with its own
|
||||
image per size, Windows tiles), the site's favicon.ico, maskable web app icons with a manifest, apple-touch-icon,
|
||||
|
|
|
|||
15
GEMINI.md
15
GEMINI.md
|
|
@ -13,9 +13,10 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
|||
chat). storebound's MCP server does not offer these at all.
|
||||
2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run, then run it
|
||||
for real only after the owner agrees.
|
||||
3. **Read before you write.** `storebound check` (offline) and `storebound validate` (read-only, both stores) tell you
|
||||
what is missing and in which order to fix it.
|
||||
4. **Credentials only from the environment or `.storebound/`** in the project (gitignored). Never ask for keys,
|
||||
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
|
||||
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
|
||||
4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
|
||||
(`~/.storebound/credentials/<profile>.json`, named by `--account <profile>` or a workspace). Never ask for keys,
|
||||
passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes
|
||||
for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there.
|
||||
5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating,
|
||||
|
|
@ -33,7 +34,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
|||
|
||||
- CLI: `storebound <command>` (`storebound help`); config `storebound.config.ts`, credentials in env or `.storebound/`.
|
||||
- MCP: `storebound mcp` (stdio). MCP 2026-07-28 + 2025-11-25. Write tools default to `dry_run: true`; submit / release / cancel / delete / send are not exposed.
|
||||
- Readiness: `storebound check` (offline), `storebound validate` (read-only, both stores).
|
||||
- Readiness: `storebound scan` (offline rejection risks in the project files), `storebound check` (offline), `storebound validate` (read-only, both stores).
|
||||
- Every endpoint: `storebound api apple|play <operationId>` (skill store-api). GETs run; writes are dry unless the owner adds `--yes` in a terminal; MCP has the read-only `api_get`.
|
||||
|
||||
## Skills
|
||||
|
||||
|
|
@ -44,8 +46,10 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
|||
| `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-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 |
|
||||
| `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 |
|
||||
| `build-and-sign` | Sign, build and upload a mobile app or game from the terminal |
|
||||
| `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` |
|
||||
| `play-first-release` | Step-by-step first (and later) Google Play release of a mobile app or game |
|
||||
|
|
@ -56,7 +60,8 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
|||
| `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-replies` | Reply to App Store and Google Play reviews of a mobile app or game the safe way |
|
||||
| `store-analytics` | Take store analytics snapshots for a mobile app or game (App Store impressions, product page views, downloads and conversion through the Analytics Reports API; Google Play store listing visitors, acquisitions and installs from the Play reports bucket) and compare them with listing, screenshot and experiment changes from git |
|
||||
| `store-analytics` | Take store analytics snapshots for a mobile app or game (App Store impressions, product page views, downloads and conversion through the Analytics Reports API; Google Play store listing visitors, acquisitions and installs from the Play reports bucket) and compare them with listing, screenshot and experiment changes from git; download App Store sales / finance reports and Play earnings / sales reports with a summary per product and currency |
|
||||
| `store-api` | Call any App Store Connect API or Google Play Developer API operation that storebound's commands do not wrap, safely |
|
||||
| `store-declarations` | Answer the store compliance forms for a mobile app or game |
|
||||
| `store-health` | Watch a released mobile app's or game's crash and ANR health on both stores |
|
||||
| `store-iap-setup` | Create and price in-app purchases (consumables, non-consumables like "remove ads" or a Pro unlock, non-renewing passes, coin/gem packs, starter packs) on Google Play and App Store Connect from one product list |
|
||||
|
|
|
|||
313
README.md
313
README.md
|
|
@ -54,7 +54,7 @@ your own click.
|
|||
|---|---|---|---|---|
|
||||
| 1 | **Set up** | `init --profile app\|game\|subscription-app` (config, `store/*.md`, declarations, App Privacy and privacy templates per profile), `install --agent <tool>`, `check` | Play: service account + API access invite; App Store: API team key (`play-first-release`, `appstore-first-release`) | developer accounts; Paid Applications agreement, banking and tax; Play payments profile |
|
||||
| 2 | **App records and bundle id** | `apple bundle` registers the bundle id, `apple status` finds the app record | App Store Connect > New App (no API); Play Console > Create app; the very first AAB upload when Play needs it from the Console | the declarations you accept when creating the Play app |
|
||||
| 3 | **Builds and testers** | `play next-version-code`, `play release app.aab` (internal track), `apple next-build`, `xcodebuild` archive + upload with the API key (the skill has the commands), `apple encryption`, `apple testflight groups / what-to-test / info / distribute` (internal groups) | Play internal testers list, Apple sandbox testers (`play-first-release`, `testflight`) | `apple testflight testers` (Apple emails the invitations), external groups and Beta App Review (`distribute --submit-review`) |
|
||||
| 3 | **Builds and testers** | `play next-version-code`, `play build`, `play upload --track internal`, `apple signing ensure`, `apple build`, `apple upload` (waits for processing), `apple encryption`, `apple testflight groups / what-to-test / info / distribute` (internal groups) | Play internal testers list, Apple sandbox testers (`play-first-release`, `testflight`) | `apple testflight testers` (Apple emails the invitations), external groups and Beta App Review (`distribute --submit-review`) |
|
||||
| 4 | **In-app products and subscriptions** | `play products` (regional prices from USD + your overrides, activated), `apple iap` (consumable, non-consumable, non-renewing; localizations, price schedule, availability), `apple iap-review`, `apple subscriptions` (groups, levels, equalized prices, intro and promotional offers, offer codes), `play subscriptions` (base plans, regional prices, offers), `catalog diff` (both stores against one catalog) | Play license testers, Apple sandbox testers, "Add for Review" of the first IAPs and subscriptions into the version's submission, Play promo codes (`store-iap-setup`, `store-subscriptions`) | custom offer codes (`apple subscriptions --codes` asks first) |
|
||||
| 5 | **Store listings, every language** | `play listing` (title, short / full description, contact email + website, promo video URL), `apple listing --version x --build N` (name, subtitle, description, keywords, promo text, URLs, privacy URL, manual release), `whats-new`, `check` (limits), `check --aso` | Play store settings: category and tags (`play-first-release`) | |
|
||||
| 6 | **Play questionnaires** | `play data-safety`: the whole Data safety form from `dataSafety` in the config (CSV import through the API) | Policy and programs > App content, answers prepared in `store/declarations.md` (`store-declarations`): privacy policy, app access with the demo account (`review-access`), delete-account URL (`account-deletion`), ads, content rating (IARC), target audience and content, advertising ID, news, government, financial and health features; Data safety summary check | the answers themselves are your statements: the agent asks when the code does not prove them |
|
||||
|
|
@ -62,7 +62,7 @@ your own click.
|
|||
| 8 | **Privacy and accounts** | privacy policy page template (`init`), `privacy-manifest --ios <path>` (PrivacyInfo.xcprivacy, required-reason APIs, SDK manifests), `validate` checks the policy, delete-account and terms URLs answer | host the pages, link them in both consoles and inside the app; in-app account deletion (`privacy-policy`, `privacy-manifest`, `account-deletion`) | |
|
||||
| 9 | **Icons** | `icons`: App Store 1024 without alpha, Play 512, adaptive + legacy Android launcher icons, web icons, Capacitor sources | | |
|
||||
| 10 | **Screenshots and previews** | `shots capture / render / check / gallery`, `play images`, `apple screenshots`, `shots record / video`, `apple previews`, `apple ppo create / upload` (App Store product page tests from `shots` variants; see [Store art](#store-art)) | Play store listing experiments (optional, `store-screenshots`) | uploading the promo video to YouTube; `apple ppo start / stop` |
|
||||
| 11 | **Validate** | `check` (offline) and `validate` (read-only on both stores: every blocker in fix order, plus the local renders) | the UI-only items `validate` cannot see (`store-preflight` lists them) | |
|
||||
| 11 | **Validate** | `scan` (offline: rejection risks in the project files, see [Catch rejections before you submit](#catch-rejections-before-you-submit)), `check` (offline) and `validate` (read-only on both stores: every blocker in fix order, plus the local renders) | the UI-only items `validate` cannot see (`store-preflight` lists them) | |
|
||||
| 12 | **Submit** | `play release --version-code N --production draft`, `apple status` | Play: countries / regions, open the production draft and save it (`play-first-release`) | **Play: Send changes for review. App Store: Submit for Review.** |
|
||||
| 13 | **After review** | `apple status --wait-review`, `apple release --phased on / pause`, `play rollout --halt`, reply drafts (`review-rejections`) | | releasing the approved version, resuming or completing a phased release or rollout (terminal commands that ask first, `release-management`) |
|
||||
| 14 | **Live app** | `health [--weekly]` (crash / ANR vitals vs Play's thresholds, App Store diagnostics; also in `validate`), `reviews list / draft`, `analytics snapshot / compare`, `prices export`, `prices import --dry`, `apple ppo status` | `store-health`, `review-replies`, `store-analytics`; Play statistics come from the reports bucket (no API) | `reviews send` (approved drafts only), `prices import` (asks first) |
|
||||
|
|
@ -76,17 +76,113 @@ New personal Play developer accounts also need a closed test with 12+ testers fo
|
|||
every language, graphics, screenshots, app previews, in-app products and prices (also from one CSV), Play Data
|
||||
safety, Apple age rating, categories, content rights, price and availability, export compliance answer, App Review
|
||||
details with the demo account, subscriptions (Apple groups, levels, prices, introductory and promotional offers,
|
||||
offer codes; Play base plans, regional prices, offers), phased release and staged rollout, TestFlight groups / testers / What to Test / Test Information, crash and
|
||||
ANR vitals and App Store diagnostics, review replies, App Store analytics reports, App Store Product Page
|
||||
Optimization tests.
|
||||
offer codes; Play base plans, regional prices, offers), phased release and staged rollout, TestFlight groups / testers / What to Test / Test Information / build
|
||||
processing / expiring builds, crash and ANR vitals and App Store diagnostics, TestFlight feedback, review replies,
|
||||
App Store analytics reports, sales and finance reports, App Store Product Page Optimization tests, IAP and
|
||||
subscription review submissions, offer codes for one-time purchases, win-back offers, promoted IAPs, pre-orders,
|
||||
custom product pages and in-app events, and pulling live listing texts back.
|
||||
- **Console only** (no public API; the skill + your agent's browser, or you): creating the App Store Connect app record
|
||||
and the Play app, Play App content (IARC content rating, target audience, ads, advertising ID, app access,
|
||||
government / financial / health / news, app access with the demo account), Play category and tags, Play countries,
|
||||
App Privacy labels and their Publish, adding first IAPs and subscriptions to the submission, Play promo codes, Play store listing experiments, test results of both stores' experiments.
|
||||
App Privacy labels and their Publish, Play promo codes, Play pre-registration, Play store listing experiments, test results of both stores' experiments, promotional images of promoted IAPs.
|
||||
Play store statistics have no API either: storebound reads the monthly exports from your Play reports bucket.
|
||||
- **Only you**: agreements, banking and tax, and the final Send for review / Submit for Review. Releases and
|
||||
rollouts after approval, Beta App Review, tester invitations, sending review replies, applying price changes and
|
||||
starting / stopping a product page test too. None of these is an MCP tool; the terminal commands ask first.
|
||||
- **Only you**: agreements, banking and tax, and the final Send for review / Submit for Review (apps, IAPs, custom
|
||||
product pages, in-app events). Releases and rollouts after approval, Beta App Review, tester invitations, sending
|
||||
review replies, applying price changes, starting / stopping a product page test, creating offer codes, win-back
|
||||
offers, switching on promoted IAPs, pre-orders and expiring builds too. None of these is an MCP tool; the terminal commands ask first.
|
||||
|
||||
## Catch rejections before you submit
|
||||
|
||||
App Store rejections cost days: you wait for review, read one sentence in the Resolution Center, fix it, and wait
|
||||
again. On Google Play a policy problem can mean a blocked update, a removal or a strike on the account. Most of the
|
||||
usual ones are visible in the project long before that. `storebound scan` reads the project itself, offline and
|
||||
read-only (Xcode project, Info.plist and build settings, entitlements, PrivacyInfo.xcprivacy, Podfile.lock,
|
||||
Package.resolved, Cartfile, Gradle files and version catalogs, AndroidManifest.xml (and the merged manifest of a local
|
||||
build), res/xml and strings.xml, CMake / ndk-build files, Unity ProjectVersion.txt, package.json,
|
||||
Expo app.json, capacitor.config, Cordova config.xml, pubspec, Unity Packages/manifest.json, ProjectSettings and
|
||||
External Dependency Manager files, Godot export presets), plus your config and listing files. It works out the stack
|
||||
and the SDKs (ads, analytics, attribution, crash, sign-in, payments, push, with versions and the file:line they come
|
||||
from) and reports every rejection risk it can prove, each with the guideline, the evidence, the fix, a severity and the
|
||||
skill to open. On the teaser fixture (`tests/fixtures/scan/teaser`):
|
||||
|
||||
```text
|
||||
$ storebound scan
|
||||
Rejection risks: 2 blocker, 3 high, 0 medium, 0 low
|
||||
1. BLOCKER 2.1(a) · App Store · Sign-in is required but there is no demo account for App Review
|
||||
at storebound.config.ts:12 reviewAccess: { signInRequired: true, instructions: 'Sign in with the demo account.' },
|
||||
at storebound.config.ts:11 accounts: { enabled: true },
|
||||
at Podfile.lock:3 Google Sign-In: GoogleSignIn 7.1.0
|
||||
2. BLOCKER 5.1.1(v) · App Store · Accounts can be created but no in-app account deletion was found
|
||||
at storebound.config.ts:11 accounts: { enabled: true },
|
||||
at Planner/LoginView.swift:11 Button("Create account") { Task { try await AccountApi.signUp() } }
|
||||
at Planner/LoginView.swift:17 static func signUp() async throws {
|
||||
3. HIGH 4.8 · App Store · Third-party login (Google / Facebook / ...) without Sign in with Apple or another equivalent login option
|
||||
at Podfile.lock:3 Google Sign-In: GoogleSignIn 7.1.0
|
||||
at Planner/LoginView.swift:9 GIDSignIn.sharedInstance.signIn(withPresenting: rootViewController()) { _, _ in }
|
||||
4. HIGH 3.1.1 · App Store · Restorable purchases (non-consumables or subscriptions) but no Restore Purchases path was found
|
||||
at storebound.config.ts:16 com.example.planner.pro (non_consumable)
|
||||
5. HIGH 5.1.2(i) · App Store · Tracking-capable code without App Tracking Transparency (Google AdMob, IDFA)
|
||||
at Podfile.lock:2 Google AdMob: Google-Mobile-Ads-SDK 11.10.0
|
||||
at Planner/Ads.swift:7 print(ASIdentifierManager.shared().advertisingIdentifier)
|
||||
```
|
||||
|
||||
Every finding also has a `fix:` line and the skill. Below the risks comes the declarations proposal: the Play Data
|
||||
safety and App Store App Privacy answers, App Tracking Transparency and privacy manifest entries the detected SDKs and
|
||||
code imply, each marked **detected (file:line)** or **ask owner**, as a diff against `dataSafety` / `appPrivacy` in
|
||||
the config. Nothing is written unless you run `storebound scan --write` (only detected answers; questions stay
|
||||
questions). The MCP tool `scan` is read-only and cannot write; `validate` includes the open scan findings; the desktop
|
||||
app shows them on the Checks tab. A finding you decided is fine goes into the config with its reason:
|
||||
`scan: { ignore: [{ rule: 'demo-account', reason: '...' }] }`.
|
||||
|
||||
| rule | App Store | Google Play | what scan proves |
|
||||
|---|---|---|---|
|
||||
| `demo-account`, `play-app-access` | 2.1(a) | App access | a sign-in (config, auth SDKs, sign-in code) without `reviewAccess` or without the demo account in `.storebound/` |
|
||||
| `account-deletion`, `play-deletion-url` | 5.1.1(v) | User Data: account deletion | sign-up or social login without a deletion path in code or `accounts.inApp`; no `accounts.deletionUrl` |
|
||||
| `login-services` | 4.8 | | Google / Facebook / other third-party login without Sign in with Apple or another equivalent option |
|
||||
| `restore-purchases`, `external-purchase`, `play-payments` | 3.1.1 | Payments | non-consumables or subscriptions without a restore path; card / PayPal SDKs next to in-app products; "buy on our website" (Play: unless `play.billingPrograms` lists user choice billing or external offers) |
|
||||
| `subscription-info` | 3.1.2(c), 3.1.2 | | no Terms of Use URL, no Terms link or renewal wording in the description, no legal links or "Manage subscription" in the app |
|
||||
| `att` | 5.1.2(i) | | tracking-capable SDKs or IDFA without ATT; the prompt without its purpose string; the string without a prompt |
|
||||
| `purpose-strings`, `unused-permission` | 5.1.1(ii), 5.1.1(iv), ITMS-90683 | | a used permission without its NS*UsageDescription; empty or vague strings; declared but unused |
|
||||
| `privacy-manifest` | ITMS-91053 / 91061 | | no PrivacyInfo.xcprivacy, required-reason APIs not declared, SDKs older than their first manifest version |
|
||||
| `privacy-policy-link`, `play-privacy-policy` | 5.1.1(i) | User Data: privacy policy | no privacy link in the app's sources (Play: every app; medium when it collects data), an `http://` link |
|
||||
| `privacy-labels` | 5.1.2 | User Data: Data safety | SDK data types missing from `dataSafety`; Play also: an answer narrower than the SDK's disclosure (purposes, sharing), SDKs with no `dataSafety` at all |
|
||||
| `play-prominent-disclosure` | | User Data: prominent disclosure, Location permissions | background location without a disclosure that says "location" and "background"; location, contacts, calendar or phone number access without any disclosure or rationale text in sources or `strings.xml` |
|
||||
| `play-background-location`, `play-photo-video`, `play-all-files-access`, `play-accessibility`, `play-install-packages`, `play-health-connect`, `play-full-screen-intent`, `play-vpn` | | Location permissions, Photo and Video Permissions, All files access, AccessibilityService API, REQUEST_INSTALL_PACKAGES, Health Connect, Full-screen intent, VpnService | the restricted permission or service in the manifest (or the merged manifest of a local build), each with the core-use test and the Play Console declaration it needs; `isAccessibilityTool` lowers the accessibility finding to medium |
|
||||
| `play-fgs`, `play-exact-alarm`, `play-query-all-packages`, `play-sms-call-log` | | Foreground service types, exact alarms, package visibility, SMS and Call Log | foreground services without a type or its permission (and the Console declaration); USE_EXACT_ALARM; QUERY_ALL_PACKAGES; SMS and call log permissions |
|
||||
| `kids-ads`, `play-families-ads`, `play-families-ad-id`, `play-families-location` | 1.3 | Families | a Kids Category age band with third-party ads or analytics SDKs; `play.targetAges` under 13 with an ad SDK that is not Families self-certified (or older than its certified version), the AD_ID permission in a child-only app (mixed audience: ad / attribution SDKs need child-directed treatment), location in a child-only app |
|
||||
| `play-ad-id` | | Advertising ID | targetSdk 33+ with ad / attribution SDKs and no AD_ID permission (medium when the merged manifest proves it is missing; Google Mobile Ads adds it itself) |
|
||||
| `play-16kb` | | 16 KB page sizes (updates blocked from 2027-02-01) | Unity before 6000.0.38f1 / 2022.3.56f1 / 2021.3.48f1, React Native before 0.77, NDK before r28 for the app's own C/C++ without the 16 KB flags, AGP before 8.5.1 with uncompressed native libraries; else prebuilt `.so` files to check |
|
||||
| `play-ads-launch` | | Ads, Better Ads Experiences | an interstitial shown from `onCreate` of the launcher activity (Android native; other engines: review-only) |
|
||||
| `play-testing-requirement` | | Testing for new personal accounts | `play.accountType: 'personal'` created after 2023-11-13 (12 testers, 14 days of closed testing before production); low when the account type is not set |
|
||||
| `other-platforms` | 2.3.10 | | "Android", "Google Play" and other stores in the App Store text or screenshot captions |
|
||||
| `metadata-keywords`, `kids-terms`, `play-metadata` | 2.3.7, 2.3.8 | Metadata | other apps' names, prices and "best / #1" in name, subtitle or keywords; keyword lists; "For Kids" outside the Kids Category. Play title over 30 characters, emoji, ALL CAPS, rank / price / promotion terms; other apps in the title or short description; repeated keywords or keyword lists in the full description |
|
||||
| `play-impersonation` | | Impersonation | a well-known brand in the package name or app name (low: a check, not a verdict) |
|
||||
| `placeholder-text` | 2.1(a) | Metadata | lorem ipsum, TODO, template lines in the listings |
|
||||
| `min-functionality` | 4.2 | | Capacitor `server.url` / Cordova `<content src>` on a remote site; a few native files around a remote WKWebView |
|
||||
| `deprecated-api`, `private-api` | 2.5.1 (ITMS-90809) | | UIWebView; `App-Prefs:` / `prefs:root` URL schemes |
|
||||
| `ipv6`, `ats` | 2.5.5, App Transport Security | | IPv4 literals in server URLs; NSAllowsArbitraryLoads |
|
||||
| `export-compliance` | export compliance | | no ITSAppUsesNonExemptEncryption and no `apple.usesNonExemptEncryption`, or the two disagree (never guessed) |
|
||||
| `review-prompt` | 5.6.1, 3.2.2(x) / 5.6.3 | | a custom "rate us" prompt without the system API; rewards for ratings |
|
||||
| `play-target-sdk` | | Target API level | below API 36 (Wear OS / Automotive 35, TV / XR 34) for new apps and updates since 2026-08-31 |
|
||||
| `play-package-name` | | Play Console upload | the reserved `com.example` prefix |
|
||||
|
||||
Rules cite Apple's App Review Guidelines and the Play Policy Center / Play Console Help pages they come from (checked
|
||||
2026-10-11, in the code comments of `cli/lib/scan/rules.ts` and `cli/lib/scan/play-rules.ts`); the SDK table with each
|
||||
vendor's data disclosure page and Google's Families self-certified ads SDK list is `cli/lib/scan/sdks.ts`. Play config
|
||||
the rules read: `play.targetAges` (Target audience age groups), `play.accountType` / `play.accountCreated`, and
|
||||
`play.billingPrograms`. When the project was built locally, scan also reads the merged manifest under
|
||||
`build/intermediates` (the permissions libraries add); otherwise it says that it could not. Not a rule because no Play
|
||||
policy page covers it: device admin apps (BIND_DEVICE_ADMIN); not a policy at all: Play Integrity / anti-tamper.
|
||||
|
||||
**Checked at review, not by scan** (no file shows them): crashes and hangs on the reviewer's device (2.1, `store-health`),
|
||||
links that are dead at review time (`validate` checks the configured URLs), screenshots and descriptions that do not
|
||||
match the app (2.3, `store-screenshots`), unfinished UI (4.0), "too simple" and spam / template apps (4.2, 4.3,
|
||||
`portfolio-originality`), IAPs that fail in the sandbox (2.1(b), `store-iap-setup`), the content of the privacy policy
|
||||
(`privacy-policy`), local law (5.2). On Google Play: whether a restricted permission really serves the app's core
|
||||
purpose (the Console declaration and its video decide), the wording and timing of a prominent disclosure, ad
|
||||
placements in Unity, Flutter or React Native code, the Health apps declaration answers, and the alignment inside a
|
||||
prebuilt `.so` (scan lists them; `zipalign -c -P 16` and `check_elf_alignment.sh` check the built app). The
|
||||
`review-rejections` skill covers what to do when one of these comes back.
|
||||
|
||||
## 5-minute quick start
|
||||
|
||||
|
|
@ -167,9 +263,15 @@ Read from environment variables, or from `.storebound/credentials.json` in your
|
|||
| `PLAY_SERVICE_ACCOUNT` | path to the Google Cloud service account JSON key (or the JSON itself) with access to your app in Play Console |
|
||||
| `ASC_KEY_ID`, `ASC_ISSUER_ID` | App Store Connect API team key (Users and Access > Integrations) |
|
||||
| `ASC_P8` | path to `AuthKey_<id>.p8` (default `~/.appstoreconnect/private_keys/AuthKey_<id>.p8`) |
|
||||
| `ASC_VENDOR_NUMBER` | vendor number for `reports apple-sales` / `apple-finance` (Payments and Financial Reports) |
|
||||
| `ANDROID_KEYSTORE`, `ANDROID_KEYSTORE_PASSWORD`, `ANDROID_KEY_ALIAS`, `ANDROID_KEY_PASSWORD` | upload key for `play build` (path to the .jks / .p12 and its passwords; handed to Gradle through the environment) |
|
||||
| `reviewContact` | (file only) App Review contact name / phone / email |
|
||||
| `reviewDemoAccount` / `REVIEW_DEMO_USER`, `REVIEW_DEMO_PASSWORD` | demo account for App Review (`reviewAccess.signInRequired`); never in the config or the repo, masked in logs |
|
||||
|
||||
Several store accounts on one machine: credential profiles (`~/.storebound/credentials/<profile>.json`, the same names
|
||||
except the per-app upload keystore)
|
||||
picked with `--account <profile>` or by a workspace ([Many apps and studios](#many-apps-and-studios)).
|
||||
|
||||
## Install for your AI tool
|
||||
|
||||
Every route gives the agent the same skills and the same MCP tools. Nothing here requires Claude: the skills are
|
||||
|
|
@ -209,9 +311,15 @@ run in the background with a log (`storebound shots render > .storebound/render.
|
|||
| `check` | local | config, copy limits, data safety, products, subscriptions, profile (delete-account URL, demo account, terms URL), files; warns on untranslated release notes |
|
||||
| `catalog diff [--store] [--threshold 10]` | API, read-only | one catalog vs both stores: missing / extra / mismatched products and subscriptions, US and override prices, locales, offers, per-region price differences between the stores; exit 1 on mismatches |
|
||||
| `check --aso` | local | keyword audit: App Store keyword field rules, Play stuffing / claims |
|
||||
| `scan [--store apple\|play] [--json] [--write]` | local, read-only | rejection risks in the project itself (stack, SDKs, Info.plist, manifest, listings) with guideline, evidence file:line, fix and skill; Data safety / App Privacy / ATT / privacy manifest proposal as a diff (`--write` adds the detected answers to the config); exit 1 on blockers |
|
||||
| `validate [--apple] [--play]` | API, read-only | readiness report with ordered blockers plus the local renders checks (`--no-local` skips); exit 1 while any blocker is left |
|
||||
| `originality --against <folders> [--json]` | local, read-only | Guideline 4.3 check vs your other apps: name, listing text, icon and screenshot perceptual hashes, project structure; scores, near-duplicate flags, suggestions; exit 1 when flagged |
|
||||
| `whats-new [--since <tag>]` | local | draft player-facing release notes from git log into both listing files |
|
||||
| `whats-new --languages en,de,tr` / `check` / `apply` | local | one file per language (`store/whats-new/`) for your agent (or a `--translate` hook of yours) to translate, per-store limits (Play 500, App Store 4000), then into both listing files |
|
||||
| `catalog pull [--write]` | API, read-only + local | IAP and subscription texts on the stores vs the config: a proposal diff (`.storebound/pull/catalog.json`); the config is never rewritten |
|
||||
| `ads scan --ios <path>` | local | AdAttributionKit / SKAdNetwork: ad network ids, postback copy endpoints, attribution windows and cooldown, conversion value updates; exit 1 on a blocker |
|
||||
| `privacy-manifest --ios <path>` | local | PrivacyInfo.xcprivacy, required-reason APIs, SDKs without manifests |
|
||||
| `api list \| coverage \| apple\|play <operation>` | API | every App Store Connect / Google Play operation (see [Every endpoint](#every-endpoint)); GET runs, writes are dry unless `--yes` in a terminal |
|
||||
| `desktop [--download]` | local | open the storebound desktop app (in an app folder: add or select it there); not installed: the download for this system, `--download` saves it to ~/Downloads after checking its signature (never installs) |
|
||||
| `doctor [--json]` | local | which local tools are here (ffmpeg, Chrome, playwright, Xcode, adb, git) and how to install the missing ones |
|
||||
| `icons` | local | App Store 1024 (no alpha), Play 512, web, Capacitor sources, Android legacy launcher icons |
|
||||
|
|
@ -224,10 +332,13 @@ run in the background with a log (`storebound shots render > .storebound/render.
|
|||
| command | kind | what |
|
||||
|---|---|---|
|
||||
| `play listing` | API | app details, title / short / full description per language, promo video URL (`play.video`) |
|
||||
| `play listing pull [--write]` | API, read-only + local | live listings back into `store/listing.md`: diff first, writes only with `--write` |
|
||||
| `play images [--variant b]` | API | icon, feature graphic, phone / 7" / 10" screenshots, one edit per language |
|
||||
| `play products` | API | one-time products: regional prices from `convertRegionPrices` + your overrides, activate |
|
||||
| `play subscriptions [--csv]` | API | subscriptions: listings + benefits, one auto-renewing base plan, regional prices, intro and extra offers, activate (plan first, asks) |
|
||||
| `play data-safety` | API | Data safety form (CSV import); `--csv` writes the file |
|
||||
| `play build [--version-code N] [--flavor f]` | local + API read | Gradle `bundleRelease` (Flutter `flutter build appbundle`; Capacitor, React Native, Unity export found) with the next free versionCode and the upload key from env / `.storebound` (passed through the environment, never argv); AAB checked and copied to `build/android/` |
|
||||
| `play upload [<aab>] --track internal\|alpha\|beta` | API | AAB to a testing track with release notes; versionCode checked first; `--dry` is read-only, a real run asks |
|
||||
| `play release <aab>` | API | upload + tracks (`--internal completed --production draft`, `--production inProgress --fraction 0.05`), release notes |
|
||||
| `play rollout` | API | `--fraction x`, `--halt`, `--resume`, `--complete` (asks first, except halt) |
|
||||
| `play next-version-code` | API, read-only | next free versionCode |
|
||||
|
|
@ -242,14 +353,26 @@ run in the background with a log (`storebound shots render > .storebound/render.
|
|||
|---|---|---|
|
||||
| `apple bundle` | API | register the bundle id, find the app record |
|
||||
| `apple listing --version x.y.z [--build N]` | API | version (manual release), the build with exactly that number, texts per locale |
|
||||
| `apple listing pull [--version x.y.z] [--write]` | API, read-only + local | live texts back into `store/appstore.md`: diff first, writes only with `--write` |
|
||||
| `apple screenshots [--variant b]` | API | 6.9" + 6.5" (+ 13" iPad with `apple.ipad`, + 6.3" with `apple.iphoneMedium`) per locale, MD5-idempotent |
|
||||
| `apple previews [--poster 5]` | API | app preview videos per locale, checked first, MD5-idempotent, poster frame |
|
||||
| `apple iap` / `apple iap-review` | API | IAPs (consumable, non-consumable, non-renewing), localizations, price schedules, availability / review screenshots |
|
||||
| `apple iap-submit [--with-version] [--no-submit]` | API | IAP / subscription / group versions into a review submission (the first of a type together with the app version); asks before adding and before submitting |
|
||||
| `apple offer-codes [--codes]` | API | offer code campaigns for one-time purchases; custom and one-time-use codes only with `--codes` (asks; codes saved to `.storebound/offer-codes/`) |
|
||||
| `apple win-back` | API | win-back offers for lapsed subscribers (asks: they go live on their start date) |
|
||||
| `apple promoted [--enable]` | API | promoted in-app purchases: create (disabled), order, switch on (asks) |
|
||||
| `apple preorder status \| enable --release-date \| end` | API | pre-orders per territory (enable / end ask first) |
|
||||
| `apple cpp list \| create \| upload \| submit \| visible` | API | custom product pages from the config and a shots variant; submit / visible ask first |
|
||||
| `apple events list \| create \| upload \| submit` | API | in-app events with schedule, localizations, card and details images; submit asks first |
|
||||
| `apple subscriptions [--csv] [--codes]` | API | groups, subscriptions, levels, localizations, availability, equalized prices + overrides + CSV (scheduled changes), introductory and promotional offers, offer code campaigns, review screenshots (plan first, asks; custom codes only with `--codes`) |
|
||||
| `apple appinfo` | API | categories, age rating, content rights, Free, territories |
|
||||
| `apple review-details` | API | App Review contact, demo account (from `.storebound/`, masked), notes (+ sign-in steps, where account deletion is) |
|
||||
| `apple encryption` | API | export compliance answer from `apple.usesNonExemptEncryption` (never guessed) |
|
||||
| `apple release --phased on\|pause\|resume\|complete`, `--manual-release` | API | phased release, release an approved version (resume / complete / release ask first) |
|
||||
| `apple signing status` | API, read-only | bundle id capabilities, distribution certificates (with / without a private key on this Mac), App Store profiles per bundle id, installed or not |
|
||||
| `apple signing ensure [--keychain] [--no-install]` | API | missing capabilities, a distribution certificate from a key made here (kept 0600 in `.storebound/signing/`, never printed), App Store profiles installed for Xcode; dry first, asks; Developer ID needs the Account Holder (403 explained) |
|
||||
| `apple build [--version x.y.z] [--build-number N]` | local + API read | xcodebuild archive + exportArchive with a generated ExportOptions.plist (app-store-connect, team, signing style, profiles) and the API key; next build number; Capacitor, React Native, Flutter, Unity projects found |
|
||||
| `apple upload [<ipa>] [--via api\|altool]` | API | IPA through the App Store Connect API build upload (or altool), build number checked, waits until VALID (exit 0 / 1 / 7); dry first, asks |
|
||||
| `apple next-build` | API, read-only | next safe build number |
|
||||
| `apple status` | API | versions, builds, IAPs, submissions; `--wait-review` (exit 0 / 1 / 7); `--cancel-submission <id>` |
|
||||
| `apple ppo status \| create --variant b \| upload --variant b` | API | Product Page Optimization test from `shots` variants: treatments, localizations, screenshot sets |
|
||||
|
|
@ -268,6 +391,8 @@ run in the background with a log (`storebound shots render > .storebound/render.
|
|||
| `apple testflight what-to-test --build N` | API | "What to Test" per locale from `store/appstore.md` (`whatToTest`, else `whatsNew`) |
|
||||
| `apple testflight info` | API | Beta App Description, feedback email, URLs, Beta App Review contact and notes |
|
||||
| `apple testflight distribute --build N --group a,b [--submit-review]` | API | the build to groups; external groups and Beta App Review ask first |
|
||||
| `apple testflight wait --build N [--timeout 60m]` | API, read-only | until processing ends, with progress; exit 0 VALID / 1 FAILED / 7 timeout |
|
||||
| `apple testflight expire --keep N \| --older-than D` | API | expire old builds (never attached or processing ones); dry run, then asks |
|
||||
|
||||
</details>
|
||||
|
||||
|
|
@ -285,6 +410,9 @@ run in the background with a log (`storebound shots render > .storebound/render.
|
|||
| `analytics setup` | API | App Store analytics report request (once, Admin key) |
|
||||
| `analytics snapshot [--days 28]` | API + local | impressions, page views, downloads (App Store), visitors, acquisitions, installs (Play reports bucket) -> `.storebound/analytics/` |
|
||||
| `analytics compare` | local | snapshots vs the git history of the store files: before / after each listing change |
|
||||
| `reports apple-sales \| apple-finance \| play-earnings \| play-sales` | API, read-only + local | sales / finance reports into `.storebound/reports/`, summary per product and currency, CSV export |
|
||||
| `triage [--days 14]` | API, read-only | TestFlight crash and screenshot feedback, Play error reports: grouped by signature with devices, OS versions, builds |
|
||||
| `aso rank [--storefronts us,de]` | network + local | App Store rank per keyword and storefront plus competitors from the public iTunes Search API (rate limited) -> `.storebound/aso/` |
|
||||
|
||||
</details>
|
||||
|
||||
|
|
@ -304,6 +432,127 @@ run in the background with a log (`storebound shots render > .storebound/render.
|
|||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Many apps and release trains</b></summary>
|
||||
|
||||
| command | kind | what |
|
||||
|---|---|---|
|
||||
| `ws init` | local | find the app folders below and write `storebound.workspace.json` (globs like `games/*`) |
|
||||
| `ws list [--all]` | local | apps (folders + store-only apps), studios, accounts and whether each credential profile has its keys |
|
||||
| `ws status [--offline] [--apps a,b]` | API, read-only | portfolio table: every app x both stores (live / rollout % / next version), catalog parity, check; parallel |
|
||||
| `ws check`, `ws validate [--apps a,b]` | local / API, read-only | the offline check / the readiness report of every app in one table |
|
||||
| `ws run <command> --apps a,b \| --all [--apply]` | per command | any read command in every app; writes as dry runs unless `--apply`; never submit / release / rollout / send |
|
||||
| `ws apps import --account <profile>` | API, read-only + local cache | the apps a store account sees, paired with the folders (the desktop's rules) |
|
||||
| `ws desktop export [--out f \| --merge [--apply]]`, `ws desktop import` | local | the workspace to and from the desktop app's state (labels, never keys) |
|
||||
| `release status [--app a,b] [--versions]` | API, read-only | both stores on one train per version: build > testing > review > live > rollout % |
|
||||
| `release plan <version> [--app a]` | API, read-only | what is left for that version on each store, in fix order, with the owner's next step |
|
||||
|
||||
</details>
|
||||
|
||||
## 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
|
||||
folders. `storebound ws init` writes `storebound.workspace.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"apps": ["games/*", { "path": "apps/notes", "apple": "solo-apple" }],
|
||||
"studios": [
|
||||
{ "name": "Acme Games", "color": "indigo", "apps": ["games/*"],
|
||||
"accounts": [{ "store": "apple", "profile": "acme-apple" }, { "store": "play", "profile": "acme-play" }] }
|
||||
],
|
||||
"accounts": [{ "store": "apple", "profile": "solo-apple", "label": "Solo" }],
|
||||
"ignore": ["games/old-*"],
|
||||
"overrides": { "pairs": [], "unpairs": [], "links": [], "appStudio": [] },
|
||||
"concurrency": 4
|
||||
}
|
||||
```
|
||||
|
||||
- **apps**: folders or globs (only folders with a `storebound.config.*` count; `node_modules` and dot folders are
|
||||
skipped). An object entry names the folder's own credential profiles.
|
||||
- **studios**: name, colour (the desktop's set), the store accounts and the app folders (globs) that belong to it.
|
||||
- **accounts**: store accounts without a studio. An account is a store and a **credential profile** name, never a key.
|
||||
- **ignore**: folder globs, `app:<store app key>` and `account:<profile>`, as in the desktop's ignore list.
|
||||
- **overrides**: the desktop's pairing corrections (`pairs`, `unpairs`, `links` of a store app to a folder,
|
||||
`appStudio`), with folders named by their path. A `storebound.workspace.ts` with `export default { ... }` works too.
|
||||
|
||||
Which keys an app uses: its own entry's profiles, else the single account of that store in its studio, else the
|
||||
single account of that store in the workspace, else the folder's own credentials (env or `.storebound/`).
|
||||
|
||||
**Credential profiles** keep many accounts apart on one machine: `~/.storebound/credentials/<profile>.json` with the
|
||||
account names of `.storebound/credentials.json` (`PLAY_SERVICE_ACCOUNT`, `ASC_KEY_ID`, `ASC_ISSUER_ID`, `ASC_P8`,
|
||||
`ASC_VENDOR_NUMBER`; the Android upload keystore belongs to the app and stays in the project;
|
||||
relative key paths are relative to that folder, which `STOREBOUND_CREDENTIALS_DIR` can move), or env
|
||||
`STOREBOUND_PROFILE_<NAME>_<KEY>` (for CI). Any command takes `--account <profile>`. `ws list` shows per account whether
|
||||
its profile has keys; no command prints a key.
|
||||
|
||||
`ws status`, `ws check`, `ws validate` and `ws run` read the apps a few at a time (`concurrency`, 1-8, or
|
||||
`--concurrency`), each app with its own keys handed to its child process only. `ws run` takes any read command and
|
||||
the MCP tool set; write commands get `--dry` unless `--apply`, and submit, release, rollout, send, start / stop,
|
||||
testers and `--yes` are refused: those stay with the owner in the app folder.
|
||||
|
||||
`ws apps import --account <profile>` lists the apps a store account sees (as `apps list`) into
|
||||
`.storebound/workspace/` and pairs them with the folders by the desktop's rules (`cli/lib/identity.ts`, the same code):
|
||||
a folder takes the store apps its config names, the remaining iOS and Android apps pair by id, close id or name,
|
||||
`unpairs` keep two apart, and the rest are store-only apps that `ws status` reads too.
|
||||
|
||||
**The desktop app** keeps the same model (studios, accounts, folders, overrides). `ws desktop import` turns its
|
||||
`state.json` (or `--state <file>`) into a workspace file and lists the credential profiles to create: the desktop's
|
||||
keychain is never read. `ws desktop export` prints the workspace as a desktop state (`--out <file>`), and
|
||||
`--merge --apply` adds it to the desktop's `state.json` while the app is closed (a backup is kept; nothing is
|
||||
removed; new accounts get their keys in the desktop's Accounts screen).
|
||||
|
||||
MCP: `workspace_list` (offline) and `workspace_status` (read-only).
|
||||
|
||||
## Release trains
|
||||
|
||||
One version, both stores, one track: **build > testing > review > live > rollout**. The CLI and the desktop's Releases
|
||||
tab share the code (`cli/lib/train.ts`, `cli/lib/portfolio.ts`), so both show the same stage for the same store state.
|
||||
|
||||
```
|
||||
$ storebound release status
|
||||
app version train App Store Google Play
|
||||
------ ------- ------- ---------------------- -----------------------------
|
||||
Puzzle 2.3.0 current rollout 20% (build 45) rollout 10% (build 230)
|
||||
Puzzle 2.4.0 next build testing (build 240, internal)
|
||||
```
|
||||
|
||||
`release plan <version>` lists what is left for that version on each store in fix order: config problems (`check`),
|
||||
the version on the store (how to create it when it is missing), store blockers (`validate`, while nothing is
|
||||
submitted), the next move and the warnings. Owner steps (submit for review, promote to production, release an approved
|
||||
version, raise or complete a rollout) are named with where the owner does them; storebound does not do them. A store
|
||||
it cannot read is "unknown", never "not there". Both commands work in an app folder (that app) and in a workspace
|
||||
(every app, or `--app a,b`); `--json` gives the structured result. MCP: `release_status`, `release_plan` (read-only).
|
||||
## Every endpoint
|
||||
|
||||
The commands above cover the journey. For anything else, `storebound api` calls **every operation** of the App Store
|
||||
Connect API (1303 operations, OpenAPI 4.5.1) and of the Google Play Developer APIs (Android Publisher v3: 145,
|
||||
Play Developer Reporting v1beta1: 25), generated from the official specs pinned in `specs/` (source URLs, dates and
|
||||
SHA-256 in `specs/SOURCES.json`). Same credentials, same retries on 429 / 5xx (Retry-After honoured), JSON:API
|
||||
documents on the Apple side.
|
||||
|
||||
```sh
|
||||
storebound api list --store apple --search "customerReviews" # find an operation
|
||||
storebound api apple apps_getCollection --param 'filter[bundleId]=com.example.app'
|
||||
storebound api apple GET /v1/apps/123/appStoreVersions --all-pages # METHOD path works too
|
||||
storebound api play reviews.list --param packageName=com.example.app --all-pages --json
|
||||
storebound api play POST /v1beta1/apps/com.example.app/crashRateMetricSet:query --body query.json
|
||||
storebound api coverage # counts per API and resource, what commands wrap
|
||||
```
|
||||
|
||||
- **GET runs right away** (so do the Reporting API `:query` calls and other POSTs that only read).
|
||||
- **Every write is a dry run by default**: it prints the exact request (method, URL, body; the credential is never
|
||||
shown) and is only sent with `--yes` from an interactive terminal.
|
||||
- **Owner-only operations** (submit, release, delete, cancel, refunds, prices, testers and users, review replies,
|
||||
product page tests, Play `edits.commit`, app signing; the list is in `cli/api/gate.ts`) also ask you to type the
|
||||
operation id before anything is sent.
|
||||
- **Agents read, never write**: MCP has one tool for this, `api_get` (GET operations only). Under MCP or the desktop
|
||||
app no write goes out, whatever the flags.
|
||||
- Small on purpose: one table row per operation plus generic helpers (`cli/api/`), typed from the rows (path and
|
||||
required parameters, JSON:API request and response shapes). `bun tools/gen-api.ts` regenerates the tables and
|
||||
[docs/api-coverage.md](docs/api-coverage.md) (every operation, its gate and the commands that already call it);
|
||||
CI fails when they are stale.
|
||||
|
||||
## Store art
|
||||
|
||||
Screenshots and previews are one step of the journey, but the one that takes the longest by hand, so storebound
|
||||
|
|
@ -364,12 +613,14 @@ navigation.
|
|||
| `migrate-from-fastlane` | `storebound import fastlane`: ids, listings, languages and screenshots from fastlane; keys and accounts stay out |
|
||||
| `play-first-release` | Google Play from zero to "In review" |
|
||||
| `appstore-first-release` | App Store from API key to "Waiting for review", incl. xcodebuild with the API key |
|
||||
| `testflight` | beta groups, testers from a CSV that never enters git, What to Test, Test Information, Beta App Review |
|
||||
| `store-iap-setup` | in-app products on both stores (consumable, non-consumable, non-renewing), prices and the price sheet CSV, catalog diff, testers, the first-IAP-with-version rule |
|
||||
| `build-and-sign` | API signing (capabilities, certificate, profiles), `apple build` / `apple upload`, `play build` / `play upload`, for native, Capacitor, React Native, Flutter and Unity projects |
|
||||
| `testflight` | beta groups, testers from a CSV that never enters git, What to Test, Test Information, Beta App Review, waiting for processing, expiring old builds |
|
||||
| `store-iap-setup` | in-app products on both stores (consumable, non-consumable, non-renewing), prices and the price sheet CSV, catalog diff, testers, review submissions through the API and the first-IAP-with-version rule |
|
||||
| `store-subscriptions` | subscription groups, levels, base plans, prices, intro and promotional offers, offer codes, disclosure and Terms (3.1.2), first submission |
|
||||
| `review-access` | demo account for reviewers (App Review fields, Play App access), never committed |
|
||||
| `account-deletion` | Apple 5.1.1(v) in-app deletion, Play delete-account web page and Data safety |
|
||||
| `aso-basics` | keyword field, subtitle, cross-localization, Play placement without stuffing |
|
||||
| `aso-basics` | keyword field, subtitle, cross-localization, Play placement without stuffing, keyword ranks via the iTunes Search API |
|
||||
| `app-store-promotion` | IAP offer codes, win-back offers, promoted IAPs, pre-orders (Play pre-registration: console guide), custom product pages, in-app events |
|
||||
| `store-declarations` | every questionnaire: Play Data safety (API) and App content (IARC, target audience, ads, advertising ID, app access, government / financial / health), Apple App Privacy labels and age rating |
|
||||
| `export-compliance` | encryption answer, Info.plist key, declarations; never exempt by default |
|
||||
| `privacy-policy` | one policy page for all your apps with a per-app services table (templates per profile) |
|
||||
|
|
@ -377,15 +628,18 @@ navigation.
|
|||
| `app-icons` | one artwork to every icon, adaptive / legacy launcher pitfalls |
|
||||
| `store-screenshots` | capture from any engine, copy, fonts, render, checks, gallery, variants, App Store product page tests, Play experiments, upload |
|
||||
| `app-previews` | app or gameplay clips, App Store previews, Play promo video, checks, upload |
|
||||
| `store-preflight` | run and read `check`, `check --aso`, `validate`, `privacy-manifest` and `release plan` before submitting; `ws check` / `ws validate` for many apps |
|
||||
| `release-management` | updates: release trains (`release status`, `release plan`), Apple phased + manual release, Play staged rollout, halt / pause (not a rollback), review wait |
|
||||
| `store-preflight` | run and read `check`, `check --aso`, `validate`, `privacy-manifest` before submitting |
|
||||
| `release-management` | updates: Apple phased + manual release, Play staged rollout, halt / pause (not a rollback), review wait |
|
||||
| `store-health` | crash / ANR vitals vs Play's bad behavior thresholds, App Store diagnostics, weekly report |
|
||||
| `store-api` | any App Store Connect / Google Play operation without a command: find it, read freely, writes dry until the owner sends them |
|
||||
| `release-management` | updates: Apple phased + manual release, Play staged rollout, halt / pause (not a rollback), review wait, pulling console edits back |
|
||||
| `store-health` | crash / ANR vitals vs Play's bad behavior thresholds, App Store diagnostics, weekly report, crash and feedback triage |
|
||||
| `review-replies` | reply drafts, tone, no incentives, store limits, the owner approves and sends |
|
||||
| `store-analytics` | App Store analytics reports, Play reports bucket, before / after listing changes |
|
||||
| `whats-new` | player-facing release notes from git, localized, within store limits |
|
||||
| `store-analytics` | App Store analytics reports, Play reports bucket, before / after listing changes, sales / finance / earnings reports |
|
||||
| `whats-new` | player-facing release notes from git, one file per language for your agent to translate, store limits checked |
|
||||
| `review-rejections` | triage a rejection (fix / clarify / push back / appeal), reply template, the guidelines apps and games hit |
|
||||
| `ads-mediation-checks` | AdMob, AppLovin MAX and LevelPlay: ids, debug tools, adapters, app-ads.txt, SKAdNetwork, no-fill (`ads-levelplay-checks` stays as a pointer) |
|
||||
| `portfolio-originality` | Guideline 4.3 gate for developers shipping many similar apps or games |
|
||||
| `ads-mediation-checks` | AdMob, AppLovin MAX and LevelPlay: ids, debug tools, adapters, app-ads.txt, SKAdNetwork, AdAttributionKit (`ads scan`), no-fill (`ads-levelplay-checks` stays as a pointer) |
|
||||
| `portfolio-originality` | Guideline 4.3 gate for developers shipping many similar apps or games, with `storebound originality` scores |
|
||||
|
||||
## MCP server
|
||||
|
||||
|
|
@ -394,9 +648,12 @@ per-request `_meta`, `resultType`, cacheable `tools/list`) and, on the same proc
|
|||
`initialize` (2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05). It runs each tool as a CLI call in the project directory
|
||||
(the server's working directory, or `STOREBOUND_PROJECT`) and returns the output.
|
||||
|
||||
- One tool per command. Read-only: `check`, `check_aso`, `validate`, `catalog_diff`, `health`, `reviews_list`, `prices_diff`,
|
||||
- One tool per command. Read-only: `scan`, `check`, `check_aso`, `validate`, `catalog_diff`, `health`, `reviews_list`, `prices_diff`,
|
||||
`analytics_compare`, `apple_status`, `apple_next_build`, `apple_testflight_status`, `apple_ppo_status`,
|
||||
`play_status`, `play_next_version_code`, `privacy_manifest`, `shots_check`. Local writes: `import_fastlane`, `whats_new`, `icons`,
|
||||
`play_status`, `play_next_version_code`, `privacy_manifest`, `shots_check`, `workspace_list`, `workspace_status`,
|
||||
`release_status`, `release_plan`. Local writes: `import_fastlane`, `whats_new`, `icons`,
|
||||
`play_status`, `play_next_version_code`, `privacy_manifest`, `shots_check`, `api_get` (any App Store Connect or
|
||||
Google Play GET operation by id). Local writes: `import_fastlane`, `whats_new`, `icons`,
|
||||
`health_report`, `reviews_draft`, `prices_export`, `analytics_snapshot`, `shots_capture`, `shots_render`,
|
||||
`shots_gallery`, `shots_record`, `shots_video`. Store writes: `play_listing`, `play_images`, `play_products`,
|
||||
`play_data_safety`, `play_subscriptions`, `play_release_testing`, `apple_bundle`, `apple_iap`, `apple_iap_review`,
|
||||
|
|
@ -430,6 +687,8 @@ model and the Dependencies screen (tool sources and licenses): [docs/desktop.md]
|
|||
storebound only talks to the official store APIs (plus Google Fonts, your own Play reports bucket and your own URLs);
|
||||
see [SECURITY.md](SECURITY.md).
|
||||
- **Dry run everywhere.** Every write command takes `--dry`; every MCP write tool has `dry_run`, **default true**.
|
||||
Raw API writes (`storebound api`) are dry unless `--yes` is given in an interactive terminal; owner-only operations
|
||||
also need the operation id typed, and MCP only gets the read-only `api_get`.
|
||||
- **Nothing public or irreversible through an agent.** Submitting for review (App Review and Beta App Review),
|
||||
releasing a version, production releases, resuming or completing a rollout or phased release, canceling a
|
||||
submission, deleting, inviting or removing testers, sending review replies, applying prices and starting or
|
||||
|
|
@ -498,9 +757,9 @@ in 0.4.0. 0.5.0 made storebound app-first (profiles, app screenshot style, accou
|
|||
brought the full in-app catalog: subscriptions on both stores with offers and offer codes, non-renewing products and
|
||||
the cross-store `catalog diff`. Next, roughly in this order:
|
||||
|
||||
- Offer codes for one-time products (`inAppPurchaseOfferCodes`), Play prepaid base plans for `non_renewing`, win-back
|
||||
offers, and a `prices export` that includes subscriptions.
|
||||
- App Store custom product pages and in-app events from the same copy and renders.
|
||||
- Play prepaid base plans for `non_renewing`, and a `prices export` that includes subscriptions.
|
||||
- The App Asset Library (API 4.5.1) for screenshots, custom product pages and in-app events once the screenshot sets
|
||||
it replaces stop working.
|
||||
- Play store listing experiments and their results, as soon as Google offers an API.
|
||||
- App preview treatments and alternate icons in Product Page Optimization tests.
|
||||
- The iPhone Duo screenshot classes Apple lists for apps built with the iOS 27.1 SDK (required from April 2027).
|
||||
|
|
@ -541,7 +800,13 @@ Checked against each tool's own docs in October 2026:
|
|||
pay-as-you-go offers as a `relativeDiscount`, Play "developer determined" offers as offers without targeting plus an
|
||||
offer tag, the ISO 8601 strings for Play billing periods (Google lists them only in words), the Play subscription
|
||||
benefit length (40, from Play Console), the Data safety sign-up method ids (`PSL_ACM_*`, Google publishes none:
|
||||
compare with a Console export) and the delete-account URL question id (use `dataSafety.extra`).
|
||||
compare with a Console export) and the delete-account URL question id (use `dataSafety.extra`). From the store
|
||||
operations (built from the App Store Connect API 4.5.1 OpenAPI spec and the cited Help pages, tested with recorded
|
||||
answers, not yet run live): the first IAP of a type sent through `reviewSubmissionItems` next to the app version
|
||||
(`--no-submit` leaves the draft for the UI if Apple refuses it), free IAP offer code and win-back prices without a
|
||||
price point, the order request for promoted purchases, the Play earnings / sales zip names beyond the documented
|
||||
prefix (storebound lists the prefix), and where Xcode stores `AttributionCopyEndpoint` (top level or inside an
|
||||
`AdAttributionKit` dictionary: both are read).
|
||||
- **Apple IAP description**: 45 characters (App Store Connect Help, "In-app purchase information"); an older App Store
|
||||
marketing page says 55. storebound checks 45.
|
||||
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@
|
|||
import { type Account, type AccountCheck, type ConsoleFillResult, type ConsoleForm, type AppsListResult, type AppStatus, type CacheEntry, DEFAULT_SETTINGS, type DownloadEvent, type DraftsResult, type ListingField, type ListingsResult,
|
||||
type PortfolioResult, type Project, type ProjectSummary, type Settings, type StoreApp, type StoreRelease, type Studio, type ToolResult } from '../api';
|
||||
import { buildApps, type Overrides } from '../lib/identity';
|
||||
import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult } from '../lib/model';
|
||||
import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult, ScanResult } from '../lib/model';
|
||||
import { ANALYTICS, DECLARATIONS, LISTING_TEXT, PPO, PPO_STORE, PRICE_DIFF, PRICES, renderArt, RENDERS } from './fixtures-more';
|
||||
|
||||
export const FIXTURE_MARKER = 'storebound-dev-fixtures';
|
||||
|
|
@ -342,6 +342,30 @@ const VALIDATE: Record<string, ValidateResult> = {
|
|||
'p-tidy': { blockers: 0, findings: [] },
|
||||
};
|
||||
|
||||
const scanCounts = (f: ScanResult['findings']): ScanResult['counts'] => {
|
||||
const c = { blocker: 0, high: 0, medium: 0, low: 0, accepted: 0 };
|
||||
for (const x of f) { if (x.accepted) c.accepted++; else c[x.severity]++; }
|
||||
return c;
|
||||
};
|
||||
const SCAN_PRISM: ScanResult['findings'] = [
|
||||
{ rule: 'att', guideline: '5.1.2(i)', store: 'apple', severity: 'high', title: 'Tracking-capable code without App Tracking Transparency (AppLovin MAX, Unity Ads)',
|
||||
evidence: [{ file: 'Packages/manifest.json', line: 4, text: 'com.applovin.mediation.ads 8.1.0' }], fix: 'Add NSUserTrackingUsageDescription and request ATT before the SDKs start, or configure non-personalized ads and answer "no tracking".', skill: 'ads-mediation-checks', ref: 'https://developer.apple.com/app-store/review/guidelines/' },
|
||||
{ rule: 'play-target-sdk', guideline: 'Play: Target API level', store: 'play', severity: 'blocker', title: 'targetSdk 35 is below 36, which new apps and updates need since 2026-08-31',
|
||||
evidence: [{ file: 'ProjectSettings/ProjectSettings.asset', line: 212, text: 'targetSdk 35' }], fix: 'Raise targetSdk to 36, test, upload a new AAB.', skill: 'play-first-release', ref: 'https://developer.android.com/google/play/requirements/target-sdk' },
|
||||
{ rule: 'restore-purchases', guideline: '3.1.1', store: 'apple', severity: 'high', title: 'Restorable purchases (non-consumables or subscriptions) but no Restore Purchases path was found',
|
||||
evidence: [{ file: 'storebound.config.ts', line: 41, text: 'no_ads (non_consumable)' }], fix: 'Add a visible "Restore Purchases" button on the store screen or in Settings.', skill: 'store-iap-setup', ref: 'https://developer.apple.com/app-store/review/guidelines/' },
|
||||
{ rule: 'demo-account', guideline: '2.1(a)', store: 'apple', severity: 'blocker', title: 'Sign-in is required but there is no demo account for App Review',
|
||||
evidence: [{ file: 'storebound.config.ts', line: 17, text: 'reviewAccess: { signInRequired: true }' }], fix: 'Add the App Review demo account in .storebound/ (review-access skill).', skill: 'review-access', ref: 'https://developer.apple.com/app-store/review/guidelines/', accepted: 'leaderboards only; the game plays without signing in' },
|
||||
];
|
||||
const SCAN: Record<string, ScanResult> = {
|
||||
'p-prism': { stacks: ['unity'], sdks: [{ id: 'applovin', name: 'AppLovin MAX', category: 'ads', tracking: true }, { id: 'unity-ads', name: 'Unity Ads', category: 'ads', tracking: true }, { id: 'gameanalytics', name: 'GameAnalytics', category: 'analytics', tracking: false }],
|
||||
findings: SCAN_PRISM, counts: scanCounts(SCAN_PRISM),
|
||||
declarations: { changed: true, items: [{ area: 'appPrivacy', what: 'tracking', value: 'AppLovin MAX, Unity Ads can track', status: 'ask', evidence: [] }, { area: 'dataSafety', what: 'PSL_DEVICE_ID', value: 'collect: advertising, analytics, fraud', status: 'detected', evidence: [{ file: 'Packages/manifest.json', line: 4 }] }] } },
|
||||
'p-tidy': { stacks: ['ios-native', 'android-native'], sdks: [{ id: 'sentry', name: 'Sentry', category: 'crash', tracking: false }], findings: [], counts: scanCounts([]),
|
||||
declarations: { changed: false, items: [] } },
|
||||
};
|
||||
const SCAN_EMPTY: ScanResult = { stacks: [], sdks: [], findings: [], counts: scanCounts([]), declarations: { changed: false, items: [] } };
|
||||
|
||||
function field(f: string, length: number, limit: number, required = true): ListingField {
|
||||
return { field: f, length, limit, required, state: !length ? (required ? 'missing' : 'empty-optional') : length > limit ? 'over' : 'ok' };
|
||||
}
|
||||
|
|
@ -404,6 +428,7 @@ function read(method: string, id: string, args: Record<string, unknown> = {}): T
|
|||
case 'apple.testflight_status': return ok(method, TF[id]);
|
||||
case 'catalog.diff': return ok(method, CATALOG[id]);
|
||||
case 'validate': return ok(method, VALIDATE[id]);
|
||||
case 'scan': return ok(method, SCAN[id] ?? SCAN_EMPTY);
|
||||
case 'project.declarations': return ok(method, DECLARATIONS[id]);
|
||||
case 'project.listing_text': return ok(method, LISTING_TEXT[id]);
|
||||
case 'project.renders': return ok(method, RENDERS[id]);
|
||||
|
|
|
|||
|
|
@ -396,6 +396,21 @@ export const en = {
|
|||
'checks.validateEmptyText': 'What is still missing on the App Store and Google Play before a submission, in the order to fix it.',
|
||||
'checks.ready': 'No blockers',
|
||||
'checks.readyText': 'Both stores have what a submission needs.',
|
||||
'checks.scan': 'Rejection risks',
|
||||
'checks.scanSub': 'Offline scan of the project files: guideline, evidence, fix',
|
||||
'checks.scanAgain': 'Scan again',
|
||||
'checks.scanClean': 'No rejection risks found',
|
||||
'checks.scanCleanText': 'Nothing in the project files, config or listings matches a known App Store rejection or Google Play policy issue.',
|
||||
'checks.scanSdks': 'SDKs: {list}',
|
||||
'checks.scanAsk': '{count} declaration answers only you can give',
|
||||
'checks.scanAsk_one': '1 declaration answer only you can give',
|
||||
'checks.scanWrite': 'Detected Data safety / App Privacy answers differ from the config: storebound scan --write adds them',
|
||||
'checks.accepted': 'Accepted: {reason}',
|
||||
'checks.sev.blocker': 'Blocker',
|
||||
'checks.sev.high': 'High',
|
||||
'checks.sev.medium': 'Medium',
|
||||
'checks.sev.accepted': 'Accepted',
|
||||
'checks.sev.low': 'Low',
|
||||
|
||||
'folders.lead': 'One folder per app with its storebound.config.ts (iOS and Android in one config). Pick the store accounts each app uses; the keys stay in the keychain.',
|
||||
'folders.list': 'App folders',
|
||||
|
|
|
|||
|
|
@ -398,6 +398,21 @@ export const tr: Record<keyof typeof en, string> = {
|
|||
'checks.validateEmptyText': 'Göndermeden önce App Store ve Google Play\'de hâlâ eksik olanlar, düzeltme sırasıyla.',
|
||||
'checks.ready': 'Engel yok',
|
||||
'checks.readyText': 'İki mağazada da gönderim için gerekenler tamam.',
|
||||
'checks.scan': 'Ret riskleri',
|
||||
'checks.scanSub': 'Proje dosyalarının çevrimdışı taraması: kural, kanıt, çözüm',
|
||||
'checks.scanAgain': 'Yeniden tara',
|
||||
'checks.scanClean': 'Ret riski bulunmadı',
|
||||
'checks.scanCleanText': 'Proje dosyalarında, ayarda ve mağaza metinlerinde bilinen bir App Store reddine veya Google Play politika sorununa uyan bir şey yok.',
|
||||
'checks.scanSdks': 'SDK\'lar: {list}',
|
||||
'checks.scanAsk': 'Yalnızca senin cevaplayabileceğin {count} beyan sorusu',
|
||||
'checks.scanAsk_one': 'Yalnızca senin cevaplayabileceğin 1 beyan sorusu',
|
||||
'checks.scanWrite': 'Bulunan Data safety / App Privacy cevapları ayardan farklı: storebound scan --write ekler',
|
||||
'checks.accepted': 'Kabul edildi: {reason}',
|
||||
'checks.sev.blocker': 'Engel',
|
||||
'checks.sev.high': 'Yüksek',
|
||||
'checks.sev.medium': 'Orta',
|
||||
'checks.sev.accepted': 'Kabul',
|
||||
'checks.sev.low': 'Düşük',
|
||||
|
||||
'folders.lead': 'Her uygulama için storebound.config.ts dosyası olan bir klasör (iOS ve Android tek ayarda). Her uygulamanın kullandığı mağaza hesaplarını seçin; anahtarlar anahtar zincirinde kalır.',
|
||||
'folders.list': 'Uygulama klasörleri',
|
||||
|
|
|
|||
|
|
@ -1,196 +1,14 @@
|
|||
// One app card per product, across studios and store accounts. Pure, so tests/identity.test.ts pins every rule.
|
||||
//
|
||||
// Inputs: app folders (with the store ids of their config), the apps each store account can see (`apps list`), and
|
||||
// the owner's overrides (manual pairs / unpairs, links of a store app to a folder, studio moves, the ignore list).
|
||||
// Order of matching:
|
||||
// 1. a folder takes the store apps its config names (explicit link > App Store app id > bundle id / package name),
|
||||
// preferring the accounts mapped to the folder;
|
||||
// 2. the remaining store apps pair iOS + Android: manual pairs, then the same bundle id and package name, then a
|
||||
// close id (".ios" / ".android" suffixes, case, punctuation) or the same name; unpairs block an automatic pair;
|
||||
// 3. what is left is a single-platform store-only app.
|
||||
// A store-only app is read through a "store target" (store:ios:<account>:<app id>:<bundle>;android:<account>:<package>).
|
||||
import type { Account, AppStatus, Project, StoreApp } from '../api';
|
||||
// One app card per product, across studios and store accounts. The pairing rules live in cli/lib/identity.ts (shared
|
||||
// with the CLI workspace, `storebound ws`); this file adds the desktop's types and the portfolio list helpers.
|
||||
import type { Project } from '../api';
|
||||
import type { UnifiedApp as CoreApp } from '../../../../cli/lib/identity';
|
||||
|
||||
export interface Pair { ios: string; android: string }
|
||||
export interface Overrides {
|
||||
pairs: Pair[];
|
||||
unpairs: Pair[];
|
||||
links: { key: string; project: string }[];
|
||||
appStudio: { key: string; studio: string }[];
|
||||
ignored: string[];
|
||||
}
|
||||
export const NO_OVERRIDES: Overrides = { pairs: [], unpairs: [], links: [], appStudio: [], ignored: [] };
|
||||
export {
|
||||
buildApps, type BuildInput, NO_OVERRIDES, normId, normName, type Overrides, type Pair, pairCandidates, type Pairing, refKey, type StoreRef, storeTarget,
|
||||
withIgnored, withLink, withPair, withStudio, withUnpair,
|
||||
} from '../../../../cli/lib/identity';
|
||||
|
||||
/** One app record of one store account. */
|
||||
export interface StoreRef { key: string; account: string; store: 'ios' | 'android'; app: StoreApp }
|
||||
|
||||
export type Pairing = 'folder' | 'manual' | 'id' | 'close' | 'name' | 'single';
|
||||
|
||||
export interface UnifiedApp {
|
||||
/** Route and list key: the project id, else the store target. */
|
||||
key: string;
|
||||
/** What reads use: the project id, else the store target ("store:..."). */
|
||||
target: string;
|
||||
name: string;
|
||||
project: Project | null;
|
||||
ios: StoreRef | null;
|
||||
android: StoreRef | null;
|
||||
studio: string | null;
|
||||
pairing: Pairing;
|
||||
/** The keys an "ignore" puts on the list ("project:<id>" or "app:<store key>"). */
|
||||
ignoreKeys: string[];
|
||||
ignored: boolean;
|
||||
/** Store icon (data URL) when the folder has none. */
|
||||
storeIcon: string | null;
|
||||
}
|
||||
|
||||
export const refKey = (account: string, a: StoreApp): string => `${a.store}:${account}:${a.id}`;
|
||||
|
||||
/** Store target of a store-only app. */
|
||||
export function storeTarget(ios: StoreRef | null, android: StoreRef | null): string {
|
||||
const parts: string[] = [];
|
||||
if (ios) parts.push(`ios:${ios.account}:${ios.app.id}:${ios.app.bundleId}`);
|
||||
if (android) parts.push(`android:${android.account}:${android.app.id}`);
|
||||
return `store:${parts.join(';')}`;
|
||||
}
|
||||
|
||||
/** "com.example.Puzzle.ios" -> "comexamplepuzzle": ids that differ only by a platform suffix, case or punctuation. */
|
||||
export function normId(id: string): string {
|
||||
return id.toLowerCase().replace(/[._-](ios|iphone|android|droid|app)$/g, '').replace(/[^a-z0-9]/g, '');
|
||||
}
|
||||
export const normName = (n: string): string => n.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]/g, '');
|
||||
|
||||
const samePair = (p: Pair, ios: string, android: string) => p.ios === ios && p.android === android;
|
||||
|
||||
export interface BuildInput {
|
||||
projects: Project[];
|
||||
/** Store ids of each folder's config (from the offline portfolio read). */
|
||||
summaryOf: (p: Project) => AppStatus['summary'] | undefined;
|
||||
accounts: Account[];
|
||||
/** The last app list of each account. */
|
||||
storeApps: { account: string; apps: StoreApp[] }[];
|
||||
overrides: Overrides;
|
||||
}
|
||||
|
||||
export function buildApps(i: BuildInput): UnifiedApp[] {
|
||||
const o = i.overrides;
|
||||
const ignoredAccounts = new Set(o.ignored.filter(x => x.startsWith('account:')).map(x => x.slice(8)));
|
||||
const accountStudio = new Map(i.accounts.map(a => [a.id, a.studio ?? null] as const));
|
||||
const known = new Set(i.accounts.map(a => a.id));
|
||||
// every store app of every (not ignored) account
|
||||
const refs: StoreRef[] = [];
|
||||
for (const s of i.storeApps) {
|
||||
if (!known.has(s.account) || ignoredAccounts.has(s.account)) continue;
|
||||
for (const app of s.apps) refs.push({ key: refKey(s.account, app), account: s.account, store: app.store, app });
|
||||
}
|
||||
const used = new Set<string>();
|
||||
const take = (r: StoreRef | null | undefined): StoreRef | null => { if (!r || used.has(r.key)) return null; used.add(r.key); return r; };
|
||||
const studioOverride = new Map(o.appStudio.map(x => [x.key, x.studio] as const));
|
||||
const ignored = new Set(o.ignored);
|
||||
const out: UnifiedApp[] = [];
|
||||
|
||||
// 1. folders
|
||||
for (const p of i.projects) {
|
||||
const s = i.summaryOf(p);
|
||||
const mine = (r: StoreRef) => r.account === (r.store === 'ios' ? p.appleAccount : p.playAccount);
|
||||
const rank = (rs: StoreRef[]) => [...rs].sort((a, b) => Number(mine(b)) - Number(mine(a)));
|
||||
const linked = o.links.filter(l => l.project === p.id).map(l => refs.find(r => r.key === l.key)).filter((r): r is StoreRef => !!r && !used.has(r.key));
|
||||
let ios = take(linked.find(r => r.store === 'ios'));
|
||||
let android = take(linked.find(r => r.store === 'android'));
|
||||
if (!ios && s?.apple) {
|
||||
const free = refs.filter(r => r.store === 'ios' && !used.has(r.key) && !o.links.some(l => l.key === r.key));
|
||||
ios = take(rank(free.filter(r => s.apple!.appId && r.app.id === s.apple!.appId))[0] ?? rank(free.filter(r => r.app.bundleId === s.apple!.bundleId))[0]);
|
||||
}
|
||||
if (!android && s?.play) {
|
||||
const free = refs.filter(r => r.store === 'android' && !used.has(r.key) && !o.links.some(l => l.key === r.key));
|
||||
android = take(rank(free.filter(r => r.app.id === s.play!.packageName))[0]);
|
||||
}
|
||||
const studio = studioOverride.get(`project:${p.id}`)
|
||||
?? (p.appleAccount && accountStudio.get(p.appleAccount)) ?? (p.playAccount && accountStudio.get(p.playAccount))
|
||||
?? (ios && accountStudio.get(ios.account)) ?? (android && accountStudio.get(android.account)) ?? null;
|
||||
out.push({
|
||||
key: p.id, target: p.id, name: p.name, project: p, ios, android, studio, pairing: 'folder',
|
||||
ignoreKeys: [`project:${p.id}`], ignored: ignored.has(`project:${p.id}`), storeIcon: ios?.app.icon ?? android?.app.icon ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
// 2. pairs among the remaining store apps
|
||||
const freeIos = () => refs.filter(r => r.store === 'ios' && !used.has(r.key));
|
||||
const freeAndroid = () => refs.filter(r => r.store === 'android' && !used.has(r.key));
|
||||
const blocked = (a: StoreRef, b: StoreRef) => o.unpairs.some(p => samePair(p, a.key, b.key));
|
||||
const sameStudio = (a: StoreRef, b: StoreRef) => (accountStudio.get(a.account) ?? null) === (accountStudio.get(b.account) ?? null);
|
||||
const pairs: [StoreRef, StoreRef, Pairing][] = [];
|
||||
for (const m of o.pairs) {
|
||||
const a = freeIos().find(r => r.key === m.ios), b = freeAndroid().find(r => r.key === m.android);
|
||||
if (a && b) { take(a); take(b); pairs.push([a, b, 'manual']); }
|
||||
}
|
||||
const auto = (how: Pairing, match: (a: StoreRef, b: StoreRef) => boolean) => {
|
||||
for (const a of freeIos()) {
|
||||
const cands = freeAndroid().filter(b => !blocked(a, b) && match(a, b)).sort((x, y) => Number(sameStudio(a, y)) - Number(sameStudio(a, x)));
|
||||
const b = cands[0];
|
||||
if (b) { take(a); take(b); pairs.push([a, b, how]); }
|
||||
}
|
||||
};
|
||||
auto('id', (a, b) => a.app.bundleId === b.app.id);
|
||||
auto('close', (a, b) => normId(a.app.bundleId) !== '' && normId(a.app.bundleId) === normId(b.app.id));
|
||||
auto('name', (a, b) => normName(a.app.name) !== '' && normName(a.app.name) === normName(b.app.name));
|
||||
|
||||
const storeOnly = (ios: StoreRef | null, android: StoreRef | null, pairing: Pairing) => {
|
||||
const target = storeTarget(ios, android);
|
||||
const keys = [ios, android].filter((r): r is StoreRef => !!r).map(r => r.key);
|
||||
const studio = keys.map(k => studioOverride.get(k)).find(Boolean)
|
||||
?? (ios && accountStudio.get(ios.account)) ?? (android && accountStudio.get(android.account)) ?? null;
|
||||
out.push({
|
||||
key: target, target, name: ios?.app.name ?? android?.app.name ?? '?', project: null, ios, android, studio, pairing,
|
||||
ignoreKeys: keys.map(k => `app:${k}`), ignored: keys.some(k => ignored.has(`app:${k}`)), storeIcon: ios?.app.icon ?? android?.app.icon ?? null,
|
||||
});
|
||||
};
|
||||
for (const [a, b, how] of pairs) storeOnly(a, b, how);
|
||||
// 3. singles
|
||||
for (const r of refs) if (!used.has(r.key)) { used.add(r.key); storeOnly(r.store === 'ios' ? r : null, r.store === 'android' ? r : null, 'single'); }
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Candidates to pair a single-platform app with (the other store's single apps), closest first. */
|
||||
export function pairCandidates(app: UnifiedApp, all: UnifiedApp[]): UnifiedApp[] {
|
||||
if (app.project || (app.ios && app.android)) return [];
|
||||
const want = app.ios ? 'android' : 'ios';
|
||||
const me = (app.ios ?? app.android)!;
|
||||
const score = (x: UnifiedApp) => {
|
||||
const r = (want === 'ios' ? x.ios : x.android)!;
|
||||
return (normId(r.app.bundleId) === normId(me.app.bundleId) ? 4 : 0) + (normName(r.app.name) === normName(me.app.name) ? 2 : 0) + (x.studio === app.studio ? 1 : 0);
|
||||
};
|
||||
return all.filter(x => !x.project && !x.ignored && (want === 'ios' ? x.ios && !x.android : x.android && !x.ios)).sort((a, b) => score(b) - score(a) || a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/** Overrides after pairing two single store apps by hand (drops an unpair of the same two). */
|
||||
export function withPair(o: Overrides, ios: string, android: string): Overrides {
|
||||
return { ...o, pairs: [...o.pairs.filter(p => p.ios !== ios && p.android !== android), { ios, android }], unpairs: o.unpairs.filter(p => !samePair(p, ios, android)) };
|
||||
}
|
||||
|
||||
/** Overrides after splitting a paired app (keeps it apart from now on). */
|
||||
export function withUnpair(o: Overrides, ios: string, android: string): Overrides {
|
||||
return { ...o, pairs: o.pairs.filter(p => !samePair(p, ios, android)), unpairs: [...o.unpairs.filter(p => !samePair(p, ios, android)), { ios, android }] };
|
||||
}
|
||||
|
||||
export function withIgnored(o: Overrides, keys: string[], on: boolean): Overrides {
|
||||
const set = new Set(o.ignored);
|
||||
for (const k of keys) { if (on) set.add(k); else set.delete(k); }
|
||||
return { ...o, ignored: [...set] };
|
||||
}
|
||||
|
||||
/** Moves an app to a studio (null: back to its accounts' studio). */
|
||||
export function withStudio(o: Overrides, app: UnifiedApp, studio: string | null): Overrides {
|
||||
const keys = app.project ? [`project:${app.project.id}`] : [app.ios?.key, app.android?.key].filter((k): k is string => !!k);
|
||||
const rest = o.appStudio.filter(x => !keys.includes(x.key));
|
||||
return { ...o, appStudio: studio ? [...rest, ...keys.map(key => ({ key, studio }))] : rest };
|
||||
}
|
||||
|
||||
/** Links the store apps of a store-only app to a folder. */
|
||||
export function withLink(o: Overrides, app: UnifiedApp, project: string): Overrides {
|
||||
const keys = [app.ios?.key, app.android?.key].filter((k): k is string => !!k);
|
||||
return { ...o, links: [...o.links.filter(l => !keys.includes(l.key)), ...keys.map(key => ({ key, project }))] };
|
||||
}
|
||||
export type UnifiedApp = CoreApp<Project>;
|
||||
|
||||
// ---- Portfolio list: filter, search, sort, group ----
|
||||
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
// Pure view models for the screens: release timeline stages, health series against the store thresholds, review
|
||||
// inbox stats, catalog parity matrix, the portfolio's "needs attention" list, and the command palette matcher.
|
||||
// "Unknown, never false": every derivation keeps "not read" apart from "none" / "ok".
|
||||
import type { AppStatus, ProjectSummary, ReleaseTrain, StoreRelease } from '../api';
|
||||
import type { AppStatus, ProjectSummary } from '../api';
|
||||
import { t } from '../i18n';
|
||||
|
||||
export type Tone = 'ok' | 'warn' | 'bad' | 'info' | 'neutral' | 'accent';
|
||||
import type { Tone } from '../../../../cli/lib/train';
|
||||
|
||||
export type { Tone };
|
||||
|
||||
// ---- CLI JSON shapes the screens read (the commands' --json output) ----
|
||||
|
||||
|
|
@ -31,72 +33,26 @@ export interface ParityRow { id: string; region: string; currency: string; apple
|
|||
export interface CatalogDiff { errors: number; rows: CatalogRow[]; parity: ParityRow[] }
|
||||
export interface Finding { store: 'apple' | 'play'; level: 'blocker' | 'warn' | 'ok'; code: string; msg: string; fix?: string }
|
||||
export interface ValidateResult { blockers: number; findings: Finding[] }
|
||||
/** `storebound scan --json` (offline rejection-risk scan of the project files), the parts the Checks tab shows. */
|
||||
export type ScanSeverity = 'blocker' | 'high' | 'medium' | 'low';
|
||||
export interface ScanFinding {
|
||||
rule: string; guideline: string; store: 'apple' | 'play'; severity: ScanSeverity; title: string;
|
||||
evidence: { file: string; line: number; text?: string }[]; fix: string; skill: string; ref: string; accepted?: string;
|
||||
}
|
||||
export interface ScanResult {
|
||||
stacks: string[];
|
||||
sdks: { id: string; name: string; category: string; tracking: boolean }[];
|
||||
findings: ScanFinding[];
|
||||
counts: Record<ScanSeverity, number> & { accepted: number };
|
||||
declarations: { changed: boolean; items: { area: string; what: string; value: string; status: 'detected' | 'ask'; evidence: { file: string; line: number }[] }[] };
|
||||
}
|
||||
|
||||
export const isError = (x: unknown): x is { error: string } => !!x && typeof x === 'object' && typeof (x as { error?: unknown }).error === 'string';
|
||||
|
||||
// ---- Release timeline ----
|
||||
// The stages and lanes live in cli/lib/train.ts, shared with `storebound release status | plan`.
|
||||
|
||||
/** Stages of one version on one store, left to right. */
|
||||
export const STAGES = ['build', 'testing', 'review', 'live', 'rollout'] as const;
|
||||
export type Stage = (typeof STAGES)[number];
|
||||
|
||||
export interface Lane {
|
||||
store: 'ios' | 'android';
|
||||
release: StoreRelease | null;
|
||||
/** Index of the stage it is at (-1: not on this store). */
|
||||
at: number;
|
||||
tone: Tone;
|
||||
/** Rollout share 0-1 when live or rolling out (1 = everyone). */
|
||||
share: number | null;
|
||||
/** The store's state word, for a tooltip. */
|
||||
state: string;
|
||||
}
|
||||
|
||||
/** Where a store release is on the track. Rollout counts as the last stage; a full release fills it. */
|
||||
export function laneOf(store: 'ios' | 'android', r: StoreRelease | null, testflightReached = false): Lane {
|
||||
if (!r) return { store, release: null, at: -1, tone: 'neutral', share: null, state: '' };
|
||||
const base = { store, release: r, state: r.state };
|
||||
switch (r.phase) {
|
||||
case 'draft': return { ...base, at: testflightReached ? 1 : 0, tone: testflightReached ? 'info' : 'neutral', share: null };
|
||||
case 'testing': return { ...base, at: 1, tone: 'info', share: null };
|
||||
case 'review': return { ...base, at: 2, tone: 'warn', share: null };
|
||||
case 'approved': return { ...base, at: 2, tone: 'ok', share: null };
|
||||
case 'rejected': return { ...base, at: 2, tone: 'bad', share: null };
|
||||
case 'live': return { ...base, at: 4, tone: 'ok', share: 1 };
|
||||
case 'rollout': return { ...base, at: 4, tone: 'accent', share: r.fraction ?? null };
|
||||
case 'halted': return { ...base, at: 4, tone: 'bad', share: r.fraction ?? null };
|
||||
default: return { ...base, at: 0, tone: 'neutral', share: null };
|
||||
}
|
||||
}
|
||||
|
||||
/** Both lanes of a train; iOS counts TestFlight as reached when a build of that version is in beta testing. */
|
||||
export function trainLanes(t: ReleaseTrain, tf?: TestFlightStatus | null): Lane[] {
|
||||
const inBeta = !!tf?.builds.some(b => b.version === t.version && /IN_BETA_TESTING|BETA_APPROVED|READY_FOR_BETA_TESTING/.test(`${b.internal ?? ''} ${b.external ?? ''}`));
|
||||
return [laneOf('ios', t.ios, inBeta), laneOf('android', t.android)];
|
||||
}
|
||||
|
||||
/** Every distinct version of the store releases, newest first, with both stores' release (best phase per store). */
|
||||
export function versionHistory(all: StoreRelease[]): ReleaseTrain[] {
|
||||
const rank: Record<string, number> = { live: 0, rollout: 1, halted: 2, approved: 3, review: 4, rejected: 5, testing: 6, draft: 7, other: 8 };
|
||||
const versions = [...new Set(all.map(r => r.version).filter((v): v is string => !!v))].sort(cmpVersion).reverse();
|
||||
const best = (store: 'ios' | 'android', v: string) => all.filter(r => r.store === store && r.version === v).sort((a, b) => (rank[a.phase] ?? 9) - (rank[b.phase] ?? 9))[0] ?? null;
|
||||
return versions.map(v => ({ version: v, ios: best('ios', v), android: best('android', v) }));
|
||||
}
|
||||
|
||||
/** On one store: the highest version reaching users (live or rolling out) and the highest version above it. */
|
||||
export function storeNow(all: StoreRelease[], store: 'ios' | 'android'): { now: StoreRelease | null; next: StoreRelease | null } {
|
||||
const rs = all.filter((r): r is StoreRelease & { version: string } => r.store === store && !!r.version);
|
||||
const desc = (a: { version: string }, b: { version: string }) => cmpVersion(b.version, a.version);
|
||||
const now = rs.filter(r => r.phase === 'live' || r.phase === 'rollout' || r.phase === 'halted').sort(desc)[0] ?? null;
|
||||
const next = rs.filter(r => !now || cmpVersion(r.version, now.version) > 0).sort(desc)[0] ?? null;
|
||||
return { now, next };
|
||||
}
|
||||
|
||||
export function cmpVersion(a: string, b: string): number {
|
||||
const pa = a.split('.').map(x => parseInt(x, 10) || 0), pb = b.split('.').map(x => parseInt(x, 10) || 0);
|
||||
for (let i = 0; i < Math.max(pa.length, pb.length); i++) { const d = (pa[i] ?? 0) - (pb[i] ?? 0); if (d) return d; }
|
||||
return 0;
|
||||
}
|
||||
export { cmpVersion, type Lane, laneOf, type Stage, STAGES, storeNow, trainLanes, versionHistory } from '../../../../cli/lib/train';
|
||||
|
||||
// ---- Health ----
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
// Checks: the offline config check (every time) and the read-only store readiness report (`validate`, on demand)
|
||||
// with its ordered blockers and fix hints.
|
||||
// Checks: the offline rejection-risk scan of the project files (`scan`, every time), the offline config check and
|
||||
// the read-only store readiness report (`validate`, on demand) with its ordered blockers and fix hints.
|
||||
import type { Project } from '../../api';
|
||||
import { t } from '../../i18n';
|
||||
import { ago } from '../../lib/format';
|
||||
import type { Finding, ValidateResult } from '../../lib/model';
|
||||
import type { Finding, ScanResult, ScanSeverity, ValidateResult } from '../../lib/model';
|
||||
import { useData, useRead } from '../../store';
|
||||
import { Icon } from '../../ui/icons';
|
||||
import { Card, Chip, Empty, ErrorNotice, Skeleton } from '../../ui/kit';
|
||||
|
|
@ -12,6 +12,50 @@ import { useExports } from '../../ui/Exports';
|
|||
|
||||
const LEVEL: Record<Finding['level'], ['bad' | 'warn' | 'ok', 'alertCircle' | 'alert' | 'check']> = { blocker: ['bad', 'alertCircle'], warn: ['warn', 'alert'], ok: ['ok', 'check'] };
|
||||
|
||||
const SEV: Record<ScanSeverity, ['bad' | 'warn' | 'info', 'alertCircle' | 'alert' | 'info']> = { blocker: ['bad', 'alertCircle'], high: ['bad', 'alert'], medium: ['warn', 'alert'], low: ['info', 'info'] };
|
||||
|
||||
/** The `storebound scan` card: rejection risks with guideline, evidence file:line, fix and skill. */
|
||||
function ScanCard({ project }: { project: Project }) {
|
||||
const s = useRead<ScanResult>(project.id, 'scan', { network: false, title: t('checks.scan') });
|
||||
const findings = Array.isArray(s.data?.findings) ? s.data!.findings : [];
|
||||
const sdks = Array.isArray(s.data?.sdks) ? s.data!.sdks : [];
|
||||
const asks = (Array.isArray(s.data?.declarations?.items) ? s.data!.declarations.items : []).filter(x => x.status === 'ask').length;
|
||||
return (
|
||||
<Card title={t('checks.scan')} icon="search" sub={s.data && sdks.length ? t('checks.scanSdks', { list: sdks.map(x => x.name).join(', ') }) : t('checks.scanSub')} pad={false}
|
||||
actions={<button className="btn btn-sm" onClick={s.refresh} disabled={s.loading}><Icon name="refresh" className={s.loading ? 'spin' : undefined} />{t('checks.scanAgain')}</button>}>
|
||||
{s.error && <div className="card-body"><ErrorNotice error={s.error} keep={!!s.data} /></div>}
|
||||
{!s.data ? (s.loading && !s.error ? <div className="card-body"><Skeleton lines={4} /></div> : null)
|
||||
: !findings.length ? <Empty compact illo="shield" title={t('checks.scanClean')}>{t('checks.scanCleanText')}</Empty> : (
|
||||
<div className="list">
|
||||
{findings.map((f, i) => {
|
||||
const [tone, icon] = f.accepted ? ['ok', 'check'] as const : SEV[f.severity] ?? SEV.low;
|
||||
const ev = Array.isArray(f.evidence) ? f.evidence : [];
|
||||
return (
|
||||
<div className="li" key={`${f.rule}-${i}`}>
|
||||
<span className={`li-icon tone-bg-${tone}`}><Icon name={icon} /></span>
|
||||
<div className="li-main">
|
||||
<span className="li-title">{f.guideline} · {f.title}</span>
|
||||
{ev.slice(0, 2).map((e, j) => <span className="li-sub selectable" key={j}><code>{e.file}:{e.line}</code>{e.text ? ` ${e.text}` : ''}</span>)}
|
||||
{f.accepted ? <span className="li-sub">{t('checks.accepted', { reason: f.accepted })}</span>
|
||||
: <span className="fix"><Icon name="wand" /><span className="selectable">{f.fix} <code>{f.skill}</code></span></span>}
|
||||
</div>
|
||||
<Chip tone={f.accepted ? 'ok' : tone}>{t(f.accepted ? 'checks.sev.accepted' : `checks.sev.${f.severity}` as Parameters<typeof t>[0])}</Chip>
|
||||
<Chip tone="outline">{f.store === 'apple' ? 'App Store' : 'Google Play'}</Chip>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{s.data && (asks > 0 || s.data.declarations?.changed) && (
|
||||
<div className="card-body">
|
||||
{asks > 0 && <div className="li-sub">{t('checks.scanAsk', { count: asks })}</div>}
|
||||
{s.data.declarations?.changed && <div className="li-sub"><code className="selectable">{t('checks.scanWrite')}</code></div>}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export function ChecksTab({ project }: { project: Project }) {
|
||||
const d = useData();
|
||||
const e = d.statusOf(project);
|
||||
|
|
@ -23,6 +67,7 @@ export function ChecksTab({ project }: { project: Project }) {
|
|||
const findings = [...(v.data?.findings ?? [])].sort((a, b) => ['blocker', 'warn', 'ok'].indexOf(a.level) - ['blocker', 'warn', 'ok'].indexOf(b.level));
|
||||
return (
|
||||
<div className="grid g2" style={{ alignItems: 'start' }}>
|
||||
<div style={{ gridColumn: '1 / -1' }}><ScanCard project={project} /></div>
|
||||
<Card title={t('checks.offline')} icon="shield" sub={t('checks.offlineSub')} pad={false}
|
||||
actions={<button className="btn btn-sm" onClick={() => d.refreshPortfolio(false)} disabled={!!d.portfolioBusy}><Icon name="refresh" className={d.portfolioBusy === 'offline' ? 'spin' : undefined} />{t('checks.again')}</button>}>
|
||||
{!e ? <div className="card-body"><Skeleton lines={4} /></div> : !problems.length && !warnings.length ? (
|
||||
|
|
|
|||
71
cli/ads.ts
Normal file
71
cli/ads.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
// Local AdAttributionKit / SKAdNetwork scan of an iOS project (no network, no credentials, no config needed).
|
||||
// storebound ads scan --ios ios/App [--plist path/to/Info.plist] [--dry] [--json]
|
||||
// Reads every app Info.plist (Pods, build output, tests and frameworks left out) plus Podfile.lock / Package.resolved
|
||||
// and the Swift / Objective-C sources, then checks: ad network ids (SKAdNetworkItems, AdNetworkIdentifiers;
|
||||
// lowercase, format, ad SDKs without ids), postback copy endpoints (AttributionCopyEndpoint, the re-engagement opt-in,
|
||||
// NSAdvertisingAttributionReportEndpoint), AdAttributionKitConfigurations (attribution windows, cooldown) and that an
|
||||
// advertised app updates its conversion value. Exit 1 on a blocker. --dry is accepted and changes nothing (read-only).
|
||||
// Rules and Apple's documentation links: cli/lib/adattribution.ts; the ads-mediation-checks skill explains the fixes.
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join, relative, resolve } from 'node:path';
|
||||
import type { Args } from './lib/args';
|
||||
import { type AakFinding, evaluateAdAttribution, sourceSignals } from './lib/adattribution';
|
||||
import { done, printJson } from './lib/log';
|
||||
import { parsePlist, type PlistValue } from './lib/plist';
|
||||
|
||||
const SKIP = new Set(['.git', 'build', 'DerivedData', 'node_modules', '.build', 'xcuserdata', 'Pods', 'Carthage', 'fastlane']);
|
||||
const SKIP_PLIST = /(Tests?|UITests|\.bundle|\.framework|\.xcframework|\.appex|Extension|Widget|Watch)(\/|$)/i;
|
||||
|
||||
function walk(dir: string, visit: (p: string) => void, depth = 0): void {
|
||||
if (depth > 12) return;
|
||||
let names: string[] = [];
|
||||
try { names = readdirSync(dir); } catch { return; }
|
||||
for (const n of names) {
|
||||
if (SKIP.has(n)) continue;
|
||||
const p = join(dir, n);
|
||||
let st;
|
||||
try { st = statSync(p); } catch { continue; }
|
||||
if (st.isDirectory()) walk(p, visit, depth + 1); else visit(p);
|
||||
}
|
||||
}
|
||||
|
||||
export async function run(args: Args): Promise<void> {
|
||||
if (args._[0] !== 'scan') throw new Error('usage: storebound ads scan --ios <path to the iOS project folder, e.g. ios/App> [--plist Info.plist] [--json]');
|
||||
const ios = args.get('ios');
|
||||
if (!ios) throw new Error('--ios <path to the iOS project folder>');
|
||||
const root = resolve(ios);
|
||||
if (!existsSync(root)) throw new Error(`${root} does not exist`);
|
||||
const plists: string[] = [];
|
||||
const files: { path: string; text: string }[] = [];
|
||||
walk(root, p => {
|
||||
const rel = relative(root, p);
|
||||
if (p.endsWith('/Info.plist') && !SKIP_PLIST.test(rel)) plists.push(p);
|
||||
if (/(\.swift|\.m|\.mm|Podfile\.lock|Package\.resolved|Cartfile\.resolved|project\.pbxproj)$/.test(p)) {
|
||||
try { if (statSync(p).size < 4_000_000) files.push({ path: rel, text: readFileSync(p, 'utf8') }); } catch { /* unreadable */ }
|
||||
}
|
||||
});
|
||||
// lock files usually sit next to the project folder (ios/Podfile.lock for ios/App)
|
||||
for (const extra of ['Podfile.lock', '../Podfile.lock', 'Package.resolved', '../Package.resolved']) {
|
||||
const p = join(root, extra);
|
||||
if (existsSync(p) && !files.some(f => resolve(root, f.path) === resolve(p))) files.push({ path: extra, text: readFileSync(p, 'utf8') });
|
||||
}
|
||||
const chosen = args.get('plist') ? [resolve(args.get('plist')!)] : plists;
|
||||
const signals = sourceSignals(files);
|
||||
const results: { plist: string; findings: AakFinding[] }[] = [];
|
||||
for (const p of chosen) {
|
||||
let parsed: PlistValue;
|
||||
try { parsed = parsePlist(readFileSync(p)); } catch (e) { results.push({ plist: relative(process.cwd(), p), findings: [{ level: 'warn', code: 'plist-read', msg: (e as Error).message }] }); continue; }
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || Buffer.isBuffer(parsed)) continue;
|
||||
results.push({ plist: relative(process.cwd(), p), findings: evaluateAdAttribution(parsed, signals) });
|
||||
}
|
||||
if (!chosen.length) results.push({ plist: '(none)', findings: [{ level: signals.adSdks.length ? 'blocker' : 'info', code: 'no-plist', msg: `no app Info.plist under ${root}${signals.adSdks.length ? ` but ad SDKs (${signals.adSdks.join(', ')}) need SKAdNetworkItems / AdNetworkIdentifiers in one` : ''}` }] });
|
||||
const blockers = results.flatMap(r => r.findings).filter(f => f.level === 'blocker').length;
|
||||
if (args.has('json')) printJson({ ios: root, signals, results, blockers });
|
||||
else {
|
||||
console.log(`ad SDKs: ${signals.adSdks.join(', ') || 'none found'} · attribution SDKs: ${signals.mmpSdks.join(', ') || 'none'} · import AdAttributionKit: ${signals.aakImport ? 'yes' : 'no'} · conversion value updates in code: ${signals.conversionUpdates ? 'yes' : 'no'}`);
|
||||
const tag = { blocker: 'BLOCKER', warn: 'warn ', ok: 'ok ', info: 'info ' } as const;
|
||||
for (const r of results) { console.log(`\n${r.plist}`); for (const f of r.findings) console.log(` ${tag[f.level]} ${f.msg}`); }
|
||||
}
|
||||
done('ads', blockers ? `${blockers} blocker(s)` : 'no blocker');
|
||||
if (blockers) process.exitCode = 1;
|
||||
}
|
||||
174
cli/api.ts
Normal file
174
cli/api.ts
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
// storebound api: every App Store Connect and Google Play Developer API operation, from the pinned specs.
|
||||
//
|
||||
// storebound api list [--store apple|play] [--search text] [--json]
|
||||
// storebound api coverage [--store apple|play] [--json]
|
||||
// storebound api apple|play <operationId | METHOD path> [--param k=v ...] [--body file.json] [--upload file]
|
||||
// [--out file] [--all-pages] [--json] [--dry] [--yes]
|
||||
// storebound api get apple|play <operationId> ... GET only (what the MCP tool api_get runs)
|
||||
//
|
||||
// GETs run right away. Writes print the exact request and are only sent with --yes in an interactive terminal;
|
||||
// owner-only operations (submit, release, delete, cancel, prices, testers, review replies, experiments: cli/api/gate.ts)
|
||||
// also need the operation id typed at the prompt. Under MCP or the desktop app no write is ever sent.
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import type { Args } from './lib/args';
|
||||
import { allOps, authFor, type BuiltRequest, buildRequest, resolveOp, send, sendAll } from './api/client';
|
||||
import { decide, gateOf, ownerReason, resourceOf, type GateKind, type Store } from './api/gate';
|
||||
import { APPLE_SPEC } from './api/apple.gen';
|
||||
import { PLAY_APIS } from './api/play.gen';
|
||||
import { WRAPPED } from './api/wrapped.gen';
|
||||
import type { ParamValue } from './api/types';
|
||||
|
||||
const STORES: Store[] = ['apple', 'play'];
|
||||
|
||||
export const USAGE = `usage:
|
||||
storebound api list [--store apple|play] [--search text] [--json]
|
||||
storebound api coverage [--store apple|play] [--json]
|
||||
storebound api apple|play <operationId | METHOD path> [--param k=v ...] [--body file.json] [--upload file]
|
||||
[--out file] [--all-pages] [--json] [--dry] [--yes]
|
||||
storebound api get apple|play <operationId> [--param k=v ...] [--all-pages] [--json] (GET only)
|
||||
|
||||
GETs run right away. Writes print the exact request and are sent only with --yes in a terminal; owner-only
|
||||
operations (submit, release, delete, cancel, prices, testers, review replies, experiments) also ask you to type the
|
||||
operation id. Full table: docs/api-coverage.md`;
|
||||
|
||||
export interface Row { store: Store; id: string; method: string; path: string; gate: GateKind; wrapped: string }
|
||||
|
||||
export function rows(store?: Store): Row[] {
|
||||
return (store ? [store] : STORES).flatMap(s => allOps(s).map(o => ({
|
||||
store: s, id: o.id, method: o.method, path: o.path, gate: gateOf(s, o.id, o.method), wrapped: WRAPPED[s][o.id] ?? '',
|
||||
})));
|
||||
}
|
||||
|
||||
export function search(list: Row[], text: string): Row[] {
|
||||
const words = text.toLowerCase().split(/\s+/).filter(Boolean);
|
||||
return list.filter(r => words.every(w => `${r.id} ${r.method} ${r.path}`.toLowerCase().includes(w)));
|
||||
}
|
||||
|
||||
export interface Coverage {
|
||||
apis: { api: string; title: string; operations: number; get: number; write: number; owner: number; wrapped: number }[];
|
||||
resources: { store: Store; resource: string; operations: number; wrapped: number }[];
|
||||
}
|
||||
|
||||
export function coverage(store?: Store): Coverage {
|
||||
const list = rows(store);
|
||||
const groups: [string, string, Row[]][] = [];
|
||||
if (!store || store === 'apple') groups.push(['appstoreconnect', `${APPLE_SPEC.title} ${APPLE_SPEC.version}`, list.filter(r => r.store === 'apple')]);
|
||||
if (!store || store === 'play') for (const [name, a] of Object.entries(PLAY_APIS)) groups.push([name, `${a.title} (${a.revision})`, list.filter(r => r.store === 'play' && r.id.startsWith(name + '.'))]);
|
||||
const res = new Map<string, { store: Store; resource: string; operations: number; wrapped: number }>();
|
||||
for (const r of list) {
|
||||
const k = `${r.store} ${resourceOf(r)}`;
|
||||
const cur = res.get(k) ?? { store: r.store, resource: resourceOf(r), operations: 0, wrapped: 0 };
|
||||
cur.operations++;
|
||||
if (r.wrapped) cur.wrapped++;
|
||||
res.set(k, cur);
|
||||
}
|
||||
return {
|
||||
apis: groups.map(([api, title, rs]) => ({ api, title, operations: rs.length, get: rs.filter(r => r.method === 'GET').length,
|
||||
write: rs.filter(r => r.gate === 'write').length, owner: rs.filter(r => r.gate === 'owner').length, wrapped: rs.filter(r => r.wrapped).length })),
|
||||
resources: [...res.values()],
|
||||
};
|
||||
}
|
||||
|
||||
/** --param k=v (repeatable; a repeated name becomes a list). */
|
||||
export function parseParams(values: string[]): Record<string, ParamValue> {
|
||||
const out: Record<string, ParamValue> = {};
|
||||
for (const kv of values) {
|
||||
const eq = kv.indexOf('=');
|
||||
if (eq <= 0) throw new Error(`--param ${kv}: expected name=value`);
|
||||
const k = kv.slice(0, eq), v = kv.slice(eq + 1);
|
||||
const cur = out[k];
|
||||
out[k] = cur === undefined ? v : [...(Array.isArray(cur) ? cur : [String(cur)]), v];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const UPLOAD_TYPES: Record<string, string> = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', apk: 'application/vnd.android.package-archive' };
|
||||
|
||||
/** The exact request as text, the credential replaced by a placeholder. */
|
||||
export function describeRequest(req: BuiltRequest): string {
|
||||
const lines = [`${req.method} ${req.url}`, `Authorization: Bearer <${req.op.store === 'apple' ? 'App Store Connect API key JWT' : 'Google service account token'}, not shown>`];
|
||||
if (req.contentType) lines.push(`Content-Type: ${req.contentType}`);
|
||||
if (typeof req.body === 'string') lines.push('', JSON.stringify(JSON.parse(req.body), null, 2));
|
||||
else if (req.body) lines.push('', `<${req.body.length} bytes of file data>`);
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
async function readLine(): Promise<string> {
|
||||
for await (const line of console) return line.trim();
|
||||
return '';
|
||||
}
|
||||
|
||||
export async function run(args: Args): Promise<void> {
|
||||
const [sub, ...rest] = args._;
|
||||
const json = args.has('json');
|
||||
const store = args.get('store') as Store | undefined;
|
||||
if (store && !STORES.includes(store)) throw new Error('--store: apple or play');
|
||||
if (!sub || args.has('help')) { console.log(USAGE); return; }
|
||||
|
||||
if (sub === 'list') {
|
||||
const list = args.get('search') ? search(rows(store), args.get('search')!) : rows(store);
|
||||
if (json) { console.log(JSON.stringify(list)); return; }
|
||||
for (const r of list) console.log(`${r.store.padEnd(5)} ${r.method.padEnd(6)} ${r.id.padEnd(60)} ${r.path}${r.gate === 'owner' ? ' [owner only]' : ''}${r.wrapped ? ` (wrapped: ${r.wrapped})` : ''}`);
|
||||
console.error(`${list.length} operation(s)`);
|
||||
return;
|
||||
}
|
||||
if (sub === 'coverage') {
|
||||
const c = coverage(store);
|
||||
if (json) { console.log(JSON.stringify(c)); return; }
|
||||
for (const a of c.apis) console.log(`${a.title}: ${a.operations} operations (${a.get} GET, ${a.write} write, ${a.owner} owner only), ${a.wrapped} wrapped by storebound commands`);
|
||||
console.log(`\n${'resource'.padEnd(62)} ops wrapped`);
|
||||
for (const r of c.resources) console.log(`${(r.store + ' ' + r.resource).padEnd(62)} ${String(r.operations).padStart(3)} ${String(r.wrapped).padStart(7)}`);
|
||||
const total = c.apis.reduce((n, a) => n + a.operations, 0);
|
||||
console.log(`\n${total} operations, every one callable with storebound api; full table: docs/api-coverage.md`);
|
||||
return;
|
||||
}
|
||||
|
||||
const getOnly = sub === 'get';
|
||||
const st = (getOnly ? rest.shift() : sub) as Store;
|
||||
if (!STORES.includes(st)) { console.error(USAGE); throw new Error(`unknown api subcommand: ${sub}`); }
|
||||
const [ref, maybePath] = rest;
|
||||
if (!ref) throw new Error(`storebound api ${getOnly ? 'get ' : ''}${st} <operationId | METHOD path>`);
|
||||
const { op, params: fromPath } = resolveOp(st, ref, maybePath);
|
||||
const params = { ...fromPath, ...parseParams(args.many('param')) };
|
||||
const body = args.get('body') ? JSON.parse(readFileSync(resolve(args.get('body')!), 'utf8')) as unknown : undefined;
|
||||
const uploadFile = args.get('upload');
|
||||
const upload = uploadFile ? { bytes: new Uint8Array(readFileSync(resolve(uploadFile))), contentType: UPLOAD_TYPES[uploadFile.split('.').pop()!.toLowerCase()] ?? 'application/octet-stream' } : undefined;
|
||||
const out = args.get('out');
|
||||
const req = buildRequest(op, params, body, { upload, download: !!out && op.flags.includes('d') });
|
||||
|
||||
const kind = gateOf(st, op.id, op.method);
|
||||
const decision = decide({
|
||||
kind, method: op.method, dry: args.has('dry'), yes: args.has('yes'), getOnly,
|
||||
tty: !!process.stdin.isTTY && !!process.stdout.isTTY,
|
||||
agent: process.env.STOREBOUND_SERVE === '1' || process.env.STOREBOUND_MCP === '1',
|
||||
});
|
||||
if (decision.action === 'refuse') throw new Error(`${op.id}: ${decision.why}`);
|
||||
if (decision.action === 'dry') {
|
||||
if (json) console.log(JSON.stringify({ dryRun: true, operation: op.id, gate: kind, why: decision.why, request: { method: req.method, url: req.url, body: typeof req.body === 'string' ? JSON.parse(req.body) : req.body ? `<${req.body.length} bytes>` : undefined } }));
|
||||
else console.log(`dry run (${decision.why}): nothing sent\n${kind === 'owner' ? `owner only: this ${ownerReason(st, op.id, op.method)}; sending also asks you to type the operation id\n` : ''}\n${describeRequest(req)}`);
|
||||
return;
|
||||
}
|
||||
if (decision.action === 'confirm') {
|
||||
console.log(describeRequest(req));
|
||||
process.stdout.write(`\nThis ${ownerReason(st, op.id, op.method)}. Type the operation id (${op.id}) to send it: `);
|
||||
if ((await readLine()) !== op.id) { console.log('not sent'); process.exitCode = 1; return; }
|
||||
}
|
||||
|
||||
const root = process.env.STOREBOUND_PROJECT || process.cwd();
|
||||
const auth = await authFor(st, root);
|
||||
const onRetry = (m: string) => console.error(`api: ${m}`);
|
||||
const all = args.has('all-pages');
|
||||
if (all && op.method !== 'GET' && !(op.store === 'play' && /[pt]/.test(op.flags))) throw new Error(`${op.id}: --all-pages is for paged reads`);
|
||||
const r = all ? await sendAll(req, auth, { onRetry, onPage: n => { if (!json) console.error(`api: page ${n}`); } }) : { ...(await send(req, auth, { onRetry })), pages: 1 };
|
||||
if (!json) console.error(`${req.method} ${req.url.replace(/\?.*$/, '')} -> ${r.status}${r.pages > 1 ? ` · ${r.pages} pages` : ''}${r.rateLimit ? ` · rate limit ${r.rateLimit}` : ''}`);
|
||||
if (r.bytes) {
|
||||
if (!out) throw new Error(`${op.id}: binary response (${r.bytes.length} bytes): pass --out <file>`);
|
||||
writeFileSync(resolve(out), r.bytes);
|
||||
console.log(json ? JSON.stringify({ status: r.status, out, bytes: r.bytes.length }) : `wrote ${out} (${r.bytes.length} bytes)`);
|
||||
return;
|
||||
}
|
||||
if (out) { writeFileSync(resolve(out), JSON.stringify(r.json, null, 2) + '\n'); if (!json) console.log(`wrote ${out}`); return; }
|
||||
console.log(json ? JSON.stringify(r.json) : JSON.stringify(r.json, null, 2));
|
||||
}
|
||||
|
||||
1311
cli/api/apple.gen.ts
Normal file
1311
cli/api/apple.gen.ts
Normal file
File diff suppressed because it is too large
Load diff
341
cli/api/client.ts
Normal file
341
cli/api/client.ts
Normal file
|
|
@ -0,0 +1,341 @@
|
|||
// Generic client for every App Store Connect and Google Play operation: the generated rows (apple.gen.ts, play.gen.ts)
|
||||
// plus a few helpers instead of a function per endpoint. Request building is pure (tests cover URLs and parameters);
|
||||
// sending retries 429 / 5xx with backoff (Retry-After honoured) and follows pages.
|
||||
// Auth: the App Store Connect team key JWT from cli/apple/asc.ts, the Play service account token from
|
||||
// cli/lib/google-auth.ts (one scope per Google API). Credentials only come from env or .storebound/.
|
||||
import { APPLE_OPS, APPLE_SPEC } from './apple.gen';
|
||||
import { PLAY_APIS, PLAY_OPS } from './play.gen';
|
||||
import type { AppleBody, AppleOp, AppleParams, AppleResponse, ParamValue, PlayBody, PlayOp, PlayParams, PlayResponse } from './types';
|
||||
import type { Store } from './gate';
|
||||
import { errorBody } from '../lib/http';
|
||||
|
||||
export interface QueryParam { name: string; required: boolean; repeated: boolean }
|
||||
|
||||
export interface Op {
|
||||
store: Store;
|
||||
id: string;
|
||||
method: string;
|
||||
/** Path template: Apple "/v1/apps/{id}", Google "androidpublisher/v3/applications/{packageName}/edits" */
|
||||
path: string;
|
||||
query: QueryParam[];
|
||||
/** Apple: resource type ("type", "type[]", "json", ""). Google: request schema name ("" for none). */
|
||||
request: string;
|
||||
/** Apple: "many:type" | "one:type" | "json" | "raw:<media type>" | "none". Google: response schema name. */
|
||||
response: string;
|
||||
/** Google: m media upload, d media download, p pageToken paging, t token paging. Apple: "". */
|
||||
flags: string;
|
||||
/** Google API name (androidpublisher, playdeveloperreporting); "" for Apple. */
|
||||
api: string;
|
||||
/** Google: the shape of each {+param}, e.g. name -> "apps/* /crashRateMetricSet" (no space; * is one segment). */
|
||||
shapes: Record<string, string>;
|
||||
}
|
||||
|
||||
/** Query parameters every Google API accepts on top of a method's own. */
|
||||
export const GOOGLE_GLOBAL = ['fields', 'prettyPrint', 'quotaUser'];
|
||||
|
||||
const parseQuery = (s: string): QueryParam[] => (s ? s.split(' ') : []).map(t => ({ name: t.replace(/[!*]/g, ''), required: t.includes('!'), repeated: t.includes('*') }));
|
||||
|
||||
const cache: Partial<Record<Store, Op[]>> = {};
|
||||
export function allOps(store: Store): Op[] {
|
||||
if (cache[store]) return cache[store]!;
|
||||
const rows = store === 'apple' ? APPLE_OPS as Record<string, readonly string[]> : PLAY_OPS as Record<string, readonly string[]>;
|
||||
return (cache[store] = Object.entries(rows).map(([id, r]) => ({
|
||||
store, id, method: r[0]!, path: r[1]!, query: parseQuery(r[2]!), request: r[3]!, response: r[4]!, flags: r[5] ?? '',
|
||||
api: store === 'play' ? id.split('.')[0]! : '',
|
||||
shapes: Object.fromEntries((r[6] ?? '').split(' ').filter(Boolean).map(s => [s.slice(0, s.indexOf('=')), s.slice(s.indexOf('=') + 1)])),
|
||||
})));
|
||||
}
|
||||
|
||||
export function getOp(store: Store, id: string): Op | undefined {
|
||||
const ops = allOps(store);
|
||||
return ops.find(o => o.id === id) ?? (store === 'play' ? ops.find(o => o.id.slice(o.api.length + 1) === id) : undefined);
|
||||
}
|
||||
|
||||
const esc = (s: string) => s.replace(/[.*+?^$()|[\]\\]/g, '\\$&');
|
||||
/** "apps/* /crashRateMetricSet" (no space) -> a regex source; * is one path segment. */
|
||||
const shapeSource = (shape: string) => shape.split('*').map(esc).join('[^/]+');
|
||||
|
||||
/** Path template -> RegExp with one group per path parameter ({+param}s narrowed by their shape). */
|
||||
function templateRe(op: Op): { re: RegExp; names: string[]; fixed: number } {
|
||||
const names: string[] = [];
|
||||
const body = op.path.replace(/^\//, '').split(/(\{\+?[^}]+\})/).map(part => {
|
||||
const m = /^\{(\+?)([^}]+)\}$/.exec(part);
|
||||
if (!m) return esc(part);
|
||||
names.push(m[2]!);
|
||||
if (!m[1]) return '([^/:]+)';
|
||||
const shape = op.shapes[m[2]!];
|
||||
return shape ? `(${shapeSource(shape)})` : '(.+)';
|
||||
}).join('');
|
||||
return { re: new RegExp('^' + body + '$'), names, fixed: op.path.split('{')[0]!.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* An operation from what the user typed: an operation id (Google ids also without the API prefix), or "METHOD path"
|
||||
* with a concrete path (and query string), whose values become parameters.
|
||||
*/
|
||||
export function resolveOp(store: Store, ref: string, path?: string): { op: Op; params: Record<string, string> } {
|
||||
if (path === undefined) {
|
||||
const op = getOp(store, ref);
|
||||
if (!op) throw new Error(`${store}: no operation "${ref}" (storebound api list --store ${store} --search <text>)`);
|
||||
return { op, params: {} };
|
||||
}
|
||||
const method = ref.toUpperCase();
|
||||
if (!/^(GET|POST|PUT|PATCH|DELETE)$/.test(method)) throw new Error(`"${ref}": expected an operation id or METHOD path`);
|
||||
let p = path.replace(/^https:\/\/[^/]+/, '');
|
||||
if (store === 'play') p = p.replace(/^\/?upload\//, '/');
|
||||
const [rawPath, qs = ''] = p.split('?', 2) as [string, string?];
|
||||
const clean = decodeURI(rawPath).replace(/^\//, '');
|
||||
const hits = allOps(store).filter(o => o.method === method).map(o => ({ o, t: templateRe(o) }))
|
||||
.map(x => ({ ...x, m: x.t.re.exec(clean) })).filter(x => x.m).sort((a, b) => b.t.fixed - a.t.fixed);
|
||||
const best = hits[0];
|
||||
if (!best) throw new Error(`${store}: no ${method} operation matches ${rawPath}`);
|
||||
const params: Record<string, string> = {};
|
||||
best.t.names.forEach((n, i) => { params[n] = best.m![i + 1]!; });
|
||||
for (const [k, v] of new URLSearchParams(qs)) params[k] = v;
|
||||
return { op: best.o, params };
|
||||
}
|
||||
|
||||
export interface BuiltRequest {
|
||||
op: Op;
|
||||
method: string;
|
||||
url: string;
|
||||
/** JSON text or file bytes */
|
||||
body?: string | Uint8Array;
|
||||
contentType?: string;
|
||||
/** Apple vendor media types (perfPowerMetrics: application/vnd.apple.xcode-metrics+json, reports: application/a-gzip) */
|
||||
accept?: string;
|
||||
}
|
||||
|
||||
const encSeg = (v: string) => encodeURIComponent(v);
|
||||
// Apple writes brackets and commas plainly in its docs and links (filter[app]=1,2); keep them readable
|
||||
const encName = (k: string) => encodeURIComponent(k).replace(/%5B/gi, '[').replace(/%5D/gi, ']');
|
||||
const encVal = (v: string) => encodeURIComponent(v).replace(/%2C/gi, ',');
|
||||
const str = (v: string | number | boolean) => String(v);
|
||||
|
||||
/** Builds the URL and body of one call. Throws on a missing path / required parameter or an unknown parameter. Pure. */
|
||||
export function buildRequest(op: Op, params: Record<string, ParamValue | undefined>, body?: unknown, o: { upload?: { bytes: Uint8Array; contentType: string }; download?: boolean } = {}): BuiltRequest {
|
||||
const left = new Map(Object.entries(params).filter(([, v]) => v !== undefined) as [string, ParamValue][]);
|
||||
const path = op.path.replace(/\{(\+?)([^}]+)\}/g, (_, plus: string, name: string) => {
|
||||
const v = left.get(name);
|
||||
if (v === undefined || v === '') throw new Error(`${op.id}: path parameter "${name}" is required`);
|
||||
left.delete(name);
|
||||
const s = Array.isArray(v) ? v.join(',') : str(v as string);
|
||||
const shape = op.shapes[name];
|
||||
if (shape && !new RegExp(`^${shapeSource(shape)}$`).test(s)) throw new Error(`${op.id}: "${name}" must look like ${shape} (* is one segment), got "${s}"`);
|
||||
return plus ? s.split('/').map(encSeg).join('/') : encSeg(s);
|
||||
});
|
||||
const known = new Map(op.query.map(q => [q.name, q] as const));
|
||||
for (const q of op.query) if (q.required && !left.has(q.name)) throw new Error(`${op.id}: query parameter "${q.name}" is required`);
|
||||
const parts: string[] = [];
|
||||
for (const [k, v] of left) {
|
||||
const q = known.get(k);
|
||||
if (!q && !(op.store === 'play' && GOOGLE_GLOBAL.includes(k))) {
|
||||
const names = op.query.map(x => x.name);
|
||||
throw new Error(`${op.id}: unknown parameter "${k}"${names.length ? ` (takes: ${names.slice(0, 30).join(', ')}${names.length > 30 ? ', …' : ''})` : ' (takes no query parameters)'}`);
|
||||
}
|
||||
const values = Array.isArray(v) ? v.map(str) : [str(v as string)];
|
||||
if (q?.repeated) for (const x of values) parts.push(`${encName(k)}=${encVal(x)}`);
|
||||
else parts.push(`${encName(k)}=${encVal(values.join(','))}`);
|
||||
}
|
||||
let base: string;
|
||||
if (op.store === 'apple') base = APPLE_SPEC.base + path;
|
||||
else {
|
||||
const api = PLAY_APIS[op.api as keyof typeof PLAY_APIS];
|
||||
if (!api) throw new Error(`${op.id}: unknown Google API ${op.api}`);
|
||||
const upload = !!o.upload && op.flags.includes('m');
|
||||
if (o.upload && !upload) throw new Error(`${op.id}: takes no file upload`);
|
||||
base = api.root + (upload ? 'upload/' : '') + path;
|
||||
if (upload) parts.unshift('uploadType=media');
|
||||
if (o.download) {
|
||||
if (!op.flags.includes('d')) throw new Error(`${op.id}: has no media download`);
|
||||
parts.push('alt=media');
|
||||
}
|
||||
}
|
||||
const req: BuiltRequest = { op, method: op.method, url: base + (parts.length ? '?' + parts.join('&') : '') };
|
||||
if (op.response.startsWith('raw:')) req.accept = op.response.slice(4);
|
||||
if (o.upload) { req.body = o.upload.bytes; req.contentType = o.upload.contentType; }
|
||||
else if (body !== undefined) {
|
||||
if (op.method === 'GET' || op.method === 'DELETE' && op.store === 'play') throw new Error(`${op.id}: ${op.method} takes no body`);
|
||||
req.body = JSON.stringify(body);
|
||||
req.contentType = 'application/json';
|
||||
}
|
||||
return req;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------- sending
|
||||
|
||||
/** Authorization header value for a request ("Bearer ..."). */
|
||||
export type Auth = (req: BuiltRequest) => Promise<string> | string;
|
||||
|
||||
export interface SendOptions {
|
||||
fetch?: (url: string, init: RequestInit) => Promise<Response>;
|
||||
sleep?: (ms: number) => Promise<unknown>;
|
||||
/** attempts for 429 / 5xx / network errors (default 5) */
|
||||
attempts?: number;
|
||||
/** each retry is logged here (stderr in the CLI) */
|
||||
onRetry?: (msg: string) => void;
|
||||
}
|
||||
|
||||
export interface ApiResult {
|
||||
status: number;
|
||||
/** parsed JSON, or null for an empty body */
|
||||
json?: unknown;
|
||||
/** non-JSON body (gzip reports, media downloads) */
|
||||
bytes?: Uint8Array;
|
||||
/** Apple's X-Rate-Limit header ("user-hour-lim:3600;user-hour-rem:3412;") */
|
||||
rateLimit?: string;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(readonly status: number, message: string) { super(message); }
|
||||
}
|
||||
|
||||
/** Wait before retry `attempt` (1-based): Retry-After when the server sent one (max 60 s), else 1, 2, 4, 8 ... s (max 30 s). */
|
||||
export function backoffMs(attempt: number, retryAfter?: string | null): number {
|
||||
const s = retryAfter ? Number(retryAfter) : NaN;
|
||||
if (Number.isFinite(s) && s >= 0) return Math.min(s, 60) * 1000;
|
||||
return Math.min(1000 * 2 ** (attempt - 1), 30_000);
|
||||
}
|
||||
|
||||
const short = (url: string) => url.replace(/^https:\/\/[^/]+/, '').replace(/\?.*$/, '');
|
||||
|
||||
export async function send(req: BuiltRequest, auth: Auth, o: SendOptions = {}): Promise<ApiResult> {
|
||||
const doFetch = o.fetch ?? ((u: string, i: RequestInit) => fetch(u, i));
|
||||
const sleep = o.sleep ?? ((ms: number) => Bun.sleep(ms));
|
||||
const attempts = o.attempts ?? 5;
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
const headers: Record<string, string> = { Authorization: await auth(req) };
|
||||
if (req.contentType) headers['Content-Type'] = req.contentType;
|
||||
if (req.accept) headers.Accept = req.accept;
|
||||
let r: Response;
|
||||
try {
|
||||
r = await doFetch(req.url, { method: req.method, headers, body: req.body as BodyInit | undefined });
|
||||
} catch (e) {
|
||||
if (attempt >= attempts) throw e;
|
||||
o.onRetry?.(`${req.method} ${short(req.url)}: ${(e as Error).message}, retry ${attempt}/${attempts - 1}`);
|
||||
await sleep(backoffMs(attempt));
|
||||
continue;
|
||||
}
|
||||
if ((r.status === 429 || r.status >= 500) && attempt < attempts) {
|
||||
const wait = backoffMs(attempt, r.headers.get('retry-after'));
|
||||
await r.body?.cancel();
|
||||
o.onRetry?.(`${req.method} ${short(req.url)} -> ${r.status}, retry ${attempt}/${attempts - 1} in ${Math.round(wait / 1000)} s`);
|
||||
await sleep(wait);
|
||||
continue;
|
||||
}
|
||||
const rateLimit = r.headers.get('x-rate-limit') ?? undefined;
|
||||
const type = r.headers.get('content-type') ?? '';
|
||||
if (!r.ok) throw new ApiError(r.status, `${req.method} ${short(req.url)} -> ${r.status} ${errorBody(await r.text())}`);
|
||||
if (/json/.test(type) || (!type && r.status !== 204)) {
|
||||
const t = await r.text();
|
||||
return { status: r.status, json: t ? JSON.parse(t) : null, rateLimit };
|
||||
}
|
||||
if (r.status === 204) return { status: 204, json: null, rateLimit };
|
||||
return { status: r.status, bytes: new Uint8Array(await r.arrayBuffer()), rateLimit };
|
||||
}
|
||||
}
|
||||
|
||||
/** Merges two pages: arrays are concatenated (Apple's included de-duplicated), the page tokens dropped. Pure. */
|
||||
export function mergePages(a: Record<string, unknown>, b: Record<string, unknown>): Record<string, unknown> {
|
||||
const out: Record<string, unknown> = { ...a };
|
||||
for (const [k, v] of Object.entries(b)) {
|
||||
const cur = out[k];
|
||||
if (Array.isArray(cur) && Array.isArray(v)) {
|
||||
if (k === 'included') {
|
||||
const seen = new Set(cur.map(x => `${(x as { type?: string }).type}/${(x as { id?: string }).id}`));
|
||||
out[k] = [...cur, ...v.filter(x => !seen.has(`${(x as { type?: string }).type}/${(x as { id?: string }).id}`))];
|
||||
} else out[k] = [...cur, ...v];
|
||||
} else if (cur === undefined) out[k] = v;
|
||||
}
|
||||
delete out.nextPageToken;
|
||||
if (out.tokenPagination) delete out.tokenPagination;
|
||||
if (out.links && typeof out.links === 'object') out.links = { ...(out.links as Record<string, unknown>), next: undefined };
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The next page of a result, or null. Apple: links.next (same host only, the token never leaves it); Google: the page token. */
|
||||
export function nextRequest(req: BuiltRequest, json: unknown): BuiltRequest | null {
|
||||
const j = (json ?? {}) as { links?: { next?: string }; nextPageToken?: string; tokenPagination?: { nextPageToken?: string } };
|
||||
if (req.op.store === 'apple') {
|
||||
const next = j.links?.next;
|
||||
if (!next) return null;
|
||||
if (!next.startsWith(APPLE_SPEC.base + '/')) throw new Error(`refusing to follow a next link to another host: ${next.slice(0, 80)}`);
|
||||
return { ...req, url: next };
|
||||
}
|
||||
const [name, token] = req.op.flags.includes('p') ? ['pageToken', j.nextPageToken] : req.op.flags.includes('t') ? ['token', j.tokenPagination?.nextPageToken] : ['', undefined];
|
||||
if (!token) return null;
|
||||
const u = new URL(req.url);
|
||||
u.searchParams.set(name, token);
|
||||
return { ...req, url: u.toString() };
|
||||
}
|
||||
|
||||
/** Every page of a GET (or a paged query), merged. `maxPages` guards against a server that never stops. */
|
||||
export async function sendAll(req: BuiltRequest, auth: Auth, o: SendOptions & { maxPages?: number; onPage?: (n: number) => void } = {}): Promise<ApiResult & { pages: number }> {
|
||||
let first = await send(req, auth, o);
|
||||
let pages = 1;
|
||||
let cur: BuiltRequest | null = req;
|
||||
let last = first.json;
|
||||
while ((cur = nextRequest(cur, last))) {
|
||||
if (pages >= (o.maxPages ?? 1000)) throw new Error(`more than ${o.maxPages ?? 1000} pages: stopped`);
|
||||
const r = await send(cur, auth, o);
|
||||
pages++;
|
||||
o.onPage?.(pages);
|
||||
last = r.json;
|
||||
first = { ...first, json: mergePages(first.json as Record<string, unknown>, r.json as Record<string, unknown>), rateLimit: r.rateLimit ?? first.rateLimit };
|
||||
}
|
||||
return { ...first, pages };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------- typed facades
|
||||
|
||||
/** Typed App Store Connect client: `api.call('apps_getCollection', { 'filter[bundleId]': 'com.example.app' })`. */
|
||||
export function appleApi(auth: Auth, o: SendOptions = {}) {
|
||||
const build = <O extends AppleOp>(op: O, params: AppleParams<O>, body?: AppleBody<O>) =>
|
||||
buildRequest(getOp('apple', op)!, params as Record<string, ParamValue>, body);
|
||||
const out = (r: ApiResult) => (r.bytes ?? r.json ?? null);
|
||||
return {
|
||||
build,
|
||||
async call<O extends AppleOp>(op: O, params: AppleParams<O>, body?: AppleBody<O>): Promise<AppleResponse<O>> {
|
||||
return out(await send(build(op, params, body), auth, o)) as AppleResponse<O>;
|
||||
},
|
||||
async all<O extends AppleOp>(op: O, params: AppleParams<O>): Promise<AppleResponse<O>> {
|
||||
return out(await sendAll(build(op, params), auth, o)) as AppleResponse<O>;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Typed Google Play client: `api.call('androidpublisher.edits.tracks.list', { packageName, editId })`. */
|
||||
export function playApi(auth: Auth, o: SendOptions = {}) {
|
||||
const build = <O extends PlayOp>(op: O, params: PlayParams<O>, body?: PlayBody<O>) =>
|
||||
body instanceof Uint8Array
|
||||
? buildRequest(getOp('play', op)!, params as Record<string, ParamValue>, undefined, { upload: { bytes: body, contentType: 'application/octet-stream' } })
|
||||
: buildRequest(getOp('play', op)!, params as Record<string, ParamValue>, body);
|
||||
const out = (r: ApiResult) => (r.bytes ?? r.json ?? {});
|
||||
return {
|
||||
build,
|
||||
async call<O extends PlayOp>(op: O, params: PlayParams<O>, body?: PlayBody<O>): Promise<PlayResponse<O>> {
|
||||
return out(await send(build(op, params, body), auth, o)) as PlayResponse<O>;
|
||||
},
|
||||
async all<O extends PlayOp>(op: O, params: PlayParams<O>): Promise<PlayResponse<O>> {
|
||||
return out(await sendAll(build(op, params), auth, o)) as PlayResponse<O>;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Auth from the project's credentials (env or .storebound/): Apple team key JWT, or a Play token for the op's API scope. */
|
||||
export async function authFor(store: Store, root: string): Promise<Auth> {
|
||||
if (store === 'apple') {
|
||||
const { ascJwt } = await import('../apple/asc');
|
||||
const { jwt } = ascJwt(root);
|
||||
return () => 'Bearer ' + jwt();
|
||||
}
|
||||
const { playServiceAccount } = await import('../lib/credentials');
|
||||
const { tokenSource } = await import('../lib/google-auth');
|
||||
const sa = playServiceAccount(root);
|
||||
const sources = new Map<string, () => Promise<string>>();
|
||||
return async req => {
|
||||
const scope = PLAY_APIS[req.op.api as keyof typeof PLAY_APIS].scope;
|
||||
if (!sources.has(scope)) sources.set(scope, tokenSource(sa, scope));
|
||||
return 'Bearer ' + (await sources.get(scope)!());
|
||||
};
|
||||
}
|
||||
99
cli/api/gate.ts
Normal file
99
cli/api/gate.ts
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
// Write gating for `storebound api`: which operations read, which write, and which only the owner may run.
|
||||
//
|
||||
// read GET (and a few POSTs that only compute or query, listed below): runs right away.
|
||||
// write any other POST / PATCH / PUT / DELETE: prints the exact request; sent only with --yes in an interactive
|
||||
// terminal, never under MCP (`storebound mcp`) or the desktop app (`storebound serve`).
|
||||
// owner writes that submit, release, delete, cancel, change prices, invite or remove testers, send review replies,
|
||||
// start or stop experiments, refund or rotate keys (AGENTS.md rule 1): a write that also needs the operation id
|
||||
// typed at the prompt. Never reachable through MCP or serve.
|
||||
// Pure; tests/api.test.ts covers every rule.
|
||||
|
||||
export type Store = 'apple' | 'play';
|
||||
export type GateKind = 'read' | 'write' | 'owner';
|
||||
|
||||
/** POSTs that change nothing (vitals queries, price conversion, batch reads). */
|
||||
export const READ_POSTS: RegExp[] = [
|
||||
/^playdeveloperreporting\..*\.query$/,
|
||||
/^androidpublisher\.monetization\.convertRegionPrices$/,
|
||||
/^androidpublisher\.monetization\..*\.batchGet$/,
|
||||
];
|
||||
|
||||
/** [pattern over "METHOD operationId", why]: the curated owner-only list. */
|
||||
export const OWNER_ONLY: Record<Store, [RegExp, string][]> = {
|
||||
apple: [
|
||||
[/^DELETE /, 'deletes'],
|
||||
[/^(POST|PATCH) \w*Submissions?(V\d)?_(create|update)Instance$/, 'submits for review (or cancels a submission)'],
|
||||
[/^POST (?!appStoreVersionPhasedReleases)\w*(Releases|ReleaseRequests)_createInstance$/, 'releases'],
|
||||
[/^PATCH appStoreVersionPhasedReleases_updateInstance$/, 'pauses, resumes or completes a phased release'],
|
||||
[/^PATCH appStoreVersionExperiments(V2)?_updateInstance$/, 'starts or stops a product page test'],
|
||||
[/^POST (appPriceSchedules|inAppPurchasePriceSchedules|subscriptionPrices)_createInstance$/, 'changes prices'],
|
||||
[/^POST customerReviewResponses_createInstance$/, 'sends a public review reply'],
|
||||
[/^POST (betaTesterInvitations|betaTesters|userInvitations)_createInstance$/, 'invites testers or users'],
|
||||
[/^POST (betaGroups_betaTesters|betaTesters_betaGroups|betaTesters_builds|builds_individualTesters)_createToManyRelationship$/, 'adds testers'],
|
||||
[/^(POST|PATCH) users_(updateInstance|visibleApps_\w+)$/, 'changes a team member\'s access'],
|
||||
],
|
||||
play: [
|
||||
[/^DELETE /, 'deletes'],
|
||||
[/^POST \S+\.(batchDelete|deleteall)$/, 'deletes'],
|
||||
[/^POST androidpublisher\.edits\.commit$/, 'publishes the edit (releases, listing and graphics go live)'],
|
||||
[/^POST \S+\.(cancel|refund|refundexternaltransaction|reviewrefund|revoke)$/, 'cancels, refunds or revokes'],
|
||||
[/^POST androidpublisher\.apprecovery\.deploy$/, 'deploys an app recovery action'],
|
||||
[/^POST \S+\.(activate|deactivate|archive|batchUpdateStates)$/, 'makes products or offers live (or takes them down)'],
|
||||
[/^POST androidpublisher\.appstoreappsreview\.updateappstorehostedapppublishstatus$/, 'changes a publish status'],
|
||||
[/^POST \S+\.(migratePrices|batchMigratePrices)$/, 'changes prices for existing subscribers'],
|
||||
[/^POST androidpublisher\.reviews\.reply$/, 'sends a public review reply'],
|
||||
[/^(PUT|PATCH) androidpublisher\.edits\.testers\.(update|patch)$/, 'changes the testers of a track'],
|
||||
[/^(POST|PATCH) androidpublisher\.(users|grants)\.(create|patch)$/, 'invites users or changes their permissions'],
|
||||
[/^POST androidpublisher\.appsigning\.(enrollApp|rotateAppSigningKey)$/, 'changes app signing (irreversible)'],
|
||||
],
|
||||
};
|
||||
|
||||
/** Why an operation is owner-only, or null. */
|
||||
export function ownerReason(store: Store, id: string, method: string): string | null {
|
||||
const key = `${method.toUpperCase()} ${id}`;
|
||||
return OWNER_ONLY[store].find(([re]) => re.test(key))?.[1] ?? null;
|
||||
}
|
||||
|
||||
/** Resource of an operation, for counts: Apple's first path segment (/v1/<apps>/...), Google's id without the method. */
|
||||
export const resourceOf = (r: { store: Store; id: string; path: string }): string =>
|
||||
r.store === 'apple' ? r.path.split('/')[2]! : r.id.split('.').slice(0, -1).join('.');
|
||||
|
||||
export function gateOf(store: Store, id: string, method: string): GateKind {
|
||||
const m = method.toUpperCase();
|
||||
if (m === 'GET') return 'read';
|
||||
if (store === 'play' && m === 'POST' && READ_POSTS.some(re => re.test(id))) return 'read';
|
||||
return ownerReason(store, id, m) ? 'owner' : 'write';
|
||||
}
|
||||
|
||||
export interface GateInput {
|
||||
kind: GateKind;
|
||||
method: string;
|
||||
/** --dry */
|
||||
dry: boolean;
|
||||
/** --yes */
|
||||
yes: boolean;
|
||||
/** stdin and stdout are a terminal */
|
||||
tty: boolean;
|
||||
/** under `storebound mcp` or `storebound serve` (STOREBOUND_MCP / STOREBOUND_SERVE) */
|
||||
agent: boolean;
|
||||
/** `storebound api get` (the MCP api_get tool): plain GETs only */
|
||||
getOnly: boolean;
|
||||
}
|
||||
|
||||
export type Decision =
|
||||
| { action: 'send' }
|
||||
| { action: 'confirm'; typed: true }
|
||||
| { action: 'dry'; why: string }
|
||||
| { action: 'refuse'; why: string };
|
||||
|
||||
/** What to do with one call. Pure. */
|
||||
export function decide(g: GateInput): Decision {
|
||||
if (g.getOnly && g.method.toUpperCase() !== 'GET') return { action: 'refuse', why: 'api get runs GET operations only' };
|
||||
if (g.kind === 'read') return g.dry ? { action: 'dry', why: '--dry' } : { action: 'send' };
|
||||
if (g.agent) return { action: 'refuse', why: g.kind === 'owner'
|
||||
? 'owner-only operation: never through MCP or the desktop app; the owner runs it in a terminal'
|
||||
: 'writes through `storebound api` are not available to MCP or the desktop app; run it in a terminal' };
|
||||
if (g.dry || !g.yes) return { action: 'dry', why: g.dry ? '--dry' : 'writes are dry by default: add --yes (in a terminal) to send' };
|
||||
if (!g.tty) return { action: 'dry', why: 'not an interactive terminal: writes through `storebound api` are only sent from one' };
|
||||
return g.kind === 'owner' ? { action: 'confirm', typed: true } : { action: 'send' };
|
||||
}
|
||||
181
cli/api/play.gen.ts
Normal file
181
cli/api/play.gen.ts
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
// GENERATED by tools/gen-api.ts from specs/androidpublisher_v3.discovery.json (Google Play Android Developer API v3, revision 20261008, https://www.googleapis.com/discovery/v1/apis/androidpublisher/v3/rest, downloaded 2026-10-11) and specs/playdeveloperreporting_v1beta1.discovery.json (Google Play Developer Reporting API v1beta1, revision 20261008, https://playdeveloperreporting.googleapis.com/$discovery/rest?version=v1beta1, downloaded 2026-10-11). Do not edit: run `bun tools/gen-api.ts` (CI checks it is fresh).
|
||||
// One row per method: [HTTP method, path ({p} one segment, {+p} may hold slashes), query parameters ("name", "name!"
|
||||
// required, "name*" repeated), request schema, response schema, flags (m media upload, d media download, p pageToken
|
||||
// paging, t token paging)]. The API is the first part of the id.
|
||||
export const PLAY_APIS = {
|
||||
androidpublisher: { title: 'Google Play Android Developer API v3', version: 'v3', revision: '20261008', root: 'https://androidpublisher.googleapis.com/', scope: 'https://www.googleapis.com/auth/androidpublisher', sha256: '668757f25cbe47e97f782758e818f1e18bf7da4e2049180ef0e49b3d0e465efc' },
|
||||
playdeveloperreporting: { title: 'Google Play Developer Reporting API v1beta1', version: 'v1beta1', revision: '20261008', root: 'https://playdeveloperreporting.googleapis.com/', scope: 'https://www.googleapis.com/auth/playdeveloperreporting', sha256: '277afdf1c026c13d91d0b3d6d5fd10a46ecaa9b21bbc2f085c104193e254a448' },
|
||||
} as const;
|
||||
|
||||
export const PLAY_OPS = {
|
||||
'androidpublisher.applications.dataSafety': ['POST', 'androidpublisher/v3/applications/{packageName}/dataSafety', '', 'SafetyLabelsUpdateRequest', 'SafetyLabelsUpdateResponse', '', ''],
|
||||
'androidpublisher.applications.deviceTierConfigs.create': ['POST', 'androidpublisher/v3/applications/{packageName}/deviceTierConfigs', 'allowUnknownDevices', 'DeviceTierConfig', 'DeviceTierConfig', '', ''],
|
||||
'androidpublisher.applications.deviceTierConfigs.get': ['GET', 'androidpublisher/v3/applications/{packageName}/deviceTierConfigs/{deviceTierConfigId}', '', '', 'DeviceTierConfig', '', ''],
|
||||
'androidpublisher.applications.deviceTierConfigs.list': ['GET', 'androidpublisher/v3/applications/{packageName}/deviceTierConfigs', 'pageSize pageToken', '', 'ListDeviceTierConfigsResponse', 'p', ''],
|
||||
'androidpublisher.applications.tracks.releases.list': ['GET', 'androidpublisher/v3/{+parent}/releases', '', '', 'ListReleaseSummariesResponse', '', 'parent=applications/*/tracks/*'],
|
||||
'androidpublisher.apprecovery.addTargeting': ['POST', 'androidpublisher/v3/applications/{packageName}/appRecoveries/{appRecoveryId}:addTargeting', '', 'AddTargetingRequest', 'AddTargetingResponse', '', ''],
|
||||
'androidpublisher.apprecovery.cancel': ['POST', 'androidpublisher/v3/applications/{packageName}/appRecoveries/{appRecoveryId}:cancel', '', 'CancelAppRecoveryRequest', 'CancelAppRecoveryResponse', '', ''],
|
||||
'androidpublisher.apprecovery.create': ['POST', 'androidpublisher/v3/applications/{packageName}/appRecoveries', '', 'CreateDraftAppRecoveryRequest', 'AppRecoveryAction', '', ''],
|
||||
'androidpublisher.apprecovery.deploy': ['POST', 'androidpublisher/v3/applications/{packageName}/appRecoveries/{appRecoveryId}:deploy', '', 'DeployAppRecoveryRequest', 'DeployAppRecoveryResponse', '', ''],
|
||||
'androidpublisher.apprecovery.list': ['GET', 'androidpublisher/v3/applications/{packageName}/appRecoveries', 'versionCode', '', 'ListAppRecoveriesResponse', '', ''],
|
||||
'androidpublisher.appsigning.enrollApp': ['POST', 'androidpublisher/v3/applications/{name}/appSigning:enrollApp', '', 'EnrollAppRequest', 'EnrollAppResponse', '', ''],
|
||||
'androidpublisher.appsigning.rotateAppSigningKey': ['POST', 'androidpublisher/v3/applications/{name}/appSigning:rotateAppSigningKey', '', 'RotateAppSigningKeyRequest', 'RotateAppSigningKeyResponse', '', ''],
|
||||
'androidpublisher.appstoreappsreview.createappstorehostedapp': ['POST', 'androidpublisher/v3/appstore/{appStorePackageName}/apps:create', '', 'CreateAppStoreHostedAppRequest', 'CreateAppStoreHostedAppResponse', '', ''],
|
||||
'androidpublisher.appstoreappsreview.updateappstorehostedapp': ['POST', 'androidpublisher/v3/appstore/{appStorePackageName}/apps:update', '', 'UpdateAppStoreHostedAppRequest', 'UpdateAppStoreHostedAppResponse', '', ''],
|
||||
'androidpublisher.appstoreappsreview.updateappstorehostedapppublishstatus': ['POST', 'androidpublisher/v3/appstore/{appStorePackageName}/apps/{packageName}:updateAppStoreHostedAppPublishStatus', '', 'UpdateAppStoreHostedAppPublishStatusRequest', 'UpdateAppStoreHostedAppPublishStatusResponse', '', ''],
|
||||
'androidpublisher.appstoreappsreview.uploadapk': ['POST', 'androidpublisher/v3/appstore/{appStorePackageName}/apps/{packageName}/apks:upload', '', 'UploadApkRequest', 'UploadApkResponse', 'm', ''],
|
||||
'androidpublisher.appstoreappsreview.uploadappstoreapppolicydeclarationfile': ['POST', 'androidpublisher/v3/appstore/{appStorePackageName}/apps/{packageName}/policyDeclarationFiles:upload', '', 'UploadAppStoreAppPolicyDeclarationFileRequest', 'UploadAppStoreAppPolicyDeclarationFileResponse', 'm', ''],
|
||||
'androidpublisher.appstoreappsreview.uploadimage': ['POST', 'androidpublisher/v3/appstore/{appStorePackageName}/apps/{packageName}/images:upload', '', 'UploadImageRequest', 'UploadImageResponse', 'm', ''],
|
||||
'androidpublisher.appstorecatalog.recentappviews.get': ['GET', 'androidpublisher/v3/appstorecatalog/{appStorePackageName}/recentAppViews/{playAppPackageName}', '', '', 'RecentAppView', '', ''],
|
||||
'androidpublisher.appstorecatalog.recentupdateevents.list': ['GET', 'androidpublisher/v3/appstorecatalog/{appStorePackageName}/recentUpdateEvents', 'endTime pageSize pageToken startTime', '', 'ListRecentUpdateEventsResponse', 'p', ''],
|
||||
'androidpublisher.edits.apks.addexternallyhosted': ['POST', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/apks/externallyHosted', '', 'ApksAddExternallyHostedRequest', 'ApksAddExternallyHostedResponse', '', ''],
|
||||
'androidpublisher.edits.apks.list': ['GET', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/apks', '', '', 'ApksListResponse', '', ''],
|
||||
'androidpublisher.edits.apks.upload': ['POST', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/apks', '', '', 'Apk', 'm', ''],
|
||||
'androidpublisher.edits.bundles.list': ['GET', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/bundles', '', '', 'BundlesListResponse', '', ''],
|
||||
'androidpublisher.edits.bundles.upload': ['POST', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/bundles', 'ackBundleInstallationWarning deviceTierConfigId', '', 'Bundle', 'm', ''],
|
||||
'androidpublisher.edits.commit': ['POST', 'androidpublisher/v3/applications/{packageName}/edits/{editId}:commit', 'changesInReviewBehavior changesNotSentForReview', '', 'AppEdit', '', ''],
|
||||
'androidpublisher.edits.countryavailability.get': ['GET', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/countryAvailability/{track}', '', '', 'TrackCountryAvailability', '', ''],
|
||||
'androidpublisher.edits.delete': ['DELETE', 'androidpublisher/v3/applications/{packageName}/edits/{editId}', '', '', '', '', ''],
|
||||
'androidpublisher.edits.deobfuscationfiles.upload': ['POST', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/apks/{apkVersionCode}/deobfuscationFiles/{deobfuscationFileType}', '', '', 'DeobfuscationFilesUploadResponse', 'm', ''],
|
||||
'androidpublisher.edits.details.get': ['GET', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/details', '', '', 'AppDetails', '', ''],
|
||||
'androidpublisher.edits.details.patch': ['PATCH', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/details', '', 'AppDetails', 'AppDetails', '', ''],
|
||||
'androidpublisher.edits.details.update': ['PUT', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/details', '', 'AppDetails', 'AppDetails', '', ''],
|
||||
'androidpublisher.edits.expansionfiles.get': ['GET', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/apks/{apkVersionCode}/expansionFiles/{expansionFileType}', '', '', 'ExpansionFile', '', ''],
|
||||
'androidpublisher.edits.expansionfiles.patch': ['PATCH', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/apks/{apkVersionCode}/expansionFiles/{expansionFileType}', '', 'ExpansionFile', 'ExpansionFile', '', ''],
|
||||
'androidpublisher.edits.expansionfiles.update': ['PUT', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/apks/{apkVersionCode}/expansionFiles/{expansionFileType}', '', 'ExpansionFile', 'ExpansionFile', '', ''],
|
||||
'androidpublisher.edits.expansionfiles.upload': ['POST', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/apks/{apkVersionCode}/expansionFiles/{expansionFileType}', '', '', 'ExpansionFilesUploadResponse', 'm', ''],
|
||||
'androidpublisher.edits.get': ['GET', 'androidpublisher/v3/applications/{packageName}/edits/{editId}', '', '', 'AppEdit', '', ''],
|
||||
'androidpublisher.edits.images.delete': ['DELETE', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/listings/{language}/{imageType}/{imageId}', '', '', '', '', ''],
|
||||
'androidpublisher.edits.images.deleteall': ['DELETE', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/listings/{language}/{imageType}', '', '', 'ImagesDeleteAllResponse', '', ''],
|
||||
'androidpublisher.edits.images.list': ['GET', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/listings/{language}/{imageType}', '', '', 'ImagesListResponse', '', ''],
|
||||
'androidpublisher.edits.images.upload': ['POST', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/listings/{language}/{imageType}', 'aiGeneratedState', '', 'ImagesUploadResponse', 'm', ''],
|
||||
'androidpublisher.edits.insert': ['POST', 'androidpublisher/v3/applications/{packageName}/edits', '', 'AppEdit', 'AppEdit', '', ''],
|
||||
'androidpublisher.edits.listings.delete': ['DELETE', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/listings/{language}', '', '', '', '', ''],
|
||||
'androidpublisher.edits.listings.deleteall': ['DELETE', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/listings', '', '', '', '', ''],
|
||||
'androidpublisher.edits.listings.get': ['GET', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/listings/{language}', '', '', 'Listing', '', ''],
|
||||
'androidpublisher.edits.listings.list': ['GET', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/listings', '', '', 'ListingsListResponse', '', ''],
|
||||
'androidpublisher.edits.listings.patch': ['PATCH', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/listings/{language}', '', 'Listing', 'Listing', '', ''],
|
||||
'androidpublisher.edits.listings.update': ['PUT', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/listings/{language}', '', 'Listing', 'Listing', '', ''],
|
||||
'androidpublisher.edits.testers.get': ['GET', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/testers/{track}', '', '', 'Testers', '', ''],
|
||||
'androidpublisher.edits.testers.patch': ['PATCH', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/testers/{track}', '', 'Testers', 'Testers', '', ''],
|
||||
'androidpublisher.edits.testers.update': ['PUT', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/testers/{track}', '', 'Testers', 'Testers', '', ''],
|
||||
'androidpublisher.edits.tracks.create': ['POST', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/tracks', '', 'TrackConfig', 'Track', '', ''],
|
||||
'androidpublisher.edits.tracks.get': ['GET', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/tracks/{track}', '', '', 'Track', '', ''],
|
||||
'androidpublisher.edits.tracks.list': ['GET', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/tracks', '', '', 'TracksListResponse', '', ''],
|
||||
'androidpublisher.edits.tracks.patch': ['PATCH', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/tracks/{track}', '', 'Track', 'Track', '', ''],
|
||||
'androidpublisher.edits.tracks.update': ['PUT', 'androidpublisher/v3/applications/{packageName}/edits/{editId}/tracks/{track}', '', 'Track', 'Track', '', ''],
|
||||
'androidpublisher.edits.validate': ['POST', 'androidpublisher/v3/applications/{packageName}/edits/{editId}:validate', '', '', 'AppEdit', '', ''],
|
||||
'androidpublisher.externaltransactions.createexternaltransaction': ['POST', 'androidpublisher/v3/{+parent}/externalTransactions', 'externalTransactionId', 'ExternalTransaction', 'ExternalTransaction', '', 'parent=applications/*'],
|
||||
'androidpublisher.externaltransactions.getexternaltransaction': ['GET', 'androidpublisher/v3/{+name}', '', '', 'ExternalTransaction', '', 'name=applications/*/externalTransactions/*'],
|
||||
'androidpublisher.externaltransactions.refundexternaltransaction': ['POST', 'androidpublisher/v3/{+name}:refund', '', 'RefundExternalTransactionRequest', 'ExternalTransaction', '', 'name=applications/*/externalTransactions/*'],
|
||||
'androidpublisher.generatedapks.download': ['GET', 'androidpublisher/v3/applications/{packageName}/generatedApks/{versionCode}/downloads/{downloadId}:download', '', '', '', 'd', ''],
|
||||
'androidpublisher.generatedapks.list': ['GET', 'androidpublisher/v3/applications/{packageName}/generatedApks/{versionCode}', '', '', 'GeneratedApksListResponse', '', ''],
|
||||
'androidpublisher.grants.create': ['POST', 'androidpublisher/v3/{+parent}/grants', '', 'Grant', 'Grant', '', 'parent=developers/*/users/*'],
|
||||
'androidpublisher.grants.delete': ['DELETE', 'androidpublisher/v3/{+name}', '', '', '', '', 'name=developers/*/users/*/grants/*'],
|
||||
'androidpublisher.grants.patch': ['PATCH', 'androidpublisher/v3/{+name}', 'updateMask', 'Grant', 'Grant', '', 'name=developers/*/users/*/grants/*'],
|
||||
'androidpublisher.inappproducts.batchDelete': ['POST', 'androidpublisher/v3/applications/{packageName}/inappproducts:batchDelete', '', 'InappproductsBatchDeleteRequest', '', '', ''],
|
||||
'androidpublisher.inappproducts.batchGet': ['GET', 'androidpublisher/v3/applications/{packageName}/inappproducts:batchGet', 'sku*', '', 'InappproductsBatchGetResponse', '', ''],
|
||||
'androidpublisher.inappproducts.batchUpdate': ['POST', 'androidpublisher/v3/applications/{packageName}/inappproducts:batchUpdate', '', 'InappproductsBatchUpdateRequest', 'InappproductsBatchUpdateResponse', '', ''],
|
||||
'androidpublisher.inappproducts.delete': ['DELETE', 'androidpublisher/v3/applications/{packageName}/inappproducts/{sku}', 'latencyTolerance', '', '', '', ''],
|
||||
'androidpublisher.inappproducts.get': ['GET', 'androidpublisher/v3/applications/{packageName}/inappproducts/{sku}', '', '', 'InAppProduct', '', ''],
|
||||
'androidpublisher.inappproducts.insert': ['POST', 'androidpublisher/v3/applications/{packageName}/inappproducts', 'autoConvertMissingPrices', 'InAppProduct', 'InAppProduct', '', ''],
|
||||
'androidpublisher.inappproducts.list': ['GET', 'androidpublisher/v3/applications/{packageName}/inappproducts', 'maxResults startIndex token', '', 'InappproductsListResponse', 't', ''],
|
||||
'androidpublisher.inappproducts.patch': ['PATCH', 'androidpublisher/v3/applications/{packageName}/inappproducts/{sku}', 'autoConvertMissingPrices latencyTolerance', 'InAppProduct', 'InAppProduct', '', ''],
|
||||
'androidpublisher.inappproducts.update': ['PUT', 'androidpublisher/v3/applications/{packageName}/inappproducts/{sku}', 'allowMissing autoConvertMissingPrices latencyTolerance', 'InAppProduct', 'InAppProduct', '', ''],
|
||||
'androidpublisher.internalappsharingartifacts.uploadapk': ['POST', 'androidpublisher/v3/applications/internalappsharing/{packageName}/artifacts/apk', '', '', 'InternalAppSharingArtifact', 'm', ''],
|
||||
'androidpublisher.internalappsharingartifacts.uploadbundle': ['POST', 'androidpublisher/v3/applications/internalappsharing/{packageName}/artifacts/bundle', '', '', 'InternalAppSharingArtifact', 'm', ''],
|
||||
'androidpublisher.monetization.convertRegionPrices': ['POST', 'androidpublisher/v3/applications/{packageName}/pricing:convertRegionPrices', '', 'ConvertRegionPricesRequest', 'ConvertRegionPricesResponse', '', ''],
|
||||
'androidpublisher.monetization.onetimeproducts.batchDelete': ['POST', 'androidpublisher/v3/applications/{packageName}/oneTimeProducts:batchDelete', '', 'BatchDeleteOneTimeProductsRequest', '', '', ''],
|
||||
'androidpublisher.monetization.onetimeproducts.batchGet': ['GET', 'androidpublisher/v3/applications/{packageName}/oneTimeProducts:batchGet', 'productIds*', '', 'BatchGetOneTimeProductsResponse', '', ''],
|
||||
'androidpublisher.monetization.onetimeproducts.batchUpdate': ['POST', 'androidpublisher/v3/applications/{packageName}/oneTimeProducts:batchUpdate', '', 'BatchUpdateOneTimeProductsRequest', 'BatchUpdateOneTimeProductsResponse', '', ''],
|
||||
'androidpublisher.monetization.onetimeproducts.delete': ['DELETE', 'androidpublisher/v3/applications/{packageName}/oneTimeProducts/{productId}', 'latencyTolerance', '', '', '', ''],
|
||||
'androidpublisher.monetization.onetimeproducts.get': ['GET', 'androidpublisher/v3/applications/{packageName}/oneTimeProducts/{productId}', '', '', 'OneTimeProduct', '', ''],
|
||||
'androidpublisher.monetization.onetimeproducts.list': ['GET', 'androidpublisher/v3/applications/{packageName}/oneTimeProducts', 'pageSize pageToken', '', 'ListOneTimeProductsResponse', 'p', ''],
|
||||
'androidpublisher.monetization.onetimeproducts.patch': ['PATCH', 'androidpublisher/v3/applications/{packageName}/onetimeproducts/{productId}', 'allowMissing latencyTolerance regionsVersion.version updateMask', 'OneTimeProduct', 'OneTimeProduct', '', ''],
|
||||
'androidpublisher.monetization.onetimeproducts.purchaseOptions.batchDelete': ['POST', 'androidpublisher/v3/applications/{packageName}/oneTimeProducts/{productId}/purchaseOptions:batchDelete', '', 'BatchDeletePurchaseOptionsRequest', '', '', ''],
|
||||
'androidpublisher.monetization.onetimeproducts.purchaseOptions.batchUpdateStates': ['POST', 'androidpublisher/v3/applications/{packageName}/oneTimeProducts/{productId}/purchaseOptions:batchUpdateStates', '', 'BatchUpdatePurchaseOptionStatesRequest', 'BatchUpdatePurchaseOptionStatesResponse', '', ''],
|
||||
'androidpublisher.monetization.onetimeproducts.purchaseOptions.offers.activate': ['POST', 'androidpublisher/v3/applications/{packageName}/oneTimeProducts/{productId}/purchaseOptions/{purchaseOptionId}/offers/{offerId}:activate', '', 'ActivateOneTimeProductOfferRequest', 'OneTimeProductOffer', '', ''],
|
||||
'androidpublisher.monetization.onetimeproducts.purchaseOptions.offers.batchDelete': ['POST', 'androidpublisher/v3/applications/{packageName}/oneTimeProducts/{productId}/purchaseOptions/{purchaseOptionId}/offers:batchDelete', '', 'BatchDeleteOneTimeProductOffersRequest', '', '', ''],
|
||||
'androidpublisher.monetization.onetimeproducts.purchaseOptions.offers.batchGet': ['POST', 'androidpublisher/v3/applications/{packageName}/oneTimeProducts/{productId}/purchaseOptions/{purchaseOptionId}/offers:batchGet', '', 'BatchGetOneTimeProductOffersRequest', 'BatchGetOneTimeProductOffersResponse', '', ''],
|
||||
'androidpublisher.monetization.onetimeproducts.purchaseOptions.offers.batchUpdate': ['POST', 'androidpublisher/v3/applications/{packageName}/oneTimeProducts/{productId}/purchaseOptions/{purchaseOptionId}/offers:batchUpdate', '', 'BatchUpdateOneTimeProductOffersRequest', 'BatchUpdateOneTimeProductOffersResponse', '', ''],
|
||||
'androidpublisher.monetization.onetimeproducts.purchaseOptions.offers.batchUpdateStates': ['POST', 'androidpublisher/v3/applications/{packageName}/oneTimeProducts/{productId}/purchaseOptions/{purchaseOptionId}/offers:batchUpdateStates', '', 'BatchUpdateOneTimeProductOfferStatesRequest', 'BatchUpdateOneTimeProductOfferStatesResponse', '', ''],
|
||||
'androidpublisher.monetization.onetimeproducts.purchaseOptions.offers.cancel': ['POST', 'androidpublisher/v3/applications/{packageName}/oneTimeProducts/{productId}/purchaseOptions/{purchaseOptionId}/offers/{offerId}:cancel', '', 'CancelOneTimeProductOfferRequest', 'OneTimeProductOffer', '', ''],
|
||||
'androidpublisher.monetization.onetimeproducts.purchaseOptions.offers.deactivate': ['POST', 'androidpublisher/v3/applications/{packageName}/oneTimeProducts/{productId}/purchaseOptions/{purchaseOptionId}/offers/{offerId}:deactivate', '', 'DeactivateOneTimeProductOfferRequest', 'OneTimeProductOffer', '', ''],
|
||||
'androidpublisher.monetization.onetimeproducts.purchaseOptions.offers.list': ['GET', 'androidpublisher/v3/applications/{packageName}/oneTimeProducts/{productId}/purchaseOptions/{purchaseOptionId}/offers', 'pageSize pageToken', '', 'ListOneTimeProductOffersResponse', 'p', ''],
|
||||
'androidpublisher.monetization.subscriptions.archive': ['POST', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}:archive', '', 'ArchiveSubscriptionRequest', 'Subscription', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.basePlans.activate': ['POST', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}/basePlans/{basePlanId}:activate', '', 'ActivateBasePlanRequest', 'Subscription', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.basePlans.batchMigratePrices': ['POST', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}/basePlans:batchMigratePrices', '', 'BatchMigrateBasePlanPricesRequest', 'BatchMigrateBasePlanPricesResponse', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.basePlans.batchUpdateStates': ['POST', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}/basePlans:batchUpdateStates', '', 'BatchUpdateBasePlanStatesRequest', 'BatchUpdateBasePlanStatesResponse', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.basePlans.deactivate': ['POST', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}/basePlans/{basePlanId}:deactivate', '', 'DeactivateBasePlanRequest', 'Subscription', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.basePlans.delete': ['DELETE', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}/basePlans/{basePlanId}', '', '', '', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.basePlans.migratePrices': ['POST', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}/basePlans/{basePlanId}:migratePrices', '', 'MigrateBasePlanPricesRequest', 'MigrateBasePlanPricesResponse', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.basePlans.offers.activate': ['POST', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}/basePlans/{basePlanId}/offers/{offerId}:activate', '', 'ActivateSubscriptionOfferRequest', 'SubscriptionOffer', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.basePlans.offers.batchGet': ['POST', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}/basePlans/{basePlanId}/offers:batchGet', '', 'BatchGetSubscriptionOffersRequest', 'BatchGetSubscriptionOffersResponse', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.basePlans.offers.batchUpdate': ['POST', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}/basePlans/{basePlanId}/offers:batchUpdate', '', 'BatchUpdateSubscriptionOffersRequest', 'BatchUpdateSubscriptionOffersResponse', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.basePlans.offers.batchUpdateStates': ['POST', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}/basePlans/{basePlanId}/offers:batchUpdateStates', '', 'BatchUpdateSubscriptionOfferStatesRequest', 'BatchUpdateSubscriptionOfferStatesResponse', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.basePlans.offers.create': ['POST', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}/basePlans/{basePlanId}/offers', 'offerId regionsVersion.version', 'SubscriptionOffer', 'SubscriptionOffer', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.basePlans.offers.deactivate': ['POST', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}/basePlans/{basePlanId}/offers/{offerId}:deactivate', '', 'DeactivateSubscriptionOfferRequest', 'SubscriptionOffer', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.basePlans.offers.delete': ['DELETE', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}/basePlans/{basePlanId}/offers/{offerId}', '', '', '', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.basePlans.offers.get': ['GET', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}/basePlans/{basePlanId}/offers/{offerId}', '', '', 'SubscriptionOffer', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.basePlans.offers.list': ['GET', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}/basePlans/{basePlanId}/offers', 'pageSize pageToken', '', 'ListSubscriptionOffersResponse', 'p', ''],
|
||||
'androidpublisher.monetization.subscriptions.basePlans.offers.patch': ['PATCH', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}/basePlans/{basePlanId}/offers/{offerId}', 'allowMissing latencyTolerance regionsVersion.version updateMask', 'SubscriptionOffer', 'SubscriptionOffer', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.batchGet': ['GET', 'androidpublisher/v3/applications/{packageName}/subscriptions:batchGet', 'productIds*', '', 'BatchGetSubscriptionsResponse', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.batchUpdate': ['POST', 'androidpublisher/v3/applications/{packageName}/subscriptions:batchUpdate', '', 'BatchUpdateSubscriptionsRequest', 'BatchUpdateSubscriptionsResponse', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.create': ['POST', 'androidpublisher/v3/applications/{packageName}/subscriptions', 'productId regionsVersion.version', 'Subscription', 'Subscription', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.delete': ['DELETE', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}', '', '', '', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.get': ['GET', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}', '', '', 'Subscription', '', ''],
|
||||
'androidpublisher.monetization.subscriptions.list': ['GET', 'androidpublisher/v3/applications/{packageName}/subscriptions', 'pageSize pageToken showArchived', '', 'ListSubscriptionsResponse', 'p', ''],
|
||||
'androidpublisher.monetization.subscriptions.patch': ['PATCH', 'androidpublisher/v3/applications/{packageName}/subscriptions/{productId}', 'allowMissing latencyTolerance regionsVersion.version updateMask', 'Subscription', 'Subscription', '', ''],
|
||||
'androidpublisher.orders.batchget': ['GET', 'androidpublisher/v3/applications/{packageName}/orders:batchGet', 'orderIds*', '', 'BatchGetOrdersResponse', '', ''],
|
||||
'androidpublisher.orders.get': ['GET', 'androidpublisher/v3/applications/{packageName}/orders/{orderId}', '', '', 'Order', '', ''],
|
||||
'androidpublisher.orders.refund': ['POST', 'androidpublisher/v3/applications/{packageName}/orders/{orderId}:refund', 'revoke', '', '', '', ''],
|
||||
'androidpublisher.orders.reviewrefund': ['POST', 'androidpublisher/v3/applications/{packageName}/orders/{orderId}:reviewrefund', '', 'OrdersReviewRefundRequest', '', '', ''],
|
||||
'androidpublisher.purchases.products.acknowledge': ['POST', 'androidpublisher/v3/applications/{packageName}/purchases/products/{productId}/tokens/{token}:acknowledge', '', 'ProductPurchasesAcknowledgeRequest', '', '', ''],
|
||||
'androidpublisher.purchases.products.consume': ['POST', 'androidpublisher/v3/applications/{packageName}/purchases/products/{productId}/tokens/{token}:consume', '', '', '', '', ''],
|
||||
'androidpublisher.purchases.products.get': ['GET', 'androidpublisher/v3/applications/{packageName}/purchases/products/{productId}/tokens/{token}', '', '', 'ProductPurchase', '', ''],
|
||||
'androidpublisher.purchases.productsv2.getproductpurchasev2': ['GET', 'androidpublisher/v3/applications/{packageName}/purchases/productsv2/tokens/{token}', '', '', 'ProductPurchaseV2', '', ''],
|
||||
'androidpublisher.purchases.subscriptions.acknowledge': ['POST', 'androidpublisher/v3/applications/{packageName}/purchases/subscriptions/{subscriptionId}/tokens/{token}:acknowledge', '', 'SubscriptionPurchasesAcknowledgeRequest', '', '', ''],
|
||||
'androidpublisher.purchases.subscriptions.cancel': ['POST', 'androidpublisher/v3/applications/{packageName}/purchases/subscriptions/{subscriptionId}/tokens/{token}:cancel', '', '', '', '', ''],
|
||||
'androidpublisher.purchases.subscriptions.defer': ['POST', 'androidpublisher/v3/applications/{packageName}/purchases/subscriptions/{subscriptionId}/tokens/{token}:defer', '', 'SubscriptionPurchasesDeferRequest', 'SubscriptionPurchasesDeferResponse', '', ''],
|
||||
'androidpublisher.purchases.subscriptionsv2.cancel': ['POST', 'androidpublisher/v3/applications/{packageName}/purchases/subscriptionsv2/tokens/{token}:cancel', '', 'CancelSubscriptionPurchaseRequest', 'CancelSubscriptionPurchaseResponse', '', ''],
|
||||
'androidpublisher.purchases.subscriptionsv2.defer': ['POST', 'androidpublisher/v3/applications/{packageName}/purchases/subscriptionsv2/tokens/{token}:defer', '', 'DeferSubscriptionPurchaseRequest', 'DeferSubscriptionPurchaseResponse', '', ''],
|
||||
'androidpublisher.purchases.subscriptionsv2.get': ['GET', 'androidpublisher/v3/applications/{packageName}/purchases/subscriptionsv2/tokens/{token}', '', '', 'SubscriptionPurchaseV2', '', ''],
|
||||
'androidpublisher.purchases.subscriptionsv2.revoke': ['POST', 'androidpublisher/v3/applications/{packageName}/purchases/subscriptionsv2/tokens/{token}:revoke', '', 'RevokeSubscriptionPurchaseRequest', 'RevokeSubscriptionPurchaseResponse', '', ''],
|
||||
'androidpublisher.purchases.voidedpurchases.list': ['GET', 'androidpublisher/v3/applications/{packageName}/purchases/voidedpurchases', 'endTime includeQuantityBasedPartialRefund maxResults startIndex startTime token type', '', 'VoidedPurchasesListResponse', 't', ''],
|
||||
'androidpublisher.reviews.get': ['GET', 'androidpublisher/v3/applications/{packageName}/reviews/{reviewId}', 'translationLanguage', '', 'Review', '', ''],
|
||||
'androidpublisher.reviews.list': ['GET', 'androidpublisher/v3/applications/{packageName}/reviews', 'maxResults startIndex token translationLanguage', '', 'ReviewsListResponse', 't', ''],
|
||||
'androidpublisher.reviews.reply': ['POST', 'androidpublisher/v3/applications/{packageName}/reviews/{reviewId}:reply', '', 'ReviewsReplyRequest', 'ReviewsReplyResponse', '', ''],
|
||||
'androidpublisher.systemapks.variants.create': ['POST', 'androidpublisher/v3/applications/{packageName}/systemApks/{versionCode}/variants', '', 'Variant', 'Variant', '', ''],
|
||||
'androidpublisher.systemapks.variants.download': ['GET', 'androidpublisher/v3/applications/{packageName}/systemApks/{versionCode}/variants/{variantId}:download', '', '', '', 'd', ''],
|
||||
'androidpublisher.systemapks.variants.get': ['GET', 'androidpublisher/v3/applications/{packageName}/systemApks/{versionCode}/variants/{variantId}', '', '', 'Variant', '', ''],
|
||||
'androidpublisher.systemapks.variants.list': ['GET', 'androidpublisher/v3/applications/{packageName}/systemApks/{versionCode}/variants', '', '', 'SystemApksListResponse', '', ''],
|
||||
'androidpublisher.users.create': ['POST', 'androidpublisher/v3/{+parent}/users', '', 'User', 'User', '', 'parent=developers/*'],
|
||||
'androidpublisher.users.delete': ['DELETE', 'androidpublisher/v3/{+name}', '', '', '', '', 'name=developers/*/users/*'],
|
||||
'androidpublisher.users.list': ['GET', 'androidpublisher/v3/{+parent}/users', 'pageSize pageToken', '', 'ListUsersResponse', 'p', 'parent=developers/*'],
|
||||
'androidpublisher.users.patch': ['PATCH', 'androidpublisher/v3/{+name}', 'updateMask', 'User', 'User', '', 'name=developers/*/users/*'],
|
||||
'playdeveloperreporting.anomalies.list': ['GET', 'v1beta1/{+parent}/anomalies', 'filter pageSize pageToken', '', 'GooglePlayDeveloperReportingV1beta1ListAnomaliesResponse', 'p', 'parent=apps/*'],
|
||||
'playdeveloperreporting.apps.fetchReleaseFilterOptions': ['GET', 'v1beta1/{+name}:fetchReleaseFilterOptions', '', '', 'GooglePlayDeveloperReportingV1beta1ReleaseFilterOptions', '', 'name=apps/*'],
|
||||
'playdeveloperreporting.apps.search': ['GET', 'v1beta1/apps:search', 'pageSize pageToken', '', 'GooglePlayDeveloperReportingV1beta1SearchAccessibleAppsResponse', 'p', ''],
|
||||
'playdeveloperreporting.vitals.anonrssandswapmemoryusage.get': ['GET', 'v1beta1/{+name}', '', '', 'GooglePlayDeveloperReportingV1beta1AnonRssAndSwapMemoryUsageMetricSet', '', 'name=apps/*/anonRssAndSwapMemoryUsageMetricSet'],
|
||||
'playdeveloperreporting.vitals.anonrssandswapmemoryusage.query': ['POST', 'v1beta1/{+name}:query', '', 'GooglePlayDeveloperReportingV1beta1QueryAnonRssAndSwapMemoryUsageMetricSetRequest', 'GooglePlayDeveloperReportingV1beta1QueryAnonRssAndSwapMemoryUsageMetricSetResponse', '', 'name=apps/*/anonRssAndSwapMemoryUsageMetricSet'],
|
||||
'playdeveloperreporting.vitals.anrrate.get': ['GET', 'v1beta1/{+name}', '', '', 'GooglePlayDeveloperReportingV1beta1AnrRateMetricSet', '', 'name=apps/*/anrRateMetricSet'],
|
||||
'playdeveloperreporting.vitals.anrrate.query': ['POST', 'v1beta1/{+name}:query', '', 'GooglePlayDeveloperReportingV1beta1QueryAnrRateMetricSetRequest', 'GooglePlayDeveloperReportingV1beta1QueryAnrRateMetricSetResponse', '', 'name=apps/*/anrRateMetricSet'],
|
||||
'playdeveloperreporting.vitals.bitmapmemoryusage.get': ['GET', 'v1beta1/{+name}', '', '', 'GooglePlayDeveloperReportingV1beta1BitmapMemoryUsageMetricSet', '', 'name=apps/*/bitmapMemoryUsageMetricSet'],
|
||||
'playdeveloperreporting.vitals.bitmapmemoryusage.query': ['POST', 'v1beta1/{+name}:query', '', 'GooglePlayDeveloperReportingV1beta1QueryBitmapMemoryUsageMetricSetRequest', 'GooglePlayDeveloperReportingV1beta1QueryBitmapMemoryUsageMetricSetResponse', '', 'name=apps/*/bitmapMemoryUsageMetricSet'],
|
||||
'playdeveloperreporting.vitals.crashrate.get': ['GET', 'v1beta1/{+name}', '', '', 'GooglePlayDeveloperReportingV1beta1CrashRateMetricSet', '', 'name=apps/*/crashRateMetricSet'],
|
||||
'playdeveloperreporting.vitals.crashrate.query': ['POST', 'v1beta1/{+name}:query', '', 'GooglePlayDeveloperReportingV1beta1QueryCrashRateMetricSetRequest', 'GooglePlayDeveloperReportingV1beta1QueryCrashRateMetricSetResponse', '', 'name=apps/*/crashRateMetricSet'],
|
||||
'playdeveloperreporting.vitals.errors.counts.get': ['GET', 'v1beta1/{+name}', '', '', 'GooglePlayDeveloperReportingV1beta1ErrorCountMetricSet', '', 'name=apps/*/errorCountMetricSet'],
|
||||
'playdeveloperreporting.vitals.errors.counts.query': ['POST', 'v1beta1/{+name}:query', '', 'GooglePlayDeveloperReportingV1beta1QueryErrorCountMetricSetRequest', 'GooglePlayDeveloperReportingV1beta1QueryErrorCountMetricSetResponse', '', 'name=apps/*/errorCountMetricSet'],
|
||||
'playdeveloperreporting.vitals.errors.issues.search': ['GET', 'v1beta1/{+parent}/errorIssues:search', 'filter interval.endTime.day interval.endTime.hours interval.endTime.minutes interval.endTime.month interval.endTime.nanos interval.endTime.seconds interval.endTime.timeZone.id interval.endTime.timeZone.version interval.endTime.utcOffset interval.endTime.year interval.startTime.day interval.startTime.hours interval.startTime.minutes interval.startTime.month interval.startTime.nanos interval.startTime.seconds interval.startTime.timeZone.id interval.startTime.timeZone.version interval.startTime.utcOffset interval.startTime.year orderBy pageSize pageToken sampleErrorReportLimit', '', 'GooglePlayDeveloperReportingV1beta1SearchErrorIssuesResponse', 'p', 'parent=apps/*'],
|
||||
'playdeveloperreporting.vitals.errors.reports.search': ['GET', 'v1beta1/{+parent}/errorReports:search', 'filter interval.endTime.day interval.endTime.hours interval.endTime.minutes interval.endTime.month interval.endTime.nanos interval.endTime.seconds interval.endTime.timeZone.id interval.endTime.timeZone.version interval.endTime.utcOffset interval.endTime.year interval.startTime.day interval.startTime.hours interval.startTime.minutes interval.startTime.month interval.startTime.nanos interval.startTime.seconds interval.startTime.timeZone.id interval.startTime.timeZone.version interval.startTime.utcOffset interval.startTime.year pageSize pageToken', '', 'GooglePlayDeveloperReportingV1beta1SearchErrorReportsResponse', 'p', 'parent=apps/*'],
|
||||
'playdeveloperreporting.vitals.excessivewakeuprate.get': ['GET', 'v1beta1/{+name}', '', '', 'GooglePlayDeveloperReportingV1beta1ExcessiveWakeupRateMetricSet', '', 'name=apps/*/excessiveWakeupRateMetricSet'],
|
||||
'playdeveloperreporting.vitals.excessivewakeuprate.query': ['POST', 'v1beta1/{+name}:query', '', 'GooglePlayDeveloperReportingV1beta1QueryExcessiveWakeupRateMetricSetRequest', 'GooglePlayDeveloperReportingV1beta1QueryExcessiveWakeupRateMetricSetResponse', '', 'name=apps/*/excessiveWakeupRateMetricSet'],
|
||||
'playdeveloperreporting.vitals.lmkrate.get': ['GET', 'v1beta1/{+name}', '', '', 'GooglePlayDeveloperReportingV1beta1LmkRateMetricSet', '', 'name=apps/*/lmkRateMetricSet'],
|
||||
'playdeveloperreporting.vitals.lmkrate.query': ['POST', 'v1beta1/{+name}:query', '', 'GooglePlayDeveloperReportingV1beta1QueryLmkRateMetricSetRequest', 'GooglePlayDeveloperReportingV1beta1QueryLmkRateMetricSetResponse', '', 'name=apps/*/lmkRateMetricSet'],
|
||||
'playdeveloperreporting.vitals.slowrenderingrate.get': ['GET', 'v1beta1/{+name}', '', '', 'GooglePlayDeveloperReportingV1beta1SlowRenderingRateMetricSet', '', 'name=apps/*/slowRenderingRateMetricSet'],
|
||||
'playdeveloperreporting.vitals.slowrenderingrate.query': ['POST', 'v1beta1/{+name}:query', '', 'GooglePlayDeveloperReportingV1beta1QuerySlowRenderingRateMetricSetRequest', 'GooglePlayDeveloperReportingV1beta1QuerySlowRenderingRateMetricSetResponse', '', 'name=apps/*/slowRenderingRateMetricSet'],
|
||||
'playdeveloperreporting.vitals.slowstartrate.get': ['GET', 'v1beta1/{+name}', '', '', 'GooglePlayDeveloperReportingV1beta1SlowStartRateMetricSet', '', 'name=apps/*/slowStartRateMetricSet'],
|
||||
'playdeveloperreporting.vitals.slowstartrate.query': ['POST', 'v1beta1/{+name}:query', '', 'GooglePlayDeveloperReportingV1beta1QuerySlowStartRateMetricSetRequest', 'GooglePlayDeveloperReportingV1beta1QuerySlowStartRateMetricSetResponse', '', 'name=apps/*/slowStartRateMetricSet'],
|
||||
'playdeveloperreporting.vitals.stuckbackgroundwakelockrate.get': ['GET', 'v1beta1/{+name}', '', '', 'GooglePlayDeveloperReportingV1beta1StuckBackgroundWakelockRateMetricSet', '', 'name=apps/*/stuckBackgroundWakelockRateMetricSet'],
|
||||
'playdeveloperreporting.vitals.stuckbackgroundwakelockrate.query': ['POST', 'v1beta1/{+name}:query', '', 'GooglePlayDeveloperReportingV1beta1QueryStuckBackgroundWakelockRateMetricSetRequest', 'GooglePlayDeveloperReportingV1beta1QueryStuckBackgroundWakelockRateMetricSetResponse', '', 'name=apps/*/stuckBackgroundWakelockRateMetricSet'],
|
||||
} as const;
|
||||
68
cli/api/types.ts
Normal file
68
cli/api/types.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
// Types of every App Store Connect / Google Play operation, derived from the generated rows (apple.gen.ts, play.gen.ts)
|
||||
// instead of one generated interface per endpoint: path parameters from the path template, query parameters from the
|
||||
// row's parameter list ("!" required), request and response shapes from the row's body / response columns.
|
||||
import type { APPLE_OPS } from './apple.gen';
|
||||
import type { PLAY_OPS } from './play.gen';
|
||||
|
||||
export type AppleOp = keyof typeof APPLE_OPS;
|
||||
export type PlayOp = keyof typeof PLAY_OPS;
|
||||
|
||||
/** A parameter value: arrays are comma-joined (Apple) or repeated (Google, "name*" parameters). */
|
||||
export type ParamValue = string | number | boolean | readonly (string | number)[];
|
||||
|
||||
/** "a b c" -> "a" | "b" | "c" (tail-recursive, so rows with 70+ parameters stay under the depth limit). */
|
||||
export type Split<S extends string, Acc = never> = S extends `${infer H} ${infer T}` ? Split<T, Acc | H> : S extends '' ? Acc : Acc | S;
|
||||
/** "/v1/apps/{id}/builds" -> "id"; "{+name}" -> "name". */
|
||||
export type PathParams<P extends string, Acc = never> = P extends `${string}{${infer N}}${infer R}` ? PathParams<R, Acc | (N extends `+${infer M}` ? M : N)> : Acc;
|
||||
type Required<T> = T extends `${infer N}!${string}` ? N : never;
|
||||
type Optional<T> = T extends `${string}!${string}` ? never : T extends `${infer N}*` ? N : T;
|
||||
|
||||
/** Parameters of one row: path parameters and required query parameters must be given, the rest may. */
|
||||
export type RowParams<R extends readonly string[]> =
|
||||
{ [K in PathParams<R[1]> | Required<Split<R[2]>>]: ParamValue } & { [K in Optional<Split<R[2]>>]?: ParamValue };
|
||||
|
||||
export type AppleParams<O extends AppleOp> = RowParams<(typeof APPLE_OPS)[O]>;
|
||||
export type PlayParams<O extends PlayOp> = RowParams<(typeof PLAY_OPS)[O]> & { fields?: string; prettyPrint?: boolean; quotaUser?: string };
|
||||
|
||||
// ---------------------------------------------------------------- JSON:API (App Store Connect), loosely typed
|
||||
|
||||
export interface Resource<T extends string = string> {
|
||||
type: T;
|
||||
id: string;
|
||||
attributes?: Record<string, unknown>;
|
||||
relationships?: Record<string, { data?: Linkage | Linkage[] | null; links?: Record<string, string>; meta?: Record<string, unknown> }>;
|
||||
links?: Record<string, string>;
|
||||
}
|
||||
export interface Linkage { type: string; id: string }
|
||||
export interface Document<D> {
|
||||
data: D;
|
||||
included?: Resource[];
|
||||
links?: { self?: string; next?: string; first?: string; related?: string };
|
||||
meta?: { paging?: { total?: number; limit?: number; nextCursor?: string } } & Record<string, unknown>;
|
||||
}
|
||||
|
||||
type AppleRow<O extends AppleOp> = (typeof APPLE_OPS)[O];
|
||||
|
||||
/** Response of an Apple operation: a JSON:API document of the row's resource type, raw bytes, or nothing. */
|
||||
export type AppleResponse<O extends AppleOp> =
|
||||
AppleRow<O>[4] extends `many:${infer T}` ? Document<Resource<T>[]>
|
||||
: AppleRow<O>[4] extends `one:${infer T}` ? Document<Resource<T>>
|
||||
: AppleRow<O>[4] extends `raw:${string}json` ? Record<string, unknown>
|
||||
: AppleRow<O>[4] extends `raw:${string}` ? Uint8Array
|
||||
: AppleRow<O>[4] extends 'none' ? null
|
||||
: Record<string, unknown>;
|
||||
|
||||
/** Request body of an Apple operation (undefined when it takes none). */
|
||||
export type AppleBody<O extends AppleOp> =
|
||||
AppleRow<O>[3] extends '' ? undefined
|
||||
: AppleRow<O>[3] extends 'json' ? Record<string, unknown>
|
||||
: AppleRow<O>[3] extends `${infer T}[]` ? { data: { type: T; id: string }[] }
|
||||
: { data: { type: AppleRow<O>[3]; id?: string; attributes?: Record<string, unknown>; relationships?: Record<string, unknown> } };
|
||||
|
||||
type PlayRow<O extends PlayOp> = (typeof PLAY_OPS)[O];
|
||||
|
||||
/** Google responses are plain JSON objects (schema name in the row); media downloads are bytes. */
|
||||
export type PlayResponse<O extends PlayOp> = PlayRow<O>[5] extends `${string}d${string}` ? Record<string, unknown> | Uint8Array : Record<string, unknown>;
|
||||
/** Request body: the JSON object of the row's schema, file bytes for a media upload, else nothing. */
|
||||
export type PlayBody<O extends PlayOp> =
|
||||
PlayRow<O>[3] extends '' ? (PlayRow<O>[5] extends `${string}m${string}` ? Uint8Array : undefined) : Record<string, unknown>;
|
||||
229
cli/api/wrapped.gen.ts
Normal file
229
cli/api/wrapped.gen.ts
Normal file
|
|
@ -0,0 +1,229 @@
|
|||
// GENERATED by tools/gen-api.ts from a scan of the API calls in cli/ (outside cli/api). Do not edit: run `bun tools/gen-api.ts` (CI checks it is fresh).
|
||||
// Operation id -> the source modules (cli/<module>.ts) of storebound commands that already call it.
|
||||
export const WRAPPED: { apple: Record<string, string>; play: Record<string, string> } = {
|
||||
apple: {
|
||||
'ageRatingDeclarations_updateInstance': 'apple/appinfo',
|
||||
'analyticsReportInstances_segments_getToManyRelated': 'analytics',
|
||||
'analyticsReportRequests_createInstance': 'analytics',
|
||||
'analyticsReportRequests_reports_getToManyRelated': 'analytics',
|
||||
'analyticsReports_instances_getToManyRelated': 'analytics',
|
||||
'appAvailabilitiesV2_createInstance': 'apple/appinfo',
|
||||
'appAvailabilitiesV2_territoryAvailabilities_getToManyRelated': 'apple/preorder',
|
||||
'appCustomProductPageLocalizations_appScreenshotSets_getToManyRelated': 'apple/cpp',
|
||||
'appCustomProductPageLocalizations_createInstance': 'lib/cpp-events',
|
||||
'appCustomProductPageLocalizations_updateInstance': 'lib/cpp-events',
|
||||
'appCustomProductPageVersions_appCustomProductPageLocalizations_getToManyRelated': 'apple/cpp',
|
||||
'appCustomProductPageVersions_updateInstance': 'apple/cpp',
|
||||
'appCustomProductPages_appCustomProductPageVersions_getToManyRelated': 'apple/cpp',
|
||||
'appCustomProductPages_createInstance': 'apple/cpp',
|
||||
'appCustomProductPages_updateInstance': 'apple/cpp',
|
||||
'appEncryptionDeclarations_getCollection': 'apple/encryption',
|
||||
'appEventLocalizations_appEventScreenshots_getToManyRelated': 'apple/events',
|
||||
'appEventLocalizations_createInstance': 'lib/cpp-events',
|
||||
'appEventLocalizations_updateInstance': 'lib/cpp-events',
|
||||
'appEventScreenshots_createInstance': 'apple/events',
|
||||
'appEventScreenshots_deleteInstance': 'apple/events',
|
||||
'appEventScreenshots_updateInstance': 'apple/events',
|
||||
'appEvents_createInstance': 'apple/events',
|
||||
'appEvents_localizations_getToManyRelated': 'apple/events',
|
||||
'appInfos_ageRatingDeclaration_getToOneRelated': 'validate',
|
||||
'appInfos_appInfoLocalizations_getToManyRelated': 'apple/listing validate',
|
||||
'appInfos_updateInstance': 'apple/appinfo',
|
||||
'appPreviewSets_appPreviews_getToManyRelated': 'apple/previews',
|
||||
'appPreviewSets_createInstance': 'apple/previews',
|
||||
'appPreviews_createInstance': 'apple/previews',
|
||||
'appPreviews_deleteInstance': 'apple/previews',
|
||||
'appPreviews_updateInstance': 'apple/previews',
|
||||
'appPriceSchedules_createInstance': 'apple/appinfo',
|
||||
'appScreenshotSets_appScreenshots_getToManyRelated': 'apple/ppo apple/screenshots validate',
|
||||
'appScreenshotSets_createInstance': 'apple/screenshots',
|
||||
'appScreenshots_createInstance': 'apple/screenshots',
|
||||
'appScreenshots_deleteInstance': 'apple/screenshots',
|
||||
'appScreenshots_updateInstance': 'apple/screenshots',
|
||||
'appStoreReviewDetails_createInstance': 'apple/review-details',
|
||||
'appStoreReviewDetails_updateInstance': 'apple/review-details',
|
||||
'appStoreVersionExperimentTreatmentLocalizations_appScreenshotSets_getToManyRelated': 'apple/ppo',
|
||||
'appStoreVersionExperimentTreatmentLocalizations_createInstance': 'lib/ppo',
|
||||
'appStoreVersionExperimentTreatments_appStoreVersionExperimentTreatmentLocalizations_getToManyRelated': 'apple/ppo',
|
||||
'appStoreVersionExperimentTreatments_createInstance': 'lib/ppo',
|
||||
'appStoreVersionExperimentsV2_appStoreVersionExperimentTreatments_getToManyRelated': 'apple/ppo',
|
||||
'appStoreVersionExperimentsV2_createInstance': 'lib/ppo',
|
||||
'appStoreVersionExperimentsV2_updateInstance': 'lib/ppo',
|
||||
'appStoreVersionLocalizations_appPreviewSets_getToManyRelated': 'apple/previews',
|
||||
'appStoreVersionLocalizations_appScreenshotSets_getToManyRelated': 'apple/screenshots validate',
|
||||
'appStoreVersionPhasedReleases_createInstance': 'apple/release',
|
||||
'appStoreVersionPhasedReleases_updateInstance': 'apple/release',
|
||||
'appStoreVersionReleaseRequests_createInstance': 'apple/release',
|
||||
'appStoreVersions_appStoreReviewDetail_getToOneRelated': 'apple/review-details validate',
|
||||
'appStoreVersions_appStoreVersionLocalizations_getToManyRelated': 'apple/listing apple/previews apple/screenshots validate',
|
||||
'appStoreVersions_appStoreVersionPhasedRelease_getToOneRelated': 'apple/release apple/status',
|
||||
'appStoreVersions_build_getToOneRelated': 'validate',
|
||||
'appStoreVersions_build_updateToOneRelationship': 'apple/listing',
|
||||
'appStoreVersions_createInstance': 'apple/listing',
|
||||
'appStoreVersions_updateInstance': 'apple/listing',
|
||||
'apps_analyticsReportRequests_getToManyRelated': 'analytics',
|
||||
'apps_appAvailabilityV2_getToOneRelated': 'apple/appinfo apple/preorder validate',
|
||||
'apps_appCustomProductPages_getToManyRelated': 'apple/cpp',
|
||||
'apps_appEvents_getToManyRelated': 'apple/events',
|
||||
'apps_appInfos_getToManyRelated': 'apple/asc apple/listing',
|
||||
'apps_appPricePoints_getToManyRelated': 'apple/appinfo',
|
||||
'apps_appPriceSchedule_getToOneRelated': 'apple/appinfo validate',
|
||||
'apps_appStoreVersionExperimentsV2_getToManyRelated': 'apple/ppo',
|
||||
'apps_appStoreVersions_getToManyRelated': 'apple/asc apple/iap-submit apple/listing apple/release apple/review-details apple/status lib/store-apps validate',
|
||||
'apps_betaAppLocalizations_getToManyRelated': 'apple/testflight',
|
||||
'apps_betaAppReviewDetail_getToOneRelated': 'apple/testflight',
|
||||
'apps_betaFeedbackCrashSubmissions_getToManyRelated': 'health',
|
||||
'apps_betaGroups_getToManyRelated': 'apple/testflight',
|
||||
'apps_customerReviews_getToManyRelated': 'reviews',
|
||||
'apps_getCollection': 'apple/asc apple/bundle apps lib/store-apps',
|
||||
'apps_getInstance': 'apple/status',
|
||||
'apps_inAppPurchasesV2_getToManyRelated': 'apple/iap apple/iap-review apple/iap-submit apple/offer-codes apple/promoted apple/status catalog prices validate',
|
||||
'apps_perfPowerMetrics_getToManyRelated': 'health',
|
||||
'apps_promotedPurchases_getToManyRelated': 'apple/promoted',
|
||||
'apps_promotedPurchases_replaceToManyRelationship': 'lib/offers',
|
||||
'apps_subscriptionGroups_getToManyRelated': 'apple/iap-submit apple/promoted apple/subscriptions apple/win-back catalog validate',
|
||||
'apps_updateInstance': 'apple/appinfo',
|
||||
'betaAppLocalizations_createInstance': 'lib/testflight',
|
||||
'betaAppLocalizations_updateInstance': 'lib/testflight',
|
||||
'betaAppReviewDetails_updateInstance': 'lib/testflight',
|
||||
'betaAppReviewSubmissions_createInstance': 'lib/testflight',
|
||||
'betaBuildLocalizations_createInstance': 'lib/testflight',
|
||||
'betaBuildLocalizations_updateInstance': 'lib/testflight',
|
||||
'betaFeedbackCrashSubmissions_crashLog_getToOneRelated': 'triage',
|
||||
'betaGroups_betaTesters_createToManyRelationship': 'lib/testflight',
|
||||
'betaGroups_betaTesters_deleteToManyRelationship': 'lib/testflight',
|
||||
'betaGroups_betaTesters_getToManyRelated': 'apple/testflight',
|
||||
'betaGroups_builds_createToManyRelationship': 'lib/testflight',
|
||||
'betaGroups_builds_getToManyRelated': 'apple/testflight',
|
||||
'betaGroups_createInstance': 'lib/testflight',
|
||||
'betaGroups_getCollection': 'apple/testflight',
|
||||
'betaTesterInvitations_createInstance': 'lib/testflight',
|
||||
'betaTesters_createInstance': 'lib/testflight',
|
||||
'betaTesters_getCollection': 'apple/testflight',
|
||||
'buildUploadFiles_createInstance': 'lib/xcode',
|
||||
'buildUploadFiles_updateInstance': 'lib/xcode',
|
||||
'buildUploads_createInstance': 'lib/xcode',
|
||||
'buildUploads_getInstance': 'apple/upload',
|
||||
'builds_appEncryptionDeclaration_getToOneRelated': 'validate',
|
||||
'builds_betaAppReviewSubmission_getToOneRelated': 'apple/testflight',
|
||||
'builds_betaBuildLocalizations_getToManyRelated': 'apple/testflight',
|
||||
'builds_diagnosticSignatures_getToManyRelated': 'health',
|
||||
'builds_getCollection': 'apple/build apple/encryption apple/listing apple/next-build apple/status apple/testflight apple/upload health lib/store-apps triage',
|
||||
'builds_updateInstance': 'apple/encryption lib/build-ops',
|
||||
'bundleIdCapabilities_createInstance': 'lib/signing',
|
||||
'bundleIds_createInstance': 'apple/bundle',
|
||||
'bundleIds_getCollection': 'apple/bundle apple/signing',
|
||||
'bundleIds_profiles_getToManyRelated': 'apple/signing',
|
||||
'certificates_createInstance': 'apple/signing lib/signing',
|
||||
'certificates_getCollection': 'apple/signing',
|
||||
'customerReviewResponses_createInstance': 'lib/reviews',
|
||||
'endAppAvailabilityPreOrders_createInstance': 'lib/offers',
|
||||
'financeReports_getCollection': 'lib/reports',
|
||||
'inAppPurchaseAppStoreReviewScreenshots_createInstance': 'apple/iap-review',
|
||||
'inAppPurchaseAppStoreReviewScreenshots_deleteInstance': 'apple/iap-review',
|
||||
'inAppPurchaseAppStoreReviewScreenshots_updateInstance': 'apple/iap-review',
|
||||
'inAppPurchaseAvailabilities_createInstance': 'apple/iap',
|
||||
'inAppPurchaseLocalizations_createInstance': 'apple/iap',
|
||||
'inAppPurchaseOfferCodeCustomCodes_createInstance': 'lib/offers',
|
||||
'inAppPurchaseOfferCodeOneTimeUseCodes_createInstance': 'lib/offers',
|
||||
'inAppPurchaseOfferCodeOneTimeUseCodes_values_getToOneRelated': 'apple/offer-codes',
|
||||
'inAppPurchaseOfferCodes_createInstance': 'apple/offer-codes',
|
||||
'inAppPurchaseOfferCodes_customCodes_getToManyRelated': 'apple/offer-codes',
|
||||
'inAppPurchaseOfferCodes_oneTimeUseCodes_getToManyRelated': 'apple/offer-codes',
|
||||
'inAppPurchasePricePoints_equalizations_getToManyRelated': 'apple/offer-codes',
|
||||
'inAppPurchasePriceSchedules_automaticPrices_getToManyRelated': 'prices',
|
||||
'inAppPurchasePriceSchedules_baseTerritory_getToOneRelated': 'prices',
|
||||
'inAppPurchasePriceSchedules_createInstance': 'apple/iap prices',
|
||||
'inAppPurchasePriceSchedules_manualPrices_getToManyRelated': 'prices',
|
||||
'inAppPurchaseVersions_createInstance': 'lib/review-submit',
|
||||
'inAppPurchasesV2_appStoreReviewScreenshot_getToOneRelated': 'apple/iap-review validate',
|
||||
'inAppPurchasesV2_createInstance': 'apple/iap',
|
||||
'inAppPurchasesV2_iapPriceSchedule_getToOneRelated': 'apple/iap catalog',
|
||||
'inAppPurchasesV2_inAppPurchaseAvailability_getToOneRelated': 'apple/iap',
|
||||
'inAppPurchasesV2_inAppPurchaseLocalizations_getToManyRelated': 'apple/iap catalog',
|
||||
'inAppPurchasesV2_offerCodes_getToManyRelated': 'apple/offer-codes',
|
||||
'inAppPurchasesV2_pricePoints_getToManyRelated': 'apple/iap apple/offer-codes prices',
|
||||
'inAppPurchasesV2_versions_getToManyRelated': 'apple/iap-submit',
|
||||
'profiles_certificates_getToManyRelationship': 'apple/signing',
|
||||
'profiles_createInstance': 'lib/signing',
|
||||
'profiles_getInstance': 'apple/signing',
|
||||
'promotedPurchases_createInstance': 'lib/offers',
|
||||
'promotedPurchases_updateInstance': 'lib/offers',
|
||||
'reviewSubmissionItems_createInstance': 'apple/events lib/cpp-events lib/review-submit',
|
||||
'reviewSubmissions_createInstance': 'apple/cpp apple/events lib/review-submit',
|
||||
'reviewSubmissions_getCollection': 'apple/cpp apple/events apple/iap-submit apple/status',
|
||||
'reviewSubmissions_items_getToManyRelated': 'apple/iap-submit',
|
||||
'reviewSubmissions_updateInstance': 'apple/cpp apple/events apple/iap-submit apple/status lib/review-submit',
|
||||
'salesReports_getCollection': 'lib/reports',
|
||||
'subscriptionAppStoreReviewScreenshots_createInstance': 'apple/subscriptions',
|
||||
'subscriptionAppStoreReviewScreenshots_updateInstance': 'apple/subscriptions',
|
||||
'subscriptionAvailabilities_createInstance': 'apple/subscriptions',
|
||||
'subscriptionGroupLocalizations_createInstance': 'apple/subscriptions',
|
||||
'subscriptionGroups_createInstance': 'apple/subscriptions',
|
||||
'subscriptionGroups_subscriptionGroupLocalizations_getToManyRelated': 'apple/subscriptions validate',
|
||||
'subscriptionGroups_subscriptions_getToManyRelated': 'apple/iap-submit apple/promoted apple/subscriptions apple/win-back catalog validate',
|
||||
'subscriptionGroups_versions_getToManyRelated': 'apple/iap-submit',
|
||||
'subscriptionLocalizations_createInstance': 'apple/subscriptions',
|
||||
'subscriptionOfferCodeCustomCodes_createInstance': 'apple/subscriptions',
|
||||
'subscriptionOfferCodes_createInstance': 'apple/subscriptions',
|
||||
'subscriptionOfferCodes_customCodes_getToManyRelated': 'apple/subscriptions',
|
||||
'subscriptionPricePoints_equalizations_getToManyRelated': 'apple/subscriptions apple/win-back',
|
||||
'subscriptionPromotionalOffers_createInstance': 'apple/subscriptions',
|
||||
'subscriptionVersions_createInstance': 'lib/review-submit',
|
||||
'subscriptions_appStoreReviewScreenshot_getToOneRelated': 'apple/subscriptions validate',
|
||||
'subscriptions_createInstance': 'apple/subscriptions',
|
||||
'subscriptions_introductoryOffers_getToManyRelated': 'apple/subscriptions catalog',
|
||||
'subscriptions_offerCodes_getToManyRelated': 'apple/subscriptions catalog',
|
||||
'subscriptions_pricePoints_getToManyRelated': 'apple/subscriptions apple/win-back',
|
||||
'subscriptions_prices_getToManyRelated': 'apple/subscriptions apple/win-back catalog',
|
||||
'subscriptions_promotionalOffers_getToManyRelated': 'apple/subscriptions catalog',
|
||||
'subscriptions_subscriptionAvailability_getToOneRelated': 'apple/subscriptions',
|
||||
'subscriptions_subscriptionLocalizations_getToManyRelated': 'apple/subscriptions catalog validate',
|
||||
'subscriptions_updateInstance': 'apple/subscriptions',
|
||||
'subscriptions_versions_getToManyRelated': 'apple/iap-submit',
|
||||
'subscriptions_winBackOffers_getToManyRelated': 'apple/win-back',
|
||||
'territories_getCollection': 'apple/appinfo apple/events apple/iap apple/offer-codes apple/subscriptions',
|
||||
'territoryAvailabilities_updateInstance': 'lib/offers',
|
||||
'winBackOffers_createInstance': 'apple/win-back',
|
||||
},
|
||||
play: {
|
||||
'androidpublisher.applications.dataSafety': 'play/data-safety',
|
||||
'androidpublisher.edits.apks.list': 'play/next-version-code',
|
||||
'androidpublisher.edits.bundles.list': 'play/next-version-code',
|
||||
'androidpublisher.edits.bundles.upload': 'play/release play/upload',
|
||||
'androidpublisher.edits.commit': 'play/client',
|
||||
'androidpublisher.edits.delete': 'apps play/client validate',
|
||||
'androidpublisher.edits.details.get': 'apps play/listing play/status validate',
|
||||
'androidpublisher.edits.details.update': 'play/listing',
|
||||
'androidpublisher.edits.images.deleteall': 'play/images',
|
||||
'androidpublisher.edits.images.list': 'apps play/images validate',
|
||||
'androidpublisher.edits.images.upload': 'play/images',
|
||||
'androidpublisher.edits.insert': 'apps play/client validate',
|
||||
'androidpublisher.edits.listings.list': 'play/listing play/status validate',
|
||||
'androidpublisher.edits.listings.update': 'play/listing',
|
||||
'androidpublisher.edits.tracks.get': 'play/rollout play/upload',
|
||||
'androidpublisher.edits.tracks.list': 'play/next-version-code play/status validate',
|
||||
'androidpublisher.edits.tracks.update': 'play/release play/rollout play/upload',
|
||||
'androidpublisher.edits.validate': 'play/client',
|
||||
'androidpublisher.monetization.convertRegionPrices': 'play/products play/subscriptions prices',
|
||||
'androidpublisher.monetization.onetimeproducts.get': 'prices',
|
||||
'androidpublisher.monetization.onetimeproducts.list': 'play/products',
|
||||
'androidpublisher.monetization.onetimeproducts.patch': 'play/products prices',
|
||||
'androidpublisher.monetization.onetimeproducts.purchaseOptions.batchUpdateStates': 'play/products',
|
||||
'androidpublisher.monetization.subscriptions.basePlans.activate': 'play/subscriptions',
|
||||
'androidpublisher.monetization.subscriptions.basePlans.offers.activate': 'play/subscriptions',
|
||||
'androidpublisher.monetization.subscriptions.basePlans.offers.create': 'play/subscriptions',
|
||||
'androidpublisher.monetization.subscriptions.basePlans.offers.list': 'catalog play/subscriptions',
|
||||
'androidpublisher.monetization.subscriptions.create': 'play/subscriptions',
|
||||
'androidpublisher.monetization.subscriptions.list': 'catalog play/subscriptions validate',
|
||||
'androidpublisher.monetization.subscriptions.patch': 'play/subscriptions',
|
||||
'androidpublisher.reviews.list': 'reviews',
|
||||
'androidpublisher.reviews.reply': 'lib/reviews',
|
||||
'playdeveloperreporting.apps.search': 'apps lib/store-apps',
|
||||
'playdeveloperreporting.vitals.anrrate.query': 'health',
|
||||
'playdeveloperreporting.vitals.crashrate.get': 'health',
|
||||
'playdeveloperreporting.vitals.crashrate.query': 'health',
|
||||
'playdeveloperreporting.vitals.errors.issues.search': 'health triage',
|
||||
'playdeveloperreporting.vitals.errors.reports.search': 'triage',
|
||||
},
|
||||
};
|
||||
|
|
@ -24,7 +24,9 @@ export function setUpToDate(existing: { checksum?: string | null; state?: string
|
|||
return existing.length === want.length && existing.every((e, i) => e.checksum === want[i] && DELIVERED.includes(e.state ?? ''));
|
||||
}
|
||||
|
||||
export async function ascClient(root: string, bundleId: string, appIdHint?: string) {
|
||||
/** Cached ES256 token getter for the team API key (env or .storebound/): valid 18 minutes, renewed after 15. Shared by
|
||||
* ascClient and the generic `storebound api apple` client (cli/api/client.ts). */
|
||||
export function ascJwt(root: string): { jwt: () => string; keyId: string } {
|
||||
const k = ascKey(root);
|
||||
const key = createPrivateKey(k.pem);
|
||||
let cached = { jwt: '', until: 0 };
|
||||
|
|
@ -36,6 +38,12 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri
|
|||
cached = { jwt: `${h}.${p}.${b64(sign('sha256', Buffer.from(h + '.' + p), { key, dsaEncoding: 'ieee-p1363' }))}`, until: now + 900 };
|
||||
return cached.jwt;
|
||||
}
|
||||
return { jwt, keyId: k.keyId };
|
||||
}
|
||||
|
||||
export async function ascClient(root: string, bundleId: string, appIdHint?: string) {
|
||||
const k = ascJwt(root);
|
||||
const jwt = k.jwt;
|
||||
|
||||
async function asc(method: string, path: string, body?: unknown, attempt = 1): Promise<J> {
|
||||
const r = await fetch(path.startsWith('http') ? path : 'https://api.appstoreconnect.apple.com' + path, {
|
||||
|
|
@ -58,6 +66,18 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri
|
|||
}
|
||||
}
|
||||
|
||||
/** GET of a binary answer (sales / finance reports: application/a-gzip). null on 404 (Apple answers 404 when there
|
||||
* is no report for that date: no sales, or not published yet). */
|
||||
async function bytes(path: string, accept = 'application/a-gzip'): Promise<Uint8Array | null> {
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
const r = await fetch('https://api.appstoreconnect.apple.com' + path, { headers: { Authorization: 'Bearer ' + jwt(), Accept: accept } });
|
||||
if ((r.status >= 500 || r.status === 429) && attempt < 5) { await r.body?.cancel(); await Bun.sleep(2000 * attempt); continue; }
|
||||
if (r.status === 404) { await r.body?.cancel(); return null; }
|
||||
if (!r.ok) throw new Error(`GET ${path.replace(/\?.*$/, '')} -> ${r.status} ${errorBody(await r.text(), 600)}`);
|
||||
return new Uint8Array(await r.arrayBuffer());
|
||||
}
|
||||
}
|
||||
|
||||
/** Every item of a paged GET. */
|
||||
async function all(path: string): Promise<J[]> {
|
||||
const out: J[] = [];
|
||||
|
|
@ -107,5 +127,5 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri
|
|||
return res.id;
|
||||
}
|
||||
|
||||
return { asc, all, maybe, getAs, app, editableVersion, editableAppInfo, uploadAsset, keyId: k.keyId };
|
||||
return { asc, all, maybe, getAs, bytes, app, editableVersion, editableAppInfo, uploadAsset, keyId: k.keyId };
|
||||
}
|
||||
|
|
|
|||
148
cli/apple/build.ts
Normal file
148
cli/apple/build.ts
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
// Archive and export an App Store IPA with xcodebuild, no Xcode UI.
|
||||
// storebound apple build [--version 1.2.0] [--build-number N] [--scheme S] [--workspace W | --project P]
|
||||
// [--configuration Release] [--out build/ios] [--dry] [--json]
|
||||
// Finds the workspace / project and scheme (native, Capacitor ios/App, React Native ios/<Name>, Flutter ios/Runner,
|
||||
// Unity Unity-iPhone), takes the next safe build number from App Store Connect (apple next-build) unless
|
||||
// --build-number is given, writes <out>/ExportOptions.plist (method app-store-connect, team, signing style and the
|
||||
// profiles from apple.signing), runs xcodebuild archive and -exportArchive with the API key
|
||||
// (-allowProvisioningUpdates -authenticationKey*), and leaves <out>/export/<App>.ipa for `storebound apple upload`.
|
||||
// Full xcodebuild output goes to <out>/xcodebuild-*.log; the terminal gets the result lines.
|
||||
// Local only: nothing is sent to App Store Connect except reads (build numbers, team id, profiles).
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join, relative } from 'node:path';
|
||||
import { ascKeyFile } from '../lib/credentials';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { need } from '../lib/ctx';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { pump } from '../lib/runner';
|
||||
import { parseMobileprovision, toXmlPlist } from '../lib/plist';
|
||||
import { nextBuildNumber } from '../lib/release';
|
||||
import { exportOptions, profileDirs } from '../lib/signing';
|
||||
import { archiveArgs, type AscAuth, exportArgs, flutterConfigArgs, ipaInfo, pickXcode, scanXcode, showCmd } from '../lib/xcode';
|
||||
import { ascClient } from './asc';
|
||||
import { findBundleId } from './signing';
|
||||
|
||||
const TAG = 'build';
|
||||
|
||||
/** Installed App Store profiles for a bundle id, newest expiry first: { uuid, name, team }. */
|
||||
export function installedProfiles(bundleId: string, teamId: string | null, home = homedir()): { uuid: string; name: string; team: string; expires: string }[] {
|
||||
const out: { uuid: string; name: string; team: string; expires: string }[] = [];
|
||||
for (const d of profileDirs(home)) {
|
||||
let files: string[] = [];
|
||||
try { files = readdirSync(d).filter(f => f.endsWith('.mobileprovision')); } catch { continue; }
|
||||
for (const f of files) {
|
||||
try {
|
||||
const p = parseMobileprovision(readFileSync(join(d, f)));
|
||||
const ent = p.Entitlements as Record<string, unknown> | undefined;
|
||||
const appId = String(ent?.['application-identifier'] ?? '');
|
||||
const team = String((p.TeamIdentifier as string[] | undefined)?.[0] ?? '');
|
||||
const store = !p.ProvisionedDevices && !p.ProvisionsAllDevices && ent?.['get-task-allow'] !== true;
|
||||
if (!store || appId !== `${team}.${bundleId}` || (teamId && team !== teamId)) continue;
|
||||
if (Date.parse(String(p.ExpirationDate)) < Date.now()) continue;
|
||||
if (!out.some(x => x.uuid === p.UUID)) out.push({ uuid: String(p.UUID), name: String(p.Name), team, expires: String(p.ExpirationDate) });
|
||||
} catch { /* not a profile */ }
|
||||
}
|
||||
}
|
||||
return out.sort((a, b) => Date.parse(b.expires) - Date.parse(a.expires));
|
||||
}
|
||||
|
||||
async function runLogged(argv: string[], cwd: string, logFile: string, show: string, env?: Record<string, string>): Promise<void> {
|
||||
log(TAG, `$ ${show}`);
|
||||
log(TAG, `full output: ${logFile}`);
|
||||
const p = Bun.spawn(argv, { cwd, stdout: 'pipe', stderr: 'pipe', env: { ...process.env, LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8', ...env } });
|
||||
const chunks: string[] = [];
|
||||
const keep = /(\berror:|\*\* (ARCHIVE|EXPORT|BUILD) (SUCCEEDED|FAILED) \*\*|requires a provisioning profile|No signing certificate|Signing for .* requires|Exported .* to)/;
|
||||
const each = (line: string): void => { chunks.push(line); if (keep.test(line)) log(TAG, line.trim().slice(0, 300)); };
|
||||
await Promise.all([pump(p.stdout, 'stdout', each), pump(p.stderr, 'stderr', each)]);
|
||||
const code = await p.exited;
|
||||
writeFileSync(logFile, chunks.join('\n'));
|
||||
if (code !== 0) throw new Error(`${argv[0]} ${argv[1] ?? ''} failed (exit ${code}); last lines:\n${chunks.slice(-15).join('\n')}\nfull log: ${logFile}`);
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const bundleId = need(config.apple?.bundleId, 'apple.bundleId');
|
||||
const cfg = config.apple?.build ?? {};
|
||||
const signing = config.apple?.signing ?? {};
|
||||
const style = signing.style ?? 'automatic';
|
||||
const dry = a.has('dry');
|
||||
const json = a.has('json');
|
||||
const target = pickXcode(scanXcode(root), { ...cfg, workspace: a.get('workspace') ?? cfg.workspace, project: a.get('project') ?? cfg.project, scheme: a.get('scheme') ?? cfg.scheme });
|
||||
const configuration = a.str('configuration', cfg.configuration ?? 'Release');
|
||||
const out = resolve(a.get('out') ?? cfg.out ?? 'build/ios');
|
||||
const version = a.get('version');
|
||||
if (version && !/^\d+(\.\d+){0,2}$/.test(version)) throw new Error('--version: x.y.z');
|
||||
|
||||
// reads: build number and team id from App Store Connect (only if not given)
|
||||
let build = a.get('build-number');
|
||||
let teamId = signing.teamId ?? null;
|
||||
if (!build || !teamId) {
|
||||
try {
|
||||
const c = await ascClient(root, bundleId, config.apple?.appId);
|
||||
if (!build) {
|
||||
const builds = await c.all(`/v1/builds?filter[app]=${await c.app()}&limit=200&fields[builds]=version`);
|
||||
build = nextBuildNumber(builds.map(b => String(b.attributes.version)));
|
||||
log(TAG, `${builds.length} builds on App Store Connect: next build number ${build}`);
|
||||
}
|
||||
if (!teamId) teamId = (await findBundleId(c, bundleId))?.attributes?.seedId ?? null;
|
||||
} catch (e) {
|
||||
if (!dry) throw new Error(`${(e as Error).message}\n(pass --build-number N and set apple.signing.teamId to build without App Store Connect reads)`);
|
||||
warn(TAG, `App Store Connect not readable (${(e as Error).message.split('\n')[0]?.slice(0, 120)}): dry run continues with placeholders`);
|
||||
}
|
||||
}
|
||||
if (build && !/^\d+(\.\d+){0,2}$/.test(build)) throw new Error('--build-number: digits, e.g. 42 or 1.0.42');
|
||||
const buildNo = build ?? '<next build number>';
|
||||
|
||||
const ids = [bundleId, ...(signing.extraBundleIds ?? [])];
|
||||
const profiles: Record<string, string> = {};
|
||||
if (style === 'manual') for (const id of ids) {
|
||||
const p = installedProfiles(id, teamId)[0];
|
||||
if (p) profiles[id] = p.uuid; else if (!dry) throw new Error(`no installed App Store profile for ${id}: storebound apple signing ensure`);
|
||||
else warn(TAG, `no installed App Store profile for ${id} (storebound apple signing ensure)`);
|
||||
}
|
||||
const opts = exportOptions({ teamId: teamId ?? '<TEAM_ID>', style, profiles: style === 'manual' ? (Object.keys(profiles).length ? profiles : { [bundleId]: '<profile uuid>' }) : undefined });
|
||||
const plist = toXmlPlist(opts);
|
||||
const archivePath = join(out, `${target.scheme}.xcarchive`);
|
||||
const exportPath = join(out, 'export');
|
||||
const authPreview: AscAuth = { keyPath: '$ASC_P8', keyId: '$ASC_KEY_ID', issuerId: '$ASC_ISSUER_ID' };
|
||||
const auth = style === 'automatic' ? authPreview : null;
|
||||
const steps = [
|
||||
...(target.framework === 'flutter' ? [showCmd(flutterConfigArgs(buildNo, version), null)] : []),
|
||||
showCmd(archiveArgs({ target, root, configuration, archivePath, version, build: buildNo, teamId: teamId ?? undefined, auth }), auth),
|
||||
showCmd(exportArgs(archivePath, join(out, 'ExportOptions.plist'), exportPath, auth), auth),
|
||||
];
|
||||
const plan = { framework: target.framework, workspace: target.workspace ?? null, project: target.project ?? null, scheme: target.scheme, configuration,
|
||||
version: version ?? '(project value)', build: buildNo, teamId, signingStyle: style, exportOptions: opts, out: relative(root, out) || '.', steps, notes: target.notes };
|
||||
if (dry) {
|
||||
if (json) { printJson(plan); return; }
|
||||
log(TAG, `${target.framework}: ${target.workspace ?? target.project} scheme ${target.scheme} (${configuration}), build ${buildNo}${version ? `, version ${version}` : ''}, signing ${style}`);
|
||||
for (const n of target.notes) log(TAG, n);
|
||||
for (const s of steps) log(TAG, `would run: ${s}`);
|
||||
console.log(`\n${relative(root, join(out, 'ExportOptions.plist'))}:\n${plist}`);
|
||||
done(TAG, 'build planned (dry run)');
|
||||
return;
|
||||
}
|
||||
if (process.platform !== 'darwin' || !Bun.which('xcodebuild')) throw new Error('apple build needs macOS with Xcode (xcode-select --install is not enough: the full Xcode app)');
|
||||
for (const n of target.notes) log(TAG, n);
|
||||
mkdirSync(out, { recursive: true });
|
||||
writeFileSync(join(out, 'ExportOptions.plist'), plist);
|
||||
const key = style === 'automatic' ? ascKeyFile(root) : null;
|
||||
const realAuth: AscAuth | null = key ? { keyPath: key.keyPath, keyId: key.keyId, issuerId: key.issuerId } : null;
|
||||
try {
|
||||
if (target.framework === 'flutter') await runLogged(flutterConfigArgs(build!, version), root, join(out, 'flutter-config.log'), showCmd(flutterConfigArgs(build!, version), null));
|
||||
const arch = archiveArgs({ target, root, configuration, archivePath, version, build: build!, teamId: teamId ?? undefined, auth: realAuth });
|
||||
await runLogged(arch, root, join(out, 'xcodebuild-archive.log'), showCmd(arch, realAuth));
|
||||
const exp = exportArgs(archivePath, join(out, 'ExportOptions.plist'), exportPath, realAuth);
|
||||
await runLogged(exp, root, join(out, 'xcodebuild-export.log'), showCmd(exp, realAuth));
|
||||
} finally { key?.cleanup(); }
|
||||
const ipa = existsSync(exportPath) ? readdirSync(exportPath).find(f => f.endsWith('.ipa')) : undefined;
|
||||
if (!ipa) throw new Error(`export finished but no .ipa in ${exportPath}`);
|
||||
const info = ipaInfo(join(exportPath, ipa));
|
||||
if (info.bundleId !== bundleId) warn(TAG, `the IPA's bundle id is ${info.bundleId}, the config says ${bundleId}`);
|
||||
if (info.build !== build) warn(TAG, `the IPA has build ${info.build}, not ${build}: the project sets CFBundleVersion itself (use $(CURRENT_PROJECT_VERSION) in Info.plist)`);
|
||||
const result = { ipa: join(exportPath, ipa), bundleId: info.bundleId, version: info.version, build: info.build };
|
||||
if (json) printJson(result);
|
||||
done(TAG, `${relative(root, result.ipa)}: ${info.bundleId} ${info.version} (${info.build}). Next: storebound apple upload ${relative(root, result.ipa)} --dry`);
|
||||
}
|
||||
145
cli/apple/cpp.ts
Normal file
145
cli/apple/cpp.ts
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
// App Store custom product pages from apple.customProductPages.
|
||||
// storebound apple cpp list [--json]
|
||||
// storebound apple cpp create [--name "..."] [--dry] [--json] pages missing on App Store Connect + localizations
|
||||
// storebound apple cpp upload --name "..." [--only en-US,tr] [--src store/renders] [--dry] screenshots (the page's variant)
|
||||
// storebound apple cpp submit --name "..." [--dry] [--yes] into a review submission (the owner's step; asks)
|
||||
// storebound apple cpp visible --name "..." [--off] [--dry] [--yes] show / hide an approved page (asks)
|
||||
// create and upload change nothing customers see (MCP tools, dry by default). A page's screenshots come from the
|
||||
// renders of its shots variant (<renders>/<variant>/<lang>/ios69 ...), MD5-idempotent like apple screenshots.
|
||||
// Pure parts and sources: cli/lib/cpp-events.ts.
|
||||
import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { byAppleLocale, confirm, need } from '../lib/ctx';
|
||||
import { CPP_EDITABLE, CPP_LIMITS, cppCreateBody, cppLocales, type CustomProductPageDef, planCppLocales, reviewItemReq } from '../lib/cpp-events';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { textTable } from '../lib/table';
|
||||
import { numberedImages } from '../play/images';
|
||||
import { variantRoot } from '../shots/lib';
|
||||
import { type Asc, ascClient, type J } from './asc';
|
||||
import { describeReq, execute, one, type Req } from './jsonapi';
|
||||
import { displaySets, syncScreenshotSet } from './screenshots';
|
||||
|
||||
const TAG = 'cpp';
|
||||
const USAGE = 'usage: storebound apple cpp list | create [--name n] | upload --name n | submit --name n | visible --name n [--off]';
|
||||
|
||||
interface Page { id: string; name: string; url?: string; visible?: boolean; version?: { id: string; state: string; deepLink?: string | null } }
|
||||
|
||||
async function pagesOf(c: Asc, appId: string): Promise<Page[]> {
|
||||
const out: Page[] = [];
|
||||
for (const p of await c.all(`/v1/apps/${appId}/appCustomProductPages?limit=200`)) {
|
||||
const vs = await c.all(`/v1/appCustomProductPages/${p.id}/appCustomProductPageVersions?limit=50`);
|
||||
const v = vs.find((x: J) => CPP_EDITABLE.has(x.attributes.state)) ?? vs.at(-1);
|
||||
out.push({ id: p.id, name: p.attributes.name, url: p.attributes.url, visible: p.attributes.visible, ...(v ? { version: { id: v.id, state: v.attributes.state, deepLink: v.attributes.deepLink } } : {}) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A draft review submission of the app (READY_FOR_REVIEW), or the request that creates one. */
|
||||
async function draftSubmission(c: Asc, appId: string): Promise<string | null> {
|
||||
return (await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&filter[platform]=IOS&filter[state]=READY_FOR_REVIEW&limit=10`))[0]?.id ?? null;
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const sub = a._[0];
|
||||
if (!sub) throw new Error(USAGE);
|
||||
const dry = a.has('dry');
|
||||
const defs = config.apple?.customProductPages ?? [];
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const pages = await pagesOf(c, appId);
|
||||
const pick = (): { def: CustomProductPageDef; page: Page | undefined } => {
|
||||
const name = need(a.get('name'), '--name "<page name>"');
|
||||
const def = defs.find(d => d.name === name);
|
||||
if (!def) throw new Error(`no custom product page "${name}" in apple.customProductPages`);
|
||||
return { def, page: pages.find(p => p.name === name) };
|
||||
};
|
||||
|
||||
if (sub === 'list') {
|
||||
const rows = [...pages.map(p => [p.name, p.visible ? 'visible' : 'hidden', p.version?.state ?? '', defs.some(d => d.name === p.name) ? 'config' : '', p.url ?? '']),
|
||||
...defs.filter(d => !pages.some(p => p.name === d.name)).map(d => [d.name, '', 'not created', 'config', ''])];
|
||||
if (a.has('json')) { printJson({ pages, missing: defs.filter(d => !pages.some(p => p.name === d.name)).map(d => d.name), limit: CPP_LIMITS.pages }); return; }
|
||||
console.log(rows.length ? textTable(['page', 'visible', 'version', 'source', 'url'], rows) : 'no custom product pages');
|
||||
done(TAG, `${pages.length} of ${CPP_LIMITS.pages} custom product pages used`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === 'create') {
|
||||
const only = a.get('name');
|
||||
const reqs: Req[] = [];
|
||||
for (const d of defs.filter(x => !only || x.name === only)) {
|
||||
const locs = cppLocales(d, config.languages);
|
||||
const page = pages.find(p => p.name === d.name);
|
||||
if (!page) { reqs.push({ method: 'POST', path: '/v1/appCustomProductPages', note: `page "${d.name}" with ${locs.length} locale(s)`, body: cppCreateBody(appId, d, locs) }); continue; }
|
||||
if (!page.version || !CPP_EDITABLE.has(page.version.state)) { log(TAG, `"${d.name}": version ${page.version?.state ?? 'missing'}, not editable (a new version: App Store Connect)`); continue; }
|
||||
const have = (await c.all(`/v1/appCustomProductPageVersions/${page.version.id}/appCustomProductPageLocalizations?limit=200`)).map((l: J) => ({ id: l.id, locale: l.attributes.locale, promotionalText: l.attributes.promotionalText }));
|
||||
reqs.push(...planCppLocales(page.version.id, have, locs));
|
||||
if ((d.deepLink ?? null) !== (page.version.deepLink ?? null) && d.deepLink) reqs.push({ method: 'PATCH', path: `/v1/appCustomProductPageVersions/${page.version.id}`, note: `"${d.name}" deep link`,
|
||||
body: { data: { type: 'appCustomProductPageVersions', id: page.version.id, attributes: { deepLink: d.deepLink } } } });
|
||||
}
|
||||
if (pages.length + reqs.filter(r => r.path === '/v1/appCustomProductPages').length > CPP_LIMITS.pages) throw new Error(`more than ${CPP_LIMITS.pages} custom product pages`);
|
||||
if (a.has('json')) printJson({ dryRun: dry, requests: reqs.map(r => describeReq(r)) });
|
||||
if (!reqs.length) { done(TAG, 'custom product pages up to date'); return; }
|
||||
await execute(c.asc, reqs, { dry, tag: TAG });
|
||||
done(TAG, dry ? `dry run: ${reqs.length} change(s)` : `${reqs.length} change(s); next: storebound apple cpp upload --name "<page>"`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === 'upload') {
|
||||
const { def, page } = pick();
|
||||
if (!page?.version) throw new Error(`"${def.name}" is not on App Store Connect yet (storebound apple cpp create)`);
|
||||
if (!CPP_EDITABLE.has(page.version.state)) throw new Error(`"${def.name}": version ${page.version.state}, screenshots can only change on an editable version`);
|
||||
const src = variantRoot(resolve(a.get('src') ?? config.renders ?? config.shots?.out ?? 'store/renders'), def.variant, config.shots?.variants);
|
||||
const only = a.list('only');
|
||||
const langOf = byAppleLocale(config.languages);
|
||||
let sets = 0;
|
||||
for (const loc of await c.all(`/v1/appCustomProductPageVersions/${page.version.id}/appCustomProductPageLocalizations?limit=200`)) {
|
||||
const locale: string = loc.attributes.locale;
|
||||
if (only.length && !only.includes(locale)) continue;
|
||||
const lang = langOf.get(locale);
|
||||
if (!lang) { warn(TAG, `${locale}: no language with apple: "${locale}", skipped`); continue; }
|
||||
const existing = await c.all(`/v1/appCustomProductPageLocalizations/${loc.id}/appScreenshotSets?limit=50`);
|
||||
for (const [dir, type] of Object.entries(displaySets(config.apple))) {
|
||||
const d = join(src, lang.id, dir);
|
||||
const files = existsSync(d) ? numberedImages(d).filter(f => f.endsWith('.png')).slice(0, 10) : [];
|
||||
if (!files.length) { warn(TAG, `${locale}: nothing in ${d}, skipped`); continue; }
|
||||
await syncScreenshotSet(c, { rel: 'appCustomProductPageLocalization', type: 'appCustomProductPageLocalizations', id: loc.id }, existing, type, files, `"${def.name}" ${locale} ${type}`, dry);
|
||||
sets++;
|
||||
}
|
||||
}
|
||||
done(TAG, `${sets} screenshot set(s) ${dry ? 'checked (dry run)' : 'synced'} for "${def.name}"`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === 'submit') {
|
||||
const { def, page } = pick();
|
||||
if (!page?.version) throw new Error(`"${def.name}" is not on App Store Connect yet (storebound apple cpp create)`);
|
||||
if (!['PREPARE_FOR_SUBMISSION', 'REJECTED'].includes(page.version.state)) { done(TAG, `"${def.name}": version is ${page.version.state}, nothing to submit`); return; }
|
||||
const draft = await draftSubmission(c, appId);
|
||||
const create: Req = { method: 'POST', path: '/v1/reviewSubmissions', note: 'new draft review submission', body: { data: { type: 'reviewSubmissions', attributes: { platform: 'IOS' }, relationships: { app: one('apps', appId) } } } };
|
||||
const item = reviewItemReq(draft ?? '${submission}', 'appCustomProductPageVersion', page.version.id, `custom product page "${def.name}"`);
|
||||
if (dry) { await execute(c.asc, [...(draft ? [] : [create]), item, { method: 'PATCH', path: `/v1/reviewSubmissions/${draft ?? '${submission}'}`, note: 'submit for App Review' }], { dry, tag: TAG }); return; }
|
||||
if (!(await confirm(ctx, `Send custom product page "${def.name}" to App Review now?`))) return;
|
||||
const sid = draft ?? ((await c.asc('POST', create.path, create.body)).data.id as string);
|
||||
await c.asc('POST', item.path, reviewItemReq(sid, 'appCustomProductPageVersion', page.version.id, '').body);
|
||||
await c.asc('PATCH', `/v1/reviewSubmissions/${sid}`, { data: { type: 'reviewSubmissions', id: sid, attributes: { submitted: true } } });
|
||||
done(TAG, `"${def.name}" submitted (review submission ${sid}); after approval: storebound apple cpp visible --name "${def.name}"`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === 'visible') {
|
||||
const { def, page } = pick();
|
||||
if (!page) throw new Error(`"${def.name}" is not on App Store Connect yet`);
|
||||
const visible = !a.has('off');
|
||||
if (page.visible === visible) { done(TAG, `"${def.name}" is already ${visible ? 'visible' : 'hidden'}`); return; }
|
||||
const req: Req = { method: 'PATCH', path: `/v1/appCustomProductPages/${page.id}`, note: `"${def.name}" ${visible ? 'visible' : 'hidden'}`, body: { data: { type: 'appCustomProductPages', id: page.id, attributes: { visible } } } };
|
||||
if (dry) { await execute(c.asc, [req], { dry, tag: TAG }); return; }
|
||||
if (!(await confirm(ctx, `${visible ? 'Show' : 'Hide'} custom product page "${def.name}" on the App Store?`))) return;
|
||||
await execute(c.asc, [req], { dry: false, tag: TAG });
|
||||
done(TAG, `"${def.name}" ${visible ? 'visible' : 'hidden'}${page.url ? ` (${page.url})` : ''}`);
|
||||
return;
|
||||
}
|
||||
throw new Error(`unknown cpp command "${sub}"\n${USAGE}`);
|
||||
}
|
||||
126
cli/apple/events.ts
Normal file
126
cli/apple/events.ts
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
// App Store in-app events from apple.events.
|
||||
// storebound apple events list [--json]
|
||||
// storebound apple events create [--name "<reference name>"] [--dry] [--json] missing events + localizations
|
||||
// storebound apple events upload --name "..." [--dry] event card (16:9) + details page (9:16) images per locale
|
||||
// storebound apple events submit --name "..." [--dry] [--yes] into a review submission (the owner's step; asks)
|
||||
// An approved event is published by its own schedule (publishStart): sending it to review is the moment it is decided,
|
||||
// so `submit` asks first and is not an MCP tool. Up to 10 published and 15 approved events per app.
|
||||
// Pure parts and sources: cli/lib/cpp-events.ts.
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { type AppEventDef, checkEventMedia, EVENT_EDITABLE, EVENT_LIMITS, eventCreateBody, planEventLocales, reviewItemReq } from '../lib/cpp-events';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { textTable } from '../lib/table';
|
||||
import { imageInfo } from '../shots/spec';
|
||||
import { ascClient, type J } from './asc';
|
||||
import { describeReq, execute, one, type Req } from './jsonapi';
|
||||
|
||||
const TAG = 'events';
|
||||
const USAGE = 'usage: storebound apple events list | create [--name n] | upload --name n | submit --name n';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const sub = a._[0];
|
||||
if (!sub) throw new Error(USAGE);
|
||||
const dry = a.has('dry');
|
||||
const defs = config.apple?.events ?? [];
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const events = await c.all(`/v1/apps/${appId}/appEvents?limit=200`);
|
||||
const localeOf = (langId: string): string | undefined => config.languages.find(l => l.id === langId)?.apple;
|
||||
const pick = (): { def: AppEventDef; ev: J | undefined } => {
|
||||
const name = need(a.get('name'), '--name "<reference name>"');
|
||||
const def = defs.find(d => d.referenceName === name);
|
||||
if (!def) throw new Error(`no event "${name}" in apple.events`);
|
||||
return { def, ev: events.find((e: J) => e.attributes.referenceName === name) };
|
||||
};
|
||||
|
||||
if (sub === 'list') {
|
||||
const rows = events.map((e: J) => { const s = e.attributes.territorySchedules?.[0] ?? {}; return [e.attributes.referenceName, e.attributes.badge ?? '', e.attributes.eventState ?? '', (s.eventStart ?? '').slice(0, 16), (s.eventEnd ?? '').slice(0, 16), defs.some(d => d.referenceName === e.attributes.referenceName) ? 'config' : '']; });
|
||||
for (const d of defs.filter(d => !events.some((e: J) => e.attributes.referenceName === d.referenceName))) rows.push([d.referenceName, d.badge, 'not created', d.schedule.eventStart.slice(0, 16), d.schedule.eventEnd.slice(0, 16), 'config']);
|
||||
if (a.has('json')) { printJson({ events: events.map((e: J) => ({ id: e.id, ...e.attributes })), missing: defs.filter(d => !events.some((e: J) => e.attributes.referenceName === d.referenceName)).map(d => d.referenceName) }); return; }
|
||||
console.log(rows.length ? textTable(['event', 'badge', 'state', 'start', 'end', 'source'], rows) : 'no in-app events');
|
||||
const published = events.filter((e: J) => e.attributes.eventState === 'PUBLISHED').length, approved = events.filter((e: J) => ['APPROVED', 'ACCEPTED', 'PUBLISHED'].includes(e.attributes.eventState)).length;
|
||||
done(TAG, `${published} of ${EVENT_LIMITS.published} published, ${approved} of ${EVENT_LIMITS.approved} approved`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === 'create') {
|
||||
const only = a.get('name');
|
||||
const territories = (await c.all('/v1/territories?limit=200')).map((t: J) => t.id as string);
|
||||
const reqs: Req[] = [];
|
||||
const created: { def: AppEventDef; index: number }[] = [];
|
||||
for (const d of defs.filter(x => !only || x.referenceName === only)) {
|
||||
const want = Object.entries(d.listings).flatMap(([lang, x]) => { const locale = localeOf(lang); return locale ? [{ locale, ...x }] : []; });
|
||||
const primary = localeOf(d.primaryLanguage ?? '') ?? want[0]?.locale ?? 'en-US';
|
||||
const ev = events.find((e: J) => e.attributes.referenceName === d.referenceName);
|
||||
if (!ev) { created.push({ def: d, index: reqs.length }); reqs.push({ method: 'POST', path: '/v1/appEvents', note: `event "${d.referenceName}" (${d.badge}, ${d.schedule.eventStart} to ${d.schedule.eventEnd})`, body: eventCreateBody(appId, d, primary, d.schedule.territories ?? territories) }); continue; }
|
||||
if (!EVENT_EDITABLE.has(ev.attributes.eventState)) { log(TAG, `"${d.referenceName}": ${ev.attributes.eventState}, not editable`); continue; }
|
||||
const have = (await c.all(`/v1/appEvents/${ev.id}/localizations?limit=200`)).map((l: J) => ({ id: l.id, ...l.attributes }));
|
||||
reqs.push(...planEventLocales(ev.id, have, want));
|
||||
}
|
||||
if (a.has('json')) printJson({ dryRun: dry, requests: reqs.map(r => describeReq(r)) });
|
||||
if (!reqs.length) { done(TAG, 'in-app events up to date'); return; }
|
||||
if (dry) {
|
||||
await execute(c.asc, reqs, { dry, tag: TAG });
|
||||
for (const x of created) log(TAG, `then: ${Object.keys(x.def.listings).length} localization(s) for "${x.def.referenceName}"`);
|
||||
done(TAG, 'dry run: nothing changed');
|
||||
return;
|
||||
}
|
||||
const out = await execute(c.asc, reqs, { dry: false, tag: TAG }) as J[];
|
||||
for (const x of created) {
|
||||
const id = out[x.index].data.id as string;
|
||||
const want = Object.entries(x.def.listings).flatMap(([lang, t]) => { const locale = localeOf(lang); return locale ? [{ locale, ...t }] : []; });
|
||||
await execute(c.asc, planEventLocales(id, [], want), { dry: false, tag: TAG });
|
||||
}
|
||||
done(TAG, 'in-app events created / updated; next: storebound apple events upload --name "<event>"');
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === 'upload') {
|
||||
const { def, ev } = pick();
|
||||
if (!ev) throw new Error(`"${def.referenceName}" is not on App Store Connect yet (storebound apple events create)`);
|
||||
if (!EVENT_EDITABLE.has(ev.attributes.eventState)) throw new Error(`"${def.referenceName}": ${ev.attributes.eventState}, media can only change on a draft`);
|
||||
let n = 0;
|
||||
for (const loc of await c.all(`/v1/appEvents/${ev.id}/localizations?limit=200`)) {
|
||||
const lang = config.languages.find(l => l.apple === loc.attributes.locale);
|
||||
if (!lang) continue;
|
||||
const have = await c.all(`/v1/appEventLocalizations/${loc.id}/appEventScreenshots?limit=50`);
|
||||
for (const [key, kind] of [['card', 'EVENT_CARD'], ['details', 'EVENT_DETAILS_PAGE']] as const) {
|
||||
const tpl = def.media?.[key];
|
||||
if (!tpl) continue;
|
||||
const file = resolve(tpl.replaceAll('{lang}', lang.id));
|
||||
if (!existsSync(file)) { warn(TAG, `${loc.attributes.locale} ${kind}: no ${file}`); continue; }
|
||||
const info = imageInfo(readFileSync(file));
|
||||
const problems = checkEventMedia(kind, info.w, info.h, info.format);
|
||||
if (problems.length) throw new Error(`${file}: ${problems.join('; ')}`);
|
||||
if (have.some((s: J) => s.attributes.appEventAssetType === kind && s.attributes.fileSize === info.bytes)) { log(TAG, `${loc.attributes.locale} ${kind}: up to date`); continue; }
|
||||
if (dry) { log(TAG, `${loc.attributes.locale} ${kind}: would upload ${file} (${info.w}x${info.h})`); n++; continue; }
|
||||
for (const s of have.filter((x: J) => x.attributes.appEventAssetType === kind)) await c.asc('DELETE', `/v1/appEventScreenshots/${s.id}`);
|
||||
await c.uploadAsset('appEventScreenshots', { appEventLocalization: { data: { type: 'appEventLocalizations', id: loc.id } } }, file, { appEventAssetType: kind });
|
||||
log(TAG, `${loc.attributes.locale} ${kind}: uploaded`);
|
||||
n++;
|
||||
}
|
||||
}
|
||||
done(TAG, `${n} image(s) ${dry ? 'to upload (dry run)' : 'uploaded'} for "${def.referenceName}"`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === 'submit') {
|
||||
const { def, ev } = pick();
|
||||
if (!ev) throw new Error(`"${def.referenceName}" is not on App Store Connect yet`);
|
||||
if (!EVENT_EDITABLE.has(ev.attributes.eventState) && ev.attributes.eventState !== 'READY_FOR_REVIEW') { done(TAG, `"${def.referenceName}" is ${ev.attributes.eventState}, nothing to submit`); return; }
|
||||
const draft = (await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&filter[platform]=IOS&filter[state]=READY_FOR_REVIEW&limit=10`))[0]?.id as string | undefined;
|
||||
const create: Req = { method: 'POST', path: '/v1/reviewSubmissions', note: 'new draft review submission', body: { data: { type: 'reviewSubmissions', attributes: { platform: 'IOS' }, relationships: { app: one('apps', appId) } } } };
|
||||
if (dry) { await execute(c.asc, [...(draft ? [] : [create]), reviewItemReq(draft ?? '${submission}', 'appEvent', ev.id, `in-app event "${def.referenceName}"`), { method: 'PATCH', path: `/v1/reviewSubmissions/${draft ?? '${submission}'}`, note: 'submit for App Review' }], { dry, tag: TAG }); return; }
|
||||
if (!(await confirm(ctx, `Send in-app event "${def.referenceName}" to App Review? Once approved it is published on ${def.schedule.publishStart} by its schedule.`))) return;
|
||||
const sid = draft ?? ((await c.asc('POST', create.path, create.body)).data.id as string);
|
||||
await c.asc('POST', '/v1/reviewSubmissionItems', reviewItemReq(sid, 'appEvent', ev.id, '').body);
|
||||
await c.asc('PATCH', `/v1/reviewSubmissions/${sid}`, { data: { type: 'reviewSubmissions', id: sid, attributes: { submitted: true } } });
|
||||
done(TAG, `"${def.referenceName}" submitted (review submission ${sid})`);
|
||||
return;
|
||||
}
|
||||
throw new Error(`unknown events command "${sub}"\n${USAGE}`);
|
||||
}
|
||||
105
cli/apple/iap-submit.ts
Normal file
105
cli/apple/iap-submit.ts
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
// Send in-app purchases and subscriptions to App Review through a review submission (the owner's action).
|
||||
// storebound apple iap-submit [--only id1,id2] [--with-version] [--new-version] [--no-submit] [--dry] [--yes] [--json]
|
||||
// Default: every product and subscription of the config sold on the App Store. The plan (cli/lib/review-submit.ts)
|
||||
// says which version of each goes in, which items are first of their type (those need an app version in the same
|
||||
// submission: --with-version adds the editable one, and then submitting submits the app too), and what is left out.
|
||||
// --new-version: approved or rejected products get a new draft version first (POST inAppPurchaseVersions /
|
||||
// subscriptionVersions) so changed metadata can go to review. --no-submit: only fill the draft submission; the owner
|
||||
// presses "Submit for Review" in App Store Connect. Without --no-submit the last step asks first (never under MCP).
|
||||
import { sellsOn } from '../lib/config';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { allSubscriptions } from '../lib/subscriptions';
|
||||
import { bindIds, latestVersion, newVersionReq, type PIap, planIapSubmission, type PSub, type SubmitState, versionsOf } from '../lib/review-submit';
|
||||
import { type Asc, ascClient, type J } from './asc';
|
||||
import { describeReq, execute } from './jsonapi';
|
||||
|
||||
const TAG = 'iap-submit';
|
||||
|
||||
export async function readSubmitState(c: Asc, appId: string, want: string[]): Promise<SubmitState> {
|
||||
const appVersions = (await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=50`)).map((v: J) => ({ id: v.id, versionString: v.attributes.versionString,
|
||||
state: v.attributes.appVersionState ?? v.attributes.appStoreState }));
|
||||
const iaps: PIap[] = [];
|
||||
for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)) {
|
||||
// every product counts for "first of its type"; versions are only read for the products we submit
|
||||
const versions = want.includes(p.attributes.productId) ? versionsOf(await c.all(`/v2/inAppPurchases/${p.id}/versions?limit=200`)) : [];
|
||||
iaps.push({ id: p.id, productId: p.attributes.productId, type: p.attributes.inAppPurchaseType, state: p.attributes.state, versions });
|
||||
}
|
||||
const subs: PSub[] = [];
|
||||
const groups: SubmitState['groups'] = [];
|
||||
for (const g of await c.all(`/v1/apps/${appId}/subscriptionGroups?limit=200`)) {
|
||||
const members = await c.all(`/v1/subscriptionGroups/${g.id}/subscriptions?limit=200`);
|
||||
const wanted = members.some((s: J) => want.includes(s.attributes.productId));
|
||||
groups.push({ id: g.id, name: g.attributes.referenceName, versions: wanted ? versionsOf(await c.all(`/v1/subscriptionGroups/${g.id}/versions?limit=200`)) : [] });
|
||||
for (const s of members) subs.push({ id: s.id, productId: s.attributes.productId, groupId: g.id, state: s.attributes.state,
|
||||
versions: want.includes(s.attributes.productId) ? versionsOf(await c.all(`/v1/subscriptions/${s.id}/versions?limit=200`)) : [] });
|
||||
}
|
||||
const drafts = await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&filter[platform]=IOS&filter[state]=READY_FOR_REVIEW&limit=10`);
|
||||
let draft: SubmitState['draft'] = null;
|
||||
if (drafts[0]) {
|
||||
const items = await c.all(`/v1/reviewSubmissions/${drafts[0].id}/items?include=appStoreVersion,inAppPurchaseVersion,subscriptionVersion,subscriptionGroupVersion&limit=200`);
|
||||
const ids = items.flatMap((it: J) => Object.values(it.relationships ?? {}).map((r: J) => r?.data?.id).filter(Boolean)) as string[];
|
||||
draft = { id: drafts[0].id, itemVersionIds: ids };
|
||||
}
|
||||
return { appVersions, iaps, subs, groups, draft };
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const dry = a.has('dry');
|
||||
const only = a.list('only');
|
||||
const ids = [...(config.products ?? []).filter(p => sellsOn(config, p, 'apple')).map(p => p.id), ...allSubscriptions(config.subscriptions).filter(x => sellsOn(config, x.sub, 'apple')).map(x => x.sub.id)]
|
||||
.filter(id => !only.length || only.includes(id));
|
||||
for (const id of only) if (!ids.includes(id)) throw new Error(`--only ${id}: not a product or subscription of the config sold on the App Store`);
|
||||
if (!ids.length) throw new Error('no in-app purchases or subscriptions in the config for the App Store');
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
let state = await readSubmitState(c, appId, ids);
|
||||
|
||||
if (a.has('new-version')) {
|
||||
const reqs = [
|
||||
...state.iaps.filter(p => ids.includes(p.productId) && ['APPROVED', 'REJECTED', 'DEVELOPER_REJECTED'].includes(latestVersion(p.versions)?.state ?? '')).map(p => newVersionReq('iap', p.id, p.productId)),
|
||||
...state.subs.filter(p => ids.includes(p.productId) && ['APPROVED', 'REJECTED', 'DEVELOPER_REJECTED'].includes(latestVersion(p.versions)?.state ?? '')).map(p => newVersionReq('sub', p.id, p.productId)),
|
||||
];
|
||||
if (reqs.length) {
|
||||
await execute(c.asc, reqs, { dry, tag: TAG });
|
||||
if (!dry) state = await readSubmitState(c, appId, ids);
|
||||
}
|
||||
}
|
||||
|
||||
const plan = planIapSubmission(state, ids, { withVersion: a.has('with-version') });
|
||||
const prepare = plan.prepare.map(r => bindIds(r, { app: appId }));
|
||||
if (a.has('json')) {
|
||||
printJson({ dryRun: dry, items: plan.items, skipped: plan.skipped, firstOfType: plan.firstOfType, hasApprovedVersion: plan.hasApprovedVersion,
|
||||
needsAppVersion: plan.needsAppVersion, blockers: plan.blockers, draft: state.draft?.id ?? null, requests: [...prepare, plan.submit].map(r => describeReq(r)) });
|
||||
if (dry || plan.blockers.length) { if (plan.blockers.length) process.exitCode = 1; return; }
|
||||
} else {
|
||||
for (const it of plan.items) log(TAG, `submit: ${it.label}`);
|
||||
for (const s of plan.skipped) log(TAG, `skip ${s.id}: ${s.why}`);
|
||||
if (plan.firstOfType.length) log(TAG, `first ${plan.firstOfType.join(' / ')} of the app: needs an app version in the same submission`);
|
||||
for (const b of plan.blockers) warn(TAG, b);
|
||||
}
|
||||
if (plan.blockers.length) { process.exitCode = 1; done(TAG, 'nothing sent: fix the blockers above'); return; }
|
||||
if (!plan.items.length) { done(TAG, 'nothing to submit'); return; }
|
||||
if (dry) {
|
||||
await execute(c.asc, [...prepare, plan.submit], { dry, tag: TAG });
|
||||
done(TAG, `dry run: ${plan.items.length} item(s) would go into ${state.draft ? `draft ${state.draft.id}` : 'a new draft submission'}`);
|
||||
return;
|
||||
}
|
||||
const what = `${plan.items.length} item(s)${plan.appVersion ? `, including app version ${plan.appVersion.versionString}` : ''}`;
|
||||
if (!(await confirm(ctx, `Add ${what} to ${state.draft ? 'the draft' : 'a new draft'} review submission?`))) return;
|
||||
let sid = state.draft?.id;
|
||||
for (const r of prepare) {
|
||||
const out = await c.asc(r.method, r.path, bindIds(r, { submission: sid }).body);
|
||||
if (r.path === '/v1/reviewSubmissions') sid = out.data.id;
|
||||
log(TAG, `${describeReq(bindIds(r, { submission: sid }))}: done`);
|
||||
}
|
||||
if (a.has('no-submit')) { done(TAG, `draft review submission ${sid} ready: press "Submit for Review" in App Store Connect (Apps > Distribution > App Review)`); return; }
|
||||
if (!(await confirm(ctx, `Submit review submission ${sid} (${what}) to App Review now?${plan.appVersion ? ' This submits the app version too.' : ''}`))) {
|
||||
done(TAG, `draft ${sid} kept; submit it in App Store Connect or re-run`); return;
|
||||
}
|
||||
await c.asc('PATCH', `/v1/reviewSubmissions/${sid}`, bindIds(plan.submit, { submission: sid }).body);
|
||||
done(TAG, `review submission ${sid} submitted (storebound apple status shows its state)`);
|
||||
}
|
||||
|
|
@ -4,11 +4,17 @@
|
|||
// - appInfoLocalizations: name, subtitle, privacy policy URL per locale
|
||||
// - appStoreVersionLocalizations: description, keywords, promotional text, what's new (not on a first version),
|
||||
// support + marketing URL per locale
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { parseAppStoreListing } from '../lib/copy';
|
||||
// And the other way round (read-only on App Store Connect):
|
||||
// storebound apple listing pull [--version x.y.z] [--write] [--json]
|
||||
// the live texts (the editable version if there is one, else the newest; --version picks one) into the App Store
|
||||
// listing file: shows the diff, writes only with --write.
|
||||
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { type AppleCopy, parseAppStoreListing } from '../lib/copy';
|
||||
import { compactDiff } from '../lib/diff';
|
||||
import { mergeAppleListing, overLimits } from '../lib/listing-pull';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { need } from '../lib/ctx';
|
||||
import { done, log } from '../lib/log';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { ascClient, type J } from './asc';
|
||||
|
||||
export function readAppleCopy(ctx: Ctx) {
|
||||
|
|
@ -34,9 +40,51 @@ async function upsertLocs(c: Awaited<ReturnType<typeof ascClient>>, list: string
|
|||
}
|
||||
}
|
||||
|
||||
/** apple listing pull: live texts -> diff -> (with --write) the App Store listing file. */
|
||||
async function pull(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const versions = await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=50`);
|
||||
const want = a.get('version');
|
||||
const sorted = [...versions].sort((x: J, y: J) => String(y.attributes.createdDate ?? '').localeCompare(String(x.attributes.createdDate ?? '')));
|
||||
const v = want ? sorted.find((x: J) => x.attributes.versionString === want) : (await c.editableVersion()) ?? sorted[0];
|
||||
if (!v) throw new Error(want ? `no iOS version ${want} on App Store Connect` : 'no iOS version on App Store Connect yet');
|
||||
const infos = await c.all(`/v1/apps/${appId}/appInfos`);
|
||||
const live = v.attributes.appVersionState ?? v.attributes.appStoreState;
|
||||
// the app info that belongs to the version: the editable one while a version is being prepared, else the live one
|
||||
const info = ['READY_FOR_DISTRIBUTION', 'READY_FOR_SALE'].includes(live)
|
||||
? infos.find((i: J) => ['READY_FOR_DISTRIBUTION', 'READY_FOR_SALE'].includes(i.attributes.state ?? i.attributes.appStoreState)) ?? infos[0]
|
||||
: await c.editableAppInfo();
|
||||
const remote: Record<string, AppleCopy> = {};
|
||||
for (const l of await c.all(`/v1/appInfos/${info.id}/appInfoLocalizations?limit=200`)) remote[l.attributes.locale] = { name: l.attributes.name ?? undefined, subtitle: l.attributes.subtitle ?? undefined };
|
||||
for (const l of await c.all(`/v1/appStoreVersions/${v.id}/appStoreVersionLocalizations?limit=200`)) {
|
||||
const at = l.attributes;
|
||||
remote[at.locale] = { ...remote[at.locale], description: at.description ?? undefined, keywords: at.keywords ?? undefined, promotionalText: at.promotionalText ?? undefined, whatsNew: at.whatsNew ?? undefined };
|
||||
}
|
||||
const file = resolve(config.apple?.listing ?? 'store/appstore.md');
|
||||
const before = existsSync(file) ? readFileSync(file, 'utf8') : '# App Store listing copy\n\nPulled from App Store Connect by `storebound apple listing pull`.\n';
|
||||
const r = mergeAppleListing(before, remote);
|
||||
const over = overLimits(r.changes, 'apple');
|
||||
const diff = compactDiff(before, r.md);
|
||||
if (a.has('json')) printJson({ version: v.attributes.versionString, state: live, file, write: a.has('write') && !a.has('dry'), changes: r.changes, added: r.added, overLimits: over, diff });
|
||||
else {
|
||||
log('apple', `pull: version ${v.attributes.versionString} (${live}), ${Object.keys(remote).length} locales`);
|
||||
for (const ch of r.changes) log('apple', `${ch.section} ${ch.field}: ${ch.from === null ? 'new' : 'changed'}`);
|
||||
if (diff.length) console.log(diff.join('\n'));
|
||||
}
|
||||
for (const o of over) warn('apple', `over the limit on the store: ${o}`);
|
||||
if (!r.changes.length) { done('apple', `${file} already matches the store`); return; }
|
||||
if (!a.has('write') || a.has('dry')) { done('apple', `${r.changes.length} change(s); nothing written (add --write to update ${file})`); return; }
|
||||
writeFileSync(file, r.md);
|
||||
done('apple', `${file}: ${r.changes.length} change(s) written${r.added.length ? `, new locales ${r.added.join(', ')}` : ''}`);
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
if (a._[0] === 'pull') return pull(ctx);
|
||||
const version = a.get('version');
|
||||
if (!version) throw new Error('usage: apple listing --version 1.0.0 [--build N] [--dry]');
|
||||
const listing = readAppleCopy(ctx);
|
||||
|
|
|
|||
92
cli/apple/offer-codes.ts
Normal file
92
cli/apple/offer-codes.ts
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
// Offer codes for one-time purchases (consumable, non-consumable, non-renewing) from products[].offerCodes.
|
||||
// storebound apple offer-codes [--only id1,id2] [--codes] [--dry] [--yes] [--json]
|
||||
// Creates the missing campaigns (by name) with their prices: free, or the USA price point of `usd` and its
|
||||
// equalizations (every territory, or `territories`). A campaign alone lets nobody redeem anything. Codes are made only
|
||||
// with --codes, after a confirmation: custom codes (anyone who has the code) and one-time-use batches; the one-time
|
||||
// codes are saved to .storebound/offer-codes/ (gitignored; treat them like vouchers). Each app may have 10 active
|
||||
// offers and 1 million codes per quarter (App Store Connect Help). Subscription offer codes: apple subscriptions.
|
||||
// Pure parts and sources: cli/lib/offers.ts.
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { sellsOn } from '../lib/config';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { iapCustomCodeReq, iapOfferCodeBody, iapOneTimeCodesReq, type TerritoryPoint, validateIapOfferCodes } from '../lib/offers';
|
||||
import { applePoints, pickPoint } from '../lib/subscriptions';
|
||||
import { pages } from '../prices';
|
||||
import { ascClient, type J } from './asc';
|
||||
import { describeReq, execute, type Req } from './jsonapi';
|
||||
|
||||
const TAG = 'offer-codes';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const dry = a.has('dry');
|
||||
const only = a.list('only');
|
||||
const products = (config.products ?? []).filter(p => p.offerCodes?.length && sellsOn(config, p, 'apple') && (!only.length || only.includes(p.id)));
|
||||
if (!products.length) throw new Error('no products with offerCodes for the App Store (products[].offerCodes in storebound.config.ts)');
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const problems = products.flatMap(p => validateIapOfferCodes(p.id, p.offerCodes, p.type, today));
|
||||
if (problems.length) throw new Error(problems.join('; '));
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const report: Record<string, unknown>[] = [];
|
||||
const codeReqs: { req: Req; product: string; campaign: string; oneTime: boolean }[] = [];
|
||||
let active = 0;
|
||||
|
||||
for (const p of products) {
|
||||
const iap = (await c.asc('GET', `/v1/apps/${appId}/inAppPurchasesV2?filter[productId]=${encodeURIComponent(p.id)}`)).data?.[0];
|
||||
if (!iap) { warn(TAG, `${p.id}: not on App Store Connect (storebound apple iap)`); report.push({ product: p.id, missing: true }); continue; }
|
||||
const existing = await c.all(`/v2/inAppPurchases/${iap.id}/offerCodes?include=customCodes,oneTimeUseCodes&limit=200`);
|
||||
active += existing.filter((x: J) => x.attributes.active).length;
|
||||
let usaPoints: ReturnType<typeof applePoints> | null = null;
|
||||
const prices = async (oc: NonNullable<typeof p.offerCodes>[number]): Promise<TerritoryPoint[]> => {
|
||||
if (oc.free) {
|
||||
const all = oc.territories ?? (await c.all('/v1/territories?limit=200')).map((t: J) => t.id as string);
|
||||
return all.map(territory => ({ territory }));
|
||||
}
|
||||
usaPoints ??= applePoints(await pages(c, `/v2/inAppPurchases/${iap.id}/pricePoints?filter[territory]=USA&include=territory&limit=200`));
|
||||
const usa = pickPoint(usaPoints, 'USA', oc.usd!);
|
||||
const eq = applePoints(await pages(c, `/v1/inAppPurchasePricePoints/${usa.id}/equalizations?include=territory&limit=200`));
|
||||
const all = [{ territory: 'USA', pointId: usa.id }, ...eq.filter(x => x.territory !== 'USA').map(x => ({ territory: x.territory, pointId: x.id }))];
|
||||
return oc.territories ? all.filter(x => oc.territories!.includes(x.territory)) : all;
|
||||
};
|
||||
for (const oc of p.offerCodes!) {
|
||||
const cur = existing.find((x: J) => x.attributes.name === oc.name);
|
||||
let id: string | undefined = cur?.id;
|
||||
if (!cur) {
|
||||
const body = iapOfferCodeBody(iap.id, oc, await prices(oc));
|
||||
const req: Req = { method: 'POST', path: '/v1/inAppPurchaseOfferCodes', body, note: `${p.id}: campaign "${oc.name}" (${oc.free ? 'free' : `USD ${oc.usd}`}, ${body.included.length} territories)` };
|
||||
if (dry) log(TAG, `would ${describeReq(req)}`);
|
||||
else { id = ((await execute(c.asc, [req], { dry, tag: TAG }))[0] as J).data.id; active++; }
|
||||
} else log(TAG, `${p.id}: campaign "${oc.name}" exists (${cur.attributes.active ? 'active' : 'inactive'}, ${cur.attributes.productionCodeCount ?? 0} production codes)`);
|
||||
const haveCustom = new Set(cur ? (await c.all(`/v1/inAppPurchaseOfferCodes/${cur.id}/customCodes?limit=200`)).map((x: J) => x.attributes.customCode) : []);
|
||||
for (const cc of oc.customCodes ?? []) if (!haveCustom.has(cc.code)) codeReqs.push({ req: iapCustomCodeReq(id ?? '${new campaign}', cc), product: p.id, campaign: oc.name, oneTime: false });
|
||||
// one-time batches are not matched one by one: a batch is created when the campaign has fewer batches than configured
|
||||
const batches = cur ? (await c.all(`/v1/inAppPurchaseOfferCodes/${cur.id}/oneTimeUseCodes?limit=200`)).length : 0;
|
||||
for (const b of (oc.oneTimeCodes ?? []).slice(batches)) codeReqs.push({ req: iapOneTimeCodesReq(id ?? '${new campaign}', b), product: p.id, campaign: oc.name, oneTime: true });
|
||||
report.push({ product: p.id, campaign: oc.name, exists: !!cur, codesToCreate: codeReqs.filter(x => x.campaign === oc.name && x.product === p.id).map(x => x.req.note) });
|
||||
}
|
||||
}
|
||||
if (active > 10) warn(TAG, `${active} active offer code campaigns: App Store Connect allows 10 active offers per app at a time`);
|
||||
if (a.has('json')) printJson({ dryRun: dry, campaigns: report, codes: codeReqs.map(x => describeReq(x.req)) });
|
||||
if (!codeReqs.length) { done(TAG, dry ? 'offer codes checked (dry run)' : 'offer codes done'); return; }
|
||||
if (!a.has('codes')) { for (const x of codeReqs) log(TAG, `not created without --codes: ${x.req.note}`); done(TAG, `${codeReqs.length} code request(s) left; run with --codes (asks first)`); return; }
|
||||
if (dry) { await execute(c.asc, codeReqs.map(x => x.req), { dry, tag: TAG }); done(TAG, 'dry run: no codes created'); return; }
|
||||
if (!(await confirm(ctx, `Create ${codeReqs.length} code request(s) (${codeReqs.map(x => x.req.note).join('; ')})? Codes count against the 1 million per quarter and can be redeemed by anyone who gets them.`))) return;
|
||||
const dir = resolve('.storebound/offer-codes');
|
||||
for (const x of codeReqs) {
|
||||
const out = (await execute(c.asc, [x.req], { dry: false, tag: TAG }))[0] as J;
|
||||
if (!x.oneTime) continue;
|
||||
// the codes of a one-time-use batch (text/csv); saved locally, never printed
|
||||
const values = await c.bytes(`/v1/inAppPurchaseOfferCodeOneTimeUseCodes/${out.data.id}/values`, 'text/csv');
|
||||
if (!values) { warn(TAG, `${x.product} "${x.campaign}": codes not ready yet; download them in App Store Connect`); continue; }
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const file = join(dir, `${x.product}-${x.campaign.replace(/[^A-Za-z0-9._-]+/g, '_')}-${out.data.id}.csv`);
|
||||
writeFileSync(file, values);
|
||||
log(TAG, `${x.product} "${x.campaign}": one-time codes saved to ${file}`);
|
||||
}
|
||||
done(TAG, `${codeReqs.length} code request(s) done`);
|
||||
}
|
||||
61
cli/apple/preorder.ts
Normal file
61
cli/apple/preorder.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
// App Store pre-orders through the app availability API.
|
||||
// storebound apple preorder status [--json]
|
||||
// storebound apple preorder enable --release-date YYYY-MM-DD [--territories USA,DEU] [--dry] [--yes] [--json]
|
||||
// storebound apple preorder end [--territories USA,DEU] [--dry] [--yes] [--json]
|
||||
// status: per territory available, release date, pre-order on, publish date, content statuses. enable puts the
|
||||
// territories (default: all the app is available in and not yet released) on pre-order with that release date; end
|
||||
// stops the pre-order and releases the app there at once. Both are public, so they show the dry run and ask first;
|
||||
// neither is an MCP tool. Apple requires an approved version first; the release date is 2-180 days ahead for a new
|
||||
// app (up to 365 days for an existing app in a new region). Google Play pre-registration has no API: Play Console >
|
||||
// Grow users > Pre-registration (see the app-store-promotion skill). Pure parts and sources: cli/lib/offers.ts.
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { done, printJson, warn } from '../lib/log';
|
||||
import { endPreOrderReq, planPreOrder, territoryRows } from '../lib/offers';
|
||||
import { textTable } from '../lib/table';
|
||||
import { ascClient, type J } from './asc';
|
||||
import { describeReq, execute } from './jsonapi';
|
||||
|
||||
const TAG = 'preorder';
|
||||
const USAGE = 'usage: storebound apple preorder status | enable --release-date YYYY-MM-DD [--territories USA,DEU] | end [--territories USA]';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const sub = a._[0];
|
||||
if (!sub || !['status', 'enable', 'end'].includes(sub)) throw new Error(USAGE);
|
||||
const dry = a.has('dry');
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const avail = (await c.maybe(`/v1/apps/${appId}/appAvailabilityV2`))?.data;
|
||||
if (!avail) throw new Error('the app has no availability yet: set territories first (storebound apple appinfo, or Pricing and Availability in App Store Connect)');
|
||||
const pagesOut: J[] = [];
|
||||
for (let url: string | null = `/v2/appAvailabilities/${avail.id}/territoryAvailabilities?include=territory&limit=200`; url;) { const p: J = await c.asc('GET', url); pagesOut.push(p); url = p.links?.next ?? null; }
|
||||
const rows = territoryRows(pagesOut);
|
||||
const territories = a.list('territories').length ? a.list('territories') : null;
|
||||
|
||||
if (sub === 'status') {
|
||||
const pre = rows.filter(r => r.preOrderEnabled);
|
||||
if (a.has('json')) { printJson({ availableInNewTerritories: avail.attributes?.availableInNewTerritories ?? null, territories: rows }); return; }
|
||||
console.log(textTable(['territory', 'available', 'release date', 'pre-order', 'pre-order published', 'status'],
|
||||
rows.filter(r => !territories || territories.includes(r.territory)).map(r => [r.territory, r.available ? 'yes' : 'no', r.releaseDate ?? '', r.preOrderEnabled ? 'on' : '', r.preOrderPublishDate ?? '', (r.contentStatuses ?? []).join(' ')])));
|
||||
done(TAG, `${rows.length} territories, ${pre.length} on pre-order`);
|
||||
return;
|
||||
}
|
||||
|
||||
const plan = sub === 'enable'
|
||||
? planPreOrder(rows, need(a.get('release-date'), '--release-date YYYY-MM-DD'), territories)
|
||||
: { reqs: [endPreOrderReq(rows, territories)].filter(r => r !== null), problems: [] as string[], warnings: [] as string[] };
|
||||
for (const w of plan.warnings) warn(TAG, w);
|
||||
if (plan.problems.length) throw new Error(plan.problems.join('; '));
|
||||
if (a.has('json') && dry) { printJson({ dryRun: true, requests: plan.reqs.map(r => describeReq(r)), warnings: plan.warnings }); return; }
|
||||
if (!plan.reqs.length) { done(TAG, sub === 'enable' ? 'pre-order already set up like that' : 'no territory is on pre-order'); return; }
|
||||
if (dry) { await execute(c.asc, plan.reqs, { dry, tag: TAG }); done(TAG, 'dry run: nothing changed'); return; }
|
||||
const q = sub === 'enable'
|
||||
? `Put the app on pre-order in ${plan.reqs.length} territor${plan.reqs.length === 1 ? 'y' : 'ies'} with release date ${a.get('release-date')}? The pre-order page goes public once you release an approved version.`
|
||||
: `End the pre-order and release the app now (${plan.reqs[0]!.note})?`;
|
||||
if (!(await confirm(ctx, q))) return;
|
||||
await execute(c.asc, plan.reqs, { dry: false, tag: TAG });
|
||||
if (a.has('json')) printJson({ dryRun: false, requests: plan.reqs.map(r => describeReq(r)) });
|
||||
done(TAG, sub === 'enable' ? 'pre-order set (storebound apple preorder status)' : 'pre-order ended; the app is released in those territories');
|
||||
}
|
||||
62
cli/apple/promoted.ts
Normal file
62
cli/apple/promoted.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
// Promoted in-app purchases on the App Store product page, from apple.promoted.
|
||||
// storebound apple promoted [--enable] [--dry] [--yes] [--json]
|
||||
// Status (what is promoted, enabled, its review state), then: creates the missing promoted purchases disabled,
|
||||
// updates visibleForAllUsers, sets the display order. --enable also switches them on, which shows them on the
|
||||
// product page once approved: that asks first and is not an MCP tool. Each promoted purchase needs its promotional
|
||||
// image (App Store Connect) and the app must handle purchases started on the App Store (StoreKit PurchaseIntent).
|
||||
// At most 20 at a time. Pure parts and sources: cli/lib/offers.ts.
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { planPromoted, type PromotedNow, promotedOrderReq } from '../lib/offers';
|
||||
import { textTable } from '../lib/table';
|
||||
import { ascClient, type J } from './asc';
|
||||
import { describeReq, execute } from './jsonapi';
|
||||
|
||||
const TAG = 'promoted';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const dry = a.has('dry');
|
||||
const cfg = config.apple?.promoted;
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const products = new Map<string, { apiId: string; kind: 'iap' | 'sub' }>();
|
||||
for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)) products.set(p.attributes.productId, { apiId: p.id, kind: 'iap' });
|
||||
for (const g of await c.all(`/v1/apps/${appId}/subscriptionGroups?limit=200`))
|
||||
for (const s of await c.all(`/v1/subscriptionGroups/${g.id}/subscriptions?limit=200`)) products.set(s.attributes.productId, { apiId: s.id, kind: 'sub' });
|
||||
const byApiId = new Map([...products.entries()].map(([pid, v]) => [v.apiId, pid] as const));
|
||||
const raw = await c.asc('GET', `/v1/apps/${appId}/promotedPurchases?include=inAppPurchaseV2,subscription&limit=50`);
|
||||
const now: PromotedNow[] = (raw.data ?? []).map((p: J) => ({ id: p.id, enabled: !!p.attributes.enabled, visibleForAllUsers: !!p.attributes.visibleForAllUsers, state: p.attributes.state,
|
||||
productId: byApiId.get(p.relationships?.inAppPurchaseV2?.data?.id ?? p.relationships?.subscription?.data?.id ?? '') ?? '?' }));
|
||||
const status = now.map((p, i) => [i + 1, p.productId, p.enabled ? 'enabled' : 'off', p.visibleForAllUsers ? 'everyone' : 'app decides', p.state ?? '']);
|
||||
if (!cfg) {
|
||||
if (a.has('json')) printJson({ promoted: now });
|
||||
else console.log(now.length ? textTable(['#', 'product', 'enabled', 'visible to', 'state'], status) : 'no promoted in-app purchases');
|
||||
done(TAG, 'apple.promoted is not set: status only');
|
||||
return;
|
||||
}
|
||||
const plan = planPromoted(appId, cfg, now, products, { enable: a.has('enable') });
|
||||
const order = promotedOrderReq(appId, cfg, now);
|
||||
for (const u of plan.unknown) warn(TAG, `${u}: not on App Store Connect (storebound apple iap / apple subscriptions)`);
|
||||
if (plan.extra.length) log(TAG, `promoted on the store but not in apple.promoted (left as they are): ${plan.extra.join(', ')}`);
|
||||
if (now.length + plan.create.length > 20) throw new Error(`${now.length + plan.create.length} promoted purchases: at most 20`);
|
||||
const reqs = [...plan.create, ...plan.update];
|
||||
if (a.has('json')) printJson({ dryRun: dry, promoted: now, requests: [...reqs, ...(order ? [order] : [])].map(r => describeReq(r)), unknown: plan.unknown, extra: plan.extra });
|
||||
else if (now.length) console.log(textTable(['#', 'product', 'enabled', 'visible to', 'state'], status));
|
||||
if (!reqs.length && !order) { done(TAG, 'promoted purchases up to date'); return; }
|
||||
if (dry) { await execute(c.asc, [...reqs, ...(order ? [order] : [])], { dry, tag: TAG }); done(TAG, 'dry run: nothing changed'); return; }
|
||||
const enabling = reqs.some(r => JSON.stringify(r.body).includes('"enabled":true'));
|
||||
if (enabling && !(await confirm(ctx, 'Switch promoted purchases on? Once approved they show on the App Store product page.'))) return;
|
||||
await execute(c.asc, reqs, { dry: false, tag: TAG });
|
||||
// the order covers the purchases that exist now (new ones included)
|
||||
if (plan.create.length || order) {
|
||||
const fresh = await c.asc('GET', `/v1/apps/${appId}/promotedPurchases?include=inAppPurchaseV2,subscription&limit=50`);
|
||||
const after: PromotedNow[] = (fresh.data ?? []).map((p: J) => ({ id: p.id, enabled: !!p.attributes.enabled, visibleForAllUsers: !!p.attributes.visibleForAllUsers,
|
||||
productId: byApiId.get(p.relationships?.inAppPurchaseV2?.data?.id ?? p.relationships?.subscription?.data?.id ?? '') ?? '?' }));
|
||||
const o = promotedOrderReq(appId, cfg, after);
|
||||
if (o) await execute(c.asc, [o], { dry: false, tag: TAG });
|
||||
}
|
||||
done(TAG, `promoted purchases updated${a.has('enable') ? '' : ' (not switched on: --enable when the images are approved)'}`);
|
||||
}
|
||||
232
cli/apple/signing.ts
Normal file
232
cli/apple/signing.ts
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
// Code signing through the App Store Connect API: bundle id capabilities, the distribution certificate and the
|
||||
// provisioning profiles, so `apple build` can sign without anyone opening Xcode's Accounts settings.
|
||||
// storebound apple signing status [--json] read-only: capabilities, certificates (with / without a
|
||||
// private key on this machine), profiles, what is installed
|
||||
// storebound apple signing ensure [--dry] [--yes] [--keychain [path]] [--no-install] [--json]
|
||||
// adds missing capabilities (apple.signing.capabilities), creates a distribution certificate when this machine
|
||||
// holds no key for any valid one (RSA 2048 key generated here, kept 0600 in .storebound/signing/, never printed;
|
||||
// --keychain also imports key + certificate into the login keychain or the given one), creates or reuses an
|
||||
// App Store profile per bundle id (apple.bundleId + apple.signing.extraBundleIds) and installs it for Xcode.
|
||||
// Every write is shown first (--dry shows only that) and asks once before anything is created. Developer ID
|
||||
// certificates need the Account Holder: the API's 403 is explained. Pure planning: cli/lib/signing.ts.
|
||||
import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { buildCsr, csrContent, newSigningKey, spkiOfKey } from '../lib/csr';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import {
|
||||
type ApiCert, type ApiProfile, type AppleSigning, capabilitySpecs, CERT_LIMIT, certificateReq, certSha1, certSpki, type CertType,
|
||||
explainCertError, parseIdentities, pickCertificate, planCapabilities, planProfile, profileDirs, type ProfileType,
|
||||
} from '../lib/signing';
|
||||
import { textTable } from '../lib/table';
|
||||
import { type Asc, ascClient, type J } from './asc';
|
||||
import { describeReq, execute, type Req } from './jsonapi';
|
||||
|
||||
const TAG = 'signing';
|
||||
const USAGE = 'usage: storebound apple signing status | ensure [--dry] [--keychain [path]] [--no-install]';
|
||||
|
||||
export const signingDir = (root: string): string => join(root, '.storebound', 'signing');
|
||||
|
||||
/** SPKIs of the private keys in .storebound/signing (file name = certificate id once created). */
|
||||
function localKeys(root: string): Map<string, string> {
|
||||
const dir = signingDir(root);
|
||||
const out = new Map<string, string>();
|
||||
if (!existsSync(dir)) return out;
|
||||
for (const f of readdirSync(dir).filter(f => f.endsWith('.key'))) {
|
||||
try { out.set(spkiOfKey(readFileSync(join(dir, f), 'utf8')), f); } catch { warn(TAG, `${f}: not a private key, ignored`); }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** SHA-1s of code signing identities in the keychain search list (macOS; empty elsewhere). Read-only. */
|
||||
function keychainIdentities(): Set<string> {
|
||||
if (process.platform !== 'darwin' || !Bun.which('security')) return new Set();
|
||||
const r = Bun.spawnSync(['security', 'find-identity', '-v', '-p', 'codesigning'], { stdout: 'pipe', stderr: 'pipe' });
|
||||
return new Set(parseIdentities(r.stdout.toString()).map(i => i.sha1));
|
||||
}
|
||||
|
||||
export async function findBundleId(c: Asc, identifier: string): Promise<J | null> {
|
||||
const r = await c.asc('GET', `/v1/bundleIds?filter[identifier]=${encodeURIComponent(identifier)}&include=bundleIdCapabilities&limit=200`);
|
||||
const hit = (r.data as J[]).find(b => b.attributes.identifier === identifier) ?? null;
|
||||
if (hit) hit.capabilities = (r.included ?? []).filter((x: J) => x.type === 'bundleIdCapabilities' && (hit.relationships?.bundleIdCapabilities?.data ?? []).some((d: J) => d.id === x.id))
|
||||
.map((x: J) => x.attributes.capabilityType as string);
|
||||
return hit;
|
||||
}
|
||||
|
||||
async function profilesOf(c: Asc, bundleIdId: string, type: ProfileType): Promise<ApiProfile[]> {
|
||||
const ps = await c.all(`/v1/bundleIds/${bundleIdId}/profiles?limit=200`);
|
||||
const out: ApiProfile[] = [];
|
||||
for (const p of ps.filter((p: J) => p.attributes.profileType === type)) {
|
||||
const certs = await c.all(`/v1/profiles/${p.id}/relationships/certificates?limit=200`);
|
||||
out.push({ id: p.id, attributes: p.attributes, certIds: certs.map((x: J) => x.id) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const installedAt = (uuid: string | undefined): string[] => (uuid ? profileDirs(homedir()).map(d => join(d, `${uuid}.mobileprovision`)).filter(existsSync) : []);
|
||||
|
||||
function install(p: ApiProfile): string[] {
|
||||
const content = p.attributes.profileContent;
|
||||
if (!content || !p.attributes.uuid) throw new Error(`profile ${p.attributes.name}: no content to install`);
|
||||
const out: string[] = [];
|
||||
for (const d of profileDirs(homedir())) {
|
||||
mkdirSync(d, { recursive: true });
|
||||
const f = join(d, `${p.attributes.uuid}.mobileprovision`);
|
||||
writeFileSync(f, Buffer.from(content, 'base64'));
|
||||
out.push(f);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function keychainImport(keyFile: string, cerFile: string, keychain: string | null): void {
|
||||
if (process.platform !== 'darwin') throw new Error('--keychain: macOS only (on other systems keep the key in .storebound/signing)');
|
||||
const kc = keychain ? ['-k', keychain] : [];
|
||||
for (const cmd of [['security', 'import', keyFile, ...kc, '-t', 'priv', '-f', 'openssl', '-T', '/usr/bin/codesign', '-T', '/usr/bin/productbuild'], ['security', 'import', cerFile, ...kc, '-t', 'cert']]) {
|
||||
const r = Bun.spawnSync(cmd, { stdout: 'pipe', stderr: 'pipe' });
|
||||
const msg = (r.stdout.toString() + r.stderr.toString()).trim();
|
||||
if (r.exitCode !== 0 && !/already exists/i.test(msg)) throw new Error(`security import failed: ${msg.slice(0, 300)}`);
|
||||
}
|
||||
log(TAG, `key and certificate imported into ${keychain ?? 'the default keychain'}`);
|
||||
}
|
||||
|
||||
export interface SigningState {
|
||||
bundleId: string; teamId: string | null; registered: boolean;
|
||||
capabilities: { present: string[]; missing: string[]; extra: string[] };
|
||||
certificate: { type: CertType; chosen: string | null; why: string; onTeam: number; withKey: number; limit: number | null };
|
||||
profiles: { bundleId: string; name: string | null; uuid: string | null; state: string; installed: boolean; why: string }[];
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const sub = a._[0];
|
||||
if (sub !== 'status' && sub !== 'ensure') throw new Error(USAGE);
|
||||
const bundleId = need(config.apple?.bundleId, 'apple.bundleId');
|
||||
const s: AppleSigning = config.apple?.signing ?? {};
|
||||
const certType: CertType = s.certificateType ?? 'DISTRIBUTION';
|
||||
const profileType: ProfileType = s.profileType ?? 'IOS_APP_STORE';
|
||||
const dry = a.has('dry');
|
||||
const json = a.has('json');
|
||||
const c = await ascClient(root, bundleId, config.apple?.appId);
|
||||
|
||||
// --- read everything first (read-only)
|
||||
const ids = [bundleId, ...(s.extraBundleIds ?? [])];
|
||||
const bundles = new Map<string, J | null>();
|
||||
for (const id of ids) bundles.set(id, await findBundleId(c, id));
|
||||
const main = bundles.get(bundleId);
|
||||
const capPlan = main ? planCapabilities(main.id, main.capabilities ?? [], capabilitySpecs(s)) : { create: [], present: [], extra: [] };
|
||||
const certs: ApiCert[] = await c.all(`/v1/certificates?filter[certificateType]=${certType}&limit=200`);
|
||||
const keys = localKeys(root);
|
||||
const identities = keychainIdentities();
|
||||
const hasKey = (x: ApiCert): boolean => {
|
||||
const content = x.attributes.certificateContent;
|
||||
if (!content) return false;
|
||||
const spki = certSpki(content);
|
||||
return (!!spki && keys.has(spki)) || identities.has(certSha1(content));
|
||||
};
|
||||
const choice = pickCertificate(certs, certType, hasKey);
|
||||
const profiles = new Map<string, { list: ApiProfile[]; plan: ReturnType<typeof planProfile> | null }>();
|
||||
for (const id of ids) {
|
||||
const b = bundles.get(id);
|
||||
if (!b) { profiles.set(id, { list: [], plan: null }); continue; }
|
||||
const list = await profilesOf(c, b.id, profileType);
|
||||
profiles.set(id, { list, plan: choice.cert ? planProfile(list, { bundleId: id, bundleIdId: b.id, certId: choice.cert.id, type: profileType }) : null });
|
||||
}
|
||||
const state: SigningState = {
|
||||
bundleId, teamId: s.teamId ?? main?.attributes?.seedId ?? null, registered: !!main,
|
||||
capabilities: { present: capPlan.present, missing: capabilitySpecs(s).filter(w => !capPlan.present.includes(w.type)).map(w => w.type), extra: capPlan.extra },
|
||||
certificate: { type: certType, chosen: choice.cert?.attributes.name ?? choice.cert?.attributes.displayName ?? null, why: choice.why,
|
||||
onTeam: certs.filter(x => Date.parse(x.attributes.expirationDate ?? '') > Date.now()).length, withKey: choice.usable.length, limit: CERT_LIMIT[certType] ?? null },
|
||||
profiles: ids.map(id => {
|
||||
const p = profiles.get(id)!;
|
||||
if (!bundles.get(id)) return { bundleId: id, name: null, uuid: null, state: 'bundle id not registered', installed: false, why: 'register it first (storebound apple bundle for the app; extensions in Certificates, Identifiers & Profiles)' };
|
||||
const r = p.plan?.reuse;
|
||||
return { bundleId: id, name: r?.attributes.name ?? null, uuid: r?.attributes.uuid ?? null, state: r ? 'ACTIVE' : 'needs a new profile',
|
||||
installed: installedAt(r?.attributes.uuid).length > 0, why: p.plan?.why ?? 'waits for a usable certificate' };
|
||||
}),
|
||||
};
|
||||
|
||||
if (sub === 'status') {
|
||||
if (json) { printJson(state); return; }
|
||||
log(TAG, `${bundleId}: ${main ? `registered, team ${state.teamId ?? '?'}` : 'NOT registered (storebound apple bundle)'}`);
|
||||
log(TAG, `capabilities: ${state.capabilities.present.join(', ') || 'none configured'}${state.capabilities.missing.length ? `; missing ${state.capabilities.missing.join(', ')}` : ''}${state.capabilities.extra.length ? `; also on the bundle id: ${state.capabilities.extra.join(', ')}` : ''}`);
|
||||
log(TAG, `certificate ${certType}: ${choice.why} (${state.certificate.onTeam} valid on the team${state.certificate.limit ? `, limit ${state.certificate.limit}` : ''})`);
|
||||
for (const x of choice.expiring) warn(TAG, `${x.attributes.name ?? x.id} expires ${x.attributes.expirationDate?.slice(0, 10)}: make a new one soon (storebound apple signing ensure)`);
|
||||
console.log(textTable(['bundle id', 'profile', 'state', 'installed', ''], state.profiles.map(p => [p.bundleId, p.name ?? '', p.state, p.installed ? 'yes' : 'no', p.why])));
|
||||
done(TAG, 'status read');
|
||||
return;
|
||||
}
|
||||
|
||||
// --- ensure: plan, show, ask once, then write
|
||||
if (!main) throw new Error(`bundle id ${bundleId} is not registered: storebound apple bundle --dry, then without --dry`);
|
||||
const missingExtra = ids.filter(id => !bundles.get(id));
|
||||
if (missingExtra.length) throw new Error(`not registered: ${missingExtra.join(', ')} (register extension bundle ids in Certificates, Identifiers & Profiles first)`);
|
||||
const needCert = !choice.cert;
|
||||
const plan: string[] = [
|
||||
...capPlan.create.map(r => describeReq(r)),
|
||||
...(needCert ? [describeReq(certificateReq(certType, '<CSR of a new RSA 2048 key>'))] : []),
|
||||
...ids.flatMap(id => {
|
||||
const p = profiles.get(id)!.plan;
|
||||
return !p || p.create ? [`POST /v1/profiles {name=..., profileType="${profileType}"} # ${id}: ${p?.why ?? 'with the new certificate'}`] : [];
|
||||
}),
|
||||
];
|
||||
if (needCert && state.certificate.limit && state.certificate.onTeam >= state.certificate.limit)
|
||||
warn(TAG, `the team already has ${state.certificate.onTeam} valid ${certType} certificates (limit ${state.certificate.limit}): Apple will refuse a new one until one is revoked (owner decision, developer.apple.com > Certificates)`);
|
||||
if (json && dry) { printJson({ ...state, plan }); return; }
|
||||
for (const line of plan) log(TAG, `${dry ? 'would ' : ''}${line}`);
|
||||
if (!plan.length) log(TAG, 'nothing to create on App Store Connect');
|
||||
if (dry) {
|
||||
for (const p of state.profiles) if (p.uuid && !p.installed && !a.has('no-install')) log(TAG, `would install profile ${p.name} (${p.uuid}) for Xcode`);
|
||||
done(TAG, `signing checked (dry run): ${plan.length} write(s)`);
|
||||
return;
|
||||
}
|
||||
if (plan.length && !(await confirm(ctx, `Create ${plan.length} item(s) on the Apple Developer team (${[capPlan.create.length && `${capPlan.create.length} capabilities`, needCert && `a ${certType} certificate`, plan.length - capPlan.create.length - (needCert ? 1 : 0) && 'provisioning profiles'].filter(Boolean).join(', ')})?`))) return;
|
||||
|
||||
await execute(c.asc, capPlan.create, { dry: false, tag: TAG });
|
||||
let cert = choice.cert;
|
||||
if (needCert) {
|
||||
const dir = signingDir(root);
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
const { key } = newSigningKey();
|
||||
const pending = join(dir, `pending-${Date.now()}.key`);
|
||||
writeFileSync(pending, key.export({ type: 'pkcs1', format: 'pem' }).toString(), { mode: 0o600 });
|
||||
chmodSync(pending, 0o600);
|
||||
let created: J;
|
||||
try {
|
||||
const csr = buildCsr(key, { commonName: `storebound ${config.app.name}`.slice(0, 64) });
|
||||
created = (await c.asc('POST', '/v1/certificates', certificateReq(certType, csrContent(csr)).body)).data;
|
||||
} catch (e) {
|
||||
rmSync(pending, { force: true });
|
||||
const why = explainCertError(e, certType);
|
||||
throw new Error(why ? `${(e as Error).message}\n\n${why}` : (e as Error).message);
|
||||
}
|
||||
const keyFile = join(dir, `${created.id}.key`), cerFile = join(dir, `${created.id}.cer`);
|
||||
renameSync(pending, keyFile);
|
||||
writeFileSync(cerFile, Buffer.from(created.attributes.certificateContent, 'base64'), { mode: 0o600 });
|
||||
log(TAG, `certificate ${created.attributes.name ?? created.id} created (expires ${String(created.attributes.expirationDate).slice(0, 10)}); key and certificate in .storebound/signing/ (gitignored, back them up)`);
|
||||
if (a.has('keychain')) keychainImport(keyFile, cerFile, a.get('keychain') === 'true' ? null : a.get('keychain')!);
|
||||
else warn(TAG, 'xcodebuild signs with identities from the keychain: re-run with --keychain to import it there (or import the .key + .cer yourself)');
|
||||
cert = created;
|
||||
}
|
||||
for (const id of ids) {
|
||||
const b = bundles.get(id)!;
|
||||
const list = profiles.get(id)!.list;
|
||||
const p = planProfile(list, { bundleId: id, bundleIdId: b.id, certId: cert!.id, type: profileType });
|
||||
let prof: ApiProfile;
|
||||
if (p.create) {
|
||||
const r = (await c.asc('POST', p.create.path, p.create.body)).data;
|
||||
prof = { id: r.id, attributes: r.attributes };
|
||||
log(TAG, `${id}: profile "${prof.attributes.name}" created (${prof.attributes.uuid})`);
|
||||
} else {
|
||||
prof = p.reuse!;
|
||||
if (!prof.attributes.profileContent) prof = { ...prof, attributes: (await c.asc('GET', `/v1/profiles/${prof.id}`)).data.attributes };
|
||||
log(TAG, `${id}: ${p.why}`);
|
||||
}
|
||||
if (!a.has('no-install')) for (const f of install(prof)) log(TAG, `${id}: installed ${f.replace(homedir(), '~')}`);
|
||||
}
|
||||
if (json) printJson({ ...state, plan, done: true });
|
||||
done(TAG, 'signing ready (storebound apple build --dry shows the ExportOptions.plist it will use)');
|
||||
}
|
||||
|
||||
|
|
@ -5,6 +5,10 @@
|
|||
// storebound apple testflight what-to-test --build N [--version x.y.z] [--locale en-US,tr] [--text "..."] [--dry]
|
||||
// storebound apple testflight info [--dry] Test Information + Beta App Review contact / notes
|
||||
// storebound apple testflight distribute --build N --group a,b [--version x.y.z] [--internal-only] [--submit-review] [--dry] [--yes]
|
||||
// storebound apple testflight wait --build N [--version x.y.z] [--timeout 60m] [--dry] [--json] until processing ends
|
||||
// exit codes: 0 VALID, 1 FAILED / INVALID, 7 timeout; --dry checks once and does not wait
|
||||
// storebound apple testflight expire (--keep N | --older-than D) [--version x.y.z] [--dry] [--yes] [--json]
|
||||
// expires old builds (permanent; asks first); builds attached to an App Store version and processing builds stay
|
||||
// Testers come from a CSV in .storebound/ (gitignored; never commit tester emails): email, first_name, last_name,
|
||||
// groups (";"-separated). Emails are masked in every log line. Adding testers makes Apple email TestFlight invitations
|
||||
// (once the group has a build), so `testers` asks first; `--remove` takes testers out of the managed groups.
|
||||
|
|
@ -16,6 +20,8 @@ import { confirm, need } from '../lib/ctx';
|
|||
import { reviewContact } from '../lib/credentials';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { textTable } from '../lib/table';
|
||||
import { BUILD_WAIT_EXIT, type BuildSeen, expireCandidates, planExpire, validHint, waitDelay, type WaitOutcome, waitOutcome } from '../lib/build-ops';
|
||||
import { parseDuration } from '../lib/release';
|
||||
import {
|
||||
type ApiBuild, betaDescriptions, betaReadiness, betaReviewReq, buildsWithVersion, type Group, groupFromApi, inviteReq, maskEmail,
|
||||
parseTesters, pickBuild, planBetaInfo, planBetaReviewDetail, planDistribute, planGroups, planTesters, planWhatToTest, whatToTestFromListing,
|
||||
|
|
@ -24,7 +30,56 @@ import { type Asc, ascClient, type J } from './asc';
|
|||
import { execute } from './jsonapi';
|
||||
|
||||
const TAG = 'testflight';
|
||||
const USAGE = 'usage: storebound apple testflight status | groups | testers | what-to-test --build N | info | distribute --build N --group <names>';
|
||||
const USAGE = 'usage: storebound apple testflight status | groups | testers | what-to-test --build N | info | distribute --build N --group <names> | wait --build N | expire --keep N | --older-than D';
|
||||
|
||||
/** The state of build `number` (of `marketing` version) right now; found: false while App Store Connect does not list it. */
|
||||
async function seeBuild(c: Asc, appId: string, number: string, marketing?: string): Promise<BuildSeen & { version?: string }> {
|
||||
const q = new URLSearchParams({ 'filter[app]': appId, 'filter[version]': number, 'filter[preReleaseVersion.platform]': 'IOS', include: 'preReleaseVersion,buildBetaDetail', limit: '50' });
|
||||
if (marketing) q.set('filter[preReleaseVersion.version]', marketing);
|
||||
const resp = await c.asc('GET', `/v1/builds?${q}`);
|
||||
const hits = buildsWithVersion(resp).filter(b => b.attributes.version === number && (!marketing || b.marketing === marketing));
|
||||
if (!hits.length) return { found: false };
|
||||
const b = pickBuild(hits, number, marketing);
|
||||
const d = (resp.included ?? []).find((x: J) => x.type === 'buildBetaDetails' && x.id === (b as J).relationships?.buildBetaDetail?.data?.id)?.attributes;
|
||||
return { found: true, processingState: b.attributes.processingState, internal: d?.internalBuildState ?? null, external: d?.externalBuildState ?? null, version: b.marketing };
|
||||
}
|
||||
|
||||
export interface BuildWait { outcome: WaitOutcome; timedOut: boolean; seen: BuildSeen & { version?: string }; waitedSeconds: number }
|
||||
|
||||
/**
|
||||
* Polls build `number` until processing ends (VALID, or FAILED / INVALID) or `timeoutMs` passes; logs each state change.
|
||||
* `once` reads the state a single time. Shared by `testflight wait` and `apple upload` (which waits after the upload).
|
||||
*/
|
||||
export async function waitForBuild(c: Asc, appId: string, number: string, o: { marketing?: string; timeoutMs: number; once?: boolean; tag?: string }): Promise<BuildWait> {
|
||||
const started = Date.now();
|
||||
let delay: number | null = null, last = '';
|
||||
for (;;) {
|
||||
const seen = await seeBuild(c, appId, number, o.marketing);
|
||||
const outcome = waitOutcome(seen);
|
||||
const line = outcome === 'missing' ? 'not listed yet (App Store Connect lists it once processing starts)' : `${seen.processingState}${seen.internal ? `, internal ${seen.internal}` : ''}`;
|
||||
if (line !== last) { log(o.tag ?? TAG, `build ${number}${seen.version ? ` (${seen.version})` : ''}: ${line} [${Math.round((Date.now() - started) / 60_000)} min]`); last = line; }
|
||||
const result = (timedOut: boolean): BuildWait => ({ outcome, timedOut, seen, waitedSeconds: Math.round((Date.now() - started) / 1000) });
|
||||
if (outcome === 'valid' || outcome === 'failed') return result(false);
|
||||
if (o.once) return result(false);
|
||||
delay = waitDelay(delay);
|
||||
if (Date.now() + delay - started > o.timeoutMs) return result(true);
|
||||
await Bun.sleep(delay);
|
||||
}
|
||||
}
|
||||
|
||||
/** The closing line for a finished wait (VALID with the next step, or FAILED / INVALID with what to do). */
|
||||
export function waitMessage(number: string, r: BuildWait): string {
|
||||
return r.outcome === 'valid'
|
||||
? `build ${number} is VALID; ${validHint(r.seen).replace('N', number)}`
|
||||
: `build ${number} is ${r.seen.processingState}: read the email from App Store Connect (missing icons, wrong SDK, invalid signature), fix and upload a new build number`;
|
||||
}
|
||||
|
||||
/** Every page of a GET, with `included` kept (c.all keeps only data). */
|
||||
async function pagesOf(c: Asc, path: string): Promise<J[]> {
|
||||
const out: J[] = [];
|
||||
for (let url: string | null = path; url;) { const page: J = await c.asc('GET', url); out.push(page); url = page.links?.next ?? null; }
|
||||
return out;
|
||||
}
|
||||
|
||||
async function groups(c: Asc, appId: string): Promise<Group[]> {
|
||||
return (await c.all(`/v1/apps/${appId}/betaGroups?limit=200`)).map(groupFromApi);
|
||||
|
|
@ -187,5 +242,35 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
done(TAG, `build ${number}: ${reqs.length ? `added to ${reqs.length} group(s)` : 'already in every group'}`);
|
||||
return;
|
||||
}
|
||||
if (sub === 'wait') {
|
||||
const number = need(a.get('build'), '--build N (the exact build number you uploaded)');
|
||||
const marketing = a.get('version');
|
||||
const r = await waitForBuild(c, appId, number, { marketing, timeoutMs: parseDuration(a.str('timeout', '60m')), once: dry });
|
||||
const code = r.outcome === 'valid' ? BUILD_WAIT_EXIT.valid : r.outcome === 'failed' ? BUILD_WAIT_EXIT.failed : BUILD_WAIT_EXIT.timeout;
|
||||
if (a.has('json')) printJson({ build: number, version: r.seen.version ?? marketing ?? null, outcome: r.timedOut ? 'timeout' : r.outcome, processingState: r.seen.processingState ?? null,
|
||||
internal: r.seen.internal ?? null, external: r.seen.external ?? null, waitedSeconds: r.waitedSeconds });
|
||||
log(TAG, r.outcome === 'valid' || r.outcome === 'failed' ? waitMessage(number, r) : dry ? 'dry run: checked once, not waiting' : `timeout after ${Math.round(r.waitedSeconds / 60)} min; still ${r.outcome} (re-run to keep waiting)`);
|
||||
process.exit(code);
|
||||
}
|
||||
|
||||
if (sub === 'expire') {
|
||||
const keep = a.get('keep') === undefined ? undefined : a.num('keep', 0);
|
||||
const olderThanDays = a.get('older-than') === undefined ? undefined : a.num('older-than', 0);
|
||||
const q = new URLSearchParams({ 'filter[app]': appId, 'filter[expired]': 'false', 'filter[preReleaseVersion.platform]': 'IOS', sort: '-uploadedDate', include: 'preReleaseVersion,appStoreVersion', limit: '200' });
|
||||
if (a.get('version')) q.set('filter[preReleaseVersion.version]', a.get('version')!);
|
||||
const plan = planExpire(expireCandidates(await pagesOf(c, `/v1/builds?${q}`)), { keep, olderThanDays });
|
||||
const row = (b: { build: string; version?: string; uploaded: string }, what: string) => [b.version ?? '', b.build, b.uploaded.slice(0, 10), what];
|
||||
const summary = { expire: plan.expire.map(b => ({ build: b.build, version: b.version ?? null, uploaded: b.uploaded })), keep: plan.keep.length,
|
||||
protected: plan.protected.map(p => ({ build: p.b.build, version: p.b.version ?? null, why: p.why })) };
|
||||
if (a.has('json') && dry) { printJson({ dryRun: true, ...summary }); return; }
|
||||
if (!a.has('json')) console.log(textTable(['version', 'build', 'uploaded', ''], [...plan.expire.map(b => row(b, 'expire')), ...plan.protected.map(p => row(p.b, `keep: ${p.why}`)), ...plan.keep.map(b => row(b, 'keep'))]));
|
||||
if (!plan.reqs.length) { done(TAG, 'nothing to expire'); if (a.has('json')) printJson({ dryRun: dry, ...summary, expired: [] }); return; }
|
||||
if (dry) { await execute(c.asc, plan.reqs, { dry, tag: TAG }); done(TAG, `dry run: ${plan.reqs.length} build(s) would be expired`); return; }
|
||||
if (!(await confirm(ctx, `Expire ${plan.reqs.length} build(s) (${plan.expire.map(b => b.build).join(', ')})? Testers lose them; an expired build cannot be brought back.`))) return;
|
||||
await execute(c.asc, plan.reqs, { dry: false, tag: TAG });
|
||||
if (a.has('json')) printJson({ dryRun: false, ...summary, expired: plan.expire.map(b => b.build) });
|
||||
done(TAG, `${plan.reqs.length} build(s) expired`);
|
||||
return;
|
||||
}
|
||||
throw new Error(`unknown testflight command "${sub}"\n${USAGE}`);
|
||||
}
|
||||
|
|
|
|||
154
cli/apple/upload.ts
Normal file
154
cli/apple/upload.ts
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
// Upload an IPA to App Store Connect and wait until Apple has processed the build.
|
||||
// storebound apple upload [<app.ipa>] [--via api|altool] [--no-wait] [--timeout 60m] [--dry] [--yes] [--json]
|
||||
// Default IPA: the newest in <apple.build.out or build/ios>/export. The bundle id, version and build number come from
|
||||
// the IPA's Info.plist; the upload is refused when that build number is already on App Store Connect for the app
|
||||
// (`apple next-build` / `apple build` pick a free one).
|
||||
// --via api (default): the App Store Connect API build upload (Build Uploads, API 4.1+): POST /v1/buildUploads,
|
||||
// reserve /v1/buildUploadFiles, PUT the parts, commit with the MD5, then poll the upload state. Same API key, no
|
||||
// Xcode needed, works on any OS.
|
||||
// --via altool: `xcrun altool --upload-package` with the API key (Xcode's own uploader; macOS).
|
||||
// Both are listed by Apple (App Store Connect Help > Upload builds); neither is deprecated. Then the build is polled
|
||||
// with `apple testflight wait` (waitForBuild) until processingState is VALID (exit 0), INVALID / FAILED (exit 1) or the
|
||||
// timeout (exit 7).
|
||||
// An upload is a write: --dry shows the plan; a real run asks first (--yes in scripts).
|
||||
import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from 'node:fs';
|
||||
import { basename, join, relative } from 'node:path';
|
||||
import { ascKeyFile } from '../lib/credentials';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { compareBuild, nextBuildNumber, nextPollDelay, parseDuration, WAIT_EXIT } from '../lib/release';
|
||||
import { altoolArgs, buildUploadReqs, ipaInfo, showCmd, UPLOAD_DONE, uploadProblems } from '../lib/xcode';
|
||||
import { BUILD_WAIT_EXIT } from '../lib/build-ops';
|
||||
import { type Asc, ascClient, type J } from './asc';
|
||||
import { waitForBuild, waitMessage } from './testflight';
|
||||
import { describeReq } from './jsonapi';
|
||||
|
||||
const TAG = 'upload';
|
||||
|
||||
function md5File(path: string): string {
|
||||
const h = new Bun.CryptoHasher('md5');
|
||||
const fd = openSync(path, 'r');
|
||||
try {
|
||||
const buf = Buffer.alloc(8 * 1048576);
|
||||
for (let n; (n = readSync(fd, buf, 0, buf.length, null)) > 0;) h.update(buf.subarray(0, n));
|
||||
} finally { closeSync(fd); }
|
||||
return h.digest('hex');
|
||||
}
|
||||
|
||||
function slice(path: string, offset: number, length: number): Buffer {
|
||||
const fd = openSync(path, 'r');
|
||||
try { const b = Buffer.alloc(length); readSync(fd, b, 0, length, offset); return b; } finally { closeSync(fd); }
|
||||
}
|
||||
|
||||
async function apiUpload(c: Asc, appId: string, ipa: string, info: ReturnType<typeof ipaInfo>, deadline: number): Promise<void> {
|
||||
const size = statSync(ipa).size;
|
||||
const reqs = buildUploadReqs(appId, info, basename(ipa), size);
|
||||
const up = (await c.asc('POST', reqs.upload.path, reqs.upload.body)).data;
|
||||
log(TAG, `build upload ${up.id} created`);
|
||||
const file = (await c.asc('POST', reqs.file(up.id).path, reqs.file(up.id).body)).data;
|
||||
const ops = (file.attributes.uploadOperations ?? []) as J[];
|
||||
log(TAG, `uploading ${(size / 1048576).toFixed(1)} MB in ${ops.length} part(s)`);
|
||||
let sent = 0;
|
||||
for (const [i, op] of ops.entries()) {
|
||||
const headers: Record<string, string> = {};
|
||||
for (const h of op.requestHeaders ?? []) headers[h.name] = h.value;
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
const r = await fetch(op.url, { method: op.method, headers, body: new Uint8Array(slice(ipa, op.offset, op.length)) });
|
||||
if (r.ok) break;
|
||||
if (attempt >= 4 || (r.status < 500 && r.status !== 429)) throw new Error(`part ${i + 1}/${ops.length} -> ${r.status}`);
|
||||
await Bun.sleep(2000 * attempt);
|
||||
}
|
||||
sent += op.length;
|
||||
if ((i + 1) % 10 === 0 || i === ops.length - 1) log(TAG, `${i + 1}/${ops.length} parts (${Math.round((sent / size) * 100)}%)`);
|
||||
}
|
||||
const commit = reqs.commit(file.id, md5File(ipa));
|
||||
await c.asc('PATCH', commit.path, commit.body);
|
||||
log(TAG, 'file committed; waiting for App Store Connect to accept the upload');
|
||||
for (let delay: number | null = null; ;) {
|
||||
const u = (await c.asc('GET', `/v1/buildUploads/${up.id}`)).data;
|
||||
const st = u.attributes?.state ?? {};
|
||||
const p = uploadProblems(st);
|
||||
for (const w of p.warnings) warn(TAG, w);
|
||||
if (UPLOAD_DONE.has(st.state)) {
|
||||
if (st.state === 'FAILED') throw new Error(`upload rejected: ${p.errors.join('; ') || 'no reason given'}`);
|
||||
log(TAG, 'upload accepted');
|
||||
return;
|
||||
}
|
||||
if (Date.now() > deadline) throw Object.assign(new Error(`upload still ${st.state ?? 'pending'} at the timeout`), { exit: WAIT_EXIT.timeout });
|
||||
delay = nextPollDelay(delay, { first: 15_000, max: 60_000 });
|
||||
log(TAG, `upload ${st.state ?? 'pending'}, next check in ${Math.round(delay / 1000)} s`);
|
||||
await Bun.sleep(delay);
|
||||
}
|
||||
}
|
||||
|
||||
async function altoolUpload(root: string, ipa: string): Promise<void> {
|
||||
if (process.platform !== 'darwin' || !Bun.which('xcrun')) throw new Error('--via altool needs macOS with Xcode; use --via api elsewhere');
|
||||
const k = ascKeyFile(root);
|
||||
try {
|
||||
const argv = altoolArgs(ipa, k);
|
||||
log(TAG, `$ ${showCmd(argv, k)}`);
|
||||
const r = Bun.spawnSync(argv, { stdout: 'pipe', stderr: 'pipe' });
|
||||
const outText = (r.stdout.toString() + '\n' + r.stderr.toString()).trim();
|
||||
if (r.exitCode !== 0) throw new Error(`altool failed (exit ${r.exitCode}): ${outText.split('\n').filter(l => /error|fail/i.test(l)).slice(0, 8).join('\n') || outText.slice(-800)}`);
|
||||
const id = /"?delivery-uuid"?\s*[:=]\s*"?([0-9a-f-]{36})/i.exec(outText)?.[1];
|
||||
log(TAG, `altool: upload done${id ? ` (delivery ${id})` : ''}`);
|
||||
} finally { k.cleanup(); }
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const bundleId = need(config.apple?.bundleId, 'apple.bundleId');
|
||||
const via = a.str('via', 'api');
|
||||
if (via !== 'api' && via !== 'altool') throw new Error('--via api | altool');
|
||||
let ipa = a._.find(x => x.endsWith('.ipa'));
|
||||
if (!ipa) {
|
||||
const dir = join(resolve(config.apple?.build?.out ?? 'build/ios'), 'export');
|
||||
const found = existsSync(dir) ? readdirSync(dir).filter(f => f.endsWith('.ipa')).map(f => join(dir, f)).sort((x, y) => statSync(y).mtimeMs - statSync(x).mtimeMs) : [];
|
||||
if (!found[0]) throw new Error(`usage: storebound apple upload <app.ipa> (nothing in ${relative(root, dir)}; storebound apple build makes one)`);
|
||||
ipa = found[0];
|
||||
} else ipa = resolve(ipa);
|
||||
const info = ipaInfo(ipa);
|
||||
if (info.bundleId !== bundleId) throw new Error(`${relative(root, ipa)} is ${info.bundleId}, the config says ${bundleId}`);
|
||||
const size = statSync(ipa).size;
|
||||
const dry = a.has('dry');
|
||||
const json = a.has('json');
|
||||
const wait = !a.has('no-wait');
|
||||
const timeout = parseDuration(a.str('timeout', '60m'));
|
||||
|
||||
const c = await ascClient(root, bundleId, config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const builds = await c.all(`/v1/builds?filter[app]=${appId}&limit=200&fields[builds]=version`);
|
||||
const numbers = builds.map(b => String(b.attributes.version));
|
||||
const next = nextBuildNumber(numbers);
|
||||
if (numbers.includes(info.build)) throw new Error(`build ${info.build} is already on App Store Connect: rebuild with --build-number ${next} (storebound apple build)`);
|
||||
if (numbers.length && compareBuild(info.build, next) < 0) warn(TAG, `build ${info.build} is lower than the highest uploaded one (next free: ${next}); Apple accepts it only if this version train has no higher build`);
|
||||
const reqs = buildUploadReqs(appId, info, basename(ipa), size);
|
||||
const plan = via === 'api'
|
||||
? [describeReq(reqs.upload), describeReq(reqs.file('<upload id>')), `PUT the file parts to the upload URLs Apple returns`, describeReq(reqs.commit('<file id>', '<md5>')), 'GET /v1/buildUploads/<id> until COMPLETE']
|
||||
: [showCmd(altoolArgs(ipa, { keyPath: '$ASC_P8', keyId: '$ASC_KEY_ID', issuerId: '$ASC_ISSUER_ID' }), null)];
|
||||
if (wait) plan.push(`GET /v1/builds?filter[version]=${info.build} until processingState is VALID (timeout ${a.str('timeout', '60m')})`);
|
||||
const summary = { ipa: relative(root, ipa), bundleId: info.bundleId, version: info.version, build: info.build, sizeMB: Math.round(size / 104857.6) / 10, via, plan };
|
||||
if (dry) {
|
||||
if (json) { printJson(summary); return; }
|
||||
log(TAG, `${summary.ipa}: ${info.bundleId} ${info.version} (${info.build}), ${summary.sizeMB} MB, build number free`);
|
||||
for (const p of plan) log(TAG, `would ${p}`);
|
||||
done(TAG, 'upload planned (dry run)');
|
||||
return;
|
||||
}
|
||||
if (!(await confirm(ctx, `Upload ${info.bundleId} ${info.version} (${info.build}) to App Store Connect? It shows up in TestFlight once processed.`))) return;
|
||||
const deadline = Date.now() + timeout;
|
||||
if (via === 'api') {
|
||||
try { await apiUpload(c, appId, ipa, info, deadline); } catch (e) { if ((e as { exit?: number }).exit) { warn(TAG, (e as Error).message); process.exit((e as { exit: number }).exit); } throw e; }
|
||||
} else await altoolUpload(root, ipa);
|
||||
if (!wait) { if (json) printJson({ ...summary, uploaded: true }); done(TAG, `build ${info.build} uploaded; storebound apple status shows when it is VALID`); return; }
|
||||
// the same poll as `storebound apple testflight wait`, within what is left of --timeout
|
||||
const r = await waitForBuild(c, appId, info.build, { marketing: info.version, timeoutMs: Math.max(0, deadline - Date.now()), tag: TAG });
|
||||
const state = r.timedOut || (r.outcome !== 'valid' && r.outcome !== 'failed') ? 'TIMEOUT' : r.seen.processingState ?? 'UNKNOWN';
|
||||
if (json) printJson({ ...summary, uploaded: true, processingState: state });
|
||||
if (r.outcome === 'valid') { done(TAG, `${waitMessage(info.build, r)}. Then: apple testflight distribute --build ${info.build} --group <name> --dry`); return; }
|
||||
if (state === 'TIMEOUT') { warn(TAG, `build ${info.build} not processed after ${a.str('timeout', '60m')}; keep waiting with storebound apple testflight wait --build ${info.build} --version ${info.version}`); process.exit(BUILD_WAIT_EXIT.timeout); }
|
||||
warn(TAG, `${waitMessage(info.build, r)} (Apple emails the ITMS-xxxxx reason to the team)`);
|
||||
process.exit(BUILD_WAIT_EXIT.failed);
|
||||
}
|
||||
70
cli/apple/win-back.ts
Normal file
70
cli/apple/win-back.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
// Win-back offers for lapsed subscribers from subscriptions[].subscriptions[].winBack.
|
||||
// storebound apple win-back [--only sub1,sub2] [--dry] [--yes] [--json]
|
||||
// Lists what each subscription has (GET /v1/subscriptions/{id}/winBackOffers) and creates the configured offers that
|
||||
// are missing (by offer id). A win-back offer goes live by itself on its start date (Manage Subscriptions, the
|
||||
// in-app offer sheet, the App Store when promoted), so creating one is the owner's step: dry run first, then a
|
||||
// terminal confirmation; never an MCP tool. The subscription must be approved; reference name, offer id and price
|
||||
// cannot be changed afterwards (App Store Connect Help). Pure parts and sources: cli/lib/offers.ts.
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { type TerritoryPoint, validateWinBack, winBackBody } from '../lib/offers';
|
||||
import { allSubscriptions, applePoints, pickPoint } from '../lib/subscriptions';
|
||||
import { textTable } from '../lib/table';
|
||||
import { pages } from '../prices';
|
||||
import { ascClient, type J } from './asc';
|
||||
import { describeReq, execute, type Req } from './jsonapi';
|
||||
|
||||
const TAG = 'win-back';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const dry = a.has('dry');
|
||||
const only = a.list('only');
|
||||
const subs = allSubscriptions(config.subscriptions).map(x => x.sub).filter(s => s.winBack?.length && (!only.length || only.includes(s.id)));
|
||||
if (!subs.length) throw new Error('no subscriptions with winBack offers (subscriptions[].subscriptions[].winBack in storebound.config.ts)');
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const onStore = new Map<string, J>();
|
||||
for (const g of await c.all(`/v1/apps/${appId}/subscriptionGroups?limit=200`))
|
||||
for (const s of await c.all(`/v1/subscriptionGroups/${g.id}/subscriptions?limit=200`)) onStore.set(s.attributes.productId, s);
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const reqs: Req[] = [];
|
||||
const rows: (string | number)[][] = [];
|
||||
const skipped: { id: string; why: string }[] = [];
|
||||
|
||||
for (const s of subs) {
|
||||
const remote = onStore.get(s.id);
|
||||
if (!remote) { skipped.push({ id: s.id, why: 'not on App Store Connect (storebound apple subscriptions)' }); continue; }
|
||||
const existing = await c.all(`/v1/subscriptions/${remote.id}/winBackOffers?limit=200`);
|
||||
for (const o of existing) rows.push([s.id, o.attributes.offerId, o.attributes.offerMode, o.attributes.startDate ?? '', o.attributes.endDate ?? '', o.attributes.priority ?? '']);
|
||||
const missing = s.winBack!.filter(o => !existing.some((x: J) => x.attributes.offerId === o.id));
|
||||
if (!missing.length) continue;
|
||||
if (remote.attributes.state !== 'APPROVED') { skipped.push({ id: s.id, why: `subscription is ${remote.attributes.state}: win-back offers need an approved subscription` }); continue; }
|
||||
const problems = validateWinBack(s.id, missing, today);
|
||||
if (problems.length) { skipped.push({ id: s.id, why: problems.join('; ') }); continue; }
|
||||
let usa: ReturnType<typeof applePoints> | null = null;
|
||||
for (const o of missing) {
|
||||
let prices: TerritoryPoint[];
|
||||
if (o.type === 'free') prices = (await c.all(`/v1/subscriptions/${remote.id}/prices?include=territory&limit=200`)).map((x: J) => ({ territory: x.relationships?.territory?.data?.id })).filter((x: TerritoryPoint) => !!x.territory);
|
||||
else {
|
||||
usa ??= applePoints(await pages(c, `/v1/subscriptions/${remote.id}/pricePoints?filter[territory]=USA&include=territory&limit=200`));
|
||||
const point = pickPoint(usa, 'USA', o.usd!);
|
||||
const eq = applePoints(await pages(c, `/v1/subscriptionPricePoints/${point.id}/equalizations?include=territory&limit=200`));
|
||||
prices = [{ territory: 'USA', pointId: point.id }, ...eq.filter(x => x.territory !== 'USA').map(x => ({ territory: x.territory, pointId: x.id }))];
|
||||
}
|
||||
reqs.push({ method: 'POST', path: '/v1/winBackOffers', body: winBackBody(remote.id, s.period, o, prices),
|
||||
note: `${s.id}: win-back "${o.id}" ${o.type}${o.usd ? ` USD ${o.usd}` : ''}, from ${o.start}${o.end ? ` to ${o.end}` : ''}, ${prices.length} territories` });
|
||||
}
|
||||
}
|
||||
if (a.has('json')) printJson({ dryRun: dry, existing: rows.map(r => ({ subscription: r[0], offerId: r[1], mode: r[2], start: r[3], end: r[4], priority: r[5] })), create: reqs.map(r => describeReq(r)), skipped });
|
||||
else if (rows.length) console.log(textTable(['subscription', 'offer', 'mode', 'start', 'end', 'priority'], rows));
|
||||
for (const s of skipped) warn(TAG, `${s.id}: ${s.why}`);
|
||||
if (!reqs.length) { done(TAG, 'no win-back offer to create'); return; }
|
||||
if (dry) { await execute(c.asc, reqs, { dry, tag: TAG }); done(TAG, `dry run: ${reqs.length} win-back offer(s) would be created`); return; }
|
||||
if (!(await confirm(ctx, `Create ${reqs.length} win-back offer(s)? Each goes live by itself on its start date; reference name, offer id and price cannot be changed afterwards.`))) return;
|
||||
await execute(c.asc, reqs, { dry: false, tag: TAG });
|
||||
log(TAG, 'the redemption URL of each offer is in App Store Connect (Subscriptions > the subscription > Win-Back Offers)');
|
||||
done(TAG, `${reqs.length} win-back offer(s) created`);
|
||||
}
|
||||
66
cli/aso.ts
Normal file
66
cli/aso.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
// App Store keyword rank check through Apple's public iTunes Search API (no account, no scraping).
|
||||
// storebound aso rank [--storefronts us,de=de-DE] [--keywords "a,b"] [--only-keywords] [--competitors 3] [--limit 200]
|
||||
// [--delay 3500] [--dry] [--json]
|
||||
// Keywords: the keyword field of each storefront's locale in store/appstore.md (us -> the primary locale unless
|
||||
// "us=en-GB"), plus --keywords (--only-keywords: just those). One request per keyword and storefront, at most one
|
||||
// every 3.5 s (Apple allows about 20 a minute); a 403 / 429 stops the run with what was read. Rank = position of the
|
||||
// app (apple.appId, else the bundle id) in the first --limit results, "-" when not there; plus the first competitors
|
||||
// (title, developer, rating). Subtitles are not in the public API and are not shown. Writes
|
||||
// .storebound/aso/<date>.json (and compares with the previous one) unless --dry. Pure parts: cli/lib/aso-rank.ts.
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { Ctx } from './lib/ctx';
|
||||
import { done, log, printJson, warn } from './lib/log';
|
||||
import { competitors, keywordList, MIN_DELAY_MS, parseStorefronts, rankDelta, rankOf, type RankRow, type SearchApp, searchUrl } from './lib/aso-rank';
|
||||
import { appleSections } from './lib/project-files';
|
||||
import { textTable } from './lib/table';
|
||||
|
||||
const TAG = 'aso';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
if (a._[0] !== 'rank') throw new Error('usage: storebound aso rank [--storefronts us,de=de-DE] [--keywords "a,b"] [--dry] [--json]');
|
||||
if (!config.apple) throw new Error('aso rank checks App Store search: the config has no apple section');
|
||||
const primary = config.apple.primaryLocale ?? config.languages.find(l => l.apple)?.apple ?? 'en-US';
|
||||
const listingFile = resolve(config.apple.listing ?? 'store/appstore.md');
|
||||
const listing = existsSync(listingFile) ? appleSections(readFileSync(listingFile, 'utf8')) : new Map<string, Record<string, string | undefined>>();
|
||||
const extra = a.list('keywords');
|
||||
const fronts = parseStorefronts(a.list('storefronts'), primary);
|
||||
const n = a.num('competitors', 3);
|
||||
const limit = a.num('limit', 200);
|
||||
const delay = Math.max(MIN_DELAY_MS, a.num('delay', MIN_DELAY_MS));
|
||||
const app = { appId: config.apple.appId, bundleId: config.apple.bundleId };
|
||||
const plan = fronts.flatMap(f => keywordList(a.has('only-keywords') ? '' : listing.get(f.locale)?.keywords, extra).map(k => ({ ...f, keyword: k })));
|
||||
if (!plan.length) throw new Error(`no keywords: ${listingFile} has no keywords for ${fronts.map(f => f.locale).join(', ')}; pass --keywords`);
|
||||
log(TAG, `${plan.length} quer${plan.length === 1 ? 'y' : 'ies'} (${fronts.map(f => f.storefront).join(', ')}), one every ${delay / 1000}s: about ${Math.ceil(plan.length * delay / 60_000)} min`);
|
||||
if (a.has('dry')) {
|
||||
if (a.has('json')) printJson({ dryRun: true, queries: plan.map(p => ({ storefront: p.storefront, keyword: p.keyword, url: searchUrl(p.keyword, p.storefront, limit) })) });
|
||||
else for (const p of plan) log(TAG, `would GET ${searchUrl(p.keyword, p.storefront, limit)}`);
|
||||
return;
|
||||
}
|
||||
const rows: RankRow[] = [];
|
||||
for (const [i, p] of plan.entries()) {
|
||||
if (i) await Bun.sleep(delay);
|
||||
const r = await fetch(searchUrl(p.keyword, p.storefront, limit), { headers: { Accept: 'application/json' } });
|
||||
if (r.status === 403 || r.status === 429) { warn(TAG, `Search API answered ${r.status} (rate limit): stopped after ${rows.length} of ${plan.length}; try later or with a larger --delay`); break; }
|
||||
if (!r.ok) { warn(TAG, `${p.storefront} "${p.keyword}": HTTP ${r.status}`); continue; }
|
||||
const results = ((await r.json()) as { results?: SearchApp[] }).results ?? [];
|
||||
const row: RankRow = { storefront: p.storefront, locale: p.locale, keyword: p.keyword, rank: rankOf(results, app), results: results.length, competitors: competitors(results, app, n) };
|
||||
rows.push(row);
|
||||
log(TAG, `${i + 1}/${plan.length} ${p.storefront} "${p.keyword}": ${row.rank ?? `not in the first ${results.length}`}`);
|
||||
}
|
||||
const dir = resolve('.storebound/aso');
|
||||
const prevFile = existsSync(dir) ? readdirSync(dir).filter(f => /^\d{4}-\d{2}-\d{2}\.json$/.test(f)).sort().at(-1) : undefined;
|
||||
const prev = prevFile ? (JSON.parse(readFileSync(join(dir, prevFile), 'utf8')) as { rows?: RankRow[] }).rows : undefined;
|
||||
const delta = rankDelta(rows, prev);
|
||||
const date = new Date().toISOString().slice(0, 10);
|
||||
if (a.has('json')) printJson({ date, previous: prevFile ?? null, rows: rows.map(r => ({ ...r, change: delta.get(`${r.storefront}|${r.keyword.toLowerCase()}`) ?? null })) });
|
||||
else console.log(textTable(['store', 'keyword', 'rank', 'change', 'top competitors'], rows.map(r => {
|
||||
const d = delta.get(`${r.storefront}|${r.keyword.toLowerCase()}`);
|
||||
return [r.storefront, r.keyword, r.rank ?? '-', d === null || d === undefined ? '' : d > 0 ? `+${d}` : String(d), r.competitors.map(c => `${c.rank}. ${c.title.slice(0, 28)} (${c.developer.slice(0, 18)})`).join('; ')];
|
||||
})));
|
||||
mkdirSync(dir, { recursive: true });
|
||||
writeFileSync(join(dir, `${date}.json`), JSON.stringify({ date, app: { appId: app.appId ?? null, bundleId: app.bundleId }, rows }, null, 2) + '\n');
|
||||
done(TAG, `${rows.length} rank(s) saved to ${join(dir, `${date}.json`)}${prevFile ? ` (change vs ${prevFile})` : ''}; Search API order is close to App Store search, read it as a trend`);
|
||||
}
|
||||
|
|
@ -5,7 +5,14 @@
|
|||
// localizations, offers, and a per-region price comparison between the stores (same currency, difference over
|
||||
// --threshold percent). Exit 1 when an item is missing or mismatched; price differences between the stores are
|
||||
// information (stores round to their own price tiers). Pure rules: lib/catalog.ts.
|
||||
// storebound catalog pull [--store apple|play] [--write] [--json]
|
||||
// The live titles and descriptions (Play: + benefits) of in-app purchases and subscriptions against the listings in
|
||||
// storebound.config.ts: a proposal diff per product and language. The config (TypeScript) is never rewritten; --write
|
||||
// saves the proposal as .storebound/pull/catalog.json for you or your agent to merge.
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
import { appleCurrent, pages, playProduct } from './prices';
|
||||
import { catalogProposal, type RemoteCatalog } from './lib/listing-pull';
|
||||
import { ascClient, type J } from './apple/asc';
|
||||
import { type CatalogRow, catalogDiff, fromApplePeriod, fromAppleType, regionOf, type StoreItem, wantedCatalog } from './lib/catalog';
|
||||
import type { Ctx } from './lib/ctx';
|
||||
|
|
@ -83,10 +90,67 @@ async function playItems(ctx: Ctx): Promise<StoreItem[]> {
|
|||
return out;
|
||||
}
|
||||
|
||||
async function appleTexts(ctx: Ctx): Promise<RemoteCatalog> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const c = await ascClient(root, config.apple!.bundleId, config.apple?.appId);
|
||||
const appId = await c.app();
|
||||
const out: RemoteCatalog = {};
|
||||
for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`))
|
||||
out[p.attributes.productId] = Object.fromEntries((await c.all(`/v2/inAppPurchases/${p.id}/inAppPurchaseLocalizations?limit=50`))
|
||||
.map((l: J) => [l.attributes.locale, { title: l.attributes.name ?? '', description: l.attributes.description ?? '' }]));
|
||||
for (const g of await c.all(`/v1/apps/${appId}/subscriptionGroups?limit=200`))
|
||||
for (const s of await c.all(`/v1/subscriptionGroups/${g.id}/subscriptions?limit=200`))
|
||||
out[s.attributes.productId] = Object.fromEntries((await c.all(`/v1/subscriptions/${s.id}/subscriptionLocalizations?limit=200`))
|
||||
.map((l: J) => [l.attributes.locale, { title: l.attributes.name ?? '', description: l.attributes.description ?? '' }]));
|
||||
log(TAG, `apple: texts of ${Object.keys(out).length} product(s)`);
|
||||
return out;
|
||||
}
|
||||
|
||||
async function playTexts(ctx: Ctx): Promise<RemoteCatalog> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const play = await playClient(root, config.play!.packageName);
|
||||
const out: RemoteCatalog = {};
|
||||
for (const { productId } of await listOneTimeProducts(play)) {
|
||||
const p = await playProduct(play, productId);
|
||||
out[productId] = Object.fromEntries(((p?.listings as { languageCode: string; title?: string; description?: string }[] | undefined) ?? []).map(l => [l.languageCode, { title: l.title ?? '', description: l.description ?? '' }]));
|
||||
}
|
||||
let page = '';
|
||||
do {
|
||||
const r = await play.call<{ subscriptions?: J[]; nextPageToken?: string }>('GET', `${play.API}/subscriptions?pageSize=100${page ? '&pageToken=' + page : ''}`);
|
||||
for (const s of r.subscriptions ?? []) out[s.productId] = Object.fromEntries((s.listings ?? []).map((l: J) => [l.languageCode, { title: l.title ?? '', description: l.description ?? '', ...(l.benefits?.length ? { benefits: l.benefits } : {}) }]));
|
||||
page = r.nextPageToken ?? '';
|
||||
} while (page);
|
||||
log(TAG, `play: texts of ${Object.keys(out).length} product(s)`);
|
||||
return out;
|
||||
}
|
||||
|
||||
async function pull(ctx: Ctx): Promise<void> {
|
||||
const { config, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const store = a.get('store');
|
||||
if (store && store !== 'apple' && store !== 'play') throw new Error('--store apple | play');
|
||||
const apple = (!store || store === 'apple') && config.apple ? await appleTexts(ctx) : undefined;
|
||||
const play = (!store || store === 'play') && config.play ? await playTexts(ctx) : undefined;
|
||||
const p = catalogProposal(config, { apple, play });
|
||||
const file = resolve('.storebound/pull/catalog.json');
|
||||
if (a.has('json')) printJson({ file, write: a.has('write') && !a.has('dry'), ...p });
|
||||
else {
|
||||
if (p.changes.length) console.log(textTable(['product', 'lang', 'store', 'field', 'config', 'store text'], p.changes.map(c => [c.id, c.lang, c.store, c.field, (c.from ?? '(missing)').slice(0, 40), c.to.slice(0, 40)])));
|
||||
if (p.unknown.length) log(TAG, `on the store but not in the config: ${p.unknown.join(', ')}`);
|
||||
if (p.unmapped.length) log(TAG, `store languages with no entry in languages: ${p.unmapped.join(', ')}`);
|
||||
}
|
||||
if (!p.changes.length) { done(TAG, 'the config listings match the stores'); return; }
|
||||
if (!a.has('write') || a.has('dry')) { done(TAG, `${p.changes.length} difference(s); proposal not written (add --write for ${file})`); return; }
|
||||
mkdirSync(dirname(file), { recursive: true });
|
||||
writeFileSync(file, JSON.stringify({ note: 'storebound catalog pull: store texts that differ from storebound.config.ts. Merge by hand (or with your agent) into products[].listings / subscriptions[].subscriptions[].listings.', listings: p.listings, changes: p.changes }, null, 2) + '\n');
|
||||
done(TAG, `proposal written: ${file} (${p.changes.length} difference(s)); storebound.config.ts is unchanged`);
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
if (a._[0] !== 'diff') throw new Error('usage: storebound catalog diff [--store apple|play] [--threshold 10] [--json]');
|
||||
if (a._[0] === 'pull') return pull(ctx);
|
||||
if (a._[0] !== 'diff') throw new Error('usage: storebound catalog diff [--store apple|play] [--threshold 10] [--json] | pull [--store apple|play] [--write] [--json]');
|
||||
const store = a.get('store');
|
||||
if (store && store !== 'apple' && store !== 'play') throw new Error('--store apple | play');
|
||||
const want = wantedCatalog(config);
|
||||
|
|
|
|||
46
cli/index.ts
46
cli/index.ts
|
|
@ -18,7 +18,12 @@ const PLAIN: Record<string, [() => Promise<Plain>, string]> = {
|
|||
'apps': [() => import('./apps'), 'list (every app the store keys can see: App Store Connect team, Play developer accounts; --icons) | check (key works / permission missing / revoked, with the fix); --store apple|play, --json; read-only'],
|
||||
'desktop': [() => import('./desktop'), 'open the storebound desktop app (in an app folder: add or select it there); not installed: the download for this system, --download saves it to ~/Downloads after checking its signature (never installs)'],
|
||||
'doctor': [() => import('./doctor'), 'local tools for screenshots, previews, icons and captures (ffmpeg, Chrome, playwright, Xcode, adb, git) and how to install what is missing; --json'],
|
||||
'scan': [() => import('./scan'), 'offline, read-only rejection-risk scan of the project itself (stack, SDKs, Info.plist, manifest, listings) with guideline, evidence file:line, fix and skill, plus the Data safety / App Privacy / ATT / privacy manifest proposal; --write puts the detected answers into the config; --json; exit 1 on blockers'],
|
||||
'api': [() => import('./api'), 'every App Store Connect / Google Play API operation: list | coverage | apple|play <operationId|METHOD path> [--param k=v] [--body f.json] [--all-pages] (GET runs; writes dry unless --yes in a terminal; owner-only ones need the id typed)'],
|
||||
'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios <path>)'],
|
||||
'ws': [() => import('./workspace'), 'many apps and studios (storebound.workspace.json): init | list | status (apps x stores, parallel) | check | validate | run <command> --apps a,b|--all (writes dry unless --apply) | apps import --account <profile> | desktop export|import'],
|
||||
'release': [() => import('./release'), 'status [--app a,b] [--versions]: both stores on one train per version (build > testing > review > live > rollout %) | plan <version>: what is left on each store, in fix order; read-only, --json'],
|
||||
'ads': [() => import('./ads'), 'scan --ios <path>: AdAttributionKit / SKAdNetwork checks of Info.plist (network ids, postback copy endpoints, attribution windows, cooldown) and sources; --json'],
|
||||
};
|
||||
const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
|
||||
'inspect': [() => import('./inspect'), 'offline summary of the config (name, store ids, languages, products, subscriptions); --json'],
|
||||
|
|
@ -26,20 +31,26 @@ const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
|
|||
'validate': [() => import('./validate'), 'read-only store readiness report with ordered blockers (--apple / --play), plus local renders checks (--no-local skips); exit 1 on blockers'],
|
||||
'analytics': [() => import('./analytics'), 'setup (App Store report request) | snapshot (impressions, page views, installs, conversion -> .storebound/analytics) | compare (vs listing changes in git)'],
|
||||
'health': [() => import('./health'), 'crash / ANR vitals (Play) and diagnostics (App Store), read-only; --weekly writes a markdown report; exit 1 over a threshold'],
|
||||
'catalog': [() => import('./catalog'), 'diff: cross-store parity of products + subscriptions (missing / extra / mismatched, prices per region, offers); read-only, exit 1 on mismatches'],
|
||||
'catalog': [() => import('./catalog'), 'diff: cross-store parity of products + subscriptions (missing / extra / mismatched, prices per region, offers); read-only, exit 1 on mismatches | pull [--write]: store texts of IAPs + subscriptions as a config proposal'],
|
||||
'reports': [() => import('./reports'), 'apple-sales | apple-finance --month | play-earnings --month | play-sales --month: download to .storebound/reports/, summary table + CSV; read-only'],
|
||||
'triage': [() => import('./triage'), 'TestFlight crash / screenshot feedback and Play error reports grouped by signature, device, OS version, build; read-only, --json'],
|
||||
'aso': [() => import('./aso'), 'rank [--storefronts us,de] [--keywords a,b]: App Store rank per keyword and storefront + competitors from the public iTunes Search API (rate limited) -> .storebound/aso/'],
|
||||
'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)'],
|
||||
'whats-new': [() => import('./whats-new'), 'draft user-facing release notes from git log into the listing files (--since <tag>)'],
|
||||
'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'],
|
||||
'play products': [() => import('./play/products'), 'one-time products: create / update, regional prices, activate'],
|
||||
'play subscriptions': [() => import('./play/subscriptions'), 'auto-renewable subscriptions: listings, base plan, regional prices, intro offer, activate (--csv prices sheet; asks first)'],
|
||||
'play listing': [() => import('./play/listing'), 'app details + title / short / full description per language'],
|
||||
'play listing': [() => import('./play/listing'), 'app details + title / short / full description per language; pull [--write]: live listings back into the listing file (diff first)'],
|
||||
'play images': [() => import('./play/images'), 'icon, feature graphic, phone / 7" / 10" screenshots per language; --variant <id>'],
|
||||
'play data-safety': [() => import('./play/data-safety'), 'Data safety form (CSV import through the API)'],
|
||||
'play release': [() => import('./play/release'), 'upload an AAB and put it on tracks with release notes'],
|
||||
'play build': [() => import('./play/build'), 'gradle bundleRelease (Flutter: flutter build appbundle) with the next free versionCode and the upload key from env / .storebound; --dry'],
|
||||
'play upload': [() => import('./play/upload'), 'upload an AAB to a testing track (--track internal|alpha|beta), versionCode checked first; --dry read-only, asks first'],
|
||||
'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 share': [() => import('./play/share'), 'internal app sharing: upload an AAB / APK, print the share link (asks first; --dry)'],
|
||||
|
|
@ -48,18 +59,28 @@ const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
|
|||
'apple iap': [() => import('./apple/iap'), 'in-app purchases, localizations, price schedules, availability'],
|
||||
'apple subscriptions': [() => import('./apple/subscriptions'), 'subscription groups, subscriptions, localizations, prices (equalized + overrides + --csv), intro offers, availability, review screenshot (asks first)'],
|
||||
'apple iap-review': [() => import('./apple/iap-review'), 'IAP review screenshots + product states'],
|
||||
'apple listing': [() => import('./apple/listing'), 'version, build, name / subtitle / description / keywords per locale'],
|
||||
'apple iap-submit': [() => import('./apple/iap-submit'), 'IAP + subscription versions into a review submission (first of a type: --with-version), then submit (asks first; --no-submit keeps a draft)'],
|
||||
'apple offer-codes': [() => import('./apple/offer-codes'), 'offer codes for one-time purchases (campaigns; custom and one-time-use codes with --codes, asks first)'],
|
||||
'apple win-back': [() => import('./apple/win-back'), 'win-back offers for lapsed subscribers (asks first: they go live on their start date)'],
|
||||
'apple promoted': [() => import('./apple/promoted'), 'promoted in-app purchases on the product page: create, order, --enable (asks first)'],
|
||||
'apple preorder': [() => import('./apple/preorder'), 'status | enable --release-date | end: App Store pre-orders per territory (asks first)'],
|
||||
'apple cpp': [() => import('./apple/cpp'), 'custom product pages: list | create | upload --name | submit --name | visible --name (submit / visible ask first)'],
|
||||
'apple events': [() => import('./apple/events'), 'in-app events: list | create | upload --name | submit --name (submit asks first)'],
|
||||
'apple listing': [() => import('./apple/listing'), 'version, build, name / subtitle / description / keywords per locale; pull [--write]: live texts back into the listing file (diff first)'],
|
||||
'apple screenshots': [() => import('./apple/screenshots'), '6.9" + 6.5" (+ 13" iPad) screenshots per locale; --variant <id>'],
|
||||
'apple appinfo': [() => import('./apple/appinfo'), 'categories, age rating, content rights, Free price, territories'],
|
||||
'apple review-details': [() => import('./apple/review-details'), 'App Review contact, demo account (from .storebound/, masked) + notes'],
|
||||
'apple status': [() => import('./apple/status'), 'versions, builds, IAPs, review submissions (--wait-review, --cancel-submission <id>)'],
|
||||
'apple previews': [() => import('./apple/previews'), 'app preview videos per locale (MD5-idempotent, poster frame time code); --dry'],
|
||||
'apple release': [() => import('./apple/release'), 'phased release on|pause|resume|complete, --manual-release (asks first)'],
|
||||
'apple signing': [() => import('./apple/signing'), 'status | ensure: bundle id capabilities, distribution certificate (key kept in .storebound/signing), App Store profiles installed for Xcode; --dry, asks first'],
|
||||
'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 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 encryption': [() => import('./apple/encryption'), 'export compliance answer for builds, from the config'],
|
||||
'apple ppo': [() => import('./apple/ppo'), 'Product Page Optimization: status | create --variant b | upload --variant b | start | stop (asks first)'],
|
||||
'apple testflight': [() => import('./apple/testflight'), 'TestFlight: status | groups | testers (CSV in .storebound/) | what-to-test --build N | info | distribute --build N --group g [--submit-review]'],
|
||||
'apple testflight': [() => import('./apple/testflight'), 'TestFlight: status | groups | testers (CSV in .storebound/) | what-to-test --build N | info | distribute --build N --group g [--submit-review] | wait --build N | expire --keep N|--older-than D (asks)'],
|
||||
'icons': [() => import('./icons'), 'App Store / Play / web / adaptive / legacy launcher icons from one artwork'],
|
||||
'shots capture': [() => import('./shots/capture'), 'raw frames: --source web (playwright) | ios-sim (simctl) | android-emu (adb) | folder; --dry'],
|
||||
'shots fonts': [() => import('./shots/fonts'), 'download font subsets for the copy (CJK / Arabic / Cyrillic ...)'],
|
||||
|
|
@ -79,8 +100,9 @@ usage: storebound <command> [options]
|
|||
${Object.entries(PLAIN).map(([k, [, d]]) => ` ${k.padEnd(25)} ${d}`).join('\n')}
|
||||
${Object.entries(COMMANDS).map(([k, [, d]]) => ` ${k.padEnd(25)} ${d}`).join('\n')}
|
||||
|
||||
common options: --config <path> --dry (no writes) --only <ids> --yes (skip confirmations)
|
||||
credentials: PLAY_SERVICE_ACCOUNT, ASC_KEY_ID, ASC_ISSUER_ID, ASC_P8, REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD (env or .storebound/credentials.json)
|
||||
common options: --config <path> --dry (no writes) --only <ids> --yes (skip confirmations) --account <profile> (credential profile)
|
||||
credentials: PLAY_SERVICE_ACCOUNT, ASC_KEY_ID, ASC_ISSUER_ID, ASC_P8, ANDROID_KEYSTORE(_PASSWORD) / ANDROID_KEY_ALIAS / ANDROID_KEY_PASSWORD, REVIEW_DEMO_USER / REVIEW_DEMO_PASSWORD (env or .storebound/credentials.json);
|
||||
profiles for many accounts: ~/.storebound/credentials/<profile>.json (same names), picked with --account <profile>
|
||||
docs: README.md and the skills/ folder of the toolchain`);
|
||||
}
|
||||
|
||||
|
|
@ -88,6 +110,16 @@ async function main(): Promise<void> {
|
|||
// tools (adb, emulator, ffmpeg…) are also looked up where they usually live, for apps started without a shell PATH
|
||||
process.env.PATH = toolPath(process.env);
|
||||
const argv = process.argv.slice(2);
|
||||
// --account <profile>: the credential profile for this run (ws apps import reads its own --account)
|
||||
if (argv[0] !== 'ws') {
|
||||
const i = argv.findIndex(x => x === '--account' || x.startsWith('--account='));
|
||||
if (i >= 0) {
|
||||
const name = argv[i]!.includes('=') ? argv[i]!.slice(10) : argv[i + 1];
|
||||
if (!name || name.startsWith('--')) throw new Error('--account <credential profile>');
|
||||
process.env.STOREBOUND_PROFILE = name;
|
||||
argv.splice(i, argv[i]!.includes('=') ? 1 : 2);
|
||||
}
|
||||
}
|
||||
const [a, b] = argv;
|
||||
if (!a || a === 'help' || a === '--help' || a === '-h') return help();
|
||||
if (a === 'version' || a === '--version') return console.log((await import('../package.json')).version);
|
||||
|
|
|
|||
172
cli/lib/adattribution.ts
Normal file
172
cli/lib/adattribution.ts
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
// AdAttributionKit / SKAdNetwork checks of an iOS app's Info.plist and sources, as pure rules. The command
|
||||
// (cli/ads.ts scan) finds the files, parses them (cli/lib/plist.ts) and prints the findings. Text checks only.
|
||||
// Sources (Apple developer documentation, checked October 2026):
|
||||
// https://developer.apple.com/documentation/adattributionkit
|
||||
// Publisher app: "add the ad network IDs" under `AdNetworkIdentifiers` (array of strings); "Lowercase the ad network ID
|
||||
// string; otherwise, the system doesn't recognize it as a valid network."
|
||||
// https://developer.apple.com/documentation/adattributionkit/configuring-a-publisher-app
|
||||
// https://developer.apple.com/documentation/bundleresources/information-property-list/adnetworkidentifiers
|
||||
// SKAdNetwork: `SKAdNetworkItems`, one dictionary with `SKAdNetworkIdentifier` per network; "Ad network IDs are
|
||||
// case-sensitive and are in lowercase." `.adattributionkit` and `.skadnetwork` ids work with both frameworks.
|
||||
// https://developer.apple.com/documentation/bundleresources/information-property-list/skadnetworkitems
|
||||
// https://developer.apple.com/documentation/adattributionkit/adattributionkit-skadnetwork-interoperability
|
||||
// Advertised app: copies of winning postbacks with `AttributionCopyEndpoint` (Xcode shows it as "AdAttributionKit -
|
||||
// Postback Copy URL"; Apple's property list reference lists the key at the top level, Xcode's editor files it under
|
||||
// an `AdAttributionKit` dictionary: both are read here), "a valid URL in the format of https://example.com"; the
|
||||
// system uses the registrable domain and posts to https://<domain>/.well-known/appattribution/report-attribution/.
|
||||
// Re-engagement copies: `EligibleForAdAttributionKitReengagementPostbackCopies` (Boolean YES). The app has to call
|
||||
// updateConversionValue at least once to start a postback's conversion window.
|
||||
// https://developer.apple.com/documentation/adattributionkit/configuring-an-advertised-app
|
||||
// https://developer.apple.com/documentation/bundleresources/information-property-list/attributioncopyendpoint
|
||||
// SKAdNetwork postback copies and Private Click Measurement: `NSAdvertisingAttributionReportEndpoint`.
|
||||
// https://developer.apple.com/documentation/bundleresources/information-property-list/nsadvertisingattributionreportendpoint
|
||||
// Attribution rules: `AdAttributionKitConfigurations` > `AttributionWindows` > `global` | <ad network id> > `install` >
|
||||
// `click` (1-30 days) / `view` (1-7 days) / `ignoreInteractionType` (view | click; ad network entries only);
|
||||
// `AttributionCooldown` > `install-cooldown-hours` / `re-engagement-cooldown-hours` (0-720).
|
||||
// https://developer.apple.com/documentation/adattributionkit/configuring-attribution-rules-for-your-app
|
||||
// AdAttributionKit needs no App Tracking Transparency prompt.
|
||||
import type { PlistValue } from './plist';
|
||||
|
||||
export type AakLevel = 'blocker' | 'warn' | 'ok' | 'info';
|
||||
export interface AakFinding { level: AakLevel; code: string; msg: string }
|
||||
|
||||
type Dict = { [k: string]: PlistValue };
|
||||
const isDict = (v: PlistValue | undefined): v is Dict => !!v && typeof v === 'object' && !Array.isArray(v) && !Buffer.isBuffer(v);
|
||||
const ID_RE = /^[a-z0-9]+\.(skadnetwork|adattributionkit)$/;
|
||||
|
||||
export interface SourceSignals {
|
||||
/** `import AdAttributionKit` (or the framework linked). */
|
||||
aakImport: boolean;
|
||||
/** updateConversionValue / updatePostbackConversionValue calls (app code or an attribution SDK). */
|
||||
conversionUpdates: boolean;
|
||||
/** Ad SDKs found (Podfile.lock, Package.resolved, frameworks): these show ads, so the app is a publisher. */
|
||||
adSdks: string[];
|
||||
/** Mobile measurement SDKs that update conversion values for you (AppsFlyer, Adjust, Branch, Singular, Kochava). */
|
||||
mmpSdks: string[];
|
||||
}
|
||||
|
||||
export const AD_SDKS: [RegExp, string][] = [
|
||||
[/Google-Mobile-Ads-SDK|GoogleMobileAds|swift-package-manager-google-mobile-ads/i, 'Google Mobile Ads (AdMob)'], [/AppLovinSDK|applovin-ios-sdk/i, 'AppLovin MAX'],
|
||||
[/IronSourceSDK|IronSource|LevelPlay/i, 'Unity LevelPlay / ironSource'], [/UnityAds/i, 'Unity Ads'], [/FBAudienceNetwork/i, 'Meta Audience Network'],
|
||||
[/Vungle|LiftoffMonetize/i, 'Liftoff Monetize'], [/InMobiSDK/i, 'InMobi'], [/MintegralAdSDK/i, 'Mintegral'], [/Pangle|Ads-Global|PAGAdSDK/i, 'Pangle'], [/ChartboostSDK/i, 'Chartboost'],
|
||||
];
|
||||
export const MMP_SDKS: [RegExp, string][] = [[/AppsFlyer/i, 'AppsFlyer'], [/\bAdjust(Sdk|Signature)?\b/i, 'Adjust'], [/\bBranch\b|BranchSDK/i, 'Branch'], [/Singular/i, 'Singular'], [/KochavaNetworking|KochavaTracker/i, 'Kochava']];
|
||||
|
||||
/** Ad / MMP SDK names and AdAttributionKit signals in dependency lock files and sources. Pure. */
|
||||
export function sourceSignals(files: { path: string; text: string }[]): SourceSignals {
|
||||
const deps = files.filter(f => /(Podfile\.lock|Package\.resolved|Cartfile\.resolved|project\.pbxproj)$/.test(f.path)).map(f => f.text).join('\n');
|
||||
const code = files.filter(f => /\.(swift|m|mm)$/.test(f.path)).map(f => f.text).join('\n');
|
||||
return {
|
||||
aakImport: /^\s*import\s+AdAttributionKit\b|@import\s+AdAttributionKit|AdAttributionKit\.framework/m.test(code + deps),
|
||||
conversionUpdates: /\bupdateConversionValue\s*\(|\bupdatePostbackConversionValue\s*\(/.test(code),
|
||||
adSdks: AD_SDKS.filter(([re]) => re.test(deps)).map(([, n]) => n),
|
||||
mmpSdks: MMP_SDKS.filter(([re]) => re.test(deps)).map(([, n]) => n),
|
||||
};
|
||||
}
|
||||
|
||||
function checkUrl(v: PlistValue | undefined, key: string, f: AakFinding[]): string | null {
|
||||
if (v === undefined) return null;
|
||||
if (typeof v !== 'string' || !/^https:\/\/[^\s/]+(\/.*)?$/i.test(v.trim())) { f.push({ level: 'blocker', code: 'endpoint-url', msg: `${key}: "${String(v)}" is not an https URL like https://example.com` }); return null; }
|
||||
const host = new URL(v.trim()).hostname;
|
||||
if (new URL(v.trim()).pathname.replace(/\/$/, '')) f.push({ level: 'warn', code: 'endpoint-path', msg: `${key}: the path is ignored; the system only uses the domain (${host})` });
|
||||
return host;
|
||||
}
|
||||
|
||||
/** Registrable-ish domain (last two labels; good enough to compare two endpoints of one app). */
|
||||
const domainOf = (host: string): string => host.split('.').slice(-2).join('.');
|
||||
|
||||
/** Every finding for one Info.plist (+ the source signals of the project). Pure. */
|
||||
export function evaluateAdAttribution(plist: Dict, s: SourceSignals): AakFinding[] {
|
||||
const f: AakFinding[] = [];
|
||||
// ---- publisher: ad network ids ----
|
||||
const skItems = plist.SKAdNetworkItems;
|
||||
const skIds: string[] = [];
|
||||
if (skItems !== undefined) {
|
||||
if (!Array.isArray(skItems)) f.push({ level: 'blocker', code: 'skadnetwork-type', msg: 'SKAdNetworkItems must be an array of dictionaries with SKAdNetworkIdentifier' });
|
||||
else for (const [i, it] of skItems.entries()) {
|
||||
const id = isDict(it) ? it.SKAdNetworkIdentifier : undefined;
|
||||
if (typeof id !== 'string') { f.push({ level: 'blocker', code: 'skadnetwork-entry', msg: `SKAdNetworkItems[${i}]: no SKAdNetworkIdentifier string` }); continue; }
|
||||
skIds.push(id);
|
||||
}
|
||||
}
|
||||
const aak = plist.AdNetworkIdentifiers;
|
||||
const aakIds: string[] = [];
|
||||
if (aak !== undefined) {
|
||||
if (!Array.isArray(aak) || !aak.every(x => typeof x === 'string')) f.push({ level: 'blocker', code: 'aak-ids-type', msg: 'AdNetworkIdentifiers must be an array of strings' });
|
||||
else aakIds.push(...(aak as string[]));
|
||||
}
|
||||
for (const [list, name] of [[skIds, 'SKAdNetworkItems'], [aakIds, 'AdNetworkIdentifiers']] as const) {
|
||||
const upper = list.filter(id => id !== id.toLowerCase());
|
||||
if (upper.length) f.push({ level: 'blocker', code: 'id-case', msg: `${name}: ${upper.length} id(s) with capital letters (${upper.slice(0, 3).join(', ')}): the system ignores them; ad network ids are lowercase` });
|
||||
const odd = list.filter(id => id === id.toLowerCase() && !ID_RE.test(id));
|
||||
if (odd.length) f.push({ level: 'warn', code: 'id-format', msg: `${name}: ${odd.slice(0, 3).join(', ')} do not look like ad network ids (<id>.skadnetwork / <id>.adattributionkit)` });
|
||||
const dup = list.filter((id, i) => list.indexOf(id) !== i);
|
||||
if (dup.length) f.push({ level: 'info', code: 'id-duplicate', msg: `${name}: listed twice: ${[...new Set(dup)].slice(0, 3).join(', ')}` });
|
||||
}
|
||||
if (s.adSdks.length && !skIds.length && !aakIds.length)
|
||||
f.push({ level: 'blocker', code: 'no-network-ids', msg: `ad SDKs (${s.adSdks.join(', ')}) but no SKAdNetworkItems / AdNetworkIdentifiers: installs from those ads cannot be attributed; add each network's ids from its list` });
|
||||
if (skIds.length && !aakIds.length)
|
||||
f.push({ level: 'warn', code: 'aak-ids-missing', msg: `SKAdNetworkItems has ${skIds.length} id(s) but there is no AdNetworkIdentifiers: impressions that networks sign with AdAttributionKit are only eligible for networks in AdNetworkIdentifiers (Configuring a publisher app); the same ids work for both` });
|
||||
else if (aakIds.length && skIds.length) {
|
||||
const onlySk = skIds.filter(x => !aakIds.includes(x));
|
||||
if (onlySk.length) f.push({ level: 'info', code: 'aak-ids-partial', msg: `${onlySk.length} id(s) only in SKAdNetworkItems (${onlySk.slice(0, 3).join(', ')}${onlySk.length > 3 ? ', ...' : ''}): add them to AdNetworkIdentifiers too if those networks use AdAttributionKit` });
|
||||
}
|
||||
if (skIds.length || aakIds.length) f.push({ level: 'ok', code: 'network-ids', msg: `${new Set([...skIds, ...aakIds]).size} ad network id(s) (SKAdNetworkItems ${skIds.length}, AdNetworkIdentifiers ${aakIds.length})` });
|
||||
|
||||
// ---- advertised app: postback copies ----
|
||||
const group = isDict(plist.AdAttributionKit) ? plist.AdAttributionKit : undefined;
|
||||
const copyRaw = group?.AttributionCopyEndpoint ?? plist.AttributionCopyEndpoint;
|
||||
const reRaw = group?.EligibleForAdAttributionKitReengagementPostbackCopies ?? plist.EligibleForAdAttributionKitReengagementPostbackCopies;
|
||||
const copyHost = checkUrl(copyRaw, 'AttributionCopyEndpoint', f);
|
||||
if (copyHost) f.push({ level: 'ok', code: 'copy-endpoint', msg: `AdAttributionKit postback copies go to https://${domainOf(copyHost)}/.well-known/appattribution/report-attribution/ (needs a valid TLS certificate and to accept HTTPS POST)` });
|
||||
if (reRaw !== undefined && typeof reRaw !== 'boolean') f.push({ level: 'blocker', code: 'reengagement-type', msg: 'EligibleForAdAttributionKitReengagementPostbackCopies must be a Boolean (YES)' });
|
||||
if (reRaw === true && !copyHost) f.push({ level: 'warn', code: 'reengagement-without-endpoint', msg: 'EligibleForAdAttributionKitReengagementPostbackCopies is on but there is no AttributionCopyEndpoint: no copy can be sent' });
|
||||
const skHost = checkUrl(plist.NSAdvertisingAttributionReportEndpoint, 'NSAdvertisingAttributionReportEndpoint', f);
|
||||
if (skHost) f.push({ level: 'ok', code: 'skan-endpoint', msg: `SKAdNetwork postback copies (and Private Click Measurement) go to https://${domainOf(skHost)}/.well-known/...` });
|
||||
if (copyHost && skHost && domainOf(copyHost) !== domainOf(skHost)) f.push({ level: 'info', code: 'endpoint-domains', msg: `AdAttributionKit copies go to ${domainOf(copyHost)}, SKAdNetwork copies to ${domainOf(skHost)}` });
|
||||
if (skHost && !copyHost && (s.aakImport || aakIds.length)) f.push({ level: 'info', code: 'copy-endpoint-missing', msg: 'SKAdNetwork postback copies are set up but AdAttributionKit ones are not: add AttributionCopyEndpoint for AdAttributionKit copies' });
|
||||
if ((copyHost || s.aakImport) && !s.conversionUpdates && !s.mmpSdks.length)
|
||||
f.push({ level: 'warn', code: 'no-conversion-update', msg: 'no updateConversionValue / updatePostbackConversionValue call and no attribution SDK found: the advertised app must update the conversion value at least once (best at first launch) to start the conversion window' });
|
||||
|
||||
// ---- attribution rules ----
|
||||
const conf = plist.AdAttributionKitConfigurations;
|
||||
if (conf !== undefined) {
|
||||
if (!isDict(conf)) f.push({ level: 'blocker', code: 'config-type', msg: 'AdAttributionKitConfigurations must be a dictionary' });
|
||||
else {
|
||||
const known = new Set([...skIds, ...aakIds]);
|
||||
const windows = conf.AttributionWindows;
|
||||
if (windows !== undefined && !isDict(windows)) f.push({ level: 'blocker', code: 'windows-type', msg: 'AttributionWindows must be a dictionary' });
|
||||
if (isDict(windows)) for (const [who, cfg] of Object.entries(windows)) {
|
||||
const at = `AttributionWindows.${who}`;
|
||||
if (who !== 'global') {
|
||||
if (who !== who.toLowerCase()) f.push({ level: 'blocker', code: 'windows-id-case', msg: `${at}: ad network ids are lowercase` });
|
||||
else if (known.size && !known.has(who)) f.push({ level: 'warn', code: 'windows-unknown-network', msg: `${at}: not in AdNetworkIdentifiers / SKAdNetworkItems` });
|
||||
}
|
||||
const install = isDict(cfg) ? cfg.install : undefined;
|
||||
if (!isDict(install)) { f.push({ level: 'warn', code: 'windows-install', msg: `${at}: expected an "install" dictionary` }); continue; }
|
||||
for (const [k, v] of Object.entries(install)) {
|
||||
if (k === 'click' && !(typeof v === 'number' && Number.isInteger(v) && v >= 1 && v <= 30)) f.push({ level: 'blocker', code: 'window-click', msg: `${at}.install.click: whole days 1-30` });
|
||||
else if (k === 'view' && !(typeof v === 'number' && Number.isInteger(v) && v >= 1 && v <= 7)) f.push({ level: 'blocker', code: 'window-view', msg: `${at}.install.view: whole days 1-7` });
|
||||
else if (k === 'ignoreInteractionType') {
|
||||
if (v !== 'view' && v !== 'click') f.push({ level: 'blocker', code: 'ignore-type', msg: `${at}.install.ignoreInteractionType: view | click` });
|
||||
if (who === 'global') f.push({ level: 'warn', code: 'ignore-global', msg: `${at}.install.ignoreInteractionType: only read in ad network entries, not in global` });
|
||||
} else if (!['click', 'view', 'ignoreInteractionType'].includes(k)) f.push({ level: 'info', code: 'window-key', msg: `${at}.install.${k}: not a documented key` });
|
||||
}
|
||||
}
|
||||
const cool = conf.AttributionCooldown;
|
||||
if (cool !== undefined) {
|
||||
if (!isDict(cool)) f.push({ level: 'blocker', code: 'cooldown-type', msg: 'AttributionCooldown must be a dictionary' });
|
||||
else for (const [k, v] of Object.entries(cool)) {
|
||||
if (k !== 'install-cooldown-hours' && k !== 're-engagement-cooldown-hours') f.push({ level: 'info', code: 'cooldown-key', msg: `AttributionCooldown.${k}: not a documented key` });
|
||||
else if (!(typeof v === 'number' && v >= 0 && v <= 720)) f.push({ level: 'blocker', code: 'cooldown-range', msg: `AttributionCooldown.${k}: hours 0-720` });
|
||||
}
|
||||
}
|
||||
for (const k of Object.keys(conf)) if (!['AttributionWindows', 'AttributionCooldown'].includes(k)) f.push({ level: 'info', code: 'config-key', msg: `AdAttributionKitConfigurations.${k}: not a documented key` });
|
||||
}
|
||||
}
|
||||
if (!skIds.length && !aakIds.length && !copyHost && !skHost && conf === undefined && !s.aakImport && !s.adSdks.length)
|
||||
f.push({ level: 'info', code: 'none', msg: 'no ad attribution setup found (fine for an app without ads and without ad campaigns)' });
|
||||
if (typeof plist.NSUserTrackingUsageDescription === 'string' && !s.adSdks.length && !s.mmpSdks.length)
|
||||
f.push({ level: 'info', code: 'att-only-for-aak', msg: 'NSUserTrackingUsageDescription is set; AdAttributionKit and SKAdNetwork need no ATT prompt (keep it only if you track across apps)' });
|
||||
return f;
|
||||
}
|
||||
61
cli/lib/app-status.ts
Normal file
61
cli/lib/app-status.ts
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
// One app's portfolio status: identity, offline config check, catalog parity and (live) the release trains from
|
||||
// `apple status --json` / `play status --json`. Shared by the desktop's `portfolio.status` (cli/serve.ts) and the CLI
|
||||
// workspace (`storebound ws status`, `storebound release status`), so all of them read an app the same way.
|
||||
// Every read is a storebound child command; `exec` runs it (serve tracks it for cancellation, the CLI just awaits it).
|
||||
import type { AppStatus, ProjectSummary } from './desktop-protocol';
|
||||
import { appIdentity, appleProductIds, appleReleases, catalogParity, playProductIds, playReleases, releaseTrains } from './portfolio';
|
||||
import type { RunResult } from './runner';
|
||||
|
||||
export type Exec = (argv: string[], cwd: string) => Promise<RunResult>;
|
||||
|
||||
export const lastLine = (s: string): string => s.trim().split('\n').filter(Boolean).at(-1)?.replace(/^error:\s*/, '') ?? '';
|
||||
|
||||
export const emptyStatus = (project: string): AppStatus =>
|
||||
({ project, ok: false, app: null, summary: null, check: null, release: { source: 'none', current: null, next: null }, catalog: null, storeErrors: {}, errors: [] });
|
||||
|
||||
/** `inspect --json` of a folder; throws "project: <reason>" when the config does not load. */
|
||||
export async function inspectApp(dir: string, exec: Exec): Promise<ProjectSummary> {
|
||||
const r = await exec(['inspect', '--json'], dir);
|
||||
if (r.cancelled) throw new Error('Request cancelled');
|
||||
if (r.code !== 0 || !r.data) throw new Error(`project: ${lastLine(r.out) || 'config could not be loaded'}`);
|
||||
return r.data as ProjectSummary;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fills `e` for the app in `dir`: summary, identity, check (skipped for a store-only app), and with `live` the release
|
||||
* trains and the live catalog parity. Errors are thrown; the caller records them in `e.errors`.
|
||||
*/
|
||||
export async function fillAppStatus(e: AppStatus, dir: string, o: { live: boolean; virtual?: boolean; exec: Exec }): Promise<AppStatus> {
|
||||
const summary = e.summary = await inspectApp(dir, o.exec);
|
||||
e.app = appIdentity(summary);
|
||||
e.catalog = catalogParity(summary);
|
||||
if (o.virtual) e.check = { ok: true, problems: [], warnings: [] };
|
||||
else {
|
||||
const c = await o.exec(['check', '--json'], dir);
|
||||
const cd = c.data as { ok?: boolean; problems?: string[]; warnings?: string[] } | undefined;
|
||||
e.check = cd ? { ok: !!cd.ok, problems: cd.problems ?? [], warnings: cd.warnings ?? [] } : { ok: false, problems: [lastLine(c.out) || `check exit ${c.code}`], warnings: [] };
|
||||
}
|
||||
if (o.live) {
|
||||
const store = async (argv: string[]): Promise<{ data?: unknown; error?: string }> => {
|
||||
const r = await o.exec(argv, dir);
|
||||
return r.code === 0 && r.data !== undefined ? { data: r.data } : { error: lastLine(r.out) || `exit ${r.code}` };
|
||||
};
|
||||
const [apple, play] = await Promise.all([summary.apple ? store(['apple', 'status', '--json']) : undefined, summary.play ? store(['play', 'status', '--json']) : undefined]);
|
||||
if (apple?.error) e.storeErrors.ios = apple.error;
|
||||
if (play?.error) e.storeErrors.android = play.error;
|
||||
const ios = apple?.data ? appleReleases(apple.data) : [], android = play?.data ? playReleases(play.data) : [];
|
||||
e.release = { source: 'live', ...releaseTrains(ios, android), all: [...ios, ...android] };
|
||||
e.catalog = catalogParity(summary, apple?.data ? appleProductIds(apple.data) : undefined, play?.data ? playProductIds(play.data) : undefined);
|
||||
}
|
||||
e.ok = e.check.ok && !e.storeErrors.ios && !e.storeErrors.android && (e.catalog?.ok ?? true);
|
||||
return e;
|
||||
}
|
||||
|
||||
/** Runs `fn` over `items`, at most `limit` at a time; results in input order. */
|
||||
export async function pool<T, R>(items: T[], limit: number, fn: (x: T, i: number) => Promise<R>): Promise<R[]> {
|
||||
const out = new Array<R>(items.length);
|
||||
let next = 0;
|
||||
const n = Math.max(1, Math.min(limit, items.length));
|
||||
await Promise.all(Array.from({ length: n }, async () => { while (next < items.length) { const i = next++; out[i] = await fn(items[i]!, i); } }));
|
||||
return out;
|
||||
}
|
||||
|
|
@ -6,21 +6,25 @@ export interface Args {
|
|||
str(name: string, d: string): string;
|
||||
num(name: string, d: number): number;
|
||||
list(name: string): string[];
|
||||
/** Every value of a flag given more than once (--param a=1 --param b=2), in order. */
|
||||
many(name: string): string[];
|
||||
}
|
||||
|
||||
export function parseArgs(argv: string[], booleans: string[] = []): Args {
|
||||
const flags = new Map<string, string>();
|
||||
const repeated = new Map<string, string[]>();
|
||||
const set = (k: string, v: string) => { flags.set(k, v); repeated.set(k, [...(repeated.get(k) ?? []), v]); };
|
||||
const _: string[] = [];
|
||||
const bool = new Set(['dry', 'yes', 'help', 'json', 'verbose', ...booleans]);
|
||||
const bool = new Set(['dry', 'yes', 'help', 'json', 'verbose', 'all-pages', ...booleans]);
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i]!;
|
||||
if (!a.startsWith('--')) { _.push(a); continue; }
|
||||
const eq = a.indexOf('=');
|
||||
if (eq > 0) { flags.set(a.slice(2, eq), a.slice(eq + 1)); continue; }
|
||||
if (eq > 0) { set(a.slice(2, eq), a.slice(eq + 1)); continue; }
|
||||
const name = a.slice(2);
|
||||
const next = argv[i + 1];
|
||||
if (bool.has(name) || name.startsWith('no-') || next === undefined || next.startsWith('--')) flags.set(name, 'true');
|
||||
else { flags.set(name, next); i++; }
|
||||
if (bool.has(name) || name.startsWith('no-') || next === undefined || next.startsWith('--')) set(name, 'true');
|
||||
else { set(name, next); i++; }
|
||||
}
|
||||
const get = (n: string) => flags.get(n);
|
||||
return {
|
||||
|
|
@ -30,5 +34,6 @@ export function parseArgs(argv: string[], booleans: string[] = []): Args {
|
|||
str: (n, d) => get(n) ?? d,
|
||||
num: (n, d) => { const v = get(n); const x = v === undefined ? d : Number(v); if (Number.isNaN(x)) throw new Error(`--${n}: not a number`); return x; },
|
||||
list: n => (get(n) ?? '').split(',').map(s => s.trim()).filter(Boolean),
|
||||
many: n => repeated.get(n) ?? [],
|
||||
};
|
||||
}
|
||||
|
|
|
|||
63
cli/lib/aso-rank.ts
Normal file
63
cli/lib/aso-rank.ts
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
// App Store keyword rank check against Apple's public iTunes Search API, as pure parts. The command (cli/aso.ts rank)
|
||||
// sends the queries one by one, slower than Apple's limit, and stores a snapshot in .storebound/aso/.
|
||||
// Source: Apple Search API (Performance Partners), checked October 2026:
|
||||
// https://itunes.apple.com/search?term=<text>&country=<2-letter>&media=software&entity=software&limit=1..200 (default 50)
|
||||
// "approximately 20 calls per minute (subject to change)". https://performance-partners.apple.com/search-api
|
||||
// What this is and is not: the order of the Search API results is close to, but not the same as, App Store search
|
||||
// (no personalisation, no search ads, no "in-app events" rows), so read ranks as a trend, not a promise. The API returns
|
||||
// title (trackName), developer (sellerName), bundleId, rating and description, but no subtitle: competitor subtitles
|
||||
// are not available through a public API, so they are not shown (storebound scrapes nothing).
|
||||
// Result fields used (as the API returns them; Apple's table lists only the general ones): trackId, trackName,
|
||||
// bundleId, sellerName, averageUserRating, userRatingCount, primaryGenreName.
|
||||
|
||||
export const SEARCH_API = 'https://itunes.apple.com/search';
|
||||
/** Apple: about 20 calls per minute. One call every 3.5 s stays below it with room for retries. */
|
||||
export const MIN_DELAY_MS = 3_500;
|
||||
export const MAX_RESULTS = 200;
|
||||
|
||||
export interface SearchApp { trackId: number; trackName: string; bundleId?: string; sellerName?: string; averageUserRating?: number; userRatingCount?: number; primaryGenreName?: string }
|
||||
|
||||
export function searchUrl(term: string, country: string, limit = MAX_RESULTS): string {
|
||||
if (!/^[a-z]{2}$/i.test(country)) throw new Error(`storefront "${country}": a two-letter country code (us, de, tr)`);
|
||||
return `${SEARCH_API}?${new URLSearchParams({ term, country: country.toLowerCase(), media: 'software', entity: 'software', limit: String(Math.min(MAX_RESULTS, Math.max(1, limit))) })}`;
|
||||
}
|
||||
|
||||
/** Keywords of one App Store locale's keyword field ("a,b,c"), trimmed and de-duplicated, plus extra terms. Pure. */
|
||||
export function keywordList(field: string | undefined, extra: string[] = []): string[] {
|
||||
const out: string[] = [];
|
||||
for (const k of [...(field ?? '').split(','), ...extra].map(s => s.trim()).filter(Boolean)) if (!out.some(x => x.toLowerCase() === k.toLowerCase())) out.push(k);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** "us=en-US,de=de-DE" or "us,de" -> storefront + listing locale (default locale for the bare ones). Pure. */
|
||||
export function parseStorefronts(spec: string[], defaultLocale: string): { storefront: string; locale: string }[] {
|
||||
const list = spec.length ? spec : ['us'];
|
||||
return list.map(s => { const [sf, loc] = s.split('='); return { storefront: sf!.trim().toLowerCase(), locale: (loc ?? defaultLocale).trim() }; });
|
||||
}
|
||||
|
||||
/** 1-based rank of the app in the results (by Apple ID, else bundle id), or null when not in the first N. Pure. */
|
||||
export function rankOf(results: SearchApp[], app: { appId?: string; bundleId?: string }): number | null {
|
||||
const i = results.findIndex(r => (app.appId && String(r.trackId) === app.appId) || (app.bundleId && r.bundleId === app.bundleId));
|
||||
return i >= 0 ? i + 1 : null;
|
||||
}
|
||||
|
||||
export interface Competitor { rank: number; title: string; developer: string; rating: number | null; ratings: number; genre: string }
|
||||
|
||||
/** The first n results that are not the app itself. Pure. */
|
||||
export function competitors(results: SearchApp[], app: { appId?: string; bundleId?: string }, n = 3): Competitor[] {
|
||||
return results.map((r, i) => ({ r, i })).filter(({ r }) => !((app.appId && String(r.trackId) === app.appId) || (app.bundleId && r.bundleId === app.bundleId))).slice(0, n)
|
||||
.map(({ r, i }) => ({ rank: i + 1, title: r.trackName, developer: r.sellerName ?? '', rating: r.averageUserRating ?? null, ratings: r.userRatingCount ?? 0, genre: r.primaryGenreName ?? '' }));
|
||||
}
|
||||
|
||||
export interface RankRow { storefront: string; locale: string; keyword: string; rank: number | null; results: number; competitors: Competitor[] }
|
||||
|
||||
/** Rank change between two snapshots: positive = moved up. Pure. */
|
||||
export function rankDelta(now: RankRow[], before: RankRow[] | undefined): Map<string, number | null> {
|
||||
const prev = new Map((before ?? []).map(r => [`${r.storefront}|${r.keyword.toLowerCase()}`, r.rank] as const));
|
||||
const out = new Map<string, number | null>();
|
||||
for (const r of now) {
|
||||
const p = prev.get(`${r.storefront}|${r.keyword.toLowerCase()}`);
|
||||
out.set(`${r.storefront}|${r.keyword.toLowerCase()}`, p === undefined || p === null || r.rank === null ? null : p - r.rank);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
89
cli/lib/build-ops.ts
Normal file
89
cli/lib/build-ops.ts
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
// TestFlight build housekeeping as pure parts: waiting for an uploaded build to finish processing, and expiring old
|
||||
// builds. The command (cli/apple/testflight.ts wait | expire) reads, calls these and prints / sends.
|
||||
// API (App Store Connect API 4.5.1 OpenAPI spec and docs, checked October 2026):
|
||||
// GET /v1/builds filter[app], filter[version], filter[expired], filter[preReleaseVersion.platform], sort=-uploadedDate,
|
||||
// include=preReleaseVersion,buildBetaDetail,appStoreVersion
|
||||
// https://developer.apple.com/documentation/appstoreconnectapi/get-v1-builds
|
||||
// Build.processingState: PROCESSING | FAILED | INVALID | VALID
|
||||
// PATCH /v1/builds/{id} { expired: true } "Expire a build or change its encryption exemption setting."
|
||||
// https://developer.apple.com/documentation/appstoreconnectapi/patch-v1-builds-_id_
|
||||
// Expiring is permanent: testers lose the build, it cannot be un-expired. So `expire` is a dry run first, then a
|
||||
// terminal confirmation; it is not an MCP tool.
|
||||
import type { Req } from '../apple/jsonapi';
|
||||
|
||||
export type WaitOutcome = 'missing' | 'processing' | 'valid' | 'failed';
|
||||
|
||||
export interface BuildSeen { found: boolean; processingState?: string; internal?: string | null; external?: string | null }
|
||||
|
||||
/** One poll result -> what it means for the waiter. A build that is not listed yet is normal for some minutes after
|
||||
* the upload (App Store Connect lists it once processing starts). */
|
||||
export function waitOutcome(b: BuildSeen): WaitOutcome {
|
||||
if (!b.found) return 'missing';
|
||||
if (b.processingState === 'VALID') return 'valid';
|
||||
if (b.processingState === 'FAILED' || b.processingState === 'INVALID') return 'failed';
|
||||
return 'processing';
|
||||
}
|
||||
|
||||
/** Poll delay: 20 s at first, x1.5 per poll, at most 2 minutes (processing usually takes 5 to 30 minutes). */
|
||||
export function waitDelay(prevMs: number | null): number {
|
||||
return prevMs === null ? 20_000 : Math.min(Math.round(prevMs * 1.5), 120_000);
|
||||
}
|
||||
|
||||
/** Exit codes of `testflight wait`: 0 VALID, 1 FAILED / INVALID, 7 timeout (the same as `apple status --wait-review`). */
|
||||
export const BUILD_WAIT_EXIT = { valid: 0, failed: 1, timeout: 7 } as const;
|
||||
|
||||
/** What the build state means for the next step, one line. */
|
||||
export function validHint(b: BuildSeen): string {
|
||||
if (b.internal === 'MISSING_EXPORT_COMPLIANCE' || b.external === 'MISSING_EXPORT_COMPLIANCE')
|
||||
return 'export compliance missing: storebound apple encryption --build N (from apple.usesNonExemptEncryption)';
|
||||
return 'ready: storebound apple testflight distribute --build N --group <name>, or apple listing --build N';
|
||||
}
|
||||
|
||||
export interface ExpireCandidate {
|
||||
id: string; build: string; version?: string; uploaded: string; processingState?: string;
|
||||
/** Attached to an App Store version (in review, live or being prepared): never expired by storebound. */
|
||||
attached: boolean;
|
||||
}
|
||||
|
||||
export interface ExpirePlan { expire: ExpireCandidate[]; keep: ExpireCandidate[]; protected: { b: ExpireCandidate; why: string }[]; reqs: Req[] }
|
||||
|
||||
/**
|
||||
* Which builds to expire. `builds` = the app's builds that are not expired yet (any order). keep = keep the newest N
|
||||
* builds (by upload date; protected builds count as kept), olderThanDays = only builds uploaded before now - D days.
|
||||
* With both, a build must be beyond the newest N AND older than D days. Builds attached to an App Store version and
|
||||
* builds still processing are never expired. Pure.
|
||||
*/
|
||||
export function planExpire(builds: ExpireCandidate[], o: { keep?: number; olderThanDays?: number; now?: number }): ExpirePlan {
|
||||
if (o.keep === undefined && o.olderThanDays === undefined) throw new Error('--keep <n> or --older-than <days> (or both)');
|
||||
if (o.keep !== undefined && !(Number.isInteger(o.keep) && o.keep >= 1)) throw new Error('--keep: a whole number >= 1 (the newest build always stays)');
|
||||
if (o.olderThanDays !== undefined && !(o.olderThanDays >= 1)) throw new Error('--older-than: days >= 1');
|
||||
const now = o.now ?? Date.now();
|
||||
const sorted = [...builds].sort((a, b) => b.uploaded.localeCompare(a.uploaded));
|
||||
const plan: ExpirePlan = { expire: [], keep: [], protected: [], reqs: [] };
|
||||
sorted.forEach((b, i) => {
|
||||
if (b.attached) { plan.protected.push({ b, why: 'attached to an App Store version' }); return; }
|
||||
if (b.processingState && b.processingState !== 'VALID' && b.processingState !== 'FAILED' && b.processingState !== 'INVALID') { plan.protected.push({ b, why: `still ${b.processingState}` }); return; }
|
||||
if (i === 0) { plan.keep.push(b); return; }
|
||||
const beyondKeep = o.keep === undefined || i >= o.keep;
|
||||
const old = o.olderThanDays === undefined || now - Date.parse(b.uploaded) > o.olderThanDays * 86_400_000;
|
||||
(beyondKeep && old ? plan.expire : plan.keep).push(b);
|
||||
});
|
||||
plan.reqs = plan.expire.map(b => ({ method: 'PATCH', path: `/v1/builds/${b.id}`, note: `expire build ${b.build}${b.version ? ` (${b.version})` : ''}, uploaded ${b.uploaded.slice(0, 10)}`,
|
||||
body: { data: { type: 'builds', id: b.id, attributes: { expired: true } } } }));
|
||||
return plan;
|
||||
}
|
||||
|
||||
/** Builds response (include=preReleaseVersion,appStoreVersion) -> expire candidates. Pure. */
|
||||
export function expireCandidates(pages: { data?: { id: string; attributes?: Record<string, unknown>; relationships?: Record<string, { data?: { id: string } | null }> }[]; included?: { type: string; id: string; attributes?: { version?: string } }[] }[]): ExpireCandidate[] {
|
||||
const out: ExpireCandidate[] = [];
|
||||
for (const page of pages) {
|
||||
const pre = new Map((page.included ?? []).filter(x => x.type === 'preReleaseVersions').map(x => [x.id, x.attributes?.version] as const));
|
||||
for (const b of page.data ?? []) {
|
||||
const a = b.attributes ?? {};
|
||||
if (a.expired === true) continue;
|
||||
out.push({ id: b.id, build: String(a.version ?? '?'), version: pre.get(b.relationships?.preReleaseVersion?.data?.id ?? ''), uploaded: String(a.uploadedDate ?? ''),
|
||||
processingState: a.processingState as string | undefined, attached: !!b.relationships?.appStoreVersion?.data });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
|
@ -3,8 +3,14 @@
|
|||
import { existsSync } from 'node:fs';
|
||||
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
||||
import { validateCapture, validateRecord } from '../shots/devices';
|
||||
import { type AppEventDef, type CustomProductPageDef, validateCpp, validateEvents } from './cpp-events';
|
||||
import { type IapOfferCodeDef, type PromotedConfig, validateIapOfferCodes, validatePromoted, validateWinBack, type WinBackDef } from './offers';
|
||||
import { validateSubscriptions } from './subscriptions';
|
||||
import { type TfConfig, validateTestflight } from './testflight';
|
||||
import { type AppleSigning, validateSigning } from './signing';
|
||||
import { type AppleBuildConfig, validateAppleBuild } from './xcode';
|
||||
import { type PlayBuildConfig, validatePlayBuild } from './gradle';
|
||||
import { type OriginalityConfig, validateOriginality } from './originality';
|
||||
|
||||
/** consumable / non_consumable: both stores. non_renewing: Apple NON_RENEWING_SUBSCRIPTION (access for a fixed time,
|
||||
* you track the expiry); Google Play has no such type, so it becomes a one-time product your app consumes when the
|
||||
|
|
@ -46,6 +52,8 @@ export interface Product {
|
|||
familySharable?: boolean;
|
||||
/** Sell this product only on these platforms (default: all of app.platforms). */
|
||||
platforms?: Platform[];
|
||||
/** Apple offer codes for this one-time purchase (`storebound apple offer-codes`). */
|
||||
offerCodes?: IapOfferCodeDef[];
|
||||
}
|
||||
|
||||
export interface Language {
|
||||
|
|
@ -304,6 +312,14 @@ export interface ReviewAccess {
|
|||
instructions?: string;
|
||||
}
|
||||
|
||||
/** App Privacy: does the app (or an SDK in it) track users across other companies' apps and websites? true needs
|
||||
* App Tracking Transparency (NSUserTrackingUsageDescription + the prompt) and the privacy manifest's NSPrivacyTracking. */
|
||||
export interface AppPrivacyConfig {
|
||||
tracking?: boolean;
|
||||
/** Domains that receive tracking data (privacy manifest NSPrivacyTrackingDomains). */
|
||||
trackingDomains?: string[];
|
||||
}
|
||||
|
||||
export type SubscriptionPeriod = 'P1W' | 'P1M' | 'P2M' | 'P3M' | 'P6M' | 'P1Y';
|
||||
|
||||
/** Introductory offer for new subscribers. Apple: subscriptionIntroductoryOffers (first-time subscribers of the group,
|
||||
|
|
@ -394,6 +410,8 @@ export interface Subscription {
|
|||
basePlanId?: string;
|
||||
/** Play grace period (ISO 8601: P3D, P7D, P14D, P30D). Default: Play's default. */
|
||||
gracePeriod?: string;
|
||||
/** Apple win-back offers for lapsed subscribers (`storebound apple win-back`; the subscription must be approved). */
|
||||
winBack?: WinBackDef[];
|
||||
}
|
||||
|
||||
/** One subscription group. Apple: a subscription group (people can hold one subscription per group and move between
|
||||
|
|
@ -406,6 +424,11 @@ export interface SubscriptionGroup {
|
|||
subscriptions: Subscription[];
|
||||
}
|
||||
|
||||
/** Play target audience age groups (App content > Target audience and content). */
|
||||
export type PlayAgeGroup = '0-5' | '6-8' | '9-12' | '13-15' | '16-17' | '18+';
|
||||
export const PLAY_AGE_GROUPS: readonly PlayAgeGroup[] = ['0-5', '6-8', '9-12', '13-15', '16-17', '18+'];
|
||||
export const PLAY_BILLING_PROGRAMS = ['user-choice-billing', 'alternative-billing', 'external-offers', 'external-content-links'] as const;
|
||||
|
||||
export interface ShipConfig {
|
||||
app: {
|
||||
name: string;
|
||||
|
|
@ -436,6 +459,19 @@ export interface ShipConfig {
|
|||
/** Cloud Storage bucket of the Play Console report exports, e.g. "pubsite_prod_rev_<number>" (Play Console >
|
||||
* Download reports > Statistics > Copy Cloud Storage URI). Used by `storebound analytics snapshot`. */
|
||||
reportsBucket?: string;
|
||||
/** `storebound play build`: Gradle project folder, module, flavor (found automatically when unset). */
|
||||
build?: PlayBuildConfig;
|
||||
/** Play Console > App content > Target audience and content: the age groups you select. Any group under 13 puts
|
||||
* the app under the Families policy (`storebound scan` checks ad SDKs, the advertising ID and location for it). */
|
||||
targetAges?: PlayAgeGroup[];
|
||||
/** Developer account type. New personal accounts (created after 2023-11-13) must run a closed test with at least
|
||||
* 12 opted-in testers for 14 days before they can apply for production (`storebound scan` reminds you). */
|
||||
accountType?: 'personal' | 'organization';
|
||||
/** When the Play developer account was created (YYYY-MM-DD), for the personal-account testing requirement. */
|
||||
accountCreated?: string;
|
||||
/** Play billing programs the app is enrolled in that allow another payment method next to Play Billing for
|
||||
* digital goods (user choice billing, alternative billing only, external offers / external content links). */
|
||||
billingPrograms?: ('user-choice-billing' | 'alternative-billing' | 'external-offers' | 'external-content-links')[];
|
||||
};
|
||||
apple?: {
|
||||
bundleId: string; appId?: string; primaryLocale?: string; listing?: string; info?: AppleAppInfo; reviewShots?: string;
|
||||
|
|
@ -462,6 +498,16 @@ export interface ShipConfig {
|
|||
iphoneMedium?: boolean;
|
||||
/** TestFlight beta groups, the tester CSV (in .storebound/) and Test Information (`storebound apple testflight`). */
|
||||
testflight?: TfConfig;
|
||||
/** Certificates, profiles and capabilities through the API (`storebound apple signing`), signing style of `apple build`. */
|
||||
signing?: AppleSigning;
|
||||
/** `storebound apple build`: workspace / project, scheme, configuration, output folder (found automatically when unset). */
|
||||
build?: AppleBuildConfig;
|
||||
/** Promoted in-app purchases on the product page, in order (`storebound apple promoted`; at most 20). */
|
||||
promoted?: PromotedConfig;
|
||||
/** Custom product pages (`storebound apple cpp`; at most 70). */
|
||||
customProductPages?: CustomProductPageDef[];
|
||||
/** In-app events (`storebound apple events`). */
|
||||
events?: AppEventDef[];
|
||||
};
|
||||
products?: Product[];
|
||||
/** Auto-renewable subscriptions (`storebound apple subscriptions`, `storebound play subscriptions`). */
|
||||
|
|
@ -476,12 +522,20 @@ export interface ShipConfig {
|
|||
baseTerritory?: string;
|
||||
};
|
||||
dataSafety?: DataSafety;
|
||||
/** App Store App Privacy answers storebound cannot derive from dataSafety (App Privacy has no API: the owner enters
|
||||
* them in App Store Connect). `storebound scan` proposes them from the detected SDKs and code. */
|
||||
appPrivacy?: AppPrivacyConfig;
|
||||
/** `storebound scan`: findings the owner has looked at and accepts, by rule id (with the reason, shown in the report). */
|
||||
scan?: { ignore?: { rule: string; store?: 'apple' | 'play'; reason: string }[] };
|
||||
/** Ads: `validate` checks that <app.website>/app-ads.txt is reachable and contains every line listed here. */
|
||||
ads?: { appAdsTxt?: string[] };
|
||||
/** Rendered store graphics dir (<renders>/<languageId>/<size>/NN.png|jpg). Defaults to shots.out. */
|
||||
renders?: string;
|
||||
shots?: ShotsConfig;
|
||||
icons?: IconsConfig;
|
||||
/** `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. */
|
||||
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`). */
|
||||
|
|
@ -671,8 +725,15 @@ export function validateConfig(c: unknown): string[] {
|
|||
if (cfg.play && !ID_RE.test(cfg.play.packageName ?? '')) e.push('play.packageName: not a package name (com.example.game)');
|
||||
if (cfg.play?.video && !/^https:\/\/(www\.youtube\.com\/watch\?v=[\w-]{6,}|youtu\.be\/[\w-]{6,})$/.test(cfg.play.video))
|
||||
e.push('play.video: a plain YouTube video URL (https://www.youtube.com/watch?v=... or https://youtu.be/...), no playlist, channel or extra parameters');
|
||||
e.push(...validatePlayBuild(cfg.play?.build), ...validateOriginality(cfg.originality));
|
||||
if (cfg.play?.reportsBucket && !/^(gs:\/\/)?pubsite_prod(_rev)?_\d+\/?$/.test(cfg.play.reportsBucket))
|
||||
e.push('play.reportsBucket: the Play reports bucket, e.g. "pubsite_prod_rev_<number>" (Play Console > Download reports > Copy Cloud Storage URI)');
|
||||
if (cfg.play?.targetAges !== undefined && !(Array.isArray(cfg.play.targetAges) && cfg.play.targetAges.length && cfg.play.targetAges.every(a => PLAY_AGE_GROUPS.includes(a))))
|
||||
e.push(`play.targetAges: a list of ${PLAY_AGE_GROUPS.join(' | ')}`);
|
||||
if (cfg.play?.accountType !== undefined && cfg.play.accountType !== 'personal' && cfg.play.accountType !== 'organization') e.push('play.accountType: personal | organization');
|
||||
if (cfg.play?.accountCreated !== undefined && !/^\d{4}-\d{2}-\d{2}$/.test(cfg.play.accountCreated)) e.push('play.accountCreated: a date, YYYY-MM-DD');
|
||||
if (cfg.play?.billingPrograms !== undefined && !(Array.isArray(cfg.play.billingPrograms) && cfg.play.billingPrograms.every(b => (PLAY_BILLING_PROGRAMS as readonly string[]).includes(b))))
|
||||
e.push(`play.billingPrograms: a list of ${PLAY_BILLING_PROGRAMS.join(' | ')}`);
|
||||
if (cfg.apple) {
|
||||
if (!ID_RE.test(cfg.apple.bundleId ?? '')) e.push('apple.bundleId: not a bundle id (com.example.game)');
|
||||
if (cfg.apple.appId && !/^\d+$/.test(cfg.apple.appId)) e.push('apple.appId: numeric Apple ID of the app (App Store Connect > App Information)');
|
||||
|
|
@ -680,7 +741,20 @@ export function validateConfig(c: unknown): string[] {
|
|||
if (enc !== undefined && typeof enc !== 'boolean') e.push('apple.usesNonExemptEncryption: true | false');
|
||||
if (cfg.apple.screenshotTypes && !cfg.apple.screenshotTypes.every(t => /^APP_[A-Z0-9_]+$/.test(t))) e.push('apple.screenshotTypes: display types like APP_IPHONE_67');
|
||||
e.push(...validateTestflight(cfg.apple.testflight));
|
||||
e.push(...validateSigning(cfg.apple.signing), ...validateAppleBuild(cfg.apple.build));
|
||||
const catalogIds = new Set([...(cfg.products ?? []).map(p => p.id), ...(cfg.subscriptions ?? []).flatMap(g => (g.subscriptions ?? []).map(x => x.id))]);
|
||||
e.push(...validatePromoted(cfg.apple.promoted, catalogIds));
|
||||
e.push(...validateCpp(cfg.apple.customProductPages, ids, Object.keys(cfg.shots?.variants ?? {})));
|
||||
e.push(...validateEvents(cfg.apple.events, ids));
|
||||
}
|
||||
if (cfg.appPrivacy) {
|
||||
if (cfg.appPrivacy.tracking !== undefined && typeof cfg.appPrivacy.tracking !== 'boolean') e.push('appPrivacy.tracking: true | false');
|
||||
if (cfg.appPrivacy.trackingDomains && !(Array.isArray(cfg.appPrivacy.trackingDomains) && cfg.appPrivacy.trackingDomains.every(d => typeof d === 'string' && /^[a-z0-9.-]+$/i.test(d))))
|
||||
e.push('appPrivacy.trackingDomains: a list of host names');
|
||||
}
|
||||
for (const [i, x] of (cfg.scan?.ignore ?? []).entries())
|
||||
if (!x || typeof x.rule !== 'string' || !x.rule || typeof x.reason !== 'string' || !x.reason.trim() || (x.store !== undefined && x.store !== 'apple' && x.store !== 'play'))
|
||||
e.push(`scan.ignore[${i}]: { rule: '<rule id from storebound scan>', reason: 'why this is fine', store?: 'apple' | 'play' }`);
|
||||
if (cfg.ads?.appAdsTxt && !cfg.ads.appAdsTxt.every(l => typeof l === 'string' && l.split(',').length >= 3))
|
||||
e.push('ads.appAdsTxt: lines like "example-network.com, pub-123, DIRECT, abc123"');
|
||||
const seen = new Set<string>();
|
||||
|
|
@ -699,6 +773,7 @@ export function validateConfig(c: unknown): string[] {
|
|||
if ([...(l.title ?? '')].length > 30) e.push(`${at}.listings.${lang}.title: over 30 characters (App Store limit)`);
|
||||
if (!l.description) e.push(`${at}.listings.${lang}.description: missing`);
|
||||
}
|
||||
e.push(...validateIapOfferCodes(at, p.offerCodes, p.type));
|
||||
for (const o of p.overrides ?? []) {
|
||||
if (!/^[A-Z]{2}$/.test(o.region)) e.push(`${at}.overrides: region "${o.region}" must be ISO alpha-2 (TR)`);
|
||||
if (!/^[A-Z]{3}$/.test(o.currency)) e.push(`${at}.overrides: currency "${o.currency}" must be ISO 4217 (TRY)`);
|
||||
|
|
@ -706,6 +781,7 @@ export function validateConfig(c: unknown): string[] {
|
|||
}
|
||||
}
|
||||
e.push(...validateSubscriptions(cfg.subscriptions, ids, seen));
|
||||
for (const [gi, g] of (cfg.subscriptions ?? []).entries()) for (const [si, sub] of (g.subscriptions ?? []).entries()) e.push(...validateWinBack(`subscriptions[${gi}].subscriptions[${si}]`, sub.winBack));
|
||||
if (cfg.prices?.baseTerritory && !/^[A-Z]{3}$/.test(cfg.prices.baseTerritory)) e.push('prices.baseTerritory: App Store territory, alpha-3 (USA)');
|
||||
if (cfg.dataSafety) {
|
||||
for (const [t, u] of Object.entries(cfg.dataSafety.data ?? {})) {
|
||||
|
|
|
|||
202
cli/lib/cpp-events.ts
Normal file
202
cli/lib/cpp-events.ts
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
// App Store custom product pages and in-app events, as pure parts: config checks, the create requests and what to
|
||||
// change. The commands (cli/apple/cpp.ts, cli/apple/events.ts) read, plan, show the dry run and send. Creating and
|
||||
// uploading change nothing customers see; sending a page or an event to App Review, and making a page visible, are
|
||||
// the owner's (terminal, asks first, not MCP tools).
|
||||
// Sources (App Store Connect API 4.5.1 OpenAPI spec + docs, App Store Connect Help; checked October 2026):
|
||||
// Custom product pages: POST /v1/appCustomProductPages (name, app, optional appStoreVersionTemplate /
|
||||
// customProductPageTemplate, inline appCustomProductPageVersions + appCustomProductPageLocalizations with locale and
|
||||
// promotionalText; Apple's example request), PATCH /v1/appCustomProductPages/{id} (name, visible),
|
||||
// POST /v1/appCustomProductPageVersions (deepLink), POST /v1/appCustomProductPageLocalizations (locale,
|
||||
// promotionalText), screenshots: appScreenshotSets with the appCustomProductPageLocalization relationship.
|
||||
// https://developer.apple.com/documentation/appstoreconnectapi/post-v1-appcustomproductpages
|
||||
// Help: up to 70 custom product pages per app; each needs App Review (independent of an app update); the deep link
|
||||
// works from iOS / iPadOS 18 once approved. https://developer.apple.com/app-store/custom-product-pages/
|
||||
// In-app events: POST /v1/appEvents (referenceName, badge, deepLink, purchaseRequirement, primaryLocale, priority,
|
||||
// purpose, territorySchedules [{ territories, publishStart, eventStart, eventEnd }]), POST /v1/appEventLocalizations
|
||||
// (locale, name, shortDescription, longDescription), POST /v1/appEventScreenshots (fileName, fileSize,
|
||||
// appEventAssetType EVENT_CARD | EVENT_DETAILS_PAGE) + the upload operations.
|
||||
// Help "Offer In-App Events": reference name up to 64 characters, event name 30, short description 50, long
|
||||
// description 120; an event lasts 15 minutes to 31 days; it can be published at most 14 days before it starts;
|
||||
// up to 10 published and 15 approved events per app; events need App Review.
|
||||
// https://developer.apple.com/help/app-store-connect/offer-in-app-events/offer-in-app-events
|
||||
// Media: event card 16:9, 1920x1080 to 3840x2160; details page 9:16, 1080x1920 to 2160x3840; .jpg / .png.
|
||||
// https://developer.apple.com/help/app-store-connect/reference/in-app-events/in-app-event-media-and-audio-specifications
|
||||
// Sending either to review: a review submission item with appCustomProductPageVersion | appEvent
|
||||
// (https://developer.apple.com/documentation/appstoreconnectapi/review-submissions).
|
||||
// Deprecation note (API 4.5.1): screenshot sets and app event screenshots are deprecated in favour of the App Asset
|
||||
// Library; they still work and storebound uses them until the asset library is the only way.
|
||||
import type { Req } from '../apple/jsonapi';
|
||||
import { one } from '../apple/jsonapi';
|
||||
import type { Language } from './config';
|
||||
|
||||
export const CPP_LIMITS = { pages: 70, promotionalText: 170 } as const;
|
||||
export const EVENT_LIMITS = { referenceName: 64, name: 30, shortDescription: 50, longDescription: 120, published: 10, approved: 15, maxDays: 31, minMinutes: 15, publishLeadDays: 14 } as const;
|
||||
export const EVENT_BADGES = ['LIVE_EVENT', 'PREMIERE', 'CHALLENGE', 'COMPETITION', 'NEW_SEASON', 'MAJOR_UPDATE', 'SPECIAL_EVENT'] as const;
|
||||
export const EVENT_PURPOSES = ['APPROPRIATE_FOR_ALL_USERS', 'ATTRACT_NEW_USERS', 'KEEP_ACTIVE_USERS_INFORMED', 'BRING_BACK_LAPSED_USERS'] as const;
|
||||
/** Event media: [min w, min h, max w, max h]. */
|
||||
export const EVENT_MEDIA = { EVENT_CARD: [1920, 1080, 3840, 2160], EVENT_DETAILS_PAGE: [1080, 1920, 2160, 3840] } as const;
|
||||
|
||||
export interface CustomProductPageDef {
|
||||
/** Page name (unique per app; shown only in App Store Connect). */
|
||||
name: string;
|
||||
/** Screenshots from this shots variant (`storebound shots render --variant <id>`); default: the base renders. */
|
||||
variant?: string;
|
||||
/** Universal link or custom URL that "Open" goes to (iOS / iPadOS 18+, after approval). */
|
||||
deepLink?: string;
|
||||
/** Language id -> promotional text (170). Every language with an App Store locale gets a localization. */
|
||||
promotionalText?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface AppEventDef {
|
||||
/** Reference name (unique per app, up to 64 characters). */
|
||||
referenceName: string;
|
||||
badge: typeof EVENT_BADGES[number];
|
||||
purpose?: typeof EVENT_PURPOSES[number];
|
||||
priority?: 'high' | 'normal';
|
||||
deepLink?: string;
|
||||
/** Text shown when the event needs a purchase or subscription, e.g. "Pro subscription". */
|
||||
purchaseRequirement?: string;
|
||||
/** Language id of the primary locale (default: the first language with an App Store locale). */
|
||||
primaryLanguage?: string;
|
||||
/** When and where: ISO date-times; territories (alpha-3) default to every territory of the app. */
|
||||
schedule: { publishStart: string; eventStart: string; eventEnd: string; territories?: string[] };
|
||||
/** Language id -> name (30), shortDescription (50), longDescription (120). */
|
||||
listings: Record<string, { name: string; shortDescription: string; longDescription: string }>;
|
||||
/** Images (paths from the project root; "{lang}" is replaced by the language id): card 16:9, details 9:16. */
|
||||
media?: { card?: string; details?: string };
|
||||
}
|
||||
|
||||
const len = (s: string): number => [...s].length;
|
||||
|
||||
export function validateCpp(pages: CustomProductPageDef[] | undefined, langIds: Set<string>, variants: string[]): string[] {
|
||||
const e: string[] = [];
|
||||
const names = new Set<string>();
|
||||
if ((pages ?? []).length > CPP_LIMITS.pages) e.push(`apple.customProductPages: at most ${CPP_LIMITS.pages} per app`);
|
||||
for (const [i, p] of (pages ?? []).entries()) {
|
||||
const at = `apple.customProductPages[${i}]`;
|
||||
if (!p.name) e.push(`${at}.name: missing`);
|
||||
if (names.has(p.name)) e.push(`${at}.name: duplicate "${p.name}"`);
|
||||
names.add(p.name);
|
||||
if (p.variant && !variants.includes(p.variant)) e.push(`${at}.variant: "${p.variant}" is not in shots.variants`);
|
||||
if (p.deepLink && !/^[a-z][a-z0-9+.-]*:\/\/\S+$/i.test(p.deepLink)) e.push(`${at}.deepLink: a universal link (https://...) or custom URL (myapp://...)`);
|
||||
for (const [l, t] of Object.entries(p.promotionalText ?? {})) {
|
||||
if (!langIds.has(l)) e.push(`${at}.promotionalText.${l}: not in languages`);
|
||||
if (len(t) > CPP_LIMITS.promotionalText) e.push(`${at}.promotionalText.${l}: ${len(t)} > ${CPP_LIMITS.promotionalText}`);
|
||||
}
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
export function validateEvents(events: AppEventDef[] | undefined, langIds: Set<string>): string[] {
|
||||
const e: string[] = [];
|
||||
const names = new Set<string>();
|
||||
for (const [i, ev] of (events ?? []).entries()) {
|
||||
const at = `apple.events[${i}]`;
|
||||
if (!ev.referenceName || len(ev.referenceName) > EVENT_LIMITS.referenceName) e.push(`${at}.referenceName: 1-${EVENT_LIMITS.referenceName} characters`);
|
||||
if (names.has(ev.referenceName)) e.push(`${at}.referenceName: duplicate`);
|
||||
names.add(ev.referenceName);
|
||||
if (!EVENT_BADGES.includes(ev.badge)) e.push(`${at}.badge: ${EVENT_BADGES.join(' | ')}`);
|
||||
if (ev.purpose && !EVENT_PURPOSES.includes(ev.purpose)) e.push(`${at}.purpose: ${EVENT_PURPOSES.join(' | ')}`);
|
||||
if (ev.priority && ev.priority !== 'high' && ev.priority !== 'normal') e.push(`${at}.priority: high | normal`);
|
||||
if (ev.primaryLanguage && !langIds.has(ev.primaryLanguage)) e.push(`${at}.primaryLanguage: not in languages`);
|
||||
const s = ev.schedule;
|
||||
const t = (x: string | undefined) => (x ? Date.parse(x) : NaN);
|
||||
if (!s || [s.publishStart, s.eventStart, s.eventEnd].some(x => Number.isNaN(t(x)))) e.push(`${at}.schedule: publishStart, eventStart, eventEnd as ISO date-times`);
|
||||
else {
|
||||
const dur = t(s.eventEnd) - t(s.eventStart);
|
||||
if (dur < EVENT_LIMITS.minMinutes * 60_000) e.push(`${at}.schedule: an event lasts at least ${EVENT_LIMITS.minMinutes} minutes`);
|
||||
if (dur > EVENT_LIMITS.maxDays * 86_400_000) e.push(`${at}.schedule: an event lasts at most ${EVENT_LIMITS.maxDays} days`);
|
||||
if (t(s.publishStart) > t(s.eventStart)) e.push(`${at}.schedule: publishStart after eventStart`);
|
||||
if (t(s.eventStart) - t(s.publishStart) > EVENT_LIMITS.publishLeadDays * 86_400_000) e.push(`${at}.schedule: published at most ${EVENT_LIMITS.publishLeadDays} days before it starts`);
|
||||
if (s.territories && !s.territories.every(x => /^[A-Z]{3}$/.test(x))) e.push(`${at}.schedule.territories: alpha-3 (USA)`);
|
||||
}
|
||||
if (!ev.listings || !Object.keys(ev.listings).length) e.push(`${at}.listings: at least one language`);
|
||||
for (const [l, x] of Object.entries(ev.listings ?? {})) {
|
||||
if (!langIds.has(l)) e.push(`${at}.listings.${l}: not in languages`);
|
||||
for (const k of ['name', 'shortDescription', 'longDescription'] as const) {
|
||||
if (!x[k]) e.push(`${at}.listings.${l}.${k}: missing`);
|
||||
else if (len(x[k]) > EVENT_LIMITS[k]) e.push(`${at}.listings.${l}.${k}: ${len(x[k])} > ${EVENT_LIMITS[k]}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
/** POST /v1/appCustomProductPages with its first version and one localization per locale (Apple's example shape).
|
||||
* templateVersionId copies the screenshots / previews of an App Store version (optional). */
|
||||
export function cppCreateBody(appId: string, p: CustomProductPageDef, locales: { locale: string; promotionalText?: string }[], templateVersionId?: string) {
|
||||
const locIds = locales.map((_, i) => `\${cpp-loc-${i}}`);
|
||||
return {
|
||||
data: { type: 'appCustomProductPages', attributes: { name: p.name }, relationships: {
|
||||
app: one('apps', appId), ...(templateVersionId ? { appStoreVersionTemplate: one('appStoreVersions', templateVersionId) } : {}),
|
||||
appCustomProductPageVersions: { data: [{ type: 'appCustomProductPageVersions', id: '${cpp-version}' }] } } },
|
||||
included: [
|
||||
{ type: 'appCustomProductPageVersions', id: '${cpp-version}', ...(p.deepLink ? { attributes: { deepLink: p.deepLink } } : {}),
|
||||
relationships: { appCustomProductPageLocalizations: { data: locIds.map(id => ({ type: 'appCustomProductPageLocalizations', id })) } } },
|
||||
...locales.map((l, i) => ({ type: 'appCustomProductPageLocalizations', id: locIds[i], attributes: { locale: l.locale, ...(l.promotionalText ? { promotionalText: l.promotionalText } : {}) } })),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** Localizations of an editable page version to add (POST) or change (PATCH promotional text). Pure. */
|
||||
export function planCppLocales(versionId: string, have: { id: string; locale: string; promotionalText?: string | null }[], want: { locale: string; promotionalText?: string }[]): Req[] {
|
||||
const out: Req[] = [];
|
||||
for (const w of want) {
|
||||
const cur = have.find(h => h.locale === w.locale);
|
||||
if (!cur) out.push({ method: 'POST', path: '/v1/appCustomProductPageLocalizations', note: w.locale,
|
||||
body: { data: { type: 'appCustomProductPageLocalizations', attributes: { locale: w.locale, ...(w.promotionalText ? { promotionalText: w.promotionalText } : {}) }, relationships: { appCustomProductPageVersion: one('appCustomProductPageVersions', versionId) } } } });
|
||||
else if (w.promotionalText !== undefined && (cur.promotionalText ?? '') !== w.promotionalText) out.push({ method: 'PATCH', path: `/v1/appCustomProductPageLocalizations/${cur.id}`, note: `${w.locale} promotional text`,
|
||||
body: { data: { type: 'appCustomProductPageLocalizations', id: cur.id, attributes: { promotionalText: w.promotionalText } } } });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Locales of a page from the config: every language with an App Store locale. */
|
||||
export function cppLocales(p: CustomProductPageDef, langs: Language[]): { locale: string; langId: string; promotionalText?: string }[] {
|
||||
return langs.filter(l => l.apple).map(l => ({ locale: l.apple!, langId: l.id, ...(p.promotionalText?.[l.id] ? { promotionalText: p.promotionalText[l.id] } : {}) }));
|
||||
}
|
||||
|
||||
/** Editable states of a custom product page version / in-app event (can still be changed and uploaded to). */
|
||||
export const CPP_EDITABLE = new Set(['PREPARE_FOR_SUBMISSION', 'REJECTED']);
|
||||
export const EVENT_EDITABLE = new Set(['DRAFT', 'REJECTED']);
|
||||
|
||||
/** POST /v1/appEvents. */
|
||||
export function eventCreateBody(appId: string, ev: AppEventDef, primaryLocale: string, territories: string[]) {
|
||||
return { data: { type: 'appEvents', attributes: {
|
||||
referenceName: ev.referenceName, badge: ev.badge, primaryLocale, priority: (ev.priority ?? 'normal').toUpperCase(),
|
||||
purpose: ev.purpose ?? 'APPROPRIATE_FOR_ALL_USERS', ...(ev.deepLink ? { deepLink: ev.deepLink } : {}), ...(ev.purchaseRequirement ? { purchaseRequirement: ev.purchaseRequirement } : {}),
|
||||
territorySchedules: [{ territories, publishStart: ev.schedule.publishStart, eventStart: ev.schedule.eventStart, eventEnd: ev.schedule.eventEnd }],
|
||||
}, relationships: { app: one('apps', appId) } } };
|
||||
}
|
||||
|
||||
/** Event localizations to add or change. Pure. */
|
||||
export function planEventLocales(eventId: string, have: { id: string; locale: string; name?: string | null; shortDescription?: string | null; longDescription?: string | null }[],
|
||||
want: { locale: string; name: string; shortDescription: string; longDescription: string }[]): Req[] {
|
||||
const out: Req[] = [];
|
||||
for (const w of want) {
|
||||
const cur = have.find(h => h.locale === w.locale);
|
||||
const attrs = { name: w.name, shortDescription: w.shortDescription, longDescription: w.longDescription };
|
||||
if (!cur) out.push({ method: 'POST', path: '/v1/appEventLocalizations', note: w.locale, body: { data: { type: 'appEventLocalizations', attributes: { locale: w.locale, ...attrs }, relationships: { appEvent: one('appEvents', eventId) } } } });
|
||||
else {
|
||||
const changed = Object.fromEntries(Object.entries(attrs).filter(([k, v]) => (cur as Record<string, unknown>)[k] !== v));
|
||||
if (Object.keys(changed).length) out.push({ method: 'PATCH', path: `/v1/appEventLocalizations/${cur.id}`, note: `${w.locale} ${Object.keys(changed).join(', ')}`, body: { data: { type: 'appEventLocalizations', id: cur.id, attributes: changed } } });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Event media size check (card 16:9 landscape, details 9:16 portrait). Pure. */
|
||||
export function checkEventMedia(kind: keyof typeof EVENT_MEDIA, w: number, h: number, format: string): string[] {
|
||||
const [minW, minH, maxW, maxH] = EVENT_MEDIA[kind];
|
||||
const e: string[] = [];
|
||||
if (format !== 'png' && format !== 'jpeg') e.push('PNG or JPEG only');
|
||||
if (w < minW || h < minH || w > maxW || h > maxH) e.push(`${w}x${h}: ${minW}x${minH} to ${maxW}x${maxH}`);
|
||||
if (Math.abs(w / h - minW / minH) > 0.01) e.push(`${w}x${h}: aspect ${kind === 'EVENT_CARD' ? '16:9' : '9:16'}`);
|
||||
return e;
|
||||
}
|
||||
|
||||
/** POST /v1/reviewSubmissionItems for a custom product page version or an in-app event (into a draft submission). */
|
||||
export const reviewItemReq = (submissionId: string, kind: 'appCustomProductPageVersion' | 'appEvent', id: string, label: string): Req => ({
|
||||
method: 'POST', path: '/v1/reviewSubmissionItems', note: label,
|
||||
body: { data: { type: 'reviewSubmissionItems', relationships: { reviewSubmission: one('reviewSubmissions', submissionId), [kind]: one(kind === 'appEvent' ? 'appEvents' : 'appCustomProductPageVersions', id) } } },
|
||||
});
|
||||
|
|
@ -7,9 +7,13 @@
|
|||
// "reviewDemoAccount": { "username": "", "password": "" } }
|
||||
// The demo account for App Review can also come from env: REVIEW_DEMO_USER, REVIEW_DEMO_PASSWORD.
|
||||
// 3. ASC_P8 only: ~/.appstoreconnect/private_keys/AuthKey_<ASC_KEY_ID>.p8 (where Xcode / altool keep it)
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
// With a credential profile (`--profile <name>` or STOREBOUND_PROFILE), the profile comes before all of these:
|
||||
// ~/.storebound/credentials/<name>.json (same four names; relative paths are relative to that file; folder:
|
||||
// STOREBOUND_CREDENTIALS_DIR) or env STOREBOUND_PROFILE_<NAME>_<KEY> (NAME upper case, other characters as _).
|
||||
// Many studios / store accounts from one machine: one profile per account; storebound.workspace.json names them.
|
||||
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { homedir, tmpdir } from 'node:os';
|
||||
import { isAbsolute, join, resolve } from 'node:path';
|
||||
|
||||
export interface ServiceAccount { client_email: string; private_key: string; token_uri?: string }
|
||||
export interface AscKey { keyId: string; issuerId: string; pem: string }
|
||||
|
|
@ -25,8 +29,52 @@ function fileStore(root: string): Store {
|
|||
|
||||
/** 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
|
||||
* 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_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
||||
|
||||
export const profileDir = (): string => process.env.STOREBOUND_CREDENTIALS_DIR || join(homedir(), '.storebound', 'credentials');
|
||||
const profileEnvName = (profile: string, key: string): string => `STOREBOUND_PROFILE_${profile.toUpperCase().replace(/[^A-Z0-9]/g, '_')}_${key}`;
|
||||
|
||||
/**
|
||||
* The credentials of one profile as env values (never printed). Env STOREBOUND_PROFILE_<NAME>_<KEY> wins over the
|
||||
* profile file; a relative key path in the file is relative to the file. Throws on a bad name or an unreadable file.
|
||||
*/
|
||||
export function profileEnv(profile: string): Record<string, string> {
|
||||
if (!PROFILE_RE.test(profile)) throw new Error(`credential profile "${profile}": letters, digits, . _ - (max 64)`);
|
||||
const file = join(profileDir(), `${profile}.json`);
|
||||
let stored: Store = {};
|
||||
if (existsSync(file)) {
|
||||
try { stored = JSON.parse(readFileSync(file, 'utf8')) as Store; } catch (e) { throw new Error(`credential profile ${profile}: ${file}: ${(e as Error).message}`); }
|
||||
}
|
||||
const out: Record<string, string> = {};
|
||||
for (const k of PROFILE_KEYS) {
|
||||
const env = process.env[profileEnvName(profile, k)];
|
||||
const v = env || (typeof stored[k] === 'string' ? stored[k] as string : '');
|
||||
if (!v) continue;
|
||||
// a path in the file: relative to the profile folder (inline JSON / PEM stays as it is)
|
||||
const isPath = !env && !/^\s*\{/.test(v) && !/BEGIN PRIVATE KEY/.test(v) && (k === 'PLAY_SERVICE_ACCOUNT' || k === 'ASC_P8');
|
||||
out[k] = isPath && !isAbsolute(v) && !v.startsWith('~') ? resolve(profileDir(), v) : v;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Which stores a profile can reach, and where it comes from. No values. */
|
||||
export function profileStatus(profile: string): { profile: string; source: 'file' | 'env' | 'missing' | 'invalid'; apple: boolean; play: boolean; error?: string } {
|
||||
try {
|
||||
const env = profileEnv(profile);
|
||||
const fromEnv = PROFILE_KEYS.some(k => !!process.env[profileEnvName(profile, k)]);
|
||||
const source = fromEnv ? 'env' : existsSync(join(profileDir(), `${profile}.json`)) ? 'file' : 'missing';
|
||||
return { profile, source, apple: !!(env.ASC_KEY_ID && env.ASC_ISSUER_ID), play: !!env.PLAY_SERVICE_ACCOUNT };
|
||||
} catch (e) {
|
||||
return { profile, source: 'invalid', apple: false, play: false, error: (e as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
function value(root: string, name: string): string | undefined {
|
||||
const profile = process.env.STOREBOUND_PROFILE;
|
||||
if (profile) { const v = profileEnv(profile)[name]; if (v) return v; }
|
||||
const env = process.env[name];
|
||||
if (env) return env;
|
||||
const v = fileStore(root)[name];
|
||||
|
|
@ -83,3 +131,39 @@ export const maskUser = (u: string): string => {
|
|||
return at > 0 ? `${u[0]}***${u.slice(at)}` : `${u[0] ?? ''}***`;
|
||||
};
|
||||
export const maskSecret = (s: string): string => (s ? '********' : '(empty)');
|
||||
|
||||
/** The App Store Connect key as a file, for tools that want a path (xcodebuild -authenticationKeyPath, altool).
|
||||
* A path in ASC_P8 (or the usual ~/.appstoreconnect location) is used as is; inline PEM content goes to a private
|
||||
* temporary folder (0700 / 0600) that `cleanup` removes. Commands show the path as $ASC_P8. */
|
||||
export function ascKeyFile(root: string): { keyPath: string; keyId: string; issuerId: string; cleanup: () => void } {
|
||||
const k = ascKey(root);
|
||||
const raw = value(root, 'ASC_P8') ?? join(homedir(), '.appstoreconnect/private_keys', `AuthKey_${k.keyId}.p8`);
|
||||
if (!/BEGIN PRIVATE KEY/.test(raw)) return { keyPath: raw.replace(/^~(?=\/)/, homedir()), keyId: k.keyId, issuerId: k.issuerId, cleanup: () => {} };
|
||||
const dir = mkdtempSync(join(tmpdir(), 'storebound-key-'));
|
||||
chmodSync(dir, 0o700);
|
||||
const keyPath = join(dir, `AuthKey_${k.keyId}.p8`);
|
||||
writeFileSync(keyPath, k.pem, { mode: 0o600 });
|
||||
return { keyPath, keyId: k.keyId, issuerId: k.issuerId, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
|
||||
}
|
||||
|
||||
export interface AndroidSigning { storeFile: string; storePassword: string; keyAlias: string; keyPassword: string }
|
||||
|
||||
/** Android upload key for `play build` (env or .storebound/credentials.json): ANDROID_KEYSTORE (path to the .jks /
|
||||
* .keystore), ANDROID_KEYSTORE_PASSWORD, ANDROID_KEY_ALIAS, ANDROID_KEY_PASSWORD (default: the keystore password).
|
||||
* null when no keystore is set (the project's own signingConfig signs then, e.g. Flutter's key.properties). */
|
||||
export function androidSigning(root: string): AndroidSigning | null {
|
||||
const storeFile = value(root, 'ANDROID_KEYSTORE');
|
||||
if (!storeFile) return null;
|
||||
const storePassword = value(root, 'ANDROID_KEYSTORE_PASSWORD'), keyAlias = value(root, 'ANDROID_KEY_ALIAS');
|
||||
if (!storePassword || !keyAlias) throw new Error('ANDROID_KEYSTORE is set but ANDROID_KEYSTORE_PASSWORD / ANDROID_KEY_ALIAS are not (env or .storebound/credentials.json)');
|
||||
const abs = storeFile.replace(/^~(?=\/)/, homedir());
|
||||
return { storeFile: abs.startsWith('/') ? abs : join(root, abs), storePassword, keyAlias, keyPassword: value(root, 'ANDROID_KEY_PASSWORD') ?? storePassword };
|
||||
}
|
||||
|
||||
/** App Store Connect vendor number for sales and finance reports (Payments and Financial Reports, top left): the
|
||||
* credential profile, env ASC_VENDOR_NUMBER, else "ASC_VENDOR_NUMBER" in .storebound/credentials.json. An account
|
||||
* id, so never in the config. */
|
||||
export function ascVendorNumber(root: string): string | null {
|
||||
const v = value(root, 'ASC_VENDOR_NUMBER');
|
||||
return v && /^\d{5,12}$/.test(v.trim()) ? v.trim() : null;
|
||||
}
|
||||
|
|
|
|||
57
cli/lib/csr.ts
Normal file
57
cli/lib/csr.ts
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
// A certificate signing request (PKCS #10, RFC 2986) built with node:crypto and a minimal DER encoder: no openssl,
|
||||
// no Keychain Access. The private key is generated here and only ever written to a 0600 file in .storebound/signing/
|
||||
// (and, when asked, imported into a keychain); the CSR carries only the public key.
|
||||
import { createPrivateKey, createPublicKey, generateKeyPairSync, type KeyObject, sign } from 'node:crypto';
|
||||
|
||||
function derLen(n: number): Buffer {
|
||||
if (n < 0x80) return Buffer.from([n]);
|
||||
const bytes: number[] = [];
|
||||
for (let v = n; v > 0; v = Math.floor(v / 256)) bytes.unshift(v & 255);
|
||||
return Buffer.from([0x80 | bytes.length, ...bytes]);
|
||||
}
|
||||
export const der = (tag: number, ...parts: Buffer[]): Buffer => { const body = Buffer.concat(parts); return Buffer.concat([Buffer.from([tag]), derLen(body.length), body]); };
|
||||
const seq = (...p: Buffer[]) => der(0x30, ...p);
|
||||
const set = (...p: Buffer[]) => der(0x31, ...p);
|
||||
|
||||
/** DER object identifier from its arcs, e.g. [2, 5, 4, 3] (commonName). */
|
||||
export function oid(arcs: number[]): Buffer {
|
||||
const [a, b, ...rest] = arcs as [number, number, ...number[]];
|
||||
const out = [40 * a + b];
|
||||
for (const n of rest) {
|
||||
const groups: number[] = [];
|
||||
for (let v = n; ; v = Math.floor(v / 128)) { groups.unshift(v & 127); if (v < 128) break; }
|
||||
out.push(...groups.map((g, i) => (i < groups.length - 1 ? g | 128 : g)));
|
||||
}
|
||||
return der(0x06, Buffer.from(out));
|
||||
}
|
||||
|
||||
const OID = { commonName: [2, 5, 4, 3], countryName: [2, 5, 4, 6], emailAddress: [1, 2, 840, 113549, 1, 9, 1], sha256WithRSA: [1, 2, 840, 113549, 1, 1, 11] };
|
||||
|
||||
export interface CsrSubject { commonName: string; country?: string; email?: string }
|
||||
|
||||
/** PEM CSR for the key. Subject: CN (and C / emailAddress when given; Apple ignores them for API-made certificates). */
|
||||
export function buildCsr(key: KeyObject, subject: CsrSubject): string {
|
||||
const rdn = (o: number[], value: Buffer) => set(seq(oid(o), value));
|
||||
const name = seq(
|
||||
...(subject.email ? [rdn(OID.emailAddress, der(0x16, Buffer.from(subject.email, 'ascii')))] : []),
|
||||
rdn(OID.commonName, der(0x0c, Buffer.from(subject.commonName, 'utf8'))),
|
||||
...(subject.country ? [rdn(OID.countryName, der(0x13, Buffer.from(subject.country, 'ascii')))] : []),
|
||||
);
|
||||
const spki = createPublicKey(key).export({ type: 'spki', format: 'der' });
|
||||
const info = seq(der(0x02, Buffer.from([0])), name, spki, der(0xa0));
|
||||
const sig = sign('sha256', info, key);
|
||||
const csr = seq(info, seq(oid(OID.sha256WithRSA), der(0x05)), der(0x03, Buffer.from([0]), sig));
|
||||
return `-----BEGIN CERTIFICATE REQUEST-----\n${csr.toString('base64').match(/.{1,64}/g)!.join('\n')}\n-----END CERTIFICATE REQUEST-----\n`;
|
||||
}
|
||||
|
||||
/** New RSA 2048 key (Apple's signing certificates use RSA 2048) as PKCS #8 PEM plus its KeyObject. */
|
||||
export function newSigningKey(): { pem: string; key: KeyObject } {
|
||||
const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
|
||||
return { pem: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), key: privateKey };
|
||||
}
|
||||
|
||||
/** The CSR's base64 body (what the App Store Connect API takes as csrContent). */
|
||||
export const csrContent = (pem: string): string => pem.replace(/-----[^-]+-----/g, '').replace(/\s+/g, '');
|
||||
|
||||
/** SPKI (DER, base64) of a private key PEM: matches a certificate's public key. */
|
||||
export const spkiOfKey = (pem: string): string => createPublicKey(createPrivateKey(pem)).export({ type: 'spki', format: 'der' }).toString('base64');
|
||||
32
cli/lib/diff.ts
Normal file
32
cli/lib/diff.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
// Line diff for "pull" commands (live store text vs the local files). Pure, no dependency: longest common subsequence
|
||||
// over lines, printed like a unified diff without hunks (" " same, "-" only local, "+" only on the store).
|
||||
|
||||
export function lineDiff(before: string, after: string): string[] {
|
||||
const a = before.split('\n'), b = after.split('\n');
|
||||
if (a.length * b.length > 4_000_000) return [...a.map(l => `-${l}`), ...b.map(l => `+${l}`)];
|
||||
const n = a.length, m = b.length;
|
||||
const lcs: Uint32Array[] = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
|
||||
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) lcs[i]![j] = a[i] === b[j] ? lcs[i + 1]![j + 1]! + 1 : Math.max(lcs[i + 1]![j]!, lcs[i]![j + 1]!);
|
||||
const out: string[] = [];
|
||||
let i = 0, j = 0;
|
||||
while (i < n && j < m) {
|
||||
if (a[i] === b[j]) { out.push(` ${a[i]}`); i++; j++; }
|
||||
else if (lcs[i + 1]![j]! >= lcs[i]![j + 1]!) out.push(`-${a[i++]}`);
|
||||
else out.push(`+${b[j++]}`);
|
||||
}
|
||||
while (i < n) out.push(`-${a[i++]}`);
|
||||
while (j < m) out.push(`+${b[j++]}`);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Only the changed lines with `context` unchanged lines around them ("..." between gaps). Empty when equal. */
|
||||
export function compactDiff(before: string, after: string, context = 2): string[] {
|
||||
const d = lineDiff(before, after);
|
||||
if (!d.some(l => l[0] !== ' ')) return [];
|
||||
const keep = new Set<number>();
|
||||
d.forEach((l, i) => { if (l[0] !== ' ') for (let k = i - context; k <= i + context; k++) keep.add(k); });
|
||||
const out: string[] = [];
|
||||
let last = -1;
|
||||
d.forEach((l, i) => { if (!keep.has(i)) return; if (last >= 0 && i > last + 1) out.push('...'); out.push(l); last = i; });
|
||||
return out;
|
||||
}
|
||||
180
cli/lib/gradle.ts
Normal file
180
cli/lib/gradle.ts
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
// Android release builds: find the Gradle project (native, Capacitor, React Native, Flutter, Unity export), the
|
||||
// bundle task, the signing environment (the upload key from env / .storebound, handed to Gradle as injected
|
||||
// properties through ORG_GRADLE_PROJECT_* variables, so passwords never appear on a command line), and read
|
||||
// package / versionCode / versionName back from the built AAB (its manifest is protocol buffers, aapt2 format).
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join, relative } from 'node:path';
|
||||
import type { AndroidSigning } from './credentials';
|
||||
import { zipEntries, zipRead } from './zip';
|
||||
|
||||
export interface PlayBuildConfig {
|
||||
/** Gradle project folder (with gradlew / settings.gradle), relative to the config. Default: android/, else the root. */
|
||||
dir?: string;
|
||||
/** Application module. Default app (Unity export: launcher). */
|
||||
module?: string;
|
||||
/** Product flavor, e.g. "prod" -> bundleProdRelease. */
|
||||
flavor?: string;
|
||||
}
|
||||
|
||||
export function validatePlayBuild(b: PlayBuildConfig | undefined): string[] {
|
||||
if (!b) return [];
|
||||
const e: string[] = [];
|
||||
if (b.module !== undefined && !/^[A-Za-z0-9_-]+(:[A-Za-z0-9_-]+)*$/.test(b.module)) e.push('play.build.module: a Gradle module name like app');
|
||||
if (b.flavor !== undefined && !/^[A-Za-z][A-Za-z0-9]*$/.test(b.flavor)) e.push('play.build.flavor: a product flavor name like prod');
|
||||
return e;
|
||||
}
|
||||
|
||||
export type AndroidFramework = 'flutter' | 'capacitor' | 'react-native' | 'unity' | 'native';
|
||||
|
||||
export interface GradleTarget { framework: AndroidFramework; dir: string; module: string; task: string; notes: string[] }
|
||||
|
||||
const isGradleDir = (d: string): boolean => ['settings.gradle', 'settings.gradle.kts'].some(f => existsSync(join(d, f)));
|
||||
|
||||
/** Finds the Gradle project. `root` is the folder of storebound.config.ts. */
|
||||
export function pickGradle(root: string, cfg: PlayBuildConfig = {}): GradleTarget {
|
||||
const notes: string[] = [];
|
||||
const framework: AndroidFramework = existsSync(join(root, 'pubspec.yaml')) ? 'flutter'
|
||||
: ['capacitor.config.ts', 'capacitor.config.json', 'capacitor.config.js'].some(f => existsSync(join(root, f))) ? 'capacitor'
|
||||
: (() => { try { const p = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')); return !!(p.dependencies?.['react-native'] ?? p.devDependencies?.['react-native']); } catch { return false; } })() ? 'react-native'
|
||||
: 'native';
|
||||
const dirs = cfg.dir ? [join(root, cfg.dir)] : [join(root, 'android'), root];
|
||||
let dir = dirs.find(isGradleDir);
|
||||
if (!dir) throw new Error(`no Gradle project (settings.gradle) in ${dirs.map(d => relative(root, d) || '.').join(' or ')}: set play.build.dir${framework === 'capacitor' ? ' (or npx cap add android)' : ''}`);
|
||||
const unity = existsSync(join(dir, 'launcher')) && existsSync(join(dir, 'unityLibrary'));
|
||||
const fw: AndroidFramework = unity ? 'unity' : framework;
|
||||
const module = cfg.module ?? (unity ? 'launcher' : 'app');
|
||||
if (!existsSync(join(dir, ...module.split(':')))) throw new Error(`module "${module}" not found in ${relative(root, dir) || '.'} (set play.build.module)`);
|
||||
const flavor = cfg.flavor ? cfg.flavor[0]!.toUpperCase() + cfg.flavor.slice(1) : '';
|
||||
if (fw === 'capacitor') notes.push('Capacitor: run npx cap sync android after the web build so the bundle has the current web assets');
|
||||
if (fw === 'unity') notes.push('Unity: export the Gradle project from Unity (Build Settings > Android > Export Project) before each build');
|
||||
if (fw === 'flutter') notes.push('Flutter: built with flutter build appbundle (build number = versionCode)');
|
||||
if (!existsSync(join(dir, process.platform === 'win32' ? 'gradlew.bat' : 'gradlew'))) notes.push('no Gradle wrapper (gradlew) in the project: using gradle from PATH');
|
||||
return { framework: fw, dir, module, task: `:${module}:bundle${flavor}Release`, notes };
|
||||
}
|
||||
|
||||
/** Command line of the release bundle build. Version code / name go in as injected properties (the same ones Android
|
||||
* Studio uses) and as -PversionCode / -PversionName for build files that read those. */
|
||||
export function gradleArgs(t: GradleTarget, o: { versionCode?: number; versionName?: string; flavor?: string; hasWrapper: boolean }): string[] {
|
||||
if (t.framework === 'flutter')
|
||||
return ['flutter', 'build', 'appbundle', '--release', ...(o.flavor ? ['--flavor', o.flavor] : []), ...(o.versionCode ? ['--build-number', String(o.versionCode)] : []), ...(o.versionName ? ['--build-name', o.versionName] : [])];
|
||||
return [o.hasWrapper ? (process.platform === 'win32' ? 'gradlew.bat' : './gradlew') : 'gradle', t.task, '--no-daemon', '--console=plain',
|
||||
...(o.versionCode ? [`-Pandroid.injected.version.code=${o.versionCode}`, `-PversionCode=${o.versionCode}`] : []),
|
||||
...(o.versionName ? [`-Pandroid.injected.version.name=${o.versionName}`, `-PversionName=${o.versionName}`] : [])];
|
||||
}
|
||||
|
||||
/** Environment that hands the upload key to the Android Gradle plugin (injected signing properties). */
|
||||
export function signingEnv(s: AndroidSigning | null): Record<string, string> {
|
||||
if (!s) return {};
|
||||
return {
|
||||
'ORG_GRADLE_PROJECT_android.injected.signing.store.file': s.storeFile,
|
||||
'ORG_GRADLE_PROJECT_android.injected.signing.store.password': s.storePassword,
|
||||
'ORG_GRADLE_PROJECT_android.injected.signing.key.alias': s.keyAlias,
|
||||
'ORG_GRADLE_PROJECT_android.injected.signing.key.password': s.keyPassword,
|
||||
};
|
||||
}
|
||||
|
||||
/** AABs written since `since` (ms) below the folders a build writes to. Newest first. */
|
||||
export function findBundles(dirs: string[], since: number): string[] {
|
||||
const out: { f: string; t: number }[] = [];
|
||||
const walk = (d: string, depth: number): void => {
|
||||
let names: string[];
|
||||
try { names = readdirSync(d); } catch { return; }
|
||||
for (const n of names) {
|
||||
const p = join(d, n);
|
||||
let st;
|
||||
try { st = statSync(p); } catch { continue; }
|
||||
if (st.isDirectory()) { if (depth > 0 && n !== 'intermediates' && n !== 'tmp') walk(p, depth - 1); }
|
||||
else if (n.endsWith('.aab') && st.mtimeMs >= since) out.push({ f: p, t: st.mtimeMs });
|
||||
}
|
||||
};
|
||||
for (const d of dirs) walk(d, 6);
|
||||
return out.sort((a, b) => b.t - a.t).map(x => x.f);
|
||||
}
|
||||
|
||||
// ---- AAB manifest (aapt2 protobuf XmlNode) ----
|
||||
|
||||
type Field = { no: number; wire: number; v: number | Buffer };
|
||||
|
||||
function fields(b: Buffer): Field[] | null {
|
||||
const out: Field[] = [];
|
||||
let i = 0;
|
||||
const varint = (): number => {
|
||||
let r = 0, mul = 1;
|
||||
for (let k = 0; k < 10; k++) {
|
||||
if (i >= b.length) throw new Error('eof');
|
||||
const x = b[i++]!;
|
||||
r += (x & 127) * mul;
|
||||
if (!(x & 128)) return r;
|
||||
mul *= 128;
|
||||
}
|
||||
throw new Error('varint');
|
||||
};
|
||||
try {
|
||||
while (i < b.length) {
|
||||
const key = varint(), no = Math.floor(key / 8), wire = key & 7;
|
||||
if (no === 0) return null;
|
||||
if (wire === 0) out.push({ no, wire, v: varint() });
|
||||
else if (wire === 2) { const n = varint(); if (i + n > b.length) return null; out.push({ no, wire, v: b.subarray(i, i + n) }); i += n; }
|
||||
else if (wire === 5) { i += 4; } else if (wire === 1) { i += 8; } else return null;
|
||||
}
|
||||
} catch { return null; }
|
||||
return i === b.length ? out : null;
|
||||
}
|
||||
|
||||
/** Attributes (name -> raw value) of every element in an aapt2 proto XML, element name first. */
|
||||
function elements(b: Buffer, out: { name: string; attrs: Record<string, string> }[] = [], depth = 0): { name: string; attrs: Record<string, string> }[] {
|
||||
// XmlNode { XmlElement element = 1; string text = 2; ... } XmlElement { ns 1; string name = 4; XmlAttribute attribute = 5; XmlNode child = 6 }
|
||||
// XmlAttribute { string namespace_uri = 1; string name = 2; string value = 3; ...; Item compiled_item = 6 }
|
||||
if (depth > 64) return out;
|
||||
const node = fields(b);
|
||||
const el = node?.find(f => f.no === 1 && f.wire === 2);
|
||||
if (!el) return out;
|
||||
const ef = fields(el.v as Buffer) ?? [];
|
||||
const name = (ef.find(f => f.no === 4)?.v as Buffer | undefined)?.toString('utf8') ?? '';
|
||||
const attrs: Record<string, string> = {};
|
||||
for (const a of ef.filter(f => f.no === 5 && f.wire === 2)) {
|
||||
const af = fields(a.v as Buffer) ?? [];
|
||||
const an = (af.find(f => f.no === 2)?.v as Buffer | undefined)?.toString('utf8');
|
||||
let av = (af.find(f => f.no === 3)?.v as Buffer | undefined)?.toString('utf8') ?? '';
|
||||
if (!av) {
|
||||
// compiled_item { Prim prim = 7 { int_decimal_value = 6 ... } } or { Str str = 2 { value = 1 } }
|
||||
const item = fields((af.find(f => f.no === 6)?.v as Buffer | undefined) ?? Buffer.alloc(0)) ?? [];
|
||||
const prim = fields((item.find(f => f.no === 7)?.v as Buffer | undefined) ?? Buffer.alloc(0)) ?? [];
|
||||
const n = prim.find(f => f.wire === 0);
|
||||
const str = fields((item.find(f => f.no === 2)?.v as Buffer | undefined) ?? Buffer.alloc(0)) ?? [];
|
||||
av = n ? String(n.v) : (str.find(f => f.no === 1)?.v as Buffer | undefined)?.toString('utf8') ?? '';
|
||||
}
|
||||
if (an) attrs[an] = av;
|
||||
}
|
||||
out.push({ name, attrs });
|
||||
for (const c of ef.filter(f => f.no === 6 && f.wire === 2)) elements(c.v as Buffer, out, depth + 1);
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface AabInfo { packageName: string; versionCode: number; versionName?: string; minSdk?: number; targetSdk?: number }
|
||||
|
||||
/** Package, versionCode and versionName of an Android App Bundle (base/manifest/AndroidManifest.xml). */
|
||||
export function aabInfo(aab: string | Buffer): AabInfo {
|
||||
const e = zipEntries(aab).find(x => x.name === 'base/manifest/AndroidManifest.xml');
|
||||
if (!e) throw new Error('not an Android App Bundle (no base/manifest/AndroidManifest.xml)');
|
||||
const els = elements(zipRead(aab, e));
|
||||
const m = els.find(x => x.name === 'manifest');
|
||||
if (!m?.attrs.package || !m.attrs.versionCode) throw new Error('AAB manifest without package / versionCode');
|
||||
const sdk = els.find(x => x.name === 'uses-sdk')?.attrs;
|
||||
return { packageName: m.attrs.package, versionCode: Number(m.attrs.versionCode), versionName: m.attrs.versionName || undefined,
|
||||
minSdk: sdk?.minSdkVersion ? Number(sdk.minSdkVersion) : undefined, targetSdk: sdk?.targetSdkVersion ? Number(sdk.targetSdkVersion) : undefined };
|
||||
}
|
||||
|
||||
/** Builds an aapt2-style proto manifest (tests and fixtures). */
|
||||
export function encodeProtoManifest(els: { name: string; attrs: Record<string, string> }[]): Buffer {
|
||||
const vint = (n: number): Buffer => { const o: number[] = []; do { let x = n % 128; n = Math.floor(n / 128); if (n) x |= 128; o.push(x); } while (n); return Buffer.from(o); };
|
||||
const ld = (no: number, b: Buffer): Buffer => Buffer.concat([vint(no * 8 + 2), vint(b.length), b]);
|
||||
const s = (no: number, t: string) => ld(no, Buffer.from(t, 'utf8'));
|
||||
const element = (i: number): Buffer => {
|
||||
const e = els[i]!;
|
||||
const attrs = Object.entries(e.attrs).map(([k, v]) => ld(5, Buffer.concat([s(1, 'http://schemas.android.com/apk/res/android'), s(2, k), s(3, v)])));
|
||||
const child = i + 1 < els.length ? [ld(6, ld(1, element(i + 1)))] : [];
|
||||
return Buffer.concat([s(4, e.name), ...attrs, ...child]);
|
||||
};
|
||||
return ld(1, element(0));
|
||||
}
|
||||
200
cli/lib/identity.ts
Normal file
200
cli/lib/identity.ts
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
// One app card per product, across studios and store accounts: the pairing rules the desktop app (apps/desktop) and
|
||||
// the CLI workspace (`storebound ws`, cli/lib/workspace.ts) share. Pure, so tests pin every rule
|
||||
// (apps/desktop/tests/identity.test.ts, tests/workspace.test.ts).
|
||||
//
|
||||
// Inputs: app folders (with the store ids of their config), the apps each store account can see (`apps list`), and
|
||||
// the owner's overrides (manual pairs / unpairs, links of a store app to a folder, studio moves, the ignore list).
|
||||
// Order of matching:
|
||||
// 1. a folder takes the store apps its config names (explicit link > App Store app id > bundle id / package name),
|
||||
// preferring the accounts mapped to the folder;
|
||||
// 2. the remaining store apps pair iOS + Android: manual pairs, then the same bundle id and package name, then a
|
||||
// close id (".ios" / ".android" suffixes, case, punctuation) or the same name; unpairs block an automatic pair;
|
||||
// 3. what is left is a single-platform store-only app.
|
||||
// A store-only app is read through a "store target" (store:ios:<account>:<app id>:<bundle>;android:<account>:<package>).
|
||||
import type { ProjectSummary, StoreApp } from './desktop-protocol';
|
||||
|
||||
/** An app folder as both front ends know it (the desktop's Project carries more fields). */
|
||||
export interface IdProject { id: string; path: string; name: string; playAccount: string | null; appleAccount: string | null }
|
||||
/** A store account: an id (16 hex) and its studio. */
|
||||
export interface IdAccount { id: string; studio?: string | null }
|
||||
|
||||
export interface Pair { ios: string; android: string }
|
||||
export interface Overrides {
|
||||
pairs: Pair[];
|
||||
unpairs: Pair[];
|
||||
links: { key: string; project: string }[];
|
||||
appStudio: { key: string; studio: string }[];
|
||||
ignored: string[];
|
||||
}
|
||||
export const NO_OVERRIDES: Overrides = { pairs: [], unpairs: [], links: [], appStudio: [], ignored: [] };
|
||||
|
||||
/** One app record of one store account. */
|
||||
export interface StoreRef { key: string; account: string; store: 'ios' | 'android'; app: StoreApp }
|
||||
|
||||
export type Pairing = 'folder' | 'manual' | 'id' | 'close' | 'name' | 'single';
|
||||
|
||||
export interface UnifiedApp<P extends IdProject = IdProject> {
|
||||
/** Route and list key: the project id, else the store target. */
|
||||
key: string;
|
||||
/** What reads use: the project id, else the store target ("store:..."). */
|
||||
target: string;
|
||||
name: string;
|
||||
project: P | null;
|
||||
ios: StoreRef | null;
|
||||
android: StoreRef | null;
|
||||
studio: string | null;
|
||||
pairing: Pairing;
|
||||
/** The keys an "ignore" puts on the list ("project:<id>" or "app:<store key>"). */
|
||||
ignoreKeys: string[];
|
||||
ignored: boolean;
|
||||
/** Store icon (data URL) when the folder has none. */
|
||||
storeIcon: string | null;
|
||||
}
|
||||
|
||||
export const refKey = (account: string, a: StoreApp): string => `${a.store}:${account}:${a.id}`;
|
||||
|
||||
/** Store target of a store-only app. */
|
||||
export function storeTarget(ios: StoreRef | null, android: StoreRef | null): string {
|
||||
const parts: string[] = [];
|
||||
if (ios) parts.push(`ios:${ios.account}:${ios.app.id}:${ios.app.bundleId}`);
|
||||
if (android) parts.push(`android:${android.account}:${android.app.id}`);
|
||||
return `store:${parts.join(';')}`;
|
||||
}
|
||||
|
||||
/** "com.example.Puzzle.ios" -> "comexamplepuzzle": ids that differ only by a platform suffix, case or punctuation. */
|
||||
export function normId(id: string): string {
|
||||
return id.toLowerCase().replace(/[._-](ios|iphone|android|droid|app)$/g, '').replace(/[^a-z0-9]/g, '');
|
||||
}
|
||||
export const normName = (n: string): string => n.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]/g, '');
|
||||
|
||||
const samePair = (p: Pair, ios: string, android: string) => p.ios === ios && p.android === android;
|
||||
|
||||
export interface BuildInput<P extends IdProject = IdProject> {
|
||||
projects: P[];
|
||||
/** Store ids of each folder's config (from the offline portfolio read). */
|
||||
summaryOf: (p: P) => ProjectSummary | null | undefined;
|
||||
accounts: IdAccount[];
|
||||
/** The last app list of each account. */
|
||||
storeApps: { account: string; apps: StoreApp[] }[];
|
||||
overrides: Overrides;
|
||||
}
|
||||
|
||||
export function buildApps<P extends IdProject>(i: BuildInput<P>): UnifiedApp<P>[] {
|
||||
const o = i.overrides;
|
||||
const ignoredAccounts = new Set(o.ignored.filter(x => x.startsWith('account:')).map(x => x.slice(8)));
|
||||
const accountStudio = new Map(i.accounts.map(a => [a.id, a.studio ?? null] as const));
|
||||
const known = new Set(i.accounts.map(a => a.id));
|
||||
// every store app of every (not ignored) account
|
||||
const refs: StoreRef[] = [];
|
||||
for (const s of i.storeApps) {
|
||||
if (!known.has(s.account) || ignoredAccounts.has(s.account)) continue;
|
||||
for (const app of s.apps) refs.push({ key: refKey(s.account, app), account: s.account, store: app.store, app });
|
||||
}
|
||||
const used = new Set<string>();
|
||||
const take = (r: StoreRef | null | undefined): StoreRef | null => { if (!r || used.has(r.key)) return null; used.add(r.key); return r; };
|
||||
const studioOverride = new Map(o.appStudio.map(x => [x.key, x.studio] as const));
|
||||
const ignored = new Set(o.ignored);
|
||||
const out: UnifiedApp<P>[] = [];
|
||||
|
||||
// 1. folders
|
||||
for (const p of i.projects) {
|
||||
const s = i.summaryOf(p);
|
||||
const mine = (r: StoreRef) => r.account === (r.store === 'ios' ? p.appleAccount : p.playAccount);
|
||||
const rank = (rs: StoreRef[]) => [...rs].sort((a, b) => Number(mine(b)) - Number(mine(a)));
|
||||
const linked = o.links.filter(l => l.project === p.id).map(l => refs.find(r => r.key === l.key)).filter((r): r is StoreRef => !!r && !used.has(r.key));
|
||||
let ios = take(linked.find(r => r.store === 'ios'));
|
||||
let android = take(linked.find(r => r.store === 'android'));
|
||||
if (!ios && s?.apple) {
|
||||
const free = refs.filter(r => r.store === 'ios' && !used.has(r.key) && !o.links.some(l => l.key === r.key));
|
||||
ios = take(rank(free.filter(r => s.apple!.appId && r.app.id === s.apple!.appId))[0] ?? rank(free.filter(r => r.app.bundleId === s.apple!.bundleId))[0]);
|
||||
}
|
||||
if (!android && s?.play) {
|
||||
const free = refs.filter(r => r.store === 'android' && !used.has(r.key) && !o.links.some(l => l.key === r.key));
|
||||
android = take(rank(free.filter(r => r.app.id === s.play!.packageName))[0]);
|
||||
}
|
||||
const studio = studioOverride.get(`project:${p.id}`)
|
||||
?? (p.appleAccount && accountStudio.get(p.appleAccount)) ?? (p.playAccount && accountStudio.get(p.playAccount))
|
||||
?? (ios && accountStudio.get(ios.account)) ?? (android && accountStudio.get(android.account)) ?? null;
|
||||
out.push({
|
||||
key: p.id, target: p.id, name: p.name, project: p, ios, android, studio, pairing: 'folder',
|
||||
ignoreKeys: [`project:${p.id}`], ignored: ignored.has(`project:${p.id}`), storeIcon: ios?.app.icon ?? android?.app.icon ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
// 2. pairs among the remaining store apps
|
||||
const freeIos = () => refs.filter(r => r.store === 'ios' && !used.has(r.key));
|
||||
const freeAndroid = () => refs.filter(r => r.store === 'android' && !used.has(r.key));
|
||||
const blocked = (a: StoreRef, b: StoreRef) => o.unpairs.some(p => samePair(p, a.key, b.key));
|
||||
const sameStudio = (a: StoreRef, b: StoreRef) => (accountStudio.get(a.account) ?? null) === (accountStudio.get(b.account) ?? null);
|
||||
const pairs: [StoreRef, StoreRef, Pairing][] = [];
|
||||
for (const m of o.pairs) {
|
||||
const a = freeIos().find(r => r.key === m.ios), b = freeAndroid().find(r => r.key === m.android);
|
||||
if (a && b) { take(a); take(b); pairs.push([a, b, 'manual']); }
|
||||
}
|
||||
const auto = (how: Pairing, match: (a: StoreRef, b: StoreRef) => boolean) => {
|
||||
for (const a of freeIos()) {
|
||||
const cands = freeAndroid().filter(b => !blocked(a, b) && match(a, b)).sort((x, y) => Number(sameStudio(a, y)) - Number(sameStudio(a, x)));
|
||||
const b = cands[0];
|
||||
if (b) { take(a); take(b); pairs.push([a, b, how]); }
|
||||
}
|
||||
};
|
||||
auto('id', (a, b) => a.app.bundleId === b.app.id);
|
||||
auto('close', (a, b) => normId(a.app.bundleId) !== '' && normId(a.app.bundleId) === normId(b.app.id));
|
||||
auto('name', (a, b) => normName(a.app.name) !== '' && normName(a.app.name) === normName(b.app.name));
|
||||
|
||||
const storeOnly = (ios: StoreRef | null, android: StoreRef | null, pairing: Pairing) => {
|
||||
const target = storeTarget(ios, android);
|
||||
const keys = [ios, android].filter((r): r is StoreRef => !!r).map(r => r.key);
|
||||
const studio = keys.map(k => studioOverride.get(k)).find(Boolean)
|
||||
?? (ios && accountStudio.get(ios.account)) ?? (android && accountStudio.get(android.account)) ?? null;
|
||||
out.push({
|
||||
key: target, target, name: ios?.app.name ?? android?.app.name ?? '?', project: null, ios, android, studio, pairing,
|
||||
ignoreKeys: keys.map(k => `app:${k}`), ignored: keys.some(k => ignored.has(`app:${k}`)), storeIcon: ios?.app.icon ?? android?.app.icon ?? null,
|
||||
});
|
||||
};
|
||||
for (const [a, b, how] of pairs) storeOnly(a, b, how);
|
||||
// 3. singles
|
||||
for (const r of refs) if (!used.has(r.key)) { used.add(r.key); storeOnly(r.store === 'ios' ? r : null, r.store === 'android' ? r : null, 'single'); }
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Candidates to pair a single-platform app with (the other store's single apps), closest first. */
|
||||
export function pairCandidates<P extends IdProject>(app: UnifiedApp<P>, all: UnifiedApp<P>[]): UnifiedApp<P>[] {
|
||||
if (app.project || (app.ios && app.android)) return [];
|
||||
const want = app.ios ? 'android' : 'ios';
|
||||
const me = (app.ios ?? app.android)!;
|
||||
const score = (x: UnifiedApp<P>) => {
|
||||
const r = (want === 'ios' ? x.ios : x.android)!;
|
||||
return (normId(r.app.bundleId) === normId(me.app.bundleId) ? 4 : 0) + (normName(r.app.name) === normName(me.app.name) ? 2 : 0) + (x.studio === app.studio ? 1 : 0);
|
||||
};
|
||||
return all.filter(x => !x.project && !x.ignored && (want === 'ios' ? x.ios && !x.android : x.android && !x.ios)).sort((a, b) => score(b) - score(a) || a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/** Overrides after pairing two single store apps by hand (drops an unpair of the same two). */
|
||||
export function withPair(o: Overrides, ios: string, android: string): Overrides {
|
||||
return { ...o, pairs: [...o.pairs.filter(p => p.ios !== ios && p.android !== android), { ios, android }], unpairs: o.unpairs.filter(p => !samePair(p, ios, android)) };
|
||||
}
|
||||
|
||||
/** Overrides after splitting a paired app (keeps it apart from now on). */
|
||||
export function withUnpair(o: Overrides, ios: string, android: string): Overrides {
|
||||
return { ...o, pairs: o.pairs.filter(p => !samePair(p, ios, android)), unpairs: [...o.unpairs.filter(p => !samePair(p, ios, android)), { ios, android }] };
|
||||
}
|
||||
|
||||
export function withIgnored(o: Overrides, keys: string[], on: boolean): Overrides {
|
||||
const set = new Set(o.ignored);
|
||||
for (const k of keys) { if (on) set.add(k); else set.delete(k); }
|
||||
return { ...o, ignored: [...set] };
|
||||
}
|
||||
|
||||
/** Moves an app to a studio (null: back to its accounts' studio). */
|
||||
export function withStudio(o: Overrides, app: UnifiedApp, studio: string | null): Overrides {
|
||||
const keys = app.project ? [`project:${app.project.id}`] : [app.ios?.key, app.android?.key].filter((k): k is string => !!k);
|
||||
const rest = o.appStudio.filter(x => !keys.includes(x.key));
|
||||
return { ...o, appStudio: studio ? [...rest, ...keys.map(key => ({ key, studio }))] : rest };
|
||||
}
|
||||
|
||||
/** Links the store apps of a store-only app to a folder. */
|
||||
export function withLink(o: Overrides, app: UnifiedApp, project: string): Overrides {
|
||||
const keys = [app.ios?.key, app.android?.key].filter((k): k is string => !!k);
|
||||
return { ...o, links: [...o.links.filter(l => !keys.includes(l.key)), ...keys.map(key => ({ key, project }))] };
|
||||
}
|
||||
138
cli/lib/imagehash.ts
Normal file
138
cli/lib/imagehash.ts
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
// Perceptual image hashes without dependencies: a PNG decoder in TypeScript (node:zlib inflates), a 32 x 32 grey
|
||||
// thumbnail, then dHash (gradients, 64 bit) and pHash (DCT low frequencies, 64 bit). JPEG / WebP go through ffmpeg
|
||||
// when it is installed (one grey 32 x 32 frame on stdout), else they are skipped with a reason. Two images whose
|
||||
// hashes differ in few bits look alike to a person (and to a reviewer comparing store pages).
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { inflateSync } from 'node:zlib';
|
||||
|
||||
export interface Gray { w: number; h: number; px: Float64Array }
|
||||
|
||||
/** Decodes a PNG to grey (alpha composited over white). 1-16 bit, every color type, Adam7 interlacing included. */
|
||||
export function decodePng(buf: Buffer): Gray {
|
||||
if (buf.readUInt32BE(0) !== 0x89504e47) throw new Error('not a PNG');
|
||||
let w = 0, h = 0, depth = 0, ctype = 0, interlace = 0;
|
||||
let palette: Buffer | null = null, trns: Buffer | null = null;
|
||||
const idat: Buffer[] = [];
|
||||
for (let p = 8; p + 8 <= buf.length;) {
|
||||
const len = buf.readUInt32BE(p), type = buf.toString('latin1', p + 4, p + 8), data = buf.subarray(p + 8, p + 8 + len);
|
||||
if (type === 'IHDR') { w = data.readUInt32BE(0); h = data.readUInt32BE(4); depth = data[8]!; ctype = data[9]!; interlace = data[12]!; }
|
||||
else if (type === 'PLTE') palette = data;
|
||||
else if (type === 'tRNS') trns = data;
|
||||
else if (type === 'IDAT') idat.push(data);
|
||||
else if (type === 'IEND') break;
|
||||
p += 12 + len;
|
||||
}
|
||||
if (!w || !h) throw new Error('PNG without IHDR');
|
||||
if (w * h > 40_000_000) throw new Error('PNG too large to hash');
|
||||
const channels = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[ctype];
|
||||
if (!channels) throw new Error(`PNG color type ${ctype} not supported`);
|
||||
const raw = inflateSync(Buffer.concat(idat));
|
||||
const bpp = Math.max(1, (channels * depth) >> 3);
|
||||
const out = new Float64Array(w * h);
|
||||
const max = (1 << depth) - 1;
|
||||
let off = 0;
|
||||
|
||||
const pass = (x0: number, y0: number, dx: number, dy: number): void => {
|
||||
const pw = Math.ceil((w - x0) / dx), ph = Math.ceil((h - y0) / dy);
|
||||
if (pw <= 0 || ph <= 0) return;
|
||||
const stride = Math.ceil((pw * channels * depth) / 8);
|
||||
let prev = new Uint8Array(stride);
|
||||
for (let y = 0; y < ph; y++) {
|
||||
const ft = raw[off]!;
|
||||
const line = new Uint8Array(raw.subarray(off + 1, off + 1 + stride));
|
||||
off += 1 + stride;
|
||||
for (let i = 0; i < stride; i++) {
|
||||
const a = i >= bpp ? line[i - bpp]! : 0, b = prev[i]!, c = i >= bpp ? prev[i - bpp]! : 0;
|
||||
let v = line[i]!;
|
||||
if (ft === 1) v += a; else if (ft === 2) v += b; else if (ft === 3) v += (a + b) >> 1;
|
||||
else if (ft === 4) { const pp = a + b - c, pa = Math.abs(pp - a), pb = Math.abs(pp - b), pc = Math.abs(pp - c); v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c; }
|
||||
line[i] = v & 255;
|
||||
}
|
||||
const sample = (x: number, ch: number): number => {
|
||||
if (depth === 8) return line[x * channels + ch]!;
|
||||
if (depth === 16) { const i = (x * channels + ch) * 2; return (line[i]! << 8) | line[i + 1]!; }
|
||||
const bit = (x * channels + ch) * depth;
|
||||
return (line[bit >> 3]! >> (8 - depth - (bit & 7))) & max;
|
||||
};
|
||||
for (let x = 0; x < pw; x++) {
|
||||
let r: number, g: number, bl: number, al = 1;
|
||||
if (ctype === 3) {
|
||||
const i = sample(x, 0);
|
||||
r = palette![i * 3]! / 255; g = palette![i * 3 + 1]! / 255; bl = palette![i * 3 + 2]! / 255;
|
||||
if (trns && i < trns.length) al = trns[i]! / 255;
|
||||
} else if (ctype === 0 || ctype === 4) { r = g = bl = sample(x, 0) / max; if (ctype === 4) al = sample(x, 1) / max; }
|
||||
else { r = sample(x, 0) / max; g = sample(x, 1) / max; bl = sample(x, 2) / max; if (ctype === 6) al = sample(x, 3) / max; }
|
||||
const lum = 0.299 * r + 0.587 * g + 0.114 * bl;
|
||||
out[(y0 + y * dy) * w + x0 + x * dx] = (lum * al + (1 - al)) * 255;
|
||||
}
|
||||
prev = line;
|
||||
}
|
||||
};
|
||||
if (interlace) for (const [x0, y0, dx, dy] of [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]] as const) pass(x0, y0, dx, dy);
|
||||
else pass(0, 0, 1, 1);
|
||||
return { w, h, px: out };
|
||||
}
|
||||
|
||||
/** Area-average resize of a grey image. */
|
||||
export function resize(g: Gray, W: number, H: number): Gray {
|
||||
const out = new Float64Array(W * H);
|
||||
for (let Y = 0; Y < H; Y++) for (let X = 0; X < W; X++) {
|
||||
const x0 = Math.floor((X * g.w) / W), x1 = Math.max(x0 + 1, Math.floor(((X + 1) * g.w) / W));
|
||||
const y0 = Math.floor((Y * g.h) / H), y1 = Math.max(y0 + 1, Math.floor(((Y + 1) * g.h) / H));
|
||||
let s = 0;
|
||||
for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) s += g.px[y * g.w + x]!;
|
||||
out[Y * W + X] = s / ((x1 - x0) * (y1 - y0));
|
||||
}
|
||||
return { w: W, h: H, px: out };
|
||||
}
|
||||
|
||||
/** 64-bit hashes as 16 hex characters. */
|
||||
export interface ImageHash { d: string; p: string }
|
||||
|
||||
const toHex = (bits: number[]): string => { let s = ''; for (let i = 0; i < 64; i += 4) s += ((bits[i]! << 3) | (bits[i + 1]! << 2) | (bits[i + 2]! << 1) | bits[i + 3]!).toString(16); return s; };
|
||||
|
||||
export function dHash(g: Gray): string {
|
||||
const s = resize(g, 9, 8);
|
||||
const bits: number[] = [];
|
||||
for (let y = 0; y < 8; y++) for (let x = 0; x < 8; x++) bits.push(s.px[y * 9 + x]! < s.px[y * 9 + x + 1]! ? 1 : 0);
|
||||
return toHex(bits);
|
||||
}
|
||||
|
||||
export function pHash(g: Gray): string {
|
||||
const N = 32, s = resize(g, N, N);
|
||||
const cos = Array.from({ length: 8 }, (_, u) => Array.from({ length: N }, (_, x) => Math.cos(((2 * x + 1) * u * Math.PI) / (2 * N))));
|
||||
const coef: number[] = [];
|
||||
for (let u = 0; u < 8; u++) for (let v = 0; v < 8; v++) {
|
||||
let sum = 0;
|
||||
for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) sum += s.px[y * N + x]! * cos[u]![y]! * cos[v]![x]!;
|
||||
coef.push(sum);
|
||||
}
|
||||
const ac = coef.slice(1).sort((a, b) => a - b);
|
||||
const median = ac[Math.floor(ac.length / 2)]!;
|
||||
return toHex(coef.map((c, i) => (i === 0 ? 0 : c > median ? 1 : 0)));
|
||||
}
|
||||
|
||||
export const hashGray = (g: Gray): ImageHash => ({ d: dHash(g), p: pHash(g) });
|
||||
|
||||
export function hamming(a: string, b: string): number {
|
||||
let n = 0;
|
||||
for (let i = 0; i < a.length; i++) { let x = parseInt(a[i]!, 16) ^ parseInt(b[i]!, 16); while (x) { n += x & 1; x >>= 1; } }
|
||||
return n;
|
||||
}
|
||||
|
||||
/** 1 = same picture, about 0.5 = unrelated. The mean of both hashes. */
|
||||
export const imageSimilarity = (a: ImageHash, b: ImageHash): number => 1 - (hamming(a.d, b.d) + hamming(a.p, b.p)) / 128;
|
||||
|
||||
/** Hash of an image file: PNG in TypeScript, anything else through ffmpeg (null with a reason when that is missing). */
|
||||
export function hashFile(path: string): { hash: ImageHash | null; reason?: string } {
|
||||
try {
|
||||
const buf = readFileSync(path);
|
||||
if (buf.length > 8 && buf.readUInt32BE(0) === 0x89504e47) return { hash: hashGray(decodePng(buf)) };
|
||||
const ffmpeg = Bun.which('ffmpeg');
|
||||
if (!ffmpeg) return { hash: null, reason: 'not a PNG and ffmpeg is not installed' };
|
||||
const r = Bun.spawnSync([ffmpeg, '-v', 'error', '-i', path, '-frames:v', '1', '-vf', 'scale=32:32:flags=area,format=gray', '-f', 'rawvideo', '-'], { stdout: 'pipe', stderr: 'pipe', timeout: 20_000 });
|
||||
const px = r.stdout;
|
||||
if (r.exitCode !== 0 || px.length !== 1024) return { hash: null, reason: `ffmpeg could not read it (${r.stderr.toString().trim().split('\n')[0]?.slice(0, 120) ?? r.exitCode})` };
|
||||
return { hash: hashGray({ w: 32, h: 32, px: Float64Array.from(px) }) };
|
||||
} catch (e) { return { hash: null, reason: (e as Error).message }; }
|
||||
}
|
||||
164
cli/lib/listing-pull.ts
Normal file
164
cli/lib/listing-pull.ts
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
// "Pull": the live store texts back into the local sources, as pure merges. The commands (apple listing pull, play
|
||||
// listing pull, catalog pull) read the stores, call these, print the diff and write only with --write.
|
||||
// - App Store: appInfoLocalizations (name, subtitle) + appStoreVersionLocalizations (description, keywords,
|
||||
// promotionalText, whatsNew) -> store/appstore.md, one "## <locale>" section per locale, "### <field>" blocks.
|
||||
// - Google Play: edits.listings (title, shortDescription, fullDescription) -> store/listing.md sections with
|
||||
// "<!-- play: <codes> -->". A section serving several Play codes is only changed when they agree on the store.
|
||||
// - In-app purchases and subscriptions: the store texts as a proposal for storebound.config.ts (a TypeScript file is
|
||||
// never rewritten by a tool): the diff per product and language, and a JSON proposal file with --write.
|
||||
// Only fields the store has a value for are written; a local field the store leaves empty is kept.
|
||||
import type { AppleCopy, AppleField } from './copy';
|
||||
import { APPLE_LIMITS, len, PLAY_LIMITS } from './copy';
|
||||
import type { Language, ShipConfig } from './config';
|
||||
import { playCodes } from './config';
|
||||
|
||||
export interface FieldChange { section: string; field: string; from: string | null; to: string }
|
||||
export interface MergeResult { md: string; changes: FieldChange[]; added: string[]; conflicts: string[] }
|
||||
|
||||
const fence = (t: string): string => '```\n' + t + '\n```';
|
||||
const BLOCK = (heading: RegExp) => new RegExp(`(^### (?:${heading.source})[^\\n]*\\n)\`\`\`[^\\n]*\\n([\\s\\S]*?)\\n?\`\`\``, 'm' + (heading.flags.includes('i') ? 'i' : ''));
|
||||
|
||||
/** Replace (or append) the fenced block under the first "### " heading matching `heading` in one section. */
|
||||
function setBlock(sec: string, heading: RegExp, newHeading: string, text: string): { sec: string; from: string | null } {
|
||||
const re = BLOCK(heading);
|
||||
const m = re.exec(sec);
|
||||
if (m) return { sec: sec.replace(re, (_a, h: string) => h + fence(text)), from: m[2]!.trim() };
|
||||
const body = sec.replace(/\s*$/, '');
|
||||
return { sec: `${body}\n\n### ${newHeading}\n${fence(text)}\n\n`, from: null };
|
||||
}
|
||||
|
||||
const APPLE_ORDER: AppleField[] = ['name', 'subtitle', 'promotionalText', 'keywords', 'description', 'whatsNew'];
|
||||
|
||||
/** Live App Store texts per locale merged into the App Store listing file. Pure. */
|
||||
export function mergeAppleListing(md: string, remote: Record<string, AppleCopy>): MergeResult {
|
||||
const parts = md.split(/^(?=## )/m);
|
||||
const res: MergeResult = { md: '', changes: [], added: [], conflicts: [] };
|
||||
const seen = new Set<string>();
|
||||
const out = parts.map(sec => {
|
||||
if (!sec.startsWith('## ')) return sec;
|
||||
const loc = sec.slice(3).split(/[\s·]/)[0]!.trim();
|
||||
const r = remote[loc];
|
||||
if (!r) return sec;
|
||||
seen.add(loc);
|
||||
for (const f of APPLE_ORDER) {
|
||||
const v = r[f];
|
||||
if (v === undefined || v === null || v === '') continue;
|
||||
const { sec: next, from } = setBlock(sec, new RegExp(`${f}\\b`), f, v);
|
||||
if (from !== v.trim()) res.changes.push({ section: loc, field: f, from, to: v });
|
||||
sec = next;
|
||||
}
|
||||
return sec;
|
||||
});
|
||||
let text = out.join('');
|
||||
for (const [loc, r] of Object.entries(remote).sort(([a], [b]) => a.localeCompare(b))) {
|
||||
if (seen.has(loc)) continue;
|
||||
const fields = APPLE_ORDER.filter(f => r[f]);
|
||||
if (!fields.length) continue;
|
||||
res.added.push(loc);
|
||||
text = text.replace(/\s*$/, '') + `\n\n## ${loc}\n\n` + fields.map(f => `### ${f}\n${fence(r[f]!)}`).join('\n\n') + '\n';
|
||||
for (const f of fields) res.changes.push({ section: loc, field: f, from: null, to: r[f]! });
|
||||
}
|
||||
res.md = text.endsWith('\n') ? text : text + '\n';
|
||||
return res;
|
||||
}
|
||||
|
||||
export interface PlayRemote { language: string; title?: string; shortDescription?: string; fullDescription?: string }
|
||||
|
||||
const PLAY_FIELDS: { key: keyof PlayRemote; re: RegExp; heading: string; limit: number }[] = [
|
||||
{ key: 'title', re: /[^\n]*\btitle\b/i, heading: `Title (max ${PLAY_LIMITS.title})`, limit: PLAY_LIMITS.title },
|
||||
{ key: 'shortDescription', re: /[^\n]*\bshort\b/i, heading: `Short description (max ${PLAY_LIMITS.short})`, limit: PLAY_LIMITS.short },
|
||||
{ key: 'fullDescription', re: /[^\n]*\bfull\b/i, heading: `Full description (max ${PLAY_LIMITS.full})`, limit: PLAY_LIMITS.full },
|
||||
];
|
||||
|
||||
/** Live Play listings merged into the Play listing file. A title equal to `defaultTitle` (app.name) is only written
|
||||
* where the section already has a title block. Pure. */
|
||||
export function mergePlayListing(md: string, remote: PlayRemote[], defaultTitle: string): MergeResult {
|
||||
const byLang = new Map(remote.map(l => [l.language, l] as const));
|
||||
const res: MergeResult = { md: '', changes: [], added: [], conflicts: [] };
|
||||
const seen = new Set<string>();
|
||||
const parts = md.split(/^(?=## )/m).map(sec => {
|
||||
const m = /^<!--\s*play:\s*([^>]+?)\s*-->$/m.exec(sec);
|
||||
if (!m) return sec;
|
||||
const codes = m[1]!.split(',').map(s => s.trim()).filter(Boolean);
|
||||
const hits = codes.map(c => byLang.get(c)).filter((x): x is PlayRemote => !!x);
|
||||
for (const c of codes) if (byLang.has(c)) seen.add(c);
|
||||
if (!hits.length) return sec;
|
||||
for (const f of PLAY_FIELDS) {
|
||||
const values = [...new Set(hits.map(h => (h[f.key] ?? '').trim()).filter(Boolean))];
|
||||
if (!values.length) continue;
|
||||
if (values.length > 1) { res.conflicts.push(`${codes.join(', ')}: ${f.key} differs between these Play languages on the store; left as it is (give each its own section)`); continue; }
|
||||
const v = values[0]!;
|
||||
const has = BLOCK(f.re).test(sec);
|
||||
if (f.key === 'title' && !has && v === defaultTitle) continue;
|
||||
const { sec: next, from } = setBlock(sec, f.re, f.heading, v);
|
||||
if (from !== v) res.changes.push({ section: codes.join(', '), field: f.key, from, to: v });
|
||||
sec = next;
|
||||
}
|
||||
return sec;
|
||||
});
|
||||
let text = parts.join('');
|
||||
for (const l of [...remote].sort((a, b) => a.language.localeCompare(b.language))) {
|
||||
if (seen.has(l.language)) continue;
|
||||
res.added.push(l.language);
|
||||
const blocks = PLAY_FIELDS.filter(f => l[f.key] && !(f.key === 'title' && l.title === defaultTitle)).map(f => `### ${f.heading}\n${fence(String(l[f.key]))}`);
|
||||
text = text.replace(/\s*$/, '') + `\n\n## ${l.language}\n<!-- play: ${l.language} -->\n\n${blocks.join('\n\n')}\n`;
|
||||
for (const f of PLAY_FIELDS) if (l[f.key]) res.changes.push({ section: l.language, field: f.key, from: null, to: String(l[f.key]) });
|
||||
}
|
||||
res.md = text.endsWith('\n') ? text : text + '\n';
|
||||
return res;
|
||||
}
|
||||
|
||||
/** Store values over a store limit (the pull still writes them; `check` will flag them). */
|
||||
export function overLimits(changes: FieldChange[], store: 'apple' | 'play'): string[] {
|
||||
const lim: Record<string, number> = store === 'apple' ? APPLE_LIMITS : { title: PLAY_LIMITS.title, shortDescription: PLAY_LIMITS.short, fullDescription: PLAY_LIMITS.full };
|
||||
return changes.filter(c => lim[c.field] !== undefined && len(c.to) > lim[c.field]!).map(c => `${c.section} ${c.field}: ${len(c.to)} > ${lim[c.field]}`);
|
||||
}
|
||||
|
||||
// ---- in-app purchases and subscriptions -> config proposal ----
|
||||
|
||||
export interface RemoteText { title: string; description: string; benefits?: string[] }
|
||||
/** Store texts per product id and store language code (App Store locale or Play language code). */
|
||||
export type RemoteCatalog = Record<string, Record<string, RemoteText>>;
|
||||
|
||||
export interface CatalogProposal {
|
||||
/** product id -> language id -> the store's texts (only where they differ from the config or are missing there). */
|
||||
listings: Record<string, Record<string, { title: string; description: string; benefits?: string[] }>>;
|
||||
changes: { id: string; lang: string; field: string; from: string | null; to: string; store: 'apple' | 'play' }[];
|
||||
/** Store languages the config has no language entry for (not mapped). */
|
||||
unmapped: string[];
|
||||
/** Products on the store that are not in the config. */
|
||||
unknown: string[];
|
||||
}
|
||||
|
||||
/** Store language code -> config language id (App Store locale or any Play code of the entry). */
|
||||
export function langIdOf(langs: Language[], store: 'apple' | 'play', code: string): string | undefined {
|
||||
return langs.find(l => (store === 'apple' ? l.apple === code : playCodes(l).includes(code)))?.id;
|
||||
}
|
||||
|
||||
/** The store texts of in-app purchases and subscriptions against the config's listings. Apple wins over Play when
|
||||
* both differ for the same language (shown as two changes). Pure. */
|
||||
export function catalogProposal(config: Pick<ShipConfig, 'languages' | 'products' | 'subscriptions'>, remote: { apple?: RemoteCatalog; play?: RemoteCatalog }): CatalogProposal {
|
||||
const local = new Map<string, Record<string, { title: string; description: string; benefits?: string[] }>>();
|
||||
for (const p of config.products ?? []) local.set(p.id, p.listings);
|
||||
for (const g of config.subscriptions ?? []) for (const s of g.subscriptions) local.set(s.id, s.listings);
|
||||
const out: CatalogProposal = { listings: {}, changes: [], unmapped: [], unknown: [] };
|
||||
for (const store of ['play', 'apple'] as const) {
|
||||
for (const [id, byCode] of Object.entries(remote[store] ?? {})) {
|
||||
const mine = local.get(id);
|
||||
if (!mine) { if (!out.unknown.includes(id)) out.unknown.push(id); continue; }
|
||||
for (const [code, t] of Object.entries(byCode)) {
|
||||
const lang = langIdOf(config.languages, store, code);
|
||||
if (!lang) { const u = `${store}:${code}`; if (!out.unmapped.includes(u)) out.unmapped.push(u); continue; }
|
||||
const cur = mine[lang];
|
||||
const fields: [string, string | null, string][] = [['title', cur?.title ?? null, t.title], ['description', cur?.description ?? null, t.description]];
|
||||
if (store === 'play' && t.benefits?.length) fields.push(['benefits', cur?.benefits?.join(' | ') ?? null, t.benefits.join(' | ')]);
|
||||
const diff = fields.filter(([, from, to]) => to && from !== to);
|
||||
if (!diff.length) continue;
|
||||
for (const [field, from, to] of diff) out.changes.push({ id, lang, field, from, to, store });
|
||||
const prev = out.listings[id]?.[lang] ?? { title: cur?.title ?? t.title, description: cur?.description ?? t.description, ...(cur?.benefits ? { benefits: cur.benefits } : {}) };
|
||||
out.listings[id] = { ...out.listings[id], [lang]: { ...prev, title: t.title || prev.title, description: t.description || prev.description, ...(store === 'play' && t.benefits?.length ? { benefits: t.benefits } : {}) } };
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
301
cli/lib/offers.ts
Normal file
301
cli/lib/offers.ts
Normal file
|
|
@ -0,0 +1,301 @@
|
|||
// App Store offers beyond introductory / promotional offers, as pure parts: offer codes for one-time purchases,
|
||||
// win-back offers for subscriptions, promoted in-app purchases and app pre-orders. The commands (cli/apple/offers.ts)
|
||||
// read, plan, print the dry run and send; everything that becomes visible to customers asks first and none of it is
|
||||
// an MCP tool.
|
||||
// Sources (App Store Connect API 4.5.1 OpenAPI spec + docs, App Store Connect Help; checked October 2026):
|
||||
// In-app purchase offer codes: POST /v1/inAppPurchaseOfferCodes (name, customerEligibilities NON_SPENDER |
|
||||
// ACTIVE_SPENDER | CHURNED_SPENDER, inAppPurchase, prices = inAppPurchaseOfferPrices: territory + pricePoint),
|
||||
// POST /v1/inAppPurchaseOfferCodeCustomCodes (customCode, numberOfCodes, expirationDate?),
|
||||
// POST /v1/inAppPurchaseOfferCodeOneTimeUseCodes (numberOfCodes, expirationDate, environment PRODUCTION | SANDBOX),
|
||||
// GET /v1/inAppPurchaseOfferCodeOneTimeUseCodes/{id}/values (the codes), GET /v2/inAppPurchases/{id}/offerCodes.
|
||||
// Help "Create offer codes for In-App Purchases": up to 10 active offers per app, 1 million codes per app per
|
||||
// quarter, one-time-use batches of 500-25,000 valid at most 6 months, custom codes up to 64 characters without
|
||||
// special characters and up to 25,000 redemptions, paid or free offers. Consumables, non-consumables and
|
||||
// non-renewing subscriptions (iOS 16.3+).
|
||||
// https://developer.apple.com/help/app-store-connect/manage-in-app-purchases/create-offer-codes-for-in-app-purchases
|
||||
// Win-back offers: POST /v1/winBackOffers (referenceName, offerId, duration, offerMode, periodCount,
|
||||
// customerEligibilityPaidSubscriptionDurationInMonths, customerEligibilityTimeSinceLastSubscribedInMonths {minimum,
|
||||
// maximum}, customerEligibilityWaitBetweenOffersInMonths?, startDate, endDate?, priority HIGH | NORMAL,
|
||||
// promotionIntent NOT_PROMOTED | USE_AUTO_GENERATED_ASSETS; subscription; prices = winBackOfferPrices with a
|
||||
// subscriptionPricePoint), GET /v1/subscriptions/{id}/winBackOffers.
|
||||
// https://developer.apple.com/documentation/appstoreconnectapi/post-v1-winbackoffers
|
||||
// Help "Set up win-back offers": the subscription must be approved first; paid duration 1-24 months or 3, 4, 5
|
||||
// years; time since last subscribed 1-24 months (min and max required); wait between offers 2-24 months; start at
|
||||
// the earliest tomorrow, run at least 3 days; at most 350 per subscription and 5 at a time per storefront; reference
|
||||
// name, offer id and price cannot be changed later; an offer id must not be reused in the group.
|
||||
// https://developer.apple.com/help/app-store-connect/manage-subscriptions/set-up-win-back-offers
|
||||
// Promoted purchases: POST /v1/promotedPurchases (visibleForAllUsers, enabled?, app, inAppPurchaseV2 | subscription),
|
||||
// PATCH /v1/promotedPurchases/{id} (visibleForAllUsers, enabled), GET /v1/apps/{id}/promotedPurchases,
|
||||
// PATCH /v1/apps/{id}/relationships/promotedPurchases (the order). Help "Promote In-App Purchases": up to 20
|
||||
// promoted at a time, each needs its promotional image, the app must handle purchases started on the App Store
|
||||
// (PurchaseIntent). https://developer.apple.com/help/app-store-connect/configure-in-app-purchase-settings/promote-in-app-purchases
|
||||
// Pre-orders: GET /v1/apps/{id}/appAvailabilityV2, GET /v2/appAvailabilities/{id}/territoryAvailabilities
|
||||
// (available, releaseDate, preOrderEnabled, preOrderPublishDate, contentStatuses), PATCH
|
||||
// /v1/territoryAvailabilities/{id} (available, releaseDate, preOrderEnabled), POST /v1/endAppAvailabilityPreOrders
|
||||
// ("End the pre-order for your app and release to store immediately"). Help "Publish for pre-order": a version
|
||||
// must be approved first; release date 2-180 days ahead (Apple's pre-orders page: up to 365 days for an existing
|
||||
// app in a new region); not possible where the app is already released.
|
||||
// https://developer.apple.com/help/app-store-connect/manage-your-apps-availability/publish-for-pre-order
|
||||
// Google Play pre-registration has no API (androidpublisher v3 lists no such resource): Play Console only.
|
||||
import type { Req } from '../apple/jsonapi';
|
||||
import { many, one } from '../apple/jsonapi';
|
||||
import { APPLE_OFFER_DURATION, APPLE_OFFER_MODE } from './subscriptions';
|
||||
|
||||
// ---- config ----
|
||||
|
||||
/** Offer code campaign for a one-time purchase (consumable, non-consumable, non-renewing). */
|
||||
export interface IapOfferCodeDef {
|
||||
/** Reference name of the campaign (unique per product). */
|
||||
name: string;
|
||||
/** NON_SPENDER = never purchased in the app, ACTIVE_SPENDER = purchased in the last 30 days, CHURNED_SPENDER =
|
||||
* purchased more than 30 days ago. All three = everyone. */
|
||||
eligibility: ('NON_SPENDER' | 'ACTIVE_SPENDER' | 'CHURNED_SPENDER')[];
|
||||
/** Free offer (no price) or a paid one in USD (the USA price point and its equalizations). */
|
||||
free?: boolean;
|
||||
usd?: number;
|
||||
/** Limit the offer to these App Store territories (alpha-3). Default: every territory. */
|
||||
territories?: string[];
|
||||
/** Custom codes (anyone with the code; created only from a terminal run with --codes that confirms). */
|
||||
customCodes?: { code: string; count: number; expires?: string }[];
|
||||
/** One-time-use code batches (500-25,000, expiry at most 6 months; --codes, confirms; the codes are saved to
|
||||
* .storebound/offer-codes/). */
|
||||
oneTimeCodes?: { count: number; expires: string; sandbox?: boolean }[];
|
||||
}
|
||||
|
||||
/** Win-back offer for lapsed subscribers of one subscription. */
|
||||
export interface WinBackDef {
|
||||
/** Offer identifier (unique in the subscription group, never reused; cannot change later). */
|
||||
id: string;
|
||||
/** Reference name (default: the id; cannot change later). */
|
||||
name?: string;
|
||||
type: 'free' | 'pay-as-you-go' | 'pay-up-front';
|
||||
/** free / pay-up-front: P3D ... P1Y; pay-as-you-go: the subscription period (default). */
|
||||
duration?: string;
|
||||
/** pay-as-you-go: number of periods (default 1). */
|
||||
periods?: number;
|
||||
/** USD price (per period for pay-as-you-go, total for pay-up-front); fixed after creation. */
|
||||
usd?: number;
|
||||
/** Customers who paid at least this many months: 1-24, 36, 48 or 60. */
|
||||
paidMonths: number;
|
||||
/** Lapsed between min and max months ago (1-24). */
|
||||
lapsedMonths: { min: number; max: number };
|
||||
/** Months between two win-back offers for one customer (2-24, optional). */
|
||||
waitMonths?: number;
|
||||
/** YYYY-MM-DD, at the earliest tomorrow. */
|
||||
start: string;
|
||||
/** YYYY-MM-DD, at least 3 days after start (optional). */
|
||||
end?: string;
|
||||
priority?: 'high' | 'normal';
|
||||
/** Promote on the App Store with auto-generated assets (needs an approved subscription image). */
|
||||
promote?: boolean;
|
||||
}
|
||||
|
||||
export interface PromotedConfig {
|
||||
/** Product / subscription ids in display order (at most 20). */
|
||||
products: string[];
|
||||
/** Shown to every user (true) or only to users your app makes it visible for (false). Default true. */
|
||||
visibleForAllUsers?: boolean;
|
||||
}
|
||||
|
||||
const DAY = 86_400_000;
|
||||
const isDate = (s: unknown): s is string => typeof s === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(s) && !Number.isNaN(Date.parse(s));
|
||||
const ELIG = ['NON_SPENDER', 'ACTIVE_SPENDER', 'CHURNED_SPENDER'];
|
||||
const PAID_MONTHS = new Set([...Array.from({ length: 24 }, (_, i) => i + 1), 36, 48, 60]);
|
||||
|
||||
/** Problems with products[].offerCodes. With `today` (when codes are about to be created) also the 6-month expiry
|
||||
* rule; the config check leaves dates relative to today out, so an old campaign never breaks the config. Pure. */
|
||||
export function validateIapOfferCodes(at: string, codes: IapOfferCodeDef[] | undefined, type: string, today?: string): string[] {
|
||||
const e: string[] = [];
|
||||
const names = new Set<string>();
|
||||
const max = today ? new Date(Date.parse(today) + 183 * DAY).toISOString().slice(0, 10) : '9999-12-31';
|
||||
for (const [i, c] of (codes ?? []).entries()) {
|
||||
const p = `${at}.offerCodes[${i}]`;
|
||||
if (!c.name || [...c.name].length > 64) e.push(`${p}.name: 1-64 characters`);
|
||||
if (names.has(c.name)) e.push(`${p}.name: duplicate "${c.name}"`);
|
||||
names.add(c.name);
|
||||
if (!Array.isArray(c.eligibility) || !c.eligibility.length || !c.eligibility.every(x => ELIG.includes(x))) e.push(`${p}.eligibility: some of ${ELIG.join(', ')}`);
|
||||
if (!!c.free === (c.usd !== undefined)) e.push(`${p}: free: true or usd (one of them)`);
|
||||
if (c.usd !== undefined && !(c.usd > 0)) e.push(`${p}.usd: positive`);
|
||||
if (c.territories && !c.territories.every(t => /^[A-Z]{3}$/.test(t))) e.push(`${p}.territories: App Store territories, alpha-3 (USA)`);
|
||||
for (const [k, cc] of (c.customCodes ?? []).entries()) {
|
||||
if (!/^[A-Za-z0-9]{1,64}$/.test(cc.code ?? '')) e.push(`${p}.customCodes[${k}].code: letters and digits, up to 64`);
|
||||
if (!(Number.isInteger(cc.count) && cc.count >= 1 && cc.count <= 25000)) e.push(`${p}.customCodes[${k}].count: 1-25000`);
|
||||
if (cc.expires !== undefined && (!isDate(cc.expires) || cc.expires > max)) e.push(`${p}.customCodes[${k}].expires: YYYY-MM-DD within 6 months`);
|
||||
}
|
||||
for (const [k, b] of (c.oneTimeCodes ?? []).entries()) {
|
||||
const lo = b.sandbox ? 10 : 500, hi = b.sandbox ? 10000 : 25000;
|
||||
if (!(Number.isInteger(b.count) && b.count >= lo && b.count <= hi)) e.push(`${p}.oneTimeCodes[${k}].count: ${lo}-${hi}`);
|
||||
if (!isDate(b.expires) || b.expires > max) e.push(`${p}.oneTimeCodes[${k}].expires: YYYY-MM-DD within 6 months (required)`);
|
||||
}
|
||||
}
|
||||
if ((codes ?? []).length && !['consumable', 'non_consumable', 'non_renewing'].includes(type)) e.push(`${at}.offerCodes: one-time purchases only`);
|
||||
return e;
|
||||
}
|
||||
|
||||
/** Problems with subscriptions[].winBack. With `today` (right before creating) also "start at the earliest
|
||||
* tomorrow". Pure. */
|
||||
export function validateWinBack(at: string, offers: WinBackDef[] | undefined, today?: string): string[] {
|
||||
const e: string[] = [];
|
||||
const ids = new Set<string>();
|
||||
for (const [i, o] of (offers ?? []).entries()) {
|
||||
const p = `${at}.winBack[${i}]`;
|
||||
if (!/^[A-Za-z0-9._-]{1,64}$/.test(o.id ?? '')) e.push(`${p}.id: letters, digits, ".", "_", "-"`);
|
||||
if (ids.has(o.id)) e.push(`${p}.id: duplicate "${o.id}"`);
|
||||
ids.add(o.id);
|
||||
if (!(o.type in APPLE_OFFER_MODE)) e.push(`${p}.type: free | pay-as-you-go | pay-up-front`);
|
||||
if (o.type !== 'pay-as-you-go' && !(o.duration && o.duration in APPLE_OFFER_DURATION)) e.push(`${p}.duration: ${Object.keys(APPLE_OFFER_DURATION).join(', ')}`);
|
||||
if (o.type !== 'free' && !(typeof o.usd === 'number' && o.usd > 0)) e.push(`${p}.usd: positive (a paid offer)`);
|
||||
if (o.type === 'free' && o.usd !== undefined) e.push(`${p}.usd: not for a free offer`);
|
||||
if (o.periods !== undefined && !(Number.isInteger(o.periods) && o.periods >= 1 && o.periods <= 12)) e.push(`${p}.periods: 1-12`);
|
||||
if (!PAID_MONTHS.has(o.paidMonths)) e.push(`${p}.paidMonths: 1-24, 36, 48 or 60`);
|
||||
const l = o.lapsedMonths;
|
||||
if (!l || !(Number.isInteger(l.min) && Number.isInteger(l.max) && l.min >= 1 && l.max <= 24 && l.min <= l.max)) e.push(`${p}.lapsedMonths: { min, max } within 1-24`);
|
||||
if (o.waitMonths !== undefined && !(Number.isInteger(o.waitMonths) && o.waitMonths >= 2 && o.waitMonths <= 24)) e.push(`${p}.waitMonths: 2-24`);
|
||||
if (!isDate(o.start)) e.push(`${p}.start: YYYY-MM-DD`);
|
||||
else if (today && o.start <= today) e.push(`${p}.start: at the earliest tomorrow`);
|
||||
if (o.end !== undefined && (!isDate(o.end) || (isDate(o.start) && Date.parse(o.end) - Date.parse(o.start) < 3 * DAY))) e.push(`${p}.end: YYYY-MM-DD, at least 3 days after start`);
|
||||
if (o.priority !== undefined && o.priority !== 'high' && o.priority !== 'normal') e.push(`${p}.priority: high | normal`);
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
export function validatePromoted(p: PromotedConfig | undefined, ids: Set<string>): string[] {
|
||||
if (!p) return [];
|
||||
const e: string[] = [];
|
||||
if (!Array.isArray(p.products) || !p.products.length) e.push('apple.promoted.products: at least one product id');
|
||||
if ((p.products ?? []).length > 20) e.push('apple.promoted.products: at most 20 (App Store limit)');
|
||||
for (const id of p.products ?? []) if (!ids.has(id)) e.push(`apple.promoted.products: "${id}" is not a product or subscription of the config`);
|
||||
if (new Set(p.products).size !== (p.products ?? []).length) e.push('apple.promoted.products: duplicates');
|
||||
return e;
|
||||
}
|
||||
|
||||
// ---- request bodies ----
|
||||
|
||||
export interface TerritoryPoint { territory: string; pointId?: string }
|
||||
|
||||
/** POST /v1/inAppPurchaseOfferCodes. A free offer sends the territories without a price point (the schema marks the
|
||||
* price point optional; not verified against a live account). */
|
||||
export function iapOfferCodeBody(iapId: string, c: IapOfferCodeDef, prices: TerritoryPoint[]) {
|
||||
const ids = prices.map((_, i) => `\${iapcode-${i}}`);
|
||||
return {
|
||||
data: { type: 'inAppPurchaseOfferCodes', attributes: { name: c.name, customerEligibilities: c.eligibility },
|
||||
relationships: { inAppPurchase: one('inAppPurchases', iapId), prices: { data: ids.map(id => ({ type: 'inAppPurchaseOfferPrices', id })) } } },
|
||||
included: prices.map((p, i) => {
|
||||
if (!c.free && !p.pointId) throw new Error(`${c.name}: paid offer in ${p.territory} needs a price point`);
|
||||
return { type: 'inAppPurchaseOfferPrices', id: ids[i], relationships: { territory: one('territories', p.territory), ...(p.pointId ? { pricePoint: one('inAppPurchasePricePoints', p.pointId) } : {}) } };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export const iapCustomCodeReq = (offerCodeId: string, cc: { code: string; count: number; expires?: string }): Req => ({ method: 'POST', path: '/v1/inAppPurchaseOfferCodeCustomCodes',
|
||||
note: `custom code ${cc.code} (${cc.count} redemptions${cc.expires ? `, until ${cc.expires}` : ''})`,
|
||||
body: { data: { type: 'inAppPurchaseOfferCodeCustomCodes', attributes: { customCode: cc.code, numberOfCodes: cc.count, ...(cc.expires ? { expirationDate: cc.expires } : {}) },
|
||||
relationships: { offerCode: one('inAppPurchaseOfferCodes', offerCodeId) } } } });
|
||||
|
||||
export const iapOneTimeCodesReq = (offerCodeId: string, b: { count: number; expires: string; sandbox?: boolean }): Req => ({ method: 'POST', path: '/v1/inAppPurchaseOfferCodeOneTimeUseCodes',
|
||||
note: `${b.count} one-time-use ${b.sandbox ? 'sandbox ' : ''}codes until ${b.expires}`,
|
||||
body: { data: { type: 'inAppPurchaseOfferCodeOneTimeUseCodes', attributes: { numberOfCodes: b.count, expirationDate: b.expires, environment: b.sandbox ? 'SANDBOX' : 'PRODUCTION' },
|
||||
relationships: { offerCode: one('inAppPurchaseOfferCodes', offerCodeId) } } } });
|
||||
|
||||
/** POST /v1/winBackOffers. `subPeriod` = the subscription's period (pay-as-you-go duration). Paid prices: one
|
||||
* subscriptionPricePoint per territory (the point carries its territory, as in Apple's example request). A free offer
|
||||
* sends the territories without a price point (not verified against a live account). */
|
||||
export function winBackBody(subId: string, subPeriod: string, o: WinBackDef, prices: TerritoryPoint[]) {
|
||||
const ids = prices.map((_, i) => `\${winback-${i}}`);
|
||||
const duration = o.type === 'pay-as-you-go' ? (o.duration ?? subPeriod) : o.duration!;
|
||||
return {
|
||||
data: { type: 'winBackOffers', attributes: {
|
||||
referenceName: o.name ?? o.id, offerId: o.id, duration: APPLE_OFFER_DURATION[duration], offerMode: APPLE_OFFER_MODE[o.type],
|
||||
periodCount: o.type === 'pay-as-you-go' ? (o.periods ?? 1) : 1,
|
||||
customerEligibilityPaidSubscriptionDurationInMonths: o.paidMonths,
|
||||
customerEligibilityTimeSinceLastSubscribedInMonths: { minimum: o.lapsedMonths.min, maximum: o.lapsedMonths.max },
|
||||
...(o.waitMonths !== undefined ? { customerEligibilityWaitBetweenOffersInMonths: o.waitMonths } : {}),
|
||||
startDate: o.start, ...(o.end ? { endDate: o.end } : {}), priority: (o.priority ?? 'normal').toUpperCase(),
|
||||
promotionIntent: o.promote ? 'USE_AUTO_GENERATED_ASSETS' : 'NOT_PROMOTED',
|
||||
}, relationships: { subscription: one('subscriptions', subId), prices: { data: ids.map(id => ({ type: 'winBackOfferPrices', id })) } } },
|
||||
included: prices.map((p, i) => {
|
||||
if (o.type !== 'free' && !p.pointId) throw new Error(`${o.id}: paid win-back offer in ${p.territory} needs a price point`);
|
||||
return { type: 'winBackOfferPrices', id: ids[i], relationships: p.pointId ? { subscriptionPricePoint: one('subscriptionPricePoints', p.pointId) } : { territory: one('territories', p.territory) } };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
// ---- promoted purchases ----
|
||||
|
||||
export interface PromotedNow { id: string; productId: string; enabled: boolean; visibleForAllUsers: boolean; state?: string }
|
||||
|
||||
export interface PromotedPlan { create: Req[]; update: Req[]; order: Req | null; unknown: string[]; extra: string[] }
|
||||
|
||||
/** Wanted promoted purchases vs the current ones. New ones are created disabled unless enable; `enable` also turns on
|
||||
* existing ones. The order request lists the configured ones first, then the others as they are. Pure. */
|
||||
export function planPromoted(appId: string, cfg: PromotedConfig, now: PromotedNow[], products: Map<string, { apiId: string; kind: 'iap' | 'sub' }>, o: { enable?: boolean } = {}): PromotedPlan {
|
||||
const plan: PromotedPlan = { create: [], update: [], order: null, unknown: [], extra: [] };
|
||||
const visible = cfg.visibleForAllUsers ?? true;
|
||||
const have = new Map(now.map(p => [p.productId, p] as const));
|
||||
for (const id of cfg.products) {
|
||||
const cur = have.get(id);
|
||||
if (cur) {
|
||||
const attrs: Record<string, boolean> = {};
|
||||
if (cur.visibleForAllUsers !== visible) attrs.visibleForAllUsers = visible;
|
||||
if (o.enable && !cur.enabled) attrs.enabled = true;
|
||||
if (Object.keys(attrs).length) plan.update.push({ method: 'PATCH', path: `/v1/promotedPurchases/${cur.id}`, note: `${id}: ${Object.entries(attrs).map(([k, v]) => `${k}=${v}`).join(', ')}`,
|
||||
body: { data: { type: 'promotedPurchases', id: cur.id, attributes: attrs } } });
|
||||
continue;
|
||||
}
|
||||
const p = products.get(id);
|
||||
if (!p) { plan.unknown.push(id); continue; }
|
||||
plan.create.push({ method: 'POST', path: '/v1/promotedPurchases', note: `promote ${id}${o.enable ? ' (enabled)' : ' (not enabled yet)'}`,
|
||||
body: { data: { type: 'promotedPurchases', attributes: { visibleForAllUsers: visible, enabled: !!o.enable },
|
||||
relationships: { app: one('apps', appId), ...(p.kind === 'iap' ? { inAppPurchaseV2: one('inAppPurchases', p.apiId) } : { subscription: one('subscriptions', p.apiId) }) } } } });
|
||||
}
|
||||
plan.extra = now.filter(p => !cfg.products.includes(p.productId)).map(p => p.productId);
|
||||
return plan;
|
||||
}
|
||||
|
||||
/** PATCH /v1/apps/{id}/relationships/promotedPurchases: the display order (configured first, then the rest). */
|
||||
export function promotedOrderReq(appId: string, cfg: PromotedConfig, now: PromotedNow[]): Req | null {
|
||||
const byProduct = new Map(now.map(p => [p.productId, p.id] as const));
|
||||
const ordered = [...cfg.products.map(id => byProduct.get(id)).filter((x): x is string => !!x), ...now.filter(p => !cfg.products.includes(p.productId)).map(p => p.id)];
|
||||
if (!ordered.length || ordered.join() === now.map(p => p.id).join()) return null;
|
||||
return { method: 'PATCH', path: `/v1/apps/${appId}/relationships/promotedPurchases`, note: 'promoted purchase order', body: many('promotedPurchases', ordered) };
|
||||
}
|
||||
|
||||
// ---- pre-orders ----
|
||||
|
||||
export interface TerritoryAvail { id: string; territory: string; available?: boolean; releaseDate?: string | null; preOrderEnabled?: boolean; preOrderPublishDate?: string | null; contentStatuses?: string[] }
|
||||
|
||||
/** Territory availabilities response(s) (include=territory) -> rows. Pure. */
|
||||
export function territoryRows(pages: { data?: { id: string; attributes?: Record<string, unknown>; relationships?: { territory?: { data?: { id: string } } } }[] }[]): TerritoryAvail[] {
|
||||
return pages.flatMap(p => (p.data ?? []).map(t => ({ id: t.id, territory: t.relationships?.territory?.data?.id ?? '?', available: t.attributes?.available as boolean | undefined,
|
||||
releaseDate: (t.attributes?.releaseDate as string | null | undefined) ?? null, preOrderEnabled: t.attributes?.preOrderEnabled as boolean | undefined,
|
||||
preOrderPublishDate: (t.attributes?.preOrderPublishDate as string | null | undefined) ?? null, contentStatuses: t.attributes?.contentStatuses as string[] | undefined })));
|
||||
}
|
||||
|
||||
/** PATCH requests that put the chosen territories on pre-order with this release date. Territories where the app is
|
||||
* already out (AVAILABLE) cannot go on pre-order. Pure. */
|
||||
export function planPreOrder(rows: TerritoryAvail[], releaseDate: string, territories: string[] | null, today = new Date().toISOString().slice(0, 10)): { reqs: Req[]; problems: string[]; warnings: string[] } {
|
||||
const problems: string[] = [], warnings: string[] = [];
|
||||
if (!isDate(releaseDate)) problems.push('--release-date: YYYY-MM-DD');
|
||||
const days = (Date.parse(releaseDate) - Date.parse(today)) / DAY;
|
||||
if (isDate(releaseDate) && days < 2) problems.push('--release-date: at least 2 days ahead');
|
||||
if (isDate(releaseDate) && days > 365) problems.push('--release-date: at most 365 days ahead (180 for a new app)');
|
||||
else if (isDate(releaseDate) && days > 180) warnings.push('more than 180 days ahead: only allowed for an existing app in a new region');
|
||||
const pick = territories ? rows.filter(r => territories.includes(r.territory)) : rows;
|
||||
if (territories) for (const t of territories) if (!rows.some(r => r.territory === t)) problems.push(`territory ${t}: not in the app's availability`);
|
||||
const reqs: Req[] = [];
|
||||
for (const r of pick) {
|
||||
if (r.contentStatuses?.includes('AVAILABLE')) { warnings.push(`${r.territory}: already released there, no pre-order possible`); continue; }
|
||||
if (r.preOrderEnabled && r.releaseDate === releaseDate && r.available) continue;
|
||||
reqs.push({ method: 'PATCH', path: `/v1/territoryAvailabilities/${r.id}`, note: `${r.territory}: pre-order, release ${releaseDate}`,
|
||||
body: { data: { type: 'territoryAvailabilities', id: r.id, attributes: { available: true, preOrderEnabled: true, releaseDate } } } });
|
||||
}
|
||||
return { reqs, problems, warnings };
|
||||
}
|
||||
|
||||
/** POST /v1/endAppAvailabilityPreOrders: end the pre-order in these territories and release there now. */
|
||||
export function endPreOrderReq(rows: TerritoryAvail[], territories: string[] | null): Req | null {
|
||||
const pick = rows.filter(r => r.preOrderEnabled && (!territories || territories.includes(r.territory)));
|
||||
if (!pick.length) return null;
|
||||
return { method: 'POST', path: '/v1/endAppAvailabilityPreOrders', note: `end the pre-order and release now in ${pick.map(r => r.territory).join(', ')}`,
|
||||
body: { data: { type: 'endAppAvailabilityPreOrders', relationships: { territoryAvailabilities: many('territoryAvailabilities', pick.map(r => r.id)) } } } };
|
||||
}
|
||||
267
cli/lib/originality.ts
Normal file
267
cli/lib/originality.ts
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
// Originality check against the owner's other apps (App Store Guideline 4.3 "spam", Google Play repetitive content):
|
||||
// listing text, icon, screenshots and project structure of this app vs each other app, offline. Every axis is a
|
||||
// 0-1 likeness (1 = the same), the overall score weighs the axes that both apps have, and a pair is flagged as a
|
||||
// near-duplicate above the threshold or when one axis alone is nearly identical. Suggestions follow the
|
||||
// portfolio-originality skill: deepen one axis until it is clearly different, or merge the idea into the other app.
|
||||
import { createHash } from 'node:crypto';
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join, relative } from 'node:path';
|
||||
import type { ShipConfig } from './config';
|
||||
import { parseAppStoreListing, parsePlayListing } from './copy';
|
||||
import { hashFile, type ImageHash, imageSimilarity } from './imagehash';
|
||||
import { findIcon } from './project-files';
|
||||
|
||||
export interface OriginalityConfig {
|
||||
/** Other apps: folders with a storebound.config.ts, or workspace folders holding several (one level down). */
|
||||
against?: string[];
|
||||
/** Overall score from which a pair counts as a near-duplicate (0-1). Default 0.7. */
|
||||
threshold?: number;
|
||||
}
|
||||
|
||||
export function validateOriginality(o: OriginalityConfig | undefined): string[] {
|
||||
if (!o) return [];
|
||||
const e: string[] = [];
|
||||
if (o.against && (!Array.isArray(o.against) || o.against.some(x => typeof x !== 'string' || !x))) e.push('originality.against: a list of folders');
|
||||
if (o.threshold !== undefined && !(o.threshold > 0 && o.threshold < 1)) e.push('originality.threshold: between 0 and 1 (e.g. 0.7)');
|
||||
return e;
|
||||
}
|
||||
|
||||
export const DEFAULT_THRESHOLD = 0.7;
|
||||
/** One axis alone at or above this likeness flags the pair too. */
|
||||
export const AXIS_FLAG = { text: 0.8, name: 0.85, icon: 0.85, screenshots: 0.8, structure: 0.85 } as const;
|
||||
const WEIGHTS = { text: 0.3, icon: 0.2, screenshots: 0.3, structure: 0.2 } as const;
|
||||
|
||||
// ---- text ----
|
||||
|
||||
const STOP = new Set(('a an and are as at be but by for from has have in is it its of on or our so that the their them this to us was we were will '
|
||||
+ 'with you your yours all any can more most new no not now one only just get got out up very than then there these those into over each '
|
||||
+ 'app apps game games play free').split(' '));
|
||||
|
||||
export const words = (s: string): string[] => (s.toLowerCase().normalize('NFKC').match(/[\p{L}\p{N}]+/gu) ?? []).filter(w => w.length > 1 && !STOP.has(w));
|
||||
|
||||
function cosine(a: string[], b: string[]): number {
|
||||
if (!a.length || !b.length) return 0;
|
||||
const ta = new Map<string, number>(), tb = new Map<string, number>();
|
||||
for (const w of a) ta.set(w, (ta.get(w) ?? 0) + 1);
|
||||
for (const w of b) tb.set(w, (tb.get(w) ?? 0) + 1);
|
||||
let dot = 0, na = 0, nb = 0;
|
||||
for (const [w, n] of ta) { na += n * n; dot += n * (tb.get(w) ?? 0); }
|
||||
for (const n of tb.values()) nb += n * n;
|
||||
return dot / Math.sqrt(na * nb);
|
||||
}
|
||||
|
||||
const shingles = (w: string[], k = 3): Set<string> => { const s = new Set<string>(); for (let i = 0; i + k <= w.length; i++) s.add(w.slice(i, i + k).join(' ')); return s; };
|
||||
|
||||
export function jaccard<T>(a: Set<T>, b: Set<T>): number {
|
||||
if (!a.size && !b.size) return 0;
|
||||
let n = 0;
|
||||
for (const x of a) if (b.has(x)) n++;
|
||||
return n / (a.size + b.size - n);
|
||||
}
|
||||
|
||||
/** Bigram (character pair) Dice coefficient of two short strings (app names). */
|
||||
export function nameSimilarity(a: string, b: string): number {
|
||||
const norm = (s: string) => s.toLowerCase().normalize('NFKC').replace(/[^\p{L}\p{N}]+/gu, '');
|
||||
const x = norm(a), y = norm(b);
|
||||
if (!x || !y) return 0;
|
||||
if (x === y) return 1;
|
||||
const bi = (s: string) => { const m = new Map<string, number>(); for (let i = 0; i < s.length - 1; i++) { const k = s.slice(i, i + 2); m.set(k, (m.get(k) ?? 0) + 1); } return m; };
|
||||
const A = bi(x), B = bi(y);
|
||||
let inter = 0;
|
||||
for (const [k, n] of A) inter += Math.min(n, B.get(k) ?? 0);
|
||||
const total = Math.max(1, x.length - 1 + y.length - 1);
|
||||
return (2 * inter) / total;
|
||||
}
|
||||
|
||||
/** Listing text likeness: word frequency cosine (same promises and vocabulary) and 3-word shingle overlap (copied
|
||||
* sentences), 0.6 / 0.4. */
|
||||
export function textSimilarity(a: string, b: string): { score: number; cosine: number; shingles: number } {
|
||||
const wa = words(a), wb = words(b);
|
||||
const c = cosine(wa, wb), s = jaccard(shingles(wa), shingles(wb));
|
||||
return { score: 0.6 * c + 0.4 * s, cosine: c, shingles: s };
|
||||
}
|
||||
|
||||
// ---- fingerprint ----
|
||||
|
||||
export interface AppFingerprint {
|
||||
name: string;
|
||||
dir: string;
|
||||
ids: string[];
|
||||
/** Listing text of the primary language (name, subtitle, keywords, descriptions). */
|
||||
text: string;
|
||||
icon: ImageHash | null;
|
||||
shots: ImageHash[];
|
||||
/** Relative file paths (folder layout) and content hashes of the project's own files. */
|
||||
paths: Set<string>;
|
||||
contents: Set<string>;
|
||||
notes: string[];
|
||||
}
|
||||
|
||||
const SKIP = new Set(['node_modules', '.git', 'build', 'dist', 'Pods', 'DerivedData', '.gradle', '.storebound', '.dart_tool', 'Library', 'Temp', 'Logs',
|
||||
'obj', '.idea', '.vscode', 'renders', '.next', '.expo', 'coverage', 'www', 'public']);
|
||||
export const MAX_FILES = 20_000;
|
||||
const MAX_HASH_BYTES = 4_000_000;
|
||||
|
||||
/** Folder layout and content hashes of a project, bounded (MAX_FILES). Store renders and build output are left out:
|
||||
* screenshots have their own axis, build output is not the developer's work. */
|
||||
export function projectStructure(root: string): { paths: Set<string>; contents: Set<string>; truncated: boolean } {
|
||||
const paths = new Set<string>(), contents = new Set<string>();
|
||||
let count = 0, truncated = false;
|
||||
const walk = (d: string): void => {
|
||||
let names: string[];
|
||||
try { names = readdirSync(d).sort(); } catch { return; }
|
||||
for (const n of names) {
|
||||
if (count >= MAX_FILES) { truncated = true; return; }
|
||||
if (n.startsWith('.') && n !== '.github') continue;
|
||||
const p = join(d, n);
|
||||
let st;
|
||||
try { st = statSync(p); } catch { continue; }
|
||||
if (st.isDirectory()) { if (!SKIP.has(n) && !n.endsWith('.xcarchive')) walk(p); continue; }
|
||||
count++;
|
||||
// names that carry the app's identity (bundle id folders, app names) are normalized away by keeping the extension and depth
|
||||
paths.add(relative(root, p).split(/[\\/]/).map((seg, i, all) => (i === all.length - 1 ? seg.toLowerCase() : seg.toLowerCase().replace(/[^a-z]+/g, '-'))).join('/'));
|
||||
if (st.size > 0 && st.size <= MAX_HASH_BYTES) { try { contents.add(createHash('md5').update(readFileSync(p)).digest('hex')); } catch { /* unreadable */ } }
|
||||
}
|
||||
};
|
||||
walk(root);
|
||||
return { paths, contents, truncated };
|
||||
}
|
||||
|
||||
function primaryText(config: ShipConfig, root: string, notes: string[]): string {
|
||||
const parts: string[] = [config.app.name];
|
||||
const read = (rel: string): string | null => { try { return readFileSync(join(root, rel), 'utf8'); } catch { return null; } };
|
||||
if (config.apple) {
|
||||
const md = read(config.apple.listing ?? 'store/appstore.md');
|
||||
if (md) try {
|
||||
const all = parseAppStoreListing(md);
|
||||
const loc = config.apple.primaryLocale ?? (all['en-US'] ? 'en-US' : Object.keys(all)[0]);
|
||||
const c = loc ? all[loc] : undefined;
|
||||
if (c) parts.push(c.name ?? '', c.subtitle ?? '', (c.keywords ?? '').replace(/,/g, ' '), c.promotionalText ?? '', c.description ?? '');
|
||||
} catch (e) { notes.push(`App Store listing not readable: ${(e as Error).message.slice(0, 120)}`); }
|
||||
else notes.push('no App Store listing file');
|
||||
}
|
||||
if (config.play) {
|
||||
const md = read(config.play.listing ?? 'store/listing.md');
|
||||
if (md) try {
|
||||
const all = parsePlayListing(md, config.app.name);
|
||||
const c = all.find(x => x.lang === (config.play!.defaultLanguage ?? 'en-US')) ?? all[0];
|
||||
if (c) parts.push(c.title, c.short, c.full);
|
||||
} catch (e) { notes.push(`Play listing not readable: ${(e as Error).message.slice(0, 120)}`); }
|
||||
else notes.push('no Play listing file');
|
||||
}
|
||||
return parts.filter(Boolean).join('\n');
|
||||
}
|
||||
|
||||
function screenshotFiles(config: ShipConfig, root: string): string[] {
|
||||
const dir = join(root, config.renders ?? config.shots?.out ?? 'store/renders');
|
||||
if (!existsSync(dir)) return [];
|
||||
const langs = readdirSync(dir).filter(n => { try { return statSync(join(dir, n)).isDirectory(); } catch { return false; } });
|
||||
const lang = langs.find(l => l === config.languages[0]?.id) ?? langs.find(l => l !== 'feature') ?? null;
|
||||
if (!lang) return [];
|
||||
const sizes = readdirSync(join(dir, lang)).map(s => join(dir, lang, s)).filter(p => { try { return statSync(p).isDirectory(); } catch { return false; } });
|
||||
const imgs = (d: string) => readdirSync(d).filter(f => /\.(png|jpe?g|webp)$/i.test(f) && !/contact|sheet|index/i.test(f)).sort().map(f => join(d, f));
|
||||
const best = sizes.map(imgs).sort((a, b) => b.length - a.length)[0] ?? imgs(join(dir, lang));
|
||||
return best.slice(0, 10);
|
||||
}
|
||||
|
||||
/** Everything the comparison needs from one app's folder and config. */
|
||||
export function fingerprint(config: ShipConfig, root: string): AppFingerprint {
|
||||
const notes: string[] = [];
|
||||
const iconPath = findIcon(config, root);
|
||||
let icon: ImageHash | null = null;
|
||||
if (iconPath) { const h = hashFile(iconPath); icon = h.hash; if (!h.hash) notes.push(`icon not hashed: ${h.reason}`); } else notes.push('no icon found');
|
||||
const files = screenshotFiles(config, root);
|
||||
const shots: ImageHash[] = [];
|
||||
for (const f of files) { const h = hashFile(f); if (h.hash) shots.push(h.hash); else notes.push(`${relative(root, f)}: ${h.reason}`); }
|
||||
if (!files.length) notes.push('no rendered screenshots (shots render)');
|
||||
const st = projectStructure(root);
|
||||
if (st.truncated) notes.push(`project structure: first ${MAX_FILES} files only`);
|
||||
return { name: config.app.name, dir: root, ids: [config.apple?.bundleId, config.play?.packageName].filter((x): x is string => !!x),
|
||||
text: primaryText(config, root, notes), icon, shots, paths: st.paths, contents: st.contents, notes };
|
||||
}
|
||||
|
||||
// ---- comparison ----
|
||||
|
||||
/** Image likeness on a 0-1 scale where unrelated pictures land near 0 (raw hash similarity of unrelated images is ~0.5). */
|
||||
export const imageLikeness = (a: ImageHash, b: ImageHash): number => Math.max(0, (imageSimilarity(a, b) - 0.5) / 0.5);
|
||||
|
||||
/** Mean of each screenshot's best match in the other set, both directions. */
|
||||
export function screenshotSimilarity(a: ImageHash[], b: ImageHash[]): number | null {
|
||||
if (!a.length || !b.length) return null;
|
||||
const best = (x: ImageHash[], y: ImageHash[]) => x.reduce((s, h) => s + Math.max(...y.map(k => imageLikeness(h, k))), 0) / x.length;
|
||||
return (best(a, b) + best(b, a)) / 2;
|
||||
}
|
||||
|
||||
export interface Axis { score: number | null; detail: string }
|
||||
export interface PairResult {
|
||||
other: { name: string; dir: string; ids: string[] };
|
||||
axes: { name: Axis; text: Axis; icon: Axis; screenshots: Axis; structure: Axis };
|
||||
overall: number;
|
||||
flagged: boolean;
|
||||
reasons: string[];
|
||||
suggestions: string[];
|
||||
}
|
||||
|
||||
const r2 = (x: number): number => Math.round(x * 100) / 100;
|
||||
|
||||
export function compare(a: AppFingerprint, b: AppFingerprint, threshold = DEFAULT_THRESHOLD): PairResult {
|
||||
const name = nameSimilarity(a.name, b.name);
|
||||
const t = a.text && b.text ? textSimilarity(a.text, b.text) : null;
|
||||
const icon = a.icon && b.icon ? imageLikeness(a.icon, b.icon) : null;
|
||||
const shots = screenshotSimilarity(a.shots, b.shots);
|
||||
const layout = a.paths.size && b.paths.size ? jaccard(a.paths, b.paths) : null;
|
||||
const content = a.contents.size && b.contents.size ? jaccard(a.contents, b.contents) : null;
|
||||
const structure = layout === null || content === null ? null : 0.4 * layout + 0.6 * content;
|
||||
const axes: PairResult['axes'] = {
|
||||
name: { score: r2(name), detail: `"${a.name}" vs "${b.name}"` },
|
||||
text: { score: t ? r2(t.score) : null, detail: t ? `vocabulary ${Math.round(t.cosine * 100)}%, copied phrases ${Math.round(t.shingles * 100)}%` : 'no listing text on one side' },
|
||||
icon: { score: icon === null ? null : r2(icon), detail: icon === null ? 'no icon on one side' : `perceptual hash likeness ${Math.round(icon * 100)}%` },
|
||||
screenshots: { score: shots === null ? null : r2(shots), detail: shots === null ? 'no screenshots on one side' : `${a.shots.length} vs ${b.shots.length} screenshots, best-match likeness ${Math.round(shots * 100)}%` },
|
||||
structure: { score: structure === null ? null : r2(structure), detail: structure === null ? 'no project files on one side' : `same file layout ${Math.round(layout! * 100)}%, identical files ${Math.round(content! * 100)}%` },
|
||||
};
|
||||
let wsum = 0, sum = 0;
|
||||
for (const k of ['text', 'icon', 'screenshots', 'structure'] as const) { const s = axes[k].score; if (s !== null) { wsum += WEIGHTS[k]; sum += WEIGHTS[k] * s; } }
|
||||
const overall = wsum ? r2(sum / wsum) : 0;
|
||||
const reasons: string[] = [];
|
||||
if (overall >= threshold) reasons.push(`overall ${overall} >= ${threshold}`);
|
||||
for (const k of ['name', 'text', 'icon', 'screenshots', 'structure'] as const) { const s = axes[k].score; if (s !== null && s >= AXIS_FLAG[k]) reasons.push(`${k} ${s} (${axes[k].detail})`); }
|
||||
return { other: { name: b.name, dir: b.dir, ids: b.ids }, axes, overall, flagged: reasons.length > 0, reasons, suggestions: suggest(axes, reasons.length > 0, overall, b.name) };
|
||||
}
|
||||
|
||||
export function suggest(axes: PairResult['axes'], flagged: boolean, overall: number, other: string): string[] {
|
||||
const s: string[] = [];
|
||||
const hi = (k: keyof typeof axes, x: number) => (axes[k].score ?? 0) >= x;
|
||||
if (hi('text', 0.6)) s.push(`Rewrite the listing around what is different from ${other} (another promise and audience), not synonyms: reviewers read both pages side by side`);
|
||||
if (hi('name', 0.7)) s.push(`Pick a name that does not read as a variant of "${other}"`);
|
||||
if (hi('icon', 0.7)) s.push('Make an icon with its own shape and subject, not a recolour of the other icon');
|
||||
if (hi('screenshots', 0.6)) s.push('Show different scenes and messages in the screenshots: the first screenshot should show what this app does that the other cannot');
|
||||
if (hi('structure', 0.6)) s.push(`Most project files are shared with ${other}: a template or reskin. Apple reviewers compare binaries; deepen one axis (core mechanic, progression, main task) until a user sees it in the first minute`);
|
||||
if (flagged) {
|
||||
s.push(`Write the differentiator: "Unlike ${other}, in this app the user <does something they cannot do there>". If it needs "theme", "skin", "colours" or "levels", it is not one`);
|
||||
if (overall >= 0.85) s.push(`Consider merging this into ${other} as a mode, world or event instead of a separate app (Guideline 4.3: fewer, richer apps)`);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
export interface OriginalityReport { app: { name: string; dir: string; ids: string[]; notes: string[] }; threshold: number; pairs: PairResult[]; flagged: number; others: { dir: string; notes: string[] }[] }
|
||||
|
||||
export function report(self: AppFingerprint, others: AppFingerprint[], threshold = DEFAULT_THRESHOLD): OriginalityReport {
|
||||
const pairs = others.map(o => compare(self, o, threshold)).sort((x, y) => y.overall - x.overall);
|
||||
return { app: { name: self.name, dir: self.dir, ids: self.ids, notes: self.notes }, threshold, pairs, flagged: pairs.filter(p => p.flagged).length,
|
||||
others: others.map(o => ({ dir: o.dir, notes: o.notes })) };
|
||||
}
|
||||
|
||||
/** Config files of the apps to compare with: each folder itself when it holds a storebound config, else its
|
||||
* sub-folders that do (a workspace). `self` (this app's folder) is left out. */
|
||||
export function findApps(folders: string[], self: string, configNames = ['storebound.config.ts', 'storebound.config.js', 'storebound.config.json']): string[] {
|
||||
const cfg = (d: string) => configNames.map(n => join(d, n)).find(existsSync) ?? null;
|
||||
const out: string[] = [];
|
||||
for (const f of folders) {
|
||||
const own = cfg(f);
|
||||
if (own) { out.push(own); continue; }
|
||||
let subs: string[] = [];
|
||||
try { subs = readdirSync(f).map(n => join(f, n)).filter(p => { try { return statSync(p).isDirectory(); } catch { return false; } }); } catch { /* missing */ }
|
||||
for (const s of subs.sort()) { const c = cfg(s); if (c) out.push(c); }
|
||||
}
|
||||
return [...new Set(out)].filter(p => !p.startsWith(join(self, 'storebound.config')));
|
||||
}
|
||||
128
cli/lib/plist.ts
Normal file
128
cli/lib/plist.ts
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
// Property lists without dependencies: write XML plists (ExportOptions.plist), read XML and binary plists (a source or
|
||||
// IPA Info.plist, the plist inside a .mobileprovision). Only the types those files use: dict, array, string, integer,
|
||||
// real, true / false, date (as an ISO string) and data (as a Buffer). Pure.
|
||||
export type PlistValue = string | number | boolean | Buffer | PlistValue[] | { [k: string]: PlistValue };
|
||||
|
||||
const esc = (s: string): string => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
|
||||
function xmlValue(v: PlistValue, ind: string): string {
|
||||
if (typeof v === 'string') return `${ind}<string>${esc(v)}</string>`;
|
||||
if (typeof v === 'boolean') return `${ind}<${v}/>`;
|
||||
if (typeof v === 'number') return Number.isInteger(v) ? `${ind}<integer>${v}</integer>` : `${ind}<real>${v}</real>`;
|
||||
if (Buffer.isBuffer(v)) return `${ind}<data>${v.toString('base64')}</data>`;
|
||||
if (Array.isArray(v)) return v.length ? `${ind}<array>\n${v.map(x => xmlValue(x, ind + '\t')).join('\n')}\n${ind}</array>` : `${ind}<array/>`;
|
||||
const keys = Object.keys(v).filter(k => v[k] !== undefined);
|
||||
if (!keys.length) return `${ind}<dict/>`;
|
||||
return `${ind}<dict>\n${keys.map(k => `${ind}\t<key>${esc(k)}</key>\n${xmlValue(v[k]!, ind + '\t')}`).join('\n')}\n${ind}</dict>`;
|
||||
}
|
||||
|
||||
/** XML plist text, the format Xcode writes. */
|
||||
export function toXmlPlist(v: PlistValue): string {
|
||||
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${xmlValue(v, '')}\n</plist>\n`;
|
||||
}
|
||||
|
||||
const unesc = (s: string): string => s.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'")
|
||||
.replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n))).replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16))).replace(/&/g, '&');
|
||||
|
||||
/** Parses an XML plist (tolerant of comments and whitespace). Throws on anything it does not understand. */
|
||||
export function parseXmlPlist(text: string): PlistValue {
|
||||
if (text.startsWith('bplist')) throw new Error('binary plist: read the file as bytes (parsePlist(Buffer)) or convert it with `plutil -convert xml1`');
|
||||
const body = /<plist[^>]*>([\s\S]*)<\/plist>/.exec(text)?.[1] ?? text.replace(/<\?xml[^>]*\?>|<!DOCTYPE[^>]*>/g, '');
|
||||
if (!/<(dict|array|string|integer|real|true|false|date|data)\b/.test(body)) throw new Error('not an XML plist');
|
||||
// tags may carry attributes or a space before "/>" (hand-edited files)
|
||||
const toks = [...body.replace(/<!--[\s\S]*?-->/g, '').matchAll(/<(\/?)([a-zA-Z]+)(?:\s[^>]*?)?\s*(\/?)>|([^<]+)/g)];
|
||||
let i = 0;
|
||||
const skipWs = () => { while (i < toks.length && toks[i]![4] !== undefined && !toks[i]![4]!.trim()) i++; };
|
||||
const text_ = (tag: string): string => {
|
||||
let s = '';
|
||||
while (i < toks.length && !(toks[i]![1] === '/' && toks[i]![2] === tag)) { s += toks[i]![4] ?? ''; i++; }
|
||||
i++;
|
||||
return unesc(s);
|
||||
};
|
||||
function value(): PlistValue {
|
||||
skipWs();
|
||||
const t = toks[i++];
|
||||
if (!t || t[1]) throw new Error('plist: unexpected end or closing tag');
|
||||
const tag = t[2]!, selfClose = t[3] === '/';
|
||||
if (tag === 'true' || tag === 'false') { if (!selfClose) text_(tag); return tag === 'true'; }
|
||||
if (selfClose) return tag === 'array' ? [] : tag === 'dict' ? {} : tag === 'data' ? Buffer.alloc(0) : '';
|
||||
if (tag === 'string' || tag === 'date') return text_(tag);
|
||||
if (tag === 'integer' || tag === 'real') return Number(text_(tag).trim());
|
||||
if (tag === 'data') return Buffer.from(text_(tag).replace(/\s+/g, ''), 'base64');
|
||||
if (tag === 'array') {
|
||||
const out: PlistValue[] = [];
|
||||
for (;;) { skipWs(); if (toks[i]?.[1] === '/' && toks[i]![2] === 'array') { i++; return out; } out.push(value()); }
|
||||
}
|
||||
if (tag === 'dict') {
|
||||
const out: Record<string, PlistValue> = {};
|
||||
for (;;) {
|
||||
skipWs();
|
||||
const k = toks[i];
|
||||
if (k?.[1] === '/' && k[2] === 'dict') { i++; return out; }
|
||||
if (k?.[2] !== 'key') throw new Error('plist: <key> expected in <dict>');
|
||||
i++;
|
||||
out[text_('key')] = value();
|
||||
}
|
||||
}
|
||||
throw new Error(`plist: unsupported <${tag}>`);
|
||||
}
|
||||
return value();
|
||||
}
|
||||
|
||||
/** Parses a binary plist ("bplist00"). */
|
||||
export function parseBinaryPlist(b: Buffer): PlistValue {
|
||||
if (b.subarray(0, 8).toString('latin1') !== 'bplist00') throw new Error('not a binary plist');
|
||||
const t = b.subarray(b.length - 32);
|
||||
const offSize = t[6]!, refSize = t[7]!;
|
||||
const numObjects = Number(t.readBigUInt64BE(8)), top = Number(t.readBigUInt64BE(16)), tableOff = Number(t.readBigUInt64BE(24));
|
||||
const uint = (at: number, n: number): number => { let v = 0; for (let k = 0; k < n; k++) v = v * 256 + b[at + k]!; return v; };
|
||||
const offset = (ref: number): number => uint(tableOff + ref * offSize, offSize);
|
||||
const depth = { n: 0 };
|
||||
function obj(ref: number): PlistValue {
|
||||
if (ref >= numObjects) throw new Error('bplist: bad object reference');
|
||||
if (++depth.n > 512) throw new Error('bplist: too deep');
|
||||
try {
|
||||
const at = offset(ref);
|
||||
const m = b[at]!, hi = m >> 4, lo = m & 15;
|
||||
const len = (): [number, number] => {
|
||||
if (lo !== 15) return [lo, at + 1];
|
||||
const sz = 1 << (b[at + 1]! & 15);
|
||||
return [uint(at + 2, sz), at + 2 + sz];
|
||||
};
|
||||
switch (hi) {
|
||||
case 0: return lo === 9; // 0x08 false, 0x09 true (0x00 null -> false)
|
||||
case 1: { const n = 1 << lo; return n === 8 ? Number(b.readBigInt64BE(at + 1)) : uint(at + 1, n); }
|
||||
case 2: return lo === 2 ? b.readFloatBE(at + 1) : b.readDoubleBE(at + 1);
|
||||
case 3: return new Date(Date.UTC(2001, 0, 1) + b.readDoubleBE(at + 1) * 1000).toISOString();
|
||||
case 4: { const [n, s] = len(); return Buffer.from(b.subarray(s, s + n)); }
|
||||
case 5: { const [n, s] = len(); return b.subarray(s, s + n).toString('latin1'); }
|
||||
case 6: { const [n, s] = len(); const u = Buffer.from(b.subarray(s, s + n * 2)); u.swap16(); return u.toString('utf16le'); }
|
||||
case 8: return uint(at + 1, lo + 1);
|
||||
case 10: { const [n, s] = len(); return Array.from({ length: n }, (_, k) => obj(uint(s + k * refSize, refSize))); }
|
||||
case 13: {
|
||||
const [n, s] = len();
|
||||
const out: Record<string, PlistValue> = {};
|
||||
for (let k = 0; k < n; k++) out[String(obj(uint(s + k * refSize, refSize)))] = obj(uint(s + (n + k) * refSize, refSize));
|
||||
return out;
|
||||
}
|
||||
default: throw new Error(`bplist: unsupported object type 0x${m.toString(16)}`);
|
||||
}
|
||||
} finally { depth.n--; }
|
||||
}
|
||||
return obj(top);
|
||||
}
|
||||
|
||||
/** XML or binary plist bytes, or XML plist text. */
|
||||
export function parsePlist(b: Buffer | string): PlistValue {
|
||||
if (typeof b === 'string') return parseXmlPlist(b);
|
||||
return b.subarray(0, 8).toString('latin1') === 'bplist00' ? parseBinaryPlist(b) : parseXmlPlist(b.toString('utf8'));
|
||||
}
|
||||
|
||||
/** The plist embedded in a .mobileprovision (a CMS envelope around an XML plist; the signature is not checked). */
|
||||
export function parseMobileprovision(b: Buffer): Record<string, PlistValue> {
|
||||
const s = b.toString('latin1');
|
||||
const start = s.indexOf('<?xml'), end = s.indexOf('</plist>');
|
||||
if (start < 0 || end < 0) throw new Error('not a provisioning profile (no embedded plist)');
|
||||
return parseXmlPlist(Buffer.from(s.slice(start, end + 8), 'latin1').toString('utf8')) as Record<string, PlistValue>;
|
||||
}
|
||||
|
|
@ -11,6 +11,8 @@ export function profileIssues(config: ShipConfig, o: { demoAccount: boolean }):
|
|||
const err = (msg: string) => out.push({ level: 'error', msg });
|
||||
const warn = (msg: string) => out.push({ level: 'warn', msg });
|
||||
const accounts = !!config.accounts?.enabled;
|
||||
if (config.dataSafety) for (const k of ['collectsData', 'encryptedInTransit', 'deletionRequest'] as const)
|
||||
if (typeof config.dataSafety[k] !== 'boolean') err(`dataSafety.${k}: not answered (true | false; ask the owner, store-declarations skill)`);
|
||||
const acm = config.dataSafety?.accountCreation ?? ['PSL_ACM_NONE'];
|
||||
if (accounts) {
|
||||
if (config.play && !config.accounts!.deletionUrl) err('accounts.enabled: set accounts.deletionUrl (Play asks for a web page to request account deletion; account-deletion skill)');
|
||||
|
|
|
|||
150
cli/lib/reports.ts
Normal file
150
cli/lib/reports.ts
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
// Sales and finance reports, as pure parts: request paths, file names and the summaries. The command
|
||||
// (cli/reports.ts) downloads into .storebound/reports/ (gitignored: these files hold per-order and per-buyer-location
|
||||
// rows) and prints / exports only aggregates.
|
||||
// Sources (checked October 2026):
|
||||
// Apple: GET /v1/salesReports (filter[vendorNumber], filter[reportType], filter[reportSubType], filter[frequency],
|
||||
// filter[reportDate], filter[version]; answer application/a-gzip, tab-separated text) and GET /v1/financeReports
|
||||
// (filter[vendorNumber], filter[reportType] FINANCIAL | FINANCE_DETAIL, filter[regionCode], filter[reportDate] =
|
||||
// fiscal month YYYY-MM). Team key only, not an individual key.
|
||||
// https://developer.apple.com/documentation/appstoreconnectapi/get-v1-salesreports
|
||||
// https://developer.apple.com/documentation/appstoreconnectapi/get-v1-financereports
|
||||
// Allowed combinations (docs table): SALES SUMMARY DAILY|WEEKLY|MONTHLY|YEARLY 1_0; SUBSCRIPTION SUMMARY DAILY 1_3;
|
||||
// SUBSCRIPTION_EVENT SUMMARY DAILY 1_3; SUBSCRIBER DETAILED DAILY 1_3; PRE_ORDER SUMMARY ... 1_0;
|
||||
// SUBSCRIPTION_OFFER_CODE_REDEMPTION SUMMARY DAILY 1_0; WIN_BACK_ELIGIBILITY SUMMARY DAILY 1_0; INSTALLS ...
|
||||
// Region codes (Help, "Financial report regions and currencies"): ZZ = all regions consolidated (FINANCIAL),
|
||||
// Z1 = the Financial Detail report (FINANCE_DETAIL).
|
||||
// Summary Sales Report columns (Help): Provider, Provider Country, SKU, Developer, Title, Version, Product Type
|
||||
// Identifier, Units, Developer Proceeds, Begin Date, End Date, Customer Currency, Country Code, Currency of Proceeds,
|
||||
// Apple Identifier, Customer Price, ...
|
||||
// Google Play: Cloud Storage bucket of the developer account (play.reportsBucket), read-only scope
|
||||
// devstorage.read_only: earnings/earnings_YYYYMM*.zip and sales/salesreport_YYYYMM*.zip, one CSV inside each.
|
||||
// Earnings columns: Description, Transaction Date, Transaction Time, Tax Type, Transaction Type, Refund Type,
|
||||
// Product Title, Package ID, Product Type, SKU ID, Hardware, Buyer Country, ..., Merchant Currency, Amount
|
||||
// (Merchant Currency), ... Estimated sales columns: Order Number, Order Charged Date, ..., Financial Status, ...,
|
||||
// Product Title, Package ID, Product Type, SKU ID, Currency of Sale, Item Price, Taxes Collected, Charged Amount,
|
||||
// ..., Country of Buyer, ... The service account needs "View financial data" in Play Console.
|
||||
// https://support.google.com/googleplay/android-developer/answer/6135870
|
||||
import { parseCsv } from './csv';
|
||||
|
||||
export const APPLE_SALES_COMBOS: Record<string, { subType: string; frequencies: string[]; version: string }> = {
|
||||
SALES: { subType: 'SUMMARY', frequencies: ['DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY'], version: '1_0' },
|
||||
PRE_ORDER: { subType: 'SUMMARY', frequencies: ['DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY'], version: '1_0' },
|
||||
SUBSCRIPTION: { subType: 'SUMMARY', frequencies: ['DAILY'], version: '1_3' },
|
||||
SUBSCRIPTION_EVENT: { subType: 'SUMMARY', frequencies: ['DAILY'], version: '1_3' },
|
||||
SUBSCRIBER: { subType: 'DETAILED', frequencies: ['DAILY'], version: '1_3' },
|
||||
SUBSCRIPTION_OFFER_CODE_REDEMPTION: { subType: 'SUMMARY', frequencies: ['DAILY'], version: '1_0' },
|
||||
WIN_BACK_ELIGIBILITY: { subType: 'SUMMARY', frequencies: ['DAILY'], version: '1_0' },
|
||||
};
|
||||
|
||||
/** The report date for a frequency: DAILY / WEEKLY YYYY-MM-DD, MONTHLY YYYY-MM, YEARLY YYYY. Default: the newest that
|
||||
* is usually there (yesterday minus one day, last month, last year). */
|
||||
export function appleReportDate(frequency: string, given: string | undefined, now = new Date()): string {
|
||||
if (given) {
|
||||
const ok = frequency === 'YEARLY' ? /^\d{4}$/ : frequency === 'MONTHLY' ? /^\d{4}-\d{2}$/ : /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (!ok.test(given)) throw new Error(`--date for ${frequency}: ${frequency === 'YEARLY' ? 'YYYY' : frequency === 'MONTHLY' ? 'YYYY-MM' : 'YYYY-MM-DD'}`);
|
||||
return given;
|
||||
}
|
||||
const d = new Date(now);
|
||||
if (frequency === 'YEARLY') return String(d.getUTCFullYear() - 1);
|
||||
if (frequency === 'MONTHLY') { d.setUTCDate(1); d.setUTCMonth(d.getUTCMonth() - 1); return d.toISOString().slice(0, 7); }
|
||||
d.setUTCDate(d.getUTCDate() - 2);
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export function appleSalesPath(vendor: string, o: { type: string; frequency: string; date: string; subType?: string; version?: string }): string {
|
||||
const combo = APPLE_SALES_COMBOS[o.type];
|
||||
if (!combo) throw new Error(`--type: one of ${Object.keys(APPLE_SALES_COMBOS).join(', ')}`);
|
||||
if (!combo.frequencies.includes(o.frequency)) throw new Error(`${o.type} reports come ${combo.frequencies.join(' / ')} only`);
|
||||
const q = new URLSearchParams({ 'filter[vendorNumber]': vendor, 'filter[reportType]': o.type, 'filter[reportSubType]': o.subType ?? combo.subType,
|
||||
'filter[frequency]': o.frequency, 'filter[reportDate]': o.date, 'filter[version]': o.version ?? combo.version });
|
||||
return `/v1/salesReports?${q}`;
|
||||
}
|
||||
|
||||
export function appleFinancePath(vendor: string, month: string, o: { type?: 'FINANCIAL' | 'FINANCE_DETAIL'; region?: string } = {}): string {
|
||||
if (!/^\d{4}-\d{2}$/.test(month)) throw new Error('--month YYYY-MM (Apple fiscal month)');
|
||||
const type = o.type ?? 'FINANCIAL';
|
||||
const region = o.region ?? (type === 'FINANCE_DETAIL' ? 'Z1' : 'ZZ');
|
||||
return `/v1/financeReports?${new URLSearchParams({ 'filter[vendorNumber]': vendor, 'filter[reportType]': type, 'filter[regionCode]': region, 'filter[reportDate]': month })}`;
|
||||
}
|
||||
|
||||
/** Tab-separated report text -> records (header row first). Apple's finance reports end with total lines after a
|
||||
* blank line; rows without the first header column are dropped. Pure. */
|
||||
export function parseTsv(text: string): Record<string, string>[] {
|
||||
const lines = text.replace(/^/, '').split(/\r?\n/);
|
||||
const head = (lines[0] ?? '').split('\t').map(h => h.trim());
|
||||
const out: Record<string, string>[] = [];
|
||||
for (const l of lines.slice(1)) {
|
||||
if (!l.trim()) break;
|
||||
const cells = l.split('\t');
|
||||
out.push(Object.fromEntries(head.map((h, i) => [h, (cells[i] ?? '').trim()])));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface SummaryRow { key: string; title: string; currency: string; units: number; amount: number; rows: number }
|
||||
|
||||
const num = (s: string | undefined): number => { const n = Number(String(s ?? '').replace(/,/g, '')); return Number.isFinite(n) ? n : 0; };
|
||||
const round2 = (n: number): number => Math.round(n * 100) / 100;
|
||||
|
||||
function group(rows: Record<string, string>[], keyOf: (r: Record<string, string>) => [string, string, string], unitsOf: (r: Record<string, string>) => number, amountOf: (r: Record<string, string>) => number): SummaryRow[] {
|
||||
const m = new Map<string, SummaryRow>();
|
||||
for (const r of rows) {
|
||||
const [key, title, currency] = keyOf(r);
|
||||
const id = `${key}\u0000${currency}`;
|
||||
const cur = m.get(id) ?? { key, title, currency, units: 0, amount: 0, rows: 0 };
|
||||
cur.units += unitsOf(r); cur.amount += amountOf(r); cur.rows++;
|
||||
m.set(id, cur);
|
||||
}
|
||||
return [...m.values()].map(x => ({ ...x, amount: round2(x.amount) })).sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : a.currency < b.currency ? -1 : a.currency > b.currency ? 1 : 0));
|
||||
}
|
||||
|
||||
/** Summary Sales Report: units and proceeds (units x Developer Proceeds) per SKU and proceeds currency. Pure. */
|
||||
export function summarizeAppleSales(rows: Record<string, string>[]): SummaryRow[] {
|
||||
return group(rows, r => [r.SKU || r['Apple Identifier'] || '?', r.Title ?? '', r['Currency of Proceeds'] ?? ''], r => num(r.Units), r => num(r.Units) * num(r['Developer Proceeds']));
|
||||
}
|
||||
|
||||
/** Financial report: quantity and Extended Partner Share per Vendor Identifier and currency. Pure. */
|
||||
export function summarizeAppleFinance(rows: Record<string, string>[]): SummaryRow[] {
|
||||
return group(rows.filter(r => r['Vendor Identifier'] !== undefined && r['Vendor Identifier'] !== ''),
|
||||
r => [r['Vendor Identifier']!, r.Title ?? '', r['Partner Share Currency'] ?? ''], r => num(r.Quantity), r => num(r['Extended Partner Share']));
|
||||
}
|
||||
|
||||
/** Play earnings: amount in the merchant currency per SKU, transaction type and currency. Pure. */
|
||||
export function summarizePlayEarnings(rows: Record<string, string>[]): SummaryRow[] {
|
||||
return group(rows, r => [`${r['SKU ID'] || r['Product Type'] || '?'} · ${r['Transaction Type'] ?? ''}`, r['Product Title'] ?? '', r['Merchant Currency'] ?? ''],
|
||||
r => (/^charge$/i.test(r['Transaction Type'] ?? '') ? 1 : 0), r => num(r['Amount (Merchant Currency)']));
|
||||
}
|
||||
|
||||
/** Play estimated sales: charged amount per SKU, financial status and currency of sale. Pure. */
|
||||
export function summarizePlaySales(rows: Record<string, string>[]): SummaryRow[] {
|
||||
return group(rows, r => [`${r['SKU ID'] || '?'} · ${r['Financial Status'] ?? ''}`, r['Product Title'] ?? '', r['Currency of Sale'] ?? ''], () => 1, r => num(r['Charged Amount']));
|
||||
}
|
||||
|
||||
/** Total per currency (summaries are never added across currencies). */
|
||||
export function totalsByCurrency(rows: SummaryRow[]): { currency: string; units: number; amount: number }[] {
|
||||
const m = new Map<string, { currency: string; units: number; amount: number }>();
|
||||
for (const r of rows) { const t = m.get(r.currency) ?? { currency: r.currency, units: 0, amount: 0 }; t.units += r.units; t.amount = round2(t.amount + r.amount); m.set(r.currency, t); }
|
||||
return [...m.values()].sort((a, b) => (a.currency < b.currency ? -1 : a.currency > b.currency ? 1 : 0));
|
||||
}
|
||||
|
||||
export const summaryCsvRows = (rows: SummaryRow[]): (string | number)[][] => [['key', 'title', 'currency', 'units', 'amount', 'rows'], ...rows.map(r => [r.key, r.title, r.currency, r.units, r.amount, r.rows])];
|
||||
|
||||
/** Play month -> object name prefix in the bucket. */
|
||||
export const playReportPrefix = (kind: 'earnings' | 'sales', month: string): string => {
|
||||
if (!/^\d{4}-\d{2}$/.test(month)) throw new Error('--month YYYY-MM');
|
||||
return kind === 'earnings' ? `earnings/earnings_${month.replace('-', '')}` : `sales/salesreport_${month.replace('-', '')}`;
|
||||
};
|
||||
|
||||
/** CSV text of a Play report (they are UTF-8, some exports UTF-16 with a BOM). Pure. */
|
||||
export function decodeReport(b: Uint8Array): string {
|
||||
if (b[0] === 0xff && b[1] === 0xfe) return new TextDecoder('utf-16le').decode(b.subarray(2));
|
||||
return new TextDecoder().decode(b).replace(/^/, '');
|
||||
}
|
||||
|
||||
/** Play report CSV -> records keyed by the original header names. Pure. */
|
||||
export const parsePlayCsv = (text: string): Record<string, string>[] => {
|
||||
const [head, ...rest] = parseCsv(text);
|
||||
if (!head) return [];
|
||||
const keys = head.map(h => h.trim());
|
||||
return rest.map(r => Object.fromEntries(keys.map((k, i) => [k, (r[i] ?? '').trim()])));
|
||||
};
|
||||
166
cli/lib/review-submit.ts
Normal file
166
cli/lib/review-submit.ts
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
// Sending in-app purchases and subscriptions to App Review through review submissions, as a pure planner. The command
|
||||
// (cli/apple/iap-submit.ts) reads the state, calls `planIapSubmission`, prints the plan and only sends it after the
|
||||
// owner says yes in a terminal. Never an MCP tool: submitting for review is the owner's action.
|
||||
//
|
||||
// How App Store Connect does it (API 4.4.1+, OpenAPI spec 4.5.1, checked October 2026):
|
||||
// - Every in-app purchase, subscription and subscription group has versions (inAppPurchaseVersions,
|
||||
// subscriptionVersions, subscriptionGroupVersions; GET /v2/inAppPurchases/{id}/versions, /v1/subscriptions/{id}/versions,
|
||||
// /v1/subscriptionGroups/{id}/versions). "Use the In-App Purchase version for submitting to review."
|
||||
// - A version goes to App Review as an item of a review submission: POST /v1/reviewSubmissions (app; platform
|
||||
// optional), POST /v1/reviewSubmissionItems with inAppPurchaseVersion | subscriptionVersion | subscriptionGroupVersion
|
||||
// (or appStoreVersion), then PATCH /v1/reviewSubmissions/{id} { submitted: true }.
|
||||
// The older inAppPurchaseSubmissions / subscriptionSubmissions / subscriptionGroupSubmissions are deprecated.
|
||||
// https://developer.apple.com/documentation/appstoreconnectapi/app-store-connect-api-4-4-1-release-notes
|
||||
// https://developer.apple.com/documentation/appstoreconnectapi/review-submissions
|
||||
// https://developer.apple.com/documentation/appstoreconnectapi/in-app-purchase-versions
|
||||
// The rules (App Store Connect Help, "Submit an In-App Purchase", checked October 2026):
|
||||
// - "The first consumable, non-consumable, auto-renewable subscription, and non-renewing subscription In-App
|
||||
// Purchase of each type must be submitted with a new app version."
|
||||
// - Later items of an approved type go without an app version "as long as your app has at least one approved app
|
||||
// version at the time of submission".
|
||||
// - A new subscription goes together with its subscription group while the group is not approved; "each new
|
||||
// subscription group must be submitted with at least one of its subscriptions".
|
||||
// - Everything reviewed together goes into the same draft submission; up to 200 items per submission.
|
||||
// - In-App Purchases with content hosting can no longer be submitted. In-app purchases are not supported on Apple Watch.
|
||||
// https://developer.apple.com/help/app-store-connect/manage-submissions-to-app-review/submit-an-in-app-purchase
|
||||
import type { Req } from '../apple/jsonapi';
|
||||
import { one } from '../apple/jsonapi';
|
||||
|
||||
export const MAX_SUBMISSION_ITEMS = 200;
|
||||
|
||||
/** App Store version states after which the app counts as having an approved version. */
|
||||
const APPROVED_APP = new Set(['READY_FOR_DISTRIBUTION', 'READY_FOR_SALE', 'PENDING_DEVELOPER_RELEASE', 'PENDING_APPLE_RELEASE', 'PROCESSING_FOR_DISTRIBUTION',
|
||||
'PROCESSING_FOR_APP_STORE', 'REPLACED_WITH_NEW_VERSION', 'ACCEPTED', 'DEVELOPER_REMOVED_FROM_SALE', 'REMOVED_FROM_SALE']);
|
||||
/** Product states (InAppPurchaseState / Subscription.state) that mean the product was approved once. */
|
||||
const APPROVED_PRODUCT = new Set(['APPROVED', 'DEVELOPER_REMOVED_FROM_SALE', 'REMOVED_FROM_SALE']);
|
||||
/** Version states that can still go into a draft submission. */
|
||||
const SUBMITTABLE = new Set(['PREPARE_FOR_SUBMISSION', 'READY_FOR_REVIEW']);
|
||||
const IN_REVIEW = new Set(['WAITING_FOR_REVIEW', 'IN_REVIEW']);
|
||||
|
||||
export type ItemKind = 'inAppPurchaseVersion' | 'subscriptionVersion' | 'subscriptionGroupVersion' | 'appStoreVersion';
|
||||
const ITEM_TYPE: Record<ItemKind, string> = {
|
||||
inAppPurchaseVersion: 'inAppPurchaseVersions', subscriptionVersion: 'subscriptionVersions', subscriptionGroupVersion: 'subscriptionGroupVersions', appStoreVersion: 'appStoreVersions',
|
||||
};
|
||||
|
||||
export interface PVersion { id: string; version?: number; state: string }
|
||||
export interface PIap { id: string; productId: string; type: string; state: string; versions: PVersion[] }
|
||||
export interface PSub { id: string; productId: string; groupId: string; state: string; versions: PVersion[] }
|
||||
export interface PGroup { id: string; name: string; versions: PVersion[] }
|
||||
export interface PAppVersion { id: string; versionString: string; state: string }
|
||||
|
||||
export interface SubmitState {
|
||||
appVersions: PAppVersion[];
|
||||
iaps: PIap[];
|
||||
subs: PSub[];
|
||||
groups: PGroup[];
|
||||
/** The app's draft review submission (state READY_FOR_REVIEW), if one exists, and the version ids already in it. */
|
||||
draft?: { id: string; itemVersionIds: string[] } | null;
|
||||
}
|
||||
|
||||
export interface PlanItem { kind: ItemKind; versionId: string; label: string }
|
||||
export interface SubmitPlan {
|
||||
items: PlanItem[];
|
||||
/** Product ids that are left out, with the reason. */
|
||||
skipped: { id: string; why: string }[];
|
||||
/** Types submitted for the first time (need an app version in the same submission). */
|
||||
firstOfType: string[];
|
||||
hasApprovedVersion: boolean;
|
||||
/** An app version must be in this submission (first of a type, or no approved app version yet). */
|
||||
needsAppVersion: boolean;
|
||||
/** The editable app version that would go in (with withVersion). */
|
||||
appVersion?: PAppVersion;
|
||||
/** Problems that stop the submission (nothing is sent while any is left). */
|
||||
blockers: string[];
|
||||
/** Requests up to and including adding the items (a draft the owner can also submit in App Store Connect). */
|
||||
prepare: Req[];
|
||||
/** The submit request itself (the owner's action). Uses the placeholder id "${submission}" when the draft is new. */
|
||||
submit: Req;
|
||||
}
|
||||
|
||||
const typeLabel = (t: string): string => ({ CONSUMABLE: 'consumable', NON_CONSUMABLE: 'non-consumable', NON_RENEWING_SUBSCRIPTION: 'non-renewing subscription', AUTO_RENEWABLE: 'auto-renewable subscription' }[t] ?? t);
|
||||
|
||||
/** The newest version of a product (highest `version`, else the last listed). */
|
||||
export function latestVersion(vs: PVersion[]): PVersion | undefined {
|
||||
return [...vs].sort((a, b) => (a.version ?? 0) - (b.version ?? 0)).at(-1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan for submitting `want` (product ids of in-app purchases and subscriptions). withVersion: put the editable app
|
||||
* version into the same submission (needed for the first item of a type, or while the app has no approved version).
|
||||
*/
|
||||
export function planIapSubmission(s: SubmitState, want: string[], o: { withVersion?: boolean } = {}): SubmitPlan {
|
||||
const plan: SubmitPlan = { items: [], skipped: [], firstOfType: [], hasApprovedVersion: s.appVersions.some(v => APPROVED_APP.has(v.state)), needsAppVersion: false, blockers: [], prepare: [],
|
||||
submit: { method: 'PATCH', path: '/v1/reviewSubmissions/${submission}', note: 'submit for App Review', body: {} } };
|
||||
const approvedTypes = new Set([...s.iaps.filter(p => APPROVED_PRODUCT.has(p.state)).map(p => p.type), ...(s.subs.some(x => APPROVED_PRODUCT.has(x.state)) ? ['AUTO_RENEWABLE'] : [])]);
|
||||
const firstTypes = new Set<string>();
|
||||
const already = new Set(s.draft?.itemVersionIds ?? []);
|
||||
const groupsNeeded = new Set<string>();
|
||||
|
||||
const pick = (id: string, productState: string, versions: PVersion[], kind: ItemKind, type: string): void => {
|
||||
if (productState === 'MISSING_METADATA') { plan.skipped.push({ id, why: 'missing metadata (price, localization or review screenshot): storebound apple iap / apple subscriptions / apple iap-review' }); return; }
|
||||
if (productState === 'WAITING_FOR_UPLOAD' || productState === 'PROCESSING_CONTENT') { plan.skipped.push({ id, why: `hosted content ${productState}: content-hosted purchases can no longer be submitted` }); return; }
|
||||
const v = latestVersion(versions);
|
||||
if (!v) { plan.skipped.push({ id, why: 'no version on App Store Connect yet (create the product first: storebound apple iap / apple subscriptions)' }); return; }
|
||||
if (IN_REVIEW.has(v.state)) { plan.skipped.push({ id, why: `already ${v.state}` }); return; }
|
||||
if (!SUBMITTABLE.has(v.state)) { plan.skipped.push({ id, why: `latest version is ${v.state}: change it in App Store Connect (or --new-version) to send a new version` }); return; }
|
||||
if (already.has(v.id)) { plan.skipped.push({ id, why: 'already in the draft submission' }); return; }
|
||||
plan.items.push({ kind, versionId: v.id, label: `${id} (${typeLabel(type)}, version ${v.version ?? '?'})` });
|
||||
if (!approvedTypes.has(type)) firstTypes.add(type);
|
||||
};
|
||||
|
||||
for (const id of want) {
|
||||
const iap = s.iaps.find(p => p.productId === id);
|
||||
const sub = s.subs.find(p => p.productId === id);
|
||||
if (iap) pick(id, iap.state, iap.versions, 'inAppPurchaseVersion', iap.type);
|
||||
else if (sub) {
|
||||
const before = plan.items.length;
|
||||
pick(id, sub.state, sub.versions, 'subscriptionVersion', 'AUTO_RENEWABLE');
|
||||
if (plan.items.length > before) groupsNeeded.add(sub.groupId);
|
||||
} else plan.skipped.push({ id, why: 'not on App Store Connect (storebound apple iap / apple subscriptions creates it)' });
|
||||
}
|
||||
for (const gid of groupsNeeded) {
|
||||
const g = s.groups.find(x => x.id === gid);
|
||||
if (!g) continue;
|
||||
if (g.versions.some(v => v.state === 'APPROVED') || s.subs.some(x => x.groupId === gid && APPROVED_PRODUCT.has(x.state))) continue;
|
||||
const v = latestVersion(g.versions);
|
||||
if (!v) { plan.blockers.push(`subscription group "${g.name}" has no version to submit`); continue; }
|
||||
if (IN_REVIEW.has(v.state) || already.has(v.id)) continue;
|
||||
if (!SUBMITTABLE.has(v.state)) { plan.blockers.push(`subscription group "${g.name}": version is ${v.state}`); continue; }
|
||||
plan.items.push({ kind: 'subscriptionGroupVersion', versionId: v.id, label: `subscription group "${g.name}" (not approved yet, goes with its subscriptions)` });
|
||||
}
|
||||
plan.firstOfType = [...firstTypes].map(typeLabel);
|
||||
plan.needsAppVersion = plan.items.length > 0 && (firstTypes.size > 0 || !plan.hasApprovedVersion);
|
||||
if (plan.needsAppVersion) {
|
||||
const editable = s.appVersions.find(v => ['PREPARE_FOR_SUBMISSION', 'DEVELOPER_REJECTED', 'REJECTED', 'METADATA_REJECTED', 'INVALID_BINARY', 'READY_FOR_REVIEW'].includes(v.state));
|
||||
const why = firstTypes.size ? `first ${plan.firstOfType.join(' / ')} of this app: Apple reviews it only together with a new app version`
|
||||
: 'the app has no approved version yet: in-app purchases go together with an app version';
|
||||
if (!o.withVersion) plan.blockers.push(`${why}. Add --with-version (the editable version ${editable ? editable.versionString : '(none yet: storebound apple listing --version x.y.z --build N)'} goes into the same submission; submitting it submits the app)`);
|
||||
else if (!editable) plan.blockers.push(`${why}, and there is no editable app version: storebound apple listing --version x.y.z --build N first`);
|
||||
else if (!already.has(editable.id)) { plan.appVersion = editable; plan.items.unshift({ kind: 'appStoreVersion', versionId: editable.id, label: `app version ${editable.versionString}` }); }
|
||||
}
|
||||
if (plan.items.length + (s.draft?.itemVersionIds.length ?? 0) > MAX_SUBMISSION_ITEMS) plan.blockers.push(`more than ${MAX_SUBMISSION_ITEMS} items in one submission: use --only for a part`);
|
||||
const sid = s.draft?.id ?? '${submission}';
|
||||
if (!s.draft && plan.items.length) plan.prepare.push({ method: 'POST', path: '/v1/reviewSubmissions', note: 'new draft review submission', body: { data: { type: 'reviewSubmissions', attributes: { platform: 'IOS' }, relationships: { app: one('apps', '${app}') } } } });
|
||||
for (const it of plan.items) plan.prepare.push({ method: 'POST', path: '/v1/reviewSubmissionItems', note: it.label,
|
||||
body: { data: { type: 'reviewSubmissionItems', relationships: { reviewSubmission: one('reviewSubmissions', sid), [it.kind]: one(ITEM_TYPE[it.kind], it.versionId) } } } });
|
||||
plan.submit = { method: 'PATCH', path: `/v1/reviewSubmissions/${sid}`, note: 'submit for App Review', body: { data: { type: 'reviewSubmissions', id: sid, attributes: { submitted: true } } } };
|
||||
return plan;
|
||||
}
|
||||
|
||||
/** Fills the placeholders of a planned request (app id, the id of the draft created a moment ago). Pure. */
|
||||
export function bindIds(r: Req, ids: { app?: string; submission?: string }): Req {
|
||||
const text = JSON.stringify(r).replaceAll('${app}', ids.app ?? '${app}').replaceAll('${submission}', ids.submission ?? '${submission}');
|
||||
return JSON.parse(text) as Req;
|
||||
}
|
||||
|
||||
/** POST /v1/inAppPurchaseVersions | /v1/subscriptionVersions: a new draft version of an approved (or rejected)
|
||||
* product, "capturing its current localized metadata and review images for App Review submission". */
|
||||
export function newVersionReq(kind: 'iap' | 'sub', productApiId: string, label: string): Req {
|
||||
return kind === 'iap'
|
||||
? { method: 'POST', path: '/v1/inAppPurchaseVersions', note: `new version of ${label}`, body: { data: { type: 'inAppPurchaseVersions', relationships: { inAppPurchase: one('inAppPurchases', productApiId) } } } }
|
||||
: { method: 'POST', path: '/v1/subscriptionVersions', note: `new version of ${label}`, body: { data: { type: 'subscriptionVersions', relationships: { subscription: one('subscriptions', productApiId) } } } };
|
||||
}
|
||||
|
||||
/** Versions response -> PVersion list. Pure. */
|
||||
export const versionsOf = (data: { id: string; attributes?: { version?: number; state?: string } }[]): PVersion[] =>
|
||||
data.map(v => ({ id: v.id, version: v.attributes?.version, state: v.attributes?.state ?? '?' }));
|
||||
|
|
@ -46,7 +46,7 @@ export function childEnv(extra: Record<string, string> = {}, machine = false): R
|
|||
return { ...base, ...extra, NO_COLOR: '1', ...(machine ? { STOREBOUND_MACHINE: '1', STOREBOUND_SERVE: '1' } : {}) };
|
||||
}
|
||||
|
||||
async function pump(stream: ReadableStream<Uint8Array>, kind: 'stdout' | 'stderr', each: (line: string, kind: 'stdout' | 'stderr') => void): Promise<void> {
|
||||
export async function pump(stream: ReadableStream<Uint8Array>, kind: 'stdout' | 'stderr', each: (line: string, kind: 'stdout' | 'stderr') => void): Promise<void> {
|
||||
const dec = new TextDecoder();
|
||||
let buf = '';
|
||||
const reader = stream.getReader();
|
||||
|
|
|
|||
71
cli/lib/scan/config-edit.ts
Normal file
71
cli/lib/scan/config-edit.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
// Writes one top-level block (dataSafety, appPrivacy) into storebound.config.ts / .js / .json text: replaces the
|
||||
// existing `key: { ... }` property, or inserts it after the `app: { ... }` block. Pure text in, text out; the rest of
|
||||
// the file (comments, order, formatting) stays as it is. Used by `storebound scan --write` only.
|
||||
|
||||
/** Index of the brace that closes the one at `open`, skipping strings, template literals and comments. -1 if none. */
|
||||
export function matchBrace(text: string, open: number): number {
|
||||
const pairs: Record<string, string> = { '{': '}', '[': ']', '(': ')' };
|
||||
const stack: string[] = [];
|
||||
for (let i = open; i < text.length; i++) {
|
||||
const ch = text[i]!;
|
||||
if (ch === '/' && text[i + 1] === '/') { i = text.indexOf('\n', i); if (i < 0) return -1; continue; }
|
||||
if (ch === '/' && text[i + 1] === '*') { i = text.indexOf('*/', i + 2); if (i < 0) return -1; i++; continue; }
|
||||
if (ch === '"' || ch === '\'' || ch === '`') {
|
||||
for (i++; i < text.length && text[i] !== ch; i++) if (text[i] === '\\') i++;
|
||||
continue;
|
||||
}
|
||||
if (pairs[ch]) stack.push(pairs[ch]!);
|
||||
else if (ch === '}' || ch === ']' || ch === ')') {
|
||||
if (stack.pop() !== ch) return -1;
|
||||
if (!stack.length) return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
const ID = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
||||
|
||||
/** A plain value as TypeScript source (single quotes, unquoted keys, trailing commas), indented by `ind`. */
|
||||
export function toTs(v: unknown, ind = ''): string {
|
||||
const next = ind + ' ';
|
||||
if (v === null || v === undefined) return 'undefined';
|
||||
if (typeof v === 'string') return `'${v.replace(/\\/g, '\\\\').replace(/'/g, '\\\'')}'`;
|
||||
if (typeof v === 'number' || typeof v === 'boolean') return String(v);
|
||||
if (Array.isArray(v)) {
|
||||
const parts = v.map(x => toTs(x, next));
|
||||
const one = `[${parts.join(', ')}]`;
|
||||
return one.length <= 100 && !one.includes('\n') ? one : `[\n${parts.map(p => `${next}${p},`).join('\n')}\n${ind}]`;
|
||||
}
|
||||
const entries = Object.entries(v as Record<string, unknown>).filter(([, x]) => x !== undefined);
|
||||
if (!entries.length) return '{}';
|
||||
const parts = entries.map(([k, x]) => `${ID.test(k) ? k : `'${k}'`}: ${toTs(x, next)}`);
|
||||
const one = `{ ${parts.join(', ')} }`;
|
||||
return one.length <= 110 && !one.includes('\n') && entries.every(([, x]) => typeof x !== 'object' || Array.isArray(x)) ? one : `{\n${parts.map(p => `${next}${p},`).join('\n')}\n${ind}}`;
|
||||
}
|
||||
|
||||
/** The config text with `key` set to `value` (plus an optional comment line above it). */
|
||||
export function upsertBlock(text: string, file: string, key: string, value: unknown, comment?: string): string {
|
||||
if (file.endsWith('.json')) {
|
||||
const j = JSON.parse(text) as Record<string, unknown>;
|
||||
j[key] = value;
|
||||
return JSON.stringify(j, null, 2) + '\n';
|
||||
}
|
||||
const re = new RegExp(`^([ \\t]*)${key}\\s*:\\s*\\{`, 'm');
|
||||
const m = re.exec(text);
|
||||
if (m) {
|
||||
const ind = m[1]!;
|
||||
const open = m.index + m[0].length - 1;
|
||||
const close = matchBrace(text, open);
|
||||
if (close < 0) throw new Error(`${file}: could not find the end of the ${key} block`);
|
||||
return `${text.slice(0, m.index)}${ind}${key}: ${toTs(value, ind)}${text.slice(close + 1)}`;
|
||||
}
|
||||
const app = /^([ \t]*)app\s*:\s*\{/m.exec(text);
|
||||
if (!app) throw new Error(`${file}: no app block found to insert ${key} after; add it by hand`);
|
||||
const ind = app[1]!;
|
||||
const close = matchBrace(text, app.index + app[0].length - 1);
|
||||
if (close < 0) throw new Error(`${file}: could not find the end of the app block`);
|
||||
let at = close + 1;
|
||||
if (text[at] === ',') at++;
|
||||
const block = `\n${comment ? `${ind}// ${comment}\n` : ''}${ind}${key}: ${toTs(value, ind)},`;
|
||||
return text.slice(0, at) + block + text.slice(at);
|
||||
}
|
||||
155
cli/lib/scan/declare.ts
Normal file
155
cli/lib/scan/declare.ts
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
// Declarations proposal for `storebound scan`: from the detected SDKs, permissions and code, the Play Data safety and
|
||||
// App Store App Privacy answers, App Tracking Transparency and the privacy manifest entries the project needs, each
|
||||
// marked "detected (file:line)" or "ask owner", and a diff against the config's dataSafety / appPrivacy blocks.
|
||||
// Only detected items are ever written (`scan --write`); "ask owner" items stay questions (AGENTS.md rule 5). Pure.
|
||||
import type { AppPrivacyConfig, DataSafety, DataUsage, PlayPurpose, ShipConfig } from '../config';
|
||||
import { APPLE_PRIVACY, applePurpose } from '../declarations';
|
||||
import { REQUIRED_REASON_APIS } from '../privacy-manifest';
|
||||
import { IOS_PERMISSIONS } from './permissions';
|
||||
import { grep, type Hit, lineOf, type ProjectFacts } from './project';
|
||||
import { SIGNALS } from './rules';
|
||||
|
||||
export type DeclArea = 'dataSafety' | 'appPrivacy' | 'att' | 'privacyManifest';
|
||||
export interface DeclItem { area: DeclArea; what: string; value: string; status: 'detected' | 'ask'; evidence: Hit[]; note?: string }
|
||||
export interface DataDiff {
|
||||
type: string;
|
||||
/** App Privacy category / type it maps to. */
|
||||
apple: string;
|
||||
change: 'add' | 'merge' | 'same' | 'kept';
|
||||
before: DataUsage | null;
|
||||
after: DataUsage;
|
||||
evidence: Hit[];
|
||||
}
|
||||
export interface Proposal {
|
||||
items: DeclItem[];
|
||||
diff: DataDiff[];
|
||||
/** The dataSafety block --write would write (null when nothing was detected and the config has none). */
|
||||
dataSafety: Partial<DataSafety> & { data: Record<string, DataUsage> } | null;
|
||||
appPrivacy: AppPrivacyConfig | null;
|
||||
appPrivacyChange: { from: boolean | null; to: boolean } | null;
|
||||
/** Types an SDK collects that the config's dataSafety does not declare (the privacy-labels rule). */
|
||||
labelGaps: { type: string; apple: string; evidence: Hit[] }[];
|
||||
/** --write would change the config. */
|
||||
changed: boolean;
|
||||
}
|
||||
|
||||
const PERMISSION_DATA: Record<string, { type: string; note: string }> = {
|
||||
NSCameraUsageDescription: { type: 'PSL_PHOTOS', note: 'only if photos / videos leave the device (uploaded, sent to an API)' },
|
||||
NSMicrophoneUsageDescription: { type: 'PSL_AUDIO', note: 'only if recordings leave the device' },
|
||||
NSPhotoLibraryUsageDescription: { type: 'PSL_PHOTOS', note: 'only if picked photos leave the device' },
|
||||
NSLocationWhenInUseUsageDescription: { type: 'PSL_APPROX_LOCATION', note: 'approximate or precise (PSL_PRECISE_LOCATION), only if it leaves the device' },
|
||||
NSContactsUsageDescription: { type: 'PSL_CONTACTS', note: 'only if contacts leave the device' },
|
||||
NSHealthShareUsageDescription: { type: 'PSL_HEALTH', note: 'only if health data leaves the device' },
|
||||
NSCalendarsFullAccessUsageDescription: { type: 'PSL_CALENDAR', note: 'only if events leave the device' },
|
||||
};
|
||||
|
||||
const uniq = <T>(a: T[]): T[] => [...new Set(a)];
|
||||
const sorted = (a: readonly string[] | undefined) => [...(a ?? [])].sort().join();
|
||||
const usageEq = (a: DataUsage, b: DataUsage) => a.shared === b.shared && sorted(a.collect) === sorted(b.collect) && sorted(a.share) === sorted(b.share);
|
||||
|
||||
export function proposeDeclarations(p: ProjectFacts, c: ShipConfig | null, configFile?: { path: string; text: string } | null): Proposal {
|
||||
const items: DeclItem[] = [];
|
||||
const detected = new Map<string, { collect: Set<PlayPurpose>; share: Set<PlayPurpose>; evidence: Hit[]; from: string[] }>();
|
||||
for (const s of p.sdks) {
|
||||
const d0 = s.deps[0]!;
|
||||
const ev: Hit = { file: d0.file, line: d0.line, text: `${s.sdk.name}: ${d0.name}${d0.version ? ` ${d0.version}` : ''}` };
|
||||
for (const d of s.sdk.data) {
|
||||
const e = detected.get(d.type) ?? { collect: new Set<PlayPurpose>(), share: new Set<PlayPurpose>(), evidence: [], from: [] };
|
||||
for (const x of d.collect) e.collect.add(x);
|
||||
for (const x of d.share ?? []) e.share.add(x);
|
||||
if (!e.from.includes(s.sdk.name)) { e.from.push(s.sdk.name); e.evidence.push(ev); }
|
||||
detected.set(d.type, e);
|
||||
}
|
||||
}
|
||||
// accounts proven by the config or sign-up code
|
||||
const signUp = grep(p.sources, SIGNALS.signUp, 1);
|
||||
if (c?.accounts?.enabled || signUp.length) {
|
||||
const ev: Hit[] = signUp.length ? signUp : [{ file: configFile?.path ?? 'storebound.config.ts', line: configFile ? lineOf(configFile.text, /accounts\s*:/) : 1, text: 'accounts.enabled' }];
|
||||
for (const t of ['PSL_EMAIL', 'PSL_USER_ACCOUNT']) {
|
||||
const e = detected.get(t) ?? { collect: new Set<PlayPurpose>(), share: new Set<PlayPurpose>(), evidence: [], from: [] };
|
||||
e.collect.add('account'); e.collect.add('functionality'); e.evidence.push(...ev); e.from.push('accounts');
|
||||
detected.set(t, e);
|
||||
}
|
||||
}
|
||||
const have = c?.dataSafety?.data ?? {};
|
||||
const diff: DataDiff[] = [];
|
||||
const out: Record<string, DataUsage> = {};
|
||||
for (const [type, e] of detected) {
|
||||
const share = [...e.share].sort();
|
||||
const det: DataUsage = { shared: share.length > 0, collect: [...e.collect].sort(), ...(share.length ? { share } : {}) };
|
||||
const before = have[type] ?? null;
|
||||
const after: DataUsage = before ? {
|
||||
...before, shared: before.shared || det.shared,
|
||||
collect: uniq([...before.collect, ...det.collect]).sort(),
|
||||
...((before.share?.length || share.length) ? { share: uniq([...(before.share ?? []), ...share]).sort() } : {}),
|
||||
} : det;
|
||||
out[type] = after;
|
||||
const [cat, name] = APPLE_PRIVACY[type] ?? ['Other Data', 'Other Data Types'];
|
||||
diff.push({ type, apple: `${cat} / ${name}`, change: !before ? 'add' : usageEq(before, after) ? 'same' : 'merge', before, after, evidence: e.evidence.slice(0, 3) });
|
||||
items.push({ area: 'dataSafety', what: type, value: `collect: ${after.collect.join(', ')}${after.shared ? `; shared: ${(after.share ?? []).join(', ')}` : ''}`, status: 'detected', evidence: e.evidence.slice(0, 2),
|
||||
note: `from ${e.from.join(', ')}; ephemeral / optional: ask owner` });
|
||||
}
|
||||
for (const [type, u] of Object.entries(have)) if (!detected.has(type)) {
|
||||
out[type] = u;
|
||||
const [cat, name] = APPLE_PRIVACY[type] ?? ['Other Data', 'Other Data Types'];
|
||||
diff.push({ type, apple: `${cat} / ${name}`, change: 'kept', before: u, after: u, evidence: [] });
|
||||
}
|
||||
// permissions that may mean collected data: questions, never written
|
||||
for (const perm of IOS_PERMISSIONS) for (const k of perm.keys) {
|
||||
const e = p.plist.get(k), pd = PERMISSION_DATA[k];
|
||||
if (!e || !pd || out[pd.type]) continue;
|
||||
items.push({ area: 'dataSafety', what: pd.type, value: `collected? ${pd.note}`, status: 'ask', evidence: [{ ...e.at, text: k }] });
|
||||
}
|
||||
const labelGaps = c?.dataSafety ? diff.filter(d => d.change === 'add').map(d => ({ type: d.type, apple: d.apple, evidence: d.evidence })) : [];
|
||||
|
||||
// top-level Data safety answers
|
||||
const anyData = Object.keys(out).length > 0;
|
||||
if (anyData) items.push({ area: 'dataSafety', what: 'collectsData', value: 'true', status: 'detected', evidence: diff.flatMap(d => d.evidence).slice(0, 1) });
|
||||
for (const k of ['encryptedInTransit', 'deletionRequest'] as const)
|
||||
items.push({ area: 'dataSafety', what: k, value: c?.dataSafety ? String(c.dataSafety[k]) : '?', status: 'ask', evidence: [], note: k === 'encryptedInTransit' ? 'all traffic over HTTPS / TLS? (ATS and the SDKs\' own endpoints)' : 'can users ask for their data to be deleted?' });
|
||||
if ((c?.accounts?.enabled || signUp.length) && (c?.dataSafety?.accountCreation ?? ['PSL_ACM_NONE']).includes('PSL_ACM_NONE'))
|
||||
items.push({ area: 'dataSafety', what: 'accountCreation', value: 'which sign-up methods (PSL_ACM_USER_ID_PASSWORD, PSL_ACM_OAUTH, ...)?', status: 'ask', evidence: signUp.slice(0, 1) });
|
||||
|
||||
// App Privacy per type (linked / tracking are owner answers)
|
||||
for (const d of diff) {
|
||||
const shared = d.after.shared ? d.after.share ?? [] : [];
|
||||
// a purpose the data is shared for counts once, as the third party's (AdMob: Third-Party Advertising, not the developer's)
|
||||
const purposes = uniq([...d.after.collect.filter(x => !shared.includes(x)).map(x => applePurpose(x, false)), ...shared.map(x => applePurpose(x, true))]).sort();
|
||||
items.push({ area: 'appPrivacy', what: d.apple, value: purposes.join(', '), status: d.change === 'kept' ? 'ask' : 'detected', evidence: d.evidence.slice(0, 1), note: 'linked to identity? used for tracking? ask owner' });
|
||||
}
|
||||
|
||||
// tracking + ATT
|
||||
const attReq = grep(p.sources, SIGNALS.attRequest, 1);
|
||||
const attStr = p.plist.get('NSUserTrackingUsageDescription');
|
||||
const trackers = p.sdks.filter(s => s.sdk.tracking);
|
||||
let tracking: boolean | null = null;
|
||||
if (attReq.length) { tracking = true; items.push({ area: 'appPrivacy', what: 'tracking', value: 'true (the app asks for App Tracking Transparency)', status: 'detected', evidence: attReq }); }
|
||||
else if (trackers.length) items.push({ area: 'appPrivacy', what: 'tracking', value: `${trackers.map(s => s.sdk.name).join(', ')} can track: personalized ads / attribution on?`, status: 'ask', evidence: trackers.map(s => ({ file: s.deps[0]!.file, line: s.deps[0]!.line, text: s.sdk.name })).slice(0, 2) });
|
||||
if (attStr) items.push({ area: 'att', what: 'NSUserTrackingUsageDescription', value: String(attStr.value).slice(0, 80), status: 'detected', evidence: [{ ...attStr.at, text: 'NSUserTrackingUsageDescription' }] });
|
||||
else if (trackers.length || attReq.length) items.push({ area: 'att', what: 'NSUserTrackingUsageDescription', value: 'needed if anything tracks, e.g. "Your data is used to show ads that fit your interests."', status: 'ask', evidence: [] });
|
||||
if (attReq.length) items.push({ area: 'att', what: 'ATT request', value: 'found', status: 'detected', evidence: attReq });
|
||||
if (trackers.length || attReq.length) items.push({ area: 'appPrivacy', what: 'trackingDomains', value: 'the SDKs\' tracking domains (from each SDK\'s privacy manifest)', status: 'ask', evidence: [] });
|
||||
|
||||
// privacy manifest
|
||||
if (p.ios) {
|
||||
const declared = new Map<string, string[]>();
|
||||
for (const m of p.privacyManifests) for (const [k, v] of Object.entries(m.apis)) declared.set(k, v);
|
||||
const nativeSrc = p.sources.filter(s => /\.(swift|m|mm|h)$/.test(s.path));
|
||||
for (const [cat, def] of Object.entries(REQUIRED_REASON_APIS)) {
|
||||
const h = grep(nativeSrc, def.symbols, 1);
|
||||
if (!h.length) continue;
|
||||
const have = declared.get(cat);
|
||||
items.push({ area: 'privacyManifest', what: cat, value: have?.length ? `declared: ${have.join(', ')}` : `add with a reason: ${def.note}`, status: have?.length ? 'detected' : 'ask', evidence: h });
|
||||
}
|
||||
const m = p.privacyManifests[0];
|
||||
if (tracking !== null || m) items.push({ area: 'privacyManifest', what: 'NSPrivacyTracking', value: tracking ? 'true' : m ? String(m.tracking) : '?', status: tracking ? 'detected' : 'ask', evidence: m ? [{ file: m.path, line: 1, text: 'PrivacyInfo.xcprivacy' }] : [] });
|
||||
if (diff.length) items.push({ area: 'privacyManifest', what: 'NSPrivacyCollectedDataTypes', value: uniq(diff.map(d => d.apple.split(' / ')[1]!)).join(', '), status: 'detected', evidence: diff.flatMap(d => d.evidence).slice(0, 1), note: 'the app\'s own collection; SDKs declare theirs in their manifests' });
|
||||
}
|
||||
|
||||
const dsChanged = diff.some(d => d.change === 'add' || d.change === 'merge') || (anyData && c?.dataSafety?.collectsData === false);
|
||||
const dataSafety = anyData || c?.dataSafety ? { ...(c?.dataSafety ?? {}), collectsData: anyData || !!c?.dataSafety?.collectsData, data: out } : null;
|
||||
const from = c?.appPrivacy?.tracking ?? null;
|
||||
const appPrivacyChange = tracking !== null && from !== tracking ? { from, to: tracking } : null;
|
||||
const appPrivacy = appPrivacyChange ? { ...(c?.appPrivacy ?? {}), tracking: appPrivacyChange.to } : c?.appPrivacy ?? null;
|
||||
return { items, diff, dataSafety, appPrivacy, appPrivacyChange, labelGaps, changed: dsChanged || !!appPrivacyChange };
|
||||
}
|
||||
128
cli/lib/scan/index.ts
Normal file
128
cli/lib/scan/index.ts
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
// `storebound scan` engine: detect the project, run the rejection-risk rules, propose the declarations. Offline and
|
||||
// read-only (the only write is `--write`, done by the command, never here).
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { join, relative } from 'node:path';
|
||||
import { CONFIG_NAMES, loadConfig, type ShipConfig } from '../config';
|
||||
import { reviewDemoAccount } from '../credentials';
|
||||
import { proposeDeclarations, type Proposal } from './declare';
|
||||
import { detectProject, ECO_LABEL, type ProjectFacts, type Stack, where } from './project';
|
||||
import { type ScanFinding, scanRules, type Severity } from './rules';
|
||||
import type { SdkCategory } from './sdks';
|
||||
|
||||
export interface ScanReport {
|
||||
root: string;
|
||||
config: string | null;
|
||||
configError: string | null;
|
||||
stacks: Stack[];
|
||||
platforms: { ios: boolean; android: boolean };
|
||||
sdks: { id: string; name: string; category: SdkCategory; tracking: boolean; deps: { eco: string; name: string; version: string | null; file: string; line: number }[] }[];
|
||||
permissions: { key: string; value: string; file: string; line: number }[];
|
||||
android: { targetSdk: number | null; targetSdkAt: string | null; permissions: string[] };
|
||||
findings: ScanFinding[];
|
||||
counts: Record<Severity, number> & { accepted: number };
|
||||
declarations: Proposal;
|
||||
scanned: number;
|
||||
notes: string[];
|
||||
}
|
||||
|
||||
export interface ScanRun { report: ScanReport; facts: ProjectFacts; config: ShipConfig | null; configPath: string | null }
|
||||
|
||||
/** Find the project's config: --config, else storebound.config.* in `dir` (no upward search: a fixture or a
|
||||
* sub-project must not pick up a parent's config). */
|
||||
async function findConfig(dir: string, explicit?: string): Promise<{ config: ShipConfig | null; path: string | null; error: string | null }> {
|
||||
const path = explicit ? join(dir, explicit) : CONFIG_NAMES.map(n => join(dir, n)).find(existsSync);
|
||||
if (!path) return { config: null, path: null, error: null };
|
||||
try { return { config: (await loadConfig(path)).config, path, error: null }; } catch (e) { return { config: null, path, error: (e as Error).message.split('\n').slice(0, 4).join('; ') }; }
|
||||
}
|
||||
|
||||
export async function runScan(dir: string, o: { config?: string } = {}): Promise<ScanRun> {
|
||||
const facts = detectProject(dir);
|
||||
const { config, path: configPath, error } = await findConfig(dir, o.config);
|
||||
const rel = (p: string) => relative(dir, p) || p;
|
||||
const readRel = (p: string | undefined): { path: string; text: string } | undefined => {
|
||||
if (!p) return undefined;
|
||||
const abs = join(dir, p);
|
||||
try { return existsSync(abs) ? { path: rel(abs), text: readFileSync(abs, 'utf8') } : undefined; } catch { return undefined; }
|
||||
};
|
||||
const listings = {
|
||||
apple: (config ? config.apple : true) ? readRel(config?.apple?.listing ?? 'store/appstore.md') : undefined,
|
||||
play: (config ? config.play : true) ? readRel(config?.play?.listing ?? 'store/listing.md') : undefined,
|
||||
captions: readRel(config?.shots?.copy ?? 'store/shots/copy.json'),
|
||||
};
|
||||
const configFile = configPath ? { path: rel(configPath), text: readFileSync(configPath, 'utf8') } : null;
|
||||
const declarations = proposeDeclarations(facts, config, configFile);
|
||||
const dataMerges = config?.dataSafety ? declarations.diff.filter(d => d.change === 'merge' && d.before).map(d => {
|
||||
const b = d.before!;
|
||||
const missing = [...d.after.collect.filter(x => !b.collect.includes(x)).map(x => `collected for ${x}`), ...(d.after.shared && !b.shared ? ['shared'] : []),
|
||||
...(d.after.share ?? []).filter(x => !(b.share ?? []).includes(x)).map(x => `shared for ${x}`)];
|
||||
return { type: d.type, missing: [...new Set(missing)].join(', '), evidence: d.evidence };
|
||||
}).filter(d => d.missing) : [];
|
||||
const findings = scanRules({ facts, config, configFile, listings, demoAccount: !!reviewDemoAccount(dir), labelGaps: declarations.labelGaps, dataMerges });
|
||||
const counts = { blocker: 0, high: 0, medium: 0, low: 0, accepted: 0 };
|
||||
for (const f of findings) { if (f.accepted) counts.accepted++; else counts[f.severity]++; }
|
||||
const notes: string[] = [];
|
||||
if (facts.android && facts.androidInfo.mergedManifest) notes.push(`Android: permissions include the merged manifest of the last local build (${facts.androidInfo.mergedManifest}); rebuild after dependency changes.`);
|
||||
else if (facts.android && facts.androidInfo.manifests.length) notes.push('Android: libraries add permissions when the manifest is merged and no local build output (build/intermediates) was found; check the merged manifest (Android Studio > Merged Manifest, or the AAB) too.');
|
||||
if (facts.ios && !facts.plistSources.length) notes.push('iOS: no Info.plist settings found (generated at build time?): purpose string, ATS and export compliance checks were skipped.');
|
||||
if (!facts.sources.length) notes.push('No app source files found: code checks (sign-in, deletion, restore, ATT prompt) could not run.');
|
||||
const report: ScanReport = {
|
||||
root: dir, config: configPath ? rel(configPath) : null, configError: error,
|
||||
stacks: facts.stacks, platforms: { ios: facts.ios, android: facts.android },
|
||||
sdks: facts.sdks.map(s => ({ id: s.sdk.id, name: s.sdk.name, category: s.sdk.category, tracking: s.sdk.tracking, deps: s.deps.map(d => ({ eco: d.eco, name: d.name, version: d.version, file: d.file, line: d.line })) })),
|
||||
permissions: [...facts.plist.values()].filter(e => /UsageDescription$/.test(e.key)).map(e => ({ key: e.key, value: String(e.value ?? ''), file: e.at.file, line: e.at.line })),
|
||||
android: { targetSdk: facts.androidInfo.targetSdk?.value ?? null, targetSdkAt: facts.androidInfo.targetSdk ? where(facts.androidInfo.targetSdk.at) : null, permissions: [...new Set(facts.androidInfo.permissions.map(x => x.name.replace(/^android\.permission\./, '')))] },
|
||||
findings, counts, declarations, scanned: facts.scanned, notes,
|
||||
};
|
||||
return { report, facts, config, configPath };
|
||||
}
|
||||
|
||||
const TAG: Record<Severity, string> = { blocker: 'BLOCKER', high: 'HIGH ', medium: 'MEDIUM ', low: 'low ' };
|
||||
const STACK: Record<Stack, string> = { 'ios-native': 'iOS (native)', 'android-native': 'Android (native)', 'react-native': 'React Native', expo: 'Expo', capacitor: 'Capacitor', cordova: 'Cordova', flutter: 'Flutter', unity: 'Unity', godot: 'Godot', web: 'web' };
|
||||
|
||||
/** The report as plain text (the terminal output of `storebound scan`). */
|
||||
export function formatScan(r: ScanReport, o: { declarations?: boolean } = {}): string {
|
||||
const L: string[] = [];
|
||||
L.push(`storebound scan · ${r.config ? r.config : 'no storebound.config.ts (project files only)'}`);
|
||||
if (r.configError) L.push(`config not loaded: ${r.configError}`);
|
||||
L.push(`stack: ${r.stacks.map(s => STACK[s]).join(', ') || 'unknown'} · targets: ${[r.platforms.ios && 'iOS', r.platforms.android && 'Android'].filter(Boolean).join(', ') || 'none found'} · ${r.scanned} files`);
|
||||
if (r.sdks.length) {
|
||||
L.push('', 'SDKs');
|
||||
for (const s of r.sdks) {
|
||||
const d = s.deps[0]!;
|
||||
L.push(` ${s.name.padEnd(30)} ${s.category}${s.tracking ? ', tracking-capable' : ''} · ${ECO_LABEL[d.eco as keyof typeof ECO_LABEL] ?? d.eco} ${d.name}${d.version ? ` ${d.version}` : ''} (${d.file}:${d.line})${s.deps.length > 1 ? ` +${s.deps.length - 1}` : ''}`);
|
||||
}
|
||||
}
|
||||
if (r.android.targetSdk !== null) L.push(`Android targetSdk ${r.android.targetSdk} (${r.android.targetSdkAt})`);
|
||||
const open = r.findings.filter(f => !f.accepted);
|
||||
L.push('', `Rejection risks: ${r.counts.blocker} blocker, ${r.counts.high} high, ${r.counts.medium} medium, ${r.counts.low} low${r.counts.accepted ? ` (+${r.counts.accepted} accepted by the owner)` : ''}`);
|
||||
if (!open.length) L.push(' none found in the project files and config');
|
||||
r.findings.forEach((f, i) => {
|
||||
L.push(`${String(i + 1).padStart(3)}. ${f.accepted ? 'accepted' : TAG[f.severity]} ${f.guideline} · ${f.store === 'apple' ? 'App Store' : 'Google Play'} · ${f.title}`);
|
||||
for (const e of f.evidence.slice(0, 3)) L.push(` at ${e.file}:${e.line}${e.text ? ` ${e.text}` : ''}`);
|
||||
if (f.accepted) L.push(` owner: ${f.accepted}`);
|
||||
else L.push(` fix: ${f.fix}`, ` skill: ${f.skill} · ${f.ref}`);
|
||||
});
|
||||
if (o.declarations !== false) {
|
||||
const d = r.declarations;
|
||||
L.push('', 'Declarations proposal (detected = proven by a file; ask owner = only the owner knows)');
|
||||
const areas: [string, string][] = [['dataSafety', 'Data safety'], ['appPrivacy', 'App Privacy'], ['att', 'App Tracking Transparency'], ['privacyManifest', 'Privacy manifest']];
|
||||
for (const [a, label] of areas) {
|
||||
const items = d.items.filter(x => x.area === a);
|
||||
if (!items.length) continue;
|
||||
L.push(` ${label}`);
|
||||
for (const x of items) L.push(` ${x.status === 'detected' ? 'detected ' : 'ask owner'} ${x.what}: ${x.value}${x.evidence[0] ? ` (${x.evidence[0].file}:${x.evidence[0].line})` : ''}${x.note ? ` · ${x.note}` : ''}`);
|
||||
}
|
||||
const changes = d.diff.filter(x => x.change === 'add' || x.change === 'merge');
|
||||
if (changes.length || d.appPrivacyChange) {
|
||||
L.push('', ` Diff against ${r.config ?? 'the config'} (written only with --write):`);
|
||||
for (const x of changes) {
|
||||
if (x.change === 'add') L.push(` + dataSafety.data.${x.type}: { shared: ${x.after.shared}, collect: [${x.after.collect.join(', ')}]${x.after.share?.length ? `, share: [${x.after.share.join(', ')}]` : ''} }`);
|
||||
else L.push(` ~ dataSafety.data.${x.type}: collect [${x.before!.collect.join(', ')}] -> [${x.after.collect.join(', ')}]${x.after.shared !== x.before!.shared ? `, shared ${x.before!.shared} -> ${x.after.shared}` : ''}${(x.after.share ?? []).join() !== (x.before!.share ?? []).join() ? `, share [${(x.before!.share ?? []).join(', ')}] -> [${(x.after.share ?? []).join(', ')}]` : ''}`);
|
||||
}
|
||||
if (d.appPrivacyChange) L.push(` ~ appPrivacy.tracking: ${d.appPrivacyChange.from ?? 'unset'} -> ${d.appPrivacyChange.to}`);
|
||||
} else if (r.config) L.push('', ` No changes to ${r.config}: the dataSafety / appPrivacy blocks already cover what was detected.`);
|
||||
}
|
||||
if (r.notes.length) L.push('', ...r.notes.map(n => `note: ${n}`));
|
||||
L.push('', 'Checked at review, not by scan: crashes and bugs on the reviewer\'s device, broken links (storebound validate checks the URLs), screenshots that do not match the app, minimum functionality and spam judgement (4.2, 4.3), local law (5.2). See the review-rejections skill.');
|
||||
return L.join('\n');
|
||||
}
|
||||
55
cli/lib/scan/permissions.ts
Normal file
55
cli/lib/scan/permissions.ts
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
// iOS privacy-sensitive APIs and the Info.plist purpose string each one needs (Apple: "Requesting access to protected
|
||||
// resources"; a missing string makes the app crash on the first request and App Store Connect rejects the upload
|
||||
// with ITMS-90683). `code` finds the API in app sources, `packages` the npm / pub / Unity packages that call it.
|
||||
// Checked 2026-10-11 against developer.apple.com/documentation/bundleresources/information-property-list.
|
||||
export interface PermissionDef {
|
||||
/** Info.plist keys; any one of them satisfies the check (e.g. calendars before / since iOS 17). */
|
||||
keys: string[];
|
||||
what: string;
|
||||
code: RegExp;
|
||||
packages: string[];
|
||||
}
|
||||
|
||||
export const IOS_PERMISSIONS: PermissionDef[] = [
|
||||
{ keys: ['NSCameraUsageDescription'], what: 'camera',
|
||||
code: /\bAVCaptureDevice\b|sourceType\s*=\s*\.camera|UIImagePickerController\.SourceType\.camera|\bWebCamTexture\b|\bVNDocumentCameraViewController\b/,
|
||||
packages: ['expo-camera', 'react-native-vision-camera', 'react-native-camera', '@capacitor/camera', 'image_picker', 'camera', 'mobile_scanner', 'expo-image-picker', 'react-native-image-picker', 'cordova-plugin-camera', '@capacitor-mlkit/barcode-scanning'] },
|
||||
{ keys: ['NSMicrophoneUsageDescription'], what: 'microphone',
|
||||
code: /\bAVAudioRecorder\b|requestRecordPermission|\.record\b.*AVAudioSession|AVAudioApplication\.requestRecordPermission|\bMicrophone\.Start\b|\bAudioEffectRecord\b/,
|
||||
packages: ['expo-av', 'react-native-audio-recorder-player', 'record', 'flutter_sound', 'cordova-plugin-media-capture', '@capacitor-community/voice-recorder'] },
|
||||
{ keys: ['NSPhotoLibraryUsageDescription'], what: 'photo library',
|
||||
code: /\bPHPhotoLibrary\.(requestAuthorization|shared)|\bPHAsset\.fetch|\bALAssetsLibrary\b/,
|
||||
packages: ['expo-media-library', 'photo_manager', '@react-native-camera-roll/camera-roll', 'image_picker', '@capacitor/camera'] },
|
||||
{ keys: ['NSPhotoLibraryAddUsageDescription', 'NSPhotoLibraryUsageDescription'], what: 'saving to the photo library',
|
||||
code: /UIImageWriteToSavedPhotosAlbum|UISaveVideoAtPathToSavedPhotosAlbum|PHAssetChangeRequest|PHAssetCreationRequest/,
|
||||
packages: ['gallery_saver', 'image_gallery_saver'] },
|
||||
{ keys: ['NSLocationWhenInUseUsageDescription', 'NSLocationAlwaysAndWhenInUseUsageDescription'], what: 'location',
|
||||
code: /\bCLLocationManager\b|requestWhenInUseAuthorization|requestAlwaysAuthorization|\bInput\.location\.Start\b|\bCLLocationUpdate\b/,
|
||||
packages: ['expo-location', '@capacitor/geolocation', 'geolocator', 'location', '@react-native-community/geolocation', 'react-native-geolocation-service', 'cordova-plugin-geolocation'] },
|
||||
{ keys: ['NSContactsUsageDescription'], what: 'contacts',
|
||||
code: /\bCNContactStore\b|\bABAddressBook/,
|
||||
packages: ['expo-contacts', 'react-native-contacts', 'flutter_contacts', 'contacts_service', '@capacitor-community/contacts', 'cordova-plugin-contacts'] },
|
||||
{ keys: ['NSCalendarsFullAccessUsageDescription', 'NSCalendarsWriteOnlyAccessUsageDescription', 'NSCalendarsUsageDescription'], what: 'calendars',
|
||||
code: /\bEKEventStore\b/, packages: ['expo-calendar', 'device_calendar', 'react-native-calendar-events'] },
|
||||
{ keys: ['NSRemindersFullAccessUsageDescription', 'NSRemindersUsageDescription'], what: 'reminders', code: /requestFullAccessToReminders|entityType:\s*\.reminder|EKEntityType\.reminder/, packages: [] },
|
||||
{ keys: ['NSBluetoothAlwaysUsageDescription'], what: 'Bluetooth',
|
||||
code: /\bCBCentralManager\b|\bCBPeripheralManager\b/, packages: ['react-native-ble-plx', 'flutter_blue_plus', 'flutter_blue', '@capacitor-community/bluetooth-le', 'cordova-plugin-ble-central'] },
|
||||
{ keys: ['NSFaceIDUsageDescription'], what: 'Face ID',
|
||||
code: /deviceOwnerAuthenticationWithBiometrics|evaluatePolicy\(/, packages: ['expo-local-authentication', 'local_auth', 'react-native-biometrics', '@capgo/capacitor-native-biometric'] },
|
||||
{ keys: ['NSMotionUsageDescription'], what: 'motion and fitness', code: /\bCMMotionActivityManager\b|\bCMPedometer\b|\bCMAltimeter\b/, packages: ['expo-sensors'] },
|
||||
{ keys: ['NSSpeechRecognitionUsageDescription'], what: 'speech recognition', code: /\bSFSpeechRecognizer\b/, packages: ['@react-native-voice/voice', 'speech_to_text', 'expo-speech-recognition'] },
|
||||
{ keys: ['NSHealthShareUsageDescription'], what: 'Health data', code: /\bHKHealthStore\b/, packages: ['react-native-health', 'health', '@kingstinct/react-native-healthkit'] },
|
||||
{ keys: ['NSUserTrackingUsageDescription'], what: 'App Tracking Transparency',
|
||||
code: /requestTrackingAuthorization|ATTrackingStatusBinding\.RequestAuthorizationTracking/,
|
||||
packages: ['expo-tracking-transparency', 'react-native-tracking-transparency', 'app_tracking_transparency', '@capacitor-community/app-tracking-transparency', 'com.unity.ads.ios-support'] },
|
||||
];
|
||||
|
||||
/** A purpose string that says nothing (empty, a placeholder, or a generic template Apple rejects under 5.1.1(ii)). */
|
||||
export function vaguePurpose(s: string): 'empty' | 'vague' | null {
|
||||
const t = s.trim();
|
||||
if (!t) return 'empty';
|
||||
if (/^(todo|tbd|fixme|placeholder|lorem|test|xxx+|\.+|-+|description|usage description|\$\([A-Z_]+\))$/i.test(t)) return 'empty';
|
||||
// Expo / plugin defaults like "Allow $(PRODUCT_NAME) to access your camera" name no reason
|
||||
if (t.length < 20 || /^(allow|let) \$\(PRODUCT_NAME\) to access your [a-z ]+\.?$/i.test(t) || /^(this app|we) (needs?|requires?|uses?) (access to )?(your )?[a-z ]+\.?$/i.test(t)) return 'vague';
|
||||
return null;
|
||||
}
|
||||
429
cli/lib/scan/play-rules.ts
Normal file
429
cli/lib/scan/play-rules.ts
Normal file
|
|
@ -0,0 +1,429 @@
|
|||
// Google Play policy rules for `storebound scan` (rejections, update blocks, suspensions and policy strikes), next to
|
||||
// the App Store rules in rules.ts. Pure, like rules.ts: project facts + config + listings in, findings out. A rule only
|
||||
// reports what a file or the config proves; where the policy turns on something no file shows (the app's core purpose,
|
||||
// what happens at runtime) the finding says what to check and which Play Console declaration it needs.
|
||||
//
|
||||
// Sources, each fetched live and checked 2026-10-11 (Play Console Help / Policy Center, developer.android.com):
|
||||
// - Permissions and APIs that Access Sensitive Information: support.google.com/googleplay/android-developer/answer/9888170
|
||||
// (index of the restricted permissions below).
|
||||
// - Background location: answer/9799150 "Understanding location in the background permissions": core feature only,
|
||||
// App content > Sensitive app permissions > Location permissions declaration with a video (30 s or less), a
|
||||
// prominent disclosure before the runtime prompt that says "location" and "background" / "when the app is closed".
|
||||
// - Photo and video permissions: answer/14115180: READ_MEDIA_IMAGES / READ_MEDIA_VIDEO only when the system photo
|
||||
// picker is not enough for the app's core purpose (gallery-type apps), with a declaration; enforced since 2025-05-28.
|
||||
// - All files access: answer/10467955: MANAGE_EXTERNAL_STORAGE only for file managers, backup and restore,
|
||||
// anti-virus, document management, on-device search, disk encryption, device migration; declaration form.
|
||||
// - AccessibilityService API: answer/10964491: isAccessibilityTool only for tools for people with disabilities; every
|
||||
// other use needs an in-app disclosure, affirmative consent and the declaration (with a video).
|
||||
// - REQUEST_INSTALL_PACKAGES: answer/12085295: core function must be sending / receiving packages and user-initiated
|
||||
// installs; Permissions Declaration Form.
|
||||
// - Health Connect: answer/12991134 (android.permission.health.*: each permission justified, permitted use cases,
|
||||
// privacy policy) and the Health apps declaration every app completes: answer/14738291.
|
||||
// - Full-screen intent: answer/13392821: on Android 14+ granted by default only to calling and alarm apps; App
|
||||
// content declaration since 2024-05-31; other apps ask the user and handle a denial.
|
||||
// - VpnService: answer/12564964: VPN as the core function (or the listed exceptions), disclosure + consent, declaration.
|
||||
// - Device admin (BIND_DEVICE_ADMIN): no Play policy page covers it (checked the pages above, Device and Network Abuse
|
||||
// answer/9888379 and User Data answer/10144311): no rule, nothing invented.
|
||||
// - User Data: answer/10144311: prominent disclosure in the app, during normal use, right before the runtime request,
|
||||
// describing the data and its use (not only in the privacy policy); a privacy policy for every app, in Play Console
|
||||
// and inside the app; Data safety must include what SDKs collect.
|
||||
// - Families: answer/9893335 (only Families Self-Certified Ads SDKs for children; child-only apps do not transmit the
|
||||
// advertising ID and should not request AD_ID on API 33+; child-only apps may not request location) and the
|
||||
// certified list answer/9859768 (in sdks.ts `families`; AppLovin left the program, Meta Audience Network is not on it).
|
||||
// - Advertising ID: answer/6048248: apps targeting Android 13+ that use the advertising ID declare
|
||||
// com.google.android.gms.permission.AD_ID (Google Mobile Ads merges it from its own manifest).
|
||||
// - 16 KB page sizes: developer.android.com/guide/practices/page-sizes: apps targeting Android 15+ must support 16 KB
|
||||
// pages on 64-bit devices; from 2027-02-01 updates that don't cannot be released. AGP 8.5.1+ zip-aligns uncompressed
|
||||
// .so files (older: useLegacyPackaging), NDK r28+ aligns by default (r27 and older: flags). Unity: 6000.0.38f1,
|
||||
// 2022.3.56f1, 2021.3.48f1, 6000.1+ (discussions.unity.com/t/info-unity-engine-support-for-16-kb-memory-page-sizes-android-15/1589588).
|
||||
// React Native: 0.77 (reactnative.dev/blog/2025/01/21/version-0.77). Flutter: no official version found, not checked.
|
||||
// - Testing for new personal developer accounts: answer/14151465: accounts created after 2023-11-13 run a closed test
|
||||
// with at least 12 opted-in testers for 14 days in a row before applying for production.
|
||||
// - Metadata: answer/9898842: title 30 characters or less; no emoji, emoticons or repeated special characters; no
|
||||
// rank / performance / price / promotion / Play program terms ("#1", "best", "top", "popular", "free", "new", "sale",
|
||||
// "% off") in the title, icon or developer name; avoid ALL CAPS unless it is the brand; no repeated or unrelated
|
||||
// keywords, no comparisons with other apps, no other brands without permission.
|
||||
// - Ads: answer/9857753 (no interstitials that show unexpectedly, before the splash screen or while the user does
|
||||
// something else) and Better Ads Experiences answer/12271244 (apps without a splash screen wait for the home screen).
|
||||
// Statically visible: an interstitial shown from the launcher activity's onCreate (Android native). Unity Start(),
|
||||
// Flutter and React Native launch paths are not reliable from files: review-only.
|
||||
// - Payments: answer/9858738 (Play Billing for digital goods; physical goods and services exempt; no steering outside
|
||||
// user choice billing answer/13821247, external offers answer/14372887, US external content links answer/16470497).
|
||||
// - Impersonation: answer/9888374 (don't imply a relation with someone you are not, e.g. in the title or developer
|
||||
// name). The brand list below is storebound's own short list of well-known app brands, reported as low "check".
|
||||
// Play Integrity / anti-tamper is not a policy: no rule.
|
||||
import { PLAY_AGE_GROUPS } from '../config';
|
||||
import { allSubscriptions } from '../subscriptions';
|
||||
import { grep, type Hit, type ProjectFacts } from './project';
|
||||
import type { ScanFinding, ScanInput } from './rules';
|
||||
import { versionAtLeast } from './sdks';
|
||||
|
||||
const PLAY = 'https://support.google.com/googleplay/android-developer/answer/';
|
||||
export const PLAY_REFS = {
|
||||
sensitive: `${PLAY}9888170`, backgroundLocation: `${PLAY}9799150`, photoVideo: `${PLAY}14115180`, allFiles: `${PLAY}10467955`,
|
||||
accessibility: `${PLAY}10964491`, installPackages: `${PLAY}12085295`, healthConnect: `${PLAY}12991134`, healthDeclaration: `${PLAY}14738291`,
|
||||
fullScreenIntent: `${PLAY}13392821`, vpn: `${PLAY}12564964`, userData: `${PLAY}10144311`, families: `${PLAY}9893335`, familiesSdks: `${PLAY}9859768`,
|
||||
adId: `${PLAY}6048248`, pageSize: 'https://developer.android.com/guide/practices/page-sizes', testing: `${PLAY}14151465`, metadata: `${PLAY}9898842`,
|
||||
ads: `${PLAY}9857753`, betterAds: `${PLAY}12271244`, payments: `${PLAY}9858738`, impersonation: `${PLAY}9888374`,
|
||||
} as const;
|
||||
/** From this date Play refuses updates that don't support 16 KB pages (developer.android.com/guide/practices/page-sizes). */
|
||||
export const PAGE_SIZE_DEADLINE = '2027-02-01';
|
||||
/** Personal accounts created after this date have the closed-testing requirement (answer/14151465). */
|
||||
export const PERSONAL_TESTING_SINCE = '2023-11-13';
|
||||
export const PERSONAL_TESTING = { testers: 12, days: 14 } as const;
|
||||
/** First Unity version of each stream with 16 KB page size support (Unity forum post above); older streams have none. */
|
||||
export const UNITY_16KB: Record<string, string> = { '2021.3': '2021.3.48f1', '2022.3': '2022.3.56f1', '6000.0': '6000.0.38f1' };
|
||||
const AD_ID = 'com.google.android.gms.permission.AD_ID';
|
||||
const BRANDS = ['instagram', 'tiktok', 'whatsapp', 'facebook', 'snapchat', 'youtube', 'netflix', 'spotify', 'telegram', 'pinterest', 'chatgpt', 'openai',
|
||||
'minecraft', 'roblox', 'fortnite', 'pubg', 'pokemon', 'duolingo', 'gmail', 'google', 'playstation', 'xbox', 'nintendo'];
|
||||
const OTHER_APPS = ['instagram', 'tiktok', 'whatsapp', 'facebook', 'snapchat', 'youtube', 'netflix', 'spotify', 'telegram', 'messenger', 'pinterest', 'uber', 'airbnb',
|
||||
'chatgpt', 'openai', 'minecraft', 'roblox', 'fortnite', 'pubg', 'candy crush', 'clash of clans', 'pokemon', 'pokémon', 'among us', 'subway surfers', 'temple run',
|
||||
'angry birds', 'tetris', 'wordle', 'duolingo', 'gmail', 'google maps', 'waze', 'shazam', 'tinder', 'evernote', 'photoshop', 'capcut'];
|
||||
const CLAIMS = /#\s?1\b|\bno\.? ?1\b|\bnumber one\b|\bbest\b|\btop\b|\bpopular\b|app of the year|game of the year|best of play|editor'?s'? choice|\bsale\b|\bdiscount\b|\d+\s?% off|cash ?back|limited time|\$\d/i;
|
||||
/** "free" and "new" are only examples in the policy as promotion ("free for limited time only") and Play program
|
||||
* ("New") terms; a plain "free" or "new" can be part of a real name, so they are a low "check". */
|
||||
const SOFT_CLAIMS = /\bfree\b|\bnew\b/i;
|
||||
const EMOJI = /\p{Extended_Pictographic}|[:;]-?[)(DP]|\(\s*[╯°□・ω^]+|([!?*★☆♥✓✔•~_=+|-])\1{1,}/u;
|
||||
const DISCLOSURE = /shouldShowRequestPermissionRationale|PermissionRationale|prominent[_ ]?disclosure|data[_ ]?disclosure|\b(collects?|transmits?|syncs?|stores?|shares?|uses?)\b[^"<\n]{0,80}\b(location|contacts?|calendar|phone numbers?)\b|\b(location|contacts?|calendar)\b[^"<\n]{0,80}\b(collected|transmitted|synced|stored|shared|used)\b/i;
|
||||
const BACKGROUND_DISCLOSURE = /location[^"<\n]{0,160}(background|when the app is closed|not in use|always in use)|(background|when the app is closed|not in use|always in use)[^"<\n]{0,160}location/i;
|
||||
const EXTERNAL_BUY = /\b(buy|subscribe|purchase|upgrade|pay)\b[^.\n]{0,40}\b(on|at|via|from) (our )?(website|web ?site|web|site)\b/i;
|
||||
const SENSITIVE_DATA: Record<string, string> = {
|
||||
ACCESS_FINE_LOCATION: 'location', ACCESS_COARSE_LOCATION: 'location', ACCESS_BACKGROUND_LOCATION: 'location', READ_CONTACTS: 'contacts',
|
||||
READ_CALENDAR: 'calendar', READ_PHONE_NUMBERS: 'phone numbers',
|
||||
};
|
||||
|
||||
type Add = (f: Omit<ScanFinding, 'ref' | 'store'> & { ref: string }) => void;
|
||||
export interface PlayCtx {
|
||||
add: Add;
|
||||
cfg: (needle: string | RegExp, text?: string) => Hit[];
|
||||
sdkHits: (pred: (s: ProjectFacts['sdks'][number]) => boolean) => Hit[];
|
||||
listingHits: (file: { path: string; text: string } | undefined, re: RegExp, o?: { fenced?: boolean; field?: RegExp }) => Hit[];
|
||||
/** Account creation evidence (rules.ts), restorable products / subscriptions, payment SDKs. */
|
||||
creates: Hit[];
|
||||
restorable: Hit[];
|
||||
paySdk: Hit[];
|
||||
}
|
||||
|
||||
const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const permName = (n: string) => n.replace(/^android\.permission\./, '');
|
||||
const ev = (x: { at: { file: string; line: number } }, text: string): Hit => ({ ...x.at, text });
|
||||
|
||||
/** Text of the first fenced block under every heading matching `field`. */
|
||||
function fieldBlocks(file: { path: string; text: string } | undefined, field: RegExp): { at: Hit; text: string }[] {
|
||||
if (!file) return [];
|
||||
const out: { at: Hit; text: string }[] = [];
|
||||
const lines = file.text.split('\n');
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (!/^###\s/.test(lines[i]!) || !field.test(lines[i]!.slice(4))) continue;
|
||||
let j = i + 1;
|
||||
while (j < lines.length && !/^```/.test(lines[j]!) && !/^##/.test(lines[j]!)) j++;
|
||||
if (j >= lines.length || !/^```/.test(lines[j]!)) continue;
|
||||
let k = j + 1;
|
||||
while (k < lines.length && !/^```/.test(lines[k]!)) k++;
|
||||
out.push({ at: { file: file.path, line: j + 2, text: (lines[j + 1] ?? '').trim().slice(0, 160) }, text: lines.slice(j + 1, k).join('\n') });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const STOP = new Set(['app', 'apps', 'game', 'games', 'the', 'and', 'for', 'with', 'your', 'you', 'that', 'this', 'from', 'have', 'are', 'will', 'can', 'all', 'more', 'just', 'into', 'every', 'each', 'one', 'when', 'what', 'they', 'them', 'their', 'our', 'out', 'not', 'any', 'also']);
|
||||
|
||||
export function playRules(inp: ScanInput, x: PlayCtx): void {
|
||||
const { facts: p, config: c } = inp;
|
||||
const { add, cfg, sdkHits } = x;
|
||||
const a = p.androidInfo;
|
||||
const android = p.android;
|
||||
const perms = new Map(a.permissions.map(q => [permName(q.name), q] as const));
|
||||
const removed = new Map(a.removedPermissions.map(q => [permName(q.name), q] as const));
|
||||
const target = a.targetSdk?.value ?? null;
|
||||
const ages = c?.play?.targetAges ?? [];
|
||||
const kidsAges = ages.filter(g => PLAY_AGE_GROUPS.indexOf(g) < 3);
|
||||
const childOnly = ages.length > 0 && kidsAges.length === ages.length;
|
||||
const mixed = kidsAges.length > 0 && !childOnly;
|
||||
const textSources = [...p.sources, ...a.strings];
|
||||
|
||||
// ---- sensitive permissions and APIs (each needs a Play Console declaration) ----
|
||||
if (android) {
|
||||
const bg = perms.get('ACCESS_BACKGROUND_LOCATION');
|
||||
if (bg)
|
||||
add({ rule: 'play-background-location', guideline: 'Play: Location permissions', severity: 'high', title: 'ACCESS_BACKGROUND_LOCATION needs a core feature that uses location in the background, the Location permissions declaration and a video',
|
||||
evidence: [ev(bg, bg.name)], ref: PLAY_REFS.backgroundLocation, skill: 'store-declarations',
|
||||
fix: 'Keep it only for one core, user-visible feature (never for ads or analytics alone); fill App content > Sensitive app permissions > Location permissions (one feature, a video of 30 s or less showing the prominent disclosure, the runtime prompt and the feature working in the background), and name the feature in the store description. Otherwise remove it (tools:node="remove" if a library adds it).' });
|
||||
const media = ['READ_MEDIA_IMAGES', 'READ_MEDIA_VIDEO'].map(n => perms.get(n)).filter(q => !!q);
|
||||
if (media.length)
|
||||
add({ rule: 'play-photo-video', guideline: 'Play: Photo and Video Permissions', severity: 'high', title: `${media.map(q => permName(q.name)).join(' / ')}: only for apps whose core purpose needs broad photo / video access; others use the photo picker`,
|
||||
evidence: media.map(q => ev(q, q.name)), ref: PLAY_REFS.photoVideo, skill: 'store-declarations',
|
||||
fix: 'Use the Android photo picker (androidx.activity 1.7.0+ PickVisualMedia, no permission) for one-time or occasional picks and remove the permissions; keep them only for gallery-type core features and fill the Photo and video permissions declaration.' });
|
||||
const mes = perms.get('MANAGE_EXTERNAL_STORAGE');
|
||||
if (mes)
|
||||
add({ rule: 'play-all-files-access', guideline: 'Play: All files access', severity: 'high', title: 'MANAGE_EXTERNAL_STORAGE (All files access) is only for file managers, backup, anti-virus, document management, search and similar apps',
|
||||
evidence: [ev(mes, mes.name)], ref: PLAY_REFS.allFiles, skill: 'store-declarations',
|
||||
fix: 'Use the Storage Access Framework or MediaStore and remove the permission; apps whose core function needs it fill the All files access declaration and explain why those APIs are not enough.' });
|
||||
const acc = a.components.filter(q => q.kind === 'service' && (q.permission === 'android.permission.BIND_ACCESSIBILITY_SERVICE' || q.actions.includes('android.accessibilityservice.AccessibilityService')));
|
||||
if (acc.length) {
|
||||
const tool = a.accessibilityConfigs.find(q => q.isTool);
|
||||
add({ rule: 'play-accessibility', guideline: 'Play: AccessibilityService API', severity: tool ? 'medium' : 'high',
|
||||
title: tool ? 'AccessibilityService marked isAccessibilityTool: only for tools whose primary purpose is helping people with disabilities' : `AccessibilityService ${acc[0]!.name} needs an in-app disclosure, affirmative consent and the AccessibilityService declaration`,
|
||||
evidence: [...acc.slice(0, 2).map(q => ev(q, `service ${q.name}`)), ...(tool ? [ev(tool, 'android:isAccessibilityTool="true"')] : a.accessibilityConfigs.slice(0, 1).map(q => ev(q, 'accessibility-service')))], ref: PLAY_REFS.accessibility, skill: 'store-declarations',
|
||||
fix: tool ? 'Keep isAccessibilityTool only for screen readers, switch, voice or braille input and similar tools (not automation, antivirus, launchers, cleaners, password managers); otherwise remove it and add the disclosure and consent. Fill the AccessibilityService declaration either way.'
|
||||
: 'Show a disclosure during normal use that says what the service accesses and why, get an affirmative "accept", keep it separate from other disclosures, and fill the AccessibilityService declaration with a video (open the app, disclosure, accept and decline, the feature). Autonomous AI-style actions through the API are not allowed.' });
|
||||
}
|
||||
const rip = perms.get('REQUEST_INSTALL_PACKAGES');
|
||||
if (rip)
|
||||
add({ rule: 'play-install-packages', guideline: 'Play: REQUEST_INSTALL_PACKAGES', severity: 'high', title: 'REQUEST_INSTALL_PACKAGES is only for apps whose core function is sending or receiving app packages for user-initiated installs',
|
||||
evidence: [ev(rip, rip.name)], ref: PLAY_REFS.installPackages, skill: 'store-declarations',
|
||||
fix: 'Remove it (self-updates must go through Play); browsers, file managers, messengers with attachments, backup and enterprise apps keep it and fill the Permissions Declaration Form.' });
|
||||
const health = a.permissions.filter(q => /^android\.permission\.health\./.test(q.name));
|
||||
if (health.length)
|
||||
add({ rule: 'play-health-connect', guideline: 'Play: Health Connect permissions', severity: 'high', title: `Health Connect permissions (${health.slice(0, 3).map(q => permName(q.name).replace(/^health\./, '')).join(', ')}${health.length > 3 ? ', ...' : ''}) need a justification for each one and a permitted use case`,
|
||||
evidence: health.slice(0, 3).map(q => ev(q, q.name)), ref: PLAY_REFS.healthConnect, skill: 'store-declarations',
|
||||
fix: 'Request only the data types a feature uses, justify each permission in the Health Connect declaration, show the privacy policy in the app, and answer App content > Health apps (answer/14738291). Ads, data sales and child-only apps are not allowed to use it.' });
|
||||
const fsi = perms.get('USE_FULL_SCREEN_INTENT');
|
||||
if (fsi && (target === null || target >= 34))
|
||||
add({ rule: 'play-full-screen-intent', guideline: 'Play: Full-screen intent', severity: 'high', title: 'USE_FULL_SCREEN_INTENT: on Android 14+ only calling and alarm apps get it by default, and every app declares it in Play Console',
|
||||
evidence: [ev(fsi, fsi.name)], ref: PLAY_REFS.fullScreenIntent, skill: 'store-declarations',
|
||||
fix: 'Remove it unless the core function is alarms or phone / video calls (an SDK may add it: check the merged manifest); otherwise fill App content > Full-screen intent, ask the user with ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT and handle a denial. Never for ads.' });
|
||||
const vpn = a.components.filter(q => q.kind === 'service' && (q.permission === 'android.permission.BIND_VPN_SERVICE' || q.actions.includes('android.net.VpnService')));
|
||||
if (vpn.length)
|
||||
add({ rule: 'play-vpn', guideline: 'Play: VpnService', severity: 'high', title: `VpnService ${vpn[0]!.name}: only for VPN apps and the listed exceptions, with a disclosure, consent and the VpnService declaration`,
|
||||
evidence: vpn.slice(0, 2).map(q => ev(q, `service ${q.name}`)), ref: PLAY_REFS.vpn, skill: 'store-declarations',
|
||||
fix: 'Use VpnService only when it is the core function (or parental control, enterprise, app usage tracking, device security, network tools, browsers); describe it in the listing, encrypt traffic to the tunnel, show an in-app disclosure with affirmative consent, and fill the VpnService declaration (videos of 90 s or less).' });
|
||||
}
|
||||
|
||||
// ---- prominent disclosure (User Data) ----
|
||||
if (android && (p.sources.length || a.strings.length)) {
|
||||
const bg = perms.get('ACCESS_BACKGROUND_LOCATION');
|
||||
const own = (q: { at: { file: string } }) => !a.mergedManifest || q.at.file !== a.mergedManifest;
|
||||
if (bg && own(bg) && !grep(textSources, BACKGROUND_DISCLOSURE, 1).length)
|
||||
add({ rule: 'play-prominent-disclosure', guideline: 'Play: User Data (prominent disclosure)', severity: 'high', title: 'Background location without a prominent disclosure that says "location" and "background" / "when the app is closed"',
|
||||
evidence: [ev(bg, bg.name)], ref: PLAY_REFS.backgroundLocation, skill: 'store-declarations',
|
||||
fix: 'Before the runtime prompt, show a dialog during normal use, e.g. "<App> collects location data to enable <feature> even when the app is closed or not in use." List every feature that uses it (and ads, if they do). It cannot live only in the privacy policy.' });
|
||||
const sensitive = [...perms.entries()].filter(([n, q]) => SENSITIVE_DATA[n] && own(q) && n !== 'ACCESS_BACKGROUND_LOCATION');
|
||||
if (sensitive.length && !grep(textSources, DISCLOSURE, 1).length)
|
||||
add({ rule: 'play-prominent-disclosure', guideline: 'Play: User Data (prominent disclosure)', severity: 'medium',
|
||||
title: `${[...new Set(sensitive.map(([n]) => SENSITIVE_DATA[n]))].join(', ')} access without a disclosure or rationale text in the app's sources or strings`,
|
||||
evidence: sensitive.slice(0, 3).map(([, q]) => ev(q, q.name)), ref: PLAY_REFS.userData, skill: 'store-declarations',
|
||||
fix: 'When people would not expect the collection, show an in-app disclosure right before the permission request that says which data is collected and how it is used or shared ("<App> collects <data> to enable <feature>, <when>."), and ask for an affirmative accept; the privacy policy alone is not enough.' });
|
||||
}
|
||||
|
||||
// ---- Data safety: SDK disclosures the config's answers miss (additions are the privacy-labels rule in rules.ts) ----
|
||||
for (const g of inp.dataMerges ?? [])
|
||||
add({ rule: 'privacy-labels', guideline: 'Play: User Data (Data safety)', severity: 'medium', title: `Data safety answer for ${g.type} is narrower than what is detected: ${g.missing}`, evidence: g.evidence.slice(0, 2),
|
||||
ref: 'https://support.google.com/googleplay/android-developer/answer/10787469', skill: 'store-declarations',
|
||||
fix: 'Check the SDK\'s Data safety guidance (sdks.ts names the page), widen the answer with `storebound scan --write`, then `storebound play data-safety`.' });
|
||||
if (c?.play && !c.dataSafety && p.sdks.some(s => s.sdk.data.length))
|
||||
add({ rule: 'privacy-labels', guideline: 'Play: User Data (Data safety)', severity: 'medium', title: 'SDKs that collect data, but the config has no dataSafety answers', evidence: sdkHits(s => s.sdk.data.length > 0).slice(0, 3),
|
||||
ref: 'https://support.google.com/googleplay/android-developer/answer/10787469', skill: 'store-declarations',
|
||||
fix: 'Run `storebound scan` and read the declarations proposal, confirm it with each SDK\'s disclosure page, `storebound scan --write`, then `storebound play data-safety`.' });
|
||||
|
||||
// ---- privacy policy in the app ----
|
||||
if (p.sources.length && android) {
|
||||
const link = grep(textSources, /privacy|gizlilik|datenschutz|confidentialit|privacidad/i, 1);
|
||||
const url = c?.app.privacyPolicyUrl ? grep(textSources, new RegExp(esc(c.app.privacyPolicyUrl)), 1) : [];
|
||||
if (!link.length && !url.length) {
|
||||
const collects = p.sdks.length > 0 || x.creates.length > 0 || [...perms.keys()].some(n => SENSITIVE_DATA[n]);
|
||||
add({ rule: 'play-privacy-policy', guideline: 'Play: User Data (privacy policy)', severity: collects ? 'medium' : 'low', title: 'No privacy policy link found in the app\'s sources (Play wants it in Play Console and inside the app)',
|
||||
evidence: [...cfg('privacyPolicyUrl'), ...sdkHits(() => true)].slice(0, 2).concat(p.sources.slice(0, 1).map(s => ({ file: s.path, line: 1, text: 'app sources' }))).slice(0, 3),
|
||||
ref: PLAY_REFS.userData, skill: 'privacy-policy',
|
||||
fix: 'Link app.privacyPolicyUrl from inside the app (e.g. Settings > Privacy policy, and the sign-up screen). It must be a public, non-geofenced https page, not a PDF, labelled as a privacy policy.' });
|
||||
}
|
||||
const insecure = grep(textSources, /["'>]http:\/\/[^"'<\s]*privacy/i, 1);
|
||||
if (insecure.length)
|
||||
add({ rule: 'play-privacy-policy', guideline: 'Play: User Data (privacy policy)', severity: 'medium', title: 'The in-app privacy policy link uses http://', evidence: insecure,
|
||||
ref: PLAY_REFS.userData, skill: 'privacy-policy', fix: 'Use the https URL (the same as app.privacyPolicyUrl).' });
|
||||
}
|
||||
|
||||
// ---- Families ----
|
||||
const adSdks = p.sdks.filter(s => s.sdk.category === 'ads');
|
||||
if (kidsAges.length) {
|
||||
const agesEv = cfg('targetAges');
|
||||
for (const s of adSdks) {
|
||||
const fam = s.sdk.families;
|
||||
const gradleDep = s.deps.find(d => d.eco === 'gradle' && d.version);
|
||||
const old = fam?.certified && fam.since && gradleDep ? versionAtLeast(gradleDep.version!, fam.since) === false : false;
|
||||
if (fam?.certified && !old) continue;
|
||||
add({ rule: 'play-families-ads', guideline: 'Play: Families policy', severity: 'high',
|
||||
title: old ? `${s.sdk.name} ${gradleDep!.version} is older than ${fam!.since}, the first Families self-certified version` : `${s.sdk.name} is not a Families Self-Certified Ads SDK (${fam?.note ?? 'not on the list'}), but the target audience includes children`,
|
||||
evidence: [...sdkHits(q => q.sdk.id === s.sdk.id), ...agesEv].slice(0, 3), ref: PLAY_REFS.familiesSdks, skill: 'ads-mediation-checks',
|
||||
fix: old ? `Update to ${fam!.since} or newer and turn on child-directed treatment.` : 'Ads shown to children (or users of unknown age) may only come from Families Self-Certified Ads SDKs (AdMob, ironSource / LevelPlay, Unity Ads and others on answer/9859768): remove this SDK and its mediation adapters, or take children out of the target audience.' });
|
||||
}
|
||||
const adIdFromSdk = p.sdks.filter(s => s.sdk.mergesAdId);
|
||||
const adId = perms.get(AD_ID);
|
||||
if (childOnly && (target === null || target >= 33) && !removed.has(AD_ID) && (adId || adIdFromSdk.length))
|
||||
add({ rule: 'play-families-ad-id', guideline: 'Play: Families policy', severity: 'high', title: 'App only for children with the advertising ID permission (AD_ID): child-only apps must not transmit the advertising ID',
|
||||
evidence: [...(adId ? [ev(adId, AD_ID)] : sdkHits(s => !!s.sdk.mergesAdId)), ...agesEv].slice(0, 3), ref: PLAY_REFS.families, skill: 'store-declarations',
|
||||
fix: 'Remove it from the merged manifest: <uses-permission android:name="com.google.android.gms.permission.AD_ID" tools:node="remove" />, turn on child-directed treatment in every ad SDK, and answer the Advertising ID declaration accordingly.' });
|
||||
else if (mixed && p.sdks.some(s => s.sdk.tracking && (s.sdk.category === 'ads' || s.sdk.category === 'attribution')))
|
||||
add({ rule: 'play-families-ad-id', guideline: 'Play: Families policy', severity: 'medium', title: 'Mixed audience with ad / attribution SDKs: no advertising ID or interest-based ads for children or users of unknown age',
|
||||
evidence: [...sdkHits(s => s.sdk.tracking && (s.sdk.category === 'ads' || s.sdk.category === 'attribution')), ...agesEv].slice(0, 3), ref: PLAY_REFS.families, skill: 'ads-mediation-checks',
|
||||
fix: 'Add a neutral age screen; for children and unknown ages turn on child-directed treatment (no advertising ID, no personalized ads or remarketing) in every SDK before it starts.' });
|
||||
const loc = ['ACCESS_FINE_LOCATION', 'ACCESS_COARSE_LOCATION', 'ACCESS_BACKGROUND_LOCATION'].map(n => perms.get(n)).filter(q => !!q);
|
||||
if (childOnly && loc.length)
|
||||
add({ rule: 'play-families-location', guideline: 'Play: Families policy', severity: 'high', title: 'App only for children requests location', evidence: [...loc.slice(0, 2).map(q => ev(q, q.name)), ...agesEv].slice(0, 3),
|
||||
ref: PLAY_REFS.families, skill: 'store-declarations', fix: 'Remove the location permissions (tools:node="remove" for ones an SDK adds); apps only for children may not request location.' });
|
||||
}
|
||||
|
||||
// ---- advertising ID permission (Android 13+) ----
|
||||
if (android && !childOnly && (target === null || target >= 33)) {
|
||||
const users = p.sdks.filter(s => s.sdk.tracking && (s.sdk.category === 'ads' || s.sdk.category === 'attribution'));
|
||||
if (users.length && !perms.has(AD_ID) && !removed.has(AD_ID) && !users.some(s => s.sdk.mergesAdId)) {
|
||||
const merged = !!a.mergedManifest;
|
||||
add({ rule: 'play-ad-id', guideline: 'Play: Advertising ID', severity: merged ? 'medium' : 'low',
|
||||
title: merged ? `The merged manifest has no AD_ID permission, but ${users.map(s => s.sdk.name).join(', ')} ${users.length > 1 ? 'use' : 'uses'} the advertising ID` : `${users.map(s => s.sdk.name).join(', ')} ${users.length > 1 ? 'use' : 'uses'} the advertising ID: check that the merged manifest declares AD_ID (targetSdk 33+)`,
|
||||
evidence: [...sdkHits(s => users.includes(s)), ...(merged ? [{ file: a.mergedManifest!, line: 1, text: 'merged AndroidManifest.xml' }] : [])].slice(0, 3), ref: PLAY_REFS.adId, skill: 'store-declarations',
|
||||
fix: 'Apps targeting Android 13+ that use the advertising ID declare <uses-permission android:name="com.google.android.gms.permission.AD_ID" /> (without it the ID reads as zeros); answer the Advertising ID question in App content the same way.' });
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 16 KB page sizes ----
|
||||
if (android) {
|
||||
const n = p.native;
|
||||
const ps: { title: string; evidence: Hit[]; fix: string; severity?: 'medium' }[] = [];
|
||||
if (n.unityVersion) {
|
||||
const v = n.unityVersion.value;
|
||||
const stream = /^(\d+\.\d+)/.exec(v)?.[1] ?? '';
|
||||
const min = UNITY_16KB[stream];
|
||||
const ok = min ? unityPatch(v) >= unityPatch(min) : Number(stream.split('.')[0]) >= 6000;
|
||||
if (!ok)
|
||||
ps.push({ title: `Unity ${v} builds without 16 KB page size support (needs ${min ?? '6000.0.38f1, 2022.3.56f1 or 2021.3.48f1 (Extended LTS)'} or newer)`, evidence: [{ ...n.unityVersion.at, text: `m_EditorVersion: ${v}` }],
|
||||
fix: `Update the editor to ${min ?? 'a supported LTS (6000.0.38f1+, 2022.3.56f1+)'} or newer and rebuild; plugins with their own .so files need 16 KB aligned builds too.` });
|
||||
}
|
||||
const rn = p.deps.find(d => d.eco === 'npm' && d.name === 'react-native' && d.version);
|
||||
if (rn && versionAtLeast(rn.version!, '0.77') === false)
|
||||
ps.push({ title: `React Native ${rn.version} is older than 0.77, the first version with full 16 KB page size support`, evidence: [{ file: rn.file, line: rn.line, text: `react-native ${rn.version}` }],
|
||||
fix: 'Upgrade React Native to 0.77 or newer (and native modules with their own .so files to aligned builds).' });
|
||||
const ndkMajor = n.ndkVersion ? Number(/^\d+/.exec(n.ndkVersion.value)?.[0]) : null;
|
||||
if (n.nativeBuild && ndkMajor !== null && ndkMajor < 28 && !n.flexiblePageSizes)
|
||||
ps.push({ title: `NDK ${n.ndkVersion!.value} (r${ndkMajor}) does not build 16 KB aligned libraries by default`, evidence: [{ ...n.ndkVersion!.at, text: `ndkVersion ${n.ndkVersion!.value}` }, { ...n.nativeBuild, text: 'native build' }],
|
||||
fix: `Use NDK r28 or newer, or ${ndkMajor === 27 ? 'set -DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON' : 'add -Wl,-z,max-page-size=16384 -Wl,-z,common-page-size=16384 to the linker flags (and link libc++ statically on r26 and older)'}.` });
|
||||
const hasNative = n.libs.length > 0 || !!n.nativeBuild || p.stacks.some(s => s === 'flutter' || s === 'react-native' || s === 'godot');
|
||||
const compressed = n.legacyPackaging || (a.extractNativeLibs?.value ? a.extractNativeLibs.at : null);
|
||||
if (hasNative && n.agp && versionAtLeast(n.agp.value, '8.5.1') === false && !compressed)
|
||||
ps.push({ title: `Android Gradle Plugin ${n.agp.value} does not 16 KB zip-align uncompressed native libraries (needs 8.5.1+)`,
|
||||
evidence: [{ ...n.agp.at, text: `AGP ${n.agp.value}` }, ...(a.extractNativeLibs ? [{ ...a.extractNativeLibs.at, text: `android:extractNativeLibs="${a.extractNativeLibs.value}"` }] : [])],
|
||||
fix: 'Update AGP to 8.5.1 or newer; until then set packaging { jniLibs { useLegacyPackaging = true } } (compressed libraries, bigger install; on AGP 8.0 or lower also android.bundle.enableUncompressedNativeLibs=false in gradle.properties).' });
|
||||
const own = n.libs.filter(f => !/(^|\/)(armeabi-v7a|armeabi|x86)\//.test(f));
|
||||
if (!ps.length && own.length)
|
||||
ps.push({ title: `${own.length} prebuilt native librar${own.length === 1 ? 'y' : 'ies'} (.so) in the project: check they are 16 KB aligned`, evidence: own.slice(0, 3).map(f => ({ file: f, line: 1, text: f.split('/').pop()! })),
|
||||
severity: 'medium', fix: 'Check the built app: zipalign -v -c -P 16 4 app.apk and check_elf_alignment.sh (LOAD segments align 2**14), or APK Analyzer; ask the vendor for an aligned build of any library that fails.' });
|
||||
for (const q of ps)
|
||||
add({ rule: 'play-16kb', guideline: 'Play: 16 KB page sizes', severity: q.severity ?? 'high',
|
||||
title: `${q.title}; from ${PAGE_SIZE_DEADLINE} Play blocks updates without 16 KB support (apps targeting Android 15+)`, evidence: q.evidence, fix: q.fix, ref: PLAY_REFS.pageSize, skill: 'play-first-release' });
|
||||
}
|
||||
|
||||
// ---- new personal developer accounts: closed testing before production ----
|
||||
if (c?.play) {
|
||||
const t = c.play.accountType;
|
||||
const created = c.play.accountCreated;
|
||||
if (t === 'personal' && (!created || created > PERSONAL_TESTING_SINCE))
|
||||
add({ rule: 'play-testing-requirement', guideline: 'Play: Testing for new personal accounts', severity: 'medium',
|
||||
title: `Personal developer account${created ? ` created ${created}` : ''}: production needs a closed test with at least ${PERSONAL_TESTING.testers} opted-in testers for ${PERSONAL_TESTING.days} days in a row first`,
|
||||
evidence: cfg('accountType'), ref: PLAY_REFS.testing, skill: 'play-first-release',
|
||||
fix: `Start the closed test early (testers opted in for ${PERSONAL_TESTING.days} continuous days), then apply for production access on the Dashboard; accounts created on or before ${PERSONAL_TESTING_SINCE} and organization accounts are exempt. Ignore this when production access is already granted.` });
|
||||
else if (!t)
|
||||
add({ rule: 'play-testing-requirement', guideline: 'Play: Testing for new personal accounts', severity: 'low',
|
||||
title: `Play account type unknown: new personal accounts need ${PERSONAL_TESTING.testers} testers for ${PERSONAL_TESTING.days} days in a closed test before production`,
|
||||
evidence: cfg(/play\s*:/), ref: PLAY_REFS.testing, skill: 'play-first-release',
|
||||
fix: `Set play.accountType ('personal' | 'organization') and play.accountCreated (YYYY-MM-DD) so scan can tell; personal accounts created after ${PERSONAL_TESTING_SINCE} need the closed test.` });
|
||||
}
|
||||
|
||||
// ---- Play listing metadata ----
|
||||
if (c?.play || inp.listings.play) {
|
||||
const listing = inp.listings.play;
|
||||
const titles: Hit[] = fieldBlocks(listing, /\btitle\b/i).map(b => ({ ...b.at, text: b.text.trim() }));
|
||||
if (!titles.length && c?.app.name) titles.push(...cfg(/\bname\s*:/, c.app.name).map(h => ({ ...h, text: c.app.name })));
|
||||
const long = titles.filter(t => [...t.text].length > 30);
|
||||
if (long.length)
|
||||
add({ rule: 'play-metadata', guideline: 'Play: Metadata', severity: 'high', title: `Play title longer than 30 characters: "${long[0]!.text}" (${[...long[0]!.text].length})`, evidence: long.slice(0, 2),
|
||||
ref: PLAY_REFS.metadata, skill: 'aso-basics', fix: 'Shorten the title to 30 characters or less (a "### title" block in store/listing.md, else app.name).' });
|
||||
const emoji = titles.filter(t => EMOJI.test(t.text));
|
||||
if (emoji.length)
|
||||
add({ rule: 'play-metadata', guideline: 'Play: Metadata', severity: 'high', title: 'Emoji, emoticons or repeated special characters in the Play title', evidence: emoji.slice(0, 2),
|
||||
ref: PLAY_REFS.metadata, skill: 'aso-basics', fix: 'Use plain words in the title (and the developer name and icon).' });
|
||||
const caps = titles.filter(t => /[A-Z]{4,}/.test(t.text) && t.text === t.text.toUpperCase());
|
||||
if (caps.length)
|
||||
add({ rule: 'play-metadata', guideline: 'Play: Metadata', severity: 'medium', title: `ALL CAPS Play title: "${caps[0]!.text}"`, evidence: caps.slice(0, 2),
|
||||
ref: PLAY_REFS.metadata, skill: 'aso-basics', fix: 'Write the title in normal case unless the capitals are your registered brand.' });
|
||||
const claims = titles.filter(t => CLAIMS.test(t.text));
|
||||
if (claims.length)
|
||||
add({ rule: 'play-metadata', guideline: 'Play: Metadata', severity: 'high', title: 'Rank, performance, price or promotion terms in the Play title ("#1", "best", "top", "popular", "sale", "% off")', evidence: claims.slice(0, 2),
|
||||
ref: PLAY_REFS.metadata, skill: 'aso-basics', fix: 'Remove claims and promotions from the title (and the icon and developer name); describe what the app does instead.' });
|
||||
const soft = titles.filter(t => !CLAIMS.test(t.text) && SOFT_CLAIMS.test(t.text));
|
||||
if (soft.length)
|
||||
add({ rule: 'play-metadata', guideline: 'Play: Metadata', severity: 'low', title: `"Free" or "New" in the Play title: "${soft[0]!.text}"`, evidence: soft.slice(0, 2),
|
||||
ref: PLAY_REFS.metadata, skill: 'aso-basics', fix: 'Keep it only when it is part of the real name; as a price, promotion or "New" label it is not allowed in the title.' });
|
||||
const others = new RegExp(`(^|[^\\p{L}])(${OTHER_APPS.map(esc).join('|')})(?=$|[^\\p{L}])`, 'iu');
|
||||
const named = [...titles.filter(t => others.test(t.text)), ...fieldBlocks(listing, /\bshort\b/i).filter(b => others.test(b.text)).map(b => b.at)];
|
||||
if (named.length)
|
||||
add({ rule: 'play-metadata', guideline: 'Play: Metadata', severity: 'medium', title: 'Other apps or brands named in the Play title or short description', evidence: named.slice(0, 2),
|
||||
ref: PLAY_REFS.metadata, skill: 'aso-basics', fix: 'Remove other apps\' names and comparisons; name a brand only for a real integration you are allowed to mention, and never in a way that implies an endorsement.' });
|
||||
for (const b of fieldBlocks(listing, /\bfull\b/i)) {
|
||||
const words = b.text.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
|
||||
const counts = new Map<string, number>();
|
||||
for (const w of words) if (w.length > 3 && !STOP.has(w)) counts.set(w, (counts.get(w) ?? 0) + 1);
|
||||
const rep = words.length >= 80 ? [...counts].filter(([, k]) => k >= 6 && k / words.length > 0.03).sort((q, r) => r[1] - q[1]) : [];
|
||||
const lists = b.text.split('\n').map((l, i) => ({ l, i })).filter(({ l }) => l.split(/[,|]/).length >= 8 && l.split(/[,|]/).every(s => s.trim().split(/\s+/).length <= 3));
|
||||
if (rep.length || lists.length)
|
||||
add({ rule: 'play-metadata', guideline: 'Play: Metadata', severity: 'medium',
|
||||
title: [rep.length ? `repeated keywords (${rep.slice(0, 3).map(([w, k]) => `"${w}" ${k}x`).join(', ')})` : '', lists.length ? 'a keyword list' : ''].filter(Boolean).join(' and ').replace(/^./, s => s.toUpperCase()) + ' in the full description',
|
||||
evidence: [...(rep.length ? [b.at] : []), ...(lists.length ? [{ file: b.at.file, line: b.at.line + lists[0]!.i, text: lists[0]!.l.trim().slice(0, 160) }] : [])], ref: PLAY_REFS.metadata, skill: 'aso-basics',
|
||||
fix: 'Write the description for people: say each thing once, no keyword lists or repeated terms (Play treats them as spam).' });
|
||||
}
|
||||
}
|
||||
|
||||
// ---- ads at app launch (Android native: the launcher activity) ----
|
||||
if (android) {
|
||||
const launcher = a.components.find(q => q.kind === 'activity' && q.categories.includes('android.intent.category.LAUNCHER') && (!a.mergedManifest || q.at.file !== a.mergedManifest));
|
||||
const cls = launcher?.name.split('.').pop();
|
||||
const file = cls ? p.sources.find(s => /\.(kt|java)$/.test(s.path) && new RegExp(`\\bclass\\s+${esc(cls)}\\b`).test(s.text)) : undefined;
|
||||
if (file) {
|
||||
const lines = file.text.split('\n');
|
||||
const start = lines.findIndex(l => /\bonCreate\s*\(/.test(l) && !/^\s*(\/\/|\*)/.test(l));
|
||||
if (start >= 0) {
|
||||
const indent = /^\s*/.exec(lines[start]!)![0].length;
|
||||
let end = start + 1;
|
||||
while (end < lines.length && !(/\S/.test(lines[end]!) && /^\s*/.exec(lines[end]!)![0].length <= indent && /^\s*(override\s+|public\s+|protected\s+|private\s+|fun\s|void\s|@)/.test(lines[end]!))) end++;
|
||||
const body = lines.slice(start, end);
|
||||
const show = body.findIndex(l => /interstitial\w*\??\.show(?:Ad)?\s*\(|showInterstitial\s*\(|IronSource\.showInterstitial|UnityAds\.show\s*\(|\bad\??\.show\s*\(\s*(this|this@\w+|activity|requireActivity\(\))/i.test(l) && !/^\s*(\/\/|\*)/.test(l));
|
||||
if (show >= 0 && body.some(l => /interstitial/i.test(l)))
|
||||
add({ rule: 'play-ads-launch', guideline: 'Play: Ads (Better Ads Experiences)', severity: 'medium', title: `An interstitial is shown from ${cls}.onCreate, the launcher activity (an ad before the app has loaded)`,
|
||||
evidence: [{ file: file.path, line: start + show + 1, text: body[show]!.trim().slice(0, 160) }, ev(launcher!, `launcher ${launcher!.name}`)], ref: PLAY_REFS.betterAds, skill: 'ads-mediation-checks',
|
||||
fix: 'Show interstitials only at natural breaks after the app has loaded (after a level or a finished task), never at launch before the home screen or while people are doing something else.' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- payments outside Play Billing ----
|
||||
const programs = c?.play?.billingPrograms ?? [];
|
||||
if (c?.play || android) {
|
||||
const extPay = sdkHits(s => s.sdk.category === 'external-payments');
|
||||
const digital = x.restorable.length || x.paySdk.length || (c?.products?.length ?? 0) > 0 || (c ? allSubscriptions(c.subscriptions).length > 0 : false);
|
||||
if (extPay.length && digital && !programs.length)
|
||||
add({ rule: 'play-payments', guideline: 'Play: Payments', severity: 'medium', title: 'A card / PayPal payment SDK next to in-app products: digital goods on Play must use Play Billing', evidence: [...extPay, ...x.restorable].slice(0, 3),
|
||||
ref: PLAY_REFS.payments, skill: 'store-iap-setup',
|
||||
fix: 'Sell unlocks, coins, subscriptions and ad removal through Play Billing; keep Stripe / PayPal for physical goods and services. Enrolled in user choice billing, external offers or US external content links? Set play.billingPrograms.' });
|
||||
const nonApple = (q: string) => !/\.(swift|m|mm|h)$/.test(q);
|
||||
const steer = programs.length ? [] : [...x.listingHits(inp.listings.play, EXTERNAL_BUY), ...grep(p.sources, EXTERNAL_BUY, 2, nonApple)];
|
||||
if (steer.length && (c?.play || android))
|
||||
add({ rule: 'play-payments', guideline: 'Play: Payments', severity: 'medium', title: 'A call to action to buy outside the app (website) in the Play listing or the app', evidence: steer.slice(0, 3),
|
||||
ref: PLAY_REFS.payments, skill: 'review-rejections', fix: 'Outside the alternative billing and external offers programs, do not lead people to pay for digital content elsewhere; remove the text or enroll and set play.billingPrograms.' });
|
||||
}
|
||||
|
||||
// ---- impersonation ----
|
||||
if (c?.play) {
|
||||
const pkg = c.play.packageName.toLowerCase();
|
||||
const segs = pkg.split('.');
|
||||
const brandIn = (s: string) => BRANDS.find(b => s.split(/[_\d]+/).includes(b) || (b.length >= 6 && s.includes(b)));
|
||||
const owner = segs[1] ?? '';
|
||||
const hitPkg = segs.slice(1).map(brandIn).find(b => b && b !== owner);
|
||||
const nameRe = new RegExp(`(^|[^\\p{L}])(${BRANDS.map(esc).join('|')})(?=$|[^\\p{L}])`, 'iu');
|
||||
const hitName = nameRe.exec(c.app.name)?.[2];
|
||||
if ((hitPkg && !brandIn(owner)) || hitName)
|
||||
add({ rule: 'play-impersonation', guideline: 'Play: Impersonation', severity: 'low', title: `${hitPkg ? `Package name ${c.play.packageName}` : `App name "${c.app.name}"`} contains "${hitPkg ?? hitName}": check that it does not suggest a relation with that brand`,
|
||||
evidence: [...(hitPkg ? cfg('packageName') : []), ...(hitName ? cfg(/\bname\s*:/) : [])].slice(0, 2), ref: PLAY_REFS.impersonation, skill: 'review-rejections',
|
||||
fix: 'Don\'t imply that the app is made or endorsed by another company: remove the brand from the name and package (it can\'t change after the first upload), or have written permission ready for an appeal.' });
|
||||
}
|
||||
}
|
||||
|
||||
/** Unity patch number for comparison inside one stream ("2022.3.56f1" -> 56). */
|
||||
function unityPatch(v: string): number { return Number(/^\d+\.\d+\.(\d+)/.exec(v)?.[1] ?? 0); }
|
||||
|
||||
581
cli/lib/scan/project.ts
Normal file
581
cli/lib/scan/project.ts
Normal file
|
|
@ -0,0 +1,581 @@
|
|||
// Project detection for `storebound scan`: reads a mobile app or game project (read-only, offline) and works out the
|
||||
// stack, the dependencies (with versions and the file:line they come from), the Info.plist keys (from Info.plist files,
|
||||
// Xcode INFOPLIST_KEY_* build settings, Expo app.json, Unity ProjectSettings and Godot export presets), entitlements,
|
||||
// privacy manifests, the Android manifest (permissions, services, target SDK) and the app's own source files.
|
||||
// Tolerant on purpose: an unreadable or odd file is skipped, never an exception.
|
||||
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { basename, extname, join, relative, sep } from 'node:path';
|
||||
import { type Manifest, parseManifest } from '../privacy-manifest';
|
||||
import { type DepRef, type Eco, matchesSdk, SDKS, type SdkDef } from './sdks';
|
||||
|
||||
export interface Loc { file: string; line: number }
|
||||
export interface PlistEntry { key: string; value: unknown; at: Loc }
|
||||
export interface Hit extends Loc { text: string }
|
||||
|
||||
export type Stack = 'ios-native' | 'android-native' | 'react-native' | 'expo' | 'capacitor' | 'cordova' | 'flutter' | 'unity' | 'godot' | 'web';
|
||||
|
||||
export interface DetectedSdk { sdk: SdkDef; deps: DepRef[] }
|
||||
|
||||
export interface AndroidComponent {
|
||||
kind: 'activity' | 'service' | 'receiver';
|
||||
name: string;
|
||||
/** android:permission (e.g. BIND_ACCESSIBILITY_SERVICE, BIND_VPN_SERVICE, BIND_DEVICE_ADMIN). */
|
||||
permission: string | null;
|
||||
fgsType: string | null;
|
||||
actions: string[];
|
||||
categories: string[];
|
||||
meta: string[];
|
||||
at: Loc;
|
||||
}
|
||||
|
||||
export interface ProjectFacts {
|
||||
root: string;
|
||||
stacks: Stack[];
|
||||
/** The project has iOS / Android build files (or a cross-platform engine that targets them). */
|
||||
ios: boolean;
|
||||
android: boolean;
|
||||
deps: DepRef[];
|
||||
sdks: DetectedSdk[];
|
||||
/** Info.plist keys merged from every source; first source wins. */
|
||||
plist: Map<string, PlistEntry>;
|
||||
/** Where Info.plist keys came from (empty = the project has no readable iOS settings: plist rules are skipped). */
|
||||
plistSources: string[];
|
||||
entitlements: Map<string, PlistEntry>;
|
||||
privacyManifests: Manifest[];
|
||||
androidInfo: {
|
||||
manifests: string[];
|
||||
permissions: { name: string; at: Loc }[];
|
||||
services: { name: string; fgsType: string | null; at: Loc }[];
|
||||
targetSdk: { value: number; at: Loc } | null;
|
||||
/** targetSdk is set by a tool we cannot read (Flutter SDK, Expo SDK, Unity "automatic"). */
|
||||
targetSdkFrom: string | null;
|
||||
formFactor: 'phone' | 'wear' | 'tv' | 'automotive';
|
||||
/** <uses-permission tools:node="remove">: permissions the app strips from the merged manifest (e.g. AD_ID). */
|
||||
removedPermissions: { name: string; at: Loc }[];
|
||||
/** Activities, services and receivers with their android:permission, intent-filter actions and meta-data names. */
|
||||
components: AndroidComponent[];
|
||||
/** <application android:extractNativeLibs="..."> */
|
||||
extractNativeLibs: { value: boolean; at: Loc } | null;
|
||||
/** A merged manifest from a local build (build/intermediates), read for the permissions libraries add. */
|
||||
mergedManifest: string | null;
|
||||
/** res/xml accessibility-service configs (android:isAccessibilityTool). */
|
||||
accessibilityConfigs: { at: Loc; isTool: boolean }[];
|
||||
/** res/values*\/strings.xml (for disclosure texts). */
|
||||
strings: { path: string; text: string }[];
|
||||
};
|
||||
/** Native code and the toolchain versions that decide 16 KB page size support. */
|
||||
native: {
|
||||
/** Prebuilt .so files in the project (jniLibs, Unity Plugins/Android, ...). */
|
||||
libs: string[];
|
||||
ndkVersion: { value: string; at: Loc } | null;
|
||||
/** The NDK version is set by a tool (flutter.ndkVersion). */
|
||||
ndkFrom: string | null;
|
||||
/** Android Gradle Plugin version. */
|
||||
agp: { value: string; at: Loc } | null;
|
||||
/** The project builds C / C++ itself (externalNativeBuild, CMakeLists.txt, Android.mk). */
|
||||
nativeBuild: Loc | null;
|
||||
/** ANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON or -Wl,-z,max-page-size=16384 in the native build. */
|
||||
flexiblePageSizes: Loc | null;
|
||||
/** jniLibs.useLegacyPackaging = true (compressed native libraries). */
|
||||
legacyPackaging: Loc | null;
|
||||
/** ProjectSettings/ProjectVersion.txt m_EditorVersion. */
|
||||
unityVersion: { value: string; at: Loc } | null;
|
||||
};
|
||||
/** Capacitor server.url / Cordova <content src> pointing at a remote site. */
|
||||
remoteStart: { url: string; at: Loc } | null;
|
||||
/** App source files (Swift, Objective-C, Kotlin, Java, Dart, JS / TS, C#, GDScript, HTML). */
|
||||
sources: { path: string; text: string }[];
|
||||
/** Files looked at, relative to root (for the report). */
|
||||
scanned: number;
|
||||
}
|
||||
|
||||
const SKIP_DIRS = new Set(['.git', 'node_modules', 'Pods', 'build', 'Build', 'DerivedData', '.gradle', '.dart_tool', '.build', 'Library', 'Temp', 'Logs',
|
||||
'obj', 'UserSettings', '.storebound', 'renders', '.idea', '.vscode', '.expo', 'vendor', 'xcuserdata', 'Carthage', '.next', 'coverage', '.godot',
|
||||
'intermediates', 'generated', 'outputs', 'tmp', '.cxx', 'fastlane', 'dist', 'www', 'public', 'clips', 'frames', 'fonts', '.fvm']);
|
||||
const SRC_EXT = new Set(['.swift', '.m', '.mm', '.h', '.kt', '.java', '.dart', '.js', '.jsx', '.ts', '.tsx', '.cs', '.gd', '.html', '.vue', '.svelte']);
|
||||
const MAX_FILES = 25_000;
|
||||
const MAX_TEXT = 1_500_000;
|
||||
|
||||
/** Every file under root (relative paths), skipping build output, dependency folders and VCS data. Native libraries
|
||||
* (.so) of any size also go into `bins` when given (they are not read, only listed). */
|
||||
export function listFiles(root: string, bins?: string[]): string[] {
|
||||
const out: string[] = [];
|
||||
const walk = (dir: string, depth: number) => {
|
||||
if (depth > 14 || out.length >= MAX_FILES) return;
|
||||
let names: string[];
|
||||
try { names = readdirSync(dir); } catch { return; }
|
||||
for (const n of names.sort()) {
|
||||
if (SKIP_DIRS.has(n) || n === '.DS_Store') continue;
|
||||
const p = join(dir, n);
|
||||
let st;
|
||||
try { st = statSync(p); } catch { continue; }
|
||||
if (st.isDirectory()) {
|
||||
// compiled frameworks are SDK binaries, not app code
|
||||
if (/\.(xc)?framework$|\.xcassets$|\.bundle$|\.app$|\.dSYM$/.test(n)) continue;
|
||||
walk(p, depth + 1);
|
||||
} else {
|
||||
if (bins && n.endsWith('.so')) bins.push(relative(root, p).split(sep).join('/'));
|
||||
if (st.size <= MAX_TEXT) out.push(relative(root, p).split(sep).join('/'));
|
||||
}
|
||||
if (out.length >= MAX_FILES) return;
|
||||
}
|
||||
};
|
||||
walk(root, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
export const lineAt = (text: string, index: number): number => (index <= 0 ? 1 : text.slice(0, index).split('\n').length);
|
||||
/** Line of the first occurrence of `needle` (1 when not found). */
|
||||
export const lineOf = (text: string, needle: string | RegExp): number => {
|
||||
const i = typeof needle === 'string' ? text.indexOf(needle) : text.search(needle);
|
||||
return i < 0 ? 1 : lineAt(text, i);
|
||||
};
|
||||
|
||||
// ---- plist ----
|
||||
|
||||
type PV = string | number | boolean | PV[] | { [k: string]: PV };
|
||||
|
||||
/** Minimal XML plist reader: the value tree, plus the line of every top-level key. Never throws (bad input -> {}). */
|
||||
export function parsePlist(xml: string): { value: Record<string, PV>; lines: Map<string, number> } {
|
||||
const lines = new Map<string, number>();
|
||||
const re = /<(\/?)(dict|array|key|string|integer|real|true|false|date|data)(\s*\/)?>|<!--[\s\S]*?-->|<\?[\s\S]*?\?>|<!DOCTYPE[^>]*>|<\/?plist[^>]*>/g;
|
||||
const toks: { tag: string; close: boolean; self: boolean; at: number; end: number }[] = [];
|
||||
for (const m of xml.matchAll(re)) if (m[2]) toks.push({ tag: m[2], close: m[1] === '/', self: !!m[3] || m[2] === 'true' || m[2] === 'false', at: m.index!, end: m.index! + m[0].length });
|
||||
let i = 0;
|
||||
const unesc = (s: string) => s.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, '\'').replace(/&/g, '&');
|
||||
const readText = (tag: string): string => {
|
||||
const open = toks[i]!;
|
||||
if (open.self) { i++; return ''; }
|
||||
const close = toks[i + 1];
|
||||
i += 2;
|
||||
return close && close.tag === tag && close.close ? unesc(xml.slice(open.end, close.at)) : '';
|
||||
};
|
||||
const value = (depth: number): PV => {
|
||||
const t = toks[i];
|
||||
if (!t || depth > 30) { i++; return ''; }
|
||||
switch (t.tag) {
|
||||
case 'true': i++; if (toks[i]?.tag === 'true' && toks[i]!.close) i++; return true;
|
||||
case 'false': i++; if (toks[i]?.tag === 'false' && toks[i]!.close) i++; return false;
|
||||
case 'integer': case 'real': return Number(readText(t.tag));
|
||||
case 'string': case 'date': case 'data': return readText(t.tag);
|
||||
case 'array': {
|
||||
i++;
|
||||
const a: PV[] = [];
|
||||
if (t.self) return a;
|
||||
while (i < toks.length && !(toks[i]!.tag === 'array' && toks[i]!.close)) a.push(value(depth + 1));
|
||||
i++;
|
||||
return a;
|
||||
}
|
||||
case 'dict': {
|
||||
i++;
|
||||
const o: Record<string, PV> = {};
|
||||
if (t.self) return o;
|
||||
while (i < toks.length && !(toks[i]!.tag === 'dict' && toks[i]!.close)) {
|
||||
if (toks[i]!.tag !== 'key') { i++; continue; }
|
||||
const at = toks[i]!.at;
|
||||
const k = readText('key');
|
||||
if (depth === 0) lines.set(k, lineAt(xml, at));
|
||||
o[k] = value(depth + 1);
|
||||
}
|
||||
i++;
|
||||
return o;
|
||||
}
|
||||
default: i++; return '';
|
||||
}
|
||||
};
|
||||
while (i < toks.length && toks[i]!.tag !== 'dict') i++;
|
||||
const v = i < toks.length ? value(0) : {};
|
||||
return { value: (v && typeof v === 'object' && !Array.isArray(v) ? v : {}) as Record<string, PV>, lines };
|
||||
}
|
||||
|
||||
// ---- dependency files ----
|
||||
|
||||
function podsLock(file: string, text: string): DepRef[] {
|
||||
const out: DepRef[] = [];
|
||||
const pods = /^PODS:\n([\s\S]*?)(?=\n\S|$(?![\s\S]))/m.exec(text)?.[1] ?? '';
|
||||
const off = text.indexOf(pods);
|
||||
for (const m of pods.matchAll(/^ {2}- "?([A-Za-z0-9_.+\-/]+) \(([^)]+)\)"?:?$/gm))
|
||||
out.push({ eco: 'cocoapods', name: m[1]!, version: m[2]!, file, line: lineAt(text, off + m.index!) });
|
||||
return out;
|
||||
}
|
||||
function podfile(file: string, text: string): DepRef[] {
|
||||
return [...text.matchAll(/^\s*pod\s+['"]([^'"]+)['"](?:\s*,\s*['"]([^'"]+)['"])?/gm)].map(m => ({ eco: 'cocoapods' as const, name: m[1]!, version: m[2] ?? null, file, line: lineAt(text, m.index!) }));
|
||||
}
|
||||
function packageResolved(file: string, text: string): DepRef[] {
|
||||
try {
|
||||
const j = JSON.parse(text) as { pins?: { identity?: string; location?: string; state?: { version?: string } }[]; object?: { pins?: { package?: string; repositoryURL?: string; state?: { version?: string } }[] } };
|
||||
const pins = j.pins ?? j.object?.pins?.map(p => ({ identity: p.package, location: p.repositoryURL, state: p.state })) ?? [];
|
||||
return pins.map(p => ({ eco: 'spm' as const, name: p.location ?? p.identity ?? '', version: p.state?.version ?? null, file, line: lineOf(text, p.location ?? p.identity ?? '') }));
|
||||
} catch { return []; }
|
||||
}
|
||||
function pbxproj(file: string, text: string): DepRef[] {
|
||||
const out: DepRef[] = [];
|
||||
for (const m of text.matchAll(/repositoryURL = "([^"]+)";/g)) out.push({ eco: 'spm', name: m[1]!, version: null, file, line: lineAt(text, m.index!) });
|
||||
for (const m of text.matchAll(/isa = XCSwiftPackageProductDependency;[\s\S]{0,300}?productName = "?([A-Za-z0-9_-]+)"?;/g)) out.push({ eco: 'spm', name: m[1]!, version: null, file, line: lineAt(text, m.index!) });
|
||||
return out;
|
||||
}
|
||||
function cartfile(file: string, text: string): DepRef[] {
|
||||
return [...text.matchAll(/^\s*(?:github|git|binary)\s+"([^"]+)"(?:\s+"?([^"\n]+)"?)?/gm)].map(m => ({ eco: 'carthage' as const, name: m[1]!, version: m[2]?.trim() ?? null, file, line: lineAt(text, m.index!) }));
|
||||
}
|
||||
function gradle(file: string, text: string): DepRef[] {
|
||||
const out: DepRef[] = [];
|
||||
for (const m of text.matchAll(/(?:implementation|api|compileOnly|runtimeOnly|kapt|ksp|annotationProcessor|classpath)\s*\(?\s*(?:platform\(\s*)?["']([A-Za-z0-9_.\-]+):([A-Za-z0-9_.\-]+)(?::([^"'@]+))?/g))
|
||||
out.push({ eco: 'gradle', name: `${m[1]}:${m[2]}`, version: m[3] ?? null, file, line: lineAt(text, m.index!) });
|
||||
return out;
|
||||
}
|
||||
function versionCatalog(file: string, text: string): DepRef[] {
|
||||
const versions = new Map<string, string>();
|
||||
const vsec = /^\[versions\]\n([\s\S]*?)(?=^\[|$(?![\s\S]))/m.exec(text)?.[1] ?? '';
|
||||
for (const m of vsec.matchAll(/^\s*([A-Za-z0-9_.\-]+)\s*=\s*"([^"]+)"/gm)) versions.set(m[1]!, m[2]!);
|
||||
const out: DepRef[] = [];
|
||||
for (const m of text.matchAll(/^\s*[A-Za-z0-9_.\-]+\s*=\s*\{([^}]*)\}/gm)) {
|
||||
const body = m[1]!;
|
||||
const mod = /module\s*=\s*"([^":]+):([^"]+)"/.exec(body);
|
||||
const grp = /group\s*=\s*"([^"]+)"/.exec(body), nm = /name\s*=\s*"([^"]+)"/.exec(body);
|
||||
const plugin = /\bid\s*=\s*"(com\.android\.(?:application|library))"/.exec(body);
|
||||
const name = mod ? `${mod[1]}:${mod[2]}` : grp && nm ? `${grp[1]}:${nm[1]}` : plugin ? 'com.android.application' : null;
|
||||
if (!name) continue;
|
||||
const ver = /version\.ref\s*=\s*"([^"]+)"/.exec(body)?.[1];
|
||||
out.push({ eco: 'gradle', name, version: ver ? versions.get(ver) ?? null : /version\s*=\s*"([^"]+)"/.exec(body)?.[1] ?? null, file, line: lineAt(text, m.index!) });
|
||||
}
|
||||
for (const m of text.matchAll(/^\s*[A-Za-z0-9_.\-]+\s*=\s*"([A-Za-z0-9_.\-]+):([A-Za-z0-9_.\-]+):([^"]+)"/gm))
|
||||
out.push({ eco: 'gradle', name: `${m[1]}:${m[2]}`, version: m[3]!, file, line: lineAt(text, m.index!) });
|
||||
return out;
|
||||
}
|
||||
function packageJson(file: string, text: string): DepRef[] {
|
||||
try {
|
||||
const j = JSON.parse(text) as { dependencies?: Record<string, string> };
|
||||
return Object.entries(j.dependencies ?? {}).map(([n, v]) => ({ eco: 'npm' as const, name: n, version: v, file, line: lineOf(text, `"${n}"`) }));
|
||||
} catch { return []; }
|
||||
}
|
||||
function pubspec(file: string, text: string): DepRef[] {
|
||||
const sec = /^dependencies:\n([\s\S]*?)(?=^\S|$(?![\s\S]))/m.exec(text);
|
||||
if (!sec) return [];
|
||||
const off = sec.index + 'dependencies:\n'.length;
|
||||
return [...sec[1]!.matchAll(/^ {2}([a-z0-9_]+):\s*([^\n#]*)/gm)].map(m => ({ eco: 'pub' as const, name: m[1]!, version: m[2]!.trim() || null, file, line: lineAt(text, off + m.index!) }));
|
||||
}
|
||||
function pubspecLock(text: string): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
for (const m of text.matchAll(/^ {2}([a-z0-9_]+):\n(?: {4}.*\n)*? {4}version: "([^"]+)"/gm)) out.set(m[1]!, m[2]!);
|
||||
return out;
|
||||
}
|
||||
function unityManifest(file: string, text: string): DepRef[] {
|
||||
try {
|
||||
const j = JSON.parse(text) as { dependencies?: Record<string, string> };
|
||||
return Object.entries(j.dependencies ?? {}).map(([n, v]) => ({ eco: 'unity' as const, name: n, version: v, file, line: lineOf(text, `"${n}"`) }));
|
||||
} catch { return []; }
|
||||
}
|
||||
/** External Dependency Manager (Assets/.../Editor/*Dependencies.xml): the pods and Gradle packages a Unity plugin adds. */
|
||||
function edmXml(file: string, text: string): DepRef[] {
|
||||
const out: DepRef[] = [];
|
||||
for (const m of text.matchAll(/<iosPod\s+name="([^"]+)"(?:\s+version="([^"]+)")?/g)) out.push({ eco: 'cocoapods', name: m[1]!, version: m[2] ?? null, file, line: lineAt(text, m.index!) });
|
||||
for (const m of text.matchAll(/<androidPackage\s+spec="([^":]+):([^":]+)(?::([^"]+))?"/g)) out.push({ eco: 'gradle', name: `${m[1]}:${m[2]}`, version: m[3] ?? null, file, line: lineAt(text, m.index!) });
|
||||
return out;
|
||||
}
|
||||
function cordovaXml(file: string, text: string): DepRef[] {
|
||||
return [...text.matchAll(/<plugin\s+name="([^"]+)"(?:\s+spec="([^"]+)")?/g)].map(m => ({ eco: 'npm' as const, name: m[1]!, version: m[2] ?? null, file, line: lineAt(text, m.index!) }));
|
||||
}
|
||||
|
||||
// ---- Info.plist key sources other than Info.plist ----
|
||||
|
||||
const UNITY_KEYS: Record<string, string> = { cameraUsageDescription: 'NSCameraUsageDescription', locationUsageDescription: 'NSLocationWhenInUseUsageDescription', microphoneUsageDescription: 'NSMicrophoneUsageDescription' };
|
||||
const GODOT_KEYS: Record<string, string> = {
|
||||
'privacy/camera_usage_description': 'NSCameraUsageDescription', 'privacy/microphone_usage_description': 'NSMicrophoneUsageDescription',
|
||||
'privacy/photolibrary_usage_description': 'NSPhotoLibraryUsageDescription',
|
||||
};
|
||||
|
||||
export function detectProject(root: string): ProjectFacts {
|
||||
const bins: string[] = [];
|
||||
const files = listFiles(root, bins);
|
||||
const cache = new Map<string, string>();
|
||||
const read = (f: string): string => {
|
||||
if (!cache.has(f)) { try { cache.set(f, readFileSync(join(root, f), 'utf8')); } catch { cache.set(f, ''); } }
|
||||
return cache.get(f)!;
|
||||
};
|
||||
const has = (re: RegExp) => files.some(f => re.test(f));
|
||||
const deps: DepRef[] = [];
|
||||
const plist = new Map<string, PlistEntry>();
|
||||
const plistSources: string[] = [];
|
||||
const entitlements = new Map<string, PlistEntry>();
|
||||
const privacyManifests: Manifest[] = [];
|
||||
const setKey = (m: Map<string, PlistEntry>, key: string, value: unknown, at: Loc) => { if (!m.has(key)) m.set(key, { key, value, at }); };
|
||||
const android: ProjectFacts['androidInfo'] = { manifests: [], permissions: [], services: [], targetSdk: null, targetSdkFrom: null, formFactor: 'phone',
|
||||
removedPermissions: [], components: [], extractNativeLibs: null, mergedManifest: null, accessibilityConfigs: [], strings: [] };
|
||||
const native: ProjectFacts['native'] = { libs: bins, ndkVersion: null, ndkFrom: null, agp: null, nativeBuild: null, flexiblePageSizes: null, legacyPackaging: null, unityVersion: null };
|
||||
const sdkHits: { value: number; at: Loc; prio: number }[] = [];
|
||||
let remoteStart: ProjectFacts['remoteStart'] = null;
|
||||
const sources: { path: string; text: string }[] = [];
|
||||
const stacks = new Set<Stack>();
|
||||
let pubLock = new Map<string, string>();
|
||||
|
||||
for (const f of files) {
|
||||
const n = basename(f);
|
||||
const testy = /(^|\/)(Tests?|UITests|[A-Za-z]+Tests|test|androidTest|__tests__|Example|Samples?)\//.test(f);
|
||||
if (n === 'Info.plist' && !testy && !/\.(app|appex)\//.test(f)) {
|
||||
const { value, lines } = parsePlist(read(f));
|
||||
if (Object.keys(value).length) plistSources.push(f);
|
||||
for (const [k, v] of Object.entries(value)) setKey(plist, k, v, { file: f, line: lines.get(k) ?? 1 });
|
||||
} else if (n.endsWith('.entitlements')) {
|
||||
const { value, lines } = parsePlist(read(f));
|
||||
for (const [k, v] of Object.entries(value)) setKey(entitlements, k, v, { file: f, line: lines.get(k) ?? 1 });
|
||||
} else if (n === 'PrivacyInfo.xcprivacy') privacyManifests.push(parseManifest(f, read(f)));
|
||||
else if (n === 'project.pbxproj') {
|
||||
const t = read(f);
|
||||
deps.push(...pbxproj(f, t));
|
||||
let found = false;
|
||||
for (const m of t.matchAll(/INFOPLIST_KEY_([A-Za-z]+) = ("(?:[^"\\]|\\.)*"|[^;\n]*);/g)) {
|
||||
found = true;
|
||||
setKey(plist, m[1]!, m[2]!.replace(/^"|"$/g, '').replace(/\\"/g, '"'), { file: f, line: lineAt(t, m.index!) });
|
||||
}
|
||||
if (found) plistSources.push(f);
|
||||
} else if (n === 'Podfile.lock') deps.push(...podsLock(f, read(f)));
|
||||
else if (n === 'Podfile') deps.push(...podfile(f, read(f)));
|
||||
else if (n === 'Package.resolved') deps.push(...packageResolved(f, read(f)));
|
||||
else if (n === 'Cartfile' || n === 'Cartfile.resolved') deps.push(...cartfile(f, read(f)));
|
||||
else if (/^(build\.gradle(\.kts)?|variables\.gradle|settings\.gradle(\.kts)?)$/.test(n)) {
|
||||
const t = read(f);
|
||||
deps.push(...gradle(f, t));
|
||||
for (const m of t.matchAll(/\btargetSdk(?:Version)?\s*(?:=|\s)\s*\(?\s*(\d{2})\b/g))
|
||||
sdkHits.push({ value: Number(m[1]), at: { file: f, line: lineAt(t, m.index!) }, prio: /(^|\/)app\/|variables\.gradle/.test(f) ? 0 : 1 });
|
||||
if (/targetSdk(?:Version)?\s*(?:=|\s)\s*flutter\.targetSdkVersion/.test(t)) android.targetSdkFrom = 'the Flutter SDK (flutter.targetSdkVersion)';
|
||||
gradleNative(f, t, native, deps);
|
||||
} else if (n === 'libs.versions.toml') {
|
||||
const t = read(f);
|
||||
deps.push(...versionCatalog(f, t));
|
||||
for (const m of t.matchAll(/^\s*(?:target-?sdk|targetSdk|android-?target-?sdk)\w*\s*=\s*"(\d{2})"/gim)) sdkHits.push({ value: Number(m[1]), at: { file: f, line: lineAt(t, m.index!) }, prio: 0 });
|
||||
const nd = /^\s*ndk(?:-?version)?\s*=\s*"(\d+\.[\d.]+)"/im.exec(t);
|
||||
if (nd && !native.ndkVersion) native.ndkVersion = { value: nd[1]!, at: { file: f, line: lineAt(t, nd.index) } };
|
||||
} else if (n === 'AndroidManifest.xml' && /(^|\/)src\/main\/AndroidManifest\.xml$|^AndroidManifest\.xml$|Plugins\/Android\/AndroidManifest\.xml$/.test(f) && !testy) {
|
||||
android.manifests.push(f);
|
||||
readManifest(f, read(f), android);
|
||||
} else if (/\/res\/xml\/[^/]+\.xml$/.test(f) && read(f).includes('<accessibility-service')) {
|
||||
const t = read(f);
|
||||
const m = /<accessibility-service\b[^>]*/.exec(t)!;
|
||||
android.accessibilityConfigs.push({ at: { file: f, line: lineAt(t, m.index) }, isTool: /android:isAccessibilityTool="true"/.test(m[0]) });
|
||||
} else if (n === 'strings.xml' && /(^|\/)res\/values[^/]*\/strings\.xml$/.test(f) && !testy) {
|
||||
android.strings.push({ path: f, text: read(f) });
|
||||
} else if (n === 'CMakeLists.txt' || n === 'Android.mk' || n === 'Application.mk') {
|
||||
const t = read(f);
|
||||
if (!native.nativeBuild) native.nativeBuild = { file: f, line: 1 };
|
||||
const fl = FLEXIBLE_PAGES.exec(t);
|
||||
if (fl && !native.flexiblePageSizes) native.flexiblePageSizes = { file: f, line: lineAt(t, fl.index) };
|
||||
} else if (n === 'ProjectVersion.txt' && /(^|\/)ProjectSettings\//.test(f)) {
|
||||
const t = read(f);
|
||||
const m = /^m_EditorVersion:\s*(\S+)/m.exec(t);
|
||||
if (m) native.unityVersion = { value: m[1]!, at: { file: f, line: lineAt(t, m.index) } };
|
||||
} else if (n === 'package.json' && !f.includes('/node_modules/')) {
|
||||
const t = read(f);
|
||||
const d = packageJson(f, t);
|
||||
deps.push(...d);
|
||||
const names = new Set(d.map(x => x.name));
|
||||
if (names.has('react-native')) stacks.add('react-native');
|
||||
if (names.has('expo')) stacks.add('expo');
|
||||
if ([...names].some(x => x.startsWith('@capacitor/'))) stacks.add('capacitor');
|
||||
if (names.has('cordova-android') || names.has('cordova-ios')) stacks.add('cordova');
|
||||
} else if ((n === 'app.json' || n === 'app.config.json') && !f.includes('/')) {
|
||||
const t = read(f);
|
||||
try {
|
||||
const j = JSON.parse(t) as { expo?: { ios?: { infoPlist?: Record<string, unknown>; usesAppleSignIn?: boolean }; android?: { permissions?: string[] }; plugins?: unknown[] } };
|
||||
if (j.expo) {
|
||||
stacks.add('expo');
|
||||
plistSources.push(f);
|
||||
for (const [k, v] of Object.entries(j.expo.ios?.infoPlist ?? {})) setKey(plist, k, v, { file: f, line: lineOf(t, `"${k}"`) });
|
||||
if (j.expo.ios?.usesAppleSignIn) setKey(entitlements, 'com.apple.developer.applesignin', ['Default'], { file: f, line: lineOf(t, '"usesAppleSignIn"') });
|
||||
for (const p of j.expo.android?.permissions ?? []) android.permissions.push({ name: p.includes('.') ? p : `android.permission.${p}`, at: { file: f, line: lineOf(t, `"${p}"`) } });
|
||||
for (const p of j.expo.plugins ?? []) {
|
||||
if (Array.isArray(p) && p[0] === 'expo-build-properties') {
|
||||
const ts = (p[1] as { android?: { targetSdkVersion?: number } } | undefined)?.android?.targetSdkVersion;
|
||||
if (ts) sdkHits.push({ value: ts, at: { file: f, line: lineOf(t, '"targetSdkVersion"') }, prio: 0 });
|
||||
}
|
||||
}
|
||||
if (!android.targetSdkFrom) android.targetSdkFrom = 'the Expo SDK version (expo-build-properties android.targetSdkVersion overrides it)';
|
||||
}
|
||||
} catch { /* not JSON */ }
|
||||
} else if (/^capacitor\.config\.(json|ts|js)$/.test(n)) {
|
||||
stacks.add('capacitor');
|
||||
const t = read(f);
|
||||
const m = /server\s*["']?\s*:\s*\{[\s\S]*?\burl["']?\s*:\s*["'](https?:\/\/[^"']+)["']/.exec(t);
|
||||
if (m && !/^https?:\/\/(localhost|127\.0\.0\.1|10\.0\.2\.2|192\.168\.)/.test(m[1]!)) remoteStart = { url: m[1]!, at: { file: f, line: lineAt(t, m.index! + m[0].indexOf(m[1]!)) } };
|
||||
} else if (n === 'config.xml' && /<widget\b/.test(read(f))) {
|
||||
stacks.add('cordova');
|
||||
const t = read(f);
|
||||
deps.push(...cordovaXml(f, t));
|
||||
const m = /<content\s+src="(https?:\/\/[^"]+)"/.exec(t);
|
||||
if (m && !/localhost|127\.0\.0\.1/.test(m[1]!)) remoteStart = { url: m[1]!, at: { file: f, line: lineAt(t, m.index!) } };
|
||||
} else if (n === 'pubspec.yaml') { stacks.add('flutter'); deps.push(...pubspec(f, read(f))); }
|
||||
else if (n === 'pubspec.lock') pubLock = pubspecLock(read(f));
|
||||
else if (f === 'Packages/manifest.json' || f.endsWith('/Packages/manifest.json')) { stacks.add('unity'); deps.push(...unityManifest(f, read(f))); }
|
||||
else if (/Dependencies\.xml$/.test(n) && /\/Editor\//.test(f)) deps.push(...edmXml(f, read(f)));
|
||||
else if (n === 'ProjectSettings.asset') {
|
||||
stacks.add('unity');
|
||||
const t = read(f);
|
||||
let any = false;
|
||||
for (const [uk, pk] of Object.entries(UNITY_KEYS)) {
|
||||
const m = new RegExp(`^\\s*${uk}:[ \\t]*(.*)$`, 'm').exec(t);
|
||||
if (m) { any = true; setKey(plist, pk, m[1]!.trim().replace(/^'|'$/g, ''), { file: f, line: lineAt(t, m.index) }); }
|
||||
}
|
||||
if (any) plistSources.push(f);
|
||||
const ts = /^\s*AndroidTargetSdkVersion:\s*(\d+)/m.exec(t);
|
||||
if (ts && Number(ts[1]) > 0) sdkHits.push({ value: Number(ts[1]), at: { file: f, line: lineAt(t, ts.index) }, prio: 0 });
|
||||
else if (ts) android.targetSdkFrom = 'Unity "Automatic (highest installed)": the Android SDK the build machine has';
|
||||
} else if (n === 'export_presets.cfg') {
|
||||
stacks.add('godot');
|
||||
const t = read(f);
|
||||
let any = false;
|
||||
for (const [gk, pk] of Object.entries(GODOT_KEYS)) {
|
||||
const m = new RegExp(`^${gk.replace('/', '\\/')}="(.*)"`, 'm').exec(t);
|
||||
if (m) { any = true; setKey(plist, pk, m[1]!, { file: f, line: lineAt(t, m.index) }); }
|
||||
}
|
||||
if (any) plistSources.push(f);
|
||||
const ts = /^gradle_build\/target_sdk="(\d+)"/m.exec(t);
|
||||
if (ts) sdkHits.push({ value: Number(ts[1]), at: { file: f, line: lineAt(t, ts.index) }, prio: 0 });
|
||||
for (const m of t.matchAll(/^permissions\/([a-z_]+)=true/gm)) android.permissions.push({ name: `android.permission.${m[1]!.toUpperCase()}`, at: { file: f, line: lineAt(t, m.index!) } });
|
||||
}
|
||||
// app sources
|
||||
if (SRC_EXT.has(extname(n)) && !testy && !/\.min\.js$|\.d\.ts$|(^|\/)(Plugins|ThirdParty|third_party|Packages|addons)\//.test(f) && !/\.config\.(ts|js)$/.test(n)) {
|
||||
const t = read(f);
|
||||
if (t && !t.includes('\u0000')) sources.push({ path: f, text: t });
|
||||
}
|
||||
}
|
||||
// Unity / Godot plugin folders count as dependencies (a folder under Assets/ or addons/)
|
||||
for (const d of new Set(files.map(f => /^Assets\/([^/]+)\//.exec(f)?.[1]).filter((x): x is string => !!x)))
|
||||
deps.push({ eco: 'unity', name: d, version: null, file: `Assets/${d}/`, line: 1 });
|
||||
for (const d of new Set(files.map(f => /^addons\/([^/]+)\//.exec(f)?.[1]).filter((x): x is string => !!x)))
|
||||
deps.push({ eco: 'godot', name: d, version: null, file: `addons/${d}/`, line: 1 });
|
||||
for (const d of deps) if (d.eco === 'pub' && pubLock.has(d.name)) d.version = pubLock.get(d.name)!;
|
||||
|
||||
if (has(/\.xcodeproj\/project\.pbxproj$/) && !stacks.has('flutter') && !stacks.has('react-native') && !stacks.has('capacitor') && !stacks.has('cordova') && !stacks.has('unity')) stacks.add('ios-native');
|
||||
if (android.manifests.length && !stacks.has('flutter') && !stacks.has('react-native') && !stacks.has('capacitor') && !stacks.has('cordova') && !stacks.has('unity') && !stacks.has('godot')) stacks.add('android-native');
|
||||
if (!stacks.size && has(/(^|\/)index\.html$/)) stacks.add('web');
|
||||
const ios = has(/\.xcodeproj\/project\.pbxproj$/) || plistSources.length > 0 || stacks.has('expo') || stacks.has('unity') || (stacks.has('godot') && /platform="iOS"/.test(read(files.find(f => basename(f) === 'export_presets.cfg') ?? '')));
|
||||
const isAndroid = android.manifests.length > 0 || has(/(^|\/)build\.gradle(\.kts)?$/) || stacks.has('expo') || stacks.has('unity') || (stacks.has('godot') && /platform="Android"/.test(read(files.find(f => basename(f) === 'export_presets.cfg') ?? '')));
|
||||
if (sdkHits.length) {
|
||||
sdkHits.sort((a, b) => a.prio - b.prio || a.value - b.value);
|
||||
android.targetSdk = { value: sdkHits[0]!.value, at: sdkHits[0]!.at };
|
||||
}
|
||||
|
||||
const sdks: DetectedSdk[] = [];
|
||||
for (const s of SDKS) {
|
||||
const hits = deps.filter(d => matchesSdk(d, s));
|
||||
if (hits.length) sdks.push({ sdk: s, deps: hits });
|
||||
}
|
||||
// the Android Gradle Plugin: buildscript classpath, plugins { id(...) version }, or the version catalog
|
||||
const agp = deps.find(d => (d.name === 'com.android.tools.build:gradle' || d.name === 'com.android.application') && d.version && /^\d/.test(d.version));
|
||||
if (agp) native.agp = { value: agp.version!, at: { file: agp.file, line: agp.line } };
|
||||
// the merged manifest of a local build, when there is one (libraries add permissions there: AD_ID, location, ...)
|
||||
if (isAndroid) {
|
||||
const merged = findMergedManifest(root, android.manifests, stacks.has('flutter'));
|
||||
let t = '';
|
||||
if (merged) { try { t = readFileSync(join(root, merged), 'utf8'); } catch { /* unreadable */ } }
|
||||
if (merged && t) {
|
||||
android.mergedManifest = merged;
|
||||
const extra: ProjectFacts['androidInfo'] = { ...android, permissions: [], services: [], components: [], removedPermissions: [], extractNativeLibs: null };
|
||||
readManifest(merged, t, extra);
|
||||
const removed = new Set(android.removedPermissions.map(x => x.name));
|
||||
const have = new Set(android.permissions.map(x => x.name));
|
||||
for (const x of extra.permissions) if (!have.has(x.name) && !removed.has(x.name)) { android.permissions.push(x); have.add(x.name); }
|
||||
const key = (k: string, n: string) => `${k}:${n.split('.').pop()}`;
|
||||
const comps = new Set(android.components.map(x => key(x.kind, x.name)));
|
||||
for (const x of extra.components) if (!comps.has(key(x.kind, x.name))) android.components.push(x);
|
||||
const svc = new Set(android.services.map(x => key('service', x.name)));
|
||||
for (const x of extra.services) if (!svc.has(key('service', x.name))) android.services.push(x);
|
||||
}
|
||||
}
|
||||
return { root, stacks: [...stacks], ios, android: isAndroid, deps, sdks, plist, plistSources, entitlements, privacyManifests, androidInfo: android, native, remoteStart, sources, scanned: files.length };
|
||||
}
|
||||
|
||||
/** NDK r27 flag and the linker flag of older NDKs that make native libraries 16 KB aligned. */
|
||||
const FLEXIBLE_PAGES = /ANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES\s*=?\s*ON|max-page-size=16384/;
|
||||
|
||||
/** Permissions, components and <application> settings of one AndroidManifest.xml, added to `a`. */
|
||||
function readManifest(f: string, t: string, a: ProjectFacts['androidInfo']): void {
|
||||
for (const m of t.matchAll(/<uses-permission(?:-sdk-23)?\b([^>]*?)\/?>/g)) {
|
||||
const name = /android:name="([^"]+)"/.exec(m[1]!)?.[1];
|
||||
if (!name) continue;
|
||||
const at = { file: f, line: lineAt(t, m.index!) };
|
||||
if (/tools:node="remove"/.test(m[1]!)) a.removedPermissions.push({ name, at });
|
||||
else a.permissions.push({ name, at });
|
||||
}
|
||||
for (const kind of ['activity', 'activity-alias', 'service', 'receiver'] as const) {
|
||||
for (const m of t.matchAll(new RegExp(`<${kind}\\b([^>]*?)(/>|>([\\s\\S]*?)</${kind}>)`, 'g'))) {
|
||||
const attrs = m[1]!, body = m[3] ?? '';
|
||||
if (/tools:node="remove"/.test(attrs)) continue;
|
||||
const c: AndroidComponent = {
|
||||
kind: kind === 'activity-alias' ? 'activity' : kind,
|
||||
name: /android:name="([^"]+)"/.exec(attrs)?.[1] ?? '?',
|
||||
permission: /android:permission="([^"]+)"/.exec(attrs)?.[1] ?? null,
|
||||
fgsType: /android:foregroundServiceType="([^"]+)"/.exec(attrs)?.[1] ?? null,
|
||||
actions: [...body.matchAll(/<action\s+android:name="([^"]+)"/g)].map(x => x[1]!),
|
||||
categories: [...body.matchAll(/<category\s+android:name="([^"]+)"/g)].map(x => x[1]!),
|
||||
meta: [...body.matchAll(/<meta-data\s+android:name="([^"]+)"/g)].map(x => x[1]!),
|
||||
at: { file: f, line: lineAt(t, m.index!) },
|
||||
};
|
||||
a.components.push(c);
|
||||
if (c.kind === 'service') a.services.push({ name: c.name, fgsType: c.fgsType, at: c.at });
|
||||
}
|
||||
}
|
||||
const app = /<application\b[^>]*/.exec(t);
|
||||
const ex = app ? /android:extractNativeLibs="(true|false)"/.exec(app[0]) : null;
|
||||
if (app && ex && !a.extractNativeLibs) a.extractNativeLibs = { value: ex[1] === 'true', at: { file: f, line: lineAt(t, app.index + ex.index) } };
|
||||
if (/android\.hardware\.type\.watch/.test(t)) a.formFactor = 'wear';
|
||||
else if (/android\.software\.leanback"[^>]*android:required="true"|android:required="true"[^>]*android\.software\.leanback/.test(t)) a.formFactor = 'tv';
|
||||
else if (/android\.hardware\.type\.automotive/.test(t)) a.formFactor = 'automotive';
|
||||
}
|
||||
|
||||
/** NDK version, AGP plugin version, native build and packaging settings in one Gradle file. */
|
||||
function gradleNative(f: string, t: string, n: ProjectFacts['native'], deps: DepRef[]): void {
|
||||
const nd = /\bndkVersion\s*=?\s*\(?\s*["'](\d+\.[\d.]+)["']/.exec(t);
|
||||
if (nd && !n.ndkVersion) n.ndkVersion = { value: nd[1]!, at: { file: f, line: lineAt(t, nd.index) } };
|
||||
if (/\bndkVersion\s*=?\s*flutter\.ndkVersion/.test(t)) n.ndkFrom = 'the Flutter SDK (flutter.ndkVersion)';
|
||||
const ext = /\bexternalNativeBuild\s*\{/.exec(t);
|
||||
if (ext && !n.nativeBuild) n.nativeBuild = { file: f, line: lineAt(t, ext.index) };
|
||||
const fl = FLEXIBLE_PAGES.exec(t);
|
||||
if (fl && !n.flexiblePageSizes) n.flexiblePageSizes = { file: f, line: lineAt(t, fl.index) };
|
||||
const lp = /\buseLegacyPackaging\s*(?:=\s*)?true\b/.exec(t);
|
||||
if (lp && !n.legacyPackaging) n.legacyPackaging = { file: f, line: lineAt(t, lp.index) };
|
||||
for (const m of t.matchAll(/\bid\s*\(?\s*["']com\.android\.(?:application|library)["']\s*\)?\s*version\s*["']([^"']+)["']/g))
|
||||
deps.push({ eco: 'gradle', name: 'com.android.application', version: m[1]!, file: f, line: lineAt(t, m.index!) });
|
||||
}
|
||||
|
||||
/** A merged AndroidManifest.xml of a local build under <module>/build/intermediates (release first), relative to
|
||||
* root; Flutter builds into build/app/ at the project root. null when the project was not built here. */
|
||||
function findMergedManifest(root: string, manifests: string[], flutter: boolean): string | null {
|
||||
const modules = new Set(manifests.filter(m => m.endsWith('src/main/AndroidManifest.xml')).map(m => `${m.slice(0, -'src/main/AndroidManifest.xml'.length)}build/`));
|
||||
if (flutter) modules.add('build/app/');
|
||||
const found: string[] = [];
|
||||
const walk = (dir: string, depth: number) => {
|
||||
if (depth > 4) return;
|
||||
let names: string[];
|
||||
try { names = readdirSync(join(root, dir)); } catch { return; }
|
||||
for (const n of names.sort()) {
|
||||
if (n === 'AndroidManifest.xml') found.push(`${dir}/${n}`);
|
||||
else if (!n.includes('.')) walk(`${dir}/${n}`, depth + 1);
|
||||
}
|
||||
};
|
||||
for (const m of modules) for (const sub of ['merged_manifest', 'merged_manifests', 'packaged_manifests']) walk(`${m}intermediates/${sub}`, 0);
|
||||
return found.find(f => /release/i.test(f)) ?? found[0] ?? null;
|
||||
}
|
||||
|
||||
const COMMENT = /^\s*(\/\/|#|\*|\/\*|<!--)/;
|
||||
|
||||
/** Source lines matching `re` (comments skipped), at most `max`. */
|
||||
export function grep(sources: { path: string; text: string }[], re: RegExp, max = 5, filter?: (path: string) => boolean): Hit[] {
|
||||
const out: Hit[] = [];
|
||||
for (const s of sources) {
|
||||
if (filter && !filter(s.path)) continue;
|
||||
if (!re.test(s.text)) continue;
|
||||
const lines = s.text.split('\n');
|
||||
for (let i = 0; i < lines.length && out.length < max; i++) {
|
||||
const l = lines[i]!;
|
||||
if (re.test(l) && !COMMENT.test(l)) out.push({ file: s.path, line: i + 1, text: l.trim().slice(0, 160) });
|
||||
}
|
||||
if (out.length >= max) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** "file:line" of a location. */
|
||||
export const where = (l: Loc): string => `${l.file}:${l.line}`;
|
||||
|
||||
/** Ecosystems in a readable order for the report. */
|
||||
export const ECO_LABEL: Record<Eco, string> = { cocoapods: 'CocoaPods', spm: 'SwiftPM', carthage: 'Carthage', gradle: 'Gradle', npm: 'npm', pub: 'pub', unity: 'Unity', godot: 'Godot' };
|
||||
511
cli/lib/scan/rules.ts
Normal file
511
cli/lib/scan/rules.ts
Normal file
|
|
@ -0,0 +1,511 @@
|
|||
// App Review and Google Play rejection-risk rules for `storebound scan`. Pure: they read the detected project facts,
|
||||
// the config (optional) and the listing files, and return findings with the guideline, the evidence (file:line), the
|
||||
// fix, a severity and the skill that covers it. Only what files or the config prove is reported; where a rule cannot
|
||||
// see enough (a sign-in flow behind a custom API, a restore button under another name) its fix says what to check.
|
||||
//
|
||||
// Sources, checked 2026-10-11:
|
||||
// - Apple App Review Guidelines: https://developer.apple.com/app-store/review/guidelines/
|
||||
// 2.1(a) app completeness (demo account, placeholder text), 2.3.7 metadata (names, keywords, no prices or other
|
||||
// apps' names), 2.3.8 ("For Kids" is reserved for the Kids Category), 2.3.10 other mobile platforms, 2.5.1 public
|
||||
// APIs, 2.5.5 IPv6-only networks, 3.1.1 restore mechanism, 3.1.2(c) subscription information (+ Schedule 2 of the
|
||||
// Developer Program License Agreement: Terms of Use and privacy policy links), 4.2 minimum functionality
|
||||
// (repackaged websites), 4.8 Login Services (an equivalent login option), 5.1.1(ii) purpose strings, 5.1.1(v)
|
||||
// account deletion in the app, 5.1.2(i) App Tracking Transparency, 1.3 Kids Category (no third-party ads/analytics),
|
||||
// 5.1.1(i) privacy policy link inside the app, 5.1.1(iv) only the access a feature needs, 5.1.2 privacy labels that
|
||||
// match the SDKs, 3.1.1 calls to action for purchases outside in-app purchase (3.1.3(e): physical goods are fine),
|
||||
// 3.1.2 subscription management, 2.5.1 private settings URL schemes, 5.6.1 system review prompt only, 3.2.2(x) and
|
||||
// 5.6.3 no rewards for ratings.
|
||||
// - The list of common rejections the rules cover was cross-checked with community collections (paraphrased, each item
|
||||
// verified against Apple's guidelines above): github.com/rshankras/claude-code-apple-skills (app-store /
|
||||
// rejection-handler / common-rejections.md), github.com/rorkai/app-store-connect-cli-skills (asc-submission-health)
|
||||
// and ascskill.wiki. Items that only show at review time (crashes, dead links, misleading screenshots, poor UI, 4.3
|
||||
// spam, 5.2 local law) are not file-detectable: the review-rejections skill lists them as "checked at review".
|
||||
// - Apple, upload checks: ITMS-90683 missing purpose string, ITMS-90809 UIWebView, ITMS-91053 / 91061 privacy
|
||||
// manifest (developer.apple.com/documentation/bundleresources/privacy-manifest-files), App Transport Security
|
||||
// (developer.apple.com/documentation/security/preventing-insecure-network-connections), export compliance
|
||||
// (developer.apple.com/documentation/security/complying-with-encryption-export-regulations).
|
||||
// - Google Play: target API level (developer.android.com/google/play/requirements/target-sdk: from 2026-08-31 new apps
|
||||
// and updates target API 36, Wear OS / Android Automotive 35, Android TV / XR 34; extension to 2026-11-01 on request),
|
||||
// account deletion (support.google.com/googleplay/android-developer/answer/13327111), foreground service types
|
||||
// (answer/13392821), Permissions and APIs that Access Sensitive Information (answer/9888170: exact alarm,
|
||||
// QUERY_ALL_PACKAGES, SMS and Call Log), App access for reviewers (answer/9859455), Families policy (answer/9893335),
|
||||
// Metadata (answer/9898842), Data safety (answer/10787469). The reserved com.example package name is an upload
|
||||
// error of Play Console (no policy page; developer.android.com/build/configure-app-module on choosing the id).
|
||||
// The other Google Play rules (sensitive permissions, prominent disclosure, Families, advertising ID, 16 KB pages,
|
||||
// testing for personal accounts, Play metadata, ads, payments, impersonation) are in play-rules.ts with their sources.
|
||||
import type { ShipConfig } from '../config';
|
||||
import { allSubscriptions } from '../subscriptions';
|
||||
import { LISTED_SDKS, REQUIRED_REASON_APIS } from '../privacy-manifest';
|
||||
import { IOS_PERMISSIONS, vaguePurpose } from './permissions';
|
||||
import { playRules } from './play-rules';
|
||||
import { grep, type Hit, lineOf, type ProjectFacts } from './project';
|
||||
import { versionAtLeast } from './sdks';
|
||||
|
||||
export type Severity = 'blocker' | 'high' | 'medium' | 'low';
|
||||
export type ScanStore = 'apple' | 'play';
|
||||
|
||||
export interface ScanFinding {
|
||||
/** Stable rule id (config `scan.ignore` uses it). */
|
||||
rule: string;
|
||||
/** Guideline or policy, e.g. "5.1.1(v)" or "Play: Target API level". */
|
||||
guideline: string;
|
||||
store: ScanStore;
|
||||
severity: Severity;
|
||||
title: string;
|
||||
evidence: Hit[];
|
||||
fix: string;
|
||||
skill: string;
|
||||
/** Policy page. */
|
||||
ref: string;
|
||||
/** Owner accepted it (`scan.ignore` in the config) with this reason. */
|
||||
accepted?: string;
|
||||
}
|
||||
|
||||
export interface ScanInput {
|
||||
facts: ProjectFacts;
|
||||
config: ShipConfig | null;
|
||||
/** The config file as text (relative path), for line numbers. */
|
||||
configFile: { path: string; text: string } | null;
|
||||
/** iOS metadata / Play listing / screenshot captions as text (relative paths). */
|
||||
listings: { apple?: { path: string; text: string }; play?: { path: string; text: string }; captions?: { path: string; text: string } };
|
||||
/** A demo account for App Review is stored locally (.storebound/credentials.json or REVIEW_DEMO_*). */
|
||||
demoAccount: boolean;
|
||||
/** Data types the detected SDKs collect that the config's dataSafety does not declare (from the declarations
|
||||
* proposal): privacy label mismatch. */
|
||||
labelGaps?: { type: string; apple: string; evidence: Hit[] }[];
|
||||
/** Data types the config's dataSafety declares, but with fewer purposes or less sharing than detected (Play). */
|
||||
dataMerges?: { type: string; missing: string; evidence: Hit[] }[];
|
||||
}
|
||||
|
||||
export const APPLE_GUIDELINES = 'https://developer.apple.com/app-store/review/guidelines/';
|
||||
const PLAY = 'https://support.google.com/googleplay/android-developer/answer/';
|
||||
export const PLAY_POLICY = 'https://play.google/developer-content-policy/';
|
||||
export const PLAY_TARGET_SDK = { phone: 36, wear: 35, automotive: 35, tv: 34 } as const;
|
||||
export const PLAY_TARGET_SDK_SINCE = '2026-08-31';
|
||||
|
||||
// ---- code signals ----
|
||||
export const SIGNALS = {
|
||||
appleSignIn: /ASAuthorizationAppleIDProvider|SignInWithAppleButton|AppleAuthenticationButton|AppleAuthentication\.signInAsync|appleAuth\.performRequest|SignInWithApple|OAuthProvider\(\s*['"]apple\.com|AppleAuthProvider|signInWithApple|AppleAuthManager/,
|
||||
thirdPartyLogin: /GIDSignIn|GoogleSignin\.signIn|GoogleSignIn\(|GoogleAuthProvider|signInWithGoogle|FacebookAuthProvider|LoginManager\(\)\.logIn|LoginManager\.logInWithPermissions|signInWithFacebook|FacebookLogin|TwitterAuthProvider|GithubAuthProvider|OAuthProvider\(\s*['"](microsoft\.com|yahoo\.com|twitter\.com|github\.com)/,
|
||||
signIn: /signInWithEmailAndPassword|signInWithPassword|signInWithCredential|createUserWithEmailAndPassword|\bsupabase\.auth\.sign|Amplify\.Auth\.signIn|\bAuth0\b|\bloginWithPassword\b|\.signIn\(\s*\{|\/(api\/)?(auth\/)?(login|signin|sign-in)\b['"`]/,
|
||||
signUp: /createUserWithEmailAndPassword|\bsignUp\s*\(|\bsupabase\.auth\.signUp|Amplify\.Auth\.signUp|\/(api\/)?(auth\/)?(register|signup|sign-up)\b['"`]|["'>](Create (an )?account|Sign up)["'<]/,
|
||||
deleteAccount: /deleteUser\b|\buser\.delete\(|currentUser\??\.delete\(|\bdeleteAccount\b|delete_account|DeleteAccount|delete-account|["'>]Delete (my |your )?account|\brevokeToken\b|auth\.admin\.deleteUser|Hesab(ı|ımı) sil/i,
|
||||
restore: /restoreCompletedTransactions|AppStore\.sync\(|restorePurchases|restoreTransactions|RestoreTransactions|getAvailablePurchases|\brestorePurchase\b|\.restore\(\)|Restore Purchases|syncPurchases|Purchases\.shared\.restore|store\.restore\b|queryPurchasesAsync/i,
|
||||
subscriptionCode: /subscriptionPeriod|Product\.SubscriptionInfo|\.autoRenewable\b|entitlements\.active|SubscriptionStoreView|ProductType\.Subscription|ProductType\.SUBS|BillingClient\.ProductType\.SUBS/,
|
||||
attRequest: /requestTrackingAuthorization|requestTrackingPermissionsAsync|requestTrackingPermission\b|AppTrackingTransparency\.requestTrackingAuthorization|ATTrackingStatusBinding\.RequestAuthorizationTracking|TrackingTransparency\.requestPermission/,
|
||||
idfa: /\bASIdentifierManager\b|advertisingIdentifier\b/,
|
||||
uiWebView: /\bUIWebView\b/,
|
||||
wkRemote: /\.load\(\s*URLRequest\(\s*url:\s*URL\(\s*string:\s*"https?:\/\/(?!localhost|127\.0\.0\.1)/,
|
||||
ipv4: /["'`]https?:\/\/(?!127\.0\.0\.1|0\.0\.0\.0|10\.0\.2\.2)(\d{1,3}\.){3}\d{1,3}(?=[:/"'`])/,
|
||||
inAppLegal: /terms|eula|privacy|nutzungsbedingungen|kullanım koşulları|gizlilik/i,
|
||||
privacyLink: /privacy|gizlilik|datenschutz|confidentialit|privacidad/i,
|
||||
manageSubs: /showManageSubscriptions|manageSubscriptionsSheet|apps\.apple\.com\/account\/subscriptions|managementURL|showManageSubscriptions|manageSubscriptions\b/,
|
||||
privateScheme: /["'`](App-Prefs|prefs):root\b/,
|
||||
ratePrompt: /["'`>](Rate (us|this app)|Enjoying [A-Z][\w ]{0,30}\?|Love (this|the) app\?)/,
|
||||
reviewApi: /SKStoreReviewController|requestReview|StoreReview\.requestReview|InAppReview|in_app_review|react-native-rate|requestReviewFlow|ReviewManager/,
|
||||
incentiveRating: /(rate|review)\b[^"'`\n]{0,60}\b(reward|coins?|gems?|bonus|free (lives|spins|coins))|(reward|coins?|gems?|bonus)\b[^"'`\n]{0,40}\b(for|to) (rating|reviewing|rate|review)\b|5[- ]?stars?\b[^"'`\n]{0,40}\b(reward|get|earn)/i,
|
||||
externalBuy: /\b(buy|subscribe|purchase|upgrade|pay)\b[^.\n]{0,40}\b(on|at|via|from) (our )?(website|web ?site|web|site)\b/i,
|
||||
};
|
||||
|
||||
const ATT_SDKS_SHOW_PROMPT = new Set(['applovin', 'levelplay']);
|
||||
const COMPETITORS = ['instagram', 'tiktok', 'whatsapp', 'facebook', 'snapchat', 'youtube', 'netflix', 'spotify', 'telegram', 'messenger', 'twitter', 'pinterest', 'uber', 'airbnb',
|
||||
'amazon', 'chatgpt', 'openai', 'minecraft', 'roblox', 'fortnite', 'pubg', 'candy crush', 'clash of clans', 'pokemon', 'pokémon', 'among us', 'subway surfers', 'temple run',
|
||||
'angry birds', 'tetris', 'wordle', 'duolingo', 'zoom', 'gmail', 'google maps', 'waze', 'shazam', 'tinder', 'notion', 'evernote', 'photoshop', 'canva', 'capcut', 'iphone', 'ipad', 'apple'];
|
||||
const OTHER_PLATFORMS = /\b(Android|Google Play|Play Store|Galaxy Store|AppGallery|Huawei|Windows Phone|BlackBerry|Amazon Appstore)\b/;
|
||||
const PLACEHOLDER = /lorem ipsum|\bTODO\b|\bTBD\b|\bFIXME\b|\bplaceholder\b|\bXXX\b|your app (name|description) here|coming soon|First paragraph:|Short hook under the name|One or two sentences you can change|İsmin altındaki kısa kanca|Yeni sürüm göndermeden istediğin zaman|\bExample (Game|App|Pro|Studio)\b/i;
|
||||
const FGS_PERMISSION: Record<string, string> = {
|
||||
camera: 'CAMERA', connectedDevice: 'CONNECTED_DEVICE', dataSync: 'DATA_SYNC', health: 'HEALTH', location: 'LOCATION', mediaPlayback: 'MEDIA_PLAYBACK',
|
||||
mediaProjection: 'MEDIA_PROJECTION', microphone: 'MICROPHONE', phoneCall: 'PHONE_CALL', remoteMessaging: 'REMOTE_MESSAGING', specialUse: 'SPECIAL_USE',
|
||||
systemExempted: 'SYSTEM_EXEMPTED', mediaProcessing: 'MEDIA_PROCESSING',
|
||||
};
|
||||
const SMS_CALL_LOG = ['READ_SMS', 'RECEIVE_MMS', 'RECEIVE_SMS', 'RECEIVE_WAP_PUSH', 'SEND_SMS', 'WRITE_SMS', 'READ_CALL_LOG', 'WRITE_CALL_LOG', 'PROCESS_OUTGOING_CALLS'];
|
||||
|
||||
/** Text lines (inside fenced blocks of a listing file, or JSON string values) that match `re`. */
|
||||
function listingHits(file: { path: string; text: string } | undefined, re: RegExp, o: { fenced?: boolean; field?: RegExp } = {}): Hit[] {
|
||||
if (!file) return [];
|
||||
const out: Hit[] = [];
|
||||
let inFence = false, heading = '';
|
||||
file.text.split('\n').forEach((l, i) => {
|
||||
if (/^###\s/.test(l)) heading = l.slice(4).trim();
|
||||
if (/^```/.test(l)) { inFence = !inFence; return; }
|
||||
if (o.fenced !== false && !inFence) return;
|
||||
if (o.field && !o.field.test(heading)) return;
|
||||
if (re.test(l)) out.push({ file: file.path, line: i + 1, text: l.trim().slice(0, 160) });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
export function scanRules(inp: ScanInput): ScanFinding[] {
|
||||
const { facts: p, config: c } = inp;
|
||||
const out: ScanFinding[] = [];
|
||||
const add = (f: Omit<ScanFinding, 'ref'> & { ref?: string }) => out.push({ ref: f.store === 'apple' ? APPLE_GUIDELINES : PLAY_POLICY, ...f });
|
||||
const cfg = (needle: string | RegExp, text?: string): Hit[] => {
|
||||
const f = inp.configFile;
|
||||
if (!f) return [];
|
||||
const i = typeof needle === 'string' ? f.text.indexOf(needle) : f.text.search(needle);
|
||||
if (i < 0) return [];
|
||||
const line = lineOf(f.text, needle);
|
||||
return [{ file: f.path, line, text: text ?? f.text.split('\n')[line - 1]!.trim().slice(0, 160) }];
|
||||
};
|
||||
const dep = (id: string): Hit[] => p.sdks.filter(s => s.sdk.id === id).flatMap(s => s.deps.slice(0, 2).map(d => ({ file: d.file, line: d.line, text: `${d.name}${d.version ? ` ${d.version}` : ''}` })));
|
||||
const sdkHits = (pred: (s: ProjectFacts['sdks'][number]) => boolean): Hit[] => p.sdks.filter(pred).flatMap(s => s.deps.slice(0, 1).map(d => ({ file: d.file, line: d.line, text: `${s.sdk.name}: ${d.name}${d.version ? ` ${d.version}` : ''}` })));
|
||||
const src = (re: RegExp, max = 3) => grep(p.sources, re, max);
|
||||
const native = (path: string) => /\.(swift|m|mm|h)$/.test(path);
|
||||
const apple = c ? !!c.apple : p.ios;
|
||||
const play = c ? !!c.play : p.android;
|
||||
const iosProject = p.ios && p.plistSources.length > 0;
|
||||
const plistVal = (k: string) => p.plist.get(k);
|
||||
|
||||
// ---- accounts, sign-in, demo account, deletion ----
|
||||
const siwa = [...(p.entitlements.has('com.apple.developer.applesignin') ? [{ ...p.entitlements.get('com.apple.developer.applesignin')!.at, text: 'com.apple.developer.applesignin' }] : []),
|
||||
...dep('apple-signin'), ...src(SIGNALS.appleSignIn, 2)];
|
||||
const thirdParty = [...sdkHits(s => s.sdk.login === 'google' || s.sdk.login === 'facebook'), ...src(SIGNALS.thirdPartyLogin, 2)];
|
||||
const authSdk = sdkHits(s => s.sdk.category === 'auth');
|
||||
const signInCode = src(SIGNALS.signIn, 2);
|
||||
const signUpCode = src(SIGNALS.signUp, 2);
|
||||
const accountsCfg = c?.accounts?.enabled ? cfg(/accounts\s*:/) : [];
|
||||
const signIn = [...accountsCfg, ...authSdk, ...signInCode];
|
||||
const creates = [...accountsCfg, ...signUpCode, ...thirdParty, ...siwa, ...sdkHits(s => s.sdk.login === 'firebase')];
|
||||
const deletion = [...(c?.accounts?.inApp ? cfg('inApp') : []), ...src(SIGNALS.deleteAccount, 2)];
|
||||
|
||||
if (signIn.length) {
|
||||
const ra = c?.reviewAccess;
|
||||
const ev = [...cfg(/signInRequired/), ...signIn].slice(0, 4);
|
||||
if (apple) {
|
||||
if (ra?.signInRequired && !inp.demoAccount)
|
||||
add({ rule: 'demo-account', guideline: '2.1(a)', store: 'apple', severity: 'blocker', title: 'Sign-in is required but there is no demo account for App Review', evidence: ev,
|
||||
fix: 'Create a demo account that sees every feature (not a sign-up the reviewer must do), put it in .storebound/credentials.json as reviewDemoAccount (never in the repo), then `storebound apple review-details`.', skill: 'review-access' });
|
||||
else if (!ra)
|
||||
add({ rule: 'demo-account', guideline: '2.1(a)', store: 'apple', severity: 'high', title: 'The app has a sign-in, but the config does not say whether App Review needs a demo account', evidence: ev,
|
||||
fix: 'Set reviewAccess { signInRequired, instructions } in storebound.config.ts. With signInRequired: true add reviewDemoAccount to .storebound/credentials.json; reviewers reject apps they cannot get into (or offer a fully featured demo mode).', skill: 'review-access' });
|
||||
}
|
||||
if (play && ra?.signInRequired && !inp.demoAccount)
|
||||
add({ rule: 'play-app-access', guideline: 'Play: App access', store: 'play', severity: 'high', title: 'Sign-in is required but there are no reviewer credentials for Play App access', evidence: ev,
|
||||
fix: 'Play Console > App content > App access: add the demo account and instructions (keep the credentials in .storebound/credentials.json only).', skill: 'review-access', ref: `${PLAY}9859455` });
|
||||
}
|
||||
if (creates.length) {
|
||||
if (apple && !deletion.length)
|
||||
add({ rule: 'account-deletion', guideline: '5.1.1(v)', store: 'apple', severity: accountsCfg.length || signUpCode.length ? 'blocker' : 'high',
|
||||
title: 'Accounts can be created but no in-app account deletion was found', evidence: creates.slice(0, 4),
|
||||
fix: 'Add "Delete account" in the app (it deletes the account and its data, not only signs out; with Sign in with Apple also revoke the token), then set accounts.inApp to where it starts, e.g. "Settings > Account > Delete account".', skill: 'account-deletion' });
|
||||
if (play && !c?.accounts?.deletionUrl)
|
||||
add({ rule: 'play-deletion-url', guideline: 'Play: Account deletion', store: 'play', severity: c?.accounts?.enabled || signUpCode.length ? 'blocker' : 'high',
|
||||
title: 'Accounts can be created but there is no web page to request account deletion (Data safety asks for it)', evidence: creates.slice(0, 4),
|
||||
fix: 'Publish a page where people request account and data deletion without the app, set accounts.deletionUrl (and dataSafety.deletionRequest: true); Play also wants the in-app path.', skill: 'account-deletion', ref: `${PLAY}13327111` });
|
||||
}
|
||||
if (apple && thirdParty.length && !siwa.length)
|
||||
add({ rule: 'login-services', guideline: '4.8', store: 'apple', severity: 'high', title: 'Third-party login (Google / Facebook / ...) without Sign in with Apple or another equivalent login option', evidence: thirdParty.slice(0, 4),
|
||||
fix: 'Offer Sign in with Apple (Signing & Capabilities > Sign in with Apple, ASAuthorizationAppleIDProvider) or another login that limits data to name and email, lets people hide their email and does not track. Not needed when the app only uses your own account system, or for the exemptions in 4.8 (education / enterprise accounts, government ID, a client for that one service).', skill: 'review-rejections' });
|
||||
|
||||
// ---- purchases ----
|
||||
const subs = c ? allSubscriptions(c.subscriptions) : [];
|
||||
const restorable = [...(c?.products ?? []).filter(x => x.type !== 'consumable').map(x => ({ ...cfg(`'${x.id}'`)[0] ?? cfg(`"${x.id}"`)[0] ?? { file: inp.configFile?.path ?? 'storebound.config.ts', line: 1, text: '' }, text: `${x.id} (${x.type})` })),
|
||||
...subs.slice(0, 2).map(x => ({ ...(cfg(`'${x.sub.id}'`)[0] ?? cfg(`"${x.sub.id}"`)[0] ?? { file: inp.configFile?.path ?? 'storebound.config.ts', line: 1, text: '' }), text: `${x.sub.id} (subscription)` }))];
|
||||
const subCode = src(SIGNALS.subscriptionCode, 2);
|
||||
const paySdk = sdkHits(s => s.sdk.category === 'payments');
|
||||
if (!c && subCode.length && paySdk.length) restorable.push(...subCode);
|
||||
if (apple && restorable.length && !src(SIGNALS.restore, 1).length)
|
||||
add({ rule: 'restore-purchases', guideline: '3.1.1', store: 'apple', severity: 'high', title: 'Restorable purchases (non-consumables or subscriptions) but no Restore Purchases path was found', evidence: [...restorable.slice(0, 3), ...paySdk.slice(0, 1)],
|
||||
fix: 'Add a visible "Restore Purchases" button (StoreKit 2: AppStore.sync(); StoreKit 1: restoreCompletedTransactions; RevenueCat: restorePurchases) on the store / paywall screen or in Settings.', skill: 'store-iap-setup' });
|
||||
const hasSubs = subs.length > 0 || (!c && subCode.length > 0);
|
||||
if (apple && hasSubs) {
|
||||
const ev = subs.length ? cfg(/subscriptions\s*:/) : subCode;
|
||||
if (c && !c.app.termsUrl)
|
||||
add({ rule: 'subscription-info', guideline: '3.1.2(c)', store: 'apple', severity: 'blocker', title: 'Subscriptions without a Terms of Use (EULA) link', evidence: ev,
|
||||
fix: 'Set app.termsUrl (Apple\'s standard EULA URL is fine) and link it in the app\'s purchase screen and in the App Store description (or a custom EULA in App Information).', skill: 'store-subscriptions' });
|
||||
const desc = listingHits(inp.listings.apple, /./, { field: /^description$/ });
|
||||
if (inp.listings.apple && desc.length) {
|
||||
const all = desc.map(d => d.text).join('\n');
|
||||
const termsUrl = c?.app.termsUrl;
|
||||
if (!(termsUrl && all.includes(termsUrl)) && !/terms of use|terms of service|\beula\b|license agreement/i.test(all))
|
||||
add({ rule: 'subscription-info', guideline: '3.1.2(c)', store: 'apple', severity: 'high', title: 'App Store description has no Terms of Use (EULA) link', evidence: desc.slice(0, 1),
|
||||
fix: 'Add a line "Terms of Use: <app.termsUrl>" (and the privacy policy) to the description of every locale, or set a custom EULA in App Store Connect > App Information.', skill: 'store-subscriptions' });
|
||||
if (!/renew|cancel/i.test(all))
|
||||
add({ rule: 'subscription-info', guideline: '3.1.2(c)', store: 'apple', severity: 'medium', title: 'App Store description does not say the subscription renews automatically or how to cancel', evidence: desc.slice(0, 1),
|
||||
fix: 'Describe what the subscription includes, the length and price per period, that it renews automatically unless cancelled at least 24 hours before the end of the period, and where to manage it.', skill: 'store-subscriptions' });
|
||||
}
|
||||
const legal = src(SIGNALS.inAppLegal, 1);
|
||||
if (p.sources.length && !legal.length && !(c?.app.termsUrl && src(new RegExp(c.app.termsUrl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')), 1).length))
|
||||
add({ rule: 'subscription-info', guideline: '3.1.2(c)', store: 'apple', severity: 'medium', title: 'No Terms of Use / privacy policy link found in the app\'s sources', evidence: ev.slice(0, 2),
|
||||
fix: 'Show functional links to the Terms of Use and the privacy policy on the purchase screen, next to the price and period.', skill: 'store-subscriptions' });
|
||||
}
|
||||
|
||||
// ---- App Tracking Transparency ----
|
||||
if (apple && p.ios) {
|
||||
const trackers = p.sdks.filter(s => s.sdk.tracking);
|
||||
const trackEv = sdkHits(s => s.sdk.tracking);
|
||||
const idfa = grep(p.sources, SIGNALS.idfa, 2, native);
|
||||
const request = [...src(SIGNALS.attRequest, 2), ...p.deps.filter(d => ['expo-tracking-transparency', 'react-native-tracking-transparency', 'app_tracking_transparency', '@capacitor-community/app-tracking-transparency', 'com.unity.ads.ios-support'].includes(d.name)).map(d => ({ file: d.file, line: d.line, text: d.name }))];
|
||||
const str = plistVal('NSUserTrackingUsageDescription');
|
||||
const manifestTracking = p.privacyManifests.find(m => m.tracking);
|
||||
const cfgTracking = c?.appPrivacy?.tracking === true;
|
||||
const sdkPrompts = trackers.some(s => ATT_SDKS_SHOW_PROMPT.has(s.sdk.id));
|
||||
if (request.length && !str && iosProject)
|
||||
add({ rule: 'att', guideline: '5.1.2(i)', store: 'apple', severity: 'blocker', title: 'The app asks for tracking permission but Info.plist has no NSUserTrackingUsageDescription (crash on the prompt)', evidence: request.slice(0, 2),
|
||||
fix: 'Add NSUserTrackingUsageDescription with a specific reason, e.g. "Your data is used to show ads that fit your interests."', skill: 'review-rejections' });
|
||||
else if (str && !request.length && !sdkPrompts && p.sources.length)
|
||||
add({ rule: 'att', guideline: '5.1.2(i)', store: 'apple', severity: 'high', title: 'NSUserTrackingUsageDescription is set but no App Tracking Transparency request was found (reviewers cannot find the prompt)', evidence: [{ ...str.at, text: 'NSUserTrackingUsageDescription' }],
|
||||
fix: 'Call ATTrackingManager.requestTrackingAuthorization (after launch, when the app is active) before any SDK reads the IDFA, or remove the string and declare "no tracking" if no SDK tracks.', skill: 'review-rejections' });
|
||||
if ((trackers.length || idfa.length || cfgTracking || manifestTracking) && !request.length && !str && !sdkPrompts)
|
||||
add({ rule: 'att', guideline: '5.1.2(i)', store: 'apple', severity: idfa.length || cfgTracking || manifestTracking ? 'high' : 'medium',
|
||||
title: `Tracking-capable code without App Tracking Transparency (${[...trackers.map(s => s.sdk.name), ...(idfa.length ? ['IDFA'] : [])].join(', ') || 'App Privacy says tracking'})`,
|
||||
evidence: [...trackEv, ...idfa, ...(cfgTracking ? cfg(/tracking\s*:\s*true/) : []), ...(manifestTracking ? [{ file: manifestTracking.path, line: 1, text: 'NSPrivacyTracking true' }] : [])].slice(0, 4),
|
||||
fix: 'If any SDK tracks (personalized ads, attribution, IDFA): add NSUserTrackingUsageDescription and request ATT before the SDKs start, and answer App Privacy "used for tracking". If nothing tracks: configure the ad SDKs for non-personalized ads and answer "no tracking".', skill: 'ads-mediation-checks' });
|
||||
}
|
||||
|
||||
// ---- purpose strings ----
|
||||
if (apple && iosProject) {
|
||||
for (const perm of IOS_PERMISSIONS) {
|
||||
if (perm.keys.includes('NSUserTrackingUsageDescription')) continue;
|
||||
const used = [...grep(p.sources, perm.code, 2, x => native(x) || /\.(cs|gd)$/.test(x)),
|
||||
...p.deps.filter(d => (d.eco === 'npm' || d.eco === 'pub' || d.eco === 'unity') && perm.packages.includes(d.name)).map(d => ({ file: d.file, line: d.line, text: d.name }))];
|
||||
if (!used.length) continue;
|
||||
const entry = perm.keys.map(k => plistVal(k)).find(Boolean);
|
||||
if (!entry)
|
||||
add({ rule: 'purpose-strings', guideline: '5.1.1(ii)', store: 'apple', severity: 'blocker', title: `${perm.what} is used but Info.plist has no ${perm.keys[0]} (ITMS-90683, crash on first use)`, evidence: used.slice(0, 2),
|
||||
fix: `Add ${perm.keys[0]} to Info.plist (or INFOPLIST_KEY_${perm.keys[0]} in the target's build settings) with a sentence that says why the app needs the ${perm.what}, e.g. "Scan receipts to add them to your budget."`, skill: 'review-rejections' });
|
||||
else {
|
||||
const v = vaguePurpose(String(entry.value ?? ''));
|
||||
if (v) add({ rule: 'purpose-strings', guideline: '5.1.1(ii)', store: 'apple', severity: v === 'empty' ? 'blocker' : 'medium',
|
||||
title: `${entry.key} is ${v === 'empty' ? 'empty or a placeholder' : 'too vague'}: "${String(entry.value ?? '').slice(0, 60)}"`, evidence: [{ ...entry.at, text: `${entry.key}: ${String(entry.value ?? '').slice(0, 80)}` }],
|
||||
fix: `Say what the ${perm.what} is used for and how it helps the user, in one specific sentence (and localize it in InfoPlist.strings).`, skill: 'review-rejections' });
|
||||
}
|
||||
}
|
||||
// declared strings that are empty, even if the code use was not found
|
||||
for (const [k, e] of p.plist) if (/^NS[A-Za-z]+UsageDescription$/.test(k) && vaguePurpose(String(e.value ?? '')) === 'empty' && !out.some(f => f.evidence.some(x => x.file === e.at.file && x.line === e.at.line)))
|
||||
add({ rule: 'purpose-strings', guideline: '5.1.1(ii)', store: 'apple', severity: 'high', title: `${k} is empty or a placeholder`, evidence: [{ ...e.at, text: `${k}: ${String(e.value ?? '')}` }],
|
||||
fix: 'Write a specific reason, or remove the key when the app does not use that permission.', skill: 'review-rejections' });
|
||||
}
|
||||
|
||||
// ---- privacy manifest ----
|
||||
if (apple && iosProject) {
|
||||
const nativeSources = p.sources.filter(s => native(s.path));
|
||||
const declared = new Map<string, string[]>();
|
||||
for (const m of p.privacyManifests) for (const [k, v] of Object.entries(m.apis)) declared.set(k, v);
|
||||
const listed = p.deps.filter(d => (d.eco === 'cocoapods' || d.eco === 'spm') && LISTED_SDKS.some(n => d.name === n || d.name.startsWith(`${n}/`) || d.name.toLowerCase().endsWith(`/${n.toLowerCase()}`) || d.name.toLowerCase().endsWith(`/${n.toLowerCase()}.git`)));
|
||||
const apiHits: Hit[] = [];
|
||||
for (const [cat, def] of Object.entries(REQUIRED_REASON_APIS)) {
|
||||
const h = grep(nativeSources, def.symbols, 1);
|
||||
if (!h.length) continue;
|
||||
if (!declared.has(cat)) apiHits.push({ ...h[0]!, text: `${cat}: ${h[0]!.text}` });
|
||||
}
|
||||
if (!p.privacyManifests.length && (apiHits.length || listed.length || p.sdks.length))
|
||||
add({ rule: 'privacy-manifest', guideline: 'Privacy manifest (ITMS-91053)', store: 'apple', severity: apiHits.length ? 'blocker' : 'high', title: 'No PrivacyInfo.xcprivacy in the app target', evidence: [...apiHits, ...listed.map(d => ({ file: d.file, line: d.line, text: d.name }))].slice(0, 4),
|
||||
fix: 'Xcode > File > New > File > App Privacy, add it to the app target, declare each required-reason API category with its reason (`storebound privacy-manifest --ios <dir>` lists them) and the collected data types.', skill: 'privacy-manifest',
|
||||
ref: 'https://developer.apple.com/documentation/bundleresources/privacy-manifest-files' });
|
||||
else if (apiHits.length)
|
||||
add({ rule: 'privacy-manifest', guideline: 'Privacy manifest (ITMS-91053)', store: 'apple', severity: 'blocker', title: `Required-reason APIs used but not declared in PrivacyInfo.xcprivacy: ${apiHits.map(h => h.text.split(':')[0]).join(', ')}`, evidence: apiHits.slice(0, 4),
|
||||
fix: 'Add each category to NSPrivacyAccessedAPITypes with an approved reason code (for app data in UserDefaults: CA92.1).', skill: 'privacy-manifest', ref: 'https://developer.apple.com/documentation/bundleresources/privacy-manifest-files/describing-use-of-required-reason-api' });
|
||||
for (const s of p.sdks) {
|
||||
if (!s.sdk.manifestSince) continue;
|
||||
for (const d of s.deps.filter(x => (x.eco === 'cocoapods' || x.eco === 'spm') && x.version)) {
|
||||
if (versionAtLeast(d.version!, s.sdk.manifestSince) === false)
|
||||
add({ rule: 'privacy-manifest', guideline: 'Privacy manifest (ITMS-91061)', store: 'apple', severity: 'high', title: `${s.sdk.name} ${d.version} is older than ${s.sdk.manifestSince}, the first version with Apple's privacy manifest`, evidence: [{ file: d.file, line: d.line, text: `${d.name} ${d.version}` }],
|
||||
fix: `Update ${d.name} to ${s.sdk.manifestSince} or newer (the SDK is on Apple's list of commonly used SDKs that need a manifest and a signature).`, skill: 'privacy-manifest', ref: 'https://developer.apple.com/support/third-party-SDK-requirements/' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- metadata (iOS listing + screenshot captions) ----
|
||||
if (apple) {
|
||||
const other = [...listingHits(inp.listings.apple, OTHER_PLATFORMS), ...listingHits(inp.listings.captions, OTHER_PLATFORMS, { fenced: false })];
|
||||
if (other.length)
|
||||
add({ rule: 'other-platforms', guideline: '2.3.10', store: 'apple', severity: 'high', title: 'Other mobile platforms or stores named in the App Store metadata or screenshot captions', evidence: other.slice(0, 4),
|
||||
fix: 'Remove "Android", "Google Play" and other platforms or stores from the App Store text and screenshots (Play listing text is separate: store/listing.md).', skill: 'aso-basics' });
|
||||
const words = new RegExp(`(^|[\\s,|/–-])(${COMPETITORS.map(w => w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})(?=$|[\\s,|/–-])`, 'i');
|
||||
const kw = [...listingHits(inp.listings.apple, words, { field: /^(keywords|name|subtitle)$/ })];
|
||||
if (kw.length)
|
||||
add({ rule: 'metadata-keywords', guideline: '2.3.7', store: 'apple', severity: 'high', title: 'Other apps\' names or trademarks in the name, subtitle or keywords', evidence: kw.slice(0, 4),
|
||||
fix: 'Use only terms that describe your app; popular app names, trademarks and Apple product names in keywords get the metadata rejected.', skill: 'aso-basics' });
|
||||
const price = listingHits(inp.listings.apple, /\b(free|best|#1|no\.? ?1|top|cheap|sale|\d+% off|\$\d)\b/i, { field: /^(name|subtitle|keywords)$/ });
|
||||
if (price.length)
|
||||
add({ rule: 'metadata-keywords', guideline: '2.3.7', store: 'apple', severity: 'medium', title: 'Prices or claims ("free", "best", "#1") in the name, subtitle or keywords', evidence: price.slice(0, 3),
|
||||
fix: 'Keep prices and superlatives out of the name, subtitle and keywords (keywords already match "free" searches only by category).', skill: 'aso-basics' });
|
||||
const stuffed = listingHits(inp.listings.apple, /^([^,|]{1,24}[,|]){5,}/, { field: /^(name|subtitle)$/ });
|
||||
if (stuffed.length)
|
||||
add({ rule: 'metadata-keywords', guideline: '2.3.7', store: 'apple', severity: 'medium', title: 'Keyword list in the name or subtitle', evidence: stuffed.slice(0, 2), fix: 'Name and subtitle are a short phrase; keywords belong in the keywords field.', skill: 'aso-basics' });
|
||||
const kids = [...listingHits(inp.listings.apple, /\bfor (kids|children|toddlers)\b/i), ...listingHits(inp.listings.captions, /\bfor (kids|children|toddlers)\b/i, { fenced: false })];
|
||||
const kidsBand = c?.apple?.info?.ageRating?.kidsAgeBand;
|
||||
if (kids.length && !kidsBand)
|
||||
add({ rule: 'kids-terms', guideline: '2.3.8', store: 'apple', severity: 'medium', title: '"For Kids" / "For Children" in the metadata, but the app is not in the Kids Category', evidence: kids.slice(0, 2),
|
||||
fix: 'Those terms are reserved for the Kids Category: remove them, or set apple.info.ageRating.kidsAgeBand and follow 1.3.', skill: 'store-declarations' });
|
||||
}
|
||||
const placeholder = [...(apple ? listingHits(inp.listings.apple, PLACEHOLDER) : []), ...(play ? listingHits(inp.listings.play, PLACEHOLDER) : [])];
|
||||
for (const store of ['apple', 'play'] as const) {
|
||||
const ev = placeholder.filter(h => h.file === (store === 'apple' ? inp.listings.apple?.path : inp.listings.play?.path));
|
||||
if (ev.length)
|
||||
add({ rule: 'placeholder-text', guideline: store === 'apple' ? '2.1(a)' : 'Play: Metadata', store, severity: store === 'apple' ? 'high' : 'medium', title: 'Placeholder or template text in the store listing', evidence: ev.slice(0, 4),
|
||||
fix: 'Replace the template lines and any lorem ipsum / TODO with the real copy before you push the listing.', skill: 'aso-basics', ref: store === 'apple' ? APPLE_GUIDELINES : `${PLAY}9898842` });
|
||||
}
|
||||
|
||||
// ---- code and build settings ----
|
||||
if (apple && p.remoteStart)
|
||||
add({ rule: 'min-functionality', guideline: '4.2', store: 'apple', severity: 'high', title: `The app loads a remote website as its start page (${p.remoteStart.url})`, evidence: [{ ...p.remoteStart.at, text: p.remoteStart.url }],
|
||||
fix: 'Ship the web app inside the binary (remove server.url / the remote <content src>) and add native value (offline use, push, native navigation, device features); a repackaged website is rejected under 4.2.', skill: 'review-rejections' });
|
||||
else if (apple && iosProject) {
|
||||
const swift = p.sources.filter(s => native(s.path));
|
||||
const remote = grep(swift, SIGNALS.wkRemote, 1);
|
||||
if (remote.length && swift.length <= 6)
|
||||
add({ rule: 'min-functionality', guideline: '4.2', store: 'apple', severity: 'medium', title: 'A few native files that load a remote website in a WKWebView', evidence: remote,
|
||||
fix: 'An app that only shows a website is rejected under 4.2: add native features or bundle the content.', skill: 'review-rejections' });
|
||||
}
|
||||
if (apple) {
|
||||
const uiw = grep(p.sources, SIGNALS.uiWebView, 3, native);
|
||||
if (uiw.length)
|
||||
add({ rule: 'deprecated-api', guideline: '2.5.1 (ITMS-90809)', store: 'apple', severity: 'blocker', title: 'UIWebView is used (deprecated; App Store Connect rejects builds that reference it)', evidence: uiw,
|
||||
fix: 'Replace UIWebView with WKWebView and update any SDK that still links it.', skill: 'review-rejections' });
|
||||
}
|
||||
if (apple && iosProject) {
|
||||
const ats = plistVal('NSAppTransportSecurity');
|
||||
const v = ats?.value as Record<string, unknown> | undefined;
|
||||
if (v && v.NSAllowsArbitraryLoads === true)
|
||||
add({ rule: 'ats', guideline: 'App Transport Security', store: 'apple', severity: 'medium', title: 'NSAllowsArbitraryLoads turns App Transport Security off for every connection', evidence: [{ ...ats!.at, text: 'NSAppTransportSecurity > NSAllowsArbitraryLoads = true' }],
|
||||
fix: 'Use HTTPS, or limit the exception to the domains that need it (NSExceptionDomains); App Review asks for a justification of a global exception.', skill: 'review-rejections',
|
||||
ref: 'https://developer.apple.com/documentation/security/preventing-insecure-network-connections' });
|
||||
const ipv4 = src(SIGNALS.ipv4, 2);
|
||||
if (ipv4.length)
|
||||
add({ rule: 'ipv6', guideline: '2.5.5', store: 'apple', severity: 'medium', title: 'Hard-coded IPv4 address in a server URL (fails on IPv6-only networks, where App Review tests)', evidence: ipv4,
|
||||
fix: 'Use a host name that resolves over IPv6 (DNS64/NAT64 then works) instead of an IPv4 literal.', skill: 'review-rejections' });
|
||||
const enc = plistVal('ITSAppUsesNonExemptEncryption');
|
||||
const cfgEnc = c?.apple?.usesNonExemptEncryption;
|
||||
if (!enc && cfgEnc === undefined)
|
||||
add({ rule: 'export-compliance', guideline: 'Export compliance', store: 'apple', severity: 'medium', title: 'Export compliance is not answered (no ITSAppUsesNonExemptEncryption, no apple.usesNonExemptEncryption)', evidence: p.plistSources.slice(0, 1).map(f => ({ file: f, line: 1, text: 'Info.plist' })),
|
||||
fix: 'Ask the owner and decide it with the export-compliance skill (false only when the app uses no encryption beyond the OS); then set ITSAppUsesNonExemptEncryption in Info.plist and apple.usesNonExemptEncryption. Builds wait in "Missing Compliance" until it is answered.', skill: 'export-compliance',
|
||||
ref: 'https://developer.apple.com/documentation/security/complying-with-encryption-export-regulations' });
|
||||
else if (enc && cfgEnc !== undefined && enc.value !== cfgEnc)
|
||||
add({ rule: 'export-compliance', guideline: 'Export compliance', store: 'apple', severity: 'high', title: `Info.plist says ITSAppUsesNonExemptEncryption ${String(enc.value)} but the config says ${String(cfgEnc)}`, evidence: [{ ...enc.at, text: `ITSAppUsesNonExemptEncryption ${String(enc.value)}` }, ...cfg('usesNonExemptEncryption')],
|
||||
fix: 'Make both the same answer (export-compliance skill).', skill: 'export-compliance' });
|
||||
}
|
||||
|
||||
// ---- kids: ads / third-party analytics ----
|
||||
const kidsBand = c?.apple?.info?.ageRating?.kidsAgeBand;
|
||||
if (kidsBand) {
|
||||
const third = sdkHits(s => s.sdk.category === 'ads' || s.sdk.category === 'attribution' || s.sdk.category === 'analytics');
|
||||
if (third.length) {
|
||||
if (apple) add({ rule: 'kids-ads', guideline: '1.3', store: 'apple', severity: 'high', title: `Kids Category app (${String(kidsBand)}) with third-party ads or analytics SDKs`, evidence: [...cfg('kidsAgeBand'), ...third].slice(0, 4),
|
||||
fix: 'Kids Category apps should not include third-party advertising or analytics (narrow exceptions: contextual ads with human-reviewed creatives, analytics without IDFA or identifiable data). Remove them or configure child-directed mode and document it in the review notes.', skill: 'store-declarations' });
|
||||
if (play && !c?.play?.targetAges) add({ rule: 'kids-ads', guideline: 'Play: Families policy', store: 'play', severity: 'high', title: 'App for children with ad / analytics SDKs: only Families self-certified ad SDKs are allowed', evidence: third.slice(0, 3),
|
||||
fix: 'Use only ad SDKs from the Families Self-Certified Ads SDK list, turn on child-directed treatment, and answer Target audience and content accordingly.', skill: 'store-declarations', ref: `${PLAY}9893335` });
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Google Play manifest and build ----
|
||||
if (play && p.android) {
|
||||
const a = p.androidInfo;
|
||||
const need = PLAY_TARGET_SDK[a.formFactor];
|
||||
if (a.targetSdk && a.targetSdk.value < need)
|
||||
add({ rule: 'play-target-sdk', guideline: 'Play: Target API level', store: 'play', severity: 'blocker', title: `targetSdk ${a.targetSdk.value} is below ${need}, which new apps and updates need since ${PLAY_TARGET_SDK_SINCE}`, evidence: [{ ...a.targetSdk.at, text: `targetSdk ${a.targetSdk.value}` }],
|
||||
fix: `Raise targetSdk (and compileSdk) to ${need}, test the behavior changes of each Android version in between, then upload a new AAB (an extension to 2026-11-01 can be requested in Play Console).`, skill: 'play-first-release',
|
||||
ref: 'https://developer.android.com/google/play/requirements/target-sdk' });
|
||||
else if (!a.targetSdk && a.targetSdkFrom)
|
||||
add({ rule: 'play-target-sdk', guideline: 'Play: Target API level', store: 'play', severity: 'low', title: `targetSdk comes from ${a.targetSdkFrom}: check that the built AAB targets ${need} or higher`, evidence: a.manifests.slice(0, 1).map(f => ({ file: f, line: 1, text: 'AndroidManifest.xml' })),
|
||||
fix: `Check with \`aapt2 dump badging app.aab\` or Play Console > App bundle explorer; Play refuses uploads below ${need}.`, skill: 'play-first-release', ref: 'https://developer.android.com/google/play/requirements/target-sdk' });
|
||||
const perms = new Map(a.permissions.map(x => [x.name.replace(/^android\.permission\./, ''), x] as const));
|
||||
const fgs = perms.get('FOREGROUND_SERVICE');
|
||||
if (fgs && (!a.targetSdk || a.targetSdk.value >= 34)) {
|
||||
const typed = a.services.filter(s => s.fgsType);
|
||||
const untyped = a.services.filter(s => !s.fgsType);
|
||||
if (untyped.length && !typed.length)
|
||||
add({ rule: 'play-fgs', guideline: 'Play: Foreground service types', store: 'play', severity: 'high', title: 'FOREGROUND_SERVICE is requested but no <service> declares android:foregroundServiceType (required when targeting Android 14+)', evidence: [{ ...fgs.at, text: 'FOREGROUND_SERVICE' }, ...untyped.slice(0, 2).map(s => ({ ...s.at, text: `service ${s.name}` }))],
|
||||
fix: 'Give each foreground service a type and its FOREGROUND_SERVICE_<TYPE> permission, then fill App content > Foreground service permissions (description, user impact, video).', skill: 'play-first-release', ref: `${PLAY}13392821` });
|
||||
for (const s of typed) {
|
||||
const types = s.fgsType!.split('|').map(x => x.trim()).filter(Boolean);
|
||||
const missing = types.filter(t => FGS_PERMISSION[t] && !perms.has(`FOREGROUND_SERVICE_${FGS_PERMISSION[t]}`));
|
||||
if (missing.length)
|
||||
add({ rule: 'play-fgs', guideline: 'Play: Foreground service types', store: 'play', severity: 'high', title: `Service ${s.name} has type ${missing.join('|')} without FOREGROUND_SERVICE_${missing.map(t => FGS_PERMISSION[t]).join(' / ')} (SecurityException on Android 14+)`, evidence: [{ ...s.at, text: `foregroundServiceType="${s.fgsType}"` }],
|
||||
fix: `Add <uses-permission android:name="android.permission.FOREGROUND_SERVICE_${FGS_PERMISSION[missing[0]!]}" />.`, skill: 'play-first-release', ref: `${PLAY}13392821` });
|
||||
}
|
||||
if (typed.length)
|
||||
add({ rule: 'play-fgs', guideline: 'Play: Foreground service types', store: 'play', severity: 'medium', title: `Foreground service types need a Play Console declaration: ${[...new Set(typed.flatMap(s => s.fgsType!.split('|')))].join(', ')}`, evidence: typed.slice(0, 3).map(s => ({ ...s.at, text: `${s.name}: ${s.fgsType}` })),
|
||||
fix: 'App content > Foreground service permissions: describe each use, the user impact if it is deferred, and add a short video; shortService needs none.', skill: 'play-first-release', ref: `${PLAY}13392821` });
|
||||
}
|
||||
const exact = perms.get('USE_EXACT_ALARM');
|
||||
if (exact)
|
||||
add({ rule: 'play-exact-alarm', guideline: 'Play: Exact alarm permission', store: 'play', severity: 'high', title: 'USE_EXACT_ALARM is only allowed for alarm clock, timer and calendar apps', evidence: [{ ...exact.at, text: 'USE_EXACT_ALARM' }],
|
||||
fix: 'Remove it (an SDK may add it: check the merged manifest and use tools:node="remove"), or use SCHEDULE_EXACT_ALARM (the user grants it) or inexact alarms / WorkManager; alarm and calendar apps fill the Play Console declaration.', skill: 'play-first-release', ref: `${PLAY}9888170` });
|
||||
const sched = perms.get('SCHEDULE_EXACT_ALARM');
|
||||
if (sched && !exact)
|
||||
add({ rule: 'play-exact-alarm', guideline: 'Play: Exact alarm permission', store: 'play', severity: 'low', title: 'SCHEDULE_EXACT_ALARM: denied by default from Android 14; the app must check canScheduleExactAlarms()', evidence: [{ ...sched.at, text: 'SCHEDULE_EXACT_ALARM' }],
|
||||
fix: 'Keep it only for user-facing, time-critical features and handle the denied case; otherwise use inexact alarms.', skill: 'play-first-release', ref: `${PLAY}9888170` });
|
||||
const qap = perms.get('QUERY_ALL_PACKAGES');
|
||||
if (qap)
|
||||
add({ rule: 'play-query-all-packages', guideline: 'Play: Package visibility', store: 'play', severity: 'high', title: 'QUERY_ALL_PACKAGES needs a core purpose that requires seeing every installed app, and a declaration', evidence: [{ ...qap.at, text: 'QUERY_ALL_PACKAGES' }],
|
||||
fix: 'Replace it with <queries> entries for the packages or intents you need; keep it only for launchers, device search, antivirus, file managers, browsers and similar, and fill the Permissions Declaration Form.', skill: 'play-first-release', ref: `${PLAY}10158779` });
|
||||
const sms = SMS_CALL_LOG.map(x => perms.get(x)).filter((x): x is NonNullable<typeof x> => !!x);
|
||||
if (sms.length)
|
||||
add({ rule: 'play-sms-call-log', guideline: 'Play: SMS and Call Log permissions', store: 'play', severity: 'high', title: `Restricted SMS / Call Log permissions: ${sms.map(x => x.name.replace(/^android\.permission\./, '')).join(', ')}`, evidence: sms.slice(0, 3).map(x => ({ ...x.at, text: x.name })),
|
||||
fix: 'Only the default SMS / Phone / Assistant handler may use them (or a listed exception with a declaration). Remove them; for one-time codes use the SMS Retriever or SMS User Consent API.', skill: 'play-first-release', ref: `${PLAY}10208820` });
|
||||
}
|
||||
|
||||
// ---- privacy policy in the app, privacy labels vs SDKs, unused permissions ----
|
||||
const collects = p.sdks.length > 0 || creates.length > 0;
|
||||
if (apple && collects && p.sources.length && !src(SIGNALS.privacyLink, 1).length && !(c?.app.privacyPolicyUrl && src(new RegExp(c.app.privacyPolicyUrl.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')), 1).length))
|
||||
add({ rule: 'privacy-policy-link', guideline: '5.1.1(i)', store: 'apple', severity: 'medium', title: 'The app collects data (SDKs or accounts) but no privacy policy link was found in its sources', evidence: [...sdkHits(() => true), ...creates].slice(0, 3),
|
||||
fix: 'Link the privacy policy (app.privacyPolicyUrl) somewhere easy to find in the app, e.g. Settings > Privacy policy, and on sign-up / purchase screens.', skill: 'privacy-policy' });
|
||||
for (const g of inp.labelGaps ?? []) {
|
||||
if (apple) add({ rule: 'privacy-labels', guideline: '5.1.2', store: 'apple', severity: 'medium', title: `App Privacy likely misses "${g.apple}": an SDK collects it, the config does not declare it`, evidence: g.evidence.slice(0, 2),
|
||||
fix: 'Run `storebound scan` and read the declarations proposal; confirm with the SDK\'s disclosure, then add the type to dataSafety (`storebound scan --write`) and to App Privacy in App Store Connect.', skill: 'store-declarations' });
|
||||
if (play) add({ rule: 'privacy-labels', guideline: 'Play: User Data (Data safety)', store: 'play', severity: 'medium', title: `Data safety likely misses ${g.type}: an SDK collects it, dataSafety does not declare it`, evidence: g.evidence.slice(0, 2),
|
||||
fix: 'Confirm with the SDK\'s Data safety guidance, add it with `storebound scan --write` (or by hand), then `storebound play data-safety`.', skill: 'store-declarations', ref: `${PLAY}10787469` });
|
||||
}
|
||||
if (apple && iosProject && p.stacks.length === 1 && p.stacks[0] === 'ios-native') {
|
||||
for (const perm of IOS_PERMISSIONS) {
|
||||
const entry = perm.keys.map(k => plistVal(k)).find(Boolean);
|
||||
if (!entry || perm.keys.includes('NSUserTrackingUsageDescription') || perm.keys.includes('NSPhotoLibraryUsageDescription')) continue;
|
||||
if (grep(p.sources, perm.code, 1, native).length || p.sdks.length) continue;
|
||||
add({ rule: 'unused-permission', guideline: '5.1.1(iv)', store: 'apple', severity: 'low', title: `${entry.key} is declared but no ${perm.what} use was found in the app's sources`, evidence: [{ ...entry.at, text: entry.key }],
|
||||
fix: 'Remove purpose strings the app does not need; ask only for the access a feature needs, when it needs it.', skill: 'review-rejections' });
|
||||
}
|
||||
}
|
||||
|
||||
// ---- payments outside in-app purchase, subscription management ----
|
||||
const extPay = sdkHits(s => s.sdk.category === 'external-payments');
|
||||
if (apple && extPay.length && (restorable.length || paySdk.length || (c?.products?.length ?? 0) > 0))
|
||||
add({ rule: 'external-purchase', guideline: '3.1.1', store: 'apple', severity: 'medium', title: 'A card / PayPal payment SDK next to in-app purchases: digital goods and features must be sold with in-app purchase', evidence: [...extPay, ...restorable].slice(0, 3),
|
||||
fix: 'Use the external payment SDK only for physical goods or services used outside the app (3.1.3(e)); sell unlocks, coins and subscriptions through StoreKit.', skill: 'review-rejections' });
|
||||
const buyOutside = apple ? [...listingHits(inp.listings.apple, SIGNALS.externalBuy), ...grep(p.sources, SIGNALS.externalBuy, 2, x => native(x) || /\.(dart|tsx?|jsx?|cs|vue|html)$/.test(x))] : [];
|
||||
if (buyOutside.length)
|
||||
add({ rule: 'external-purchase', guideline: '3.1.1', store: 'apple', severity: 'medium', title: 'A call to action to buy outside the app (website) in the iOS app or its metadata', evidence: buyOutside.slice(0, 3),
|
||||
fix: 'Outside the storefronts and entitlements that allow external purchase links, remove buttons, links and text that send people to buy digital content elsewhere.', skill: 'review-rejections' });
|
||||
if (apple && hasSubs && p.sources.length && !src(SIGNALS.manageSubs, 1).length)
|
||||
add({ rule: 'subscription-info', guideline: '3.1.2', store: 'apple', severity: 'low', title: 'No "Manage subscription" entry found in the app', evidence: (subs.length ? cfg(/subscriptions\s*:/) : subCode).slice(0, 1),
|
||||
fix: 'Offer a way to manage or cancel in the app (StoreKit showManageSubscriptions / SwiftUI manageSubscriptionsSheet, or a link to the App Store subscriptions page).', skill: 'store-subscriptions' });
|
||||
|
||||
// ---- private URL schemes, review prompts ----
|
||||
if (apple) {
|
||||
const priv = grep(p.sources, SIGNALS.privateScheme, 2);
|
||||
if (priv.length)
|
||||
add({ rule: 'private-api', guideline: '2.5.1', store: 'apple', severity: 'high', title: 'Private settings URL scheme (App-Prefs: / prefs:root)', evidence: priv,
|
||||
fix: 'Open your own settings page with UIApplication.openSettingsURLString instead.', skill: 'review-rejections' });
|
||||
const incent = grep(p.sources, SIGNALS.incentiveRating, 2);
|
||||
if (incent.length)
|
||||
add({ rule: 'review-prompt', guideline: '3.2.2(x) / 5.6.3', store: 'apple', severity: 'high', title: 'A reward for rating or reviewing the app', evidence: incent,
|
||||
fix: 'Never reward or gate ratings; ask with the system review prompt only.', skill: 'review-replies' });
|
||||
const custom = grep(p.sources, SIGNALS.ratePrompt, 2);
|
||||
if (custom.length && !src(SIGNALS.reviewApi, 1).length && !p.deps.some(d => /review|rate/i.test(d.name)))
|
||||
add({ rule: 'review-prompt', guideline: '5.6.1', store: 'apple', severity: 'medium', title: 'A custom "rate us" prompt without the system review API', evidence: custom,
|
||||
fix: 'Ask for ratings with SKStoreReviewController / requestReview (StoreKit); custom review prompts are not allowed.', skill: 'review-replies' });
|
||||
}
|
||||
if (play && c?.play && /^com\.example(\.|$)/.test(c.play.packageName))
|
||||
add({ rule: 'play-package-name', guideline: 'Play: Package name', store: 'play', severity: 'blocker', title: `Package name ${c.play.packageName} uses the reserved com.example prefix`, evidence: cfg('packageName'),
|
||||
fix: 'Pick your own reverse-domain package name (it can never change after the first upload) and set it in the Gradle applicationId and play.packageName.', skill: 'play-first-release',
|
||||
ref: 'https://developer.android.com/build/configure-app-module' });
|
||||
|
||||
// ---- the other Google Play policies (play-rules.ts) ----
|
||||
if (play)
|
||||
playRules(inp, { add: f => add({ ...f, store: 'play' }), cfg, sdkHits, listingHits, creates, restorable, paySdk });
|
||||
|
||||
// ---- owner-accepted findings ----
|
||||
const ignore = c?.scan?.ignore ?? [];
|
||||
for (const f of out) {
|
||||
const hit = ignore.find(i => i.rule === f.rule && (!i.store || i.store === f.store));
|
||||
if (hit) f.accepted = hit.reason;
|
||||
}
|
||||
return sortScan(out);
|
||||
}
|
||||
|
||||
const RANK: Record<Severity, number> = { blocker: 0, high: 1, medium: 2, low: 3 };
|
||||
/** Open findings first (blocker, high, medium, low), owner-accepted ones last; stable inside a level. */
|
||||
export function sortScan(f: ScanFinding[]): ScanFinding[] {
|
||||
return f.map((x, i) => [x, i] as const).sort(([a, i], [b, j]) => Number(!!a.accepted) - Number(!!b.accepted) || RANK[a.severity] - RANK[b.severity] || i - j).map(([x]) => x);
|
||||
}
|
||||
216
cli/lib/scan/sdks.ts
Normal file
216
cli/lib/scan/sdks.ts
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
// The SDK table `storebound scan` detects: which third-party SDKs a mobile app or game ships, from its dependency files
|
||||
// (CocoaPods, Swift Package Manager, Carthage, Gradle and version catalogs, npm, pub, Unity packages and External
|
||||
// Dependency Manager XML, Godot addons, Cordova plugins), and what each one means for the store declarations.
|
||||
//
|
||||
// Maintained by hand. Every entry names the SDK's own data disclosure page (`docs`): that page is the source for the
|
||||
// data types listed in `data`, which are the types the SDK collects by default as its vendor documents them for the
|
||||
// Play Data safety form and Apple's App Privacy. The app's own configuration can change them (for example
|
||||
// non-personalized ads only, analytics collection off), which is why scan proposes and the owner decides.
|
||||
// Checked 2026-10-11. When a vendor changes its disclosure, update the entry and the date.
|
||||
import type { PlayPurpose } from '../config';
|
||||
|
||||
export type SdkCategory = 'ads' | 'analytics' | 'attribution' | 'crash' | 'auth' | 'payments' | 'external-payments' | 'push';
|
||||
export type Eco = 'cocoapods' | 'spm' | 'carthage' | 'gradle' | 'npm' | 'pub' | 'unity' | 'godot';
|
||||
|
||||
export interface SdkData {
|
||||
/** Play Data safety type id (PSL_...). The App Privacy type follows from it (declarations.ts APPLE_PRIVACY). */
|
||||
type: string;
|
||||
collect: PlayPurpose[];
|
||||
/** Sent to the SDK vendor for its own use (Play "shared"; Apple "third-party advertising" when for ads). */
|
||||
share?: PlayPurpose[];
|
||||
}
|
||||
|
||||
export interface SdkDef {
|
||||
id: string;
|
||||
name: string;
|
||||
category: SdkCategory;
|
||||
/** Can track across apps (reads IDFA / the Android advertising id, or links data with other companies' data):
|
||||
* needs App Tracking Transparency on iOS before it does. */
|
||||
tracking: boolean;
|
||||
/** Login provider this SDK adds (4.8 Login Services). */
|
||||
login?: 'google' | 'facebook' | 'apple' | 'firebase';
|
||||
/** Matchers per ecosystem. cocoapods: pod name (or its prefix before "/"); spm: a fragment of the repository URL or
|
||||
* the package identity; gradle: "group:artifact" (or "group:" for any artifact of the group); npm / pub: package
|
||||
* name; unity: UPM package id or a folder under Assets/; godot: a folder under addons/. */
|
||||
match: Partial<Record<Eco, string[]>>;
|
||||
data: SdkData[];
|
||||
/** Vendor's data disclosure / privacy page: the source for `data`. */
|
||||
docs: string;
|
||||
/** iOS: first version that ships Apple's privacy manifest (only where the vendor's release notes say so). */
|
||||
manifestSince?: string;
|
||||
/** Ad SDKs: on Google's Families Self-Certified Ads SDK list (support.google.com/googleplay/android-developer/answer/9859768,
|
||||
* checked 2026-10-11), from `since` (the Android SDK version the list names). false = not on the list. */
|
||||
families?: { certified: boolean; since?: string; note?: string };
|
||||
/** Android: the SDK's own manifest declares com.google.android.gms.permission.AD_ID, so it reaches the merged
|
||||
* manifest without the app declaring it (Play "Advertising ID" page names Google Mobile Ads as an example). */
|
||||
mergesAdId?: boolean;
|
||||
}
|
||||
|
||||
const ADS_DATA: SdkData[] = [
|
||||
{ type: 'PSL_DEVICE_ID', collect: ['advertising', 'analytics', 'fraud'], share: ['advertising'] },
|
||||
{ type: 'PSL_APPROX_LOCATION', collect: ['advertising', 'analytics', 'fraud'], share: ['advertising'] },
|
||||
{ type: 'PSL_USER_INTERACTION', collect: ['advertising', 'analytics'], share: ['advertising'] },
|
||||
{ type: 'PSL_PERFORMANCE_DIAGNOSTICS', collect: ['analytics'] },
|
||||
];
|
||||
const ANALYTICS_DATA: SdkData[] = [
|
||||
{ type: 'PSL_DEVICE_ID', collect: ['analytics'] },
|
||||
{ type: 'PSL_USER_INTERACTION', collect: ['analytics'] },
|
||||
];
|
||||
const CRASH_DATA: SdkData[] = [
|
||||
{ type: 'PSL_CRASH_LOGS', collect: ['analytics'] },
|
||||
{ type: 'PSL_PERFORMANCE_DIAGNOSTICS', collect: ['analytics'] },
|
||||
];
|
||||
const LOGIN_DATA: SdkData[] = [
|
||||
{ type: 'PSL_NAME', collect: ['account'] },
|
||||
{ type: 'PSL_EMAIL', collect: ['account'] },
|
||||
{ type: 'PSL_USER_ACCOUNT', collect: ['account'] },
|
||||
];
|
||||
|
||||
export const SDKS: SdkDef[] = [
|
||||
// ---- ads (tracking-capable: they read the advertising id when the user allows it) ----
|
||||
{ id: 'admob', name: 'Google AdMob', category: 'ads', tracking: true, data: ADS_DATA, manifestSince: '11.2.0', mergesAdId: true,
|
||||
families: { certified: true, since: '19.0.0' },
|
||||
docs: 'https://developers.google.com/admob/android/privacy/play-data-disclosure',
|
||||
match: { cocoapods: ['Google-Mobile-Ads-SDK'], spm: ['swift-package-manager-google-mobile-ads'], gradle: ['com.google.android.gms:play-services-ads'],
|
||||
npm: ['react-native-google-mobile-ads', '@capacitor-community/admob', 'admob-plus-cordova', 'expo-ads-admob'], pub: ['google_mobile_ads'],
|
||||
unity: ['com.google.ads.mobile', 'GoogleMobileAds'], godot: ['admob'] } },
|
||||
{ id: 'applovin', name: 'AppLovin MAX', category: 'ads', tracking: true, data: ADS_DATA,
|
||||
families: { certified: false, note: 'AppLovin left the program; Families apps had to move off it by 2023-05-31' },
|
||||
docs: 'https://support.axon.ai/en/max/android/overview/data-and-privacy',
|
||||
match: { cocoapods: ['AppLovinSDK'], spm: ['applovin-ios-sdk'], gradle: ['com.applovin:applovin-sdk'], npm: ['react-native-applovin-max'],
|
||||
pub: ['applovin_max'], unity: ['com.applovin.mediation.ads', 'MaxSdk'] } },
|
||||
{ id: 'levelplay', name: 'Unity LevelPlay (ironSource)', category: 'ads', tracking: true, data: ADS_DATA,
|
||||
families: { certified: true, since: '7.2.1', note: 'listed as ironSource; every mediated network must be on the list too' },
|
||||
docs: 'https://developers.is.com/ironsource-mobile/general/ironsource-mobile-sdk-data-disclosure/',
|
||||
match: { cocoapods: ['IronSourceSDK', 'IronSourcePod'], gradle: ['com.unity3d.ads-mediation:mediation-sdk', 'com.ironsource.sdk:mediationsdk'],
|
||||
npm: ['ironsource-mediation', 'react-native-ironsource-mediation'], pub: ['unity_levelplay_mediation', 'ironsource_mediation'],
|
||||
unity: ['com.unity.services.levelplay', 'IronSource', 'LevelPlay'] } },
|
||||
{ id: 'unity-ads', name: 'Unity Ads', category: 'ads', tracking: true, data: ADS_DATA,
|
||||
families: { certified: true, since: '4.0.1' },
|
||||
docs: 'https://docs.unity.com/en-us/grow/ads/privacy/google-data-safety',
|
||||
match: { cocoapods: ['UnityAds'], gradle: ['com.unity3d.ads:unity-ads'], pub: ['unity_ads_plugin'], unity: ['com.unity.ads'], npm: ['react-native-unity-ads'] } },
|
||||
{ id: 'meta-an', name: 'Meta Audience Network', category: 'ads', tracking: true, data: ADS_DATA,
|
||||
families: { certified: false, note: 'not on the list' },
|
||||
docs: 'https://developers.facebook.com/docs/audience-network/',
|
||||
match: { cocoapods: ['FBAudienceNetwork'], gradle: ['com.facebook.android:audience-network-sdk'], npm: ['react-native-fbads'],
|
||||
pub: ['facebook_audience_network'], unity: ['AudienceNetwork'] } },
|
||||
// ---- attribution (tracking by design) ----
|
||||
{ id: 'appsflyer', name: 'AppsFlyer', category: 'attribution', tracking: true,
|
||||
data: [{ type: 'PSL_DEVICE_ID', collect: ['analytics', 'advertising', 'fraud'], share: ['advertising'] }, { type: 'PSL_USER_INTERACTION', collect: ['analytics', 'advertising'] }],
|
||||
docs: 'https://www.appsflyer.com/legal/services-privacy-policy/',
|
||||
match: { cocoapods: ['AppsFlyerFramework'], spm: ['AppsFlyerFramework'], gradle: ['com.appsflyer:af-android-sdk'], npm: ['react-native-appsflyer', 'cordova-plugin-appsflyer-sdk'],
|
||||
pub: ['appsflyer_sdk'], unity: ['appsflyer-unity-plugin', 'AppsFlyer'] } },
|
||||
{ id: 'adjust', name: 'Adjust', category: 'attribution', tracking: true,
|
||||
data: [{ type: 'PSL_DEVICE_ID', collect: ['analytics', 'advertising', 'fraud'], share: ['advertising'] }, { type: 'PSL_USER_INTERACTION', collect: ['analytics', 'advertising'] }],
|
||||
docs: 'https://help.adjust.com/en/article/google-play-data-safety',
|
||||
match: { cocoapods: ['Adjust'], spm: ['ios_sdk'], gradle: ['com.adjust.sdk:adjust-android'], npm: ['react-native-adjust'], pub: ['adjust_sdk'], unity: ['com.adjust.sdk', 'Adjust'] } },
|
||||
// ---- analytics ----
|
||||
{ id: 'firebase-analytics', name: 'Firebase Analytics', category: 'analytics', tracking: false, manifestSince: '10.22.0',
|
||||
data: [{ type: 'PSL_DEVICE_ID', collect: ['analytics'] }, { type: 'PSL_USER_INTERACTION', collect: ['analytics'] }, { type: 'PSL_APPROX_LOCATION', collect: ['analytics'] }],
|
||||
docs: 'https://firebase.google.com/docs/android/play-data-disclosure',
|
||||
match: { cocoapods: ['FirebaseAnalytics', 'Firebase/Analytics'], spm: ['firebase-ios-sdk#FirebaseAnalytics'], gradle: ['com.google.firebase:firebase-analytics'],
|
||||
npm: ['@react-native-firebase/analytics', '@capacitor-firebase/analytics', '@capacitor-community/firebase-analytics'], pub: ['firebase_analytics'],
|
||||
unity: ['com.google.firebase.analytics', 'FirebaseAnalytics'] } },
|
||||
{ id: 'gameanalytics', name: 'GameAnalytics', category: 'analytics', tracking: false, data: ANALYTICS_DATA,
|
||||
docs: 'https://gameanalytics.com/privacy-policy',
|
||||
match: { cocoapods: ['GA-SDK-IOS', 'GameAnalytics'], gradle: ['com.gameanalytics.sdk:gameanalytics-android'], unity: ['com.gameanalytics.sdk', 'GameAnalytics'],
|
||||
pub: ['gameanalytics_sdk'], npm: ['react-native-gameanalytics'] } },
|
||||
{ id: 'amplitude', name: 'Amplitude', category: 'analytics', tracking: false, data: ANALYTICS_DATA,
|
||||
docs: 'https://amplitude.com/security-and-privacy',
|
||||
match: { cocoapods: ['Amplitude', 'AmplitudeSwift'], spm: ['Amplitude-iOS', 'Amplitude-Swift'], gradle: ['com.amplitude:'], npm: ['@amplitude/analytics-react-native', '@amplitude/react-native'],
|
||||
pub: ['amplitude_flutter'], unity: ['Amplitude'] } },
|
||||
{ id: 'mixpanel', name: 'Mixpanel', category: 'analytics', tracking: false, data: ANALYTICS_DATA,
|
||||
docs: 'https://docs.mixpanel.com/docs/privacy/protecting-user-data',
|
||||
match: { cocoapods: ['Mixpanel', 'Mixpanel-swift'], spm: ['mixpanel-swift', 'mixpanel-iphone'], gradle: ['com.mixpanel.android:mixpanel-android'], npm: ['mixpanel-react-native'],
|
||||
pub: ['mixpanel_flutter'], unity: ['com.mixpanel.unity', 'Mixpanel'] } },
|
||||
// ---- crash reporting ----
|
||||
{ id: 'crashlytics', name: 'Firebase Crashlytics', category: 'crash', tracking: false, data: CRASH_DATA, manifestSince: '10.22.0',
|
||||
docs: 'https://firebase.google.com/docs/android/play-data-disclosure',
|
||||
match: { cocoapods: ['FirebaseCrashlytics', 'Firebase/Crashlytics'], spm: ['firebase-ios-sdk#FirebaseCrashlytics'], gradle: ['com.google.firebase:firebase-crashlytics'],
|
||||
npm: ['@react-native-firebase/crashlytics', '@capacitor-firebase/crashlytics'], pub: ['firebase_crashlytics'], unity: ['com.google.firebase.crashlytics', 'FirebaseCrashlytics'] } },
|
||||
{ id: 'sentry', name: 'Sentry', category: 'crash', tracking: false, data: CRASH_DATA, manifestSince: '8.21.0',
|
||||
docs: 'https://docs.sentry.io/platforms/android/data-management/data-collected/',
|
||||
match: { cocoapods: ['Sentry'], spm: ['sentry-cocoa'], gradle: ['io.sentry:sentry-android'], npm: ['@sentry/react-native', '@sentry/capacitor'], pub: ['sentry_flutter'], unity: ['io.sentry.unity'] } },
|
||||
// ---- sign-in ----
|
||||
{ id: 'google-signin', name: 'Google Sign-In', category: 'auth', tracking: false, login: 'google', data: LOGIN_DATA, manifestSince: '7.1.0',
|
||||
docs: 'https://developers.google.com/identity/sign-in/ios/start-integrating',
|
||||
match: { cocoapods: ['GoogleSignIn'], spm: ['GoogleSignIn-iOS'], gradle: ['com.google.android.gms:play-services-auth', 'com.google.android.libraries.identity.googleid:googleid'],
|
||||
npm: ['@react-native-google-signin/google-signin', '@codetrix-studio/capacitor-google-auth', 'expo-google-sign-in'], pub: ['google_sign_in'], unity: ['com.google.signin', 'GoogleSignIn'] } },
|
||||
{ id: 'facebook-login', name: 'Facebook Login', category: 'auth', tracking: true, login: 'facebook', data: LOGIN_DATA, manifestSince: '17.0.0',
|
||||
docs: 'https://developers.facebook.com/docs/facebook-login/',
|
||||
match: { cocoapods: ['FBSDKLoginKit', 'FacebookLogin'], spm: ['facebook-ios-sdk'], gradle: ['com.facebook.android:facebook-login', 'com.facebook.android:facebook-android-sdk'],
|
||||
npm: ['react-native-fbsdk-next', '@capacitor-community/facebook-login'], pub: ['flutter_facebook_auth'], unity: ['com.facebook.sdk', 'FacebookSDK'] } },
|
||||
{ id: 'apple-signin', name: 'Sign in with Apple', category: 'auth', tracking: false, login: 'apple', data: [{ type: 'PSL_NAME', collect: ['account'] }, { type: 'PSL_EMAIL', collect: ['account'] }],
|
||||
docs: 'https://developer.apple.com/sign-in-with-apple/',
|
||||
match: { npm: ['expo-apple-authentication', '@invertase/react-native-apple-authentication', '@capacitor-community/apple-sign-in', 'cordova-plugin-sign-in-with-apple'],
|
||||
pub: ['sign_in_with_apple', 'the_apple_sign_in'], unity: ['com.lupidan.apple-signin-unity', 'AppleAuth'] } },
|
||||
{ id: 'firebase-auth', name: 'Firebase Authentication', category: 'auth', tracking: false, login: 'firebase', data: LOGIN_DATA, manifestSince: '10.22.0',
|
||||
docs: 'https://firebase.google.com/docs/android/play-data-disclosure',
|
||||
match: { cocoapods: ['FirebaseAuth', 'Firebase/Auth'], spm: ['firebase-ios-sdk#FirebaseAuth'], gradle: ['com.google.firebase:firebase-auth'],
|
||||
npm: ['@react-native-firebase/auth', '@capacitor-firebase/authentication'], pub: ['firebase_auth'], unity: ['com.google.firebase.auth', 'FirebaseAuth'] } },
|
||||
// ---- payments ----
|
||||
{ id: 'play-billing', name: 'Google Play Billing', category: 'payments', tracking: false, data: [{ type: 'PSL_PURCHASE_HISTORY', collect: ['functionality'] }],
|
||||
docs: 'https://developer.android.com/google/play/billing',
|
||||
match: { gradle: ['com.android.billingclient:billing'] } },
|
||||
{ id: 'revenuecat', name: 'RevenueCat', category: 'payments', tracking: false, data: [{ type: 'PSL_PURCHASE_HISTORY', collect: ['functionality', 'analytics'] }, { type: 'PSL_USER_ACCOUNT', collect: ['functionality'] }],
|
||||
docs: 'https://www.revenuecat.com/docs/platform-resources/apple-platform-resources/apple-app-privacy',
|
||||
match: { cocoapods: ['RevenueCat', 'Purchases'], spm: ['purchases-ios'], gradle: ['com.revenuecat.purchases:purchases'], npm: ['react-native-purchases', '@revenuecat/purchases-capacitor', 'cordova-plugin-purchases'],
|
||||
pub: ['purchases_flutter'], unity: ['com.revenuecat.purchases-unity', 'RevenueCat'] } },
|
||||
{ id: 'iap-wrapper', name: 'In-app purchase plugin', category: 'payments', tracking: false, data: [{ type: 'PSL_PURCHASE_HISTORY', collect: ['functionality'] }],
|
||||
docs: 'https://developer.apple.com/storekit/',
|
||||
match: { npm: ['react-native-iap', 'expo-iap', 'expo-in-app-purchases', 'cordova-plugin-purchase', '@capgo/native-purchases'], pub: ['in_app_purchase'], unity: ['com.unity.purchasing'] } },
|
||||
// ---- payments outside the stores (fine for physical goods and services; digital goods need in-app purchase) ----
|
||||
{ id: 'stripe', name: 'Stripe', category: 'external-payments', tracking: false, data: [{ type: 'PSL_CREDIT_DEBIT_BANK_ACCOUNT_NUMBER', collect: ['functionality', 'fraud'] }, { type: 'PSL_PURCHASE_HISTORY', collect: ['functionality'] }],
|
||||
docs: 'https://stripe.com/privacy',
|
||||
match: { cocoapods: ['Stripe', 'StripePaymentSheet'], spm: ['stripe-ios'], gradle: ['com.stripe:stripe-android'], npm: ['@stripe/stripe-react-native', '@capacitor-community/stripe'], pub: ['flutter_stripe'] } },
|
||||
{ id: 'paypal', name: 'PayPal / Braintree', category: 'external-payments', tracking: false, data: [{ type: 'PSL_PURCHASE_HISTORY', collect: ['functionality'] }],
|
||||
docs: 'https://www.paypal.com/us/legalhub/privacy-full',
|
||||
match: { cocoapods: ['Braintree', 'PayPalCheckout', 'PayPal'], spm: ['braintree_ios', 'paypal-ios'], gradle: ['com.braintreepayments.api:', 'com.paypal.checkout:', 'com.paypal.android:'],
|
||||
npm: ['react-native-paypal', 'react-native-braintree-dropin-ui'], pub: ['flutter_braintree', 'flutter_paypal'] } },
|
||||
// ---- push ----
|
||||
{ id: 'fcm', name: 'Firebase Cloud Messaging', category: 'push', tracking: false, data: [{ type: 'PSL_DEVICE_ID', collect: ['functionality'] }], manifestSince: '10.22.0',
|
||||
docs: 'https://firebase.google.com/docs/android/play-data-disclosure',
|
||||
match: { cocoapods: ['FirebaseMessaging', 'Firebase/Messaging'], spm: ['firebase-ios-sdk#FirebaseMessaging'], gradle: ['com.google.firebase:firebase-messaging'],
|
||||
npm: ['@react-native-firebase/messaging', '@capacitor-firebase/messaging'], pub: ['firebase_messaging'], unity: ['com.google.firebase.messaging', 'FirebaseMessaging'] } },
|
||||
{ id: 'onesignal', name: 'OneSignal', category: 'push', tracking: false, data: [{ type: 'PSL_USER_INTERACTION', collect: ['analytics'] }, { type: 'PSL_PURCHASE_HISTORY', collect: ['analytics'] }],
|
||||
docs: 'https://documentation.onesignal.com/docs/google-play-data-safety-requirements',
|
||||
match: { cocoapods: ['OneSignalXCFramework', 'OneSignal'], spm: ['OneSignal-XCFramework'], gradle: ['com.onesignal:OneSignal'], npm: ['react-native-onesignal', 'onesignal-cordova-plugin', 'onesignal-expo-plugin'],
|
||||
pub: ['onesignal_flutter'], unity: ['com.onesignal.unity', 'OneSignal'] } },
|
||||
{ id: 'push-plugin', name: 'Push notifications plugin', category: 'push', tracking: false, data: [],
|
||||
docs: 'https://developer.apple.com/documentation/usernotifications',
|
||||
match: { npm: ['@capacitor/push-notifications', 'expo-notifications', '@react-native-community/push-notification-ios', 'react-native-push-notification'], pub: ['flutter_local_notifications'], unity: ['com.unity.mobile.notifications'] } },
|
||||
];
|
||||
|
||||
export interface DepRef { eco: Eco; name: string; version: string | null; file: string; line: number }
|
||||
|
||||
/** Does a dependency match an SDK? Pods match by name or "Name/Sub"; Gradle by "group:artifact" or a "group:" prefix;
|
||||
* SPM by URL fragment (or "url#Product" for one product of a multi-product repository, matched on the product). */
|
||||
export function matchesSdk(d: DepRef, s: SdkDef): boolean {
|
||||
const list = s.match[d.eco] ?? [];
|
||||
const n = d.name;
|
||||
return list.some(m => {
|
||||
switch (d.eco) {
|
||||
case 'cocoapods': return n === m || n.startsWith(`${m}/`);
|
||||
case 'gradle': return m.endsWith(':') ? n.startsWith(m) : n === m;
|
||||
case 'spm': {
|
||||
const [repo, product] = m.split('#') as [string, string | undefined];
|
||||
if (product) return n.toLowerCase() === product.toLowerCase();
|
||||
return n.toLowerCase().includes(repo.toLowerCase());
|
||||
}
|
||||
case 'unity': return n === m || n.toLowerCase() === m.toLowerCase();
|
||||
default: return n === m;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** "1.2.3" vs "1.10" numerically; non-numeric parts count as 0. Ranges like "^11.2.0" or "~> 11.0" use their numbers. */
|
||||
export function versionAtLeast(v: string, min: string): boolean | null {
|
||||
const nums = (s: string) => (/\d+(\.\d+)*/.exec(s)?.[0] ?? '').split('.').filter(Boolean).map(Number);
|
||||
const a = nums(v), b = nums(min);
|
||||
if (!a.length) return null;
|
||||
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
||||
const x = a[i] ?? 0, y = b[i] ?? 0;
|
||||
if (x !== y) return x > y;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
173
cli/lib/signing.ts
Normal file
173
cli/lib/signing.ts
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
// Code signing through the App Store Connect API (Certificates, Identifiers & Profiles), pure planning:
|
||||
// bundle id capabilities, which distribution certificate to use, which provisioning profile to (re)create, where
|
||||
// profiles are installed, and the ExportOptions.plist for `xcodebuild -exportArchive`. The command is
|
||||
// cli/apple/signing.ts; requests are JSON:API `Req`s (printed on --dry, sent otherwise).
|
||||
// API reference: https://developer.apple.com/documentation/appstoreconnectapi (Bundle IDs, Bundle ID Capabilities,
|
||||
// Certificates, Profiles).
|
||||
import { createHash, X509Certificate } from 'node:crypto';
|
||||
import { join } from 'node:path';
|
||||
import type { Req } from '../apple/jsonapi';
|
||||
import { one, many } from '../apple/jsonapi';
|
||||
import type { PlistValue } from './plist';
|
||||
|
||||
/** CapabilityType values of the App Store Connect API (BundleIdCapability.capabilityType). */
|
||||
export const CAPABILITY_TYPES = ['ICLOUD', 'IN_APP_PURCHASE', 'GAME_CENTER', 'PUSH_NOTIFICATIONS', 'WALLET', 'INTER_APP_AUDIO', 'MAPS',
|
||||
'ASSOCIATED_DOMAINS', 'PERSONAL_VPN', 'APP_GROUPS', 'HEALTHKIT', 'HOMEKIT', 'WIRELESS_ACCESSORY_CONFIGURATION', 'APPLE_PAY', 'DATA_PROTECTION',
|
||||
'SIRIKIT', 'NETWORK_EXTENSIONS', 'MULTIPATH', 'HOT_SPOT', 'NFC_TAG_READING', 'CLASSKIT', 'AUTOFILL_CREDENTIAL_PROVIDER',
|
||||
'ACCESS_WIFI_INFORMATION', 'NETWORK_CUSTOM_PROTOCOL', 'COREMEDIA_HLS_LOW_LATENCY', 'SYSTEM_EXTENSION_INSTALL', 'USER_MANAGEMENT',
|
||||
'APPLE_ID_AUTH'] as const;
|
||||
export type CapabilityType = typeof CAPABILITY_TYPES[number];
|
||||
|
||||
/** Certificate types storebound creates: Apple Distribution (DISTRIBUTION, all platforms), the older iOS Distribution,
|
||||
* and Developer ID Application (Mac apps outside the App Store; Account Holder only). */
|
||||
export const CERT_TYPES = ['DISTRIBUTION', 'IOS_DISTRIBUTION', 'DEVELOPER_ID_APPLICATION', 'DEVELOPER_ID_APPLICATION_G2'] as const;
|
||||
export type CertType = typeof CERT_TYPES[number];
|
||||
|
||||
/** Profile types for store builds (Profile.profileType). */
|
||||
export const PROFILE_TYPES = ['IOS_APP_STORE', 'IOS_APP_ADHOC', 'TVOS_APP_STORE', 'MAC_APP_STORE', 'MAC_APP_DIRECT', 'MAC_CATALYST_APP_STORE'] as const;
|
||||
export type ProfileType = typeof PROFILE_TYPES[number];
|
||||
|
||||
export interface CapabilitySpec { type: CapabilityType; settings?: unknown[] }
|
||||
|
||||
export interface AppleSigning {
|
||||
/** automatic (default): xcodebuild -allowProvisioningUpdates with the API key creates what it needs.
|
||||
* manual: the certificate and profiles from `storebound apple signing ensure`, named in ExportOptions.plist. */
|
||||
style?: 'automatic' | 'manual';
|
||||
/** Team ID (10 characters). Default: the bundle id's seedId from the API. */
|
||||
teamId?: string;
|
||||
/** Default DISTRIBUTION (Apple Distribution). */
|
||||
certificateType?: CertType;
|
||||
/** Default IOS_APP_STORE. */
|
||||
profileType?: ProfileType;
|
||||
/** Capabilities the bundle id must have (Certificates, Identifiers & Profiles), e.g. ['IN_APP_PURCHASE', 'GAME_CENTER']. */
|
||||
capabilities?: (CapabilityType | CapabilitySpec)[];
|
||||
/** Bundle ids of app extensions / widgets / watch apps in the same archive: each gets its own profile. */
|
||||
extraBundleIds?: string[];
|
||||
}
|
||||
|
||||
export function validateSigning(s: AppleSigning | undefined): string[] {
|
||||
if (!s) return [];
|
||||
const e: string[] = [];
|
||||
if (s.style && !['automatic', 'manual'].includes(s.style)) e.push('apple.signing.style: automatic | manual');
|
||||
if (s.teamId && !/^[A-Z0-9]{10}$/.test(s.teamId)) e.push('apple.signing.teamId: the 10-character Team ID');
|
||||
if (s.certificateType && !CERT_TYPES.includes(s.certificateType)) e.push(`apple.signing.certificateType: one of ${CERT_TYPES.join(', ')}`);
|
||||
if (s.profileType && !PROFILE_TYPES.includes(s.profileType)) e.push(`apple.signing.profileType: one of ${PROFILE_TYPES.join(', ')}`);
|
||||
for (const c of s.capabilities ?? []) {
|
||||
const t = typeof c === 'string' ? c : c?.type;
|
||||
if (!CAPABILITY_TYPES.includes(t as CapabilityType)) e.push(`apple.signing.capabilities: unknown capability "${String(t)}" (${CAPABILITY_TYPES.slice(0, 6).join(', ')}, ...)`);
|
||||
}
|
||||
for (const b of s.extraBundleIds ?? []) if (!/^[A-Za-z0-9.-]+$/.test(b)) e.push(`apple.signing.extraBundleIds: "${b}" is not a bundle id`);
|
||||
return e;
|
||||
}
|
||||
|
||||
export const capabilitySpecs = (s: AppleSigning | undefined): CapabilitySpec[] =>
|
||||
(s?.capabilities ?? []).map(c => (typeof c === 'string' ? { type: c } : c));
|
||||
|
||||
/** Capabilities to add (never removes one: removing can break a shipped feature; extra ones are reported). */
|
||||
export function planCapabilities(bundleIdId: string, existing: string[], want: CapabilitySpec[]): { create: Req[]; present: string[]; extra: string[] } {
|
||||
const have = new Set(existing);
|
||||
const create = want.filter(w => !have.has(w.type)).map((w): Req => ({
|
||||
method: 'POST', path: '/v1/bundleIdCapabilities', note: `capability ${w.type}`,
|
||||
body: { data: { type: 'bundleIdCapabilities', attributes: { capabilityType: w.type, ...(w.settings ? { settings: w.settings } : {}) }, relationships: { bundleId: one('bundleIds', bundleIdId) } } },
|
||||
}));
|
||||
return { create, present: want.filter(w => have.has(w.type)).map(w => w.type), extra: existing.filter(t => !want.some(w => w.type === t)) };
|
||||
}
|
||||
|
||||
export interface ApiCert { id: string; attributes: { certificateType?: string; certificateContent?: string; expirationDate?: string; displayName?: string; name?: string; serialNumber?: string; activated?: boolean } }
|
||||
|
||||
/** SHA-1 of the certificate DER, upper-case hex: what `security find-identity` prints. */
|
||||
export const certSha1 = (contentB64: string): string => createHash('sha1').update(Buffer.from(contentB64, 'base64')).digest('hex').toUpperCase();
|
||||
|
||||
/** SPKI (DER, base64) of a certificate's public key, or null when it does not parse. */
|
||||
export function certSpki(contentB64: string): string | null {
|
||||
try { return new X509Certificate(Buffer.from(contentB64, 'base64')).publicKey.export({ type: 'spki', format: 'der' }).toString('base64'); } catch { return null; }
|
||||
}
|
||||
|
||||
export interface CertChoice { cert: ApiCert | null; why: string; usable: ApiCert[]; withoutKey: ApiCert[]; expiring: ApiCert[] }
|
||||
|
||||
/** A certificate is usable when it is of the wanted type, active, valid for 30 more days and this machine holds its
|
||||
* private key (a key file in .storebound/signing or a code signing identity in the keychain). Newest first. */
|
||||
export function pickCertificate(certs: ApiCert[], type: CertType, hasKey: (c: ApiCert) => boolean, now = Date.now()): CertChoice {
|
||||
const ofType = certs.filter(c => c.attributes.certificateType === type && c.attributes.activated !== false);
|
||||
const valid = ofType.filter(c => Date.parse(c.attributes.expirationDate ?? '') > now);
|
||||
const expiring = valid.filter(c => Date.parse(c.attributes.expirationDate!) - now < 30 * 86_400_000);
|
||||
const usable = valid.filter(c => hasKey(c) && !expiring.includes(c)).sort((a, b) => Date.parse(b.attributes.expirationDate!) - Date.parse(a.attributes.expirationDate!));
|
||||
const withoutKey = valid.filter(c => !hasKey(c));
|
||||
const cert = usable[0] ?? null;
|
||||
const why = cert ? `using ${cert.attributes.name ?? cert.attributes.displayName ?? type} (expires ${cert.attributes.expirationDate?.slice(0, 10)})`
|
||||
: withoutKey.length ? `${withoutKey.length} ${type} certificate(s) on the team, but this machine has none of their private keys: a new one is needed (or import the .p12 from the Mac that made it)`
|
||||
: `no valid ${type} certificate`;
|
||||
return { cert, why, usable, withoutKey, expiring };
|
||||
}
|
||||
|
||||
/** Apple caps distribution certificates per team (Apple Distribution: 3 per team). */
|
||||
export const CERT_LIMIT: Partial<Record<CertType, number>> = { DISTRIBUTION: 3, IOS_DISTRIBUTION: 3, DEVELOPER_ID_APPLICATION: 5, DEVELOPER_ID_APPLICATION_G2: 5 };
|
||||
|
||||
export function certificateReq(type: CertType, csr: string): Req {
|
||||
return { method: 'POST', path: '/v1/certificates', note: `create ${type} certificate (key in .storebound/signing, never printed)`,
|
||||
body: { data: { type: 'certificates', attributes: { certificateType: type, csrContent: csr } } } };
|
||||
}
|
||||
|
||||
/** A 403 when creating a Developer ID certificate: only the Account Holder may create them. Explanation or null. */
|
||||
export function explainCertError(err: unknown, type: CertType): string | null {
|
||||
const s = String(err);
|
||||
if (/DEVELOPER_ID/.test(type) && /-> 403/.test(s))
|
||||
return 'Developer ID certificates can only be created by the Account Holder of the team. An API key (even Admin) gets 403 here. '
|
||||
+ 'The Account Holder creates it once in Xcode (Settings > Accounts > Manage Certificates > + > Developer ID Application) or at '
|
||||
+ 'developer.apple.com > Certificates, then exports the .p12 for this machine. App Store builds need DISTRIBUTION instead.';
|
||||
if (/-> 409/.test(s) && /maximum|limit|already/i.test(s))
|
||||
return 'The team has reached its limit of this certificate type. Revoke an unused one at developer.apple.com > Certificates (owner decision: '
|
||||
+ 'builds signed with it keep working, but its profiles become invalid), or use a certificate whose key is on another Mac (export a .p12 there).';
|
||||
if (/-> 403/.test(s)) return 'The API key may not manage certificates: it needs the Admin role (Users and Access > Integrations).';
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface ApiProfile { id: string; attributes: { name?: string; profileType?: string; profileState?: string; expirationDate?: string; uuid?: string; profileContent?: string }; certIds?: string[] }
|
||||
|
||||
export const profileName = (bundleId: string, type: ProfileType, date = new Date()): string =>
|
||||
`storebound ${bundleId} ${type === 'IOS_APP_STORE' ? 'App Store' : type} ${date.toISOString().slice(0, 16).replace('T', ' ')}`;
|
||||
|
||||
export interface ProfilePlan { reuse: ApiProfile | null; create: Req | null; why: string }
|
||||
|
||||
/** Reuse an ACTIVE profile of the type that holds the certificate and is valid for 14 more days; else create one. */
|
||||
export function planProfile(existing: ApiProfile[], o: { bundleId: string; bundleIdId: string; certId: string; type: ProfileType; now?: number }): ProfilePlan {
|
||||
const now = o.now ?? Date.now();
|
||||
const ok = existing.filter(p => p.attributes.profileType === o.type && p.attributes.profileState === 'ACTIVE'
|
||||
&& Date.parse(p.attributes.expirationDate ?? '') - now > 14 * 86_400_000 && (p.certIds ?? []).includes(o.certId))
|
||||
.sort((a, b) => Date.parse(b.attributes.expirationDate!) - Date.parse(a.attributes.expirationDate!));
|
||||
if (ok[0]) return { reuse: ok[0], create: null, why: `profile "${ok[0].attributes.name}" is active (expires ${ok[0].attributes.expirationDate?.slice(0, 10)})` };
|
||||
const stale = existing.filter(p => p.attributes.profileType === o.type);
|
||||
const why = stale.length ? `${stale.length} ${o.type} profile(s), none active with this certificate (states: ${[...new Set(stale.map(p => p.attributes.profileState))].join(', ')})` : `no ${o.type} profile`;
|
||||
return { reuse: null, why, create: {
|
||||
method: 'POST', path: '/v1/profiles', note: `create ${o.type} profile for ${o.bundleId}`,
|
||||
body: { data: { type: 'profiles', attributes: { name: profileName(o.bundleId, o.type, new Date(now)), profileType: o.type },
|
||||
relationships: { bundleId: one('bundleIds', o.bundleIdId), certificates: many('certificates', [o.certId]) } } },
|
||||
} };
|
||||
}
|
||||
|
||||
/** Where provisioning profiles are installed: Xcode 16 and later read ~/Library/Developer/Xcode/UserData/Provisioning
|
||||
* Profiles; older Xcode (and some tools) ~/Library/MobileDevice/Provisioning Profiles. storebound writes both. */
|
||||
export const profileDirs = (home: string): string[] => [join(home, 'Library/Developer/Xcode/UserData/Provisioning Profiles'), join(home, 'Library/MobileDevice/Provisioning Profiles')];
|
||||
|
||||
/** Lines of `security find-identity -v -p codesigning` -> SHA-1 hashes of identities with a private key. */
|
||||
export function parseIdentities(out: string): { sha1: string; name: string }[] {
|
||||
return [...out.matchAll(/^\s*\d+\)\s+([0-9A-F]{40})\s+"([^"]+)"/gm)].map(m => ({ sha1: m[1]!, name: m[2]! }));
|
||||
}
|
||||
|
||||
export interface ExportOptionsInput { teamId: string; style: 'automatic' | 'manual'; profiles?: Record<string, string>; method?: string; uploadSymbols?: boolean; certificate?: string }
|
||||
|
||||
/** ExportOptions.plist for an App Store Connect export (`method` app-store-connect, Xcode 15.3+; "app-store" is the
|
||||
* deprecated name). destination export: storebound uploads the IPA itself (`apple upload`), with the build number it
|
||||
* chose, so Xcode must not change it (manageAppVersionAndBuildNumber false). */
|
||||
export function exportOptions(i: ExportOptionsInput): Record<string, PlistValue> {
|
||||
const o: Record<string, PlistValue> = {
|
||||
method: i.method ?? 'app-store-connect', teamID: i.teamId, signingStyle: i.style, destination: 'export',
|
||||
uploadSymbols: i.uploadSymbols ?? true, manageAppVersionAndBuildNumber: false,
|
||||
};
|
||||
if (i.style === 'manual') {
|
||||
if (!i.profiles || !Object.keys(i.profiles).length) throw new Error('manual signing needs a provisioning profile per bundle id (storebound apple signing ensure)');
|
||||
o.provisioningProfiles = { ...i.profiles };
|
||||
o.signingCertificate = i.certificate ?? 'Apple Distribution';
|
||||
}
|
||||
return o;
|
||||
}
|
||||
229
cli/lib/train.ts
Normal file
229
cli/lib/train.ts
Normal file
|
|
@ -0,0 +1,229 @@
|
|||
// Release trains: one version across the App Store and Google Play, on one track of stages
|
||||
// (build -> testing -> review -> live -> rollout). The desktop app's Releases tab (apps/desktop/src/lib/model.ts
|
||||
// re-exports these) and `storebound release status | plan` (cli/release.ts) share this file, so both show the same
|
||||
// stage for the same store state. Pure; the store reads are `apple status --json` / `play status --json`, turned into
|
||||
// StoreRelease rows by cli/lib/portfolio.ts.
|
||||
import type { ReleaseTrain, StoreRelease } from './desktop-protocol';
|
||||
import { cmpVersion } from './portfolio';
|
||||
import type { Finding } from './validate-rules';
|
||||
|
||||
export { cmpVersion };
|
||||
|
||||
export type Tone = 'ok' | 'warn' | 'bad' | 'info' | 'neutral' | 'accent';
|
||||
|
||||
/** Stages of one version on one store, left to right. */
|
||||
export const STAGES = ['build', 'testing', 'review', 'live', 'rollout'] as const;
|
||||
export type Stage = (typeof STAGES)[number];
|
||||
|
||||
export interface Lane {
|
||||
store: 'ios' | 'android';
|
||||
release: StoreRelease | null;
|
||||
/** Index of the stage it is at (-1: not on this store). */
|
||||
at: number;
|
||||
tone: Tone;
|
||||
/** Rollout share 0-1 when live or rolling out (1 = everyone). */
|
||||
share: number | null;
|
||||
/** The store's state word, for a tooltip. */
|
||||
state: string;
|
||||
}
|
||||
|
||||
/** Where a store release is on the track. Rollout counts as the last stage; a full release fills it. */
|
||||
export function laneOf(store: 'ios' | 'android', r: StoreRelease | null, testflightReached = false): Lane {
|
||||
if (!r) return { store, release: null, at: -1, tone: 'neutral', share: null, state: '' };
|
||||
const base = { store, release: r, state: r.state };
|
||||
switch (r.phase) {
|
||||
case 'draft': return { ...base, at: testflightReached ? 1 : 0, tone: testflightReached ? 'info' : 'neutral', share: null };
|
||||
case 'testing': return { ...base, at: 1, tone: 'info', share: null };
|
||||
case 'review': return { ...base, at: 2, tone: 'warn', share: null };
|
||||
case 'approved': return { ...base, at: 2, tone: 'ok', share: null };
|
||||
case 'rejected': return { ...base, at: 2, tone: 'bad', share: null };
|
||||
case 'live': return { ...base, at: 4, tone: 'ok', share: 1 };
|
||||
case 'rollout': return { ...base, at: 4, tone: 'accent', share: r.fraction ?? null };
|
||||
case 'halted': return { ...base, at: 4, tone: 'bad', share: r.fraction ?? null };
|
||||
default: return { ...base, at: 0, tone: 'neutral', share: null };
|
||||
}
|
||||
}
|
||||
|
||||
/** TestFlight builds as `apple testflight status --json` lists them (only what the lanes need). */
|
||||
export interface BetaBuilds { builds: { version: string | null; internal: string | null; external: string | null }[] }
|
||||
|
||||
/** Both lanes of a train; iOS counts TestFlight as reached when a build of that version is in beta testing. */
|
||||
export function trainLanes(t: ReleaseTrain, tf?: BetaBuilds | null): Lane[] {
|
||||
const inBeta = !!tf?.builds.some(b => b.version === t.version && /IN_BETA_TESTING|BETA_APPROVED|READY_FOR_BETA_TESTING/.test(`${b.internal ?? ''} ${b.external ?? ''}`));
|
||||
return [laneOf('ios', t.ios, inBeta), laneOf('android', t.android)];
|
||||
}
|
||||
|
||||
/** Every distinct version of the store releases, newest first, with both stores' release (best phase per store). */
|
||||
export function versionHistory(all: StoreRelease[]): ReleaseTrain[] {
|
||||
const rank: Record<string, number> = { live: 0, rollout: 1, halted: 2, approved: 3, review: 4, rejected: 5, testing: 6, draft: 7, other: 8 };
|
||||
const versions = [...new Set(all.map(r => r.version).filter((v): v is string => !!v))].sort(cmpVersion).reverse();
|
||||
const best = (store: 'ios' | 'android', v: string) => all.filter(r => r.store === store && r.version === v).sort((a, b) => (rank[a.phase] ?? 9) - (rank[b.phase] ?? 9))[0] ?? null;
|
||||
return versions.map(v => ({ version: v, ios: best('ios', v), android: best('android', v) }));
|
||||
}
|
||||
|
||||
/** On one store: the highest version reaching users (live or rolling out) and the highest version above it. */
|
||||
export function storeNow(all: StoreRelease[], store: 'ios' | 'android'): { now: StoreRelease | null; next: StoreRelease | null } {
|
||||
const rs = all.filter((r): r is StoreRelease & { version: string } => r.store === store && !!r.version);
|
||||
const desc = (a: { version: string }, b: { version: string }) => cmpVersion(b.version, a.version);
|
||||
const now = rs.filter(r => r.phase === 'live' || r.phase === 'rollout' || r.phase === 'halted').sort(desc)[0] ?? null;
|
||||
const next = rs.filter(r => !now || cmpVersion(r.version, now.version) > 0).sort(desc)[0] ?? null;
|
||||
return { now, next };
|
||||
}
|
||||
|
||||
// ---- Terminal view of a lane (release status) ----
|
||||
|
||||
const pctText = (x: number | null): string => (x === null ? '' : `${Math.round(x * 1000) / 10}%`);
|
||||
|
||||
/** "review (approved)", "rollout 20%", "rollout (halted) 5%", "live", "-" for a store without this version. */
|
||||
export function laneText(l: Lane): string {
|
||||
if (!l.release) return '-';
|
||||
const stage = STAGES[l.at] ?? 'build';
|
||||
const p = l.release.phase;
|
||||
if (p === 'live') return 'live'; // the whole track filled: everyone has it
|
||||
const word = p === stage || (p === 'draft' && stage === 'build') || (p === 'other' && stage === 'build') ? stage : `${stage} (${p})`;
|
||||
if (p === 'rollout' || p === 'halted') return `${word} ${pctText(l.share)}`.trim();
|
||||
return word;
|
||||
}
|
||||
|
||||
/** "build > testing > [review] > live > rollout" with the reached stage in brackets. */
|
||||
export function trackText(l: Lane): string {
|
||||
return STAGES.map((s, i) => (i === l.at ? `[${s}]` : s)).join(' > ');
|
||||
}
|
||||
|
||||
// ---- Release plan: what is left for one version on each store, in fix order ----
|
||||
|
||||
export type PlanKind = 'config' | 'store' | 'blocker' | 'owner' | 'wait' | 'warning' | 'done';
|
||||
|
||||
export interface PlanStep {
|
||||
kind: PlanKind;
|
||||
text: string;
|
||||
/** The command or console place that does it. Owner steps name what the owner runs; storebound never does them. */
|
||||
fix?: string;
|
||||
code?: string;
|
||||
}
|
||||
|
||||
export interface StorePlan {
|
||||
store: 'ios' | 'android';
|
||||
/** The store's release of this version (best phase), or null when the version is not on the store yet. */
|
||||
release: StoreRelease | null;
|
||||
lane: Lane;
|
||||
steps: PlanStep[];
|
||||
done: boolean;
|
||||
}
|
||||
|
||||
export interface ReleasePlan {
|
||||
version: string;
|
||||
/** Offline config problems (storebound check): both stores need them fixed first. */
|
||||
shared: PlanStep[];
|
||||
ios: StorePlan | null;
|
||||
android: StorePlan | null;
|
||||
/** Every store the app is on has the version live to everyone. */
|
||||
done: boolean;
|
||||
/** What the plan could not read ("unknown, never false"). */
|
||||
unknown: string[];
|
||||
}
|
||||
|
||||
export interface PlanInput {
|
||||
version: string;
|
||||
platforms: { ios: boolean; android: boolean };
|
||||
/** `storebound check --json`, or null when it did not run. */
|
||||
check: { problems: string[]; warnings: string[] } | null;
|
||||
/** `storebound validate --json` findings, or null when it did not run. Validate reads the editable App Store version
|
||||
* and the Play edit, so its blockers count for a version that is not yet in review. */
|
||||
validate: Finding[] | null;
|
||||
/** Every store release read (`AppStatus.release.all`), or null when the stores were not read. */
|
||||
releases: StoreRelease[] | null;
|
||||
storeErrors?: { ios?: string; android?: string };
|
||||
}
|
||||
|
||||
const STORE_NAME = { ios: 'App Store', android: 'Google Play' } as const;
|
||||
|
||||
/** Phases where the store blockers of `validate` still matter (nothing is submitted yet). */
|
||||
const BEFORE_REVIEW = new Set(['none', 'draft', 'testing', 'rejected', 'other']);
|
||||
|
||||
function storeSteps(store: 'ios' | 'android', v: string, r: StoreRelease | null, findings: Finding[] | null): PlanStep[] {
|
||||
const steps: PlanStep[] = [];
|
||||
const phase = r?.phase ?? 'none';
|
||||
const name = STORE_NAME[store];
|
||||
// 1. the version itself on the store
|
||||
if (!r) {
|
||||
steps.push(store === 'ios'
|
||||
? { kind: 'store', text: `${v} is not on ${name} yet: upload a build (Xcode / Transporter), then create the version with its texts`, fix: `storebound apple next-build; storebound apple listing --version ${v} --build <N> --dry` }
|
||||
: { kind: 'store', text: `${v} is not on ${name} yet: upload the AAB to a testing track`, fix: 'storebound play next-version-code; storebound play release <aab> --internal completed --dry' });
|
||||
} else if (phase === 'rejected') {
|
||||
steps.push({ kind: 'blocker', text: `${v} was rejected (${r.state}): read the reason, fix it, then resubmit`, fix: 'review-rejections skill', code: 'rejected' });
|
||||
}
|
||||
// 2. store blockers (validate, already in fix order), only while nothing is submitted
|
||||
const tag = store === 'ios' ? 'apple' : 'play';
|
||||
const mine = (findings ?? []).filter(f => f.store === tag);
|
||||
if (BEFORE_REVIEW.has(phase)) for (const f of mine.filter(x => x.level === 'blocker')) steps.push({ kind: 'blocker', text: f.msg, ...(f.fix ? { fix: f.fix } : {}), code: f.code });
|
||||
// 3. the next move on the track
|
||||
switch (phase) {
|
||||
case 'none': case 'other':
|
||||
break;
|
||||
case 'draft':
|
||||
steps.push(store === 'ios'
|
||||
? { kind: 'owner', text: `submit ${v} for App Review (owner)`, fix: 'App Store Connect > the version > Add for Review' }
|
||||
: r!.track && r!.track !== 'production'
|
||||
? { kind: 'owner', text: `roll out the ${r!.track} draft of ${v} to its testers (owner)`, fix: `Play Console > Test and release > ${r!.track}` }
|
||||
: { kind: 'owner', text: `send the production draft of ${v} for review (owner)`, fix: 'Play Console > Publishing overview > Send for review' });
|
||||
break;
|
||||
case 'testing':
|
||||
steps.push({ kind: 'owner', text: `promote ${v} from ${r!.track ?? 'testing'} to production (owner)`, fix: 'Play Console > Test and release > Production, or `storebound play release <aab> --production draft` in a terminal' });
|
||||
break;
|
||||
case 'rejected':
|
||||
steps.push({ kind: 'owner', text: `resubmit ${v} after the fix (owner)`, fix: store === 'ios' ? 'App Store Connect > App Review > reply / resubmit' : 'Play Console > Publishing overview' });
|
||||
break;
|
||||
case 'review':
|
||||
steps.push({ kind: 'wait', text: `${v} is in review (${r!.state}); nothing to do until the store answers`, fix: store === 'ios' ? 'storebound apple status --wait-review' : 'storebound play status' });
|
||||
break;
|
||||
case 'approved':
|
||||
steps.push({ kind: 'owner', text: `${v} is approved (${r!.state}): release it (owner)`, fix: store === 'ios' ? 'App Store Connect > Release this version, or `storebound apple release --manual-release` in a terminal' : 'Play Console > Publishing overview' });
|
||||
break;
|
||||
case 'rollout':
|
||||
steps.push({ kind: 'owner', text: `${v} reaches ${pctText(r!.fraction) || 'part'} of users: raise or complete the rollout when health is good (owner)`,
|
||||
fix: store === 'ios' ? 'storebound health; then `storebound apple release --phased complete` in a terminal' : 'storebound health; then `storebound play rollout --fraction <x>` or `--complete` in a terminal' });
|
||||
break;
|
||||
case 'halted':
|
||||
steps.push({ kind: 'owner', text: `the rollout of ${v} is halted at ${pctText(r!.fraction) || '?'}: fix and resume, or ship a new version (owner)`,
|
||||
fix: store === 'ios' ? '`storebound apple release --phased resume` in a terminal' : '`storebound play rollout --resume` in a terminal' });
|
||||
break;
|
||||
case 'live':
|
||||
steps.push({ kind: 'done', text: `${v} is live on ${name} for everyone` });
|
||||
break;
|
||||
}
|
||||
// 4. warnings last (they do not block)
|
||||
if (BEFORE_REVIEW.has(phase)) for (const f of mine.filter(x => x.level === 'warn')) steps.push({ kind: 'warning', text: f.msg, ...(f.fix ? { fix: f.fix } : {}), code: f.code });
|
||||
return steps;
|
||||
}
|
||||
|
||||
/**
|
||||
* What is left for `version` on each store, in fix order: config problems (offline check) first, then per store the
|
||||
* version itself, the store blockers (validate), the next move on the track (owner steps are named, never done) and
|
||||
* the warnings. A store whose state could not be read is listed in `unknown`, never planned as "not there".
|
||||
*/
|
||||
export function releasePlan(i: PlanInput): ReleasePlan {
|
||||
const unknown: string[] = [];
|
||||
const shared: PlanStep[] = [];
|
||||
if (i.check) {
|
||||
for (const p of i.check.problems) shared.push({ kind: 'config', text: p, fix: 'storebound check' });
|
||||
} else unknown.push('config check did not run');
|
||||
const trains = i.releases ? versionHistory(i.releases) : [];
|
||||
const train = trains.find(t => cmpVersion(t.version, i.version) === 0 && t.version.split('.').length === i.version.split('.').length)
|
||||
?? trains.find(t => cmpVersion(t.version, i.version) === 0) ?? null;
|
||||
const one = (store: 'ios' | 'android'): StorePlan | null => {
|
||||
if (!i.platforms[store]) return null;
|
||||
const err = i.storeErrors?.[store];
|
||||
if (!i.releases || err) {
|
||||
unknown.push(`${STORE_NAME[store]} state not read${err ? `: ${err}` : ''}`);
|
||||
return { store, release: null, lane: laneOf(store, null), steps: [{ kind: 'store', text: `${STORE_NAME[store]} could not be read: the plan for this store is unknown`, fix: store === 'ios' ? 'storebound apple status' : 'storebound play status' }], done: false };
|
||||
}
|
||||
const r = train?.[store] ?? null;
|
||||
const steps = storeSteps(store, i.version, r, i.validate);
|
||||
return { store, release: r, lane: laneOf(store, r), steps, done: r?.phase === 'live' };
|
||||
};
|
||||
if (!i.validate) unknown.push('store readiness (validate) did not run');
|
||||
const ios = one('ios'), android = one('android');
|
||||
const stores = [ios, android].filter((x): x is StorePlan => !!x);
|
||||
return { version: i.version, shared, ios, android, done: !shared.length && stores.length > 0 && stores.every(s => s.done), unknown };
|
||||
}
|
||||
122
cli/lib/triage.ts
Normal file
122
cli/lib/triage.ts
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
// Crash and feedback triage, as pure parts: crash signatures from TestFlight crash logs, and clusters by signature,
|
||||
// device and OS version for TestFlight feedback and Google Play vitals error reports. The command (cli/triage.ts)
|
||||
// reads (GET only), groups and prints a table or --json. Tester emails are never read into the output (the feedback
|
||||
// requests ask only for the fields listed below).
|
||||
// Sources (checked October 2026):
|
||||
// TestFlight feedback (App Store Connect API 4.0+, OpenAPI 4.5.1): GET /v1/apps/{id}/betaFeedbackCrashSubmissions,
|
||||
// GET /v1/apps/{id}/betaFeedbackScreenshotSubmissions (createdDate, comment, deviceModel, osVersion, locale,
|
||||
// appPlatform, deviceFamily, build relationship; filter[build], sort=-createdDate, fields[...]),
|
||||
// GET /v1/betaFeedbackCrashSubmissions/{id}/crashLog -> BetaCrashLog.logText.
|
||||
// https://developer.apple.com/documentation/appstoreconnectapi/prerelease-versions-and-beta-testers
|
||||
// Google Play Developer Reporting API v1beta1: errorIssues:search (issues = Play's own clusters: type, cause,
|
||||
// location, errorReportCount, distinctUsers) and errorReports:search (filter "errorIssueId = <id>", interval
|
||||
// hour-aligned UTC, pageSize <= 100; ErrorReport: name, type, reportText, issue, eventTime, deviceModel
|
||||
// {deviceId {buildBrand, buildDevice}, marketingName}, osVersion {apiLevel}, appVersion {versionCode}).
|
||||
// https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.errors.reports/search
|
||||
// https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.errors.reports
|
||||
|
||||
/** Fields read for feedback (no email, no tester relationship). */
|
||||
export const FEEDBACK_FIELDS = 'createdDate,comment,deviceModel,osVersion,locale,appPlatform,deviceFamily,build';
|
||||
export const CRASH_FIELDS = 'createdDate,comment,deviceModel,osVersion,locale,appPlatform,deviceFamily,build,crashLog';
|
||||
|
||||
const cleanFrame = (s: string): string => s.replace(/\s+\+\s+\d+$/, '').replace(/0x[0-9a-f]+/gi, '').replace(/\s+/g, ' ').trim();
|
||||
|
||||
/**
|
||||
* One crash signature from a crash log: "<exception type> @ <first frame of the crashed thread in the app>" (else the
|
||||
* first frame). Handles the text crash report format and the JSON .ips format (header line + body). Pure.
|
||||
*/
|
||||
export function crashSignature(log: string): string {
|
||||
const text = log.trim();
|
||||
// .ips: first line is a JSON header, the rest a JSON body
|
||||
const nl = text.indexOf('\n');
|
||||
if (text.startsWith('{') && nl > 0) {
|
||||
try {
|
||||
const head = JSON.parse(text.slice(0, nl)) as { app_name?: string; name?: string };
|
||||
const body = JSON.parse(text.slice(nl + 1)) as { exception?: { type?: string; signal?: string }; faultingThread?: number; threads?: { triggered?: boolean; frames?: { imageIndex?: number; symbol?: string; imageOffset?: number }[] }[]; usedImages?: { name?: string }[]; procName?: string };
|
||||
const ex = [body.exception?.type, body.exception?.signal].filter(Boolean).join(' ') || 'crash';
|
||||
const t = body.threads?.[body.faultingThread ?? -1] ?? body.threads?.find(x => x.triggered);
|
||||
const app = body.procName ?? head.app_name ?? head.name;
|
||||
const frames = (t?.frames ?? []).map(f => ({ image: body.usedImages?.[f.imageIndex ?? -1]?.name ?? '?', symbol: f.symbol ?? `+${f.imageOffset ?? '?'}` }));
|
||||
const f = frames.find(x => app && x.image === app) ?? frames[0];
|
||||
return f ? `${ex} @ ${f.image} ${cleanFrame(f.symbol)}` : ex;
|
||||
} catch { /* fall through to the text format */ }
|
||||
}
|
||||
const ex = /^Exception Type:\s*(.+)$/m.exec(text)?.[1]?.trim() ?? /^Termination Reason:\s*(.+)$/m.exec(text)?.[1]?.trim() ?? 'crash';
|
||||
const proc = /^Process:\s*([^\s\[]+)/m.exec(text)?.[1];
|
||||
const crashed = /^Crashed Thread:\s*(\d+)/m.exec(text)?.[1];
|
||||
const lines = text.split(/\r?\n/);
|
||||
const at = lines.findIndex(l => (crashed !== undefined ? new RegExp(`^Thread ${crashed} Crashed`) : /^Thread \d+ Crashed/).test(l));
|
||||
const block: string[] = [];
|
||||
if (at >= 0) for (const l of lines.slice(at + 1)) { if (!l.trim()) break; block.push(l); }
|
||||
const frames = block.map(l => /^\d+\s+(\S+)\s+0x[0-9a-f]+\s+(.+)$/i.exec(l.trim())).filter((m): m is RegExpExecArray => !!m).map(m => ({ image: m[1]!, symbol: m[2]! }));
|
||||
const f = frames.find(x => proc && x.image === proc) ?? frames[0];
|
||||
return f ? `${ex} @ ${f.image} ${cleanFrame(f.symbol)}` : ex;
|
||||
}
|
||||
|
||||
export interface TriageItem { signature: string; device: string; os: string; build?: string; date?: string; comment?: string }
|
||||
export interface Cluster { signature: string; count: number; devices: [string, number][]; os: [string, number][]; builds: [string, number][]; first?: string; last?: string; comments?: string[] }
|
||||
|
||||
const top = (xs: string[], n = 3): [string, number][] => {
|
||||
const m = new Map<string, number>();
|
||||
for (const x of xs) m.set(x, (m.get(x) ?? 0) + 1);
|
||||
return [...m.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, n);
|
||||
};
|
||||
|
||||
/** Items -> clusters by signature, most frequent first, each with its top devices, OS versions and builds. Pure. */
|
||||
export function cluster(items: TriageItem[], o: { comments?: number } = {}): Cluster[] {
|
||||
const by = new Map<string, TriageItem[]>();
|
||||
for (const i of items) by.set(i.signature, [...(by.get(i.signature) ?? []), i]);
|
||||
return [...by.entries()].map(([signature, xs]) => {
|
||||
const dates = xs.map(x => x.date ?? '').filter(Boolean).sort();
|
||||
const comments = o.comments ? xs.map(x => (x.comment ?? '').replace(/\s+/g, ' ').trim()).filter(Boolean).slice(0, o.comments).map(c => c.slice(0, 120)) : undefined;
|
||||
return { signature, count: xs.length, devices: top(xs.map(x => x.device)), os: top(xs.map(x => x.os)), builds: top(xs.map(x => x.build ?? '?')),
|
||||
...(dates.length ? { first: dates[0], last: dates.at(-1) } : {}), ...(comments?.length ? { comments } : {}) };
|
||||
}).sort((a, b) => b.count - a.count || a.signature.localeCompare(b.signature));
|
||||
}
|
||||
|
||||
/** TestFlight feedback (crash or screenshot submissions) -> items. Screenshot feedback has no crash: its signature is
|
||||
* "feedback". Pure. */
|
||||
export function feedbackItems(subs: { id: string; attributes?: Record<string, unknown>; relationships?: { build?: { data?: { id: string } | null } } }[], builds: Map<string, string>, signatures: Map<string, string> = new Map()): TriageItem[] {
|
||||
return subs.map(s => {
|
||||
const a = s.attributes ?? {};
|
||||
return { signature: signatures.get(s.id) ?? 'feedback', device: String(a.deviceModel ?? '?'), os: String(a.osVersion ?? '?'),
|
||||
build: builds.get(s.relationships?.build?.data?.id ?? '') ?? undefined, date: typeof a.createdDate === 'string' ? a.createdDate : undefined,
|
||||
comment: typeof a.comment === 'string' ? a.comment : undefined };
|
||||
});
|
||||
}
|
||||
|
||||
export interface PlayIssueRef { id: string; type: string; cause: string; location: string; reports: number; users: number }
|
||||
|
||||
/** errorIssues:search -> issue refs with their id (the last part of `name`). Pure. */
|
||||
export function playIssues(resp: { errorIssues?: { name?: string; type?: string; cause?: string; location?: string; errorReportCount?: string; distinctUsers?: string }[] }): PlayIssueRef[] {
|
||||
return (resp.errorIssues ?? []).map(i => ({ id: (i.name ?? '').split('/').pop() ?? '', type: i.type === 'APPLICATION_NOT_RESPONDING' ? 'ANR' : i.type ?? '?', cause: i.cause ?? '',
|
||||
location: i.location ?? '', reports: Number(i.errorReportCount ?? 0), users: Number(i.distinctUsers ?? 0) })).filter(i => i.id);
|
||||
}
|
||||
|
||||
/** errorReports:search -> items with the signature of their issue. Pure. */
|
||||
export function playReportItems(resp: { errorReports?: { issue?: string; type?: string; eventTime?: string; deviceModel?: { marketingName?: string; deviceId?: { buildBrand?: string; buildDevice?: string } }; osVersion?: { apiLevel?: string }; appVersion?: { versionCode?: string } }[] }, issues: PlayIssueRef[]): TriageItem[] {
|
||||
const sig = new Map(issues.map(i => [i.id, `${i.type} ${i.cause}${i.location ? ` @ ${i.location}` : ''}`] as const));
|
||||
return (resp.errorReports ?? []).map(r => {
|
||||
const id = (r.issue ?? '').split('/').pop() ?? '';
|
||||
const dev = r.deviceModel?.marketingName || [r.deviceModel?.deviceId?.buildBrand, r.deviceModel?.deviceId?.buildDevice].filter(Boolean).join('/') || '?';
|
||||
return { signature: sig.get(id) ?? `${r.type ?? '?'} issue ${id}`, device: dev, os: r.osVersion?.apiLevel ? `API ${r.osVersion.apiLevel}` : '?', build: r.appVersion?.versionCode, date: r.eventTime };
|
||||
});
|
||||
}
|
||||
|
||||
/** errorReports:search query string for one issue (UTC, hour-aligned interval, newest window). Pure. */
|
||||
export function reportsQuery(issueId: string, start: Date, end: Date, pageSize = 100): string {
|
||||
const p = new URLSearchParams();
|
||||
for (const [k, d] of [['start', start], ['end', end]] as const) {
|
||||
p.set(`interval.${k}Time.year`, String(d.getUTCFullYear())); p.set(`interval.${k}Time.month`, String(d.getUTCMonth() + 1)); p.set(`interval.${k}Time.day`, String(d.getUTCDate()));
|
||||
p.set(`interval.${k}Time.hours`, '0'); p.set(`interval.${k}Time.timeZone.id`, 'UTC');
|
||||
}
|
||||
p.set('filter', `errorIssueId = ${issueId}`);
|
||||
p.set('pageSize', String(Math.min(100, pageSize)));
|
||||
return p.toString();
|
||||
}
|
||||
|
||||
/** Table rows for a cluster list. Pure. */
|
||||
export function clusterRows(cs: Cluster[]): (string | number)[][] {
|
||||
const fmt = (xs: [string, number][]) => xs.map(([k, n]) => `${k} (${n})`).join(', ');
|
||||
return cs.map(c => [c.count, c.signature.slice(0, 70), fmt(c.devices), fmt(c.os), fmt(c.builds)]);
|
||||
}
|
||||
|
|
@ -1,5 +1,7 @@
|
|||
// User-facing release notes from commit subjects, and writing them into the two listing files. Pure.
|
||||
// The draft is a starting point for a human: commit messages are written for developers, notes are for users.
|
||||
import type { Language } from './config';
|
||||
import { playCodes } from './config';
|
||||
import { len, PLAY_LIMITS } from './copy';
|
||||
|
||||
export const NOTES_LIMITS = { play: PLAY_LIMITS.whatsNew, apple: 4000 } as const;
|
||||
|
|
@ -98,3 +100,69 @@ export function setAppleWhatsNew(md: string, locale: string, text: string): { md
|
|||
});
|
||||
return { md: out.join(''), changed };
|
||||
}
|
||||
|
||||
// ---- many languages: one file per language, translated by your agent (whats-new skill) or a provider hook ----
|
||||
// Limits per store (what each store enforces for the release-notes field):
|
||||
// Google Play "What's new" (edits.tracks releaseNotes / Play Console): 500 characters per language.
|
||||
// App Store "What's New in This Version" (appStoreVersionLocalizations.whatsNew): 4000 characters.
|
||||
|
||||
export type NotesStatus = 'source' | 'translate' | 'translated';
|
||||
export interface NotesFile { lang: string; source: string; status: NotesStatus; text: string }
|
||||
|
||||
const HEAD_RE = /^<!--\s*whats-new\s+lang=(\S+)\s+source=(\S+)\s+status=(source|translate|translated)\s*-->\n?/;
|
||||
|
||||
/** One language file: a header line the tools read, then the text. Pure. */
|
||||
export function notesFileText(f: NotesFile): string {
|
||||
return `<!-- whats-new lang=${f.lang} source=${f.source} status=${f.status} -->\n${f.text.trim()}\n`;
|
||||
}
|
||||
|
||||
/** Parses a language file; a file without the header is taken as translated text. Pure. */
|
||||
export function parseNotesFile(text: string, lang: string): NotesFile {
|
||||
const m = HEAD_RE.exec(text);
|
||||
if (!m) return { lang, source: '', status: 'translated', text: text.trim() };
|
||||
return { lang: m[1]!, source: m[2]!, status: m[3] as NotesStatus, text: text.slice(m[0].length).trim() };
|
||||
}
|
||||
|
||||
/** --languages values (config language ids, App Store locales or Play codes) -> language entries, in that order. */
|
||||
export function resolveLanguages(langs: Language[], wanted: string[]): Language[] {
|
||||
const out: Language[] = [];
|
||||
for (const w of wanted) {
|
||||
const l = langs.find(x => x.id === w) ?? langs.find(x => x.apple === w) ?? langs.find(x => playCodes(x).includes(w));
|
||||
if (!l) throw new Error(`--languages: "${w}" is not a language of the config (ids: ${langs.map(x => x.id).join(', ')})`);
|
||||
if (!out.includes(l)) out.push(l);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface LangCheck { lang: string; chars: number; play?: { limit: number; ok: boolean }; apple?: { limit: number; ok: boolean }; problems: string[] }
|
||||
|
||||
/** Limits and wording of one language's notes, for the stores that language is listed on. Pure. */
|
||||
export function checkLanguageNotes(l: Language, f: NotesFile, sourceText?: string): LangCheck {
|
||||
const chars = len(f.text);
|
||||
const c: LangCheck = { lang: l.id, chars, problems: [] };
|
||||
if (playCodes(l).length) { c.play = { limit: NOTES_LIMITS.play, ok: chars <= NOTES_LIMITS.play }; if (!c.play.ok) c.problems.push(`Google Play: ${chars} > ${NOTES_LIMITS.play} characters`); }
|
||||
if (l.apple) { c.apple = { limit: NOTES_LIMITS.apple, ok: chars <= NOTES_LIMITS.apple }; if (!c.apple.ok) c.problems.push(`App Store: ${chars} > ${NOTES_LIMITS.apple} characters`); }
|
||||
if (!f.text) c.problems.push('empty');
|
||||
if (f.status === 'translate') c.problems.push('not translated yet (status=translate)');
|
||||
else if (sourceText !== undefined && f.status !== 'source' && f.text === sourceText.trim()) c.problems.push('identical to the source language: translate it');
|
||||
const hook = f.text.split('\n')[0] ?? '';
|
||||
if (len(hook) > HOOK_CHARS) c.problems.push(`first line is ${len(hook)} characters; about ${HOOK_CHARS} show before "more"`);
|
||||
return c;
|
||||
}
|
||||
|
||||
/** Writes one language's notes into the listing files (every Play code of the language, its App Store locale). Pure. */
|
||||
export function applyLanguageNotes(md: { play?: string; apple?: string }, l: Language, text: string): { play?: string; apple?: string; changed: string[] } {
|
||||
const out: { play?: string; apple?: string; changed: string[] } = { ...md, changed: [] };
|
||||
if (md.play !== undefined) for (const code of playCodes(l)) {
|
||||
const r = setPlayWhatsNew(out.play!, code, text);
|
||||
out.play = r.md;
|
||||
out.changed.push(...r.changed.map(x => `play:${x}`));
|
||||
}
|
||||
if (md.apple !== undefined && l.apple) {
|
||||
const r = setAppleWhatsNew(out.apple!, l.apple, text);
|
||||
out.apple = r.md;
|
||||
out.changed.push(...r.changed.map(x => `apple:${x}`));
|
||||
}
|
||||
out.changed = [...new Set(out.changed)];
|
||||
return out;
|
||||
}
|
||||
|
|
|
|||
404
cli/lib/workspace.ts
Normal file
404
cli/lib/workspace.ts
Normal file
|
|
@ -0,0 +1,404 @@
|
|||
// The multi-app workspace: one storebound.workspace.json (or .ts) in a folder above many app folders. It names the
|
||||
// app folders (globs allowed), the studios and their store accounts (by credential profile, never a secret), an
|
||||
// ignore list and the owner's pairing overrides. It is the same model as the desktop app's state (studios, accounts,
|
||||
// projects, overrides: apps/desktop/src-tauri/src/store.rs, workspace.rs), so `storebound ws desktop export | import`
|
||||
// moves it both ways. Pairing of store apps with folders is cli/lib/identity.ts, shared with the desktop.
|
||||
//
|
||||
// {
|
||||
// "apps": ["apps/*", { "path": "games/puzzle", "apple": "acme-apple", "play": "acme-play" }],
|
||||
// "studios": [{ "name": "Acme Games", "color": "indigo", "apps": ["games/*"],
|
||||
// "accounts": [{ "store": "apple", "profile": "acme-apple" }, { "store": "play", "profile": "acme-play" }] }],
|
||||
// "accounts": [{ "store": "play", "profile": "solo-play" }],
|
||||
// "ignore": ["apps/old-*", "app:ios:<account id>:<app id>", "account:solo-play"],
|
||||
// "overrides": { "pairs": [], "unpairs": [], "links": [], "appStudio": [] },
|
||||
// "concurrency": 4
|
||||
// }
|
||||
import { createHash } from 'node:crypto';
|
||||
import { existsSync, readFileSync, statSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
||||
import { CONFIG_NAMES } from './config';
|
||||
import { PROFILE_RE } from './credentials';
|
||||
import type { StoreApp } from './desktop-protocol';
|
||||
import { type IdProject, NO_OVERRIDES, type Overrides, type Pair } from './identity';
|
||||
|
||||
export const WORKSPACE_NAMES = ['storebound.workspace.json', 'storebound.workspace.ts', 'storebound.workspace.js'];
|
||||
/** Colours a studio can carry: the desktop's set (workspace.rs STUDIO_COLORS). */
|
||||
export const STUDIO_COLORS = ['indigo', 'violet', 'rose', 'amber', 'emerald', 'teal', 'sky', 'slate'] as const;
|
||||
export type StudioColor = (typeof STUDIO_COLORS)[number];
|
||||
export type Store = 'apple' | 'play';
|
||||
|
||||
export interface WsAccount {
|
||||
store: Store;
|
||||
/** Credential profile: ~/.storebound/credentials/<profile>.json or env STOREBOUND_PROFILE_<NAME>_* */
|
||||
profile: string;
|
||||
label?: string;
|
||||
/** The desktop's account id (16 hex) when it came from there; else derived from store + profile. */
|
||||
id?: string;
|
||||
}
|
||||
export interface WsStudio { id?: string; name: string; color?: StudioColor; accounts?: WsAccount[]; apps?: string[] }
|
||||
export interface WsAppEntry { path: string; name?: string; apple?: string; play?: string }
|
||||
/** Pairing overrides as the desktop keeps them; a project is named by its folder (relative to the workspace). */
|
||||
export interface WsOverrides { pairs?: Pair[]; unpairs?: Pair[]; links?: { key: string; project: string }[]; appStudio?: { key: string; studio: string }[] }
|
||||
export interface Workspace {
|
||||
apps: (string | WsAppEntry)[];
|
||||
studios?: WsStudio[];
|
||||
accounts?: WsAccount[];
|
||||
ignore?: string[];
|
||||
overrides?: WsOverrides;
|
||||
/** Apps read at the same time (1-8, default 4: the desktop's default). */
|
||||
concurrency?: number;
|
||||
}
|
||||
|
||||
/** For a storebound.workspace.ts: `export default defineWorkspace({ ... })`. */
|
||||
export const defineWorkspace = (w: Workspace): Workspace => w;
|
||||
|
||||
export interface LoadedWorkspace { file: string; root: string; ws: Workspace }
|
||||
|
||||
/** Resolved account: the workspace entry with its id and studio. */
|
||||
export interface Account extends WsAccount { id: string; studio: string | null }
|
||||
export interface Studio { id: string; name: string; color: StudioColor }
|
||||
/** One app folder of the workspace. `id` is its path relative to the workspace (forward slashes). */
|
||||
export interface AppFolder extends IdProject { rel: string; ignored: boolean; studio: string | null; appleProfile: string | null; playProfile: string | null }
|
||||
|
||||
const hex16 = (s: string): string => createHash('sha256').update(s).digest('hex').slice(0, 16);
|
||||
export const accountId = (a: WsAccount): string => (a.id && /^[0-9a-f]{16}$/.test(a.id) ? a.id : hex16(`${a.store}:${a.profile}`));
|
||||
export const slug = (s: string): string => s.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 48) || 'studio';
|
||||
export const studioId = (s: WsStudio): string => s.id || slug(s.name);
|
||||
const posix = (p: string): string => p.split(sep).join('/');
|
||||
|
||||
/** Finds the workspace file in `from` or a folder above it. */
|
||||
export function findWorkspace(from: string, explicit?: string): string | null {
|
||||
if (explicit) {
|
||||
const p = resolve(from, explicit);
|
||||
if (existsSync(p) && statSync(p).isDirectory()) return WORKSPACE_NAMES.map(n => join(p, n)).find(existsSync) ?? null;
|
||||
return existsSync(p) ? p : null;
|
||||
}
|
||||
let d = resolve(from);
|
||||
for (;;) {
|
||||
const hit = WORKSPACE_NAMES.map(n => join(d, n)).find(existsSync);
|
||||
if (hit) return hit;
|
||||
const up = resolve(d, '..');
|
||||
if (up === d) return null;
|
||||
d = up;
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadWorkspace(from: string, explicit?: string): Promise<LoadedWorkspace> {
|
||||
const file = findWorkspace(from, explicit);
|
||||
if (!file) throw new Error(`no storebound.workspace.json in ${from} or above (storebound ws init creates one)`);
|
||||
let raw: unknown;
|
||||
if (file.endsWith('.json')) {
|
||||
try { raw = JSON.parse(readFileSync(file, 'utf8')); } catch (e) { throw new Error(`${file}: ${(e as Error).message}`); }
|
||||
} else raw = ((await import(file)) as { default?: unknown }).default;
|
||||
const problems = checkWorkspace(raw);
|
||||
if (problems.length) throw new Error(`${file}:\n ${problems.join('\n ')}`);
|
||||
return { file, root: resolve(file, '..'), ws: raw as Workspace };
|
||||
}
|
||||
|
||||
const ACCOUNT_KEYS = ['store', 'profile', 'label', 'id'];
|
||||
|
||||
/** Problems of a workspace file (empty = fine). Secrets are refused: only profile names belong here. */
|
||||
export function checkWorkspace(raw: unknown): string[] {
|
||||
const e: string[] = [];
|
||||
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return ['not an object'];
|
||||
const w = raw as Record<string, unknown>;
|
||||
const known = ['$schema', 'apps', 'studios', 'accounts', 'ignore', 'overrides', 'concurrency'];
|
||||
for (const k of Object.keys(w)) if (!known.includes(k)) e.push(`${k}: unknown field (${known.slice(1).join(', ')})`);
|
||||
if (!Array.isArray(w.apps)) e.push('apps: a list of app folders or globs ("apps/*")');
|
||||
else w.apps.forEach((a, i) => {
|
||||
if (typeof a === 'string') { if (!a.trim()) e.push(`apps[${i}]: empty`); return; }
|
||||
if (typeof a !== 'object' || a === null || typeof (a as WsAppEntry).path !== 'string') { e.push(`apps[${i}]: a path or { path, name?, apple?, play? }`); return; }
|
||||
for (const k of Object.keys(a)) if (!['path', 'name', 'apple', 'play'].includes(k)) e.push(`apps[${i}].${k}: unknown`);
|
||||
for (const s of ['apple', 'play'] as const) { const p = (a as WsAppEntry)[s]; if (p !== undefined && (typeof p !== 'string' || !PROFILE_RE.test(p))) e.push(`apps[${i}].${s}: a credential profile name`); }
|
||||
});
|
||||
const account = (a: unknown, where: string) => {
|
||||
if (typeof a !== 'object' || a === null) { e.push(`${where}: { store, profile }`); return; }
|
||||
const o = a as Record<string, unknown>;
|
||||
for (const k of Object.keys(o)) if (!ACCOUNT_KEYS.includes(k)) e.push(`${where}.${k}: unknown (secrets never go here: put them in the credential profile)`);
|
||||
if (o.store !== 'apple' && o.store !== 'play') e.push(`${where}.store: apple or play`);
|
||||
if (typeof o.profile !== 'string' || !PROFILE_RE.test(o.profile)) e.push(`${where}.profile: a credential profile name (letters, digits, . _ -)`);
|
||||
if (o.id !== undefined && (typeof o.id !== 'string' || !/^[0-9a-f]{16}$/.test(o.id))) e.push(`${where}.id: 16 hex characters (the desktop's account id)`);
|
||||
if (o.label !== undefined && (typeof o.label !== 'string' || o.label.length > 60)) e.push(`${where}.label: up to 60 characters`);
|
||||
};
|
||||
if (w.accounts !== undefined) { if (!Array.isArray(w.accounts)) e.push('accounts: a list'); else w.accounts.forEach((a, i) => account(a, `accounts[${i}]`)); }
|
||||
if (w.studios !== undefined) {
|
||||
if (!Array.isArray(w.studios)) e.push('studios: a list');
|
||||
else w.studios.forEach((s, i) => {
|
||||
if (typeof s !== 'object' || s === null) { e.push(`studios[${i}]: { name, color?, accounts?, apps? }`); return; }
|
||||
const o = s as Record<string, unknown>;
|
||||
for (const k of Object.keys(o)) if (!['id', 'name', 'color', 'accounts', 'apps'].includes(k)) e.push(`studios[${i}].${k}: unknown`);
|
||||
if (typeof o.name !== 'string' || !o.name.trim() || o.name.length > 48) e.push(`studios[${i}].name: 1 to 48 characters`);
|
||||
if (o.color !== undefined && !(STUDIO_COLORS as readonly unknown[]).includes(o.color)) e.push(`studios[${i}].color: one of ${STUDIO_COLORS.join(', ')}`);
|
||||
if (o.accounts !== undefined) { if (!Array.isArray(o.accounts)) e.push(`studios[${i}].accounts: a list`); else o.accounts.forEach((a, j) => account(a, `studios[${i}].accounts[${j}]`)); }
|
||||
if (o.apps !== undefined && (!Array.isArray(o.apps) || o.apps.some(x => typeof x !== 'string'))) e.push(`studios[${i}].apps: a list of folder globs`);
|
||||
});
|
||||
}
|
||||
if (w.ignore !== undefined && (!Array.isArray(w.ignore) || w.ignore.some(x => typeof x !== 'string'))) e.push('ignore: a list of folder globs, app:<store app key> or account:<profile>');
|
||||
if (w.concurrency !== undefined && !(Number.isInteger(w.concurrency) && (w.concurrency as number) >= 1 && (w.concurrency as number) <= 8)) e.push('concurrency: 1 to 8');
|
||||
if (w.overrides !== undefined && (typeof w.overrides !== 'object' || w.overrides === null || Array.isArray(w.overrides))) e.push('overrides: { pairs, unpairs, links, appStudio }');
|
||||
// duplicate profiles per store would make two accounts with one id
|
||||
const all = [...((w.accounts as WsAccount[] | undefined) ?? []), ...(((w.studios as WsStudio[] | undefined) ?? []).flatMap(s => s?.accounts ?? []))];
|
||||
const seen = new Set<string>();
|
||||
for (const a of all) { const k = `${a?.store}:${a?.profile}`; if (seen.has(k)) e.push(`account ${k}: listed twice`); seen.add(k); }
|
||||
return e;
|
||||
}
|
||||
|
||||
/** Every account of the workspace (studio accounts and the loose ones) with ids and studios. */
|
||||
export function accountsOf(ws: Workspace): Account[] {
|
||||
const out: Account[] = [];
|
||||
for (const s of ws.studios ?? []) for (const a of s.accounts ?? []) out.push({ ...a, id: accountId(a), studio: studioId(s) });
|
||||
for (const a of ws.accounts ?? []) out.push({ ...a, id: accountId(a), studio: null });
|
||||
return out;
|
||||
}
|
||||
|
||||
export const studiosOf = (ws: Workspace): Studio[] =>
|
||||
(ws.studios ?? []).map((s, i) => ({ id: studioId(s), name: s.name, color: s.color ?? STUDIO_COLORS[i % STUDIO_COLORS.length]! }));
|
||||
|
||||
const isGlob = (p: string): boolean => /[*?[{]/.test(p);
|
||||
const matchAny = (globs: string[], rel: string): boolean => globs.some(g => new Bun.Glob(g.replace(/\/+$/, '')).match(rel));
|
||||
const hasConfig = (dir: string): boolean => CONFIG_NAMES.some(n => existsSync(join(dir, n)));
|
||||
|
||||
/**
|
||||
* The app folders: globs expanded (folders with a storebound config only; node_modules and dot folders skipped), the
|
||||
* ignore globs applied (kept with `ignored: true`, so `ws list --all` can show them), accounts and studio resolved:
|
||||
* an entry's own profiles > the single account of that store in the studio whose `apps` globs match > the single
|
||||
* account of that store in the workspace > none (the folder's own credentials, env or .storebound/).
|
||||
*/
|
||||
export function resolveApps(l: LoadedWorkspace): { apps: AppFolder[]; warnings: string[] } {
|
||||
const { root, ws } = l;
|
||||
const warnings: string[] = [];
|
||||
const found = new Map<string, WsAppEntry>();
|
||||
for (const a of ws.apps) {
|
||||
const entry: WsAppEntry = typeof a === 'string' ? { path: a } : a;
|
||||
const p = entry.path.replace(/^~(?=\/)/, homedir());
|
||||
if (isGlob(p)) {
|
||||
const base = isAbsolute(p) ? '/' : root;
|
||||
const pattern = isAbsolute(p) ? p.slice(1) : p;
|
||||
let hits = 0;
|
||||
for (const m of new Bun.Glob(pattern.replace(/\/+$/, '')).scanSync({ cwd: base, onlyFiles: false, dot: false })) {
|
||||
if (/(^|\/)(node_modules|\.git)(\/|$)/.test(m)) continue;
|
||||
const dir = resolve(base, m);
|
||||
try { if (!statSync(dir).isDirectory()) continue; } catch { continue; }
|
||||
if (!hasConfig(dir)) continue;
|
||||
hits++;
|
||||
if (!found.has(dir)) found.set(dir, { ...entry, path: dir });
|
||||
}
|
||||
if (!hits) warnings.push(`${entry.path}: no app folder (with a storebound config) matches`);
|
||||
} else {
|
||||
const dir = resolve(root, p);
|
||||
if (!existsSync(dir)) { warnings.push(`${entry.path}: folder not found`); continue; }
|
||||
if (!hasConfig(dir)) { warnings.push(`${entry.path}: no storebound.config.ts in it`); continue; }
|
||||
found.set(dir, { ...found.get(dir), ...entry, path: dir });
|
||||
}
|
||||
}
|
||||
const accounts = accountsOf(ws);
|
||||
const byProfile = (store: Store, profile: string | undefined) => (profile ? accounts.find(a => a.store === store && a.profile === profile) : undefined);
|
||||
const ignoreGlobs = (ws.ignore ?? []).filter(x => !/^(app|account|project):/.test(x));
|
||||
const apps: AppFolder[] = [];
|
||||
for (const [dir, entry] of found) {
|
||||
const rel = posix(relative(root, dir)) || '.';
|
||||
const studio = (ws.studios ?? []).find(s => matchAny(s.apps ?? [], rel)) ?? null;
|
||||
const pick = (store: Store): WsAccount | null => {
|
||||
const named = entry[store];
|
||||
// a profile the workspace does not list is still usable (its id is derived the same way)
|
||||
if (named) return byProfile(store, named) ?? { store, profile: named };
|
||||
const inStudio = (studio?.accounts ?? []).filter(a => a.store === store);
|
||||
if (inStudio.length === 1) return inStudio[0]!;
|
||||
const all = accounts.filter(a => a.store === store);
|
||||
return all.length === 1 ? all[0]! : null;
|
||||
};
|
||||
const apple = pick('apple'), play = pick('play');
|
||||
apps.push({ id: rel, rel, path: dir, name: entry.name ?? basename(dir), appleAccount: apple ? accountId(apple) : null, playAccount: play ? accountId(play) : null,
|
||||
appleProfile: apple?.profile ?? null, playProfile: play?.profile ?? null,
|
||||
ignored: matchAny(ignoreGlobs, rel) || (ws.ignore ?? []).includes(`project:${rel}`), studio: studio ? studioId(studio) : null });
|
||||
}
|
||||
apps.sort((a, b) => a.rel.localeCompare(b.rel));
|
||||
return { apps, warnings };
|
||||
}
|
||||
|
||||
/** Desktop-style overrides of the workspace: folder studios from `studios[].apps`, ignore keys with account ids. */
|
||||
export function overridesOf(ws: Workspace, apps: AppFolder[]): Overrides {
|
||||
const o = ws.overrides ?? {};
|
||||
const accounts = accountsOf(ws);
|
||||
const explicit = o.appStudio ?? [];
|
||||
const fromGlobs = apps.filter(a => a.studio && !explicit.some(x => x.key === `project:${a.id}`)).map(a => ({ key: `project:${a.id}`, studio: a.studio! }));
|
||||
const ignored: string[] = [];
|
||||
for (const x of ws.ignore ?? []) {
|
||||
if (x.startsWith('app:') || x.startsWith('project:')) ignored.push(x);
|
||||
else if (x.startsWith('account:')) {
|
||||
const p = x.slice(8);
|
||||
const hit = accounts.filter(a => a.profile === p || a.id === p);
|
||||
ignored.push(...(hit.length ? hit.map(a => `account:${a.id}`) : [x]));
|
||||
}
|
||||
}
|
||||
for (const a of apps) if (a.ignored && !ignored.includes(`project:${a.id}`)) ignored.push(`project:${a.id}`);
|
||||
return { ...NO_OVERRIDES, pairs: o.pairs ?? [], unpairs: o.unpairs ?? [], links: o.links ?? [], appStudio: [...explicit, ...fromGlobs], ignored };
|
||||
}
|
||||
|
||||
/** Filters apps by `--apps a,b` (folder, folder name or app name, case-insensitive; globs allowed). */
|
||||
export function selectApps<T extends { rel: string; name: string }>(apps: T[], names: string[]): { picked: T[]; unknown: string[] } {
|
||||
if (!names.length) return { picked: apps, unknown: [] };
|
||||
const unknown: string[] = [];
|
||||
const picked = new Set<T>();
|
||||
for (const n of names) {
|
||||
const lc = n.toLowerCase();
|
||||
const hits = apps.filter(a => a.rel.toLowerCase() === lc || basename(a.rel).toLowerCase() === lc || a.name.toLowerCase() === lc || (isGlob(n) && new Bun.Glob(n).match(a.rel)));
|
||||
if (!hits.length) unknown.push(n);
|
||||
hits.forEach(h => picked.add(h));
|
||||
}
|
||||
return { picked: apps.filter(a => picked.has(a)), unknown };
|
||||
}
|
||||
|
||||
// ---- Store app lists (ws apps import): a local cache, gitignored with the rest of .storebound/ ----
|
||||
|
||||
export interface StoreAppsCache { profile: string; store: Store; account: string; at: string; apps: StoreApp[] }
|
||||
|
||||
export const cacheDir = (root: string): string => join(root, '.storebound', 'workspace');
|
||||
export const cacheFile = (root: string, a: { store: Store; profile: string }): string => join(cacheDir(root), `apps-${a.store}-${a.profile}.json`);
|
||||
|
||||
export function readStoreApps(root: string, accounts: Account[]): { account: string; apps: StoreApp[]; at: string }[] {
|
||||
const out: { account: string; apps: StoreApp[]; at: string }[] = [];
|
||||
for (const a of accounts) {
|
||||
const f = cacheFile(root, a);
|
||||
if (!existsSync(f)) continue;
|
||||
try {
|
||||
const c = JSON.parse(readFileSync(f, 'utf8')) as StoreAppsCache;
|
||||
if (Array.isArray(c.apps)) out.push({ account: a.id, apps: c.apps, at: c.at });
|
||||
} catch { /* a broken cache is a cache miss */ }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- The desktop's state (state.json in its data folder) <-> the workspace ----
|
||||
|
||||
export interface DesktopProject { id: string; path: string; name: string; playAccount: string | null; appleAccount: string | null; added: string }
|
||||
export interface DesktopAccount { id: string; label: string; kind: Store; created: string; studio: string | null }
|
||||
export interface DesktopStudio { id: string; name: string; color: string; logo: string | null; created: string }
|
||||
export interface DesktopState {
|
||||
version: number;
|
||||
projects: DesktopProject[];
|
||||
accounts: DesktopAccount[];
|
||||
studios: DesktopStudio[];
|
||||
overrides: Overrides;
|
||||
settings?: unknown;
|
||||
}
|
||||
|
||||
/** Where the desktop app keeps state.json (Tauri app data folder of dev.storebound.desktop). */
|
||||
export function desktopStateFile(env: Record<string, string | undefined> = process.env, platform = process.platform): string {
|
||||
if (env.STOREBOUND_DESKTOP_DATA) return join(env.STOREBOUND_DESKTOP_DATA, 'state.json');
|
||||
const id = 'dev.storebound.desktop';
|
||||
if (platform === 'darwin') return join(homedir(), 'Library', 'Application Support', id, 'state.json');
|
||||
if (platform === 'win32') return join(env.APPDATA ?? join(homedir(), 'AppData', 'Roaming'), id, 'state.json');
|
||||
return join(env.XDG_DATA_HOME ?? join(homedir(), '.local', 'share'), id, 'state.json');
|
||||
}
|
||||
|
||||
/** The desktop's project id of a folder: stable per absolute path (16 hex, like the desktop's own ids). */
|
||||
export const desktopProjectId = (absPath: string): string => hex16(`project:${absPath}`);
|
||||
|
||||
/**
|
||||
* Workspace -> desktop state (format 2). Accounts carry labels only: their keys go into the desktop's keychain from
|
||||
* its Accounts screen (the desktop never reads the profiles). Project keys in the overrides become the desktop's ids.
|
||||
*/
|
||||
export function toDesktopState(ws: Workspace, apps: AppFolder[], now = new Date().toISOString()): DesktopState {
|
||||
const accounts = accountsOf(ws);
|
||||
const idOf = new Map(apps.map(a => [a.id, desktopProjectId(a.path)] as const));
|
||||
const mapKey = (k: string) => (k.startsWith('project:') && idOf.has(k.slice(8)) ? `project:${idOf.get(k.slice(8))}` : k);
|
||||
const o = overridesOf(ws, apps);
|
||||
return {
|
||||
version: 2,
|
||||
projects: apps.map(a => ({ id: idOf.get(a.id)!, path: a.path, name: a.name, playAccount: a.playAccount, appleAccount: a.appleAccount, added: now })),
|
||||
accounts: accounts.map(a => ({ id: a.id, label: a.label ?? a.profile, kind: a.store, created: now, studio: a.studio })),
|
||||
studios: studiosOf(ws).map(s => ({ id: s.id, name: s.name, color: s.color, logo: null, created: now })),
|
||||
overrides: {
|
||||
pairs: o.pairs, unpairs: o.unpairs,
|
||||
links: o.links.map(l => ({ key: l.key, project: idOf.get(l.project) ?? l.project })),
|
||||
appStudio: o.appStudio.map(x => ({ key: mapKey(x.key), studio: x.studio })),
|
||||
ignored: o.ignored.map(mapKey),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A profile name for a desktop account: its label as a slug, made unique per store. */
|
||||
function profileFor(a: DesktopAccount, taken: Set<string>): string {
|
||||
const base = (slug(a.label).slice(0, 56) || 'account');
|
||||
let name = taken.has(base) ? `${base}-${a.kind}` : base;
|
||||
for (let i = 2; taken.has(name); i++) name = `${base}-${a.kind}-${i}`;
|
||||
taken.add(name);
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Desktop state -> workspace. Folders under `root` become relative paths, others stay absolute. Each account becomes
|
||||
* a credential profile name (the owner creates ~/.storebound/credentials/<profile>.json; the desktop's keychain is
|
||||
* never read). Account ids are kept, so the overrides' store app keys stay valid.
|
||||
*/
|
||||
export function fromDesktopState(state: DesktopState, root: string): { ws: Workspace; profiles: { profile: string; store: Store; label: string }[] } {
|
||||
const taken = new Set<string>();
|
||||
const profile = new Map(state.accounts.map(a => [a.id, profileFor(a, taken)] as const));
|
||||
const acc = (a: DesktopAccount): WsAccount => ({ store: a.kind, profile: profile.get(a.id)!, label: a.label, id: a.id });
|
||||
const relOf = new Map(state.projects.map(p => {
|
||||
const r = posix(relative(root, p.path));
|
||||
return [p.id, !r || r.startsWith('..') || isAbsolute(r) ? p.path : r] as const;
|
||||
}));
|
||||
const proj = (k: string) => (k.startsWith('project:') && relOf.has(k.slice(8)) ? `project:${relOf.get(k.slice(8))}` : k);
|
||||
const studios: WsStudio[] = state.studios.map(s => ({ id: s.id, name: s.name, ...((STUDIO_COLORS as readonly string[]).includes(s.color) ? { color: s.color as StudioColor } : {}),
|
||||
accounts: state.accounts.filter(a => a.studio === s.id).map(acc) }));
|
||||
const ignore: string[] = [];
|
||||
for (const x of state.overrides?.ignored ?? []) {
|
||||
if (x.startsWith('account:')) ignore.push(`account:${profile.get(x.slice(8)) ?? x.slice(8)}`);
|
||||
else ignore.push(proj(x));
|
||||
}
|
||||
const ws: Workspace = {
|
||||
apps: state.projects.map(p => {
|
||||
const e: WsAppEntry = { path: relOf.get(p.id)! };
|
||||
if (p.name && p.name !== basename(p.path)) e.name = p.name;
|
||||
if (p.appleAccount && profile.has(p.appleAccount)) e.apple = profile.get(p.appleAccount)!;
|
||||
if (p.playAccount && profile.has(p.playAccount)) e.play = profile.get(p.playAccount)!;
|
||||
return Object.keys(e).length === 1 ? e.path : e;
|
||||
}),
|
||||
studios,
|
||||
accounts: state.accounts.filter(a => !a.studio || !state.studios.some(s => s.id === a.studio)).map(acc),
|
||||
ignore,
|
||||
overrides: {
|
||||
pairs: state.overrides?.pairs ?? [], unpairs: state.overrides?.unpairs ?? [],
|
||||
links: (state.overrides?.links ?? []).map(l => ({ key: l.key, project: relOf.get(l.project) ?? l.project })),
|
||||
appStudio: (state.overrides?.appStudio ?? []).map(x => ({ key: proj(x.key), studio: x.studio })),
|
||||
},
|
||||
};
|
||||
return { ws, profiles: state.accounts.map(a => ({ profile: profile.get(a.id)!, store: a.kind, label: a.label })) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the workspace's desktop state to an existing desktop state: folders by path (an existing project keeps its id
|
||||
* and accounts), accounts and studios by id (existing ones win), overrides as a union. Nothing is removed.
|
||||
*/
|
||||
export function mergeDesktopState(cur: DesktopState, add: DesktopState): { state: DesktopState; added: { projects: number; accounts: number; studios: number; overrides: number } } {
|
||||
const idMap = new Map<string, string>();
|
||||
const projects = [...cur.projects];
|
||||
let np = 0;
|
||||
for (const p of add.projects) {
|
||||
const have = projects.find(x => x.path === p.path);
|
||||
if (have) idMap.set(p.id, have.id);
|
||||
else { projects.push(p); np++; }
|
||||
}
|
||||
const remap = (k: string) => (k.startsWith('project:') && idMap.has(k.slice(8)) ? `project:${idMap.get(k.slice(8))}` : k);
|
||||
const accounts = [...cur.accounts];
|
||||
let na = 0;
|
||||
for (const a of add.accounts) if (!accounts.some(x => x.id === a.id)) { accounts.push(a); na++; }
|
||||
const studios = [...cur.studios];
|
||||
let ns = 0;
|
||||
for (const s of add.studios) if (!studios.some(x => x.id === s.id)) { studios.push(s); ns++; }
|
||||
const co = { ...NO_OVERRIDES, ...cur.overrides };
|
||||
const ao = add.overrides;
|
||||
const uniq = <T>(xs: T[]) => { const seen = new Set<string>(); return xs.filter(x => { const k = JSON.stringify(x); if (seen.has(k)) return false; seen.add(k); return true; }); };
|
||||
const overrides: Overrides = {
|
||||
pairs: uniq([...co.pairs, ...ao.pairs]),
|
||||
unpairs: uniq([...co.unpairs, ...ao.unpairs]),
|
||||
links: uniq([...co.links, ...ao.links.map(l => ({ key: l.key, project: idMap.get(l.project) ?? l.project }))]),
|
||||
appStudio: uniq([...co.appStudio, ...ao.appStudio.map(x => ({ key: remap(x.key), studio: x.studio })).filter(x => !co.appStudio.some(y => y.key === x.key))]),
|
||||
ignored: uniq([...co.ignored, ...ao.ignored.map(remap)]),
|
||||
};
|
||||
const count = (o: Overrides) => o.pairs.length + o.unpairs.length + o.links.length + o.appStudio.length + o.ignored.length;
|
||||
return { state: { ...cur, version: Math.max(cur.version ?? 1, 2), projects, accounts, studios, overrides }, added: { projects: np, accounts: na, studios: ns, overrides: count(overrides) - count(co) } };
|
||||
}
|
||||
188
cli/lib/xcode.ts
Normal file
188
cli/lib/xcode.ts
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
// Xcode builds without Xcode's UI: find the workspace / project and scheme (native, Capacitor, React Native, Flutter,
|
||||
// Unity-exported projects), build the xcodebuild archive and export command lines, read an IPA's Info.plist.
|
||||
// Pure except scanXcode (a bounded directory walk) and ipaInfo (reads the IPA).
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { basename, dirname, join, relative } from 'node:path';
|
||||
import { parsePlist, type PlistValue } from './plist';
|
||||
import { zipEntries, zipRead } from './zip';
|
||||
|
||||
export type Framework = 'flutter' | 'capacitor' | 'react-native' | 'unity' | 'native';
|
||||
|
||||
export interface AppleBuildConfig {
|
||||
/** .xcworkspace (CocoaPods / Flutter / React Native) relative to the config; wins over `project`. */
|
||||
workspace?: string;
|
||||
/** .xcodeproj when there is no workspace. */
|
||||
project?: string;
|
||||
scheme?: string;
|
||||
/** Default Release. */
|
||||
configuration?: string;
|
||||
/** Output folder for the archive, ExportOptions.plist, the IPA and logs. Default build/ios. */
|
||||
out?: string;
|
||||
}
|
||||
|
||||
export function validateAppleBuild(b: AppleBuildConfig | undefined): string[] {
|
||||
if (!b) return [];
|
||||
const e: string[] = [];
|
||||
if (b.workspace && !b.workspace.endsWith('.xcworkspace')) e.push('apple.build.workspace: a path ending in .xcworkspace');
|
||||
if (b.project && !b.project.endsWith('.xcodeproj')) e.push('apple.build.project: a path ending in .xcodeproj');
|
||||
if (b.scheme !== undefined && !b.scheme.trim()) e.push('apple.build.scheme: empty');
|
||||
return e;
|
||||
}
|
||||
|
||||
/** What scanXcode found, relative to the project root. */
|
||||
export interface XcodeScan {
|
||||
/** Files that tell the framework: pubspec.yaml, capacitor.config.*, package.json with react-native, Unity-iPhone.xcodeproj. */
|
||||
markers: string[];
|
||||
workspaces: string[];
|
||||
projects: string[];
|
||||
/** Shared scheme names per container (xcshareddata/xcschemes). */
|
||||
schemes: Record<string, string[]>;
|
||||
/** Folders with a Podfile and whether Pods/ exists next to it. */
|
||||
pods: { dir: string; installed: boolean }[];
|
||||
}
|
||||
|
||||
const SKIP_DIRS = new Set(['node_modules', 'Pods', 'build', 'DerivedData', '.git', '.storebound', '.dart_tool', 'Library', 'Temp', '.gradle', 'dist', 'www']);
|
||||
|
||||
/** Walks at most `depth` folders deep (default 4) for Xcode containers. */
|
||||
export function scanXcode(root: string, depth = 4): XcodeScan {
|
||||
const s: XcodeScan = { markers: [], workspaces: [], projects: [], schemes: {}, pods: [] };
|
||||
for (const m of ['pubspec.yaml', 'capacitor.config.ts', 'capacitor.config.json', 'capacitor.config.js']) if (existsSync(join(root, m))) s.markers.push(m);
|
||||
try {
|
||||
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
|
||||
if (pkg.dependencies?.['react-native'] || pkg.devDependencies?.['react-native']) s.markers.push('package.json:react-native');
|
||||
} catch { /* no package.json */ }
|
||||
const walk = (dir: string, d: number): void => {
|
||||
let names: string[];
|
||||
try { names = readdirSync(dir); } catch { return; }
|
||||
if (names.includes('Podfile')) s.pods.push({ dir: relative(root, dir) || '.', installed: names.includes('Pods') });
|
||||
for (const n of names) {
|
||||
const p = join(dir, n);
|
||||
if (n.endsWith('.xcworkspace')) { s.workspaces.push(relative(root, p)); continue; }
|
||||
if (n.endsWith('.xcodeproj')) {
|
||||
s.projects.push(relative(root, p));
|
||||
if (n === 'Unity-iPhone.xcodeproj') s.markers.push('Unity-iPhone.xcodeproj');
|
||||
const sd = join(p, 'xcshareddata', 'xcschemes');
|
||||
try { s.schemes[relative(root, p)] = readdirSync(sd).filter(f => f.endsWith('.xcscheme')).map(f => f.slice(0, -9)); } catch { /* none shared */ }
|
||||
continue;
|
||||
}
|
||||
if (d <= 0 || n.startsWith('.') || SKIP_DIRS.has(n)) continue;
|
||||
try { if (statSync(p).isDirectory()) walk(p, d - 1); } catch { /* unreadable */ }
|
||||
}
|
||||
};
|
||||
walk(root, depth);
|
||||
return s;
|
||||
}
|
||||
|
||||
export interface XcodeTarget { framework: Framework; workspace?: string; project?: string; scheme: string; notes: string[] }
|
||||
|
||||
const stem = (p: string): string => basename(p).replace(/\.(xcworkspace|xcodeproj)$/, '');
|
||||
|
||||
/** Picks the container and scheme. Config values win; else the framework's usual layout; else the only one found. */
|
||||
export function pickXcode(scan: XcodeScan, cfg: AppleBuildConfig = {}): XcodeTarget {
|
||||
const notes: string[] = [];
|
||||
const has = (m: string) => scan.markers.includes(m);
|
||||
const framework: Framework = has('pubspec.yaml') ? 'flutter' : scan.markers.some(m => m.startsWith('capacitor.config')) ? 'capacitor'
|
||||
: has('package.json:react-native') ? 'react-native' : has('Unity-iPhone.xcodeproj') ? 'unity' : 'native';
|
||||
let workspace = cfg.workspace, project = cfg.project;
|
||||
if (!workspace && !project) {
|
||||
const pref: Record<Framework, (string | RegExp)[]> = {
|
||||
flutter: ['ios/Runner.xcworkspace', 'ios/Runner.xcodeproj'],
|
||||
capacitor: ['ios/App/App.xcworkspace', 'ios/App/App.xcodeproj'],
|
||||
'react-native': [/^ios\/[^/]+\.xcworkspace$/, /^ios\/[^/]+\.xcodeproj$/],
|
||||
unity: [/(^|\/)Unity-iPhone\.xcworkspace$/, /(^|\/)Unity-iPhone\.xcodeproj$/],
|
||||
native: [],
|
||||
};
|
||||
const all = [...scan.workspaces, ...scan.projects];
|
||||
let hit = pref[framework].map(p => all.find(x => (typeof p === 'string' ? x === p : p.test(x)))).find(Boolean);
|
||||
if (!hit) {
|
||||
// a workspace next to a project (CocoaPods) beats the project; a lone container is taken as is
|
||||
const ws = scan.workspaces.filter(w => !w.includes('.xcodeproj/'));
|
||||
if (ws.length === 1) hit = ws[0];
|
||||
else if (!ws.length && scan.projects.length === 1) hit = scan.projects[0];
|
||||
else if (ws.length + scan.projects.length === 0) throw new Error('no .xcworkspace or .xcodeproj found (set apple.build.workspace or apple.build.project; Flutter: flutter create, Capacitor: npx cap add ios, Unity: Build Settings > iOS > Build)');
|
||||
else throw new Error(`several Xcode containers (${[...ws, ...scan.projects].slice(0, 6).join(', ')}): set apple.build.workspace or apple.build.project`);
|
||||
}
|
||||
if (hit!.endsWith('.xcworkspace')) workspace = hit; else project = hit;
|
||||
// CocoaPods: the workspace next to the project
|
||||
if (project) { const w = project.replace(/\.xcodeproj$/, '.xcworkspace'); if (scan.workspaces.includes(w)) { workspace = w; project = undefined; } }
|
||||
}
|
||||
const container = (workspace ?? project)!;
|
||||
const projOf = workspace ? scan.projects.find(p => dirname(p) === dirname(workspace!) && !/^Pods\//.test(basename(p))) : project;
|
||||
const shared = projOf ? scan.schemes[projOf] ?? [] : [];
|
||||
const usual: Record<Framework, string | null> = { flutter: 'Runner', capacitor: 'App', 'react-native': null, unity: 'Unity-iPhone', native: null };
|
||||
const scheme = cfg.scheme ?? usual[framework] ?? (shared.includes(stem(projOf ?? container)) ? stem(projOf ?? container) : shared.length === 1 ? shared[0]! : stem(projOf ?? container));
|
||||
if (!cfg.scheme && shared.length > 1 && !usual[framework]) notes.push(`several shared schemes (${shared.join(', ')}); using "${scheme}" (set apple.build.scheme to pick another)`);
|
||||
const podDir = dirname(container);
|
||||
const pod = scan.pods.find(p => p.dir === podDir || (p.dir === '.' && podDir === '.'));
|
||||
if (pod && !pod.installed) notes.push(`Podfile without Pods/ in ${pod.dir}: run pod install there first${framework === 'capacitor' ? ' (or npx cap sync ios)' : ''}`);
|
||||
if (framework === 'capacitor') notes.push('Capacitor: run npx cap sync ios after the web build so the archive has the current web assets');
|
||||
if (framework === 'flutter') notes.push('Flutter: storebound runs flutter build ios --config-only first (build number and name, Generated.xcconfig)');
|
||||
if (framework === 'unity') notes.push('Unity: build the Xcode project from Unity (Build Settings > iOS) before each archive; signing team can stay empty in Unity');
|
||||
return { framework, ...(workspace ? { workspace } : { project }), scheme, notes };
|
||||
}
|
||||
|
||||
export interface AscAuth { keyPath: string; keyId: string; issuerId: string }
|
||||
|
||||
const authArgs = (a: AscAuth | null): string[] => (a ? ['-allowProvisioningUpdates', '-authenticationKeyPath', a.keyPath, '-authenticationKeyID', a.keyId, '-authenticationKeyIssuerID', a.issuerId] : []);
|
||||
|
||||
export interface ArchiveInput { target: XcodeTarget; root: string; configuration: string; archivePath: string; version?: string; build: string; teamId?: string; auth: AscAuth | null }
|
||||
|
||||
/** xcodebuild archive. Version / build go in as build settings (they beat the project's values). */
|
||||
export function archiveArgs(i: ArchiveInput): string[] {
|
||||
return ['xcodebuild', ...(i.target.workspace ? ['-workspace', join(i.root, i.target.workspace)] : ['-project', join(i.root, i.target.project!)]),
|
||||
'-scheme', i.target.scheme, '-configuration', i.configuration, '-destination', 'generic/platform=iOS', '-archivePath', i.archivePath,
|
||||
...authArgs(i.auth), 'archive', `CURRENT_PROJECT_VERSION=${i.build}`, ...(i.version ? [`MARKETING_VERSION=${i.version}`] : []),
|
||||
...(i.teamId ? [`DEVELOPMENT_TEAM=${i.teamId}`] : [])];
|
||||
}
|
||||
|
||||
export function exportArgs(archivePath: string, plist: string, exportPath: string, auth: AscAuth | null): string[] {
|
||||
return ['xcodebuild', '-exportArchive', '-archivePath', archivePath, '-exportOptionsPlist', plist, '-exportPath', exportPath, ...authArgs(auth)];
|
||||
}
|
||||
|
||||
/** flutter build ios --config-only: writes Generated.xcconfig with the build name / number, no build, no signing. */
|
||||
export const flutterConfigArgs = (build: string, version?: string): string[] =>
|
||||
['flutter', 'build', 'ios', '--release', '--config-only', '--no-codesign', '--build-number', build, ...(version ? ['--build-name', version] : [])];
|
||||
|
||||
/** A command line for logs: the API key path is shown as $ASC_P8. */
|
||||
export const showCmd = (argv: string[], auth: AscAuth | null): string =>
|
||||
argv.map(a => (auth && a === auth.keyPath ? '$ASC_P8' : /[\s"'$]/.test(a) ? JSON.stringify(a) : a)).join(' ');
|
||||
|
||||
export interface IpaInfo { bundleId: string; version: string; build: string; minOs?: string; name?: string; platform?: string }
|
||||
|
||||
/** Bundle id, CFBundleShortVersionString and CFBundleVersion from Payload/<App>.app/Info.plist of an IPA. */
|
||||
export function ipaInfo(ipa: string | Buffer): IpaInfo {
|
||||
const e = zipEntries(ipa).find(x => /^Payload\/[^/]+\.app\/Info\.plist$/.test(x.name));
|
||||
if (!e) throw new Error('not an iOS app archive (no Payload/<App>.app/Info.plist)');
|
||||
const p = parsePlist(zipRead(ipa, e)) as Record<string, PlistValue>;
|
||||
const str = (k: string): string | undefined => (typeof p[k] === 'string' ? p[k] as string : undefined);
|
||||
const bundleId = str('CFBundleIdentifier'), version = str('CFBundleShortVersionString'), build = str('CFBundleVersion');
|
||||
if (!bundleId || !version || !build) throw new Error('Info.plist without CFBundleIdentifier / CFBundleShortVersionString / CFBundleVersion');
|
||||
return { bundleId, version, build, minOs: str('MinimumOSVersion'), name: str('CFBundleDisplayName') ?? str('CFBundleName'), platform: (p.CFBundleSupportedPlatforms as string[] | undefined)?.[0] };
|
||||
}
|
||||
|
||||
/** End states of an App Store Connect build upload (BuildUploadState); processing is polled by apple testflight wait. */
|
||||
export const UPLOAD_DONE = new Set(['COMPLETE', 'FAILED']);
|
||||
|
||||
/** Requests of an App Store Connect API build upload (Build Uploads, API 4.1): the upload, then the file reservation. */
|
||||
export function buildUploadReqs(appId: string, info: IpaInfo, fileName: string, fileSize: number) {
|
||||
return {
|
||||
upload: { method: 'POST' as const, path: '/v1/buildUploads', note: `build ${info.build} (${info.version})`,
|
||||
body: { data: { type: 'buildUploads', attributes: { cfBundleShortVersionString: info.version, cfBundleVersion: info.build, platform: 'IOS' },
|
||||
relationships: { app: { data: { type: 'apps', id: appId } } } } } },
|
||||
file: (uploadId: string) => ({ method: 'POST' as const, path: '/v1/buildUploadFiles', note: `${fileName} (${(fileSize / 1048576).toFixed(1)} MB)`,
|
||||
body: { data: { type: 'buildUploadFiles', attributes: { assetType: 'ASSET', fileName, fileSize, uti: 'com.apple.ipa' },
|
||||
relationships: { buildUpload: { data: { type: 'buildUploads', id: uploadId } } } } } }),
|
||||
commit: (fileId: string, md5: string) => ({ method: 'PATCH' as const, path: `/v1/buildUploadFiles/${fileId}`, note: 'commit',
|
||||
body: { data: { type: 'buildUploadFiles', id: fileId, attributes: { uploaded: true, sourceFileChecksums: { file: { hash: md5, algorithm: 'MD5' } } } } } }),
|
||||
};
|
||||
}
|
||||
|
||||
/** altool upload (Xcode's command line uploader) with the API key. */
|
||||
export const altoolArgs = (ipa: string, auth: AscAuth): string[] =>
|
||||
['xcrun', 'altool', '--upload-package', ipa, '--api-key', auth.keyId, '--api-issuer', auth.issuerId, '--p8-file-path', auth.keyPath, '--output-format', 'json'];
|
||||
|
||||
/** Errors and warnings of a build upload's state (StateDetail: code, message). */
|
||||
export function uploadProblems(state: { errors?: { code?: string; message?: string; description?: string }[]; warnings?: { code?: string; message?: string; description?: string }[] } | undefined): { errors: string[]; warnings: string[] } {
|
||||
const f = (x: { code?: string; message?: string; description?: string }) => [x.code, x.message ?? x.description].filter(Boolean).join(': ');
|
||||
return { errors: (state?.errors ?? []).map(f), warnings: (state?.warnings ?? []).map(f) };
|
||||
}
|
||||
59
cli/lib/zip.ts
Normal file
59
cli/lib/zip.ts
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
// Reads entries of a ZIP archive without dependencies: the central directory, then one entry, stored or deflated
|
||||
// (node:zlib, built into Bun). Used for an .ipa / .aab (Payload/<App>.app/Info.plist, the manifest) and the Play
|
||||
// financial report exports (earnings_YYYYMM.zip, salesreport_YYYYMM.zip: one CSV inside). No ZIP64, no encryption.
|
||||
import { closeSync, fstatSync, openSync, readSync } from 'node:fs';
|
||||
import { inflateRawSync } from 'node:zlib';
|
||||
|
||||
export interface ZipEntry { name: string; method: number; compressedSize: number; size: number; localOffset: number }
|
||||
|
||||
function readAt(fd: number, pos: number, len: number): Buffer {
|
||||
const b = Buffer.alloc(len);
|
||||
const n = readSync(fd, b, 0, len, pos);
|
||||
return b.subarray(0, n);
|
||||
}
|
||||
|
||||
/** Entries of the central directory of a ZIP file (path) or buffer. */
|
||||
export function zipEntries(src: string | Buffer): ZipEntry[] {
|
||||
const fd = typeof src === 'string' ? openSync(src, 'r') : -1;
|
||||
try {
|
||||
const size = fd >= 0 ? fstatSync(fd).size : (src as Buffer).length;
|
||||
const read = (pos: number, len: number): Buffer => (fd >= 0 ? readAt(fd, pos, len) : (src as Buffer).subarray(pos, pos + len));
|
||||
const tailLen = Math.min(size, 65_557);
|
||||
const tail = read(size - tailLen, tailLen);
|
||||
let eocd = -1;
|
||||
for (let i = tail.length - 22; i >= 0; i--) if (tail.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }
|
||||
if (eocd < 0) throw new Error('not a ZIP archive (no end of central directory)');
|
||||
const count = tail.readUInt16LE(eocd + 10), cdSize = tail.readUInt32LE(eocd + 12), cdOff = tail.readUInt32LE(eocd + 16);
|
||||
if (cdOff === 0xffffffff) throw new Error('ZIP64 archives are not supported');
|
||||
const cd = read(cdOff, cdSize);
|
||||
const out: ZipEntry[] = [];
|
||||
for (let p = 0, k = 0; k < count && p + 46 <= cd.length; k++) {
|
||||
if (cd.readUInt32LE(p) !== 0x02014b50) throw new Error('ZIP: bad central directory entry');
|
||||
const nameLen = cd.readUInt16LE(p + 28), extraLen = cd.readUInt16LE(p + 30), commentLen = cd.readUInt16LE(p + 32);
|
||||
out.push({ name: cd.subarray(p + 46, p + 46 + nameLen).toString('utf8'), method: cd.readUInt16LE(p + 10),
|
||||
compressedSize: cd.readUInt32LE(p + 20), size: cd.readUInt32LE(p + 24), localOffset: cd.readUInt32LE(p + 42) });
|
||||
p += 46 + nameLen + extraLen + commentLen;
|
||||
}
|
||||
return out;
|
||||
} finally { if (fd >= 0) closeSync(fd); }
|
||||
}
|
||||
|
||||
/** The uncompressed bytes of one entry. */
|
||||
export function zipRead(src: string | Buffer, e: ZipEntry): Buffer {
|
||||
const fd = typeof src === 'string' ? openSync(src, 'r') : -1;
|
||||
try {
|
||||
const read = (pos: number, len: number): Buffer => (fd >= 0 ? readAt(fd, pos, len) : (src as Buffer).subarray(pos, pos + len));
|
||||
const h = read(e.localOffset, 30);
|
||||
if (h.readUInt32LE(0) !== 0x04034b50) throw new Error(`ZIP: bad local header for ${e.name}`);
|
||||
const data = read(e.localOffset + 30 + h.readUInt16LE(26) + h.readUInt16LE(28), e.compressedSize);
|
||||
if (e.method === 0) return Buffer.from(data);
|
||||
if (e.method === 8) return inflateRawSync(data);
|
||||
throw new Error(`ZIP: compression method ${e.method} not supported (${e.name})`);
|
||||
} finally { if (fd >= 0) closeSync(fd); }
|
||||
}
|
||||
|
||||
/** Every file entry with its uncompressed bytes, from an in-memory archive (a Play report export). */
|
||||
export function unzip(buf: Uint8Array): { name: string; data: Uint8Array }[] {
|
||||
const b = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||
return zipEntries(b).filter(e => !e.name.endsWith('/')).map(e => ({ name: e.name, data: new Uint8Array(zipRead(b, e)) }));
|
||||
}
|
||||
127
cli/mcp-tools.ts
127
cli/mcp-tools.ts
|
|
@ -3,7 +3,7 @@
|
|||
// submits for review, releases to the public, resumes / completes a rollout, cancels a submission or deletes is
|
||||
// exposed. Those stay terminal commands the owner runs (they also ask for confirmation there).
|
||||
|
||||
export interface JsonSchema { type: string; description?: string; enum?: (string | number)[]; default?: unknown; items?: JsonSchema; minimum?: number; maximum?: number; pattern?: string }
|
||||
export interface JsonSchema { type: string; description?: string; enum?: (string | number)[]; default?: unknown; items?: JsonSchema; minimum?: number; maximum?: number; pattern?: string; additionalProperties?: JsonSchema | boolean }
|
||||
|
||||
export interface ToolDef {
|
||||
name: string;
|
||||
|
|
@ -28,6 +28,7 @@ const only: JsonSchema = { type: 'string', description: 'Comma-separated ids / l
|
|||
const lang: JsonSchema = { type: 'string', description: 'Comma-separated language ids from the config (default: all)' };
|
||||
const variant: JsonSchema = { type: 'string', pattern: '^[a-z0-9][a-z0-9-]*$', description: 'A/B variant id from shots.variants (default: the base renders)' };
|
||||
const source: JsonSchema = { type: 'string', enum: ['web', 'ios-sim', 'android-emu', 'folder'], description: 'Default: from the config' };
|
||||
const APP_NAMES = '^[^,\\x00-\\x1f]{1,120}(,[^,\\x00-\\x1f]{1,120}){0,99}$';
|
||||
const opt = (flag: string, v: unknown): string[] => (v === undefined || v === null || v === '' ? [] : [`--${flag}`, String(v)]);
|
||||
const flag = (name: string, v: unknown): string[] => (v === true ? [`--${name}`] : []);
|
||||
|
||||
|
|
@ -38,6 +39,10 @@ export const TOOLS: ToolDef[] = [
|
|||
description: 'Offline ASO audit of the listing files: App Store keyword field rules (100 chars, no spaces, no name/subtitle repeats, >= 90% used) and Play keyword stuffing.',
|
||||
props: { storefront: { type: 'string', description: 'App Store storefront for the cross-locale hint', default: 'US' } },
|
||||
args: i => ['--aso', ...opt('storefront', i.storefront)] },
|
||||
{ name: 'scan', title: 'Rejection-risk scan of the project', command: ['scan'], write: false, network: false,
|
||||
description: 'Offline, read-only scan of the project itself before submitting: detects the stack (iOS, Android, React Native, Expo, Capacitor, Cordova, Flutter, Unity, Godot) and SDKs (ads, analytics, crash, sign-in, payments, push) with versions and file:line, then reports App Store and Google Play rejection risks with the guideline, evidence, fix, severity and skill (demo account 2.1, account deletion 5.1.1(v), Sign in with Apple 4.8, Restore Purchases 3.1.1, subscription info 3.1.2, ATT 5.1.2, purpose strings, privacy manifest, other platforms 2.3.10, keywords 2.3.7, placeholder text, web wrappers 4.2, UIWebView, ATS, IPv6, export compliance, kids ads, Play target SDK, delete-account URL, restricted permissions and their declarations (background location, photo / video, All files access, accessibility, install packages, Health Connect, full-screen intent, VPN, foreground services, exact alarms, QUERY_ALL_PACKAGES, SMS / call log), prominent disclosure, Families, AD_ID, 16 KB page sizes, testing for personal accounts, Play metadata, ads at launch, payments, impersonation) and proposes the Data safety / App Privacy / ATT / privacy manifest answers as a diff against the config. Never writes (the owner runs `storebound scan --write` in a terminal).',
|
||||
props: { store: { type: 'string', enum: ['apple', 'play'], description: 'Only this store\'s findings (default: both)' } },
|
||||
args: i => opt('store', i.store) },
|
||||
{ name: 'validate', title: 'Store readiness report', command: ['validate'], write: false, network: true,
|
||||
description: 'Read-only readiness report for App Store Connect and/or Google Play with ordered blockers (build, encryption, metadata, screenshots, review details and demo account, age rating, prices, IAPs, subscriptions, privacy, delete-account and terms URLs, app-ads.txt, tracks, products, base plans).',
|
||||
props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' } },
|
||||
|
|
@ -86,6 +91,14 @@ export const TOOLS: ToolDef[] = [
|
|||
description: 'Read-only App Store Connect overview: versions and their states, recent builds, in-app purchases, review submissions.' },
|
||||
{ name: 'apple_next_build', title: 'Next iOS build number', command: ['apple', 'next-build'], write: false, network: true,
|
||||
description: 'Next safe CFBundleVersion: one above every build uploaded for the app.' },
|
||||
{ name: 'apple_signing_status', title: 'Code signing status', command: ['apple', 'signing', 'status'], write: false, network: true,
|
||||
description: 'Read-only signing overview from App Store Connect: bundle id capabilities vs apple.signing.capabilities, distribution certificates (and whether this machine holds a private key for one), App Store provisioning profiles per bundle id and whether they are installed for Xcode. Creating certificates and profiles stays a terminal command (apple signing ensure, asks first).',
|
||||
args: () => ['--json'] },
|
||||
{ name: 'originality', title: 'Originality check (Guideline 4.3)', command: ['originality'], write: false, network: false,
|
||||
description: 'Offline comparison of this app with the owner\'s other apps (folders with a storebound.config.ts): listing text, name, icon and screenshot perceptual hashes, project structure. Scores per axis, overall, near-duplicate flags and suggestions; exit 1 when a pair is flagged. Pair with the portfolio-originality skill.',
|
||||
props: { against: { type: 'string', description: 'Comma-separated folders of the other apps, or a folder holding several (default: originality.against in the config)' },
|
||||
threshold: { type: 'number', minimum: 0.05, maximum: 0.95, description: 'Overall score that counts as a near-duplicate (default 0.7)' } },
|
||||
args: i => ['--json', ...opt('against', i.against), ...opt('threshold', i.threshold)] },
|
||||
{ name: 'play_status', title: 'Google Play status', command: ['play', 'status'], write: false, network: true,
|
||||
description: 'Read-only Play overview: tracks and releases (with rollout fraction), listing languages, one-time products.' },
|
||||
{ name: 'play_next_version_code', title: 'Next Play versionCode', command: ['play', 'next-version-code'], write: false, network: true,
|
||||
|
|
@ -204,6 +217,14 @@ export const TOOLS: ToolDef[] = [
|
|||
description: 'Sync the screenshots of one shots variant (renders/<variant>/<lang>/...) into the matching treatment of the editable Product Page Optimization test, per locale (MD5-idempotent; changed sets are replaced). Nothing is shown to players until the owner starts the test.',
|
||||
props: { variant, experiment: { type: 'string', description: 'Test name (default: the one editable test)' }, only },
|
||||
required: ['variant'], args: i => [...opt('variant', i.variant), ...opt('experiment', i.experiment), ...opt('only', i.only)] },
|
||||
{ name: 'api_get', title: 'Any store API read', command: ['api', 'get'], write: false, network: true,
|
||||
description: 'Read-only call of any App Store Connect API or Google Play Developer API GET operation by its operation id (every one is listed by `storebound api list` and in docs/api-coverage.md), e.g. store apple, operation apps_getCollection, params {"filter[bundleId]": "com.example.app"}. GET only: writes, and anything that submits, releases, deletes or cancels, are never available here.',
|
||||
props: { store: { type: 'string', enum: ['apple', 'play'] },
|
||||
operation: { type: 'string', pattern: '^[A-Za-z][A-Za-z0-9_.]{0,200}$', description: 'Operation id: Apple e.g. apps_getCollection, Google e.g. androidpublisher.reviews.list (the API prefix may be left out)' },
|
||||
params: { type: 'object', additionalProperties: { type: 'string' }, description: 'Path and query parameters by name (string, number or boolean values; lists comma-separated)' },
|
||||
all_pages: { type: 'boolean', description: 'Follow every page and merge them' } },
|
||||
required: ['store', 'operation'],
|
||||
args: i => [String(i.store), String(i.operation), ...Object.entries((i.params ?? {}) as Record<string, unknown>).map(([k, v]) => `--param=${k}=${String(v)}`), ...flag('all-pages', i.all_pages), '--json'] },
|
||||
{ name: 'icons', title: 'Generate icons', command: ['icons'], write: true, network: false, idempotent: true,
|
||||
description: 'Write every store / launcher / web icon from the artwork in the config (local files, needs ffmpeg).' },
|
||||
{ name: 'import_fastlane', title: 'Import a fastlane setup', command: ['import', 'fastlane'], write: true, network: false, idempotent: true,
|
||||
|
|
@ -211,12 +232,108 @@ export const TOOLS: ToolDef[] = [
|
|||
props: { dir: { type: 'string', pattern: '^(?!/)(?!.*\\.\\.)(?!.*,/)[A-Za-z0-9._ /,-]{1,400}$', description: 'fastlane folder(s) relative to the project, comma-separated (default: fastlane, ios/fastlane, android/fastlane)' },
|
||||
profile: { type: 'string', enum: ['app', 'game', 'subscription-app'], description: 'Default: game for the GAMES category, else app' } },
|
||||
args: i => [...opt('dir', i.dir), ...opt('profile', i.profile)] },
|
||||
{ name: 'workspace_list', title: 'Workspace apps', command: ['ws', 'list'], write: false, network: false,
|
||||
description: 'Offline: the apps of the storebound.workspace.json above the project (app folders from its globs, store-only apps from `ws apps import`), paired across iOS and Android by the desktop\'s rules, with studios and accounts (credential profile names and whether their keys are there; never a key).',
|
||||
props: { all: { type: 'boolean', default: false, description: 'Also the ignored apps' }, json: { type: 'boolean', default: false } },
|
||||
args: i => [...flag('all', i.all), ...flag('json', i.json)] },
|
||||
{ name: 'workspace_status', title: 'Workspace portfolio status', command: ['ws', 'status'], write: false, network: true,
|
||||
description: 'Read-only portfolio table of every app in the workspace across both stores: the version that reaches users and the next one (build > testing > review > live > rollout %), catalog parity, offline check, read in parallel with each account\'s credential profile.',
|
||||
props: { apps: { type: 'string', pattern: APP_NAMES, description: 'Comma-separated app names or folders (default: all)' },
|
||||
offline: { type: 'boolean', default: false, description: 'Skip the store reads' }, json: { type: 'boolean', default: false } },
|
||||
args: i => [...opt('apps', i.apps), ...flag('offline', i.offline), ...flag('json', i.json)] },
|
||||
{ name: 'release_status', title: 'Release trains', command: ['release', 'status'], write: false, network: true,
|
||||
description: 'Read-only release trains: per app, both stores on one train per version (build > testing > review > live > rollout %), the version that reaches users and the next one; versions lists every version. In an app folder that app, in a workspace every app (or app).',
|
||||
props: { app: { type: 'string', pattern: APP_NAMES, description: 'Workspace app names (comma-separated)' },
|
||||
versions: { type: 'boolean', default: false }, json: { type: 'boolean', default: false } },
|
||||
args: i => [...opt('app', i.app), ...flag('versions', i.versions), ...flag('json', i.json)] },
|
||||
{ name: 'release_plan', title: 'Release plan for a version', command: ['release', 'plan'], write: false, network: true,
|
||||
description: 'Read-only: what is left for one version on each store, in fix order: config problems (check), the version on the store, store blockers (validate), the next move (owner steps such as submitting or releasing are named, never done), warnings.',
|
||||
props: { version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,3}$' }, app: { type: 'string', pattern: APP_NAMES, description: 'Workspace app names (comma-separated)' },
|
||||
no_validate: { type: 'boolean', default: false, description: 'Skip the store readiness read' }, json: { type: 'boolean', default: false } },
|
||||
required: ['version'], args: i => [String(i.version), ...opt('app', i.app), ...flag('no-validate', i.no_validate), ...flag('json', i.json)] },
|
||||
|
||||
// ---- store operations (read-only plans, local pulls and reports; submits, codes, offers and pre-orders stay terminal-only) ----
|
||||
{ name: 'apple_testflight_wait', title: 'Wait for a TestFlight build', command: ['apple', 'testflight', 'wait'], write: false, network: true,
|
||||
description: 'Poll one uploaded build (exact number) until processing ends: exit 0 VALID, 1 FAILED / INVALID, 7 timeout. Read-only. check_once reads the state once without waiting.',
|
||||
props: { build: { type: 'string', pattern: '^[0-9][0-9.]*$', description: 'Exact build number (CFBundleVersion) you uploaded' }, version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$' },
|
||||
timeout_minutes: { type: 'integer', minimum: 1, maximum: 60, default: 30 }, check_once: { type: 'boolean', default: false } },
|
||||
required: ['build'], args: i => [...opt('build', i.build), ...opt('version', i.version), '--timeout', `${Number(i.timeout_minutes ?? 30)}m`, '--json', ...flag('dry', i.check_once)] },
|
||||
{ name: 'apple_iap_review_plan', title: 'IAP review submission plan', command: ['apple', 'iap-submit'], write: false, network: true,
|
||||
description: 'Read-only plan for sending in-app purchases and subscriptions to App Review: which version of each goes in, which are the first of their type (Apple reviews those only with a new app version), what is left out and why. Submitting is an owner-only terminal command.',
|
||||
props: { only, with_version: { type: 'boolean', default: false, description: 'Plan with the editable app version in the same submission' } },
|
||||
args: i => [...opt('only', i.only), ...flag('with-version', i.with_version), '--json', '--dry'] },
|
||||
{ name: 'apple_listing_pull', title: 'Pull App Store texts', command: ['apple', 'listing', 'pull'], write: true, network: true, idempotent: true,
|
||||
description: 'Read the live App Store texts (name, subtitle, description, keywords, promotional text, what\'s new per locale) and diff them against the App Store listing file. dry_run shows the diff; with dry_run false the file is updated (local file only).',
|
||||
props: { version: { type: 'string', pattern: '^\\d+(\\.\\d+){0,2}$', description: 'Version to read (default: the editable one, else the newest)' } },
|
||||
args: i => [...opt('version', i.version), '--json', ...(i.dry_run === false ? ['--write'] : [])] },
|
||||
{ name: 'play_listing_pull', title: 'Pull Google Play texts', command: ['play', 'listing', 'pull'], write: true, network: true, idempotent: true,
|
||||
description: 'Read the live Play listings (title, short and full description per language; one throwaway edit, deleted) and diff them against the Play listing file. dry_run shows the diff; with dry_run false the file is updated (local file only).',
|
||||
args: i => ['--json', ...(i.dry_run === false ? ['--write'] : [])] },
|
||||
{ name: 'catalog_pull', title: 'Pull IAP and subscription texts', command: ['catalog', 'pull'], write: true, network: true, idempotent: true,
|
||||
description: 'Store titles and descriptions (Play: benefits) of in-app purchases and subscriptions vs the config listings, as a proposal diff. storebound.config.ts is never rewritten; with dry_run false the proposal is saved to .storebound/pull/catalog.json.',
|
||||
props: { store: { type: 'string', enum: ['apple', 'play'] } }, args: i => [...opt('store', i.store), '--json', ...(i.dry_run === false ? ['--write'] : [])] },
|
||||
{ name: 'whats_new_languages', title: 'Release notes per language', command: ['whats-new'], write: true, network: false, idempotent: true,
|
||||
description: 'Draft release notes from git into one file per language (store/whats-new/<language id>.md): the first language gets the draft, the others status=translate files for you to translate (keep the header line, set status=translated). Then whats_new_check and whats_new_apply. Local files only.',
|
||||
props: { languages: { type: 'string', pattern: '^[A-Za-z0-9_-]+(,[A-Za-z0-9_-]+)*$', description: 'Comma-separated language ids or store codes, source language first' }, since: { type: 'string', description: 'Git tag or ref (default: latest tag)' } },
|
||||
required: ['languages'], args: i => [...opt('languages', i.languages), ...opt('since', i.since), '--json'] },
|
||||
{ name: 'whats_new_check', title: 'Check release notes per language', command: ['whats-new', 'check'], write: false, network: false,
|
||||
description: 'Offline: the per-language release notes files against the store limits (Google Play 500, App Store 4000 characters), untranslated or identical-to-source files, long first lines.',
|
||||
args: () => ['--json'] },
|
||||
{ name: 'whats_new_apply', title: 'Apply release notes per language', command: ['whats-new', 'apply'], write: true, network: false, idempotent: true,
|
||||
description: 'Write the checked per-language release notes into both listing files (Play "What\'s new" per Play code, App Store whatsNew per locale). Refuses while a language is over a limit or untranslated. Local files only; nothing is sent to a store.',
|
||||
args: () => ['--json'] },
|
||||
{ name: 'reports', title: 'Sales and finance reports', command: ['reports'], write: true, network: true, idempotent: true,
|
||||
description: 'Download a sales or finance report into .storebound/reports/ (gitignored) and print a summary per product and currency (amounts never added across currencies) plus a summary CSV. Apple needs ASC_VENDOR_NUMBER and a team key; Play needs play.reportsBucket and "View financial data". dry_run shows the request only.',
|
||||
props: { kind: { type: 'string', enum: ['apple-sales', 'apple-finance', 'play-earnings', 'play-sales'] }, month: { type: 'string', pattern: '^\\d{4}-\\d{2}$', description: 'YYYY-MM (apple-finance: Apple fiscal month; Play reports)' },
|
||||
date: { type: 'string', pattern: '^\\d{4}(-\\d{2}(-\\d{2})?)?$', description: 'apple-sales report date (DAILY / WEEKLY YYYY-MM-DD, MONTHLY YYYY-MM, YEARLY YYYY)' },
|
||||
frequency: { type: 'string', enum: ['DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY'] }, type: { type: 'string', enum: ['SALES', 'PRE_ORDER', 'SUBSCRIPTION', 'SUBSCRIPTION_EVENT', 'SUBSCRIBER', 'SUBSCRIPTION_OFFER_CODE_REDEMPTION', 'WIN_BACK_ELIGIBILITY'] } },
|
||||
required: ['kind'], args: i => [String(i.kind), ...opt('month', i.month), ...opt('date', i.date), ...opt('frequency', i.frequency), ...opt('type', i.type), '--json'] },
|
||||
{ name: 'triage', title: 'Crash and feedback triage', command: ['triage'], write: false, network: true,
|
||||
description: 'Read-only: TestFlight crash reports (signature from each crash log), TestFlight screenshot feedback and Google Play error reports of the top issues, grouped by signature with their top devices, OS versions and builds. Tester emails are never read.',
|
||||
props: { store: { type: 'string', enum: ['both', 'apple', 'play'], default: 'both' }, days: { type: 'integer', minimum: 1, maximum: 90, default: 14 }, build: { type: 'string', pattern: '^[0-9][0-9.]*$' },
|
||||
issues: { type: 'integer', minimum: 1, maximum: 50, default: 10 } },
|
||||
args: i => [...(i.store === 'apple' ? ['--apple'] : i.store === 'play' ? ['--play'] : []), ...opt('days', i.days), ...opt('build', i.build), ...opt('issues', i.issues), '--json'] },
|
||||
{ name: 'aso_rank', title: 'App Store keyword ranks', command: ['aso', 'rank'], write: true, network: true, idempotent: true,
|
||||
description: 'Rank of the app per keyword (the keyword field of store/appstore.md, plus extra keywords) and storefront in Apple\'s public iTunes Search API results, with the top competitors. One request every 3.5 s (Apple allows about 20 a minute). dry_run lists the queries; with dry_run false it queries and saves .storebound/aso/<date>.json. Search API order is close to, not equal to, App Store search.',
|
||||
props: { storefronts: { type: 'string', pattern: '^[a-z]{2}(=[A-Za-z-]+)?(,[a-z]{2}(=[A-Za-z-]+)?)*$', description: 'e.g. us,de=de-DE (default us)' }, keywords: { type: 'string', description: 'Extra keywords, comma-separated' },
|
||||
competitors: { type: 'integer', minimum: 0, maximum: 10, default: 3 } },
|
||||
args: i => [...opt('storefronts', i.storefronts), ...opt('keywords', i.keywords), ...opt('competitors', i.competitors), '--json'] },
|
||||
{ name: 'ads_scan', title: 'AdAttributionKit scan', command: ['ads', 'scan'], write: false, network: false,
|
||||
description: 'Local scan of an iOS project for AdAttributionKit and SKAdNetwork: ad network ids (SKAdNetworkItems, AdNetworkIdentifiers, lowercase), postback copy endpoints (AttributionCopyEndpoint, re-engagement copies, NSAdvertisingAttributionReportEndpoint), attribution windows and cooldown, conversion value updates in code, ad SDKs without ids.',
|
||||
props: { ios: { type: 'string', description: 'Path of the iOS project folder, e.g. ios/App' } }, required: ['ios'], args: i => [...opt('ios', i.ios), '--json'] },
|
||||
{ name: 'apple_cpp_list', title: 'Custom product pages', command: ['apple', 'cpp', 'list'], write: false, network: true,
|
||||
description: 'Read-only list of the App Store custom product pages (visible or not, version state, URL) and the configured ones not created yet (at most 70 per app).', args: () => ['--json'] },
|
||||
{ name: 'apple_cpp_create', title: 'Create custom product pages', command: ['apple', 'cpp', 'create'], write: true, network: true, idempotent: true,
|
||||
description: 'Create the custom product pages of apple.customProductPages that are missing (with a localization per App Store locale, promotional text, deep link) and update editable ones. Nothing is shown to customers: submitting a page and making it visible are owner-only terminal commands.',
|
||||
props: { name: { type: 'string', description: 'Only this page' } }, args: i => opt('name', i.name) },
|
||||
{ name: 'apple_cpp_upload', title: 'Upload custom product page screenshots', command: ['apple', 'cpp', 'upload'], write: true, destructive: true, network: true, idempotent: true,
|
||||
description: 'Sync the screenshots of a custom product page from the renders of its shots variant, per locale (MD5-idempotent; changed sets are replaced). Only on an editable page version.',
|
||||
props: { name: { type: 'string', description: 'Page name from apple.customProductPages' }, only }, required: ['name'], args: i => [...opt('name', i.name), ...opt('only', i.only)] },
|
||||
{ name: 'apple_events_list', title: 'In-app events', command: ['apple', 'events', 'list'], write: false, network: true,
|
||||
description: 'Read-only list of the App Store in-app events (badge, state, schedule) and the configured ones not created yet (10 published / 15 approved per app).', args: () => ['--json'] },
|
||||
{ name: 'apple_events_create', title: 'Create in-app events', command: ['apple', 'events', 'create'], write: true, network: true, idempotent: true,
|
||||
description: 'Create the in-app events of apple.events that are missing (reference name, badge, purpose, priority, deep link, schedule, localizations with name 30 / short 50 / long 120 characters) and update draft ones. Sending an event to App Review is an owner-only terminal command.',
|
||||
props: { name: { type: 'string', description: 'Only this event (reference name)' } }, args: i => opt('name', i.name) },
|
||||
{ name: 'apple_events_upload', title: 'Upload in-app event images', command: ['apple', 'events', 'upload'], write: true, destructive: true, network: true, idempotent: true,
|
||||
description: 'Upload the event card (16:9, 1920x1080 to 3840x2160) and details page (9:16) images of one draft in-app event per locale, size-checked first.',
|
||||
props: { name: { type: 'string', description: 'Reference name from apple.events' } }, required: ['name'], args: i => opt('name', i.name) },
|
||||
{ name: 'apple_preorder_status', title: 'App Store pre-order status', command: ['apple', 'preorder', 'status'], write: false, network: true,
|
||||
description: 'Read-only: per territory whether the app is available, its release date, pre-order on / off and its content status. Enabling or ending a pre-order is an owner-only terminal command.', args: () => ['--json'] },
|
||||
];
|
||||
|
||||
/** CLI flags / commands that must never be reachable through MCP. Tests assert none of the tools can produce them. */
|
||||
export const FORBIDDEN_ARGS = ['--yes', '--manual-release', '--cancel-submission', '--production', 'rollout', 'resume', 'complete',
|
||||
export const FORBIDDEN_ARGS = ['--write', '--yes', '--manual-release', '--cancel-submission', '--production', 'rollout', 'resume', 'complete',
|
||||
'--submit-review', '--remove', '--invite', 'testers', 'send', 'start', 'stop'];
|
||||
|
||||
/**
|
||||
* The one exception to FORBIDDEN_ARGS: the pull tools, whose `--write` (only with dry_run false) writes the live store
|
||||
* texts into a local file (store/*.md, .storebound/pull/catalog.json; never storebound.config.ts, never a store).
|
||||
* `scan --write` (compliance answers into the config) stays unreachable: scan is not in this list.
|
||||
*/
|
||||
export const LOCAL_WRITE_TOOLS: Record<string, readonly string[]> = {
|
||||
apple_listing_pull: ['--write'], play_listing_pull: ['--write'], catalog_pull: ['--write'],
|
||||
};
|
||||
|
||||
export function inputSchema(t: ToolDef): Record<string, unknown> {
|
||||
const props: Record<string, JsonSchema> = { ...(t.props ?? {}) };
|
||||
if (t.write) props.dry_run = { type: 'boolean', default: true, description: 'Default true: only show what would change. Set false only after the owner agreed.' };
|
||||
|
|
@ -248,8 +365,10 @@ export function validateInput(t: ToolDef, input: unknown): string[] {
|
|||
for (const [k, v] of Object.entries(i)) {
|
||||
const p = s.properties[k];
|
||||
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' : true;
|
||||
if (!ok) { e.push(`${k}: must be ${p.type}`); continue; }
|
||||
const ok = p.type === 'integer' ? Number.isInteger(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)))
|
||||
: true;
|
||||
if (!ok) { e.push(`${k}: must be ${p.type === 'object' ? 'an object of name -> string / number / boolean' : p.type}`); continue; }
|
||||
if (p.enum && !p.enum.includes(v as string)) e.push(`${k}: one of ${p.enum.join(', ')}`);
|
||||
if (p.pattern && typeof v === 'string' && !new RegExp(p.pattern).test(v)) e.push(`${k}: does not match ${p.pattern}`);
|
||||
if (p.minimum !== undefined && typeof v === 'number' && v < p.minimum) e.push(`${k}: >= ${p.minimum}`);
|
||||
|
|
|
|||
|
|
@ -47,6 +47,7 @@ export const INSTRUCTIONS = [
|
|||
'Write tools default to dry_run: show the dry run to the owner and only call again with dry_run false after they agree.',
|
||||
'Nothing here submits for review, releases, cancels, deletes or sends anything public (review replies, tester invitations, price changes, experiment starts): tell the owner which terminal command or console click does that.',
|
||||
'Credentials come only from env or .storebound/ in the project; never ask for keys in chat or write them into files.',
|
||||
'Many apps: workspace_list / workspace_status read the storebound.workspace.json above the project; release_status and release_plan show both stores on one train per version.',
|
||||
'Run `check` (offline) and `validate` (read-only) before writes. Long uploads (images, screenshots) are better run in a terminal with a log.',
|
||||
].join(' ');
|
||||
|
||||
|
|
@ -120,7 +121,8 @@ const running = new Map<Id, Running>();
|
|||
function cancel(id: Id | undefined): void { if (id !== undefined) running.get(id)?.cancel(); }
|
||||
|
||||
async function runCli(argv: string[], id: Id): Promise<{ code: number; out: string }> {
|
||||
const r = runCommand(argv, { cwd: process.env.STOREBOUND_PROJECT || process.cwd() });
|
||||
// STOREBOUND_MCP: `storebound api` never sends a write from an MCP call, whatever the arguments
|
||||
const r = runCommand(argv, { cwd: process.env.STOREBOUND_PROJECT || process.cwd(), env: { STOREBOUND_MCP: '1' } });
|
||||
running.set(id, r);
|
||||
try { const { code, out } = await r.result; return { code, out }; } finally { running.delete(id); }
|
||||
}
|
||||
|
|
|
|||
53
cli/originality.ts
Normal file
53
cli/originality.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
// Originality check (App Store Guideline 4.3, Google Play repetitive content) against the owner's other apps. Offline.
|
||||
// storebound originality [--against <folder>[,<folder>]] [--threshold 0.7] [--json]
|
||||
// --against (or originality.against in the config): folders with a storebound.config.ts, or workspace folders that
|
||||
// hold several apps one level down. Per other app: listing text, name, icon and screenshot perceptual hashes, project
|
||||
// structure (file layout and identical files), an overall score, why a pair is flagged, and what to change.
|
||||
// Exit 1 when a pair is flagged as a near-duplicate. The scoring is in cli/lib/originality.ts; the judgement
|
||||
// (mechanic, content, differentiator sentence) is the portfolio-originality skill.
|
||||
import { realpathSync } from 'node:fs';
|
||||
import { relative } from 'node:path';
|
||||
import { loadConfig } from './lib/config';
|
||||
import type { Ctx } from './lib/ctx';
|
||||
import { done, log, printJson, warn } from './lib/log';
|
||||
import { DEFAULT_THRESHOLD, findApps, fingerprint, report } from './lib/originality';
|
||||
import { textTable } from './lib/table';
|
||||
|
||||
const TAG = 'originality';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const folders = (a.list('against').length ? a.list('against') : config.originality?.against ?? []).map(f => resolve(f));
|
||||
if (!folders.length) throw new Error('nothing to compare with: --against <folder of another app, or a folder holding several> (or originality.against in the config)');
|
||||
const threshold = a.has('threshold') ? a.num('threshold', DEFAULT_THRESHOLD) : config.originality?.threshold ?? DEFAULT_THRESHOLD;
|
||||
if (!(threshold > 0 && threshold < 1)) throw new Error('--threshold: between 0 and 1');
|
||||
const self = realpathSync(root);
|
||||
const configs = findApps(folders.map(f => { try { return realpathSync(f); } catch { return f; } }), self);
|
||||
if (!configs.length) throw new Error(`no other app (storebound.config.ts) in ${folders.map(f => relative(root, f) || '.').join(', ')}`);
|
||||
const json = a.has('json');
|
||||
if (!json) log(TAG, `${config.app.name} vs ${configs.length} app(s), offline`);
|
||||
const me = fingerprint(config, root);
|
||||
const others = [];
|
||||
for (const p of configs) {
|
||||
try {
|
||||
const l = await loadConfig(p);
|
||||
others.push(fingerprint(l.config, l.root));
|
||||
} catch (e) { warn(TAG, `${p}: skipped (${(e as Error).message.split('\n')[0]?.slice(0, 160)})`); }
|
||||
}
|
||||
const r = report(me, others, threshold);
|
||||
if (json) { printJson(r); if (r.flagged) process.exitCode = 1; return; }
|
||||
for (const n of me.notes) warn(TAG, `${config.app.name}: ${n}`);
|
||||
const pct = (x: number | null) => (x === null ? '-' : `${Math.round(x * 100)}%`);
|
||||
console.log(textTable(['app', 'overall', 'name', 'text', 'icon', 'screens', 'structure', ''], r.pairs.map(p =>
|
||||
[p.other.name, pct(p.overall), pct(p.axes.name.score), pct(p.axes.text.score), pct(p.axes.icon.score), pct(p.axes.screenshots.score), pct(p.axes.structure.score), p.flagged ? 'NEAR-DUPLICATE' : ''])));
|
||||
for (const p of r.pairs) {
|
||||
if (!p.flagged && !p.suggestions.length) continue;
|
||||
console.log(`\n${p.other.name} (${relative(root, p.other.dir) || '.'})${p.flagged ? ': flagged' : ''}`);
|
||||
for (const why of p.reasons) console.log(` - ${why}`);
|
||||
for (const s of p.suggestions) console.log(` > ${s}`);
|
||||
}
|
||||
for (const o of r.others) for (const n of o.notes) log(TAG, `${relative(root, o.dir) || '.'}: ${n}`);
|
||||
if (r.flagged) { warn(TAG, `${r.flagged} near-duplicate(s) at threshold ${threshold}: see the portfolio-originality skill before submitting`); process.exitCode = 1; }
|
||||
done(TAG, `${r.pairs.length} pair(s) compared, ${r.flagged} flagged`);
|
||||
}
|
||||
91
cli/play/build.ts
Normal file
91
cli/play/build.ts
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
// Build a signed release Android App Bundle.
|
||||
// storebound play build [--version-code N] [--version-name 1.2.0] [--flavor prod] [--dir android] [--module app]
|
||||
// [--out build/android] [--dry] [--json]
|
||||
// Finds the Gradle project (android/ of Capacitor, React Native and Flutter apps, the root of a native one, a Unity
|
||||
// export with launcher/ + unityLibrary/), takes the next free versionCode from Google Play (play next-version-code)
|
||||
// unless --version-code is given, runs `gradlew :app:bundleRelease` (Flutter: flutter build appbundle) and copies the
|
||||
// AAB to <out>/<package>-<versionCode>.aab, checked by reading its manifest. Signing: the upload key from env or
|
||||
// .storebound/credentials.json (ANDROID_KEYSTORE, ANDROID_KEYSTORE_PASSWORD, ANDROID_KEY_ALIAS, ANDROID_KEY_PASSWORD)
|
||||
// goes to Gradle as injected signing properties through the environment, never on the command line; without it the
|
||||
// project's own signingConfig signs. Local only: Play is only read (version codes).
|
||||
import { copyFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { join, relative } from 'node:path';
|
||||
import { androidSigning } from '../lib/credentials';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { need } from '../lib/ctx';
|
||||
import { done, log, printJson, warn } from '../lib/log';
|
||||
import { pump } from '../lib/runner';
|
||||
import { aabInfo, findBundles, gradleArgs, pickGradle, signingEnv } from '../lib/gradle';
|
||||
import { nextVersionCode } from '../lib/release';
|
||||
import { playClient } from './client';
|
||||
import { usedVersionCodes } from './next-version-code';
|
||||
|
||||
const TAG = 'build';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const pkg = need(config.play?.packageName, 'play.packageName');
|
||||
const cfg = config.play?.build ?? {};
|
||||
const flavor = a.get('flavor') ?? cfg.flavor;
|
||||
const t = pickGradle(root, { dir: a.get('dir') ?? cfg.dir, module: a.get('module') ?? cfg.module, flavor });
|
||||
const dry = a.has('dry');
|
||||
const json = a.has('json');
|
||||
const out = resolve(a.get('out') ?? 'build/android');
|
||||
let code = a.has('version-code') ? a.num('version-code', 0) : 0;
|
||||
if (a.has('version-code') && !(Number.isInteger(code) && code > 0 && code <= 2_100_000_000)) throw new Error('--version-code: 1-2100000000');
|
||||
if (!code) {
|
||||
try {
|
||||
const play = await playClient(root, pkg);
|
||||
code = await play.read(async id => nextVersionCode(await usedVersionCodes(play, id)));
|
||||
log(TAG, `next free versionCode on Google Play: ${code}`);
|
||||
} catch (e) {
|
||||
if (!dry) throw new Error(`${(e as Error).message}\n(pass --version-code N to build without reading Google Play)`);
|
||||
warn(TAG, `Google Play not readable (${(e as Error).message.split('\n')[0]?.slice(0, 120)}): dry run continues without a versionCode`);
|
||||
}
|
||||
}
|
||||
const versionName = a.get('version-name');
|
||||
const signing = androidSigning(root);
|
||||
const hasWrapper = existsSync(join(t.dir, 'gradlew'));
|
||||
const argv = gradleArgs(t, { versionCode: code || undefined, versionName, flavor, hasWrapper });
|
||||
const cwd = t.framework === 'flutter' ? root : t.dir;
|
||||
const plan = { framework: t.framework, dir: relative(root, t.dir) || '.', module: t.module, task: t.framework === 'flutter' ? 'flutter build appbundle' : t.task,
|
||||
versionCode: code || null, versionName: versionName ?? null, signing: signing ? `upload key from ${process.env.ANDROID_KEYSTORE ? 'env' : '.storebound/credentials.json'} (alias ${signing.keyAlias})` : 'the project\'s own signingConfig',
|
||||
command: argv.join(' '), out: relative(root, out) || '.', notes: t.notes };
|
||||
if (dry) {
|
||||
if (json) { printJson(plan); return; }
|
||||
log(TAG, `${t.framework}: ${plan.dir} ${plan.task}, versionCode ${code || '?'}${versionName ? `, versionName ${versionName}` : ''}`);
|
||||
log(TAG, `signing: ${plan.signing}`);
|
||||
for (const n of t.notes) log(TAG, n);
|
||||
log(TAG, `would run (in ${relative(root, cwd) || '.'}): ${plan.command}`);
|
||||
done(TAG, 'build planned (dry run)');
|
||||
return;
|
||||
}
|
||||
if (signing && !existsSync(signing.storeFile)) throw new Error('ANDROID_KEYSTORE: the keystore file does not exist');
|
||||
if (!signing) warn(TAG, 'no ANDROID_KEYSTORE: the project\'s own release signingConfig must sign, else Play refuses the bundle');
|
||||
for (const n of t.notes) log(TAG, n);
|
||||
log(TAG, `$ ${plan.command}`);
|
||||
const started = Date.now();
|
||||
mkdirSync(out, { recursive: true });
|
||||
const p = Bun.spawn(argv, { cwd, stdout: 'pipe', stderr: 'pipe', env: { ...process.env, ...signingEnv(signing) } });
|
||||
const lines: string[] = [];
|
||||
const each = (line: string): void => {
|
||||
lines.push(line);
|
||||
if (/^(> Task .*bundle|BUILD (SUCCESSFUL|FAILED)|FAILURE:|\* What went wrong|e: |error:|✓ Built)/.test(line)) log(TAG, line.trim().slice(0, 300));
|
||||
};
|
||||
await Promise.all([pump(p.stdout, 'stdout', each), pump(p.stderr, 'stderr', each)]);
|
||||
const exit = await p.exited;
|
||||
const logFile = join(out, 'gradle.log');
|
||||
writeFileSync(logFile, lines.join('\n'));
|
||||
if (exit !== 0) throw new Error(`build failed (exit ${exit}); last lines:\n${lines.slice(-20).join('\n')}\nfull log: ${relative(root, logFile)}`);
|
||||
const aab = findBundles([join(t.dir, t.module, 'build', 'outputs', 'bundle'), join(root, 'build', 'app', 'outputs', 'bundle')], started - 1000)[0];
|
||||
if (!aab) throw new Error(`build finished but no new .aab under ${relative(root, t.dir)}/${t.module}/build/outputs/bundle`);
|
||||
const info = aabInfo(aab);
|
||||
if (info.packageName !== pkg) warn(TAG, `the AAB's package is ${info.packageName}, the config says ${pkg}`);
|
||||
if (code && info.versionCode !== code) warn(TAG, `the AAB has versionCode ${info.versionCode}, not ${code}: the build file sets it itself; read -PversionCode there or pass that number to play upload knowingly`);
|
||||
const dest = join(out, `${info.packageName}-${info.versionCode}.aab`);
|
||||
copyFileSync(aab, dest);
|
||||
const result = { aab: dest, packageName: info.packageName, versionCode: info.versionCode, versionName: info.versionName ?? null };
|
||||
if (json) printJson(result);
|
||||
done(TAG, `${relative(root, dest)}: ${info.packageName} ${info.versionName ?? ''} (${info.versionCode}). Next: storebound play upload ${relative(root, dest)} --track internal --dry`);
|
||||
}
|
||||
|
|
@ -6,11 +6,15 @@
|
|||
// Listings: title, short and full description of every `<!-- play: ... -->` section of the listing file, plus the promo
|
||||
// video (play.video, a YouTube URL) on every language. Play has no video upload: make the video with
|
||||
// `storebound shots video --target youtube`, upload it to YouTube (public or unlisted, ads off, embeddable), paste the URL.
|
||||
import { readFileSync } from 'node:fs';
|
||||
// And the other way round (read-only on Play, one throwaway edit that is deleted):
|
||||
// storebound play listing pull [--write] [--json] live listings -> diff -> (with --write) the Play listing file
|
||||
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { parsePlayListing } from '../lib/copy';
|
||||
import { compactDiff } from '../lib/diff';
|
||||
import { mergePlayListing, overLimits } from '../lib/listing-pull';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { need } from '../lib/ctx';
|
||||
import { done, log, step } from '../lib/log';
|
||||
import { done, log, printJson, step, warn } from '../lib/log';
|
||||
import { playClient } from './client';
|
||||
|
||||
export function readPlayCopy(ctx: Ctx) {
|
||||
|
|
@ -47,8 +51,33 @@ export function detailsChanges(current: Record<string, string | undefined>, want
|
|||
return Object.keys(wanted).filter(k => (current[k] ?? '') !== (wanted[k] ?? ''));
|
||||
}
|
||||
|
||||
async function pull(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const play = await playClient(root, need(config.play?.packageName, 'play.packageName'));
|
||||
const now = await play.read(async id => (await play.call<{ listings?: PlayListing[] }>('GET', `${play.API}/edits/${id}/listings`)).listings ?? []);
|
||||
const file = resolve(config.play?.listing ?? 'store/listing.md');
|
||||
const before = existsSync(file) ? readFileSync(file, 'utf8') : '# Google Play listing copy\n\nPulled from Google Play by `storebound play listing pull`.\n';
|
||||
const r = mergePlayListing(before, now, config.app.name);
|
||||
const over = overLimits(r.changes, 'play');
|
||||
const diff = compactDiff(before, r.md);
|
||||
if (a.has('json')) printJson({ file, write: a.has('write') && !a.has('dry'), languages: now.map(l => l.language), changes: r.changes, added: r.added, conflicts: r.conflicts, overLimits: over, diff });
|
||||
else {
|
||||
log('play', `pull: ${now.length} listing(s) on Play`);
|
||||
for (const ch of r.changes) log('play', `${ch.section} ${ch.field}: ${ch.from === null ? 'new' : 'changed'}`);
|
||||
if (diff.length) console.log(diff.join('\n'));
|
||||
}
|
||||
for (const c of r.conflicts) warn('play', c);
|
||||
for (const o of over) warn('play', `over the limit on the store: ${o}`);
|
||||
if (!r.changes.length) { done('play', `${file} already matches the store`); return; }
|
||||
if (!a.has('write') || a.has('dry')) { done('play', `${r.changes.length} change(s); nothing written (add --write to update ${file})`); return; }
|
||||
writeFileSync(file, r.md);
|
||||
done('play', `${file}: ${r.changes.length} change(s) written${r.added.length ? `, new languages ${r.added.join(', ')}` : ''}`);
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
if (ctx.args._[0] === 'pull') return pull(ctx);
|
||||
const pkg = need(config.play?.packageName, 'play.packageName');
|
||||
const copy = readPlayCopy(ctx);
|
||||
const details = { defaultLanguage: config.play?.defaultLanguage ?? 'en-US', contactEmail: config.app.contactEmail, contactWebsite: config.app.website };
|
||||
|
|
|
|||
|
|
@ -6,16 +6,21 @@ import type { Ctx } from '../lib/ctx';
|
|||
import { need } from '../lib/ctx';
|
||||
import { printJson } from '../lib/log';
|
||||
import { nextVersionCode } from '../lib/release';
|
||||
import { playClient } from './client';
|
||||
import { type PlayClient, playClient } from './client';
|
||||
|
||||
/** Every versionCode Play knows for the app: uploaded bundles and APKs, and the codes on every track (read-only edit). */
|
||||
export async function usedVersionCodes(play: PlayClient, id: string): Promise<number[]> {
|
||||
const bundles = (await play.call<{ bundles?: { versionCode: number }[] }>('GET', `${play.API}/edits/${id}/bundles`)).bundles ?? [];
|
||||
const apks = (await play.call<{ apks?: { versionCode: number }[] }>('GET', `${play.API}/edits/${id}/apks`).catch(() => ({ apks: [] }))).apks ?? [];
|
||||
const tracks = (await play.call<{ tracks?: { releases?: { versionCodes?: string[] }[] }[] }>('GET', `${play.API}/edits/${id}/tracks`)).tracks ?? [];
|
||||
return [...bundles.map(b => b.versionCode), ...apks.map(a => a.versionCode), ...tracks.flatMap(t => (t.releases ?? []).flatMap(r => (r.versionCodes ?? []).map(Number)))];
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const play = await playClient(root, need(config.play?.packageName, 'play.packageName'));
|
||||
await play.read(async id => {
|
||||
const bundles = (await play.call<{ bundles?: { versionCode: number }[] }>('GET', `${play.API}/edits/${id}/bundles`)).bundles ?? [];
|
||||
const apks = (await play.call<{ apks?: { versionCode: number }[] }>('GET', `${play.API}/edits/${id}/apks`).catch(() => ({ apks: [] }))).apks ?? [];
|
||||
const tracks = (await play.call<{ tracks?: { releases?: { versionCodes?: string[] }[] }[] }>('GET', `${play.API}/edits/${id}/tracks`)).tracks ?? [];
|
||||
const codes = [...bundles.map(b => b.versionCode), ...apks.map(a => a.versionCode), ...tracks.flatMap(t => (t.releases ?? []).flatMap(r => r.versionCodes ?? []))];
|
||||
const codes = await usedVersionCodes(play, id);
|
||||
// the same code is in the bundle list and on every track it was released to: count distinct codes
|
||||
const distinct = new Set(codes.map(String)).size;
|
||||
if (ctx.args.has('json')) printJson({ next: nextVersionCode(codes), seen: distinct });
|
||||
|
|
|
|||
78
cli/play/upload.ts
Normal file
78
cli/play/upload.ts
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
// Upload an Android App Bundle to a Google Play testing track.
|
||||
// storebound play upload [<app.aab>] [--track internal|alpha|beta] [--status completed|draft] [--name text] [--dry] [--yes] [--json]
|
||||
// Default AAB: the newest in build/android (storebound play build). Package and versionCode are read from the bundle;
|
||||
// the upload is refused when Play already has that versionCode. Release notes: the "What's new" of every listing
|
||||
// language. --dry is read-only (one throwaway edit: version codes and the track are read, the edit is deleted).
|
||||
// A real run asks first (--yes in scripts). Production is not offered here: `storebound play release --production
|
||||
// draft` (and the play-first-release / release-management skills) keep that the owner's step.
|
||||
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join, relative } from 'node:path';
|
||||
import type { Ctx } from '../lib/ctx';
|
||||
import { confirm, need } from '../lib/ctx';
|
||||
import { aabInfo } from '../lib/gradle';
|
||||
import { done, log, printJson } from '../lib/log';
|
||||
import { nextVersionCode } from '../lib/release';
|
||||
import { playClient } from './client';
|
||||
import { readPlayCopy } from './listing';
|
||||
import { usedVersionCodes } from './next-version-code';
|
||||
|
||||
const TAG = 'upload';
|
||||
export const UPLOAD_TRACKS = ['internal', 'alpha', 'beta'] as const;
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const pkg = need(config.play?.packageName, 'play.packageName');
|
||||
const track = a.str('track', 'internal');
|
||||
if (track === 'production') throw new Error('play upload is for testing tracks; production goes through storebound play release --production draft (the owner sends it)');
|
||||
if (!(UPLOAD_TRACKS as readonly string[]).includes(track)) throw new Error(`--track: ${UPLOAD_TRACKS.join(' | ')}`);
|
||||
const status = a.str('status', 'completed');
|
||||
if (!['completed', 'draft'].includes(status)) throw new Error('--status: completed | draft');
|
||||
let aab = a._.find(x => x.endsWith('.aab'));
|
||||
if (aab) aab = resolve(aab);
|
||||
else {
|
||||
const dir = resolve('build/android');
|
||||
let found: string[] = [];
|
||||
try { found = readdirSync(dir).filter(f => f.endsWith('.aab')).map(f => join(dir, f)).sort((x, y) => statSync(y).mtimeMs - statSync(x).mtimeMs); } catch { /* none */ }
|
||||
if (!found[0]) throw new Error('usage: storebound play upload <app.aab> --track internal (nothing in build/android; storebound play build makes one)');
|
||||
aab = found[0];
|
||||
}
|
||||
const info = aabInfo(aab);
|
||||
if (info.packageName !== pkg) throw new Error(`${relative(root, aab)} is ${info.packageName}, the config says ${pkg}`);
|
||||
const size = statSync(aab).size;
|
||||
const dry = a.has('dry');
|
||||
const json = a.has('json');
|
||||
const notes = readPlayCopy(ctx).filter(c => c.whatsNew).map(c => ({ language: c.lang, text: c.whatsNew }));
|
||||
const play = await playClient(root, pkg);
|
||||
const { used, current } = await play.read(async id => ({
|
||||
used: await usedVersionCodes(play, id),
|
||||
current: (await play.call<{ releases?: { status: string; versionCodes?: string[] }[] }>('GET', `${play.API}/edits/${id}/tracks/${track}`).catch(() => ({ releases: [] }))).releases ?? [],
|
||||
}));
|
||||
if (used.includes(info.versionCode)) throw new Error(`versionCode ${info.versionCode} is already on Google Play: rebuild with --version-code ${nextVersionCode(used)} (storebound play build)`);
|
||||
const summary = { aab: relative(root, aab), packageName: info.packageName, versionCode: info.versionCode, versionName: info.versionName ?? null, sizeMB: Math.round(size / 104857.6) / 10,
|
||||
track, status, notes: notes.map(n => n.language), replaces: current.map(r => `${r.status} ${(r.versionCodes ?? []).join(',')}`) };
|
||||
if (dry) {
|
||||
if (json) { printJson(summary); return; }
|
||||
log(TAG, `${summary.aab}: ${info.packageName} ${info.versionName ?? ''} (${info.versionCode}), ${summary.sizeMB} MB, versionCode free`);
|
||||
log(TAG, `would upload it and set track ${track} to ${status} ${info.versionCode}${notes.length ? `, notes in ${notes.length} language(s)` : ', no release notes'}${current.length ? ` (now on ${track}: ${summary.replaces.join('; ')})` : ''}`);
|
||||
done(TAG, 'upload planned (dry run, read-only)');
|
||||
return;
|
||||
}
|
||||
if (!(await confirm(ctx, `Upload ${info.packageName} versionCode ${info.versionCode} and put it on the ${track} track (${status})? Testers of that track get it.`))) return;
|
||||
try {
|
||||
await play.edit(async id => {
|
||||
log(TAG, `uploading ${summary.sizeMB} MB, this can take minutes`);
|
||||
const b = await play.call<{ versionCode: number }>('POST', `${play.UPLOAD}/edits/${id}/bundles?uploadType=media`, new Uint8Array(readFileSync(aab!)), { 'Content-Type': 'application/octet-stream' });
|
||||
log(TAG, `uploaded versionCode ${b.versionCode}`);
|
||||
const release: Record<string, unknown> = { versionCodes: [String(b.versionCode)], status, ...(notes.length ? { releaseNotes: notes } : {}), ...(a.get('name') ? { name: a.get('name') } : {}) };
|
||||
await play.call('PUT', `${play.API}/edits/${id}/tracks/${track}`, { track, releases: [release] });
|
||||
log(TAG, `${track} <- ${b.versionCode} (${status})`);
|
||||
}, { retries: 0 });
|
||||
} catch (e) {
|
||||
if (/draft app|status draft/i.test(String(e)) && status !== 'draft')
|
||||
throw new Error(`${(e as Error).message}\n\nThis app has never been published: Play only takes draft releases. Re-run with --status draft and roll it out from the Console (skill play-first-release).`);
|
||||
throw e;
|
||||
}
|
||||
if (json) printJson({ ...summary, uploaded: true });
|
||||
done(TAG, `versionCode ${info.versionCode} on ${track}`);
|
||||
}
|
||||
171
cli/release.ts
Normal file
171
cli/release.ts
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
// `storebound release`: release trains from the terminal, read-only. The same stages as the desktop's Releases tab
|
||||
// (cli/lib/train.ts, cli/lib/app-status.ts are shared with it).
|
||||
// release status [--app a,b] [--versions] [--json]
|
||||
// per app: the version that reaches users and the next one, both stores on one train
|
||||
// (build -> testing -> review -> live -> rollout %); --versions lists every version the stores know
|
||||
// release plan <version> [--app a] [--no-validate] [--json]
|
||||
// what is left for <version> on each store, in fix order: config problems (check), the version on the store,
|
||||
// store blockers (validate), the next move (owner steps are named, never done), warnings
|
||||
// In an app folder: that app (its own credentials). In a workspace (storebound.workspace.json above): every app, or
|
||||
// --app a,b, with the credential profiles of the workspace.
|
||||
import { existsSync } from 'node:fs';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import type { Args } from './lib/args';
|
||||
import { emptyStatus, fillAppStatus, lastLine, pool } from './lib/app-status';
|
||||
import { CONFIG_NAMES } from './lib/config';
|
||||
import type { AppStatus, ReleaseTrain } from './lib/desktop-protocol';
|
||||
import { log, printJson, warn } from './lib/log';
|
||||
import { runCommand, type RunResult } from './lib/runner';
|
||||
import { textTable } from './lib/table';
|
||||
import { laneOf, laneText, type PlanStep, releasePlan, type ReleasePlan, trackText, versionHistory } from './lib/train';
|
||||
import type { Finding } from './lib/validate-rules';
|
||||
import { findWorkspace, loadWorkspace, resolveApps, selectApps } from './lib/workspace';
|
||||
import { appDir, appEnv, workspaceApps } from './workspace';
|
||||
|
||||
interface Target { name: string; dir: string; virtual: boolean; env: Record<string, string>; problems: string[] }
|
||||
|
||||
const USAGE = 'usage: storebound release status [--app a,b] [--versions] [--json] | release plan <version> [--app a] [--no-validate] [--json]';
|
||||
|
||||
function configDir(from: string): string | null {
|
||||
for (let d = resolve(from); ; d = dirname(d)) {
|
||||
if (CONFIG_NAMES.some(n => existsSync(join(d, n)))) return d;
|
||||
if (dirname(d) === d) return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The apps to read: this app folder, or the workspace's apps (filtered by --app). */
|
||||
async function targets(args: Args): Promise<{ list: Target[]; concurrency: number }> {
|
||||
const cwd = process.cwd();
|
||||
const here = configDir(cwd);
|
||||
const wsFile = findWorkspace(cwd, args.get('workspace'));
|
||||
// an app folder wins unless --app asks for the workspace (or the workspace file is closer than the config)
|
||||
if (here && !args.get('app') && (!wsFile || dirname(wsFile).length <= here.length)) {
|
||||
return { list: [{ name: here.split(/[\\/]/).pop() ?? here, dir: here, virtual: false, env: {}, problems: [] }], concurrency: 1 };
|
||||
}
|
||||
if (!wsFile) throw new Error('no storebound.config.ts here and no storebound.workspace.json above (run it in an app folder or a workspace)');
|
||||
const l = await loadWorkspace(cwd, args.get('workspace'));
|
||||
const n = Math.min(8, Math.max(1, l.ws.concurrency ?? 4));
|
||||
const { apps: folders } = resolveApps(l);
|
||||
const summaries = new Map<string, AppStatus['summary']>();
|
||||
await pool(folders, n, async f => {
|
||||
const r = await runCommand(['inspect', '--json'], { cwd: f.path, machine: true }).result;
|
||||
if (r.code === 0 && r.data) summaries.set(f.id, r.data as AppStatus['summary']);
|
||||
});
|
||||
const { apps, accounts } = workspaceApps(l, summaries);
|
||||
const { picked, unknown } = selectApps(apps.filter(a => !a.ignored), args.list('app'));
|
||||
if (unknown.length) throw new Error(`--app: no app named ${unknown.join(', ')} (storebound ws list shows the names)`);
|
||||
return { list: picked.map(a => { const { env, problems } = appEnv(a.unified, accounts); return { name: a.name, dir: appDir(a), virtual: a.virtual, env, problems }; }), concurrency: n };
|
||||
}
|
||||
|
||||
const exec = (env: Record<string, string>) => (argv: string[], cwd: string): Promise<RunResult> => runCommand(argv, { cwd, env, machine: true }).result;
|
||||
|
||||
async function readLive(t: Target): Promise<AppStatus> {
|
||||
const e = emptyStatus(t.dir);
|
||||
if (t.virtual) e.virtual = true;
|
||||
try { await fillAppStatus(e, t.dir, { live: true, virtual: t.virtual, exec: exec(t.env) }); } catch (err) { e.errors.push((err as Error).message); }
|
||||
if (e.summary?.name) t.name = e.summary.name;
|
||||
return e;
|
||||
}
|
||||
|
||||
export interface TrainRow { app: string; version: string; which: 'current' | 'next' | 'other'; ios: string; android: string }
|
||||
|
||||
/** The trains of one app to show: current + next (the desktop's portfolio), or every version. */
|
||||
export function trainsOf(s: AppStatus, all: boolean): { which: TrainRow['which']; train: ReleaseTrain }[] {
|
||||
if (all) {
|
||||
const cur = s.release.current?.version, next = s.release.next?.version;
|
||||
return versionHistory(s.release.all ?? []).map(t => ({ which: t.version === cur ? 'current' as const : t.version === next ? 'next' as const : 'other' as const, train: t }));
|
||||
}
|
||||
return [...(s.release.current ? [{ which: 'current' as const, train: s.release.current }] : []), ...(s.release.next ? [{ which: 'next' as const, train: s.release.next }] : [])];
|
||||
}
|
||||
|
||||
const cell = (store: 'ios' | 'android', t: ReleaseTrain, s: AppStatus): string => {
|
||||
if (s.storeErrors[store]) return 'unreadable';
|
||||
const on = store === 'ios' ? s.summary?.apple : s.summary?.play;
|
||||
if (!on) return '';
|
||||
const r = t[store];
|
||||
if (!r) return '-';
|
||||
const extra = [r.build ? `build ${r.build}` : '', store === 'android' && r.track && r.track !== 'production' ? r.track : ''].filter(Boolean).join(', ');
|
||||
return `${laneText(laneOf(store, r))}${extra ? ` (${extra})` : ''}`;
|
||||
};
|
||||
|
||||
async function status(args: Args): Promise<void> {
|
||||
const { list, concurrency } = await targets(args);
|
||||
const all = args.has('versions');
|
||||
const read = await pool(list, concurrency, async t => ({ t, s: await readLive(t) }));
|
||||
if (args.has('json')) {
|
||||
printJson({ apps: read.map(({ t, s }) => ({
|
||||
app: t.name, folder: t.virtual ? null : t.dir, errors: [...t.problems, ...s.errors], storeErrors: s.storeErrors,
|
||||
trains: trainsOf(s, all).map(({ which, train }) => ({ which, version: train.version, ios: train.ios, android: train.android,
|
||||
lanes: { ios: laneOf('ios', train.ios), android: laneOf('android', train.android) } })),
|
||||
})), at: new Date().toISOString() });
|
||||
} else {
|
||||
const rows: string[][] = [];
|
||||
for (const { t, s } of read) {
|
||||
const trains = trainsOf(s, all);
|
||||
const unread = Object.keys(s.storeErrors).length > 0;
|
||||
if (!trains.length) rows.push([t.name, '', '', s.errors[0] ? `error: ${s.errors[0]}` : unread ? 'not read (see the warnings)' : 'no version on either store yet', '']);
|
||||
for (const { which, train } of trains) rows.push([t.name, train.version, which === 'other' ? '' : which, cell('ios', train, s), cell('android', train, s)]);
|
||||
for (const p of [...t.problems, ...s.errors.slice(trains.length ? 0 : 1), ...Object.entries(s.storeErrors).map(([k, v]) => `${k}: ${v}`)]) warn('release', `${t.name}: ${p}`);
|
||||
}
|
||||
console.log(textTable(['app', 'version', 'train', 'App Store', 'Google Play'], rows));
|
||||
log('release', 'stages: build > testing > review > live > rollout (%); owner steps (submit, release, rollout) stay with the owner');
|
||||
}
|
||||
if (read.some(({ s }) => s.errors.length || s.storeErrors.ios || s.storeErrors.android)) process.exitCode = 1;
|
||||
}
|
||||
|
||||
const KIND: Record<PlanStep['kind'], string> = { config: 'CONFIG ', store: 'STORE ', blocker: 'BLOCKER', owner: 'OWNER ', wait: 'wait ', warning: 'warn ', done: 'done ' };
|
||||
|
||||
export function formatPlan(app: string, p: ReleasePlan): string {
|
||||
const out: string[] = [`${app} ${p.version}${p.done ? ': live everywhere, nothing left' : ''}`];
|
||||
let i = 0;
|
||||
const line = (s: PlanStep) => ` ${String(++i).padStart(2)}. ${KIND[s.kind]} ${s.text}${s.fix ? `\n -> ${s.fix}` : ''}`;
|
||||
if (p.shared.length) { out.push(' both stores (fix first):'); out.push(...p.shared.map(line)); }
|
||||
for (const sp of [p.ios, p.android]) {
|
||||
if (!sp) continue;
|
||||
out.push(` ${sp.store === 'ios' ? 'App Store' : 'Google Play'}: ${sp.release ? `${laneText(sp.lane)} [${trackText(sp.lane)}]` : 'not on the store'}`);
|
||||
out.push(...sp.steps.map(line));
|
||||
}
|
||||
for (const u of p.unknown) out.push(` unknown: ${u}`);
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
async function plan(args: Args): Promise<void> {
|
||||
const version = args._[1];
|
||||
if (!version || !/^\d+(\.\d+){0,3}$/.test(version)) throw new Error('release plan <version>, e.g. release plan 2.4.0');
|
||||
const { list, concurrency } = await targets(args);
|
||||
const plans = await pool(list, concurrency, async t => {
|
||||
const s = await readLive(t);
|
||||
const check = s.check ? { problems: s.check.problems, warnings: s.check.warnings } : null;
|
||||
let validate: Finding[] | null = null;
|
||||
// validate only while something is not yet submitted on a store (it reads the editable version / the Play edit)
|
||||
const pre = releasePlan({ version, platforms: { ios: !!s.summary?.apple, android: !!s.summary?.play }, check, validate: [], releases: s.release.all ?? null, storeErrors: s.storeErrors });
|
||||
const needs = [pre.ios, pre.android].some(x => x && !x.done && (!x.release || ['draft', 'testing', 'rejected', 'other'].includes(x.release.phase)));
|
||||
if (needs && !args.has('no-validate') && !t.virtual && s.summary) {
|
||||
if (!args.has('json')) log('release', `${t.name}: validate (read-only, both stores)`);
|
||||
const r = await exec(t.env)(['validate', '--json', '--no-health'], t.dir);
|
||||
const d = r.data as { findings?: Finding[] } | undefined;
|
||||
if (d?.findings) validate = d.findings;
|
||||
else s.errors.push(`validate: ${lastLine(r.out) || `exit ${r.code}`}`);
|
||||
} else if (!needs) validate = [];
|
||||
const p = releasePlan({ version, platforms: { ios: !!s.summary?.apple, android: !!s.summary?.play }, check, validate, releases: s.summary ? s.release.all ?? null : null, storeErrors: s.storeErrors });
|
||||
if (args.has('no-validate') && needs) p.unknown = p.unknown.map(u => (u.startsWith('store readiness') ? 'store readiness not checked (--no-validate)' : u));
|
||||
return { t, s, p };
|
||||
});
|
||||
if (args.has('json')) printJson({ version, apps: plans.map(({ t, s, p }) => ({ app: t.name, folder: t.virtual ? null : t.dir, errors: [...t.problems, ...s.errors], plan: p })) });
|
||||
else {
|
||||
for (const { t, s, p } of plans) {
|
||||
console.log(formatPlan(t.name, p));
|
||||
for (const e of [...t.problems, ...s.errors]) warn('release', `${t.name}: ${e}`);
|
||||
console.log('');
|
||||
}
|
||||
}
|
||||
if (plans.some(({ s }) => s.errors.length)) process.exitCode = 1;
|
||||
}
|
||||
|
||||
export async function run(args: Args): Promise<void> {
|
||||
const sub = args._[0];
|
||||
if (sub === 'status') return status(args);
|
||||
if (sub === 'plan') return plan(args);
|
||||
console.error(USAGE);
|
||||
process.exit(2);
|
||||
}
|
||||
121
cli/reports.ts
Normal file
121
cli/reports.ts
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
// Sales and finance reports of both stores into .storebound/reports/ (gitignored), with a summary table and a CSV export.
|
||||
// storebound reports apple-sales [--type SALES] [--frequency DAILY|WEEKLY|MONTHLY|YEARLY] [--date ...] [--vendor N]
|
||||
// storebound reports apple-finance --month YYYY-MM [--detail] [--region ZZ] [--vendor N]
|
||||
// storebound reports play-earnings --month YYYY-MM
|
||||
// storebound reports play-sales --month YYYY-MM
|
||||
// common: [--out .storebound/reports] [--csv <summary.csv>] [--dry] [--json]
|
||||
// The raw report is saved as it came (the TSV / the CSV out of the zip) next to a <name>.summary.csv with only
|
||||
// aggregates (per product and currency; amounts are never added across currencies). --dry prints what would be
|
||||
// fetched and fetches nothing. Apple needs a team API key (not an individual key) with access to reports and the vendor
|
||||
// number (ASC_VENDOR_NUMBER in env or .storebound/credentials.json; --vendor). Play needs play.reportsBucket and the
|
||||
// service account with "View financial data". Read-only on both stores. Pure parts and sources: cli/lib/reports.ts.
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { ascClient } from './apple/asc';
|
||||
import { bucketName } from './lib/analytics';
|
||||
import { ascVendorNumber } from './lib/credentials';
|
||||
import type { Ctx } from './lib/ctx';
|
||||
import { need } from './lib/ctx';
|
||||
import { toCsv } from './lib/csv';
|
||||
import { STORAGE_READ_SCOPE } from './lib/google-auth';
|
||||
import { done, log, printJson, warn } from './lib/log';
|
||||
import {
|
||||
APPLE_SALES_COMBOS, appleFinancePath, appleReportDate, appleSalesPath, decodeReport, parsePlayCsv, parseTsv, playReportPrefix, type SummaryRow, summarizeAppleFinance,
|
||||
summarizeAppleSales, summarizePlayEarnings, summarizePlaySales, summaryCsvRows, totalsByCurrency,
|
||||
} from './lib/reports';
|
||||
import { textTable } from './lib/table';
|
||||
import { unzip } from './lib/zip';
|
||||
import { googleClient } from './play/google';
|
||||
|
||||
const TAG = 'reports';
|
||||
const USAGE = 'usage: storebound reports apple-sales | apple-finance --month YYYY-MM | play-earnings --month YYYY-MM | play-sales --month YYYY-MM';
|
||||
|
||||
function show(name: string, rows: SummaryRow[], json: boolean, extra: Record<string, unknown>): void {
|
||||
const totals = totalsByCurrency(rows);
|
||||
if (json) { printJson({ report: name, ...extra, summary: rows, totals }); return; }
|
||||
console.log(rows.length ? textTable(['product', 'title', 'currency', 'units', 'amount'], rows.map(r => [r.key, r.title.slice(0, 30), r.currency, r.units, r.amount.toFixed(2)])) : 'no rows');
|
||||
if (totals.length) console.log('\n' + textTable(['currency', 'units', 'total'], totals.map(t => [t.currency, t.units, t.amount.toFixed(2)])));
|
||||
}
|
||||
|
||||
function save(dir: string, name: string, raw: string | Uint8Array, rows: SummaryRow[], csvOut: string | undefined): { raw: string; summary: string } {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const rawFile = join(dir, name);
|
||||
writeFileSync(rawFile, raw);
|
||||
const summary = csvOut ?? join(dir, name.replace(/\.(tsv|csv|txt)$/, '') + '.summary.csv');
|
||||
mkdirSync(dirname(summary), { recursive: true });
|
||||
writeFileSync(summary, toCsv(summaryCsvRows(rows)));
|
||||
return { raw: rawFile, summary };
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const sub = a._[0];
|
||||
if (!sub) throw new Error(USAGE);
|
||||
const dry = a.has('dry');
|
||||
const out = resolve(a.get('out') ?? '.storebound/reports');
|
||||
const csvOut = a.get('csv') ? resolve(a.get('csv')!) : undefined;
|
||||
|
||||
if (sub === 'apple-sales' || sub === 'apple-finance') {
|
||||
const vendor = a.get('vendor') ?? ascVendorNumber(root);
|
||||
if (!vendor || !/^\d{5,12}$/.test(vendor)) throw new Error('vendor number missing: ASC_VENDOR_NUMBER in env or .storebound/credentials.json, or --vendor (App Store Connect > Payments and Financial Reports)');
|
||||
let path: string, name: string;
|
||||
if (sub === 'apple-sales') {
|
||||
const type = a.str('type', 'SALES').toUpperCase();
|
||||
const frequency = a.str('frequency', APPLE_SALES_COMBOS[type]?.frequencies[0] ?? 'DAILY').toUpperCase();
|
||||
const date = appleReportDate(frequency, a.get('date'));
|
||||
path = appleSalesPath(vendor, { type, frequency, date });
|
||||
name = `apple-${type.toLowerCase()}-${frequency.toLowerCase()}-${date}.tsv`;
|
||||
} else {
|
||||
const month = need(a.get('month'), '--month YYYY-MM');
|
||||
const type = a.has('detail') ? 'FINANCE_DETAIL' as const : 'FINANCIAL' as const;
|
||||
path = appleFinancePath(vendor, month, { type, region: a.get('region') });
|
||||
name = `apple-${type === 'FINANCIAL' ? 'finance' : 'finance-detail'}-${month}.tsv`;
|
||||
}
|
||||
const shown = path.replace(vendor, '<vendor>');
|
||||
if (dry) { if (a.has('json')) printJson({ dryRun: true, request: `GET ${shown}`, file: join(out, name) }); else log(TAG, `would GET ${shown} -> ${join(out, name)}`); return; }
|
||||
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
|
||||
log(TAG, `GET ${shown}`);
|
||||
const gz = await c.bytes(path);
|
||||
if (!gz) { done(TAG, 'no report for that date (no sales then, or not published yet: daily reports come out the next day, monthly ones about a week later)'); if (a.has('json')) printJson({ report: name, empty: true }); return; }
|
||||
const text = new TextDecoder().decode(gz[0] === 0x1f && gz[1] === 0x8b ? Bun.gunzipSync(gz as Uint8Array<ArrayBuffer>) : gz);
|
||||
const rows = parseTsv(text);
|
||||
const summary = sub === 'apple-sales' ? (a.str('type', 'SALES').toUpperCase() === 'SALES' ? summarizeAppleSales(rows) : []) : summarizeAppleFinance(rows);
|
||||
const files = save(out, name, text, summary, csvOut);
|
||||
show(name, summary, a.has('json'), { rows: rows.length, files });
|
||||
if (sub === 'apple-sales' && a.str('type', 'SALES').toUpperCase() !== 'SALES') log(TAG, `${rows.length} rows saved; the summary table covers SALES reports, open the TSV for this type`);
|
||||
done(TAG, `${rows.length} rows -> ${files.raw}; summary ${files.summary}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sub === 'play-earnings' || sub === 'play-sales') {
|
||||
const bucket = config.play?.reportsBucket;
|
||||
if (!bucket) throw new Error('play.reportsBucket is not set (Play Console > Download reports > Financial > Copy Cloud Storage URI)');
|
||||
const month = need(a.get('month'), '--month YYYY-MM');
|
||||
const kind = sub === 'play-earnings' ? 'earnings' : 'sales';
|
||||
const prefix = playReportPrefix(kind, month);
|
||||
const list = `https://storage.googleapis.com/storage/v1/b/${encodeURIComponent(bucketName(bucket))}/o?prefix=${encodeURIComponent(prefix)}`;
|
||||
if (dry) { if (a.has('json')) printJson({ dryRun: true, request: `GET gs://${bucketName(bucket)}/${prefix}*.zip`, dir: out }); else log(TAG, `would read gs://${bucketName(bucket)}/${prefix}*.zip -> ${out}`); return; }
|
||||
const g = googleClient(root, STORAGE_READ_SCOPE);
|
||||
const items = ((await g.json<{ items?: { name: string }[] }>('GET', list)).items ?? []).filter(o => o.name.endsWith('.zip'));
|
||||
if (!items.length) { done(TAG, `no ${prefix}*.zip in the bucket (not published yet: earnings come early in the next month; or the service account lacks "View financial data")`); if (a.has('json')) printJson({ report: kind, month, empty: true }); return; }
|
||||
const all: Record<string, string>[] = [];
|
||||
let text = '';
|
||||
for (const o of items) {
|
||||
log(TAG, `gs://${bucketName(bucket)}/${o.name}`);
|
||||
const zip = await g.bytes(`https://storage.googleapis.com/storage/v1/b/${encodeURIComponent(bucketName(bucket))}/o/${encodeURIComponent(o.name)}?alt=media`);
|
||||
for (const e of unzip(zip).filter(x => x.name.toLowerCase().endsWith('.csv'))) {
|
||||
const t = decodeReport(e.data);
|
||||
text += (text ? '\n' : '') + t;
|
||||
all.push(...parsePlayCsv(t));
|
||||
}
|
||||
}
|
||||
if (!all.length) warn(TAG, 'the zip(s) held no CSV rows');
|
||||
const summary = kind === 'earnings' ? summarizePlayEarnings(all) : summarizePlaySales(all);
|
||||
const files = save(out, `play-${kind}-${month}.csv`, text, summary, csvOut);
|
||||
show(`play-${kind}-${month}`, summary, a.has('json'), { rows: all.length, files });
|
||||
done(TAG, `${all.length} rows -> ${files.raw}; summary ${files.summary}`);
|
||||
return;
|
||||
}
|
||||
throw new Error(`unknown reports command "${sub}"\n${USAGE}`);
|
||||
}
|
||||
58
cli/scan.ts
Normal file
58
cli/scan.ts
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
// Offline, read-only scan of the project itself for App Store and Google Play rejection risks, before you submit.
|
||||
// storebound scan [--dir <project>] [--config <file>] [--store apple|play] [--json] [--no-declarations]
|
||||
// storebound scan --write also write the detected dataSafety / appPrivacy answers into the config
|
||||
// Reads the project files (Xcode project, Info.plist, entitlements, privacy manifests, Podfile.lock, Package.resolved,
|
||||
// Gradle files, AndroidManifest.xml and a local build's merged manifest, res/xml and strings.xml, CMake / ndk-build
|
||||
// files, package.json, app.json, capacitor.config, pubspec, Unity and Godot settings and ProjectVersion.txt), the
|
||||
// config and the listing files; detects the stack and the SDKs; reports each risk with the guideline, the evidence
|
||||
// (file:line), the fix, a severity and the skill; and proposes the Data safety / App Privacy / ATT / privacy manifest
|
||||
// answers as a diff against the config. Nothing is written without --write (and --dry always wins). No network.
|
||||
// Exit 1 while an open blocker is left.
|
||||
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import type { Args } from './lib/args';
|
||||
import { CONFIG_NAMES } from './lib/config';
|
||||
import { log, printJson, warn } from './lib/log';
|
||||
import { upsertBlock } from './lib/scan/config-edit';
|
||||
import { formatScan, runScan } from './lib/scan';
|
||||
|
||||
/** Project folder: --dir, else the folder of the nearest storebound.config.* above the working directory, else it. */
|
||||
function projectDir(args: Args): string {
|
||||
if (args.get('dir')) return resolve(args.get('dir')!);
|
||||
for (let d = process.cwd(); ; d = dirname(d)) {
|
||||
if (CONFIG_NAMES.some(n => existsSync(join(d, n)))) return d;
|
||||
if (dirname(d) === d) return process.cwd();
|
||||
}
|
||||
}
|
||||
|
||||
export async function run(args: Args): Promise<void> {
|
||||
const dir = projectDir(args);
|
||||
if (!existsSync(dir)) throw new Error(`${dir} does not exist`);
|
||||
const { report, configPath } = await runScan(dir, { config: args.get('config') });
|
||||
const store = args.get('store');
|
||||
if (store === 'apple' || store === 'play') {
|
||||
report.findings = report.findings.filter(f => f.store === store);
|
||||
report.counts = { blocker: 0, high: 0, medium: 0, low: 0, accepted: 0 };
|
||||
for (const f of report.findings) { if (f.accepted) report.counts.accepted++; else report.counts[f.severity]++; }
|
||||
} else if (store) throw new Error('--store apple | play');
|
||||
if (args.has('json')) printJson(report);
|
||||
else console.log(formatScan(report, { declarations: !args.has('no-declarations') }));
|
||||
|
||||
if (args.has('write')) {
|
||||
const d = report.declarations;
|
||||
if (!configPath) warn('scan', '--write: no storebound.config.ts in this project (storebound init creates one)');
|
||||
else if (!d.changed) log('scan', `--write: nothing to change in ${report.config}`);
|
||||
else if (args.has('dry')) log('scan', `--dry: would write ${[d.diff.some(x => x.change !== 'kept' && x.change !== 'same') && 'dataSafety', d.appPrivacyChange && 'appPrivacy'].filter(Boolean).join(' + ')} into ${report.config}`);
|
||||
else {
|
||||
let text = readFileSync(configPath, 'utf8');
|
||||
const ds = d.dataSafety!;
|
||||
const missing = (['encryptedInTransit', 'deletionRequest'] as const).filter(k => typeof ds[k] !== 'boolean');
|
||||
if (d.diff.some(x => x.change === 'add' || x.change === 'merge'))
|
||||
text = upsertBlock(text, configPath, 'dataSafety', ds, missing.length ? `storebound scan: answer ${missing.join(' and ')} (ask the owner; store-declarations skill)` : undefined);
|
||||
if (d.appPrivacyChange) text = upsertBlock(text, configPath, 'appPrivacy', d.appPrivacy);
|
||||
writeFileSync(configPath, text);
|
||||
log('scan', `wrote the detected answers into ${report.config}${missing.length ? `; still to answer: dataSafety.${missing.join(', dataSafety.')}` : ''}. Review the diff (git diff) before pushing it to a store.`);
|
||||
}
|
||||
}
|
||||
if (report.counts.blocker) process.exitCode = 1;
|
||||
}
|
||||
34
cli/serve.ts
34
cli/serve.ts
|
|
@ -19,7 +19,7 @@ import { CONFIG_NAMES } from './lib/config';
|
|||
import {
|
||||
DESKTOP_PROTOCOL, ERR, type AppStatus, type MethodDescriptor, type PortfolioResult, type ProjectSummary, type ToolResult, type VirtualProject,
|
||||
} from './lib/desktop-protocol';
|
||||
import { appIdentity, appleProductIds, appleReleases, catalogParity, playProductIds, playReleases, releaseTrains } from './lib/portfolio';
|
||||
import { emptyStatus, fillAppStatus, lastLine } from './lib/app-status';
|
||||
import { RENDER_FILE_RE } from './lib/project-files';
|
||||
import { detectTools } from './lib/tools';
|
||||
import { compiled, pickCallEnv, runCommand, type RunOptions, type Running } from './lib/runner';
|
||||
|
|
@ -39,13 +39,13 @@ const lang = { type: 'string', pattern: '^[A-Za-z0-9_-]{1,20}(,[A-Za-z0-9_-]{1,2
|
|||
export const PRICE_SHEET_RE = /^(?!-)[^\x00-\x1f]{1,1000}\.[cC][sS][vV]$/;
|
||||
|
||||
/** MCP tools the desktop profile leaves out (sending builds to testers on Play, release state changes: the window has
|
||||
* the owner actions for those). */
|
||||
export const DESKTOP_EXCLUDED = new Set(['play_release_testing', 'apple_phased_release']);
|
||||
* the owner actions for those; workspace and release-train reads: the window has portfolio.status for those; the raw API reader api_get). */
|
||||
export const DESKTOP_EXCLUDED = new Set(['play_release_testing', 'apple_phased_release', 'workspace_list', 'workspace_status', 'release_status', 'release_plan', 'api_get']);
|
||||
/** Words no desktop method name may contain. */
|
||||
export const FORBIDDEN_METHOD_WORDS = /submit|release|publish|rollout|resume|complete|send|start|stop|cancel|delete|remove|invite/i;
|
||||
|
||||
/** Read tools whose command prints a structured result with --json. */
|
||||
export const JSON_TOOLS = new Set(['check', 'check_aso', 'validate', 'health', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status',
|
||||
export const JSON_TOOLS = new Set(['check', 'check_aso', 'scan', 'validate', 'health', 'reviews_list', 'prices_diff', 'analytics_compare', 'apple_status',
|
||||
'apple_next_build', 'play_status', 'play_next_version_code', 'shots_check', 'apple_testflight_status', 'apple_ppo_status', 'catalog_diff',
|
||||
'project_icon', 'project_listings', 'reviews_drafts', 'project_declarations', 'project_listing_text', 'project_renders', 'project_render', 'prices_current']);
|
||||
|
||||
|
|
@ -434,7 +434,7 @@ export class Session {
|
|||
const raw = list[i] as unknown;
|
||||
// a store-only app: { key: "store:...", virtual: { name, apple?, play? } }
|
||||
const virt = typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? raw as { key?: unknown; virtual?: unknown } : null;
|
||||
const e: AppStatus = { project: virt ? String(virt.key ?? '') : String(raw), ok: false, app: null, summary: null, check: null, release: { source: 'none', current: null, next: null }, catalog: null, storeErrors: {}, errors: [] };
|
||||
const e: AppStatus = emptyStatus(virt ? String(virt.key ?? '') : String(raw));
|
||||
out[i] = e;
|
||||
try {
|
||||
let dir: string;
|
||||
|
|
@ -443,28 +443,7 @@ export class Session {
|
|||
dir = virtualDir(checkVirtual(virt.virtual));
|
||||
e.virtual = true;
|
||||
} else { dir = checkProject(raw); e.project = dir; }
|
||||
const summary = e.summary = await this.inspect(dir, env, id);
|
||||
e.app = appIdentity(summary);
|
||||
e.catalog = catalogParity(summary);
|
||||
if (virt) e.check = { ok: true, problems: [], warnings: [] };
|
||||
else {
|
||||
const c = await this.track(id, this.run(['check', '--json'], { cwd: dir, env, machine: true })).result;
|
||||
const cd = c.data as { ok?: boolean; problems?: string[]; warnings?: string[] } | undefined;
|
||||
e.check = cd ? { ok: !!cd.ok, problems: cd.problems ?? [], warnings: cd.warnings ?? [] } : { ok: false, problems: [lastLine(c.out) || `check exit ${c.code}`], warnings: [] };
|
||||
}
|
||||
if (live) {
|
||||
const store = async (argv: string[]): Promise<{ data?: unknown; error?: string }> => {
|
||||
const r = await this.track(id, this.run(argv, { cwd: dir, env, machine: true })).result;
|
||||
return r.code === 0 && r.data !== undefined ? { data: r.data } : { error: lastLine(r.out) || `exit ${r.code}` };
|
||||
};
|
||||
const [apple, play] = await Promise.all([summary.apple ? store(['apple', 'status', '--json']) : undefined, summary.play ? store(['play', 'status', '--json']) : undefined]);
|
||||
if (apple?.error) e.storeErrors.ios = apple.error;
|
||||
if (play?.error) e.storeErrors.android = play.error;
|
||||
const ios = apple?.data ? appleReleases(apple.data) : [], android = play?.data ? playReleases(play.data) : [];
|
||||
e.release = { source: 'live', ...releaseTrains(ios, android), all: [...ios, ...android] };
|
||||
e.catalog = catalogParity(summary, apple?.data ? appleProductIds(apple.data) : undefined, play?.data ? playProductIds(play.data) : undefined);
|
||||
}
|
||||
e.ok = e.check.ok && !e.storeErrors.ios && !e.storeErrors.android && (e.catalog?.ok ?? true);
|
||||
await fillAppStatus(e, dir, { live, virtual: !!virt, exec: (argv, cwd) => this.track(id, this.run(argv, { cwd, env, machine: true })).result });
|
||||
} catch (err) {
|
||||
if (this.cancelled.has(id)) throw err;
|
||||
e.errors.push((err as Error).message);
|
||||
|
|
@ -482,7 +461,6 @@ export class Session {
|
|||
/** Store target keys of store-only apps ("store:ios:<account>:<app id>:<bundle id>;android:<account>:<package>"). */
|
||||
export const STORE_KEY_RE = /^store:[A-Za-z0-9:;._-]{1,400}$/;
|
||||
|
||||
const lastLine = (s: string): string => s.trim().split('\n').filter(Boolean).at(-1)?.replace(/^error:\s*/, '') ?? '';
|
||||
|
||||
/** Optional local tools with versions; app-managed copies (STOREBOUND_TOOL_PATH / STOREBOUND_CHROME) included. */
|
||||
export function localTools(): Json {
|
||||
|
|
|
|||
96
cli/triage.ts
Normal file
96
cli/triage.ts
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
// Crash and feedback triage: TestFlight crash and screenshot feedback, and Google Play vitals error reports, grouped
|
||||
// by signature with their top devices, OS versions and builds. Read-only on both stores.
|
||||
// storebound triage [--apple] [--play] [--days 14] [--build N] [--issues 10] [--comments 3] [--dry] [--json]
|
||||
// Apple: crash feedback -> the crash log of each (signature = exception + first app frame of the crashed thread);
|
||||
// screenshot feedback grouped by device / OS / build (--comments N shows up to N tester comments per group, cut to
|
||||
// 120 characters; emails are never read). Play: the top --issues issues of the window (Play's own clusters), then
|
||||
// their error reports for the device / API level / versionCode spread. --dry lists the requests without sending.
|
||||
// Pure parts and sources: cli/lib/triage.ts.
|
||||
import { ascClient, type J } from './apple/asc';
|
||||
import type { Ctx } from './lib/ctx';
|
||||
import { REPORTING_SCOPE } from './lib/google-auth';
|
||||
import { issuesQuery, ymd } from './lib/health';
|
||||
import { done, log, printJson, warn } from './lib/log';
|
||||
import { textTable } from './lib/table';
|
||||
import { CRASH_FIELDS, cluster, type Cluster, clusterRows, crashSignature, FEEDBACK_FIELDS, feedbackItems, playIssues, playReportItems, reportsQuery } from './lib/triage';
|
||||
import { googleClient, REPORTING_API } from './play/google';
|
||||
|
||||
const TAG = 'triage';
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const both = !a.has('apple') && !a.has('play');
|
||||
const days = a.num('days', 14);
|
||||
if (!(days >= 1 && days <= 90)) throw new Error('--days: 1-90');
|
||||
const dry = a.has('dry');
|
||||
const since = new Date(Date.now() - days * 86_400_000).toISOString();
|
||||
const result: { apple?: { crashes: Cluster[]; feedback: Cluster[] } | { error: string }; play?: { issues: Cluster[] } | { error: string } } = {};
|
||||
|
||||
if ((both || a.has('apple')) && config.apple) {
|
||||
try {
|
||||
const c = await ascClient(root, config.apple.bundleId, config.apple.appId);
|
||||
const appId = dry ? '<app>' : await c.app();
|
||||
const buildFilter = a.get('build');
|
||||
let buildIds: string[] = [];
|
||||
const builds = new Map<string, string>();
|
||||
if (!dry) for (const b of (await c.asc('GET', `/v1/builds?filter[app]=${appId}&sort=-uploadedDate&limit=200${buildFilter ? `&filter[version]=${encodeURIComponent(buildFilter)}` : ''}`)).data as J[]) builds.set(b.id, b.attributes.version);
|
||||
buildIds = [...builds.keys()];
|
||||
if (buildFilter && !dry && !buildIds.length) throw new Error(`no build ${buildFilter}`);
|
||||
const q = (fields: string, kind: string) => `/v1/apps/${appId}/${kind}?sort=-createdDate&limit=200&include=build&fields[builds]=version&fields[${kind}]=${fields}${buildFilter && buildIds.length ? `&filter[build]=${buildIds.join(',')}` : ''}`;
|
||||
if (dry) {
|
||||
log(TAG, `would GET ${q(CRASH_FIELDS, 'betaFeedbackCrashSubmissions')} + each crashLog`);
|
||||
log(TAG, `would GET ${q(FEEDBACK_FIELDS, 'betaFeedbackScreenshotSubmissions')}`);
|
||||
} else {
|
||||
const recent = (xs: J[]) => xs.filter(x => (x.attributes?.createdDate ?? '') >= since);
|
||||
const crashes = recent(await c.all(q(CRASH_FIELDS, 'betaFeedbackCrashSubmissions')));
|
||||
log(TAG, `apple: ${crashes.length} TestFlight crash report(s) in ${days} days`);
|
||||
const sigs = new Map<string, string>();
|
||||
for (const s of crashes) {
|
||||
const logText = (await c.maybe(`/v1/betaFeedbackCrashSubmissions/${s.id}/crashLog`))?.data?.attributes?.logText as string | undefined;
|
||||
sigs.set(s.id, logText ? crashSignature(logText) : 'crash (no log)');
|
||||
}
|
||||
const shots = recent(await c.all(q(FEEDBACK_FIELDS, 'betaFeedbackScreenshotSubmissions')));
|
||||
log(TAG, `apple: ${shots.length} TestFlight screenshot feedback(s)`);
|
||||
const comments = a.num('comments', 0);
|
||||
const fb = feedbackItems(shots, builds).map(i => ({ ...i, signature: `feedback on ${i.device}` }));
|
||||
result.apple = { crashes: cluster(feedbackItems(crashes, builds, sigs)), feedback: cluster(fb, { comments }) };
|
||||
}
|
||||
} catch (e) { result.apple = { error: (e as Error).message }; warn(TAG, `apple: ${(e as Error).message.slice(0, 300)}`); }
|
||||
}
|
||||
|
||||
if ((both || a.has('play')) && config.play) {
|
||||
try {
|
||||
const app = `${REPORTING_API}/apps/${encodeURIComponent(config.play.packageName)}`;
|
||||
const end = ymd(new Date(), 0);
|
||||
const iq = issuesQuery(end, days, { pageSize: a.num('issues', 10) });
|
||||
if (dry) log(TAG, `would GET ${app}/errorIssues:search?${iq} + errorReports:search per issue`);
|
||||
else {
|
||||
const g = googleClient(root, REPORTING_SCOPE);
|
||||
const issues = playIssues(await g.json('GET', `${app}/errorIssues:search?${iq}`));
|
||||
log(TAG, `play: ${issues.length} top issue(s) in ${days} days`);
|
||||
const items = [];
|
||||
const startD = new Date(Date.UTC(end.year, end.month - 1, end.day) - days * 86_400_000), endD = new Date(Date.UTC(end.year, end.month - 1, end.day));
|
||||
for (const i of issues) items.push(...playReportItems(await g.json('GET', `${app}/errorReports:search?${reportsQuery(i.id, startD, endD)}`), issues));
|
||||
const cs = cluster(items);
|
||||
// issues with no sampled reports still show with Play's own counts
|
||||
for (const i of issues) {
|
||||
const s = `${i.type} ${i.cause}${i.location ? ` @ ${i.location}` : ''}`;
|
||||
if (!cs.some(c => c.signature === s)) cs.push({ signature: s, count: 0, devices: [], os: [], builds: [] });
|
||||
}
|
||||
result.play = { issues: cs.map(c => ({ ...c, ...(() => { const i = issues.find(x => c.signature.startsWith(`${x.type} ${x.cause}`)); return i ? { reports: i.reports, users: i.users } : {}; })() })) };
|
||||
}
|
||||
} catch (e) { result.play = { error: (e as Error).message }; warn(TAG, `play: ${(e as Error).message.slice(0, 300)}`); }
|
||||
}
|
||||
|
||||
if (dry) { if (a.has('json')) printJson({ dryRun: true }); done(TAG, 'dry run: nothing read'); return; }
|
||||
if (a.has('json')) { printJson(result); return; }
|
||||
const head = ['n', 'signature', 'devices', 'os', 'builds'];
|
||||
if (result.apple && !('error' in result.apple)) {
|
||||
console.log(`\nTestFlight crashes (${days} days)\n` + (result.apple.crashes.length ? textTable(head, clusterRows(result.apple.crashes)) : 'none'));
|
||||
console.log(`\nTestFlight feedback (${days} days)\n` + (result.apple.feedback.length ? textTable(head, clusterRows(result.apple.feedback)) : 'none'));
|
||||
for (const c of result.apple.feedback) for (const t of c.comments ?? []) console.log(` ${c.signature}: "${t}"`);
|
||||
}
|
||||
if (result.play && !('error' in result.play)) console.log(`\nGoogle Play crashes and ANRs (${days} days; n = sampled reports)\n` + (result.play.issues.length ? textTable(head, clusterRows(result.play.issues)) : 'none'));
|
||||
done(TAG, 'triage done (fix the top signature first; storebound health for the rates)');
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
// Store readiness report (read-only on both stores): what still blocks a submission, in the order to fix it.
|
||||
// storebound validate [--apple] [--play] [--json] [--src store/renders] [--no-local] [--no-health]
|
||||
// storebound validate [--apple] [--play] [--json] [--src store/renders] [--no-local] [--no-health] [--no-scan]
|
||||
// Without --apple / --play: every store the config has. Exit code 1 when there is at least one blocker.
|
||||
// Reads only: GETs on App Store Connect, a Play edit that is opened, read and deleted (never committed), and plain GETs
|
||||
// of the public privacy policy and app-ads.txt URLs. Also checks the local renders folder (if there is one) with the
|
||||
|
|
@ -8,6 +8,9 @@
|
|||
// Subscriptions (when the config has them): App Store states, localizations, group names, review screenshots; Play
|
||||
// subscriptions with an active base plan. App profile: delete-account URL answers (accounts), demo account locally and
|
||||
// on App Review (sign-in required), Terms of Use URL answers and is linked in the description (subscriptions).
|
||||
// Project scan (offline, `storebound scan`): rejection risks proven by the project's own files (sign-in without a demo
|
||||
// account, no account deletion, no Restore Purchases, ATT, purpose strings, privacy manifest, target SDK ...): open
|
||||
// blockers stay blockers, high and medium risks are warnings, owner-accepted ones (scan.ignore) are left out. --no-scan skips.
|
||||
// Live apps: crash / ANR vitals (Play Reporting API) and App Store diagnostics, as in `storebound health`: over a Play
|
||||
// bad behavior threshold is a blocker, near it a warning; a store without vitals access is only noted. --no-health skips.
|
||||
import { ascClient, type J } from './apple/asc';
|
||||
|
|
@ -22,6 +25,8 @@ import { healthFindings } from './lib/health';
|
|||
import { log, printJson, warn } from './lib/log';
|
||||
import { type AppleSnapshot, appleRules, type Finding, formatFindings, PLAY_REQUIRED_IMAGES, type PlaySnapshot, playRules, type ProfileFacts, rendersFindings, sortFindings } from './lib/validate-rules';
|
||||
import { rendersCheck } from './shots/check';
|
||||
import { runScan } from './lib/scan';
|
||||
import type { ScanFinding } from './lib/scan/rules';
|
||||
import { playClient } from './play/client';
|
||||
import { listOneTimeProducts } from './play/products';
|
||||
|
||||
|
|
@ -155,6 +160,16 @@ export async function collectPlay(ctx: Ctx): Promise<PlaySnapshot> {
|
|||
}
|
||||
}
|
||||
|
||||
/** Scan findings as validate findings: blocker stays blocker, high / medium become warnings; low and owner-accepted
|
||||
* ones are left out (they are in the full `storebound scan` report). */
|
||||
export function scanAsFindings(f: ScanFinding[], stores: { apple: boolean; play: boolean }): Finding[] {
|
||||
return f.filter(x => !x.accepted && x.severity !== 'low' && stores[x.store]).map(x => ({
|
||||
store: x.store, level: x.severity === 'blocker' ? 'blocker' as const : 'warn' as const, code: `scan-${x.rule}`,
|
||||
msg: `${x.guideline}: ${x.title}${x.evidence[0] ? ` (${x.evidence[0].file}:${x.evidence[0].line})` : ''}`,
|
||||
fix: `${x.fix} · ${x.skill} skill`,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
|
|
@ -171,6 +186,13 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
try { findings.push(...playRules({ ...(await collectPlay(ctx)), renders: local?.play })); }
|
||||
catch (e) { findings.push({ store: 'play', level: 'blocker', code: 'api', msg: (e as Error).message.slice(0, 400) }, ...rendersFindings('play', local?.play)); }
|
||||
} else if (a.has('play')) warn('validate', 'no play section in the config');
|
||||
if (!a.has('no-scan')) {
|
||||
log('validate', 'project scan (offline): rejection risks in the project files');
|
||||
try {
|
||||
const { report } = await runScan(ctx.loaded.root);
|
||||
findings.push(...sortFindings(scanAsFindings(report.findings, { apple: (both || a.has('apple')) && !!config.apple, play: (both || a.has('play')) && !!config.play })));
|
||||
} catch (e) { warn('validate', `project scan failed: ${(e as Error).message}`); }
|
||||
}
|
||||
if (!a.has('no-health') && (config.apple || config.play)) {
|
||||
log('validate', 'vitals and diagnostics (last 7 days)');
|
||||
const h = await collectHealth(ctx, { apple: (both || a.has('apple')) && !!config.apple, play: (both || a.has('play')) && !!config.play, days: 7 });
|
||||
|
|
|
|||
103
cli/whats-new.ts
103
cli/whats-new.ts
|
|
@ -5,10 +5,78 @@
|
|||
// --since: default the latest tag (git describe --tags --abbrev=0); --lang: the Play code / App Store locale to write
|
||||
// (default: the Play default language and the first App Store locale); --all: write the same draft into every
|
||||
// language (to translate afterwards; `storebound check` warns while they are identical).
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
//
|
||||
// Many languages, one file each (the CLI never calls a translation service and needs no key for one):
|
||||
// storebound whats-new --languages en-US,de-DE,tr [--dir store/whats-new] [--translate "<command>"] [--force] [--dry] [--json]
|
||||
// the draft goes into the first language's file (status=source); every other language gets a file with the
|
||||
// source text and status=translate for your agent to translate (whats-new skill), or the output of --translate:
|
||||
// a command of yours run once per language with the source text on stdin and STOREBOUND_SOURCE_LANG /
|
||||
// STOREBOUND_TARGET_LANG (App Store locale, else Play code, else language id) in the environment; its stdout is
|
||||
// the translation. Existing translated files are kept unless --force.
|
||||
// storebound whats-new check [--dir store/whats-new] [--json] limits per store (Play 500, App Store 4000), untranslated files
|
||||
// storebound whats-new apply [--dir store/whats-new] [--dry] [--json] checked files -> both listing files
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { Language } from './lib/config';
|
||||
import { playCodes } from './lib/config';
|
||||
import type { Ctx } from './lib/ctx';
|
||||
import { log, warn } from './lib/log';
|
||||
import { checkNotes, formatNotes, NOTES_LIMITS, noteItems, setAppleWhatsNew, setPlayWhatsNew } from './lib/whats-new';
|
||||
import { done, log, printJson, warn } from './lib/log';
|
||||
import { textTable } from './lib/table';
|
||||
import {
|
||||
applyLanguageNotes, checkLanguageNotes, checkNotes, formatNotes, type LangCheck, NOTES_LIMITS, type NotesFile, noteItems, notesFileText, parseNotesFile,
|
||||
resolveLanguages, setAppleWhatsNew, setPlayWhatsNew,
|
||||
} from './lib/whats-new';
|
||||
|
||||
const TAG = 'whats-new';
|
||||
const storeCode = (l: Language): string => l.apple ?? playCodes(l)[0] ?? l.id;
|
||||
|
||||
/** The language files of a notes folder, in config order. */
|
||||
function readDir(dir: string, langs: Language[]): { l: Language; f: NotesFile }[] {
|
||||
if (!existsSync(dir)) throw new Error(`no ${dir} (storebound whats-new --languages ... writes it)`);
|
||||
const names = new Set(readdirSync(dir).filter(n => n.endsWith('.md')).map(n => n.slice(0, -3)));
|
||||
return langs.filter(l => names.has(l.id)).map(l => ({ l, f: parseNotesFile(readFileSync(join(dir, `${l.id}.md`), 'utf8'), l.id) }));
|
||||
}
|
||||
|
||||
function checkAll(files: { l: Language; f: NotesFile }[]): LangCheck[] {
|
||||
const src = files.find(x => x.f.status === 'source');
|
||||
return files.map(x => checkLanguageNotes(x.l, x.f, src && src !== x ? src.f.text : undefined));
|
||||
}
|
||||
|
||||
function printChecks(checks: LangCheck[]): void {
|
||||
console.log(textTable(['language', 'chars', 'play (500)', 'app store (4000)', 'problems'], checks.map(c => [c.lang, c.chars,
|
||||
c.play ? (c.play.ok ? 'ok' : 'OVER') : '-', c.apple ? (c.apple.ok ? 'ok' : 'OVER') : '-', c.problems.join('; ')])));
|
||||
}
|
||||
|
||||
async function languagesFlow(ctx: Ctx, draft: { play: string; apple: string }): Promise<void> {
|
||||
const { config, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
const dir = resolve(a.get('dir') ?? 'store/whats-new');
|
||||
const langs = resolveLanguages(config.languages, a.list('languages'));
|
||||
const [src, ...rest] = langs;
|
||||
// the source text: the shorter Play draft when the source language is on Play (it has to fit 500)
|
||||
const text = playCodes(src!).length ? draft.play : draft.apple;
|
||||
const files: { l: Language; f: NotesFile; write: boolean; note: string }[] = [{ l: src!, f: { lang: src!.id, source: src!.id, status: 'source', text }, write: true, note: 'draft (source)' }];
|
||||
const hook = a.get('translate');
|
||||
for (const l of rest) {
|
||||
const path = join(dir, `${l.id}.md`);
|
||||
const cur = existsSync(path) ? parseNotesFile(readFileSync(path, 'utf8'), l.id) : null;
|
||||
if (cur && cur.status === 'translated' && !a.has('force')) { files.push({ l, f: cur, write: false, note: 'kept (translated; --force replaces it)' }); continue; }
|
||||
if (hook && !a.has('dry')) {
|
||||
const r = Bun.spawnSync(['sh', '-c', hook], { stdin: new TextEncoder().encode(text), stdout: 'pipe', stderr: 'pipe',
|
||||
env: { ...process.env, STOREBOUND_SOURCE_LANG: storeCode(src!), STOREBOUND_TARGET_LANG: storeCode(l), STOREBOUND_TARGET_LANG_ID: l.id } });
|
||||
const out = r.stdout.toString().trim();
|
||||
if (r.exitCode !== 0 || !out) { warn(TAG, `${l.id}: --translate failed (exit ${r.exitCode}): ${r.stderr.toString().trim().slice(0, 200)}`); files.push({ l, f: { lang: l.id, source: src!.id, status: 'translate', text }, write: true, note: 'to translate (hook failed)' }); continue; }
|
||||
files.push({ l, f: { lang: l.id, source: src!.id, status: 'translated', text: out }, write: true, note: 'translated by the hook' });
|
||||
} else files.push({ l, f: { lang: l.id, source: src!.id, status: 'translate', text }, write: true, note: hook ? 'would run the --translate hook' : 'to translate (your agent: whats-new skill)' });
|
||||
}
|
||||
const checks = checkAll(files.map(x => ({ l: x.l, f: x.f })));
|
||||
if (a.has('json')) printJson({ dir, dryRun: a.has('dry'), files: files.map((x, i) => ({ lang: x.l.id, file: join(dir, `${x.l.id}.md`), status: x.f.status, write: x.write, note: x.note, check: checks[i] })) });
|
||||
else { for (const x of files) log(TAG, `${join(dir, `${x.l.id}.md`)}: ${x.note}`); printChecks(checks); }
|
||||
if (a.has('dry')) { done(TAG, 'dry run: nothing written'); return; }
|
||||
mkdirSync(dir, { recursive: true });
|
||||
for (const x of files) if (x.write) writeFileSync(join(dir, `${x.l.id}.md`), notesFileText(x.f));
|
||||
done(TAG, `${files.filter(x => x.write).length} file(s) in ${dir}; translate the status=translate ones, then storebound whats-new apply`);
|
||||
}
|
||||
|
||||
function git(args: string[], cwd: string): string {
|
||||
const r = Bun.spawnSync(['git', ...args], { cwd, stdout: 'pipe', stderr: 'pipe' });
|
||||
|
|
@ -19,6 +87,31 @@ function git(args: string[], cwd: string): string {
|
|||
export async function run(ctx: Ctx): Promise<void> {
|
||||
const { config, root, resolve } = ctx.loaded;
|
||||
const a = ctx.args;
|
||||
if (a._[0] === 'check' || a._[0] === 'apply') {
|
||||
const dir = resolve(a.get('dir') ?? 'store/whats-new');
|
||||
const files = readDir(dir, config.languages);
|
||||
if (!files.length) throw new Error(`${dir}: no <language id>.md files`);
|
||||
const checks = checkAll(files);
|
||||
const bad = checks.filter(c => c.problems.some(p => !p.startsWith('first line')));
|
||||
if (a._[0] === 'check' || bad.length) {
|
||||
if (a.has('json')) printJson({ dir, checks, ok: !bad.length });
|
||||
else printChecks(checks);
|
||||
if (bad.length) { process.exitCode = 1; done(TAG, `${bad.length} language(s) not ready: ${bad.map(c => c.lang).join(', ')}${a._[0] === 'apply' ? '; nothing written' : ''}`); return; }
|
||||
if (a._[0] === 'check') { done(TAG, `${checks.length} language(s) within the store limits`); return; }
|
||||
}
|
||||
const playFile = config.play ? resolve(config.play.listing ?? 'store/listing.md') : undefined;
|
||||
const appleFile = config.apple ? resolve(config.apple.listing ?? 'store/appstore.md') : undefined;
|
||||
let md: { play?: string; apple?: string } = { play: playFile ? readFileSync(playFile, 'utf8') : undefined, apple: appleFile ? readFileSync(appleFile, 'utf8') : undefined };
|
||||
const changed: string[] = [];
|
||||
for (const { l, f } of files) { const r = applyLanguageNotes(md, l, f.text); md = { play: r.play, apple: r.apple }; changed.push(...r.changed); }
|
||||
if (a.has('json')) printJson({ dir, checks, dryRun: a.has('dry'), changed });
|
||||
else { printChecks(checks); log(TAG, `sections: ${changed.join(', ') || 'none (no matching listing sections)'}`); }
|
||||
if (a.has('dry')) { done(TAG, 'dry run: listing files not written'); return; }
|
||||
if (playFile && md.play !== undefined) writeFileSync(playFile, md.play);
|
||||
if (appleFile && md.apple !== undefined) writeFileSync(appleFile, md.apple);
|
||||
done(TAG, `release notes of ${files.length} language(s) written into the listing files; push them with play release / apple listing`);
|
||||
return;
|
||||
}
|
||||
const since = a.get('since') ?? (() => { try { return git(['describe', '--tags', '--abbrev=0'], root).trim(); } catch { return ''; } })();
|
||||
const range = since ? `${since}..HEAD` : 'HEAD';
|
||||
const subjects = git(['log', range, '--no-merges', '--format=%s'], root).split('\n').filter(Boolean);
|
||||
|
|
@ -28,7 +121,9 @@ export async function run(ctx: Ctx): Promise<void> {
|
|||
const play = formatNotes(items, { hook, limit: NOTES_LIMITS.play });
|
||||
const apple = formatNotes(items, { hook, limit: NOTES_LIMITS.apple });
|
||||
for (const [store, text] of [['play', play], ['apple', apple]] as const) for (const p of checkNotes(text, store)) warn('whats-new', `${store}: ${p}`);
|
||||
console.log(`--- draft (Play, ${[...play].length}/500) ---\n${play}\n---`);
|
||||
if (a.has('languages')) return languagesFlow(ctx, { play, apple });
|
||||
if (a.has('json')) printJson({ since: since || null, commits: subjects.length, items, play, apple, limits: NOTES_LIMITS });
|
||||
else console.log(`--- draft (Play, ${[...play].length}/500) ---\n${play}\n---`);
|
||||
if (a.has('dry')) return;
|
||||
|
||||
const all = a.has('all');
|
||||
|
|
|
|||
450
cli/workspace.ts
Normal file
450
cli/workspace.ts
Normal file
|
|
@ -0,0 +1,450 @@
|
|||
// `storebound ws`: many apps and studios from one folder (storebound.workspace.json; model: cli/lib/workspace.ts).
|
||||
// ws init [--dry] [--force] find the app folders below and write storebound.workspace.json
|
||||
// ws list [--all] [--json] apps (folders + store-only apps from `ws apps import`), studios, accounts
|
||||
// ws status [--offline] [--apps a,b] [--json] portfolio table: apps x stores (release trains, catalog, check), read
|
||||
// in parallel (concurrency from the workspace, default 4)
|
||||
// ws check | ws validate [--apps a,b] [--json] the offline check / read-only store readiness of every app
|
||||
// ws run <command> [args] [--apps a,b | --all] [--apply]
|
||||
// any read command per app; write commands run as dry runs unless
|
||||
// --apply; submit / release / rollout / send / start / stop never
|
||||
// ws apps import --account <profile> [--json] the apps the account sees -> local cache, paired with the folders
|
||||
// (the desktop's rules: cli/lib/identity.ts)
|
||||
// ws desktop export [--out f | --merge [--apply]] the workspace as the desktop app's state (labels, never keys)
|
||||
// ws desktop import [--state f] [--out f] [--dry] [--force]
|
||||
// the desktop's studios, accounts, folders and overrides -> workspace
|
||||
// Credentials: per account a credential profile (cli/lib/credentials.ts), handed to each app's child command as env.
|
||||
// Nothing here prints a secret.
|
||||
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, relative, resolve, sep } from 'node:path';
|
||||
import type { Args } from './lib/args';
|
||||
import { emptyStatus, fillAppStatus, lastLine, pool } from './lib/app-status';
|
||||
import { CONFIG_NAMES } from './lib/config';
|
||||
import { PROFILE_KEYS, profileEnv, profileStatus } from './lib/credentials';
|
||||
import type { AppStatus, AppsListResult } from './lib/desktop-protocol';
|
||||
import { buildApps, type UnifiedApp } from './lib/identity';
|
||||
import { log, printJson, warn } from './lib/log';
|
||||
import { runCommand, type RunResult } from './lib/runner';
|
||||
import { textTable } from './lib/table';
|
||||
import { laneOf, laneText } from './lib/train';
|
||||
import {
|
||||
type Account, accountsOf, type AppFolder, cacheFile, type DesktopState, desktopStateFile, fromDesktopState, type LoadedWorkspace, loadWorkspace, mergeDesktopState,
|
||||
overridesOf, readStoreApps, resolveApps, selectApps, type Store, type StoreAppsCache, studiosOf, toDesktopState, type Workspace, WORKSPACE_NAMES,
|
||||
} from './lib/workspace';
|
||||
import { FORBIDDEN_ARGS, TOOLS } from './mcp-tools';
|
||||
import { checkVirtual, VIRTUAL_READS, virtualDir } from './serve';
|
||||
|
||||
/** One app of the workspace: a folder or a store-only app, with the credentials env its commands get. */
|
||||
export interface WsApp { key: string; rel: string; name: string; studio: string | null; dir: string | null; virtual: boolean; ignored: boolean; unified: UnifiedApp<AppFolder>; summary: AppStatus['summary'] }
|
||||
|
||||
const USAGE = `usage: storebound ws <init | list | status | check | validate | run <command> | apps import --account <profile> | desktop export | desktop import>
|
||||
common: --workspace <file or folder> --apps a,b --json --concurrency 1-8`;
|
||||
|
||||
// ---- building blocks (exported for tests) ----
|
||||
|
||||
/** Credentials env for one app: the apple account's ASC_* and the play account's PLAY_* from their profiles. */
|
||||
export function appEnv(u: UnifiedApp<AppFolder>, accounts: Account[]): { env: Record<string, string>; problems: string[] } {
|
||||
const env: Record<string, string> = { STOREBOUND_PROFILE: '' };
|
||||
const problems: string[] = [];
|
||||
const profileOf = (store: Store): string | null => {
|
||||
const fromFolder = store === 'apple' ? u.project?.appleProfile : u.project?.playProfile;
|
||||
if (fromFolder) return fromFolder;
|
||||
const ref = store === 'apple' ? u.ios : u.android;
|
||||
return ref ? accounts.find(a => a.id === ref.account)?.profile ?? null : null;
|
||||
};
|
||||
for (const store of ['apple', 'play'] as const) {
|
||||
const p = profileOf(store);
|
||||
if (!p) continue;
|
||||
try {
|
||||
const all = profileEnv(p);
|
||||
const keys = store === 'apple' ? ['ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8'] : ['PLAY_SERVICE_ACCOUNT'];
|
||||
const got = keys.filter(k => all[k]);
|
||||
if (!got.length) problems.push(`credential profile ${p}: no ${store === 'apple' ? 'ASC_KEY_ID / ASC_ISSUER_ID' : 'PLAY_SERVICE_ACCOUNT'}`);
|
||||
for (const k of got) env[k] = all[k]!;
|
||||
} catch (e) { problems.push((e as Error).message); }
|
||||
}
|
||||
return { env, problems };
|
||||
}
|
||||
|
||||
/** Folder apps and store-only apps of the workspace, paired by the desktop's rules. */
|
||||
export function workspaceApps(l: LoadedWorkspace, summaries: Map<string, AppStatus['summary']>): { apps: WsApp[]; accounts: Account[]; warnings: string[] } {
|
||||
const { apps: folders, warnings } = resolveApps(l);
|
||||
const accounts = accountsOf(l.ws);
|
||||
const unified = buildApps<AppFolder>({
|
||||
projects: folders, summaryOf: p => summaries.get(p.id) ?? null, accounts,
|
||||
storeApps: readStoreApps(l.root, accounts), overrides: overridesOf(l.ws, folders),
|
||||
});
|
||||
const apps: WsApp[] = unified.map(u => ({
|
||||
key: u.key, rel: u.project ? u.project.rel : u.target, name: u.project ? (summaries.get(u.project.id)?.name ?? u.name) : u.name, studio: u.studio,
|
||||
dir: u.project?.path ?? null, virtual: !u.project, ignored: u.ignored, unified: u, summary: u.project ? summaries.get(u.project.id) ?? null : null,
|
||||
}));
|
||||
return { apps, accounts, warnings };
|
||||
}
|
||||
|
||||
/** The directory a command for this app runs in: its folder, or a generated config for a store-only app. */
|
||||
export function appDir(a: WsApp): string {
|
||||
if (a.dir) return a.dir;
|
||||
const u = a.unified;
|
||||
return virtualDir(checkVirtual({ name: u.name, ...(u.ios ? { apple: { bundleId: u.ios.app.bundleId, appId: u.ios.app.id } } : {}), ...(u.android ? { play: { packageName: u.android.app.id } } : {}) }));
|
||||
}
|
||||
|
||||
const words = (argv: string[]): string[] => { const w: string[] = []; for (const a of argv) { if (a.startsWith('-')) break; w.push(a); } return w; };
|
||||
|
||||
/**
|
||||
* Whether `ws run` may run this command, and whether it writes (then it gets --dry unless --apply). Allowed: the MCP
|
||||
* tool set (cli/mcp-tools.ts) plus `inspect`; never anything that submits, releases, rolls out, sends, starts / stops,
|
||||
* removes or invites, and never --yes.
|
||||
*/
|
||||
export function runPolicy(argv: string[]): { ok: true; write: boolean } | { ok: false; why: string } {
|
||||
const w = words(argv);
|
||||
if (!w.length) return { ok: false, why: 'no command (e.g. ws run validate --play)' };
|
||||
const bad = argv.find(a => FORBIDDEN_ARGS.includes(a) || ['--manual-release', 'submit', 'publish', 'distribute', '--phased'].includes(a));
|
||||
if (bad) return { ok: false, why: `"${bad}" is an owner step: run it in the app folder yourself` };
|
||||
if (w.includes('release') || w.includes('rollout')) return { ok: false, why: 'release and rollout commands are owner steps: run them in the app folder yourself' };
|
||||
if (w[0] === 'ws') return { ok: false, why: 'ws inside ws run' };
|
||||
if (w.length === 1 && w[0] === 'inspect') return { ok: true, write: false };
|
||||
const cmdWords = (c: string[]) => words(c);
|
||||
const matches = TOOLS.filter(t => { const cw = cmdWords(t.command); return cw.length <= w.length && cw.every((x, i) => w[i] === x); });
|
||||
if (!matches.length) return { ok: false, why: `${w.join(' ')}: not a command ws run offers (read commands and dry runs of the MCP tool set, plus inspect)` };
|
||||
const longest = Math.max(...matches.map(t => cmdWords(t.command).length));
|
||||
const same = matches.filter(t => cmdWords(t.command).length === longest);
|
||||
// the variant whose extra flags are all present (health --weekly), else the plain one
|
||||
const variant = same.filter(t => t.command.slice(longest).every(f => argv.includes(f))).sort((a, b) => b.command.length - a.command.length)[0] ?? same[0]!;
|
||||
const write = variant.write || (variant.args?.({}) ?? []).includes('--dry');
|
||||
return { ok: true, write };
|
||||
}
|
||||
|
||||
// ---- output helpers ----
|
||||
|
||||
const storeCell = (s: AppStatus, store: 'ios' | 'android'): string => {
|
||||
const err = s.storeErrors[store];
|
||||
if (err) return 'unreadable';
|
||||
const has = store === 'ios' ? s.summary?.apple : s.summary?.play;
|
||||
if (!has) return '';
|
||||
if (s.release.source !== 'live') return 'offline';
|
||||
const r = s.release.current?.[store] ?? null;
|
||||
return r ? `${r.version} ${laneText(laneOf(store, r))}` : 'not live';
|
||||
};
|
||||
const nextCell = (s: AppStatus): string => {
|
||||
const n = s.release.next;
|
||||
if (!n) return '';
|
||||
const part = (store: 'ios' | 'android') => { const r = n[store]; return r ? `${store === 'ios' ? 'iOS' : 'Android'} ${laneText(laneOf(store, r))}` : ''; };
|
||||
return `${n.version}: ${[part('ios'), part('android')].filter(Boolean).join(', ')}`;
|
||||
};
|
||||
const catalogCell = (s: AppStatus): string => {
|
||||
const c = s.catalog;
|
||||
if (!c) return '';
|
||||
if (!c.products && !c.subscriptions) return '-';
|
||||
const issues = c.onlyIos.length + c.onlyAndroid.length + c.missingIos.length + c.missingAndroid.length;
|
||||
return `${c.products + c.subscriptions} items${c.checked === 'live' ? (issues ? `, ${issues} mismatched` : ', in parity') : ''}`;
|
||||
};
|
||||
|
||||
async function loadAll(args: Args): Promise<LoadedWorkspace> {
|
||||
return loadWorkspace(process.cwd(), args.get('workspace'));
|
||||
}
|
||||
|
||||
function concurrencyOf(args: Args, ws: Workspace): number {
|
||||
const n = args.num('concurrency', ws.concurrency ?? 4);
|
||||
if (!Number.isInteger(n) || n < 1 || n > 8) throw new Error('--concurrency: 1 to 8');
|
||||
return n;
|
||||
}
|
||||
|
||||
function exec(env: Record<string, string>) {
|
||||
return (argv: string[], cwd: string): Promise<RunResult> => runCommand(argv, { cwd, env, machine: true }).result;
|
||||
}
|
||||
|
||||
/** Offline summaries of the folder apps (inspect --json), for pairing and names. */
|
||||
async function summariesOf(folders: AppFolder[], n: number): Promise<Map<string, AppStatus['summary']>> {
|
||||
const m = new Map<string, AppStatus['summary']>();
|
||||
await pool(folders, n, async f => {
|
||||
const r = await runCommand(['inspect', '--json'], { cwd: f.path, machine: true }).result;
|
||||
if (r.code === 0 && r.data) m.set(f.id, r.data as AppStatus['summary']);
|
||||
});
|
||||
return m;
|
||||
}
|
||||
|
||||
async function prepared(args: Args, o: { includeIgnored?: boolean } = {}) {
|
||||
const l = await loadAll(args);
|
||||
const n = concurrencyOf(args, l.ws);
|
||||
const { apps: folders } = resolveApps(l);
|
||||
const summaries = await summariesOf(folders, n);
|
||||
const { apps, accounts, warnings } = workspaceApps(l, summaries);
|
||||
const visible = apps.filter(a => o.includeIgnored || !a.ignored);
|
||||
const { picked, unknown } = selectApps(visible, args.list('apps'));
|
||||
if (unknown.length) throw new Error(`--apps: no app named ${unknown.join(', ')} (ws list shows the names)`);
|
||||
return { l, n, apps: picked, all: apps, accounts, warnings };
|
||||
}
|
||||
|
||||
// ---- commands ----
|
||||
|
||||
/** App folders below `root` (depth <= 4), as the globs ws init writes: "parent/*" when a folder holds several. */
|
||||
export function discoverApps(root: string, depth = 4): string[] {
|
||||
const found: string[] = [];
|
||||
const walk = (dir: string, d: number) => {
|
||||
if (CONFIG_NAMES.some(n => existsSync(join(dir, n))) && dir !== root) { found.push(relative(root, dir).split(sep).join('/')); return; }
|
||||
if (d === 0) return;
|
||||
let entries: string[] = [];
|
||||
try { entries = readdirSync(dir); } catch { return; }
|
||||
for (const e of entries.sort()) {
|
||||
if (e.startsWith('.') || e === 'node_modules' || e === 'build' || e === 'dist') continue;
|
||||
const p = join(dir, e);
|
||||
try { if (statSync(p).isDirectory()) walk(p, d - 1); } catch { /* unreadable */ }
|
||||
}
|
||||
};
|
||||
walk(root, depth);
|
||||
const byParent = new Map<string, string[]>();
|
||||
for (const f of found) { const parent = f.includes('/') ? f.slice(0, f.lastIndexOf('/')) : ''; byParent.set(parent, [...(byParent.get(parent) ?? []), f]); }
|
||||
const out: string[] = [];
|
||||
for (const [parent, list] of byParent) out.push(...(list.length > 1 ? [parent ? `${parent}/*` : '*'] : list));
|
||||
return out.sort();
|
||||
}
|
||||
|
||||
async function init(args: Args): Promise<void> {
|
||||
const root = process.cwd();
|
||||
const file = join(root, 'storebound.workspace.json');
|
||||
const existing = WORKSPACE_NAMES.map(n => join(root, n)).find(existsSync);
|
||||
if (existing && !args.has('force')) throw new Error(`${existing} exists (--force overwrites)`);
|
||||
const apps = discoverApps(root);
|
||||
const ws: Workspace = { apps, studios: [], accounts: [], ignore: [], overrides: { pairs: [], unpairs: [], links: [], appStudio: [] }, concurrency: 4 };
|
||||
const text = JSON.stringify(ws, null, 2) + '\n';
|
||||
if (args.has('dry')) { console.log(text); log('ws', `dry run: ${file} not written (${apps.length} app folder pattern(s))`); return; }
|
||||
writeFileSync(file, text);
|
||||
const gi = join(root, '.gitignore');
|
||||
const giText = existsSync(gi) ? readFileSync(gi, 'utf8') : '';
|
||||
if (!/^\.storebound\/?$/m.test(giText)) writeFileSync(gi, giText + (giText && !giText.endsWith('\n') ? '\n' : '') + '.storebound/\n');
|
||||
log('ws', `wrote ${file}: ${apps.length ? apps.join(', ') : 'no app folders found yet (add them under "apps")'}`);
|
||||
log('ws', 'next: add studios and accounts by credential profile (~/.storebound/credentials/<profile>.json), then storebound ws list');
|
||||
}
|
||||
|
||||
async function list(args: Args): Promise<void> {
|
||||
const { l, apps, accounts, warnings } = await prepared(args, { includeIgnored: args.has('all') });
|
||||
const studios = studiosOf(l.ws);
|
||||
const sName = (id: string | null) => (id ? studios.find(s => s.id === id)?.name ?? id : '');
|
||||
const profiles = accounts.map(a => ({ ...profileStatus(a.profile), store: a.store, id: a.id, studio: a.studio, label: a.label ?? null }));
|
||||
if (args.has('json')) {
|
||||
printJson({ workspace: l.file, studios, accounts: profiles,
|
||||
apps: apps.map(a => ({ name: a.name, key: a.key, folder: a.dir, studio: a.studio, pairing: a.unified.pairing, ignored: a.ignored,
|
||||
ios: a.unified.ios ? { account: a.unified.ios.account, appId: a.unified.ios.app.id, bundleId: a.unified.ios.app.bundleId } : null,
|
||||
android: a.unified.android ? { account: a.unified.android.account, packageName: a.unified.android.app.id } : null,
|
||||
accounts: { apple: a.unified.project?.appleProfile ?? null, play: a.unified.project?.playProfile ?? null } })),
|
||||
warnings });
|
||||
return;
|
||||
}
|
||||
log('ws', `${l.file}: ${apps.length} app(s), ${studios.length} studio(s), ${accounts.length} account(s)`);
|
||||
console.log(textTable(['app', 'studio', 'folder', 'iOS', 'Android', 'accounts', 'pairing'], apps.map(a => {
|
||||
const u = a.unified;
|
||||
// the config's ids; "(store app <id>)" once `ws apps import` found the app on the account
|
||||
const ios = [a.summary?.apple?.bundleId ?? u.ios?.app.bundleId, u.ios ? `(store ${u.ios.app.id})` : ''].filter(Boolean).join(' ');
|
||||
const android = [a.summary?.play?.packageName ?? u.android?.app.id, u.android ? '(store)' : ''].filter(Boolean).join(' ');
|
||||
return [a.name + (a.ignored ? ' (ignored)' : ''), sName(a.studio), a.dir ? a.rel : '(store only)', ios, android,
|
||||
[u.project?.appleProfile, u.project?.playProfile].filter(Boolean).join(', '), u.pairing];
|
||||
})));
|
||||
if (profiles.length) {
|
||||
console.log('');
|
||||
console.log(textTable(['account', 'store', 'studio', 'profile', 'keys'], profiles.map(p => [p.label ?? p.profile, p.store, sName(p.studio), p.profile,
|
||||
p.source === 'missing' ? 'missing' : p.source === 'invalid' ? `invalid: ${p.error}` : (p.store === 'apple' ? p.apple : p.play) ? `ok (${p.source})` : `no ${p.store} keys in it`])));
|
||||
}
|
||||
for (const w of warnings) warn('ws', w);
|
||||
}
|
||||
|
||||
export interface WsStatusRow { name: string; key: string; folder: string | null; studio: string | null; status: AppStatus; problems: string[] }
|
||||
|
||||
async function status(args: Args): Promise<void> {
|
||||
const { l, n, apps, accounts } = await prepared(args);
|
||||
const live = !args.has('offline');
|
||||
const studios = studiosOf(l.ws);
|
||||
let done = 0;
|
||||
const rows = await pool(apps, n, async (a): Promise<WsStatusRow> => {
|
||||
const e = emptyStatus(a.dir ?? a.key);
|
||||
if (a.virtual) e.virtual = true;
|
||||
const { env, problems } = appEnv(a.unified, accounts);
|
||||
try { await fillAppStatus(e, appDir(a), { live, virtual: a.virtual, exec: exec(env) }); } catch (err) { e.errors.push((err as Error).message); }
|
||||
if (!args.has('json')) log('ws', `${++done}/${apps.length} ${a.name}`);
|
||||
return { name: a.name, key: a.key, folder: a.dir, studio: a.studio, status: e, problems: live ? problems : [] };
|
||||
});
|
||||
if (args.has('json')) { printJson({ workspace: l.file, live, apps: rows, at: new Date().toISOString() }); }
|
||||
else {
|
||||
const sName = (id: string | null) => (id ? studios.find(s => s.id === id)?.name ?? id : '');
|
||||
console.log(textTable(['app', 'studio', 'App Store', 'Google Play', 'next', 'catalog', 'check', 'notes'], rows.map(r => {
|
||||
const s = r.status;
|
||||
const notes = [...r.problems, ...s.errors, ...Object.entries(s.storeErrors).map(([k, v]) => `${k}: ${v}`)].join('; ');
|
||||
return [r.name, sName(r.studio), storeCell(s, 'ios'), storeCell(s, 'android'), nextCell(s), catalogCell(s),
|
||||
s.check ? (s.check.ok ? `ok${s.check.warnings.length ? ` (${s.check.warnings.length} warn)` : ''}` : `${s.check.problems.length} problem(s)`) : '', notes.slice(0, 160)];
|
||||
})));
|
||||
if (!live) log('ws', 'offline: store states not read (drop --offline to read both stores)');
|
||||
}
|
||||
if (rows.some(r => !r.status.ok)) process.exitCode = 1;
|
||||
}
|
||||
|
||||
/** Runs one command in every picked app (bounded parallel), output buffered per app. */
|
||||
async function runEach(args: Args, argv: string[], o: { json: boolean; label: string }) {
|
||||
const { n, apps, accounts } = await prepared(args);
|
||||
// store-only apps (no folder) take the store reads the desktop allows them (serve.ts VIRTUAL_READS) and inspect
|
||||
const w = words(argv);
|
||||
const storeRead = w.join(' ') === 'inspect' || TOOLS.some(t => VIRTUAL_READS.has(t.name) && words(t.command).join(' ') === w.join(' '));
|
||||
const folderOnly = !storeRead;
|
||||
const targets = apps.filter(a => !a.virtual || !folderOnly);
|
||||
const skipped = apps.filter(a => !targets.includes(a));
|
||||
const results = await pool(targets, n, async a => {
|
||||
const { env, problems } = appEnv(a.unified, accounts);
|
||||
const r = await runCommand(o.json ? [...argv, '--json'] : argv, { cwd: appDir(a), env, machine: o.json }).result;
|
||||
return { app: a, r, problems };
|
||||
});
|
||||
return { results, skipped };
|
||||
}
|
||||
|
||||
async function checkAll(args: Args, kind: 'check' | 'validate'): Promise<void> {
|
||||
const extra = kind === 'validate' ? [...(args.has('apple') ? ['--apple'] : []), ...(args.has('play') ? ['--play'] : []), ...(args.has('no-health') ? ['--no-health'] : [])] : [];
|
||||
const { results, skipped } = await runEach(args, [kind, ...extra], { json: true, label: kind });
|
||||
const rows = results.map(({ app, r, problems }) => {
|
||||
const d = r.data as { ok?: boolean; problems?: string[]; warnings?: string[]; blockers?: number; findings?: { level: string; msg: string; store: string }[] } | undefined;
|
||||
if (kind === 'check') return { app: app.name, folder: app.dir, ok: !!d?.ok, problems: d?.problems ?? (d ? [] : [lastLine(r.out) || `exit ${r.code}`]), warnings: d?.warnings ?? [], credentialProblems: [] as string[] };
|
||||
const blockers = d?.findings?.filter(f => f.level === 'blocker') ?? [];
|
||||
return { app: app.name, folder: app.dir, ok: !!d && !d.blockers, blockers: d ? d.blockers ?? 0 : null, findings: d?.findings ?? [], error: d ? null : lastLine(r.out) || `exit ${r.code}`, first: blockers[0] ? `${blockers[0].store}: ${blockers[0].msg}` : '', credentialProblems: problems };
|
||||
});
|
||||
if (args.has('json')) printJson({ [kind]: rows, skipped: skipped.map(a => a.name) });
|
||||
else {
|
||||
if (kind === 'check') console.log(textTable(['app', 'result', 'problems', 'warnings', 'first problem'], rows.map(x => { const c = x as { app: string; ok: boolean; problems: string[]; warnings: string[] }; return [c.app, c.ok ? 'ok' : 'PROBLEMS', c.problems.length, c.warnings.length, (c.problems[0] ?? '').slice(0, 100)]; })));
|
||||
else console.log(textTable(['app', 'result', 'blockers', 'first blocker'], rows.map(x => { const v = x as { app: string; ok: boolean; blockers: number | null; first: string; error: string | null }; return [v.app, v.blockers === null ? 'unreadable' : v.ok ? 'ready' : 'BLOCKED', v.blockers ?? '?', (v.error ?? v.first).slice(0, 110)]; })));
|
||||
for (const x of rows) for (const p of x.credentialProblems) warn('ws', `${x.app}: ${p}`);
|
||||
if (skipped.length) log('ws', `store-only apps skipped (no app folder): ${skipped.map(a => a.name).join(', ')}`);
|
||||
}
|
||||
if (rows.some(x => !x.ok)) process.exitCode = 1;
|
||||
}
|
||||
|
||||
async function runCmd(args: Args): Promise<void> {
|
||||
// the command line after `ws run`, minus the ws options
|
||||
const raw = process.argv.slice(process.argv.indexOf('run') + 1);
|
||||
const forward: string[] = [];
|
||||
const WS_VALUE = new Set(['--apps', '--concurrency', '--workspace']), WS_FLAG = new Set(['--all', '--apply']);
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const a = raw[i]!;
|
||||
const name = a.split('=')[0]!;
|
||||
if (WS_VALUE.has(name)) { if (!a.includes('=')) i++; continue; }
|
||||
if (WS_FLAG.has(a)) continue;
|
||||
forward.push(a);
|
||||
}
|
||||
const p = runPolicy(forward);
|
||||
if (!p.ok) throw new Error(`ws run: ${p.why}`);
|
||||
if (!args.has('all') && !args.list('apps').length) throw new Error('ws run: say which apps: --apps a,b or --all');
|
||||
const argv = p.write && !args.has('apply') && !forward.includes('--dry') ? [...forward, '--dry'] : forward;
|
||||
const json = forward.includes('--json');
|
||||
const { results, skipped } = await runEach(args, argv.filter(a => a !== '--json'), { json, label: 'run' });
|
||||
if (json) printJson({ command: `storebound ${argv.join(' ')}`, apps: results.map(({ app, r }) => ({ app: app.name, folder: app.dir, exitCode: r.code, data: r.data ?? null, output: r.data === undefined ? r.out : undefined })), skipped: skipped.map(a => a.name) });
|
||||
else {
|
||||
for (const { app, r, problems } of results) {
|
||||
console.log(`\n== ${app.name}${app.dir ? ` (${app.rel})` : ' (store only)'}: storebound ${argv.join(' ')} [exit ${r.code}]`);
|
||||
for (const x of problems) warn('ws', x);
|
||||
if (r.out) console.log(r.out);
|
||||
}
|
||||
if (skipped.length) log('ws', `store-only apps skipped (the command needs an app folder): ${skipped.map(a => a.name).join(', ')}`);
|
||||
if (p.write && !args.has('apply')) log('ws', 'dry run: nothing was changed. After the owner agreed, the same command with --apply runs it.');
|
||||
}
|
||||
if (results.some(x => x.r.code !== 0)) process.exitCode = 1;
|
||||
}
|
||||
|
||||
let neutral: string | null = null;
|
||||
const neutralDir = (): string => {
|
||||
if (!neutral) { neutral = join(tmpdir(), `storebound-ws-${process.pid}`); mkdirSync(neutral, { recursive: true }); }
|
||||
return neutral;
|
||||
};
|
||||
|
||||
async function appsImport(args: Args): Promise<void> {
|
||||
const l = await loadAll(args);
|
||||
const profile = args.get('account');
|
||||
if (!profile) throw new Error('ws apps import --account <credential profile>');
|
||||
const accounts = accountsOf(l.ws);
|
||||
const mine = accounts.filter(a => a.profile === profile);
|
||||
const st = profileStatus(profile);
|
||||
if (st.source === 'missing' || st.source === 'invalid') throw new Error(`credential profile ${profile}: ${st.error ?? 'not found (~/.storebound/credentials/<profile>.json or STOREBOUND_PROFILE_<NAME>_* env)'}`);
|
||||
const stores: Store[] = mine.length ? mine.map(a => a.store) : [...(st.apple ? ['apple' as const] : []), ...(st.play ? ['play' as const] : [])];
|
||||
if (!mine.length) warn('ws', `profile ${profile} is not listed in the workspace: add { "store": "${stores[0] ?? 'apple'}", "profile": "${profile}" } to accounts (or a studio) so its apps show up`);
|
||||
const env = profileEnv(profile);
|
||||
const pass: Record<string, string> = { STOREBOUND_PROFILE: '' };
|
||||
for (const k of PROFILE_KEYS) if (env[k]) pass[k] = env[k]!;
|
||||
const imported: { store: Store; count: number; warnings: string[] }[] = [];
|
||||
for (const store of stores) {
|
||||
const r = await runCommand(['apps', 'list', '--store', store, '--json'], { cwd: neutralDir(), env: pass, machine: true }).result;
|
||||
if (r.code !== 0 || !r.data) throw new Error(`${profile} (${store}): ${lastLine(r.out) || `exit ${r.code}`}`);
|
||||
const res = r.data as AppsListResult;
|
||||
const acc = mine.find(a => a.store === store);
|
||||
const cache: StoreAppsCache = { profile, store, account: acc?.id ?? '', at: res.at, apps: res.apps.map(a => ({ ...a, icon: null })) };
|
||||
const f = cacheFile(l.root, { store, profile });
|
||||
mkdirSync(resolve(f, '..'), { recursive: true });
|
||||
writeFileSync(f, JSON.stringify(cache, null, 2) + '\n');
|
||||
imported.push({ store, count: res.apps.length, warnings: res.warnings });
|
||||
log('ws', `${profile} (${store}): ${res.apps.length} app(s) -> ${relative(l.root, f)}`);
|
||||
}
|
||||
// the pairing with the folders, as ws list shows it from now on
|
||||
const { apps: folders } = resolveApps(l);
|
||||
const { apps } = workspaceApps(l, await summariesOf(folders, concurrencyOf(args, l.ws)));
|
||||
const touched = apps.filter(a => [a.unified.ios?.account, a.unified.android?.account].some(id => id && mine.some(m => m.id === id)));
|
||||
if (args.has('json')) { printJson({ imported, apps: touched.map(a => ({ name: a.name, folder: a.dir, pairing: a.unified.pairing, ios: a.unified.ios?.app.bundleId ?? null, android: a.unified.android?.app.id ?? null, ignored: a.ignored })) }); return; }
|
||||
console.log(textTable(['app', 'folder', 'iOS', 'Android', 'pairing'], touched.map(a => [a.name + (a.ignored ? ' (ignored)' : ''), a.dir ? a.rel : '(store only)', a.unified.ios?.app.bundleId ?? '', a.unified.android?.app.id ?? '', a.unified.pairing])));
|
||||
for (const i of imported) for (const w of i.warnings) warn('ws', w);
|
||||
log('ws', 'wrong pair? add it to overrides.unpairs (or pairs / links) in the workspace file: the same rules as the desktop');
|
||||
}
|
||||
|
||||
async function desktop(args: Args): Promise<void> {
|
||||
const sub = args._[1];
|
||||
if (sub === 'export') {
|
||||
const l = await loadAll(args);
|
||||
const { apps } = resolveApps(l);
|
||||
const state = toDesktopState(l.ws, apps);
|
||||
if (!args.has('merge')) {
|
||||
const out = args.get('out');
|
||||
if (!out) { printJson(state); return; }
|
||||
if (args.has('dry')) { log('ws', `dry run: ${out} not written`); printJson(state); return; }
|
||||
writeFileSync(resolve(out), JSON.stringify(state, null, 2) + '\n');
|
||||
log('ws', `wrote ${out}: ${state.projects.length} app folder(s), ${state.accounts.length} account(s), ${state.studios.length} studio(s)`);
|
||||
return;
|
||||
}
|
||||
const file = args.get('state') ? resolve(args.get('state')!) : desktopStateFile();
|
||||
const cur: DesktopState = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) as DesktopState : { version: 2, projects: [], accounts: [], studios: [], overrides: { pairs: [], unpairs: [], links: [], appStudio: [], ignored: [] } };
|
||||
const { state: merged, added } = mergeDesktopState(cur, state);
|
||||
log('ws', `${file}: +${added.projects} app folder(s), +${added.accounts} account(s), +${added.studios} studio(s), +${added.overrides} override(s)`);
|
||||
if (!args.has('apply')) { log('ws', 'dry run: nothing written. Quit the desktop app, then run again with --apply (a backup of state.json is kept).'); return; }
|
||||
mkdirSync(resolve(file, '..'), { recursive: true });
|
||||
if (existsSync(file)) copyFileSync(file, `${file}.ws-${new Date().toISOString().replace(/[:.]/g, '-')}.bak`);
|
||||
writeFileSync(file, JSON.stringify(merged, null, 2) + '\n');
|
||||
log('ws', 'merged. New accounts need their keys in the desktop (Accounts > the account > Add key): the desktop keeps keys in the OS keychain, not in profiles.');
|
||||
return;
|
||||
}
|
||||
if (sub === 'import') {
|
||||
const file = args.get('state') ? resolve(args.get('state')!) : desktopStateFile();
|
||||
if (!existsSync(file)) throw new Error(`no desktop state at ${file} (--state <file>)`);
|
||||
const root = process.cwd();
|
||||
const { ws, profiles } = fromDesktopState(JSON.parse(readFileSync(file, 'utf8')) as DesktopState, root);
|
||||
const out = resolve(args.get('out') ?? join(root, 'storebound.workspace.json'));
|
||||
const text = JSON.stringify({ ...ws, concurrency: 4 }, null, 2) + '\n';
|
||||
if (args.has('dry')) { console.log(text); log('ws', `dry run: ${out} not written`); }
|
||||
else {
|
||||
if (existsSync(out) && !args.has('force')) throw new Error(`${out} exists (--force overwrites, --out writes elsewhere)`);
|
||||
writeFileSync(out, text);
|
||||
log('ws', `wrote ${out}: ${ws.apps.length} app folder(s), ${(ws.studios ?? []).length} studio(s), ${profiles.length} account(s)`);
|
||||
}
|
||||
const missing = profiles.filter(p => profileStatus(p.profile).source === 'missing');
|
||||
if (missing.length) {
|
||||
log('ws', `credential profiles to create (the desktop's keychain is not read; put each account's key in its file):`);
|
||||
for (const p of missing) console.log(` ${p.label} (${p.store}): ~/.storebound/credentials/${p.profile}.json ${p.store === 'apple' ? '{ "ASC_KEY_ID", "ASC_ISSUER_ID", "ASC_P8" }' : '{ "PLAY_SERVICE_ACCOUNT" }'}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
throw new Error('ws desktop export [--out f | --merge [--apply]] | ws desktop import [--state f] [--out f]');
|
||||
}
|
||||
|
||||
export async function run(args: Args): Promise<void> {
|
||||
const sub = args._[0];
|
||||
switch (sub) {
|
||||
case 'init': return init(args);
|
||||
case 'list': return list(args);
|
||||
case 'status': return status(args);
|
||||
case 'check': return checkAll(args, 'check');
|
||||
case 'validate': return checkAll(args, 'validate');
|
||||
case 'run': return runCmd(args);
|
||||
case 'apps': if (args._[1] === 'import') return appsImport(args); break;
|
||||
case 'desktop': return desktop(args);
|
||||
}
|
||||
console.error(USAGE);
|
||||
process.exit(2);
|
||||
}
|
||||
|
|
@ -9,9 +9,10 @@ These rules apply to every AI tool that uses storebound (skills, MCP server or t
|
|||
chat). storebound's MCP server does not offer these at all.
|
||||
2. **Dry run first.** Every write command has `--dry` (MCP: `dry_run`, default true). Show the dry run, then run it
|
||||
for real only after the owner agrees.
|
||||
3. **Read before you write.** `storebound check` (offline) and `storebound validate` (read-only, both stores) tell you
|
||||
what is missing and in which order to fix it.
|
||||
4. **Credentials only from the environment or `.storebound/`** in the project (gitignored). Never ask for keys,
|
||||
3. **Read before you write.** `storebound scan` (offline: rejection risks in the project itself), `storebound check`
|
||||
(offline) and `storebound validate` (read-only, both stores) tell you what is missing and in which order to fix it.
|
||||
4. **Credentials only from the environment, `.storebound/`** in the project (gitignored) **or a credential profile**
|
||||
(`~/.storebound/credentials/<profile>.json`, named by `--account <profile>` or a workspace). Never ask for keys,
|
||||
passwords or tokens in chat, never print them, never write them into the config, docs or commits. The same goes
|
||||
for the App Review demo account (`reviewDemoAccount` in `.storebound/credentials.json`): the owner puts it there.
|
||||
5. **Never answer a compliance question you cannot know.** Export compliance, Data safety, App Privacy, age rating,
|
||||
|
|
|
|||
1768
docs/api-coverage.md
Normal file
1768
docs/api-coverage.md
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -52,7 +52,8 @@ Types of the protocol: `cli/lib/desktop-protocol.ts`; pure portfolio logic: `cli
|
|||
rendered screenshots), Health (`health`: daily user-perceived crash and ANR rate against the Play thresholds,
|
||||
worst devices, top issues, App Store metrics and signatures), Reviews (`reviews.list` + `reviews.drafts`: star
|
||||
distribution, filters, the local draft with its send checks, Approve via `reviews.approve`), TestFlight
|
||||
(`apple.testflight_status`), Checks (offline `check` + `validate` with fix hints).
|
||||
(`apple.testflight_status`), Checks (offline `scan`: rejection risks with guideline, evidence file:line, fix
|
||||
and skill, owner-accepted ones marked; offline `check`; `validate` with fix hints).
|
||||
- **First-run guide**: what the app does, add or start an app folder (`project.init` = `storebound init --profile`,
|
||||
confirmed in a native dialog), store keys into the keychain and which app uses which, local tools, first read.
|
||||
- **Command palette** (Cmd/Ctrl+K): apps, tabs, screens and actions. Cmd/Ctrl+1 Portfolio, +2-5 workspace screens,
|
||||
|
|
@ -167,6 +168,16 @@ Each write is a dry run, then the native dialog, then the real run, with one pro
|
|||
- **TestFlight tab:** What to Test, internal groups, testers.
|
||||
- **Reviews tab:** reply editor (`reviews.reply`), approve, send (owner action).
|
||||
|
||||
### The same model in the terminal
|
||||
|
||||
The CLI workspace (`storebound.workspace.json`, README "Many apps and studios") holds the same studios, accounts
|
||||
(credential profile names instead of keychain entries), folders and overrides. The pairing rules
|
||||
(`cli/lib/identity.ts`) and the release lanes (`cli/lib/train.ts`) are one implementation for both; the window
|
||||
re-exports them (`src/lib/identity.ts`, `src/lib/model.ts`). `storebound ws desktop import` reads `state.json` into a
|
||||
workspace file (the keychain is never read; the profiles to create are listed); `storebound ws desktop export --merge
|
||||
--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).
|
||||
|
||||
### 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
|
||||
|
|
|
|||
|
|
@ -17,4 +17,10 @@ bun ../../cli/index.ts check # profile checks: delete-accoun
|
|||
bun ../../cli/index.ts play data-safety --dry # the Data safety CSV Play imports, from dataSafety in the config
|
||||
```
|
||||
|
||||
`bun ../../cli/index.ts scan` (offline rejection-risk scan) finds four things that are true for a fictional app and
|
||||
are accepted on purpose in `scan.ignore` of the config, each with its reason: no App Review demo account and no Play
|
||||
App access credentials (there is no backend to sign in to), the `com.example` package name (the repo placeholder,
|
||||
never uploaded), and no Play developer account type (there is no account). A real app with accounts must fix the first
|
||||
two (`review-access` skill), pick its own package name and set `play.accountType`.
|
||||
|
||||
Everything it writes (`store/shots/frames`, `store/renders`, `.storebound`) is gitignored.
|
||||
|
|
|
|||
|
|
@ -34,6 +34,15 @@ const config: ShipConfig = {
|
|||
PSL_CRASH_LOGS: { shared: false, collect: ['analytics'] },
|
||||
},
|
||||
},
|
||||
// `storebound scan` findings that are true for this fictional demo and accepted on purpose (README.md)
|
||||
scan: {
|
||||
ignore: [
|
||||
{ rule: 'demo-account', reason: 'fictional demo app without a store record: there is no backend to sign in to, so no App Review demo account' },
|
||||
{ rule: 'play-app-access', reason: 'fictional demo app without a store record: no Play App access credentials' },
|
||||
{ rule: 'play-package-name', reason: 'fictional demo app: com.example.* is the repo placeholder and is never uploaded' },
|
||||
{ rule: 'play-testing-requirement', reason: 'fictional demo app without a Play developer account, so there is no account type to set' },
|
||||
],
|
||||
},
|
||||
renders: 'store/renders',
|
||||
shots: {
|
||||
style: 'app',
|
||||
|
|
|
|||
|
|
@ -21,3 +21,8 @@ bun ../../cli/index.ts icons # every icon from store/icon (ar
|
|||
```
|
||||
|
||||
Everything it writes (`store/shots/frames`, `store/renders`, `store/video`, `store/icons`, `.storebound`) is gitignored.
|
||||
|
||||
`bun ../../cli/index.ts scan` (offline rejection-risk scan) reports two findings, accepted on purpose in `scan.ignore`
|
||||
of the config: the `com.example` package name is the repo placeholder and is never uploaded (a real game picks its
|
||||
own), and there is no Play developer account type to set (a real game sets `play.accountType`). The game has no native project here, so the code checks (ATT, purpose strings, privacy manifest) have nothing
|
||||
to read.
|
||||
|
|
|
|||
|
|
@ -19,6 +19,13 @@ const config: ShipConfig = {
|
|||
],
|
||||
play: { packageName: 'com.example.prismpuddle' },
|
||||
apple: { bundleId: 'com.example.prismpuddle', ipad: true },
|
||||
// `storebound scan` findings that are true for this fictional demo and accepted on purpose (README.md)
|
||||
scan: {
|
||||
ignore: [
|
||||
{ rule: 'play-package-name', reason: 'fictional demo game: com.example.* is the repo placeholder and is never uploaded' },
|
||||
{ rule: 'play-testing-requirement', reason: 'fictional demo game without a Play developer account, so there is no account type to set' },
|
||||
],
|
||||
},
|
||||
renders: 'store/renders',
|
||||
// One artwork -> every icon: `storebound icons` (sources in store/icon, from bg.svg and fg.svg; output is gitignored)
|
||||
icons: {
|
||||
|
|
|
|||
|
|
@ -1,40 +1,55 @@
|
|||
# storebound teaser (about 50 s social video)
|
||||
# storebound teaser (about 34 s social video)
|
||||
|
||||
A scripted terminal animation, not a screen recording. Every frame is a pure function of time, rendered from an
|
||||
HTML/CSS/JS timeline in headless Chrome and encoded with ffmpeg. The music is original and synthesized from scratch in
|
||||
the same browser (Web Audio `OfflineAudioContext`): no samples, no downloaded audio, nothing to license.
|
||||
A scripted motion piece, not a screen recording. Every frame is a pure function of time, rendered from an
|
||||
HTML/CSS/JS timeline in headless Chrome and encoded with ffmpeg. The music and the sound design are original and
|
||||
synthesized from scratch in the same browser (Web Audio `OfflineAudioContext`): no samples, no downloaded audio,
|
||||
nothing to license.
|
||||
|
||||
| s | scene |
|
||||
|---|---|
|
||||
| 0.00-3.28 | hook: a generic, made-up inbox; three rejection mails stack up, then "Rejected. Again." |
|
||||
| 3.28-11.25 | hard cut to black: `storebound scan` is typed; the real output: SDKs with file:line, five findings with guideline and fix, the camera on each |
|
||||
| 11.25-14.06 | the re-scan after the fixes: the five reds flip green, 0 blockers |
|
||||
| 14.06-16.88 | the store screenshot wall (the demo game's real renders), 200 store screenshots |
|
||||
| 16.88-19.69 | the declarations proposal from the scan, Data safety answers ticking, 764 answers |
|
||||
| 19.69-28.13 | the desktop app (real frames, fixture data): Portfolio across studios · release timeline, rollout filling to 20% · Checks, rejection risks turning green |
|
||||
| 28.13-30.94 | "It never presses Submit. You do." over a Submit button |
|
||||
| 30.94-33.75 | logo, storebound.dev, Open source · macOS · Windows · Linux |
|
||||
|
||||
| file | what |
|
||||
|---|---|
|
||||
| `script.js` | the timeline: tempo (128 BPM, 26 bars = 48.75 s), scenes, terminal lines, prices, languages, blockers, the desktop steps |
|
||||
| `desktop.ts` | the desktop scene's frames: apps/desktop's Vite dev server in fixture mode (`VITE_FIXTURES=1`, example.com-style data), captured headlessly in dark at 1280x800 @2x, plus `boxes.json` (cursor targets) -> `out/desktop/` |
|
||||
| `script.js` | the timeline: 128 BPM, scenes in beats (every cut on the beat), captions, the inbox, the scan lines, the desktop camera, the sound cues |
|
||||
| `desktop.ts` | the desktop scenes' frames: apps/desktop's Vite dev server in fixture mode (`VITE_FIXTURES=1`, example.com-style data), captured headlessly in dark at 1280x800 @2x with the dev markers hidden, plus `boxes.json` (cursor and callout targets) -> `out/desktop/` |
|
||||
| `index.html` + `teaser.js` | the picture; `window.teaser.seek(t)` sets every element for time `t` |
|
||||
| `music.js` | the music: arp, kick, hats, clap, offbeat bass, pad, impacts on the cuts, key clicks, riser |
|
||||
| `render.ts` | frames -> ffmpeg (H.264 high, yuv420p, 30 fps), music -> loudnorm (-14 LUFS, -1.5 dBTP), mux, posters |
|
||||
| `icons/` | the mouse cursor and the blocker-list icons: Phosphor files copied unchanged by `bun tools/site-icons.ts` (no hand-written SVG; CI checks it) |
|
||||
| `music.js` | music (F minor: tense intro, silence for the typed command, the groove from Enter, a calm bar under Submit, the logo hit) and sound design: mail blips, key clicks, a whoosh into every whip / mask / zoom, a hit on every cut, ticks on findings, rising chimes on fixes |
|
||||
| `render.ts` | frames at 60 fps blended to 30 fps (motion blur) -> ffmpeg (H.264 high, yuv420p), sound -> loudnorm (-14 LUFS, -1.5 dBTP), mux, posters, the 1280x720 web version |
|
||||
| `icons/` | the mouse cursor and the UI icons: Phosphor files copied unchanged by `bun tools/site-icons.ts` (no hand-written SVG; CI checks it) |
|
||||
| `poster.jpg` | end card still (1920x1080, small) |
|
||||
|
||||
The terminal text is modelled on real storebound output for the demo game (`examples/demo-game`, placeholder ids,
|
||||
dry runs); the price table values are illustrative. The store art is the demo game's real renders. The desktop scene
|
||||
shows real frames of the desktop app on its fixture data in a CSS window; only the confirm dialog is drawn (in the app it
|
||||
is a native OS dialog), with the app's own wording and the dry run of the diff in the frame behind it.
|
||||
The scan text is the real `storebound scan` output of `tests/fixtures/scan/teaser` (five classic App Review
|
||||
rejections) and, after the fixes, of `tests/fixtures/scan/teaser-fixed`; `tests/teaser.test.ts` runs both scans and
|
||||
checks every line the video shows, the beat grid, the caption lengths (at most 7 words) and holds (at least 1.2 s), and
|
||||
that every scene holds at least 2.5 s. Each fix line shows a verbatim piece of the real fix. The mail list is fictional:
|
||||
no real names or addresses, no mail-app branding. The desktop scenes are real frames of the app on its fixture data;
|
||||
the "after" Checks frame is the same tab with the fixture's scan answering no findings.
|
||||
|
||||
## Render
|
||||
|
||||
Needs Bun, ffmpeg and Playwright (repo devDependency; Playwright's Chromium or an installed Google Chrome).
|
||||
|
||||
```sh
|
||||
# optional, for sharp store art: the demo renders (otherwise crops of docs/img/showcase.jpg are used)
|
||||
# optional, for the real screenshot wall: the demo renders (otherwise crops of docs/img/showcase.jpg are used)
|
||||
cd examples/demo-game && bun serve.ts & bun ../../cli/index.ts shots capture && bun ../../cli/index.ts shots fonts && bun ../../cli/index.ts shots render
|
||||
# from the repo root
|
||||
bun media/teaser/render.ts # both formats + music, about 12 min (captures out/desktop/ first when missing)
|
||||
bun media/teaser/render.ts # both formats, sound, posters, web version: about 15 min
|
||||
bun media/teaser/render.ts --desktop # capture the desktop app frames again (after a UI change)
|
||||
bun media/teaser/render.ts --only v # vertical only (h = horizontal)
|
||||
bun media/teaser/render.ts --only v # vertical only (h = horizontal; the web version is made from h)
|
||||
bun media/teaser/render.ts --stills 2,12.5,30 # PNG stills in out/stills for a quick layout check
|
||||
bun media/teaser/render.ts --serve --port 8750 # live preview: /index.html?w=1080&h=1920&play=1 (or &t=12.5)
|
||||
```
|
||||
|
||||
Outputs (gitignored) in `media/teaser/out/`: `teaser-1080x1920.mp4` (X / TikTok / Reels), `teaser-1920x1080.mp4`
|
||||
(X / YouTube), `-silent` variants, `poster-*.jpg`, `music.wav`.
|
||||
(X / YouTube), `teaser-web.mp4` (1280x720, about 3.5 MB, for the site) with `poster-web.jpg`, `-silent` variants,
|
||||
`poster-*.jpg`, `music.wav`.
|
||||
|
||||
Vertical layout keeps captions and key text inside the central 80% and leaves the bottom ~22% free for app overlays.
|
||||
The vertical layout keeps captions inside the centre 80% and the bottom ~22% free of key text for app overlays.
|
||||
|
|
|
|||
|
|
@ -1,7 +1,14 @@
|
|||
#!/usr/bin/env bun
|
||||
// Real desktop-app frames for the teaser's desktop scene: the Vite dev server of apps/desktop in fixture mode
|
||||
// (VITE_FIXTURES=1: example.com-style fixture data, no Tauri, no store accounts), captured headlessly, dark theme.
|
||||
// Writes media/teaser/out/desktop/*.jpg plus boxes.json (where the cursor goes, as fractions of the frame).
|
||||
// Real desktop-app frames for the teaser's three desktop scenes: the Vite dev server of apps/desktop in fixture mode
|
||||
// (VITE_FIXTURES=1: example.com-style fixture data, no Tauri, no store accounts), captured headlessly, dark theme,
|
||||
// with the two dev-build markers hidden (they are not in a release build).
|
||||
// Writes media/teaser/out/desktop/*.jpg plus boxes.json (cursor and callout targets, as fractions of the frame).
|
||||
// portfolio.jpg Portfolio: every app of every studio, grouped by studio
|
||||
// releases.jpg Prism Puddle's release timeline, both stores rolling out at 20%
|
||||
// releases-empty.jpg the same frame with the rollout bars' fill and "20%" hidden (the video fills the bar)
|
||||
// checks.jpg the Checks tab: the "Rejection risks" card with its findings
|
||||
// checks-clean.jpg the same tab after the fixes: the fixture's scan answer with no findings (the app's own
|
||||
// "No rejection risks found" state; the fixture module is served with an empty findings list)
|
||||
// render.ts runs it when out/desktop/ is missing; run it by hand after a UI change: bun media/teaser/desktop.ts
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
|
@ -29,65 +36,80 @@ export async function captureDesktop(): Promise<void> {
|
|||
await Bun.sleep(250);
|
||||
}
|
||||
const browser = await launch(ROOT, { headless: true });
|
||||
const ctx = await browser.newContext({ viewport: VIEW, deviceScaleFactor: 2, colorScheme: 'dark', reducedMotion: 'reduce' });
|
||||
const page = await ctx.newPage();
|
||||
const errors: string[] = [];
|
||||
page.on('pageerror', (e: unknown) => errors.push(String(e)));
|
||||
const boxes: Record<string, Box> = {};
|
||||
const box = async (name: string, loc: any): Promise<void> => {
|
||||
const errors: string[] = [];
|
||||
|
||||
const session = async (clean: boolean) => {
|
||||
const ctx = await browser.newContext({ viewport: VIEW, deviceScaleFactor: 2, colorScheme: 'dark', reducedMotion: 'reduce' });
|
||||
if (clean) {
|
||||
// after the fixes: the fixture's scan of Prism Puddle answers with no findings (the UI is unchanged)
|
||||
await ctx.route(/\/src\/dev\/fixtures\.ts/, async (route: any) => {
|
||||
const res = await route.fetch();
|
||||
const src = await res.text();
|
||||
const body = src.replace(/findings:\s*SCAN_PRISM,\s*counts:\s*scanCounts\(SCAN_PRISM\)/, 'findings: [], counts: scanCounts([])');
|
||||
if (body === src) errors.push('fixtures.ts: the Prism Puddle scan entry moved (desktop.ts clean capture)');
|
||||
await route.fulfill({ response: res, body });
|
||||
});
|
||||
}
|
||||
const page = await ctx.newPage();
|
||||
page.on('pageerror', (e: unknown) => errors.push(String(e)));
|
||||
return { ctx, page };
|
||||
};
|
||||
const open = async (page: any, start: string): Promise<void> => {
|
||||
await page.goto(`${base}/?start=${encodeURIComponent(start)}&theme=dark&lang=en`);
|
||||
await page.waitForLoadState('networkidle');
|
||||
await page.addStyleTag({ content: '.brand small, .dev-pill { display: none !important; }' });
|
||||
await page.waitForTimeout(1200);
|
||||
};
|
||||
const box = async (page: any, name: string, loc: any): Promise<void> => {
|
||||
const b = await loc.first().boundingBox();
|
||||
if (!b) throw new Error(`no box for ${name}`);
|
||||
boxes[name] = { x: b.x / VIEW.width, y: b.y / VIEW.height, w: b.width / VIEW.width, h: b.height / VIEW.height };
|
||||
};
|
||||
const open = async (start: string): Promise<void> => {
|
||||
await page.goto(`${base}/?start=${encodeURIComponent(start)}&theme=dark&lang=en`);
|
||||
await page.waitForLoadState('networkidle');
|
||||
// the two dev-build markers ("DEV" by the name, the "DEV FIXTURES" pill) are not in a release build
|
||||
await page.addStyleTag({ content: '.brand small, .dev-pill { display: none !important; }' });
|
||||
await page.waitForTimeout(900);
|
||||
};
|
||||
const shot = async (name: string): Promise<void> => {
|
||||
const shot = async (page: any, name: string): Promise<void> => {
|
||||
await page.mouse.move(VIEW.width - 2, VIEW.height - 2);
|
||||
await page.waitForTimeout(150);
|
||||
await page.screenshot({ path: join(OUT, `${name}.jpg`), type: 'jpeg', quality: 92 });
|
||||
await page.waitForTimeout(200);
|
||||
await page.screenshot({ path: join(OUT, `${name}.jpg`), type: 'jpeg', quality: 93 });
|
||||
};
|
||||
|
||||
await open('portfolio');
|
||||
await shot('portfolio');
|
||||
const a = await session(false);
|
||||
await open(a.page, 'portfolio');
|
||||
await box(a.page, 'studios', a.page.locator('.fchips'));
|
||||
await box(a.page, 'table', a.page.locator('table').first());
|
||||
await shot(a.page, 'portfolio');
|
||||
|
||||
await open('app:releases');
|
||||
await box('console', page.getByRole('button', { name: /App Store Connect/ }));
|
||||
await shot('releases');
|
||||
|
||||
await open('app:growth');
|
||||
const chart = page.locator('#tabpanel .lchart-plot').first();
|
||||
await box('chart', chart);
|
||||
await shot('growth');
|
||||
const c = boxes.chart!;
|
||||
const hx = (c.x + c.w * 0.68) * VIEW.width, hy = (c.y + c.h * 0.5) * VIEW.height;
|
||||
await page.mouse.move(hx, hy, { steps: 4 });
|
||||
await page.waitForTimeout(400);
|
||||
boxes.hover = { x: hx / VIEW.width, y: hy / VIEW.height, w: 0, h: 0 };
|
||||
await page.screenshot({ path: join(OUT, 'growth-hover.jpg'), type: 'jpeg', quality: 92 });
|
||||
|
||||
await open('palette');
|
||||
await shot('palette');
|
||||
|
||||
await open('app:prices');
|
||||
await page.getByRole('button', { name: /Compare store\/prices.csv/ }).click();
|
||||
await page.waitForTimeout(5200); // the "compared" result toast closes by itself after 4.5 s
|
||||
await page.getByText(/against the stores/).first().evaluate((el: HTMLElement) => {
|
||||
await open(a.page, 'app:releases');
|
||||
// the release timeline (both stores, rollout bars) at the top of the frame
|
||||
await a.page.locator('.tl-lane').first().evaluate((el: HTMLElement) => {
|
||||
el.scrollIntoView({ block: 'start' });
|
||||
document.getElementById('content')?.scrollBy({ top: -24 });
|
||||
document.getElementById('content')?.scrollBy({ top: -150 });
|
||||
});
|
||||
await page.waitForTimeout(300);
|
||||
await box('apply', page.getByRole('button', { name: /^Apply \d+ changes/ }));
|
||||
await shot('prices-diff');
|
||||
await a.page.waitForTimeout(300);
|
||||
await box(a.page, 'roll', a.page.locator('.tl-roll').first());
|
||||
await box(a.page, 'roll2', a.page.locator('.tl-roll').nth(1));
|
||||
await box(a.page, 'timeline', a.page.locator('.tl-lane').first());
|
||||
await shot(a.page, 'releases');
|
||||
await a.page.addStyleTag({ content: '.tl-roll .rbar rect:not(.track) { display: none !important; } .tl-roll .pct { visibility: hidden !important; }' });
|
||||
await a.page.waitForTimeout(150);
|
||||
await shot(a.page, 'releases-empty');
|
||||
|
||||
await open(a.page, 'app:checks');
|
||||
await box(a.page, 'scan', a.page.locator('.card').first());
|
||||
await box(a.page, 'finding', a.page.locator('.card').first().locator('.li').first());
|
||||
await box(a.page, 'scanAgain', a.page.locator('.card').first().locator('.btn').first());
|
||||
await shot(a.page, 'checks');
|
||||
await a.ctx.close();
|
||||
|
||||
const b = await session(true);
|
||||
await open(b.page, 'app:checks');
|
||||
await box(b.page, 'scanClean', b.page.locator('.card').first());
|
||||
await shot(b.page, 'checks-clean');
|
||||
await b.ctx.close();
|
||||
|
||||
writeFileSync(join(OUT, 'boxes.json'), `${JSON.stringify(boxes, null, 1)}\n`);
|
||||
await browser.close();
|
||||
if (errors.length) throw new Error(`page errors:\n ${[...new Set(errors)].join('\n ')}`);
|
||||
log(`6 frames + boxes.json -> ${OUT}`);
|
||||
log(`5 frames + boxes.json -> ${OUT}`);
|
||||
} finally {
|
||||
vite.kill();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M224.49,136.49l-72,72a12,12,0,0,1-17-17L187,140H40a12,12,0,0,1,0-24H187L135.51,64.48a12,12,0,0,1,17-17l72,72A12,12,0,0,1,224.49,136.49Z"/></svg>
|
||||
|
Before Width: | Height: | Size: 235 B |
1
media/teaser/icons/check-circle-fill.svg
Normal file
1
media/teaser/icons/check-circle-fill.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm45.66,85.66-56,56a8,8,0,0,1-11.32,0l-24-24a8,8,0,0,1,11.32-11.32L112,148.69l50.34-50.35a8,8,0,0,1,11.32,11.32Z"/></svg>
|
||||
|
After Width: | Height: | Size: 268 B |
1
media/teaser/icons/magnifying-glass-bold.svg
Normal file
1
media/teaser/icons/magnifying-glass-bold.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M232.49,215.51,185,168a92.12,92.12,0,1,0-17,17l47.53,47.54a12,12,0,0,0,17-17ZM44,112a68,68,0,1,1,68,68A68.07,68.07,0,0,1,44,112Z"/></svg>
|
||||
|
After Width: | Height: | Size: 228 B |
1
media/teaser/icons/paper-plane-tilt-fill.svg
Normal file
1
media/teaser/icons/paper-plane-tilt-fill.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" fill="currentColor"><path d="M231.4,44.34s0,.1,0,.15l-58.2,191.94a15.88,15.88,0,0,1-14,11.51q-.69.06-1.38.06a15.86,15.86,0,0,1-14.42-9.15L107,164.15a4,4,0,0,1,.77-4.58l57.92-57.92a8,8,0,0,0-11.31-11.31L96.43,148.26a4,4,0,0,1-4.58.77L17.08,112.64a16,16,0,0,1,2.49-29.8l191.94-58.2.15,0A16,16,0,0,1,231.4,44.34Z"/></svg>
|
||||
|
After Width: | Height: | Size: 380 B |
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue