Compare commits

..

No commits in common. "7b2cc8da0a44f8c7a2cc995a2c3a5a3226c7411c" and "0ce0c51ff6ebea9f973b63ad70bec42e327b2e50" have entirely different histories.

54 changed files with 345 additions and 3985 deletions

View file

@ -15,14 +15,11 @@ const only = arg('only', '').split(',').filter(Boolean);
const themes = arg('themes', 'light,dark').split(','); const themes = arg('themes', 'light,dark').split(',');
const lang = arg('lang', 'en'); const lang = arg('lang', 'en');
const suffix = arg('suffix', ''); const suffix = arg('suffix', '');
const prefix = arg('prefix', 'd3');
export const SCREENS: [string, string][] = [ export const SCREENS: [string, string][] = [
['portfolio', 'portfolio'], ['releases', 'app:releases'], ['releases-2', 'app:releases:2'], ['catalog', 'app:catalog'], ['listings', 'app:listings'], ['portfolio', 'portfolio'], ['releases', 'app:releases'], ['releases-2', 'app:releases:2'], ['catalog', 'app:catalog'], ['listings', 'app:listings'],
['health', 'app:health'], ['reviews', 'app:reviews'], ['testflight', 'app:testflight'], ['checks', 'app:checks'], ['health', 'app:health'], ['reviews', 'app:reviews'], ['testflight', 'app:testflight'], ['checks', 'app:checks'],
['apps', 'apps'], ['accounts', 'accounts'], ['dependencies', 'dependencies'], ['settings', 'settings'], ['apps', 'apps'], ['accounts', 'accounts'], ['dependencies', 'dependencies'], ['settings', 'settings'],
['ignored', 'ignored'], ['store-app', 'app:releases:3'], ['store-app-reviews', 'app:reviews:3'], ['store-app-single', 'app:releases:7'],
['settings-pairing', 'settings:pairing'], ['settings-refresh', 'settings:refresh'], ['settings-privacy', 'settings:privacy'],
['palette', 'palette'], ['welcome-1', 'welcome:1'], ['welcome-2', 'welcome:2'], ['welcome-3', 'welcome:3'], ['welcome-4', 'welcome:4'], ['welcome-5', 'welcome:5'], ['palette', 'palette'], ['welcome-1', 'welcome:1'], ['welcome-2', 'welcome:2'], ['welcome-3', 'welcome:3'], ['welcome-4', 'welcome:4'], ['welcome-5', 'welcome:5'],
]; ];
@ -44,7 +41,7 @@ for (const theme of themes) {
if (only.length && !only.includes(name)) continue; if (only.length && !only.includes(name)) continue;
await page.goto(`${base}/?start=${encodeURIComponent(start)}&theme=${theme}&lang=${lang}`); await page.goto(`${base}/?start=${encodeURIComponent(start)}&theme=${theme}&lang=${lang}`);
await settle(page); await settle(page);
const f = join(out, `${prefix}-${name}${suffix}-${theme}${lang === 'en' ? '' : `-${lang}`}.png`); const f = join(out, `d2-${name}${suffix}-${theme}${lang === 'en' ? '' : `-${lang}`}.png`);
await page.screenshot({ path: f }); await page.screenshot({ path: f });
files.push(f); files.push(f);
} }
@ -54,45 +51,10 @@ for (const theme of themes) {
await settle(page); await settle(page);
await page.getByRole('button', { name: /Read the stores|Mağazaları oku/ }).first().click(); await page.getByRole('button', { name: /Read the stores|Mağazaları oku/ }).first().click();
await page.waitForTimeout(900); await page.waitForTimeout(900);
const f = join(out, `${prefix}-toast${suffix}-${theme}${lang === 'en' ? '' : `-${lang}`}.png`); const f = join(out, `d2-toast${suffix}-${theme}${lang === 'en' ? '' : `-${lang}`}.png`);
await page.screenshot({ path: f }); await page.screenshot({ path: f });
files.push(f); files.push(f);
} }
const shot = async (name: string) => {
const f = join(out, `${prefix}-${name}${suffix}-${theme}${lang === 'en' ? '' : `-${lang}`}.png`);
await page.screenshot({ path: f });
files.push(f);
};
if (!only.length || only.includes('accounts-tested')) {
// every account checked: one Play service account was never invited (permission missing, with the fix)
await page.goto(`${base}/?start=accounts&theme=${theme}&lang=${lang}`);
await settle(page);
await page.getByRole('button', { name: /Test all accounts|Tüm hesapları sına/ }).click();
await page.waitForTimeout(900);
await page.getByText(/Sample Labs · Play/).first().scrollIntoViewIfNeeded();
await page.evaluate(() => document.getElementById('content')?.scrollBy({ top: 260 }));
await page.waitForTimeout(200);
await shot('accounts-tested');
}
if (!only.length || only.includes('portfolio-filter')) {
// one studio, sorted by name, no grouping, with a search
await page.goto(`${base}/?start=portfolio&theme=${theme}&lang=${lang}`);
await settle(page);
await page.locator('.fchip', { hasText: 'Example Games' }).click();
await page.getByPlaceholder(/Search apps|Uygulama, bundle/).fill('o');
await page.waitForTimeout(300);
await shot('portfolio-filter');
await page.locator('.fchip').first().click();
await page.getByPlaceholder(/Search apps|Uygulama, bundle/).fill('');
}
if (!only.length || only.includes('import')) {
// Import apps running, with its progress toast
await page.goto(`${base}/?start=accounts&theme=${theme}&lang=${lang}`);
await settle(page);
await page.getByRole('button', { name: /^Import apps$|^Uygulamaları içe aktar$/ }).first().click();
await page.waitForTimeout(700);
await shot('import');
}
if (errors.length) console.error(`${theme}: page errors:\n ${[...new Set(errors)].join('\n ')}`); if (errors.length) console.error(`${theme}: page errors:\n ${[...new Set(errors)].join('\n ')}`);
await ctx.close(); await ctx.close();
} }

View file

@ -29,20 +29,6 @@
"allow-open-external", "allow-open-external",
"allow-tools-info", "allow-tools-info",
"allow-tools-install", "allow-tools-install",
"allow-tools-uninstall", "allow-tools-uninstall"
"allow-workspace-get",
"allow-studio-save",
"allow-studio-remove",
"allow-studio-logo",
"allow-account-update",
"allow-account-check",
"allow-store-apps-refresh",
"allow-store-apps-cached",
"allow-overrides-set",
"allow-settings-set",
"allow-cache-info",
"allow-data-reveal",
"allow-notify",
"allow-app-reset"
] ]
} }

View file

@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-account-check"
description = "Enables the account_check command without any pre-configured scope."
commands.allow = ["account_check"]
[[permission]]
identifier = "deny-account-check"
description = "Denies the account_check command without any pre-configured scope."
commands.deny = ["account_check"]

View file

@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-account-update"
description = "Enables the account_update command without any pre-configured scope."
commands.allow = ["account_update"]
[[permission]]
identifier = "deny-account-update"
description = "Denies the account_update command without any pre-configured scope."
commands.deny = ["account_update"]

View file

@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-app-reset"
description = "Enables the app_reset command without any pre-configured scope."
commands.allow = ["app_reset"]
[[permission]]
identifier = "deny-app-reset"
description = "Denies the app_reset command without any pre-configured scope."
commands.deny = ["app_reset"]

View file

@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-cache-info"
description = "Enables the cache_info command without any pre-configured scope."
commands.allow = ["cache_info"]
[[permission]]
identifier = "deny-cache-info"
description = "Denies the cache_info command without any pre-configured scope."
commands.deny = ["cache_info"]

View file

@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-data-reveal"
description = "Enables the data_reveal command without any pre-configured scope."
commands.allow = ["data_reveal"]
[[permission]]
identifier = "deny-data-reveal"
description = "Denies the data_reveal command without any pre-configured scope."
commands.deny = ["data_reveal"]

View file

@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-notify"
description = "Enables the notify command without any pre-configured scope."
commands.allow = ["notify"]
[[permission]]
identifier = "deny-notify"
description = "Denies the notify command without any pre-configured scope."
commands.deny = ["notify"]

View file

@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-overrides-set"
description = "Enables the overrides_set command without any pre-configured scope."
commands.allow = ["overrides_set"]
[[permission]]
identifier = "deny-overrides-set"
description = "Denies the overrides_set command without any pre-configured scope."
commands.deny = ["overrides_set"]

View file

@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-settings-set"
description = "Enables the settings_set command without any pre-configured scope."
commands.allow = ["settings_set"]
[[permission]]
identifier = "deny-settings-set"
description = "Denies the settings_set command without any pre-configured scope."
commands.deny = ["settings_set"]

View file

@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-store-apps-cached"
description = "Enables the store_apps_cached command without any pre-configured scope."
commands.allow = ["store_apps_cached"]
[[permission]]
identifier = "deny-store-apps-cached"
description = "Denies the store_apps_cached command without any pre-configured scope."
commands.deny = ["store_apps_cached"]

View file

@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-store-apps-refresh"
description = "Enables the store_apps_refresh command without any pre-configured scope."
commands.allow = ["store_apps_refresh"]
[[permission]]
identifier = "deny-store-apps-refresh"
description = "Denies the store_apps_refresh command without any pre-configured scope."
commands.deny = ["store_apps_refresh"]

View file

@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-studio-logo"
description = "Enables the studio_logo command without any pre-configured scope."
commands.allow = ["studio_logo"]
[[permission]]
identifier = "deny-studio-logo"
description = "Denies the studio_logo command without any pre-configured scope."
commands.deny = ["studio_logo"]

View file

@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-studio-remove"
description = "Enables the studio_remove command without any pre-configured scope."
commands.allow = ["studio_remove"]
[[permission]]
identifier = "deny-studio-remove"
description = "Denies the studio_remove command without any pre-configured scope."
commands.deny = ["studio_remove"]

View file

@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-studio-save"
description = "Enables the studio_save command without any pre-configured scope."
commands.allow = ["studio_save"]
[[permission]]
identifier = "deny-studio-save"
description = "Denies the studio_save command without any pre-configured scope."
commands.deny = ["studio_save"]

View file

@ -1,11 +0,0 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-get"
description = "Enables the workspace_get command without any pre-configured scope."
commands.allow = ["workspace_get"]
[[permission]]
identifier = "deny-workspace-get"
description = "Denies the workspace_get command without any pre-configured scope."
commands.deny = ["workspace_get"]

View file

@ -22,9 +22,6 @@ pub struct Account {
pub label: String, pub label: String,
pub kind: AccountKind, pub kind: AccountKind,
pub created: String, pub created: String,
/// The studio this account belongs to (workspace::Studio id), if any.
#[serde(default)]
pub studio: Option<String>,
} }
/// The keychain entry of one account (JSON). /// The keychain entry of one account (JSON).

View file

@ -94,19 +94,6 @@ impl Cache {
Ok(()) Ok(())
} }
/// Rows, bytes of the saved values and the oldest read time.
pub fn info(&self) -> Result<(u64, u64, Option<String>), String> {
let db = self.db.lock().map_err(|_| "cache poisoned")?;
db.query_row("SELECT COUNT(*), COALESCE(SUM(LENGTH(value)), 0), MIN(at) FROM reads", [], |r| Ok((r.get::<_, i64>(0)? as u64, r.get::<_, i64>(1)? as u64, r.get(2)?)))
.map_err(|e| e.to_string())
}
/// Drops reads older than `cutoff` (RFC 3339, compared as text: every `at` is written in the same UTC format).
pub fn prune_before(&self, cutoff: &str) -> Result<usize, String> {
let db = self.db.lock().map_err(|_| "cache poisoned")?;
db.execute("DELETE FROM reads WHERE at < ?1", params![cutoff]).map_err(|e| e.to_string())
}
pub fn clear(&self) -> Result<(), String> { pub fn clear(&self) -> Result<(), String> {
let db = self.db.lock().map_err(|_| "cache poisoned")?; let db = self.db.lock().map_err(|_| "cache poisoned")?;
db.execute("DELETE FROM reads", []).map_err(|e| e.to_string())?; db.execute("DELETE FROM reads", []).map_err(|e| e.to_string())?;

View file

@ -17,7 +17,6 @@ use crate::downloads;
use crate::policy::{self, Kind}; use crate::policy::{self, Kind};
use crate::sidecar::{valid_job, Fail, Progress, Sidecar}; use crate::sidecar::{valid_job, Fail, Progress, Sidecar};
use crate::store::{self, Project, State as Saved}; use crate::store::{self, Project, State as Saved};
use crate::workspace::{self, Overrides, Settings, StoreTarget, Studio};
pub struct AppState { pub struct AppState {
pub sidecar: Sidecar, pub sidecar: Sidecar,
@ -63,40 +62,6 @@ fn project_params(s: &AppState, project_id: &str) -> Res<(Project, Map<String, V
Ok((p, creds)) Ok((p, creds))
} }
/// Credentials of the accounts a store-only app is read with; each part must use an account of its store.
fn target_params(s: &AppState, t: &StoreTarget) -> Res<Map<String, Value>> {
let st = saved(s)?;
let kind = |id: &str| st.accounts.iter().find(|a| a.id == id).map(|a| a.kind);
if let Some((acc, ..)) = &t.ios {
if kind(acc) != Some(AccountKind::Apple) {
return Err(Fail::host("store app: not an App Store Connect account"));
}
}
if let Some((acc, _)) = &t.android {
if kind(acc) != Some(AccountKind::Play) {
return Err(Fail::host("store app: not a Google Play account"));
}
}
drop(st);
let mut creds = Map::new();
for id in t.accounts() {
if let Ok(secret) = s.secrets.get(id) {
secret.to_credentials(&mut creds);
}
}
Ok(creds)
}
/// One account's credentials only (account reads).
fn account_creds(s: &AppState, id: &str) -> Res<Map<String, Value>> {
if !saved(s)?.accounts.iter().any(|a| a.id == id) {
return Err(Fail::host("unknown account"));
}
let mut creds = Map::new();
s.secrets.get(id).map_err(Fail::host)?.to_credentials(&mut creds);
Ok(creds)
}
#[derive(Serialize)] #[derive(Serialize)]
pub struct AppInfo { pub struct AppInfo {
version: &'static str, version: &'static str,
@ -140,24 +105,6 @@ pub async fn sidecar_call(window: WebviewWindow, app: AppHandle, state: State<'_
let mut cache_project = None; let mut cache_project = None;
if matches!(kind, Some(Kind::Read | Kind::Write)) { if matches!(kind, Some(Kind::Read | Kind::Write)) {
let id = project_id.ok_or_else(|| Fail::host(format!("{method} needs a project")))?; let id = project_id.ok_or_else(|| Fail::host(format!("{method} needs a project")))?;
if id.starts_with("store:") {
// a store-only app: store reads only, through the sidecar's generated config
if kind != Some(Kind::Read) {
return Err(Fail::host("store-only apps are read-only: link a folder to change anything"));
}
let target = StoreTarget::parse(&id).map_err(Fail::host)?;
let creds = target_params(&state, &target)?;
let o = p.as_object_mut().ok_or_else(|| Fail::host("params"))?;
o.insert("virtual".into(), target.virtual_project());
if !creds.is_empty() {
o.insert("credentials".into(), Value::Object(creds));
}
let res = r.call_job(&method, p, job.as_deref()).await?;
if res["ok"] == Value::Bool(true) && !res["data"].is_null() {
let _ = state.cache.put(&id, &method, &args, &res, &store::now_iso());
}
return Ok(res);
}
let (proj, creds) = project_params(&state, &id)?; let (proj, creds) = project_params(&state, &id)?;
let o = p.as_object_mut().ok_or_else(|| Fail::host("params"))?; let o = p.as_object_mut().ok_or_else(|| Fail::host("params"))?;
o.insert("project".into(), Value::String(proj.path)); o.insert("project".into(), Value::String(proj.path));
@ -400,10 +347,6 @@ pub fn project_remove(window: WebviewWindow, state: State<'_, AppState>, id: Str
guard(&window)?; guard(&window)?;
let mut st = saved(&state)?; let mut st = saved(&state)?;
st.projects.retain(|p| p.id != id); st.projects.retain(|p| p.id != id);
st.overrides.links.retain(|l| l.project != id);
let (ig, key) = (format!("project:{id}"), format!("project:{id}"));
st.overrides.ignored.retain(|i| i != &ig);
st.overrides.app_studio.retain(|a| a.key != key);
let _ = state.cache.forget_project(&id); let _ = state.cache.forget_project(&id);
persist(&state, &st) persist(&state, &st)
} }
@ -437,19 +380,9 @@ pub fn accounts_list(window: WebviewWindow, state: State<'_, AppState>) -> Res<V
Ok(saved(&state)?.accounts.clone()) Ok(saved(&state)?.accounts.clone())
} }
fn check_studio(state: &AppState, studio: &Option<String>) -> Res<()> { fn add_account(state: &AppState, label: &str, secret: Secret) -> Res<Account> {
if let Some(s) = studio {
if !saved(state)?.studios.iter().any(|x| &x.id == s) {
return Err(Fail::host("unknown studio"));
}
}
Ok(())
}
fn add_account(state: &AppState, label: &str, secret: Secret, studio: Option<String>) -> Res<Account> {
let label = accounts::check_label(label).map_err(Fail::host)?; let label = accounts::check_label(label).map_err(Fail::host)?;
check_studio(state, &studio)?; let acc = Account { id: store::new_id()?, label, kind: secret.kind(), created: store::now_iso() };
let acc = Account { id: store::new_id()?, label, kind: secret.kind(), created: store::now_iso(), studio };
state.secrets.set(&acc.id, &secret).map_err(Fail::host)?; state.secrets.set(&acc.id, &secret).map_err(Fail::host)?;
let mut st = saved(state)?; let mut st = saved(state)?;
st.accounts.push(acc.clone()); st.accounts.push(acc.clone());
@ -476,26 +409,24 @@ async fn pick_file(window: &WebviewWindow, title: &'static str, filter: (&'stati
/// Google Play: pick the service account JSON key in a native dialog; it goes to the keychain only. /// Google Play: pick the service account JSON key in a native dialog; it goes to the keychain only.
#[tauri::command] #[tauri::command]
pub async fn account_add_play(window: WebviewWindow, state: State<'_, AppState>, label: String, studio: Option<String>) -> Res<Option<Account>> { pub async fn account_add_play(window: WebviewWindow, state: State<'_, AppState>, label: String) -> Res<Option<Account>> {
guard(&window)?; guard(&window)?;
accounts::check_label(&label).map_err(Fail::host)?; accounts::check_label(&label).map_err(Fail::host)?;
check_studio(&state, &studio)?;
let Some(text) = pick_file(&window, "Google Play service account key (JSON)", ("JSON key", &["json"])).await? else { return Ok(None) }; let Some(text) = pick_file(&window, "Google Play service account key (JSON)", ("JSON key", &["json"])).await? else { return Ok(None) };
let sa = accounts::check_service_account(&text).map_err(Fail::host)?; let sa = accounts::check_service_account(&text).map_err(Fail::host)?;
add_account(&state, &label, Secret::Play { service_account: sa }, studio).map(Some) add_account(&state, &label, Secret::Play { service_account: sa }).map(Some)
} }
/// App Store Connect: key id + issuer id typed in the app, the .p8 picked in a native dialog; all to the keychain. /// App Store Connect: key id + issuer id typed in the app, the .p8 picked in a native dialog; all to the keychain.
#[tauri::command] #[tauri::command]
pub async fn account_add_apple(window: WebviewWindow, state: State<'_, AppState>, label: String, key_id: String, issuer_id: String, studio: Option<String>) -> Res<Option<Account>> { pub async fn account_add_apple(window: WebviewWindow, state: State<'_, AppState>, label: String, key_id: String, issuer_id: String) -> Res<Option<Account>> {
guard(&window)?; guard(&window)?;
accounts::check_label(&label).map_err(Fail::host)?; accounts::check_label(&label).map_err(Fail::host)?;
check_studio(&state, &studio)?;
let key_id = accounts::check_key_id(&key_id).map_err(Fail::host)?; let key_id = accounts::check_key_id(&key_id).map_err(Fail::host)?;
let issuer_id = accounts::check_issuer_id(&issuer_id).map_err(Fail::host)?; let issuer_id = accounts::check_issuer_id(&issuer_id).map_err(Fail::host)?;
let Some(text) = pick_file(&window, "App Store Connect API key (.p8)", ("API key", &["p8"])).await? else { return Ok(None) }; let Some(text) = pick_file(&window, "App Store Connect API key (.p8)", ("API key", &["p8"])).await? else { return Ok(None) };
let p8 = accounts::check_p8(&text).map_err(Fail::host)?; let p8 = accounts::check_p8(&text).map_err(Fail::host)?;
add_account(&state, &label, Secret::Apple { key_id, issuer_id, p8 }, studio).map(Some) add_account(&state, &label, Secret::Apple { key_id, issuer_id, p8 }).map(Some)
} }
#[tauri::command] #[tauri::command]
@ -504,9 +435,6 @@ pub fn account_remove(window: WebviewWindow, state: State<'_, AppState>, id: Str
state.secrets.delete(&id).map_err(Fail::host)?; state.secrets.delete(&id).map_err(Fail::host)?;
let mut st = saved(&state)?; let mut st = saved(&state)?;
st.accounts.retain(|a| a.id != id); st.accounts.retain(|a| a.id != id);
let ignored = format!("account:{id}");
st.overrides.ignored.retain(|i| i != &ignored);
let _ = state.cache.forget_project(&format!("acct:{id}"));
for p in st.projects.iter_mut() { for p in st.projects.iter_mut() {
if p.play_account.as_deref() == Some(id.as_str()) { if p.play_account.as_deref() == Some(id.as_str()) {
p.play_account = None; p.play_account = None;
@ -518,31 +446,18 @@ pub fn account_remove(window: WebviewWindow, state: State<'_, AppState>, id: Str
persist(&state, &st) persist(&state, &st)
} }
/// Store-only apps one live portfolio read takes at most. /// Store reads run at most this many apps at once (each is two status reads).
const MAX_STORE_TARGETS: usize = 300; const LIVE_PARALLEL: usize = 4;
/// `portfolio.status` over every project. Offline unless `live`; live reads every app with its own accounts, several /// `portfolio.status` over every project. Offline unless `live`; live reads every app with its own accounts, several
/// at once, and sends one progress line per finished app (job progress n / total). Each live app result is cached; /// at once, and sends one progress line per finished app (job progress n / total). Each live app result is cached;
/// the whole live result too (project "*"), so the portfolio shows the last read when offline. /// the whole live result too (project "*"), so the portfolio shows the last read when offline.
#[tauri::command] #[tauri::command]
pub async fn portfolio_status(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, live: Option<bool>, stores: Option<Vec<String>>, job: Option<String>) -> Res<Value> { pub async fn portfolio_status(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, live: Option<bool>, job: Option<String>) -> Res<Value> {
guard(&window)?; guard(&window)?;
let job = job_of(job)?; let job = job_of(job)?;
let (projects, parallel) = { let projects = saved(&state)?.projects.clone();
let st = saved(&state)?; if projects.is_empty() {
let ignored: Vec<&str> = st.overrides.ignored.iter().filter_map(|i| i.strip_prefix("project:")).collect();
(st.projects.iter().filter(|p| !ignored.contains(&p.id.as_str())).cloned().collect::<Vec<_>>(), st.settings.refresh.parallel.clamp(1, 8) as usize)
};
// store-only apps (live reads only): validated targets with their accounts' credentials
let mut targets = Vec::new();
if live == Some(true) {
for key in stores.unwrap_or_default().into_iter().take(MAX_STORE_TARGETS) {
let t = StoreTarget::parse(&key).map_err(Fail::host)?;
let creds = target_params(&state, &t)?;
targets.push((key, t, creds));
}
}
if projects.is_empty() && targets.is_empty() {
return Ok(json!({ "apps": [], "at": store::now_iso() })); return Ok(json!({ "apps": [], "at": store::now_iso() }));
} }
let r = state.sidecar.get(&app).await?; let r = state.sidecar.get(&app).await?;
@ -550,8 +465,8 @@ pub async fn portfolio_status(window: WebviewWindow, app: AppHandle, state: Stat
let paths: Vec<&str> = projects.iter().map(|p| p.path.as_str()).collect(); let paths: Vec<&str> = projects.iter().map(|p| p.path.as_str()).collect();
return r.call_job("portfolio.status", json!({ "projects": paths }), job.as_deref()).await; return r.call_job("portfolio.status", json!({ "projects": paths }), job.as_deref()).await;
} }
let total = projects.len() + targets.len(); let total = projects.len();
let sem = Arc::new(tokio::sync::Semaphore::new(parallel)); let sem = Arc::new(tokio::sync::Semaphore::new(LIVE_PARALLEL));
let done = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let done = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let mut handles = Vec::new(); let mut handles = Vec::new();
for p in &projects { for p in &projects {
@ -566,18 +481,6 @@ pub async fn portfolio_status(window: WebviewWindow, app: AppHandle, state: Stat
(id, res) (id, res)
})); }));
} }
for (key, t, creds) in targets {
let (r, sem, done, app, job, id) = (r.clone(), sem.clone(), done.clone(), app.clone(), job.clone(), key.clone());
let entry = json!({ "key": key, "virtual": t.virtual_project() });
handles.push(tauri::async_runtime::spawn(async move {
let _permit = sem.acquire_owned().await.ok();
let sub = job.as_ref().map(|j| format!("{j}:p"));
let res = r.call_job("portfolio.status", json!({ "projects": [entry], "live": true, "credentials": creds }), sub.as_deref()).await;
let n = done.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
let _ = app.emit_to(policy::MAIN, "sidecar-progress", Progress { params: json!({ "requestId": 0, "n": n, "total": total, "project": id }), job: job.clone() });
(id, res)
}));
}
let mut all = Vec::new(); let mut all = Vec::new();
let at = store::now_iso(); let at = store::now_iso();
for h in handles { for h in handles {
@ -638,250 +541,3 @@ pub async fn tools_uninstall(window: WebviewWindow, state: State<'_, AppState>,
state.sidecar.shutdown().await; state.sidecar.shutdown().await;
Ok(()) Ok(())
} }
// ---- D3: studios, store accounts' apps, pairing overrides, ignore list, settings ----
#[derive(Serialize)]
pub struct Workspace {
studios: Vec<Studio>,
overrides: Overrides,
settings: Settings,
}
/// Studios, the owner's pairing / link / ignore overrides and the app settings in one read.
#[tauri::command]
pub fn workspace_get(window: WebviewWindow, state: State<'_, AppState>) -> Res<Workspace> {
guard(&window)?;
let st = saved(&state)?;
Ok(Workspace { studios: st.studios.clone(), overrides: st.overrides.clone(), settings: st.settings.clone() })
}
/// Creates (no id) or renames / recolours a studio.
#[tauri::command]
pub fn studio_save(window: WebviewWindow, state: State<'_, AppState>, id: Option<String>, name: String, color: String) -> Res<Studio> {
guard(&window)?;
let name = workspace::check_studio_name(&name).map_err(Fail::host)?;
let color = workspace::check_color(&color).map_err(Fail::host)?;
let mut st = saved(&state)?;
let out = match id {
Some(id) => {
let s = st.studios.iter_mut().find(|s| s.id == id).ok_or_else(|| Fail::host("unknown studio"))?;
s.name = name;
s.color = color;
s.clone()
}
None => {
if st.studios.len() >= 100 {
return Err(Fail::host("at most 100 studios"));
}
let s = Studio { id: store::new_id()?, name, color, logo: None, created: store::now_iso() };
st.studios.push(s.clone());
s
}
};
persist(&state, &st)?;
Ok(out)
}
/// Removes a studio; its accounts and apps stay, without a studio.
#[tauri::command]
pub fn studio_remove(window: WebviewWindow, state: State<'_, AppState>, id: String) -> Res<()> {
guard(&window)?;
let mut st = saved(&state)?;
st.studios.retain(|s| s.id != id);
for a in st.accounts.iter_mut() {
if a.studio.as_deref() == Some(id.as_str()) {
a.studio = None;
}
}
st.overrides.app_studio.retain(|a| a.studio != id);
persist(&state, &st)
}
/// Studio logo: a small PNG / JPEG / WebP picked in a native dialog (kept as a data URL), or `clear`.
#[tauri::command]
pub async fn studio_logo(window: WebviewWindow, state: State<'_, AppState>, id: String, clear: bool) -> Res<Option<Studio>> {
guard(&window)?;
if !saved(&state)?.studios.iter().any(|s| s.id == id) {
return Err(Fail::host("unknown studio"));
}
let logo = if clear {
None
} else {
let w = window.clone();
let picked = tauri::async_runtime::spawn_blocking(move || w.app_handle().dialog().file().set_title("Studio logo (PNG, JPEG or WebP)").add_filter("Image", &["png", "jpg", "jpeg", "webp"]).set_parent(&w).blocking_pick_file())
.await
.map_err(|e| Fail::host(e.to_string()))?;
let Some(p) = picked else { return Ok(None) };
let path = p.into_path().map_err(|e| Fail::host(e.to_string()))?;
if std::fs::metadata(&path).map_err(|e| Fail::host(e.to_string()))?.len() > workspace::LOGO_MAX as u64 {
return Err(Fail::host("logo: at most 256 KB"));
}
Some(workspace::logo_data_url(&std::fs::read(&path).map_err(|e| Fail::host(e.to_string()))?).map_err(Fail::host)?)
};
let mut st = saved(&state)?;
let s = st.studios.iter_mut().find(|s| s.id == id).ok_or_else(|| Fail::host("unknown studio"))?;
s.logo = logo;
let out = s.clone();
persist(&state, &st)?;
Ok(Some(out))
}
/// Renames an account or moves it to another studio (the key in the keychain stays as it is).
#[tauri::command]
pub fn account_update(window: WebviewWindow, state: State<'_, AppState>, id: String, label: String, studio: Option<String>) -> Res<Account> {
guard(&window)?;
let label = accounts::check_label(&label).map_err(Fail::host)?;
check_studio(&state, &studio)?;
let mut st = saved(&state)?;
let a = st.accounts.iter_mut().find(|a| a.id == id).ok_or_else(|| Fail::host("unknown account"))?;
a.label = label;
a.studio = studio;
let out = a.clone();
persist(&state, &st)?;
Ok(out)
}
/// Does the account's key work, and can it see apps (sidecar `account.check`). Not cached: it is a live answer.
#[tauri::command]
pub async fn account_check(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, id: String, job: Option<String>) -> Res<Value> {
guard(&window)?;
let job = job_of(job)?;
let creds = account_creds(&state, &id)?;
let r = state.sidecar.get(&app).await?;
r.call_job("account.check", json!({ "credentials": creds }), job.as_deref()).await
}
/// Reads every app the account can see from its store (sidecar `apps.list`, icons per Settings) and keeps the list
/// (cache project "acct:<id>").
#[tauri::command]
pub async fn store_apps_refresh(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>, id: String, job: Option<String>) -> Res<Entry> {
guard(&window)?;
let job = job_of(job)?;
let creds = account_creds(&state, &id)?;
let icons = saved(&state)?.settings.refresh.icons;
let r = state.sidecar.get(&app).await?;
let value = r.call_job("apps.list", json!({ "credentials": creds, "args": { "icons": icons } }), job.as_deref()).await?;
let at = store::now_iso();
state.cache.put(&format!("acct:{id}"), "apps.list", &json!({}), &value, &at).map_err(Fail::host)?;
Ok(Entry { value, at })
}
#[derive(Serialize)]
pub struct AccountApps {
account: String,
entry: Option<Entry>,
}
/// The last app list read of every account (null for an account never read).
#[tauri::command]
pub fn store_apps_cached(window: WebviewWindow, state: State<'_, AppState>) -> Res<Vec<AccountApps>> {
guard(&window)?;
let ids: Vec<String> = saved(&state)?.accounts.iter().map(|a| a.id.clone()).collect();
ids.into_iter()
.map(|account| {
let entry = state.cache.get(&format!("acct:{account}"), "apps.list", &json!({})).map_err(Fail::host)?;
Ok(AccountApps { account, entry })
})
.collect()
}
/// Replaces the pairing / link / studio / ignore overrides (every key is checked).
#[tauri::command]
pub fn overrides_set(window: WebviewWindow, state: State<'_, AppState>, overrides: Overrides) -> Res<Overrides> {
guard(&window)?;
workspace::check_overrides(&overrides).map_err(Fail::host)?;
let mut st = saved(&state)?;
st.overrides = overrides.clone();
persist(&state, &st)?;
Ok(overrides)
}
/// Saves the app settings; a shorter "keep saved reads" drops older reads right away.
#[tauri::command]
pub fn settings_set(window: WebviewWindow, state: State<'_, AppState>, settings: Settings) -> Res<Settings> {
guard(&window)?;
workspace::check_settings(&settings).map_err(Fail::host)?;
let mut st = saved(&state)?;
st.settings = settings.clone();
persist(&state, &st)?;
drop(st);
prune_cache(&state, settings.cache.keep_days);
Ok(settings)
}
pub fn prune_cache(state: &AppState, keep_days: u32) {
if keep_days == 0 {
return;
}
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
let cutoff = store::iso_from_unix(now.saturating_sub(u64::from(keep_days) * 86_400));
let _ = state.cache.prune_before(&cutoff);
}
#[derive(Serialize)]
pub struct CacheInfo {
rows: u64,
bytes: u64,
oldest: Option<String>,
/// cache.sqlite (+ its WAL) on disk.
file_bytes: u64,
}
#[tauri::command]
pub fn cache_info(window: WebviewWindow, state: State<'_, AppState>) -> Res<CacheInfo> {
guard(&window)?;
let (rows, bytes, oldest) = state.cache.info().map_err(Fail::host)?;
let file_bytes = ["", "-wal", "-shm"].iter().filter_map(|s| std::fs::metadata(state.data_dir.join(format!("{}{s}", crate::cache::FILE))).ok()).map(|m| m.len()).sum();
Ok(CacheInfo { rows, bytes, oldest, file_bytes })
}
/// Shows the app data folder (state, saved reads, downloaded tools; never keys) in the file manager.
#[tauri::command]
pub fn data_reveal(window: WebviewWindow, app: AppHandle, state: State<'_, AppState>) -> Res<()> {
guard(&window)?;
let _ = std::fs::create_dir_all(&state.data_dir);
app.opener().reveal_item_in_dir(state.data_dir.join(store::FILE)).or_else(|_| app.opener().open_path(state.data_dir.to_string_lossy(), None::<&str>)).map_err(|e| Fail::host(e.to_string()))
}
/// A desktop notification (review state changed, a new 1-2 star review, a crash rate over the threshold). The window
/// decides when, from Settings > Notifications; text is plain and short.
#[tauri::command]
pub fn notify(window: WebviewWindow, app: AppHandle, title: String, body: String) -> Res<()> {
guard(&window)?;
use tauri_plugin_notification::NotificationExt;
let cut = |s: &str, n: usize| s.chars().filter(|c| !c.is_control()).take(n).collect::<String>();
app.notification().builder().title(cut(&title, 80)).body(cut(&body, 240)).show().map_err(|e| Fail::host(e.to_string()))
}
/// Forgets everything after a native confirmation: store keys (keychain), studios, accounts, app folders (the folders
/// themselves stay), overrides, settings and saved reads. Downloaded tools stay. True when it was reset.
#[tauri::command]
pub async fn app_reset(window: WebviewWindow, state: State<'_, AppState>) -> Res<bool> {
guard(&window)?;
let w = window.clone();
let yes = tauri::async_runtime::spawn_blocking(move || {
w.app_handle()
.dialog()
.message("Removes every store key from the system keychain and forgets studios, accounts, app folders (the folders and their files stay), pairing, the ignore list, settings and saved store reads.\n\nDownloaded tools stay. This cannot be undone.")
.title("Reset storebound desktop?")
.kind(MessageDialogKind::Warning)
.buttons(MessageDialogButtons::OkCancelCustom("Reset".into(), "Cancel".into()))
.parent(&w)
.blocking_show()
})
.await
.map_err(|e| Fail::host(e.to_string()))?;
if !yes {
return Ok(false);
}
let mut st = saved(&state)?;
for a in &st.accounts {
state.secrets.delete(&a.id).map_err(Fail::host)?;
}
*st = Saved::default();
persist(&state, &st)?;
drop(st);
state.cache.clear().map_err(Fail::host)?;
Ok(true)
}

View file

@ -22,18 +22,4 @@ pub const COMMANDS: &[&str] = &[
"tools_info", "tools_info",
"tools_install", "tools_install",
"tools_uninstall", "tools_uninstall",
"workspace_get",
"studio_save",
"studio_remove",
"studio_logo",
"account_update",
"account_check",
"store_apps_refresh",
"store_apps_cached",
"overrides_set",
"settings_set",
"cache_info",
"data_reveal",
"notify",
"app_reset",
]; ];

View file

@ -8,7 +8,6 @@ pub mod downloads;
pub mod policy; pub mod policy;
pub mod sidecar; pub mod sidecar;
pub mod store; pub mod store;
pub mod workspace;
include!("commands_list.rs"); include!("commands_list.rs");
@ -137,19 +136,14 @@ pub fn run() {
let data_dir = app.path().app_data_dir()?; let data_dir = app.path().app_data_dir()?;
dev_seed(&data_dir); dev_seed(&data_dir);
let cache = cache::Cache::open(&data_dir).or_else(|_| cache::Cache::in_memory()).map_err(std::io::Error::other)?; let cache = cache::Cache::open(&data_dir).or_else(|_| cache::Cache::in_memory()).map_err(std::io::Error::other)?;
let saved = store::load(&data_dir); app.manage(commands::AppState {
let keep_days = saved.settings.cache.keep_days;
let state = commands::AppState {
sidecar: sidecar::Sidecar::default(), sidecar: sidecar::Sidecar::default(),
saved: Mutex::new(saved), saved: Mutex::new(store::load(&data_dir)),
data_dir, data_dir,
secrets: Box::new(accounts::Keychain), secrets: Box::new(accounts::Keychain),
cache, cache,
downloads: downloads::Jobs::default(), downloads: downloads::Jobs::default(),
}; });
// Settings > Offline cache: drop saved reads older than the chosen number of days
commands::prune_cache(&state, keep_days);
app.manage(state);
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
app.set_menu(menu(app.handle())?)?; app.set_menu(menu(app.handle())?)?;
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
@ -200,20 +194,6 @@ pub fn run() {
commands::tools_info, commands::tools_info,
commands::tools_install, commands::tools_install,
commands::tools_uninstall, commands::tools_uninstall,
commands::workspace_get,
commands::studio_save,
commands::studio_remove,
commands::studio_logo,
commands::account_update,
commands::account_check,
commands::store_apps_refresh,
commands::store_apps_cached,
commands::overrides_set,
commands::settings_set,
commands::cache_info,
commands::data_reveal,
commands::notify,
commands::app_reset,
]) ])
.build(tauri::generate_context!()) .build(tauri::generate_context!())
.expect("storebound desktop failed to start"); .expect("storebound desktop failed to start");

View file

@ -51,8 +51,6 @@ pub enum Kind {
System, System,
Portfolio, Portfolio,
Session, Session,
/// Account-scoped store reads (apps.list, account.check): the host runs them with one account's key.
Account,
} }
impl Kind { impl Kind {
@ -63,7 +61,6 @@ impl Kind {
"system" => Kind::System, "system" => Kind::System,
"portfolio" => Kind::Portfolio, "portfolio" => Kind::Portfolio,
"session" => Kind::Session, "session" => Kind::Session,
"account" => Kind::Account,
_ => return None, _ => return None,
}) })
} }
@ -81,7 +78,6 @@ pub fn sanitize_js_call(method: &str, kind: Option<Kind>, params: &Value) -> Res
match kind { match kind {
Kind::Session => return Err(format!("{method} is the host's")), Kind::Session => return Err(format!("{method} is the host's")),
Kind::Portfolio => return Err(format!("{method}: use portfolio_status")), Kind::Portfolio => return Err(format!("{method}: use portfolio_status")),
Kind::Account => return Err(format!("{method}: use the account commands")),
_ => {} _ => {}
} }
let empty = Map::new(); let empty = Map::new();
@ -113,8 +109,6 @@ pub const EXTERNAL_HOSTS: &[&str] = &[
"ffmpeg.org", "ffmpeg.org",
"googlechromelabs.github.io", "googlechromelabs.github.io",
"git-scm.com", "git-scm.com",
// account health fixes (enable an API in the service account's Google Cloud project)
"console.cloud.google.com",
]; ];
/// Executable of a Chrome for Testing download, relative to its unpacked folder (app data `tools/chrome/`). /// Executable of a Chrome for Testing download, relative to its unpacked folder (app data `tools/chrome/`).
@ -137,7 +131,7 @@ pub fn external_allowed(url: &Url) -> bool {
} }
/// Deep links the app reacts to: `storebound://<screen>` for a known screen, nothing else. /// Deep links the app reacts to: `storebound://<screen>` for a known screen, nothing else.
pub const DEEP_LINK_SCREENS: &[&str] = &["portfolio", "apps", "accounts", "ignored", "dependencies", "settings"]; pub const DEEP_LINK_SCREENS: &[&str] = &["portfolio", "apps", "accounts", "dependencies", "settings"];
pub fn deep_link_screen(url: &Url) -> Option<&'static str> { pub fn deep_link_screen(url: &Url) -> Option<&'static str> {
if url.scheme() != "storebound" { if url.scheme() != "storebound" {

View file

@ -6,7 +6,6 @@ use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::accounts::Account; use crate::accounts::Account;
use crate::workspace::{Overrides, Settings, Studio};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
@ -28,12 +27,6 @@ pub struct State {
pub projects: Vec<Project>, pub projects: Vec<Project>,
#[serde(default)] #[serde(default)]
pub accounts: Vec<Account>, pub accounts: Vec<Account>,
#[serde(default)]
pub studios: Vec<Studio>,
#[serde(default)]
pub overrides: Overrides,
#[serde(default)]
pub settings: Settings,
} }
pub const FILE: &str = "state.json"; pub const FILE: &str = "state.json";

View file

@ -1,309 +0,0 @@
//! Studios, app pairing overrides, the ignore list, app settings and store-only app targets. Pure data and checks, so
//! tests/workspace.rs can pin every rule. Nothing here is a secret: studios are names and colours, overrides are store
//! app keys (account id + store app id), settings are numbers and switches.
//!
//! Store app key: "ios:<account id>:<App Store Connect app id>" or "android:<account id>:<package name>"
//! Store target id: "store:ios:<account>:<app id>:<bundle id>;android:<account>:<package>" (either part optional, at least
//! one): a store-only app (no app folder) the window reads through the sidecar's generated config.
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
/// Colours a studio can carry (CSS classes `studio-<name>` in the window, contrast-checked there).
pub const STUDIO_COLORS: &[&str] = &["indigo", "violet", "rose", "amber", "emerald", "teal", "sky", "slate"];
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Studio {
pub id: String,
pub name: String,
pub color: String,
/// Small logo as a data: URL (PNG / JPEG / WebP, at most LOGO_MAX bytes before encoding), or none (monogram).
#[serde(default)]
pub logo: Option<String>,
pub created: String,
}
pub const LOGO_MAX: usize = 256 * 1024;
pub fn check_studio_name(s: &str) -> Result<String, String> {
let s = s.trim();
if s.is_empty() || s.chars().count() > 48 || s.chars().any(char::is_control) {
return Err("studio name: 1 to 48 characters".into());
}
Ok(s.to_string())
}
pub fn check_color(s: &str) -> Result<String, String> {
if STUDIO_COLORS.contains(&s) {
Ok(s.to_string())
} else {
Err(format!("colour: one of {}", STUDIO_COLORS.join(", ")))
}
}
/// Logo bytes -> data URL; only small raster images whose bytes match the type.
pub fn logo_data_url(bytes: &[u8]) -> Result<String, String> {
use base64::{engine::general_purpose::STANDARD, Engine};
if bytes.len() > LOGO_MAX {
return Err("logo: at most 256 KB".into());
}
let mime = if bytes.starts_with(&[0x89, b'P', b'N', b'G']) {
"image/png"
} else if bytes.starts_with(&[0xff, 0xd8, 0xff]) {
"image/jpeg"
} else if bytes.len() > 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
"image/webp"
} else {
return Err("logo: a PNG, JPEG or WebP image".into());
};
Ok(format!("data:{mime};base64,{}", STANDARD.encode(bytes)))
}
/// Account ids are what store::new_id makes (16 hex).
pub fn is_account_id(s: &str) -> bool {
s.len() == 16 && s.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
}
fn is_bundle(s: &str) -> bool {
!s.is_empty() && s.len() <= 155 && s.contains('.') && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-') && s.chars().next().is_some_and(|c| c.is_ascii_alphanumeric())
}
fn is_package(s: &str) -> bool {
let parts: Vec<&str> = s.split('.').collect();
s.len() <= 155
&& parts.len() >= 2
&& parts.iter().all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
&& parts[0].chars().next().is_some_and(|c| c.is_ascii_alphabetic())
}
fn is_asc_id(s: &str) -> bool {
!s.is_empty() && s.len() <= 20 && s.chars().all(|c| c.is_ascii_digit())
}
/// One app record on one store account.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StoreAppKey {
Ios { account: String, app_id: String },
Android { account: String, package: String },
}
impl StoreAppKey {
pub fn parse(s: &str) -> Result<StoreAppKey, String> {
let mut it = s.splitn(3, ':');
let (store, account, id) = (it.next().unwrap_or_default(), it.next().unwrap_or_default(), it.next().unwrap_or_default());
if !is_account_id(account) {
return Err(format!("store app key {s}: bad account id"));
}
match store {
"ios" if is_asc_id(id) => Ok(StoreAppKey::Ios { account: account.into(), app_id: id.into() }),
"android" if is_package(id) => Ok(StoreAppKey::Android { account: account.into(), package: id.into() }),
_ => Err(format!("store app key {s}: ios:<account>:<app id> or android:<account>:<package>")),
}
}
pub fn account(&self) -> &str {
match self {
StoreAppKey::Ios { account, .. } | StoreAppKey::Android { account, .. } => account,
}
}
}
/// A store-only app the window reads: which accounts, which store ids.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct StoreTarget {
/// (account, App Store Connect app id, bundle id)
pub ios: Option<(String, String, String)>,
/// (account, package name)
pub android: Option<(String, String)>,
}
impl StoreTarget {
pub fn parse(s: &str) -> Result<StoreTarget, String> {
let rest = s.strip_prefix("store:").ok_or("store target: store:...")?;
if rest.len() > 400 {
return Err("store target: too long".into());
}
let mut t = StoreTarget::default();
for part in rest.split(';') {
let f: Vec<&str> = part.split(':').collect();
match f.as_slice() {
["ios", acc, id, bundle] if t.ios.is_none() && is_account_id(acc) && is_asc_id(id) && is_bundle(bundle) => {
t.ios = Some((acc.to_string(), id.to_string(), bundle.to_string()));
}
["android", acc, pkg] if t.android.is_none() && is_account_id(acc) && is_package(pkg) => {
t.android = Some((acc.to_string(), pkg.to_string()));
}
_ => return Err(format!("store target: bad part '{part}'")),
}
}
if t.ios.is_none() && t.android.is_none() {
return Err("store target: ios and / or android".into());
}
Ok(t)
}
/// The sidecar's `virtual` object: store ids only, named after them.
pub fn virtual_project(&self) -> Value {
let name = self.ios.as_ref().map(|i| i.2.clone()).or_else(|| self.android.as_ref().map(|a| a.1.clone())).unwrap_or_default();
let mut v = json!({ "name": name });
if let Some((_, id, bundle)) = &self.ios {
v["apple"] = json!({ "bundleId": bundle, "appId": id });
}
if let Some((_, pkg)) = &self.android {
v["play"] = json!({ "packageName": pkg });
}
v
}
pub fn accounts(&self) -> Vec<&str> {
self.ios.iter().map(|i| i.0.as_str()).chain(self.android.iter().map(|a| a.0.as_str())).collect()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Pair {
pub ios: String,
pub android: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Link {
/// Store app key.
pub key: String,
/// Project id (app folder).
pub project: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AppStudio {
/// Store app key or "project:<id>".
pub key: String,
pub studio: String,
}
/// The owner's corrections to automatic pairing, links of store apps to folders, studio moves and the ignore list.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Overrides {
#[serde(default)]
pub pairs: Vec<Pair>,
#[serde(default)]
pub unpairs: Vec<Pair>,
#[serde(default)]
pub links: Vec<Link>,
#[serde(default)]
pub app_studio: Vec<AppStudio>,
/// "app:<store app key>", "project:<id>" or "account:<id>".
#[serde(default)]
pub ignored: Vec<String>,
}
pub const MAX_OVERRIDES: usize = 2000;
/// Checks every key; drops nothing silently (an error names the bad entry).
pub fn check_overrides(o: &Overrides) -> Result<(), String> {
if o.pairs.len() + o.unpairs.len() + o.links.len() + o.app_studio.len() + o.ignored.len() > MAX_OVERRIDES {
return Err("too many overrides".into());
}
for p in o.pairs.iter().chain(o.unpairs.iter()) {
match (StoreAppKey::parse(&p.ios)?, StoreAppKey::parse(&p.android)?) {
(StoreAppKey::Ios { .. }, StoreAppKey::Android { .. }) => {}
_ => return Err("pair: an iOS key and an Android key".into()),
}
}
for l in &o.links {
StoreAppKey::parse(&l.key)?;
if l.project.is_empty() || l.project.len() > 64 {
return Err("link: project id".into());
}
}
for a in &o.app_studio {
if let Some(p) = a.key.strip_prefix("project:") {
if p.is_empty() || p.len() > 64 {
return Err("app studio: project id".into());
}
} else {
StoreAppKey::parse(&a.key)?;
}
if a.studio.is_empty() || a.studio.len() > 64 {
return Err("app studio: studio id".into());
}
}
for i in &o.ignored {
let ok = match i.split_once(':') {
Some(("app", k)) => StoreAppKey::parse(k).is_ok(),
Some(("account", id)) => is_account_id(id),
Some(("project", id)) => !id.is_empty() && id.len() <= 64,
_ => false,
};
if !ok {
return Err(format!("ignored: bad entry '{i}'"));
}
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RefreshSettings {
/// Minutes between automatic store reads; 0 = off.
pub auto_minutes: u32,
pub on_launch: bool,
/// Apps read at the same time (1-8).
pub parallel: u8,
/// Read app icons from the stores when importing (an extra request per app).
pub icons: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CacheSettings {
/// Saved reads older than this many days are dropped; 0 = keep.
pub keep_days: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NotifySettings {
pub review_state: bool,
pub low_reviews: bool,
pub crash: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Settings {
pub refresh: RefreshSettings,
pub cache: CacheSettings,
pub notify: NotifySettings,
/// Update channel (placeholder until the updater ships): stable | beta.
pub channel: String,
}
impl Default for Settings {
fn default() -> Settings {
Settings {
refresh: RefreshSettings { auto_minutes: 0, on_launch: false, parallel: 4, icons: true },
cache: CacheSettings { keep_days: 30 },
notify: NotifySettings { review_state: true, low_reviews: true, crash: true },
channel: "stable".into(),
}
}
}
pub const AUTO_MINUTES: &[u32] = &[0, 15, 30, 60, 180, 720];
pub const KEEP_DAYS: &[u32] = &[0, 7, 30, 90, 365];
pub fn check_settings(s: &Settings) -> Result<(), String> {
if !AUTO_MINUTES.contains(&s.refresh.auto_minutes) {
return Err("refresh: 0 (off), 15, 30, 60, 180 or 720 minutes".into());
}
if !(1..=8).contains(&s.refresh.parallel) {
return Err("parallel reads: 1 to 8".into());
}
if !KEEP_DAYS.contains(&s.cache.keep_days) {
return Err("keep saved reads: 0 (always), 7, 30, 90 or 365 days".into());
}
if !["stable", "beta"].contains(&s.channel.as_str()) {
return Err("channel: stable or beta".into());
}
Ok(())
}

View file

@ -9,9 +9,9 @@ const FAKE_PEM: &str = "-----BEGIN PRIVATE KEY-----\nnot-a-real-key\n-----END PR
#[test] #[test]
fn shown_metadata_carries_no_secret() { fn shown_metadata_carries_no_secret() {
let a = Account { id: "abc".into(), label: "Studio Play".into(), kind: AccountKind::Play, created: "2026-10-10T00:00:00Z".into(), studio: Some("s1".into()) }; let a = Account { id: "abc".into(), label: "Studio Play".into(), kind: AccountKind::Play, created: "2026-10-10T00:00:00Z".into() };
let v = serde_json::to_value(&a).unwrap(); let v = serde_json::to_value(&a).unwrap();
assert_eq!(v.as_object().unwrap().keys().cloned().collect::<Vec<_>>(), vec!["created", "id", "kind", "label", "studio"]); assert_eq!(v.as_object().unwrap().keys().cloned().collect::<Vec<_>>(), vec!["created", "id", "kind", "label"]);
assert_eq!(v["kind"], "play"); assert_eq!(v["kind"], "play");
} }
@ -53,7 +53,6 @@ fn state_file_round_trip_is_atomic_and_tolerant() {
let st = State { let st = State {
projects: vec![Project { id: "1".into(), path: "/games/a".into(), name: "A".into(), play_account: Some("p".into()), apple_account: None, added: "2026-10-10T00:00:00Z".into() }], projects: vec![Project { id: "1".into(), path: "/games/a".into(), name: "A".into(), play_account: Some("p".into()), apple_account: None, added: "2026-10-10T00:00:00Z".into() }],
accounts: vec![], accounts: vec![],
..State::default()
}; };
store::save(dir.path(), &st).unwrap(); store::save(dir.path(), &st).unwrap();
assert_eq!(store::load(dir.path()), st); assert_eq!(store::load(dir.path()), st);

View file

@ -1,160 +0,0 @@
//! Desktop D3: studios, store app keys and store-only targets, pairing / ignore overrides, settings, old state files.
use serde_json::json;
use storebound_desktop::cache::Cache;
use storebound_desktop::policy::{sanitize_js_call, Kind};
use storebound_desktop::store::{self, State};
use storebound_desktop::workspace::*;
const A1: &str = "0123456789abcdef";
const A2: &str = "fedcba9876543210";
#[test]
fn studio_names_colours_and_logos() {
assert_eq!(check_studio_name(" Example Games ").unwrap(), "Example Games");
assert!(check_studio_name("").is_err());
assert!(check_studio_name(&"x".repeat(49)).is_err());
assert!(check_studio_name("a\nb").is_err());
for c in STUDIO_COLORS {
assert!(check_color(c).is_ok());
}
assert!(check_color("#ff0000").is_err());
assert!(check_color("red; background:url(x)").is_err());
assert!(logo_data_url(&[0x89, b'P', b'N', b'G', 1, 2]).unwrap().starts_with("data:image/png;base64,"));
assert!(logo_data_url(&[0xff, 0xd8, 0xff, 0]).unwrap().starts_with("data:image/jpeg;base64,"));
assert!(logo_data_url(b"RIFF\0\0\0\0WEBPVP8 ").unwrap().starts_with("data:image/webp;"));
assert!(logo_data_url(b"<svg onload=alert(1)>").is_err(), "no SVG (scripts) as a logo");
assert!(logo_data_url(&vec![0x89; LOGO_MAX + 1]).is_err());
}
#[test]
fn store_app_keys() {
assert_eq!(StoreAppKey::parse(&format!("ios:{A1}:6400000101")).unwrap(), StoreAppKey::Ios { account: A1.into(), app_id: "6400000101".into() });
assert_eq!(StoreAppKey::parse(&format!("android:{A2}:com.example.puzzle")).unwrap().account(), A2);
for bad in [
format!("ios:{A1}:com.example.puzzle"),
format!("android:{A1}:6400000101"),
"ios:nothex0123456789:1".to_string(),
format!("mac:{A1}:1"),
format!("android:{A1}:com.example.puzzle/../x"),
format!("android:{A1}:.example"),
format!("ios:{}:1", A1.to_uppercase()),
] {
assert!(StoreAppKey::parse(&bad).is_err(), "{bad}");
}
}
#[test]
fn store_only_targets_become_virtual_projects_with_store_ids_only() {
let t = StoreTarget::parse(&format!("store:ios:{A1}:6400000101:com.example.puzzle;android:{A2}:com.example.puzzle")).unwrap();
assert_eq!(t.accounts(), vec![A1, A2]);
assert_eq!(
t.virtual_project(),
json!({ "name": "com.example.puzzle", "apple": { "bundleId": "com.example.puzzle", "appId": "6400000101" }, "play": { "packageName": "com.example.puzzle" } })
);
let only = StoreTarget::parse(&format!("store:android:{A2}:com.example.runner")).unwrap();
assert_eq!(only.virtual_project(), json!({ "name": "com.example.runner", "play": { "packageName": "com.example.runner" } }));
for bad in [
"store:".to_string(),
"ios:x".to_string(),
format!("store:ios:{A1}:6400000101"),
format!("store:ios:{A1}:6400000101:com.example.a;ios:{A1}:6400000102:com.example.b"),
format!("store:android:{A2}:com.example.a;android:{A2}:com.example.b"),
format!("store:android:{A2}:com.example.a;path:/etc"),
format!("store:ios:{A1}:6400000101:../../etc"),
format!("store:android:{A2}:com.example.a;{}", "x".repeat(400)),
] {
assert!(StoreTarget::parse(&bad).is_err(), "{bad}");
}
}
#[test]
fn overrides_are_checked_entry_by_entry() {
let ok = Overrides {
pairs: vec![Pair { ios: format!("ios:{A1}:6400000101"), android: format!("android:{A2}:com.example.puzzle") }],
unpairs: vec![Pair { ios: format!("ios:{A1}:6400000102"), android: format!("android:{A2}:com.example.notes") }],
links: vec![Link { key: format!("ios:{A1}:6400000103"), project: "p1".into() }],
app_studio: vec![AppStudio { key: format!("android:{A2}:com.example.runner"), studio: "s1".into() }, AppStudio { key: "project:p1".into(), studio: "s2".into() }],
ignored: vec![format!("app:ios:{A1}:6400000104"), format!("account:{A2}"), "project:p9".into()],
};
assert!(check_overrides(&ok).is_ok());
let mut swapped = ok.clone();
swapped.pairs = vec![Pair { ios: format!("android:{A2}:com.example.puzzle"), android: format!("ios:{A1}:6400000101") }];
assert!(check_overrides(&swapped).is_err());
for bad in ["app:ios:x:1", "account:short", "project:", "everything", "app:"] {
let mut o = ok.clone();
o.ignored.push(bad.into());
assert!(check_overrides(&o).is_err(), "{bad}");
}
let many = Overrides { ignored: (0..=MAX_OVERRIDES).map(|i| format!("project:p{i}")).collect(), ..Default::default() };
assert!(check_overrides(&many).is_err());
// camelCase on the wire
let v = serde_json::to_value(&ok).unwrap();
assert!(v.get("appStudio").is_some());
}
#[test]
fn settings_have_safe_defaults_and_bounds() {
let d = Settings::default();
assert!(check_settings(&d).is_ok());
assert_eq!((d.refresh.auto_minutes, d.refresh.on_launch, d.refresh.parallel, d.cache.keep_days, d.channel.as_str()), (0, false, 4, 30, "stable"));
let mut s = d.clone();
s.refresh.parallel = 0;
assert!(check_settings(&s).is_err());
s = d.clone();
s.refresh.parallel = 9;
assert!(check_settings(&s).is_err());
s = d.clone();
s.refresh.auto_minutes = 1;
assert!(check_settings(&s).is_err(), "no tight polling of the store APIs");
s = d.clone();
s.cache.keep_days = 3;
assert!(check_settings(&s).is_err());
s = d;
s.channel = "nightly".into();
assert!(check_settings(&s).is_err());
let v = serde_json::to_value(Settings::default()).unwrap();
assert_eq!(v["refresh"]["autoMinutes"], 0);
assert_eq!(v["cache"]["keepDays"], 30);
assert_eq!(v["notify"]["lowReviews"], true);
}
#[test]
fn a_d2_state_file_still_loads_with_empty_d3_parts() {
let dir = tempfile::tempdir().unwrap();
let d2 = json!({
"projects": [{ "id": "p1", "path": "/x", "name": "X", "playAccount": null, "appleAccount": null, "added": "2026-10-01T00:00:00Z" }],
"accounts": [{ "id": A1, "label": "Play", "kind": "play", "created": "2026-10-01T00:00:00Z" }]
});
std::fs::write(dir.path().join(store::FILE), d2.to_string()).unwrap();
let st = store::load(dir.path());
assert_eq!(st.projects.len(), 1);
assert_eq!(st.accounts[0].studio, None);
assert!(st.studios.is_empty());
assert_eq!(st.overrides, Overrides::default());
assert_eq!(st.settings, Settings::default());
store::save(dir.path(), &st).unwrap();
assert_eq!(store::load(dir.path()), st);
assert_eq!(State::default().settings.refresh.parallel, 4);
}
#[test]
fn account_reads_are_the_hosts() {
// the window cannot call apps.list / account.check directly: only the account commands (one key per call)
assert!(sanitize_js_call("apps.list", Some(Kind::Account), &json!({ "credentials": {} })).is_err());
assert!(sanitize_js_call("account.check", Some(Kind::Account), &json!({})).is_err());
assert_eq!(Kind::parse("account"), Some(Kind::Account));
}
#[test]
fn cache_info_and_pruning_by_age() {
let c = Cache::in_memory().unwrap();
c.put("p", "health", &json!({}), &json!({ "n": 1 }), "2026-01-01T00:00:00Z").unwrap();
c.put("p", "reviews.list", &json!({}), &json!({ "n": 2 }), "2026-10-01T00:00:00Z").unwrap();
c.put("acct:x", "apps.list", &json!({}), &json!({ "apps": [] }), "2026-10-10T00:00:00Z").unwrap();
let (rows, bytes, oldest) = c.info().unwrap();
assert_eq!((rows, oldest.as_deref()), (3, Some("2026-01-01T00:00:00Z")));
assert!(bytes > 0);
assert_eq!(c.prune_before("2026-09-01T00:00:00Z").unwrap(), 1);
assert!(c.get("p", "health", &json!({})).unwrap().is_none());
assert!(c.get("p", "reviews.list", &json!({})).unwrap().is_some());
}

View file

@ -1,34 +1,27 @@
// Shell: sidebar (studios, collapsible, with their apps; the workspace), top bar (breadcrumbs, last read, refresh), // Shell: sidebar (apps with their icons, workspace), top bar (breadcrumbs, last read, refresh), the screen, the
// the screen, the command palette (Cmd/Ctrl+K), toasts and the first-run welcome guide. // command palette (Cmd/Ctrl+K), toasts and the first-run welcome guide.
import { useCallback, useEffect, useMemo, useState } from 'react'; import { useCallback, useEffect, useMemo, useState } from 'react';
import { FIXTURES, onDeepLink } from './api'; import { FIXTURES, onDeepLink } from './api';
import { devSwitch } from './dev/switches'; import { devSwitch } from './dev/switches';
import { type Key, t } from './i18n'; import { type Key, t } from './i18n';
import { ago } from './lib/format'; import { ago } from './lib/format';
import { groupByStudio, type UnifiedApp } from './lib/identity'; import { APP_TABS, NavCtx, parseStart, type Route, sameRoute, TAB_ICON, TAB_KEY, WORKSPACE, type WorkspaceScreen } from './nav';
import { NavCtx, parseStart, type Route, sameRoute, TAB_ICON, TAB_KEY, tabsFor, WORKSPACE, type WorkspaceScreen } from './nav';
import { usePrefs } from './prefs-ctx'; import { usePrefs } from './prefs-ctx';
import { Accounts } from './screens/Accounts'; import { Accounts } from './screens/Accounts';
import { AppFolders } from './screens/AppFolders'; import { AppFolders } from './screens/AppFolders';
import { AppView } from './screens/AppView'; import { AppView } from './screens/AppView';
import { Dependencies } from './screens/Dependencies'; import { Dependencies } from './screens/Dependencies';
import { Ignored } from './screens/Ignored';
import { Onboarding } from './screens/Onboarding'; import { Onboarding } from './screens/Onboarding';
import { Portfolio } from './screens/Portfolio'; import { Portfolio } from './screens/Portfolio';
import { Settings } from './screens/Settings'; import { Settings } from './screens/Settings';
import { useData } from './store'; import { useData } from './store';
import { Icon, type IconName, Mark } from './ui/icons'; import { Icon, type IconName, Mark } from './ui/icons';
import { AppIcon, Kbd, MOD, StudioMark } from './ui/kit'; import { AppIcon, Kbd, MOD } from './ui/kit';
import { type Command, Palette } from './ui/Palette'; import { type Command, Palette } from './ui/Palette';
import { Toasts } from './ui/Toasts'; import { Toasts } from './ui/Toasts';
const WS_ICON: Record<WorkspaceScreen, IconName> = { apps: 'folder', accounts: 'building', ignored: 'eyeOff', dependencies: 'package', settings: 'settings' }; const WS_ICON: Record<WorkspaceScreen, IconName> = { apps: 'folder', accounts: 'key', dependencies: 'package', settings: 'settings' };
export const WS_KEY: Record<WorkspaceScreen, Key> = { apps: 'nav.apps', accounts: 'nav.accounts', ignored: 'nav.ignored', dependencies: 'nav.dependencies', settings: 'nav.settings' }; const WS_KEY: Record<WorkspaceScreen, Key> = { apps: 'nav.apps', accounts: 'nav.accounts', dependencies: 'nav.dependencies', settings: 'nav.settings' };
const SIDE_KEY = 'storebound.side.v1';
function loadCollapsed(): string[] {
try { const v = JSON.parse(localStorage.getItem(SIDE_KEY) ?? '[]') as unknown; return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []; } catch { return []; }
}
export function App({ onTheme }: { onTheme: () => void }) { export function App({ onTheme }: { onTheme: () => void }) {
const d = useData(); const d = useData();
@ -37,15 +30,8 @@ export function App({ onTheme }: { onTheme: () => void }) {
const [palette, setPalette] = useState(false); const [palette, setPalette] = useState(false);
const [welcome, setWelcome] = useState(false); const [welcome, setWelcome] = useState(false);
const [started, setStarted] = useState(false); const [started, setStarted] = useState(false);
const [collapsed, setCollapsed] = useState<string[]>(loadCollapsed);
const go = useCallback((r: Route) => { setRoute(r); document.getElementById('content')?.scrollTo({ top: 0 }); }, []); const go = useCallback((r: Route) => { setRoute(r); document.getElementById('content')?.scrollTo({ top: 0 }); }, []);
const visible = useMemo(() => d.apps.filter(a => !a.ignored).sort((a, b) => a.name.localeCompare(b.name)), [d.apps]);
const toggleGroup = (id: string) => setCollapsed(c => {
const next = c.includes(id) ? c.filter(x => x !== id) : [...c, id];
try { localStorage.setItem(SIDE_KEY, JSON.stringify(next)); } catch { /* private mode */ }
return next;
});
// first screen: dev switch (VITE_START), else the welcome guide on a first run // first screen: dev switch (VITE_START), else the welcome guide on a first run
useEffect(() => { useEffect(() => {
@ -54,92 +40,69 @@ export function App({ onTheme }: { onTheme: () => void }) {
const v = devSwitch('start'); const v = devSwitch('start');
if (v === 'welcome' || v.startsWith('welcome:')) { setWelcome(true); return; } if (v === 'welcome' || v.startsWith('welcome:')) { setWelcome(true); return; }
if (v === 'palette') setPalette(true); if (v === 'palette') setPalette(true);
const r = parseStart(v, d.apps.filter(a => !a.ignored).map(a => a.key)); const r = parseStart(v, d.projects.map(p => p.id));
if (r) { go(r); return; } if (r) { go(r); return; }
if (!d.projects.length && !d.accounts.length && !prefs.onboarded) setWelcome(true); if (!d.projects.length && !prefs.onboarded) setWelcome(true);
}, [d.ready, d.apps, d.projects, d.accounts, started, go, prefs.onboarded]); }, [d.ready, d.projects, started, go, prefs.onboarded]);
useEffect(() => { useEffect(() => {
const un = onDeepLink(s => { const r = parseStart(s, []); if (r) go(r); }); const un = onDeepLink(s => { const r = parseStart(s, []); if (r) go(r); });
return () => { un.then(f => f()); }; return () => { un.then(f => f()); };
}, [go]); }, [d.projects, go]);
const app = route.screen === 'app' ? d.appByKey(route.appId) : undefined; // keyboard: Cmd/Ctrl+K palette, Cmd/Ctrl+1 portfolio, 2-5 workspace, Cmd/Ctrl+Shift+[ ] app tabs
const tabs = app ? tabsFor(!!app.project) : [];
// keyboard: Cmd/Ctrl+K palette, Cmd/Ctrl+1 portfolio, 2-6 workspace, Cmd/Ctrl+Shift+[ ] app tabs
useEffect(() => { useEffect(() => {
const onKey = (e: KeyboardEvent) => { const onKey = (e: KeyboardEvent) => {
const mod = e.metaKey || e.ctrlKey; const mod = e.metaKey || e.ctrlKey;
if (mod && !e.shiftKey && !e.altKey && e.key.toLowerCase() === 'k') { e.preventDefault(); setPalette(p => !p); return; } if (mod && !e.shiftKey && !e.altKey && e.key.toLowerCase() === 'k') { e.preventDefault(); setPalette(p => !p); return; }
if (palette || welcome) return; if (palette || welcome) return;
if (mod && !e.shiftKey && !e.altKey && /^[1-6]$/.test(e.key)) { if (mod && !e.shiftKey && !e.altKey && /^[1-5]$/.test(e.key)) {
e.preventDefault(); e.preventDefault();
const n = Number(e.key); const n = Number(e.key);
go(n === 1 ? { screen: 'portfolio' } : { screen: WORKSPACE[n - 2]! }); go(n === 1 ? { screen: 'portfolio' } : { screen: WORKSPACE[n - 2]! });
return; return;
} }
if (mod && e.shiftKey && (e.key === '[' || e.key === ']' || e.key === '{' || e.key === '}') && route.screen === 'app' && tabs.length) { if (mod && e.shiftKey && (e.key === '[' || e.key === ']' || e.key === '{' || e.key === '}') && route.screen === 'app') {
e.preventDefault(); e.preventDefault();
const i = tabs.indexOf(route.tab) + (e.key === ']' || e.key === '}' ? 1 : -1); const i = APP_TABS.indexOf(route.tab) + (e.key === ']' || e.key === '}' ? 1 : -1);
go({ ...route, tab: tabs[(i + tabs.length) % tabs.length]! }); go({ ...route, tab: APP_TABS[(i + APP_TABS.length) % APP_TABS.length]! });
} }
}; };
window.addEventListener('keydown', onKey); window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey);
}, [palette, welcome, route, go, tabs]); }, [palette, welcome, route, go]);
const closeWelcome = useCallback(() => { const closeWelcome = useCallback(() => {
setWelcome(false); setWelcome(false);
if (!prefs.onboarded) update({ ...prefs, onboarded: true }); if (!prefs.onboarded) update({ ...prefs, onboarded: true });
}, [prefs, update]); }, [prefs, update]);
useEffect(() => { if (route.screen === 'app' && d.ready && d.apps.length && !app) go({ screen: 'portfolio' }); }, [route, app, d.ready, d.apps.length, go]); const app = route.screen === 'app' ? d.projects.find(p => p.id === route.appId) : undefined;
useEffect(() => { if (route.screen === 'app' && d.ready && !app) go({ screen: 'portfolio' }); }, [route, app, d.ready, go]);
const commands = useMemo<Command[]>(() => { const commands = useMemo<Command[]>(() => {
const c: Command[] = []; const c: Command[] = [];
const G = { apps: t('palette.gApps'), go: t('palette.gGo'), tabs: t('palette.gTabs'), act: t('palette.gActions') }; const G = { apps: t('palette.gApps'), go: t('palette.gGo'), tabs: t('palette.gTabs'), act: t('palette.gActions') };
const studioName = (a: UnifiedApp) => d.studios.find(s => s.id === a.studio)?.name; for (const p of d.projects) c.push({ id: `app-${p.id}`, group: G.apps, title: d.statusOf(p)?.app?.name ?? p.name, hint: t('palette.openApp'), app: { name: p.name, icon: d.icons[p.id] }, run: () => go({ screen: 'app', appId: p.id, tab: route.screen === 'app' ? route.tab : 'releases' }) });
for (const a of visible) c.push({ id: `app-${a.key}`, group: G.apps, title: a.name, hint: studioName(a) ?? t('palette.openApp'), keywords: `${a.ios?.app.bundleId ?? ''} ${a.android?.app.id ?? ''} ${a.project?.name ?? ''}`, app: { name: a.name, icon: d.iconFor(a) },
run: () => go({ screen: 'app', appId: a.key, tab: route.screen === 'app' && tabsFor(!!a.project).includes(route.tab) ? route.tab : 'releases' }) });
c.push({ id: 'go-portfolio', group: G.go, title: t('nav.portfolio'), icon: 'portfolio', hint: `${MOD} 1`, run: () => go({ screen: 'portfolio' }) }); c.push({ id: 'go-portfolio', group: G.go, title: t('nav.portfolio'), icon: 'portfolio', hint: `${MOD} 1`, run: () => go({ screen: 'portfolio' }) });
WORKSPACE.forEach((s, i) => c.push({ id: `go-${s}`, group: G.go, title: t(WS_KEY[s]), icon: WS_ICON[s], hint: `${MOD} ${i + 2}`, run: () => go({ screen: s }) })); WORKSPACE.forEach((s, i) => c.push({ id: `go-${s}`, group: G.go, title: t(WS_KEY[s]), icon: WS_ICON[s], hint: `${MOD} ${i + 2}`, run: () => go({ screen: s }) }));
for (const s of d.studios) c.push({ id: `studio-${s.id}`, group: G.go, title: s.name, icon: 'building', keywords: 'studio', hint: t('palette.studio'), run: () => go({ screen: 'accounts', section: s.id }) }); if (app) for (const tab of APP_TABS) c.push({ id: `tab-${tab}`, group: G.tabs, title: `${app.name} · ${t(TAB_KEY[tab])}`, icon: TAB_ICON[tab], run: () => go({ screen: 'app', appId: app.id, tab }) });
if (app) for (const tab of tabs) c.push({ id: `tab-${tab}`, group: G.tabs, title: `${app.name} · ${t(TAB_KEY[tab])}`, icon: TAB_ICON[tab], run: () => go({ screen: 'app', appId: app.key, tab }) }); else if (d.projects[0]) for (const p of d.projects) for (const tab of APP_TABS) c.push({ id: `tab-${p.id}-${tab}`, group: G.tabs, title: `${p.name} · ${t(TAB_KEY[tab])}`, icon: TAB_ICON[tab], keywords: 'tab', run: () => go({ screen: 'app', appId: p.id, tab }) });
c.push({ id: 'act-live', group: G.act, title: t('action.readStores'), icon: 'refresh', keywords: 'refresh sync', run: () => { d.refreshPortfolio(true); } }); c.push({ id: 'act-live', group: G.act, title: t('action.readStores'), icon: 'refresh', keywords: 'refresh sync', run: () => { d.refreshPortfolio(true); } });
c.push({ id: 'act-import', group: G.act, title: t('action.importApps'), icon: 'download', keywords: 'import sync accounts', run: () => { d.importApps(); } });
c.push({ id: 'act-check', group: G.act, title: t('action.checkConfigs'), icon: 'shield', run: () => { d.refreshPortfolio(false); } }); c.push({ id: 'act-check', group: G.act, title: t('action.checkConfigs'), icon: 'shield', run: () => { d.refreshPortfolio(false); } });
c.push({ id: 'act-add', group: G.act, title: t('action.addFolder'), icon: 'folderPlus', run: () => go({ screen: 'apps' }) }); c.push({ id: 'act-add', group: G.act, title: t('action.addFolder'), icon: 'folderPlus', run: () => go({ screen: 'apps' }) });
c.push({ id: 'act-account', group: G.act, title: t('action.addAccount'), icon: 'key', run: () => go({ screen: 'accounts' }) }); c.push({ id: 'act-account', group: G.act, title: t('action.addAccount'), icon: 'key', run: () => go({ screen: 'accounts' }) });
c.push({ id: 'act-theme', group: G.act, title: t('action.toggleTheme'), icon: 'moon', keywords: 'dark light', run: onTheme }); c.push({ id: 'act-theme', group: G.act, title: t('action.toggleTheme'), icon: 'moon', keywords: 'dark light', run: onTheme });
c.push({ id: 'act-welcome', group: G.act, title: t('action.welcome'), icon: 'sparkle', keywords: 'onboarding start guide', run: () => setWelcome(true) }); c.push({ id: 'act-welcome', group: G.act, title: t('action.welcome'), icon: 'sparkle', keywords: 'onboarding start guide', run: () => setWelcome(true) });
return c; return c;
}, [d, visible, app, tabs, route, go, onTheme]); }, [d, app, route, go, onTheme]);
const crumbs: { label: string; to?: Route }[] = route.screen === 'portfolio' ? [{ label: t('nav.portfolio') }] const crumbs: { label: string; to?: Route }[] = route.screen === 'portfolio' ? [{ label: t('nav.portfolio') }]
: route.screen === 'app' ? [{ label: t('nav.portfolio'), to: { screen: 'portfolio' } }, { label: app?.name ?? '', to: app ? { screen: 'app', appId: app.key, tab: 'releases' } : undefined }, { label: t(TAB_KEY[route.tab]) }] : route.screen === 'app' ? [{ label: t('nav.portfolio'), to: { screen: 'portfolio' } }, { label: app?.name ?? '', to: app ? { screen: 'app', appId: app.id, tab: 'releases' } : undefined }, { label: t(TAB_KEY[route.tab]) }]
: [{ label: t('nav.workspace') }, { label: t(WS_KEY[route.screen]) }]; : [{ label: t('nav.workspace') }, { label: t(WS_KEY[route.screen]) }];
const lastRead = d.live?.at ?? null; const lastRead = d.live?.at ?? null;
const nav = useMemo(() => ({ route, go, openPalette: () => setPalette(true), openWelcome: () => setWelcome(true) }), [route, go]); const nav = useMemo(() => ({ route, go, openPalette: () => setPalette(true), openWelcome: () => setWelcome(true) }), [route, go]);
const current = (r: Route) => (sameRoute(r, route) || (r.screen === 'app' && route.screen === 'app' && r.appId === route.appId) || (r.screen !== 'app' && r.screen !== 'portfolio' && r.screen === route.screen) ? 'page' : undefined); const current = (r: Route) => (sameRoute(r, route) || (r.screen === 'app' && route.screen === 'app' && r.appId === route.appId) ? 'page' : undefined);
const groups = d.studios.length ? groupByStudio(visible.map(a => ({ app: a })), d.studios) : [{ studio: null as string | null, rows: visible.map(a => ({ app: a })) }];
const ignoredCount = d.apps.filter(a => a.ignored).length + d.overrides.ignored.filter(i => i.startsWith('account:')).length;
const appItem = (a: UnifiedApp) => {
const e = d.statusFor(a);
const bad = (e?.errors.length ?? 0) + (e?.check?.problems.length ?? 0);
return (
<div role="listitem" key={a.key}>
<button className="nav nav-app" aria-current={current({ screen: 'app', appId: a.key, tab: 'releases' })}
onClick={() => go({ screen: 'app', appId: a.key, tab: route.screen === 'app' && tabsFor(!!a.project).includes(route.tab) ? route.tab : 'releases' })}>
<AppIcon name={a.name} src={d.iconFor(a)} />
<span className="grow">{a.name}</span>
{!a.project && <span className="so-dot" title={t('apps.storeOnlyHint')}><Icon name="cloud" /></span>}
{bad > 0 && <span className="tag-count bad" aria-label={t('nav.problems', { count: bad })}>{bad}</span>}
</button>
</div>
);
};
return ( return (
<NavCtx.Provider value={nav}> <NavCtx.Provider value={nav}>
@ -154,32 +117,32 @@ export function App({ onTheme }: { onTheme: () => void }) {
</div> </div>
<div className="side-scroll"> <div className="side-scroll">
<button className="nav" aria-current={current({ screen: 'portfolio' })} onClick={() => go({ screen: 'portfolio' })}> <button className="nav" aria-current={current({ screen: 'portfolio' })} onClick={() => go({ screen: 'portfolio' })}>
<Icon name="portfolio" /><span className="grow">{t('nav.portfolio')}</span><span className="count">{visible.length}</span> <Icon name="portfolio" /><span className="grow">{t('nav.portfolio')}</span>
</button> </button>
<div className="side-label" id="apps-label"><span>{d.studios.length ? t('nav.studiosLabel') : t('nav.appsLabel')}</span> <div className="side-label" id="apps-label"><span>{t('nav.appsLabel')}</span>
<button onClick={() => go({ screen: 'apps' })} aria-label={t('action.addFolder')} title={t('action.addFolder')}><Icon name="plus" /></button> <button onClick={() => go({ screen: 'apps' })} aria-label={t('action.addFolder')} title={t('action.addFolder')}><Icon name="plus" /></button>
</div> </div>
{groups.map(g => { <div role="list" aria-labelledby="apps-label">
const s = d.studios.find(x => x.id === g.studio) ?? null; {d.projects.map(p => {
const gid = g.studio ?? 'none'; const e = d.statusOf(p);
const open = !collapsed.includes(gid); const bad = (e?.errors.length ?? 0) + (e?.check?.problems.length ?? 0);
if (!d.studios.length) return <div role="list" aria-labelledby="apps-label" key={gid}>{g.rows.map(r => appItem(r.app))}</div>;
return ( return (
<div className="side-group" key={gid}> <div role="listitem" key={p.id}>
<button className="side-group-head" aria-expanded={open} aria-controls={`sg-${gid}`} onClick={() => toggleGroup(gid)}> <button className="nav nav-app" aria-current={current({ screen: 'app', appId: p.id, tab: 'releases' })} onClick={() => go({ screen: 'app', appId: p.id, tab: route.screen === 'app' ? route.tab : 'releases' })}>
<Icon name="chevronRight" className="chev" /><StudioMark studio={s} size="sm" /><span className="grow">{s?.name ?? t('studio.none')}</span><span className="count">{g.rows.length}</span> <AppIcon name={p.name} src={d.icons[p.id]} />
<span className="grow">{e?.app?.name ?? p.name}</span>
{bad > 0 && <span className="tag-count bad" aria-label={t('nav.problems', { count: bad })}>{bad}</span>}
</button> </button>
{open && <div role="list" id={`sg-${gid}`} aria-label={s?.name ?? t('studio.none')}>{g.rows.map(r => appItem(r.app))}</div>}
</div> </div>
); );
})} })}
{!visible.length && <p className="side-empty">{t('nav.noApps')}</p>} {!d.projects.length && <p className="side-empty">{t('nav.noApps')}</p>}
</div>
<div className="side-label"><span>{t('nav.workspace')}</span></div> <div className="side-label"><span>{t('nav.workspace')}</span></div>
{WORKSPACE.map((s, i) => ( {WORKSPACE.map((s, i) => (
<button key={s} className="nav" aria-current={current({ screen: s })} onClick={() => go({ screen: s })} title={`${t(WS_KEY[s])} (${MOD} ${i + 2})`}> <button key={s} className="nav" aria-current={current({ screen: s })} onClick={() => go({ screen: s })} title={`${t(WS_KEY[s])} (${MOD} ${i + 2})`}>
<Icon name={WS_ICON[s]} /><span className="grow">{t(WS_KEY[s])}</span> <Icon name={WS_ICON[s]} /><span className="grow">{t(WS_KEY[s])}</span>
{s === 'accounts' && <span className="count">{d.accounts.length}</span>} {s === 'accounts' && <span className="count">{d.accounts.length}</span>}
{s === 'ignored' && ignoredCount > 0 && <span className="count">{ignoredCount}</span>}
</button> </button>
))} ))}
</div> </div>
@ -202,18 +165,17 @@ export function App({ onTheme }: { onTheme: () => void }) {
<span className="spacer" /> <span className="spacer" />
{FIXTURES && <span className="dev-pill" title={t('dev.fixturesHint')}>{t('dev.fixtures')}</span>} {FIXTURES && <span className="dev-pill" title={t('dev.fixturesHint')}>{t('dev.fixtures')}</span>}
<span className="stamp"><Icon name="clock" />{lastRead ? t('top.storesRead', { when: ago(lastRead) }) : t('top.storesNotRead')}</span> <span className="stamp"><Icon name="clock" />{lastRead ? t('top.storesRead', { when: ago(lastRead) }) : t('top.storesNotRead')}</span>
<button className="btn btn-sm" onClick={() => d.refreshPortfolio(true)} disabled={!!d.portfolioBusy || !visible.length} title={t('action.readStoresHint')}> <button className="btn btn-sm" onClick={() => d.refreshPortfolio(true)} disabled={!!d.portfolioBusy || !d.projects.length} title={t('action.readStoresHint')}>
<Icon name="refresh" className={d.portfolioBusy === 'live' ? 'spin' : undefined} />{d.portfolioBusy === 'live' ? t('action.reading') : t('action.readStores')} <Icon name="refresh" className={d.portfolioBusy === 'live' ? 'spin' : undefined} />{d.portfolioBusy === 'live' ? t('action.reading') : t('action.readStores')}
</button> </button>
</header> </header>
<main className="content" id="content" tabIndex={-1}> <main className="content" id="content" tabIndex={-1}>
{route.screen === 'portfolio' && <Portfolio />} {route.screen === 'portfolio' && <Portfolio />}
{route.screen === 'app' && app && <AppView key={app.key} app={app} tab={tabs.includes(route.tab) ? route.tab : 'releases'} />} {route.screen === 'app' && app && <AppView key={app.id} project={app} tab={route.tab} />}
{route.screen === 'apps' && <AppFolders />} {route.screen === 'apps' && <AppFolders />}
{route.screen === 'accounts' && <Accounts focus={route.section} />} {route.screen === 'accounts' && <Accounts />}
{route.screen === 'ignored' && <Ignored />}
{route.screen === 'dependencies' && <Dependencies />} {route.screen === 'dependencies' && <Dependencies />}
{route.screen === 'settings' && <Settings onTheme={onTheme} section={route.section} />} {route.screen === 'settings' && <Settings onTheme={onTheme} />}
</main> </main>
</div> </div>
</div> </div>

View file

@ -3,11 +3,10 @@
// release builds, so that branch and the fixture module are dropped from them (tests/webview.test.ts checks dist/). // release builds, so that branch and the fixture module are dropped from them (tests/webview.test.ts checks dist/).
import { invoke as tauriInvoke } from '@tauri-apps/api/core'; import { invoke as tauriInvoke } from '@tauri-apps/api/core';
import { listen as tauriListen, type UnlistenFn } from '@tauri-apps/api/event'; import { listen as tauriListen, type UnlistenFn } from '@tauri-apps/api/event';
import type { AccountCheck, AppsListResult, DraftsResult, IconResult, ListingsResult, MethodDescriptor, PortfolioResult, ProgressParams, ToolResult } from '../../../cli/lib/desktop-protocol'; import type { DraftsResult, IconResult, ListingsResult, MethodDescriptor, PortfolioResult, ProgressParams, ToolResult } from '../../../cli/lib/desktop-protocol';
import type { Overrides } from './lib/identity';
export type { export type {
AccountCheck, AppIdentity, AppsListResult, AppStatus, CatalogParity, DraftsResult, StoreApp, IconResult, ListingField, ListingLocale, ListingsResult, MethodDescriptor, PortfolioResult, AppIdentity, AppStatus, CatalogParity, DraftsResult, IconResult, ListingField, ListingLocale, ListingsResult, MethodDescriptor, PortfolioResult,
ProgressParams, ProjectSummary, ReleasePhase, ReleaseTrain, ReplyDraft, StoreRelease, ToolResult, ProgressParams, ProjectSummary, ReleasePhase, ReleaseTrain, ReplyDraft, StoreRelease, ToolResult,
} from '../../../cli/lib/desktop-protocol'; } from '../../../cli/lib/desktop-protocol';
@ -18,21 +17,7 @@ export interface SidecarStatus { running: boolean; version: string; protocol: st
/** An app folder (one storebound.config.ts = one app on iOS and / or Android) and the accounts it uses. */ /** An app folder (one storebound.config.ts = one app on iOS and / or Android) and the accounts it uses. */
export interface Project { id: string; path: string; name: string; playAccount: string | null; appleAccount: string | null; added: string } export interface Project { id: string; path: string; name: string; playAccount: string | null; appleAccount: string | null; added: string }
export type AccountKind = 'play' | 'apple'; export type AccountKind = 'play' | 'apple';
export interface Account { id: string; label: string; kind: AccountKind; created: string; studio?: string | null } export interface Account { id: string; label: string; kind: AccountKind; created: string }
export const STUDIO_COLORS = ['indigo', 'violet', 'rose', 'amber', 'emerald', 'teal', 'sky', 'slate'] as const;
export type StudioColor = (typeof STUDIO_COLORS)[number];
/** A user-named group of store accounts (and so of apps). */
export interface Studio { id: string; name: string; color: StudioColor; logo: string | null; created: string }
export interface Settings {
refresh: { autoMinutes: 0 | 15 | 30 | 60 | 180 | 720; onLaunch: boolean; parallel: number; icons: boolean };
cache: { keepDays: 0 | 7 | 30 | 90 | 365 };
notify: { reviewState: boolean; lowReviews: boolean; crash: boolean };
channel: 'stable' | 'beta';
}
export const DEFAULT_SETTINGS: Settings = { refresh: { autoMinutes: 0, onLaunch: false, parallel: 4, icons: true }, cache: { keepDays: 30 }, notify: { reviewState: true, lowReviews: true, crash: true }, channel: 'stable' };
export interface Workspace { studios: Studio[]; overrides: Overrides; settings: Settings }
export interface AccountApps { account: string; entry: CacheEntry<AppsListResult> | null }
export interface CacheInfo { rows: number; bytes: number; oldest: string | null; file_bytes: number }
export interface WriteOutcome { confirmed: boolean; stage: 'dry-run' | 'dialog' | 'done'; dryRun: ToolResult; result?: ToolResult } export interface WriteOutcome { confirmed: boolean; stage: 'dry-run' | 'dialog' | 'done'; dryRun: ToolResult; result?: ToolResult }
export interface CacheEntry<T = unknown> { value: T; at: string } export interface CacheEntry<T = unknown> { value: T; at: string }
export interface DownloadInfo { tool: 'ffmpeg' | 'chrome'; available: boolean; version: string | null; size: number | null; license: string; licenseUrl: string; source: string; installed: boolean; folder: string } export interface DownloadInfo { tool: 'ffmpeg' | 'chrome'; available: boolean; version: string | null; size: number | null; license: string; licenseUrl: string; source: string; installed: boolean; folder: string }
@ -85,28 +70,10 @@ export const api = {
removeProject: (id: string) => invoke<void>('project_remove', { id }), removeProject: (id: string) => invoke<void>('project_remove', { id }),
setProjectAccounts: (id: string, play: string | null, apple: string | null) => invoke<Project>('project_set_accounts', { id, play, apple }), setProjectAccounts: (id: string, play: string | null, apple: string | null) => invoke<Project>('project_set_accounts', { id, play, apple }),
accounts: () => invoke<Account[]>('accounts_list'), accounts: () => invoke<Account[]>('accounts_list'),
addPlayAccount: (label: string, studio: string | null = null) => invoke<Account | null>('account_add_play', { label, studio }), addPlayAccount: (label: string) => invoke<Account | null>('account_add_play', { label }),
addAppleAccount: (label: string, keyId: string, issuerId: string, studio: string | null = null) => invoke<Account | null>('account_add_apple', { label, keyId, issuerId, studio }), addAppleAccount: (label: string, keyId: string, issuerId: string) => invoke<Account | null>('account_add_apple', { label, keyId, issuerId }),
removeAccount: (id: string) => invoke<void>('account_remove', { id }), removeAccount: (id: string) => invoke<void>('account_remove', { id }),
updateAccount: (id: string, label: string, studio: string | null) => invoke<Account>('account_update', { id, label, studio }), portfolio: (live = false, job?: string) => invoke<PortfolioResult>('portfolio_status', { live, job: job ?? null }),
/** Does the key work, can it see apps (live, not cached). */
checkAccount: (id: string, job?: string) => invoke<AccountCheck>('account_check', { id, job: job ?? null }),
/** Reads the apps an account can see from its store and keeps the list. */
refreshStoreApps: (id: string, job?: string) => invoke<CacheEntry<AppsListResult>>('store_apps_refresh', { id, job: job ?? null }),
storeAppsCached: () => invoke<AccountApps[]>('store_apps_cached'),
workspace: () => invoke<Workspace>('workspace_get'),
saveStudio: (id: string | null, name: string, color: StudioColor) => invoke<Studio>('studio_save', { id, name, color }),
removeStudio: (id: string) => invoke<void>('studio_remove', { id }),
studioLogo: (id: string, clear = false) => invoke<Studio | null>('studio_logo', { id, clear }),
setOverrides: (overrides: Overrides) => invoke<Overrides>('overrides_set', { overrides }),
setSettings: (settings: Settings) => invoke<Settings>('settings_set', { settings }),
cacheInfo: () => invoke<CacheInfo>('cache_info'),
revealData: () => invoke<void>('data_reveal'),
notify: (title: string, body: string) => invoke<void>('notify', { title, body }),
/** Native confirmation first; true when everything was forgotten. */
reset: () => invoke<boolean>('app_reset'),
/** Offline (folders) or live; live also reads the given store-only apps (store targets). */
portfolio: (live = false, job?: string, stores: string[] = []) => invoke<PortfolioResult>('portfolio_status', { live, stores, job: job ?? null }),
openExternal: (url: string) => invoke<void>('open_external', { url }), openExternal: (url: string) => invoke<void>('open_external', { url }),
toolsInfo: () => invoke<DownloadInfo[]>('tools_info'), toolsInfo: () => invoke<DownloadInfo[]>('tools_info'),
installTool: (tool: 'ffmpeg' | 'chrome', job: string) => invoke<string>('tools_install', { tool, job }), installTool: (tool: 'ffmpeg' | 'chrome', job: string) => invoke<string>('tools_install', { tool, job }),

View file

@ -3,9 +3,7 @@
// screenshotted without store accounts, in a browser or in `tauri dev`. Nothing here is real store data; the window // screenshotted without store accounts, in a browser or in `tauri dev`. Nothing here is real store data; the window
// shows a "DEV FIXTURES" badge. src/api.ts only imports this module behind import.meta.env.DEV, so release builds do // shows a "DEV FIXTURES" badge. src/api.ts only imports this module behind import.meta.env.DEV, so release builds do
// not contain it (tests/webview.test.ts checks the built files for FIXTURE_MARKER). // not contain it (tests/webview.test.ts checks the built files for FIXTURE_MARKER).
import { type Account, type AccountCheck, type AppsListResult, type AppStatus, type CacheEntry, DEFAULT_SETTINGS, type DownloadEvent, type DraftsResult, type ListingField, type ListingsResult, import type { Account, AppStatus, CacheEntry, DownloadEvent, DraftsResult, ListingField, ListingsResult, PortfolioResult, Project, ProjectSummary, StoreRelease, ToolResult } from '../api';
type PortfolioResult, type Project, type ProjectSummary, type Settings, type StoreApp, type StoreRelease, type Studio, type ToolResult } from '../api';
import { buildApps, type Overrides } from '../lib/identity';
import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult } from '../lib/model'; import type { CatalogDiff, HealthSnapshot, MetricRow, Review, TestFlightStatus, ValidateResult } from '../lib/model';
export const FIXTURE_MARKER = 'storebound-dev-fixtures'; export const FIXTURE_MARKER = 'storebound-dev-fixtures';
@ -34,88 +32,16 @@ const ICONS: Record<string, string> = {
'p-tidy': svg(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><defs><linearGradient id="g" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#2fd18b"/><stop offset="1" stop-color="#0f9d74"/></linearGradient></defs><rect width="64" height="64" fill="url(#g)"/><rect x="14" y="13" width="36" height="40" rx="7" fill="#fff"/><path d="M20 25l3 3 6-6M20 37l3 3 6-6" stroke="#0f9d74" stroke-width="3" fill="none" stroke-linecap="round" stroke-linejoin="round"/><path d="M33 26h11M33 38h11" stroke="#b6e8d4" stroke-width="3" stroke-linecap="round"/></svg>`), 'p-tidy': svg(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><defs><linearGradient id="g" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#2fd18b"/><stop offset="1" stop-color="#0f9d74"/></linearGradient></defs><rect width="64" height="64" fill="url(#g)"/><rect x="14" y="13" width="36" height="40" rx="7" fill="#fff"/><path d="M20 25l3 3 6-6M20 37l3 3 6-6" stroke="#0f9d74" stroke-width="3" fill="none" stroke-linecap="round" stroke-linejoin="round"/><path d="M33 26h11M33 38h11" stroke="#b6e8d4" stroke-width="3" stroke-linecap="round"/></svg>`),
}; };
// ---- workspace: 3 studios, 2 Play service accounts + 3 App Store Connect teams, 2 app folders, store-only apps ---- // ---- workspace ----
// Placeholder names only (example.com style): no real studio, person, team or id.
const P1 = '0a1b2c3d4e5f6071', P2 = '1b2c3d4e5f607182', A1 = '2c3d4e5f60718293', A2 = '3d4e5f6071829304', A3 = '4e5f607182930415';
const S1 = 's-example', S2 = 's-sample', S3 = 's-demo';
let studios: Studio[] = [
{ id: S1, name: 'Example Games', color: 'indigo', logo: null, created: iso(60 * 24 * 30) },
{ id: S2, name: 'Sample Labs', color: 'emerald', logo: null, created: iso(60 * 24 * 20) },
{ id: S3, name: 'Demo Indie', color: 'amber', logo: null, created: iso(60 * 24 * 9) },
];
let projects: Project[] = [ let projects: Project[] = [
{ id: 'p-prism', path: `${HOME}/apps/prism-puddle`, name: 'Prism Puddle', playAccount: P1, appleAccount: A1, added: iso(60 * 24 * 12) }, { id: 'p-prism', path: `${HOME}/apps/prism-puddle`, name: 'Prism Puddle', playAccount: 'a-play', appleAccount: 'a-apple', added: iso(60 * 24 * 12) },
{ id: 'p-tidy', path: `${HOME}/apps/tidy-lists`, name: 'Tidy Lists', playAccount: P1, appleAccount: A2, added: iso(60 * 24 * 5) }, { id: 'p-tidy', path: `${HOME}/apps/tidy-lists`, name: 'Tidy Lists', playAccount: 'a-play', appleAccount: 'a-apple', added: iso(60 * 24 * 5) },
]; ];
let accounts: Account[] = [ let accounts: Account[] = [
{ id: P1, label: 'Example Games · Play', kind: 'play', created: iso(60 * 24 * 30), studio: S1 }, { id: 'a-play', label: 'Example Studio · Play', kind: 'play', created: iso(60 * 24 * 12) },
{ id: A1, label: 'Example Games · App Store (company)', kind: 'apple', created: iso(60 * 24 * 30), studio: S1 }, { id: 'a-apple', label: 'Example Studio · App Store', kind: 'apple', created: iso(60 * 24 * 12) },
{ id: P2, label: 'Sample Labs · Play', kind: 'play', created: iso(60 * 24 * 20), studio: S2 },
{ id: A2, label: 'Sample Labs · App Store', kind: 'apple', created: iso(60 * 24 * 20), studio: S2 },
{ id: A3, label: 'Demo Indie · App Store (individual)', kind: 'apple', created: iso(60 * 24 * 9), studio: S3 },
]; ];
if (import.meta.env.VITE_FIXTURES === 'empty') { projects = []; accounts = []; studios = []; } if (import.meta.env.VITE_FIXTURES === 'empty') { projects = []; accounts = []; }
/** Small drawn icons for the store apps (fixture art). */
const glyph = (a: string, b: string, inner: string) => `data:image/svg+xml;base64,${btoa(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="${a}"/><stop offset="1" stop-color="${b}"/></linearGradient></defs><rect width="64" height="64" fill="url(#g)"/>${inner}</svg>`)}`;
const G = {
orbit: glyph('#0ea5e9', '#6366f1', '<circle cx="32" cy="32" r="9" fill="#fff"/><ellipse cx="32" cy="32" rx="22" ry="9" fill="none" stroke="#fff" stroke-width="3" transform="rotate(-25 32 32)"/>'),
block: glyph('#22c55e', '#15803d', '<rect x="14" y="30" width="16" height="16" rx="3" fill="#fff"/><rect x="34" y="30" width="16" height="16" rx="3" fill="#bbf7d0"/><rect x="24" y="12" width="16" height="16" rx="3" fill="#fff"/>'),
lantern: glyph('#f59e0b', '#b45309', '<path d="M24 18h16l4 8v16l-4 6H24l-4-6V26z" fill="#fff"/><text x="32" y="41" font-family="Georgia" font-size="16" font-weight="700" text-anchor="middle" fill="#b45309">W</text>'),
tycoon: glyph('#a855f7', '#6d28d9', '<circle cx="32" cy="32" r="16" fill="#fde68a"/><text x="32" y="39" font-family="Arial" font-size="18" font-weight="800" text-anchor="middle" fill="#92400e">$</text>'),
racer: glyph('#ef4444', '#991b1b', '<path d="M14 38l6-12h24l6 12v6H14z" fill="#fff"/><circle cx="22" cy="44" r="4" fill="#111"/><circle cx="42" cy="44" r="4" fill="#111"/>'),
habit: glyph('#14b8a6', '#0f766e', '<ellipse cx="32" cy="36" rx="13" ry="16" fill="#fff"/><path d="M24 34l5 5 11-11" stroke="#0f766e" stroke-width="4" fill="none" stroke-linecap="round"/>'),
focus: glyph('#f43f5e', '#be123c', '<circle cx="32" cy="34" r="15" fill="#fff"/><path d="M32 34V24M32 34l7 4" stroke="#be123c" stroke-width="3.5" stroke-linecap="round"/>'),
sketch: glyph('#fb923c', '#ea580c', '<path d="M32 13l5 11 12 1-9 8 3 12-11-7-11 7 3-12-9-8 12-1z" fill="#fff"/>'),
night: glyph('#1e293b', '#4338ca', '<path d="M38 16a16 16 0 1 0 10 28 13 13 0 0 1-10-28z" fill="#fde68a"/><rect x="18" y="40" width="20" height="3" rx="1.5" fill="#c7d2fe"/>'),
mood: glyph('#ec4899', '#8b5cf6', '<rect x="14" y="14" width="10" height="10" rx="3" fill="#fff"/><rect x="27" y="14" width="10" height="10" rx="3" fill="#fbcfe8"/><rect x="40" y="14" width="10" height="10" rx="3" fill="#fff"/><rect x="14" y="27" width="10" height="10" rx="3" fill="#ddd6fe"/><rect x="27" y="27" width="10" height="10" rx="3" fill="#fff"/><rect x="40" y="27" width="10" height="10" rx="3" fill="#fbcfe8"/><rect x="14" y="40" width="10" height="10" rx="3" fill="#fff"/><rect x="27" y="40" width="10" height="10" rx="3" fill="#ddd6fe"/><rect x="40" y="40" width="10" height="10" rx="3" fill="#fff"/>'),
};
const ios = (id: string, bundleId: string, name: string, icon: string | null, latest: [string, string] | null): StoreApp =>
({ store: 'ios', id, bundleId, name, platforms: ['IOS'], sku: null, primaryLocale: 'en-US', latest: latest ? { version: latest[0], state: latest[1], platform: 'IOS' } : null, icon });
const droid = (pkg: string, name: string, icon: string | null): StoreApp => ({ store: 'android', id: pkg, bundleId: pkg, name, platforms: ['ANDROID'], sku: null, primaryLocale: null, latest: null, icon });
const STORE_APPS: Record<string, StoreApp[]> = {
// one Play service account invited to two developer accounts: it sees Example Games' and Sample Labs' Play apps
[P1]: [
droid('com.example.prismpuddle', 'Prism Puddle', null), droid('com.example.tidylists', 'Tidy Lists', null), droid('com.example.orbithop', 'Orbit Hop', G.orbit),
droid('com.example.blockgarden', 'Block Garden', G.block), droid('com.example.lantern.words', 'Word Lantern', G.lantern), droid('com.example.pockettycoon', 'Pocket Tycoon', G.tycoon),
droid('com.example.nightnotes.free', 'Nightnotes Free', G.night), droid('com.example.moodgrid', 'Mood Grid', G.mood),
],
[A1]: [
ios('6400000001', 'com.example.prismpuddle', 'Prism Puddle', null, ['2.4.0', 'WAITING_FOR_REVIEW']), ios('6400000011', 'com.example.orbithop', 'Orbit Hop', G.orbit, ['3.1.0', 'READY_FOR_SALE']),
ios('6400000012', 'com.example.blockgarden.ios', 'Block Garden', G.block, ['1.2.0', 'IN_REVIEW']), ios('6400000013', 'com.example.wordlantern', 'Word Lantern', G.lantern, ['2.0.1', 'READY_FOR_SALE']),
ios('6400000014', 'com.example.oldracer', 'Old Racer', G.racer, ['1.9.3', 'REMOVED_FROM_SALE']),
],
[A2]: [
ios('6400000002', 'com.example.tidylists', 'Tidy Lists', null, ['1.5.0', 'PREPARE_FOR_SUBMISSION']), ios('6400000021', 'com.example.habithatch', 'Habit Hatch', G.habit, ['1.0.4', 'READY_FOR_SALE']),
ios('6400000022', 'com.example.focustimer', 'Focus Timer Mini', G.focus, ['2.2.0', 'READY_FOR_SALE']),
],
[A3]: [ios('6400000031', 'com.example.starsketch', 'Star Sketch', G.sketch, ['1.1.0', 'READY_FOR_SALE']), ios('6400000032', 'com.example.nightnotes', 'Night Notes', G.night, ['4.0.0', 'READY_FOR_SALE'])],
};
// Sample Labs' Play service account was never invited: no app list, and its check says what to do
const IMPORTED: Record<string, number> = { [P1]: 60 * 3, [A1]: 60 * 3, [A2]: 60 * 3, [A3]: 60 * 26 };
let overrides: Overrides = {
pairs: [{ ios: `ios:${A3}:6400000032`, android: `android:${P1}:com.example.nightnotes.free` }],
unpairs: [], links: [],
appStudio: [{ key: `android:${P1}:com.example.moodgrid`, studio: S3 }],
ignored: [`app:ios:${A1}:6400000014`],
};
if (import.meta.env.VITE_FIXTURES === 'empty') overrides = { pairs: [], unpairs: [], links: [], appStudio: [], ignored: [] };
let settings: Settings = { ...DEFAULT_SETTINGS, refresh: { ...DEFAULT_SETTINGS.refresh, autoMinutes: 60 } };
const PLAY_INVITE = (who: string) => `Play Console > Users and permissions > Invite new users: add ${who}. Account permissions: "View app information and download bulk reports (read-only)"; per app, as needed: "Manage store presence", "Manage testing tracks", "Release to production, exclude devices and use Play App Signing" (rollouts), "Reply to reviews", "Manage orders and subscriptions". One service account can be invited to several developer accounts.`;
const CHECKS: Record<string, AccountCheck> = {
[P1]: { store: 'android', status: 'ok', principal: 'storebound@example-games-123.iam.gserviceaccount.com', apps: 8, message: 'The service account can see 8 apps.', fix: null, docs: null },
[P2]: { store: 'android', status: 'permission', principal: 'storebound@sample-labs-456.iam.gserviceaccount.com', apps: 0, message: 'The key works, but no developer account has invited this service account (it sees no apps).', fix: PLAY_INVITE('storebound@sample-labs-456.iam.gserviceaccount.com'), docs: 'https://play.google.com/console/developers/users-and-permissions' },
[A1]: { store: 'ios', status: 'ok', principal: null, apps: 5, message: 'The key works and can read the team\'s apps.', fix: null, docs: null },
[A2]: { store: 'ios', status: 'ok', principal: null, apps: 3, message: 'The key works and can read the team\'s apps.', fix: null, docs: null },
[A3]: { store: 'ios', status: 'ok', principal: null, apps: 2, message: 'The key works and can read the team\'s apps.', fix: null, docs: null },
};
const appsEntry = (id: string): CacheEntry<AppsListResult> | null => (STORE_APPS[id] && IMPORTED[id] !== undefined && import.meta.env.VITE_FIXTURES !== 'cold'
? { value: { store: accounts.find(a => a.id === id)?.kind === 'play' ? 'android' : 'ios', apps: STORE_APPS[id]!, warnings: [], at: iso(IMPORTED[id]!) }, at: iso(IMPORTED[id]!) } : null);
/** Store-only apps as the window pairs them (so the cached live read covers them too). */
const storeTargets = () => buildApps({
projects, accounts, overrides, summaryOf: p => SUMMARY[p.id],
storeApps: accounts.map(a => ({ account: a.id, apps: appsEntry(a.id)?.value.apps ?? [] })),
}).filter(a => !a.project && !a.ignored);
const SUMMARY: Record<string, ProjectSummary> = { const SUMMARY: Record<string, ProjectSummary> = {
'p-prism': { 'p-prism': {
@ -172,39 +98,7 @@ function status(id: string, live: boolean): AppStatus {
storeErrors: {}, errors: [], storeErrors: {}, errors: [],
}; };
} }
/** Store-only app releases (fixture), by bundle id / package name. */ const portfolio = (live: boolean): PortfolioResult => ({ apps: projects.map(p => status(p.id, live)), at: live ? iso(14) : iso(0) });
const STORE_RELEASES: Record<string, StoreRelease[]> = {
'com.example.orbithop': [rel('ios', '3.1.0', 'live', { build: '88', state: 'READY_FOR_SALE', date: iso(60 * 24 * 6) }), rel('android', '3.1.0', 'rollout', { build: '310', state: 'inProgress', fraction: 0.5 })],
'com.example.blockgarden.ios': [rel('ios', '1.2.0', 'review', { build: '17', state: 'IN_REVIEW', date: iso(60 * 5) }), rel('ios', '1.1.2', 'live', { build: '15', state: 'READY_FOR_SALE', date: iso(60 * 24 * 40) })],
'com.example.blockgarden': [rel('android', '1.2.0', 'live', { build: '120', state: 'completed' })],
'com.example.wordlantern': [rel('ios', '2.0.1', 'live', { build: '41', state: 'READY_FOR_SALE', date: iso(60 * 24 * 18) })],
'com.example.lantern.words': [rel('android', '2.0.1', 'halted', { build: '201', state: 'halted', fraction: 0.1 })],
'com.example.pockettycoon': [rel('android', '5.4.0', 'live', { build: '540', state: 'completed' })],
'com.example.habithatch': [rel('ios', '1.0.4', 'live', { build: '9', state: 'READY_FOR_SALE', date: iso(60 * 24 * 60) })],
'com.example.focustimer': [rel('ios', '2.2.0', 'live', { build: '30', state: 'READY_FOR_SALE', date: iso(60 * 24 * 3) }), rel('ios', '2.3.0', 'rejected', { build: '31', state: 'REJECTED', date: iso(60 * 10) })],
'com.example.starsketch': [rel('ios', '1.1.0', 'live', { build: '12', state: 'READY_FOR_SALE', date: iso(60 * 24 * 12) })],
'com.example.nightnotes': [rel('ios', '4.0.0', 'live', { build: '77', state: 'READY_FOR_SALE', date: iso(60 * 24 * 2) })],
'com.example.nightnotes.free': [rel('android', '4.0.0', 'rollout', { build: '400', state: 'inProgress', fraction: 0.2 })],
'com.example.moodgrid': [rel('android', '0.9.0', 'testing', { build: '9', state: 'completed', track: 'beta' })],
};
function storeStatus(target: string, live: boolean): AppStatus {
const ios = /ios:[^:]+:(\d+):([^;]+)/.exec(target), android = /android:[^:]+:([^;]+)/.exec(target);
const bundle = ios?.[2] ?? null, pkg = android?.[1] ?? null;
const all = [...(bundle ? STORE_RELEASES[bundle] ?? [] : []), ...(pkg ? STORE_RELEASES[pkg] ?? [] : [])];
const name = Object.values(STORE_APPS).flat().find(a => a.bundleId === (bundle ?? pkg))?.name ?? bundle ?? pkg ?? '?';
const versions = [...new Set(all.map(r => r.version!))].sort().reverse();
const live1 = versions.find(v => all.some(r => r.version === v && ['live', 'rollout', 'halted'].includes(r.phase))) ?? null;
const next1 = versions.find(v => !live1 || v > live1) ?? null;
const s: ProjectSummary = { dir: '', config: '', name, languages: ['en'], play: pkg ? { packageName: pkg } : null, apple: bundle ? { bundleId: bundle, appId: ios![1]! } : null,
platforms: [...(bundle ? ['ios' as const] : []), ...(pkg ? ['android' as const] : [])], products: 0, productIds: [], subscriptions: 0, subscriptionIds: [], catalog: { ios: [], android: [] }, shots: false, testflightGroups: 0 };
return {
project: target, ok: true, virtual: true, summary: s, check: { ok: true, problems: [], warnings: [] },
app: { id: target, name, platforms: { ios: bundle ? { bundleId: bundle, ascAppId: ios![1]! } : null, android: pkg ? { packageName: pkg } : null } },
release: live ? { source: 'live', current: live1 ? train(all, live1) : null, next: next1 && next1 !== live1 ? train(all, next1) : null, all } : { source: 'none', current: null, next: null },
catalog: { checked: 'config', products: 0, subscriptions: 0, onlyIos: [], onlyAndroid: [], missingIos: [], missingAndroid: [], ok: true }, storeErrors: {}, errors: [],
};
}
const portfolio = (live: boolean, stores: string[] = []): PortfolioResult => ({ apps: [...projects.map(p => status(p.id, live)), ...(live ? stores.map(s => storeStatus(s, true)) : [])], at: live ? iso(14) : iso(0) });
// ---- per-app store reads ---- // ---- per-app store reads ----
const series = (n: number, base: number, drift: number, seed: number): number[] => const series = (n: number, base: number, drift: number, seed: number): number[] =>
@ -388,23 +282,7 @@ let chromeInstalled = false;
const ok = (method: string, data: unknown): ToolResult => ({ method, ok: true, exitCode: 0, dryRun: false, command: `storebound ${method.replace('.', ' ')} --json`, output: '', data }); const ok = (method: string, data: unknown): ToolResult => ({ method, ok: true, exitCode: 0, dryRun: false, command: `storebound ${method.replace('.', ' ')} --json`, output: '', data });
const STORE_REVIEWS: Review[] = [
R('apple', 's-a1', 5, 'Lovely', 'Simple and quick, does exactly what it says.', 'USA', 1),
R('play', 's-p1', 1, 'Stuck on loading', 'Since the last update it stays on the loading screen on my tablet.', 'en', 1),
R('apple', 's-a2', 4, 'Nice update', 'The new widgets are great. Please add a dark icon.', 'GBR', 3),
R('play', 's-p2', 2, 'Too many ads', 'An ad after every round is too much.', 'en', 5),
R('apple', 's-a3', 5, 'Harika', 'Her gün kullanıyorum, çok sade.', 'TUR', 7),
];
function read(method: string, id: string): ToolResult { function read(method: string, id: string): ToolResult {
if (id.startsWith('store:')) {
const play = /android:/.test(id);
switch (method) {
case 'health': return ok(method, play ? HEALTH['p-tidy'] : { date: day(0), apple: HEALTH['p-tidy']!.apple });
case 'reviews.list': return ok(method, STORE_REVIEWS.filter(r => (play || r.store === 'apple') && (/ios:/.test(id) || r.store === 'play')));
case 'apple.testflight_status': return ok(method, TF['p-tidy']);
default: return { method, ok: false, exitCode: 1, dryRun: false, command: `storebound ${method}`, output: `fixture: ${method} needs an app folder` };
}
}
switch (method) { switch (method) {
case 'project.icon': return ok(method, { path: SUMMARY[id]?.icon ?? null, dataUrl: ICONS[id] ?? null }); case 'project.icon': return ok(method, { path: SUMMARY[id]?.icon ?? null, dataUrl: ICONS[id] ?? null });
case 'project.listings': return ok(method, LISTINGS[id]); case 'project.listings': return ok(method, LISTINGS[id]);
@ -438,48 +316,21 @@ async function answer(cmd: string, a: Record<string, unknown>): Promise<unknown>
case 'sidecar_status': return { running: true, version: '0.5.0', protocol: 'storebound-desktop/1', methods: Array.from({ length: 64 }, (_, i) => ({ method: `m${i}` })), tools: { tools: TOOLS.map(x => (x.id === 'chrome' && chromeInstalled ? { ...x, found: true, name: 'Chrome for Testing', version: '141.0.7390.54', source: 'app' } : x)) } }; case 'sidecar_status': return { running: true, version: '0.5.0', protocol: 'storebound-desktop/1', methods: Array.from({ length: 64 }, (_, i) => ({ method: `m${i}` })), tools: { tools: TOOLS.map(x => (x.id === 'chrome' && chromeInstalled ? { ...x, found: true, name: 'Chrome for Testing', version: '141.0.7390.54', source: 'app' } : x)) } };
case 'projects_list': return projects; case 'projects_list': return projects;
case 'accounts_list': return accounts; case 'accounts_list': return accounts;
case 'workspace_get': return { studios, overrides, settings };
case 'store_apps_cached': return accounts.map(x => ({ account: x.id, entry: appsEntry(x.id) }));
case 'store_apps_refresh': {
const id = a.id as string;
await progressLines(job, ['[apps] reading the account\'s apps', '[apps] icons']);
if (job && cancelled.has(job)) throw { code: -32800, message: 'Request cancelled' };
if (!STORE_APPS[id]) throw { code: -32603, message: `Google Play: ${CHECKS[id]?.message ?? 'no apps'}` };
IMPORTED[id] = 0;
return appsEntry(id);
}
case 'account_check': await sleep(350); return CHECKS[a.id as string];
case 'studio_save': {
const s = a.id ? studios.find(x => x.id === a.id)! : { id: `s-${studios.length + 1}`, logo: null, created: iso(0) } as Studio;
Object.assign(s, { name: a.name, color: a.color });
if (!a.id) studios = [...studios, s];
return s;
}
case 'studio_remove': studios = studios.filter(s => s.id !== a.id); accounts = accounts.map(x => (x.studio === a.id ? { ...x, studio: null } : x)); return null;
case 'studio_logo': return null;
case 'account_update': { const x = accounts.find(y => y.id === a.id)!; x.label = a.label as string; x.studio = (a.studio as string | null) ?? null; return x; }
case 'overrides_set': overrides = a.overrides as Overrides; return overrides;
case 'settings_set': settings = a.settings as Settings; return settings;
case 'cache_info': return { rows: 214, bytes: 3_412_000, oldest: iso(60 * 24 * 26), file_bytes: 4_718_592 };
case 'data_reveal': case 'notify': return null;
case 'app_reset': return false;
case 'portfolio_status': { case 'portfolio_status': {
const stores = (a.stores as string[] | undefined) ?? [];
if (a.live) { if (a.live) {
const total = projects.length + stores.length; for (let n = 1; n <= projects.length; n++) {
for (let n = 1; n <= total; n++) { await sleep(700);
await sleep(total > 6 ? 180 : 700);
if (job && cancelled.has(job)) throw { code: -32800, message: 'Request cancelled' }; if (job && cancelled.has(job)) throw { code: -32800, message: 'Request cancelled' };
emit('sidecar-progress', { params: { requestId: 0, n, total, project: projects[n - 1]?.path ?? stores[n - 1 - projects.length] }, job }); emit('sidecar-progress', { params: { requestId: 0, n, total: projects.length, project: projects[n - 1]!.path }, job });
} }
return portfolio(true, stores); return portfolio(true);
} }
await sleep(120); await sleep(120);
return portfolio(false); return portfolio(false);
} }
case 'cache_get': { case 'cache_get': {
const method = a.method as string, id = a.projectId as string; const method = a.method as string, id = a.projectId as string;
if (id === '*' && method === 'portfolio.status') return projects.length ? { value: portfolio(true, storeTargets().map(x => x.target)), at: iso(14) } satisfies CacheEntry<PortfolioResult> : null; if (id === '*' && method === 'portfolio.status') return projects.length ? { value: portfolio(true), at: iso(14) } satisfies CacheEntry<PortfolioResult> : null;
if (method === 'project.icon') return ICONS[id] ? { value: read(method, id), at: iso(60) } : null; if (method === 'project.icon') return ICONS[id] ? { value: read(method, id), at: iso(60) } : null;
if (CACHED_AGO[method] !== undefined && import.meta.env.VITE_FIXTURES !== 'cold') return { value: read(method, id), at: iso(CACHED_AGO[method]!) }; if (CACHED_AGO[method] !== undefined && import.meta.env.VITE_FIXTURES !== 'cold') return { value: read(method, id), at: iso(CACHED_AGO[method]!) };
return null; return null;

View file

@ -8,7 +8,7 @@ export const en = {
'nav.appsLabel': 'Apps', 'nav.appsLabel': 'Apps',
'nav.workspace': 'Workspace', 'nav.workspace': 'Workspace',
'nav.apps': 'App folders', 'nav.apps': 'App folders',
'nav.accounts': 'Studios & accounts', 'nav.accounts': 'Accounts',
'nav.dependencies': 'Dependencies', 'nav.dependencies': 'Dependencies',
'nav.settings': 'Settings', 'nav.settings': 'Settings',
'nav.noApps': 'No apps yet', 'nav.noApps': 'No apps yet',
@ -557,221 +557,4 @@ export const en = {
'wz.back': 'Back', 'wz.back': 'Back',
'wz.next': 'Next', 'wz.next': 'Next',
'wz.finish': 'Finish', 'wz.finish': 'Finish',
'nav.ignored': 'Ignored',
'nav.studios': 'Studios',
'nav.studiosLabel': 'Studios',
'palette.studio': 'Studio',
'action.importApps': 'Import apps',
'action.importAppsHint': 'Read-only: every app each store account can see, from App Store Connect and Google Play',
'apps.storeOnly': 'Store only',
'apps.storeOnlyHint': 'On a store account, no app folder yet: store data only (read-only)',
'common.save': 'Save',
'studio.studio': 'Studio',
'studio.none': 'No studio',
'studio.noneSub': 'Accounts not in a studio yet',
'studio.new': 'New studio',
'studio.newSub': 'A studio groups store accounts, and with them their apps',
'studio.name': 'Name',
'studio.namePlaceholder': 'Example Games',
'studio.color': 'Colour',
'studio.add': 'Add a studio',
'studio.added': 'Studio {name} added',
'studio.edit': 'Edit',
'studio.logo': 'Logo',
'studio.logoClear': 'Remove logo',
'studio.remove': 'Remove',
'studio.removeHint': 'Removes the studio only: its accounts and apps stay, without a studio',
'studio.counts': '{count} accounts · {apps} apps · {store} store only',
'studio.noAccounts': 'No store account in this studio yet: add one below and pick this studio.',
'studio.allAssigned': 'Every account is in a studio.',
'color.indigo': 'Indigo',
'color.violet': 'Violet',
'color.rose': 'Rose',
'color.amber': 'Amber',
'color.emerald': 'Emerald',
'color.teal': 'Teal',
'color.sky': 'Sky',
'color.slate': 'Slate',
'accounts.leadStudios': 'Studios group your store accounts: Google Play service accounts and App Store Connect team keys. Keys stay in the system keychain; apps come in with Import apps.',
'accounts.emptyTextStudios': 'Add a studio, then its Google Play service account and App Store Connect keys. Import apps then lists every app those keys can see.',
'accounts.playSubMany': 'Service account JSON key. One service account can be invited to several Play developer accounts: it sees all their apps.',
'accounts.appleSubMany': 'One API key per team (company or individual): key id, issuer id and the .p8 file.',
'accounts.safetyStudios': 'Keys are read once from the file you pick, stored in the system keychain and never shown again. storebound gets one account\'s key in memory for one call. Studio names, labels and app lists stay on this computer.',
'acct.ok': 'Works',
'acct.noApps': 'No apps',
'acct.permission': 'Permission missing',
'acct.revoked': 'Key revoked',
'acct.apiDisabled': 'API off',
'acct.error': 'Not reachable',
'acct.notTested': 'Not tested',
'acct.kindPlay': 'Google Play service account',
'acct.kindApple': 'App Store Connect team key',
'acct.appsRead': '{count} apps, read {when}',
'acct.appsRead_one': '1 app, read {when}',
'acct.notImported': 'apps not imported yet',
'acct.folders': 'used by {count} folders',
'acct.folders_one': 'used by 1 folder',
'acct.test': 'Test',
'acct.testAll': 'Test all accounts',
'acct.import': 'Import apps',
'acct.edit': 'Rename or move to a studio',
'acct.editAria': 'Edit {label}',
'acct.ignore': 'Ignore this account',
'acct.ignoreHint': 'Ignore: leave this account\'s apps out of the portfolio and store reads',
'acct.unignore': 'Show this account again',
'acct.ignored': 'Ignored',
'acct.openFix': 'Open',
'ignored.lead': 'Apps and accounts left out of the portfolio, the sidebar and store reads. Nothing on the stores changes.',
'ignored.restoreAll': 'Restore all',
'ignored.restore': 'Restore',
'ignored.emptyTitle': 'Nothing is ignored',
'ignored.emptyText': 'Ignore an app from its page (or a whole account in Studios & accounts) to keep test apps and old titles out of the way.',
'ignored.apps': 'Apps',
'ignored.appsSub': '{count} ignored',
'ignored.accounts': 'Accounts',
'ignored.accountsSub': 'Every app of these accounts is left out',
'ignored.accountApps': '{count} apps',
'ignored.accountApps_one': '1 app',
'ignored.noApps': 'No ignored app.',
'ignored.noAccounts': 'No ignored account.',
'ignored.howTo': 'Pairing and single-store apps:',
'ignored.toPairing': 'Settings > App pairing',
'pair.folder': 'From its app folder',
'pair.manual': 'Paired by hand',
'pair.id': 'Paired: same bundle id and package name',
'pair.close': 'Paired: close ids',
'pair.name': 'Paired: same name',
'pair.single': 'One store only',
'app.moveStudio': 'Move to a studio',
'app.pairWith': 'Pair with',
'app.pairWithName': 'Pair {name} with',
'app.pick': 'Pick an app',
'app.unpair': 'Unpair',
'app.ignore': 'Ignore',
'app.ignoreHint': 'Leave this app out of the portfolio and store reads (Ignored lists it to restore)',
'app.studioHint': 'Open the studio',
'app.storeOnlyTitle': 'Store only.',
'app.storeOnlyText': 'This app is on your store accounts but has no app folder: releases, reviews, health and TestFlight are shown read-only. Link its folder, or start one, to manage listings, products and checks.',
'app.linkFolder': 'Link a folder',
'app.initHere': 'Start an app folder here',
'app.linked': '{name} is linked',
'app.linkFailed': 'Could not link the folder',
'portfolio.subStudios': '{count} apps · {stores} store listings · {studios} studios',
'portfolio.emptyAccounts': 'Add a studio and its accounts',
'portfolio.notImported': 'Apps of {count} accounts are not imported yet: Import apps lists everything those keys can see.',
'portfolio.notImported_one': 'Apps of 1 account are not imported yet: Import apps lists everything its key can see.',
'portfolio.toolbar': 'Filter and sort the apps',
'portfolio.search': 'Search apps, bundle ids, packages',
'portfolio.studioFilter': 'Studio',
'portfolio.allStudios': 'All studios',
'portfolio.sort': 'Sort',
'portfolio.sortAttention': 'Needs attention',
'portfolio.sortRecent': 'Recently updated',
'portfolio.sortName': 'Name',
'portfolio.group': 'Group by studio',
'portfolio.groupCount': '{count} apps',
'portfolio.noConfig': 'No config',
'portfolio.storeOnlyCheck': 'Store only',
'portfolio.noMatch': 'No app matches',
'portfolio.noMatchText': 'Clear the search or pick another studio.',
'portfolio.studiosN': '{count} studios',
'portfolio.studiosN_one': '1 studio',
'portfolio.folders': 'App folders',
'portfolio.foldersN': '{count} folders · {store} store only',
'portfolio.ignoredN': '{count} apps',
'portfolio.ignoredN_one': '1 app',
'kpi.appsSubStore': 'iOS {ios} · Android {android} · {store} store only',
'toast.importing': 'Importing apps',
'toast.importingDetail': 'Every app each account can see (read-only)',
'toast.importDone': '{count} apps on your accounts',
'toast.importDone_one': '1 app on your accounts',
'toast.importDoneDetail': 'from {count} accounts',
'toast.importDoneDetail_one': 'from 1 account',
'toast.importPartial': '{count} accounts could not be read',
'toast.importPartial_one': '1 account could not be read',
'toast.saveFailed': 'Not saved',
'notify.releaseTitle': '{name}: store state changed',
'notify.releaseBody': '{store} {version}: {phase}',
'notify.lowTitle': '{name}: {count} new low ratings',
'notify.lowTitle_one': '{name}: a new low rating',
'notify.crashTitle': '{name}: over the Play threshold',
'set.lead': 'Studios, accounts, store reads, the offline cache, language, theme, notifications and more. Everything stays on this computer.',
'set.sections': 'Settings sections',
'set.studios': 'Studios & accounts',
'set.studiosSub': 'Which accounts belong to which studio',
'set.studioLine': 'Play {play} · App Store {apple} · {apps} apps',
'set.noStudios': 'No studio yet. Studios group accounts and their apps in the portfolio and the sidebar.',
'set.manage': 'Manage',
'set.pairing': 'App pairing & ignore list',
'set.pairingSub': 'An iOS and an Android app become one card when their ids or names match; pair or split them by hand here',
'set.pairedHow': 'Pairing',
'set.noCandidates': 'Nothing to pair with',
'set.noStoreOnly': 'Every app has its folder: pairing comes from the configs.',
'set.ignoredLine': 'Ignored: {count} apps, {accounts} accounts.',
'set.openIgnored': 'Open the list',
'set.refresh': 'Store reads',
'set.refreshSub': 'Reads use each account\'s API quota: they run when you ask, or on the schedule here',
'set.autoRefresh': 'Read the stores automatically',
'set.autoHint': 'While the app is open. Off by default.',
'set.off': 'Off',
'set.min': '{n} min',
'set.hour': '{n} h',
'set.onLaunch': 'Read when the app starts',
'set.onLaunchHint': 'Imports the apps of every account, then reads every app\'s store status',
'set.icons': 'Store icons on import',
'set.iconsHint': 'One extra request per app; folders use their own icon',
'set.parallel': 'Apps read at the same time',
'set.parallelHint': 'Fewer is gentler on rate limits',
'set.cache': 'Offline cache',
'set.cacheSub': 'The last store reads, shown with their time when you are offline',
'set.cacheSize': 'On disk',
'set.cacheRows': '{count} saved reads',
'set.cacheRows_one': '1 saved read',
'set.cacheOldest': 'Oldest',
'set.keep': 'Keep saved reads',
'set.days': '{n} days',
'set.year': '1 year',
'set.always': 'Always',
'set.notifications': 'Notifications',
'set.notificationsSub': 'After a read, when something changed since the previous one',
'set.nReview': 'Review and release state changes',
'set.nReviewHint': 'In review, approved, rejected, live, halted',
'set.nLow': 'New 1 or 2 star reviews',
'set.nLowHint': 'When the Reviews tab reads new ones',
'set.nCrash': 'Crash or ANR rate over the threshold',
'set.nCrashHint': 'Google Play bad behavior thresholds',
'set.testNotify': 'Send a test notification',
'set.testTitle': 'storebound',
'set.testBody': 'Notifications work.',
'set.appCopy': 'app copy',
'set.depsText': 'Store work needs no local tool. Screenshots, previews and icons use ffmpeg and Chrome: one click on the Dependencies screen.',
'set.cli': 'CLI sidecar',
'set.protocol': 'Protocol',
'set.state': 'State',
'set.running': 'Running',
'set.writes': 'Writes',
'set.writesText': 'Dry run first, then your Apply in a system dialog. Submit, release and publish stay in the consoles.',
'set.privacy': 'Privacy',
'set.p1': 'No telemetry, no analytics, no crash reports: the app talks only to the stores, with your keys, when you ask.',
'set.p2': 'Store keys live in the system keychain; the app data folder holds names, settings and saved reads, never keys.',
'set.p3': 'Nothing is written into your app folders unless you confirm it in a system dialog.',
'set.p4': 'Tester emails stay masked; review drafts stay in each app folder\'s .storebound/ (gitignored).',
'set.reveal': 'Show the data folder',
'set.scQuit': 'Quit',
'set.updates': 'Updates',
'set.channel': 'Channel',
'set.stable': 'Stable',
'set.beta': 'Beta',
'set.updatesText': 'Signed updates from storebound.dev arrive with the first public desktop release; the channel is kept for then.',
'set.reset': 'Reset',
'set.resetText': 'Forgets {accounts} accounts (their keys are removed from the keychain), {studios} studios, {folders} app folders (the folders stay on disk), pairing, the ignore list, settings and saved reads. A system dialog asks first.',
'set.resetButton': 'Reset the app',
'set.resetDone': 'storebound desktop was reset',
'set.footer': '{n} apps known to this computer',
'studio.counts_one': '1 account · {apps} apps · {store} store only',
'portfolio.groupCount_one': '1 app',
'portfolio.groupAccounts': '{count} accounts',
'portfolio.groupAccounts_one': '1 account',
} as const; } as const;

View file

@ -10,7 +10,7 @@ export const tr: Record<keyof typeof en, string> = {
'nav.appsLabel': 'Uygulamalar', 'nav.appsLabel': 'Uygulamalar',
'nav.workspace': 'Çalışma alanı', 'nav.workspace': 'Çalışma alanı',
'nav.apps': 'Uygulama klasörleri', 'nav.apps': 'Uygulama klasörleri',
'nav.accounts': 'Stüdyolar ve hesaplar', 'nav.accounts': 'Hesaplar',
'nav.dependencies': 'Bağımlılıklar', 'nav.dependencies': 'Bağımlılıklar',
'nav.settings': 'Ayarlar', 'nav.settings': 'Ayarlar',
'nav.noApps': 'Henüz uygulama yok', 'nav.noApps': 'Henüz uygulama yok',
@ -559,221 +559,4 @@ export const tr: Record<keyof typeof en, string> = {
'wz.back': 'Geri', 'wz.back': 'Geri',
'wz.next': 'İleri', 'wz.next': 'İleri',
'wz.finish': 'Bitir', 'wz.finish': 'Bitir',
'nav.ignored': 'Yok sayılanlar',
'nav.studios': 'Stüdyolar',
'nav.studiosLabel': 'Stüdyolar',
'palette.studio': 'Stüdyo',
'action.importApps': 'Uygulamaları içe aktar',
'action.importAppsHint': 'Salt okunur: her mağaza hesabının gördüğü tüm uygulamalar, App Store Connect ve Google Play\'den',
'apps.storeOnly': 'Yalnızca mağaza',
'apps.storeOnlyHint': 'Bir mağaza hesabında, henüz uygulama klasörü yok: yalnızca mağaza verisi (salt okunur)',
'common.save': 'Kaydet',
'studio.studio': 'Stüdyo',
'studio.none': 'Stüdyosuz',
'studio.noneSub': 'Henüz bir stüdyoda olmayan hesaplar',
'studio.new': 'Yeni stüdyo',
'studio.newSub': 'Stüdyo mağaza hesaplarını, onlarla birlikte uygulamalarını gruplar',
'studio.name': 'Ad',
'studio.namePlaceholder': 'Örnek Oyunlar',
'studio.color': 'Renk',
'studio.add': 'Stüdyo ekle',
'studio.added': '{name} stüdyosu eklendi',
'studio.edit': 'Düzenle',
'studio.logo': 'Logo',
'studio.logoClear': 'Logoyu kaldır',
'studio.remove': 'Kaldır',
'studio.removeHint': 'Yalnızca stüdyoyu kaldırır: hesapları ve uygulamaları stüdyosuz kalır',
'studio.counts': '{count} hesap · {apps} uygulama · {store} yalnızca mağazada',
'studio.noAccounts': 'Bu stüdyoda henüz mağaza hesabı yok: aşağıdan bir hesap ekleyip bu stüdyoyu seçin.',
'studio.allAssigned': 'Her hesap bir stüdyoda.',
'color.indigo': 'Çivit',
'color.violet': 'Mor',
'color.rose': 'Gül',
'color.amber': 'Kehribar',
'color.emerald': 'Zümrüt',
'color.teal': 'Deniz mavisi',
'color.sky': 'Gök mavisi',
'color.slate': 'Arduvaz',
'accounts.leadStudios': 'Stüdyolar mağaza hesaplarınızı gruplar: Google Play hizmet hesapları ve App Store Connect ekip anahtarları. Anahtarlar sistem anahtar zincirinde kalır; uygulamalar "Uygulamaları içe aktar" ile gelir.',
'accounts.emptyTextStudios': 'Bir stüdyo, sonra onun Google Play hizmet hesabını ve App Store Connect anahtarlarını ekleyin. "Uygulamaları içe aktar" bu anahtarların gördüğü tüm uygulamaları listeler.',
'accounts.playSubMany': 'Hizmet hesabı JSON anahtarı. Bir hizmet hesabı birden çok Play geliştirici hesabına davet edilebilir: hepsinin uygulamalarını görür.',
'accounts.appleSubMany': 'Ekip başına bir API anahtarı (şirket ya da bireysel): anahtar kimliği, issuer kimliği ve .p8 dosyası.',
'accounts.safetyStudios': 'Anahtarlar seçtiğiniz dosyadan bir kez okunur, sistem anahtar zincirine kaydedilir ve bir daha gösterilmez. storebound bir hesabın anahtarını tek bir çağrı için bellekte alır. Stüdyo adları, etiketler ve uygulama listeleri bu bilgisayarda kalır.',
'acct.ok': 'Çalışıyor',
'acct.noApps': 'Uygulama yok',
'acct.permission': 'İzin eksik',
'acct.revoked': 'Anahtar iptal',
'acct.apiDisabled': 'API kapalı',
'acct.error': 'Ulaşılamadı',
'acct.notTested': 'Sınanmadı',
'acct.kindPlay': 'Google Play hizmet hesabı',
'acct.kindApple': 'App Store Connect ekip anahtarı',
'acct.appsRead': '{count} uygulama, {when} okundu',
'acct.appsRead_one': '1 uygulama, {when} okundu',
'acct.notImported': 'uygulamalar henüz içe aktarılmadı',
'acct.folders': '{count} klasör kullanıyor',
'acct.folders_one': '1 klasör kullanıyor',
'acct.test': 'Sına',
'acct.testAll': 'Tüm hesapları sına',
'acct.import': 'Uygulamaları al',
'acct.edit': 'Yeniden adlandır ya da stüdyoya taşı',
'acct.editAria': '{label} düzenle',
'acct.ignore': 'Bu hesabı yok say',
'acct.ignoreHint': 'Yok say: bu hesabın uygulamalarını portföy ve mağaza okumalarının dışında bırak',
'acct.unignore': 'Bu hesabı yeniden göster',
'acct.ignored': 'Yok sayıldı',
'acct.openFix': 'Aç',
'ignored.lead': 'Portföy, kenar çubuğu ve mağaza okumalarının dışında bırakılan uygulamalar ve hesaplar. Mağazalarda hiçbir şey değişmez.',
'ignored.restoreAll': 'Tümünü geri getir',
'ignored.restore': 'Geri getir',
'ignored.emptyTitle': 'Yok sayılan bir şey yok',
'ignored.emptyText': 'Test uygulamalarını ve eski başlıkları uzak tutmak için bir uygulamayı kendi sayfasından (ya da bütün bir hesabı Stüdyolar ve hesaplar\'dan) yok sayın.',
'ignored.apps': 'Uygulamalar',
'ignored.appsSub': '{count} yok sayıldı',
'ignored.accounts': 'Hesaplar',
'ignored.accountsSub': 'Bu hesapların tüm uygulamaları dışarıda',
'ignored.accountApps': '{count} uygulama',
'ignored.accountApps_one': '1 uygulama',
'ignored.noApps': 'Yok sayılan uygulama yok.',
'ignored.noAccounts': 'Yok sayılan hesap yok.',
'ignored.howTo': 'Eşleştirme ve tek mağazalı uygulamalar:',
'ignored.toPairing': 'Ayarlar > Uygulama eşleştirme',
'pair.folder': 'Uygulama klasöründen',
'pair.manual': 'Elle eşleştirildi',
'pair.id': 'Eşleşti: aynı bundle id ve paket adı',
'pair.close': 'Eşleşti: benzer kimlikler',
'pair.name': 'Eşleşti: aynı ad',
'pair.single': 'Tek mağaza',
'app.moveStudio': 'Bir stüdyoya taşı',
'app.pairWith': 'Şununla eşleştir',
'app.pairWithName': '{name} uygulamasını şununla eşleştir',
'app.pick': 'Bir uygulama seçin',
'app.unpair': 'Eşleşmeyi ayır',
'app.ignore': 'Yok say',
'app.ignoreHint': 'Bu uygulamayı portföy ve mağaza okumalarının dışında bırak (Yok sayılanlar ekranından geri getirilir)',
'app.studioHint': 'Stüdyoyu aç',
'app.storeOnlyTitle': 'Yalnızca mağaza.',
'app.storeOnlyText': 'Bu uygulama mağaza hesaplarınızda ama uygulama klasörü yok: sürümler, yorumlar, sağlık ve TestFlight salt okunur gösterilir. Mağaza metinlerini, ürünleri ve denetimleri yönetmek için klasörünü bağlayın ya da yeni bir klasör başlatın.',
'app.linkFolder': 'Klasör bağla',
'app.initHere': 'Burada uygulama klasörü başlat',
'app.linked': '{name} bağlandı',
'app.linkFailed': 'Klasör bağlanamadı',
'portfolio.subStudios': '{count} uygulama · {stores} mağaza kaydı · {studios} stüdyo',
'portfolio.emptyAccounts': 'Stüdyo ve hesaplarını ekle',
'portfolio.notImported': '{count} hesabın uygulamaları henüz içe aktarılmadı: "Uygulamaları içe aktar" bu anahtarların gördüğü her şeyi listeler.',
'portfolio.notImported_one': '1 hesabın uygulamaları henüz içe aktarılmadı: "Uygulamaları içe aktar" anahtarının gördüğü her şeyi listeler.',
'portfolio.toolbar': 'Uygulamaları süz ve sırala',
'portfolio.search': 'Uygulama, bundle id, paket ara',
'portfolio.studioFilter': 'Stüdyo',
'portfolio.allStudios': 'Tüm stüdyolar',
'portfolio.sort': 'Sırala',
'portfolio.sortAttention': 'Dikkat isteyen',
'portfolio.sortRecent': 'Son güncellenen',
'portfolio.sortName': 'Ad',
'portfolio.group': 'Stüdyoya göre grupla',
'portfolio.groupCount': '{count} uygulama',
'portfolio.noConfig': 'Yapılandırma yok',
'portfolio.storeOnlyCheck': 'Yalnızca mağaza',
'portfolio.noMatch': 'Eşleşen uygulama yok',
'portfolio.noMatchText': 'Aramayı temizleyin ya da başka bir stüdyo seçin.',
'portfolio.studiosN': '{count} stüdyo',
'portfolio.studiosN_one': '1 stüdyo',
'portfolio.folders': 'Uygulama klasörleri',
'portfolio.foldersN': '{count} klasör · {store} yalnızca mağazada',
'portfolio.ignoredN': '{count} uygulama',
'portfolio.ignoredN_one': '1 uygulama',
'kpi.appsSubStore': 'iOS {ios} · Android {android} · {store} yalnızca mağazada',
'toast.importing': 'Uygulamalar içe aktarılıyor',
'toast.importingDetail': 'Her hesabın gördüğü tüm uygulamalar (salt okunur)',
'toast.importDone': 'Hesaplarınızda {count} uygulama',
'toast.importDone_one': 'Hesaplarınızda 1 uygulama',
'toast.importDoneDetail': '{count} hesaptan',
'toast.importDoneDetail_one': '1 hesaptan',
'toast.importPartial': '{count} hesap okunamadı',
'toast.importPartial_one': '1 hesap okunamadı',
'toast.saveFailed': 'Kaydedilmedi',
'notify.releaseTitle': '{name}: mağaza durumu değişti',
'notify.releaseBody': '{store} {version}: {phase}',
'notify.lowTitle': '{name}: {count} yeni düşük puan',
'notify.lowTitle_one': '{name}: yeni bir düşük puan',
'notify.crashTitle': '{name}: Play eşiğinin üstünde',
'set.lead': 'Stüdyolar, hesaplar, mağaza okumaları, çevrimdışı önbellek, dil, tema, bildirimler ve dahası. Hepsi bu bilgisayarda kalır.',
'set.sections': 'Ayar bölümleri',
'set.studios': 'Stüdyolar ve hesaplar',
'set.studiosSub': 'Hangi hesap hangi stüdyoya ait',
'set.studioLine': 'Play {play} · App Store {apple} · {apps} uygulama',
'set.noStudios': 'Henüz stüdyo yok. Stüdyolar hesapları ve uygulamalarını portföyde ve kenar çubuğunda gruplar.',
'set.manage': 'Yönet',
'set.pairing': 'Uygulama eşleştirme ve yok sayılanlar',
'set.pairingSub': 'Bir iOS ve bir Android uygulaması kimlikleri ya da adları eşleşince tek kart olur; burada elle eşleştirin ya da ayırın',
'set.pairedHow': 'Eşleştirme',
'set.noCandidates': 'Eşleştirilecek bir şey yok',
'set.noStoreOnly': 'Her uygulamanın klasörü var: eşleştirme yapılandırmalardan gelir.',
'set.ignoredLine': 'Yok sayılan: {count} uygulama, {accounts} hesap.',
'set.openIgnored': 'Listeyi aç',
'set.refresh': 'Mağaza okumaları',
'set.refreshSub': 'Okumalar her hesabın API kotasını kullanır: siz istediğinizde ya da buradaki zamanlamayla çalışır',
'set.autoRefresh': 'Mağazaları otomatik oku',
'set.autoHint': 'Uygulama açıkken. Varsayılan olarak kapalı.',
'set.off': 'Kapalı',
'set.min': '{n} dk',
'set.hour': '{n} sa',
'set.onLaunch': 'Uygulama açılınca oku',
'set.onLaunchHint': 'Her hesabın uygulamalarını içe aktarır, sonra her uygulamanın mağaza durumunu okur',
'set.icons': 'İçe aktarırken mağaza simgeleri',
'set.iconsHint': 'Uygulama başına bir ek istek; klasörler kendi simgelerini kullanır',
'set.parallel': 'Aynı anda okunan uygulama',
'set.parallelHint': 'Daha az, hız sınırlarına daha nazik',
'set.cache': 'Çevrimdışı önbellek',
'set.cacheSub': 'Son mağaza okumaları, çevrimdışıyken zamanlarıyla gösterilir',
'set.cacheSize': 'Diskte',
'set.cacheRows': '{count} kayıtlı okuma',
'set.cacheRows_one': '1 kayıtlı okuma',
'set.cacheOldest': 'En eski',
'set.keep': 'Kayıtlı okumaları sakla',
'set.days': '{n} gün',
'set.year': '1 yıl',
'set.always': 'Her zaman',
'set.notifications': 'Bildirimler',
'set.notificationsSub': 'Bir okumadan sonra, öncekinden beri bir şey değiştiyse',
'set.nReview': 'İnceleme ve yayın durumu değişiklikleri',
'set.nReviewHint': 'İncelemede, onaylandı, reddedildi, yayında, durduruldu',
'set.nLow': 'Yeni 1 ya da 2 yıldızlı yorumlar',
'set.nLowHint': 'Yorumlar sekmesi yenilerini okuduğunda',
'set.nCrash': 'Çökme ya da ANR oranı eşiğin üstünde',
'set.nCrashHint': 'Google Play kötü davranış eşikleri',
'set.testNotify': 'Deneme bildirimi gönder',
'set.testTitle': 'storebound',
'set.testBody': 'Bildirimler çalışıyor.',
'set.appCopy': 'uygulama kopyası',
'set.depsText': 'Mağaza işleri yerel araç gerektirmez. Ekran görüntüleri, önizlemeler ve simgeler ffmpeg ve Chrome kullanır: Bağımlılıklar ekranında tek tık.',
'set.cli': 'CLI yardımcısı',
'set.protocol': 'Protokol',
'set.state': 'Durum',
'set.running': 'Çalışıyor',
'set.writes': 'Yazmalar',
'set.writesText': 'Önce deneme, sonra sistem penceresinde sizin Uygula onayınız. Gönderme, yayınlama ve yayımlama konsollarda kalır.',
'set.privacy': 'Gizlilik',
'set.p1': 'Telemetri, analiz ya da çökme raporu yok: uygulama yalnızca siz istediğinizde, anahtarlarınızla mağazalarla konuşur.',
'set.p2': 'Mağaza anahtarları sistem anahtar zincirinde durur; uygulama veri klasöründe adlar, ayarlar ve kayıtlı okumalar vardır, anahtar asla.',
'set.p3': 'Siz bir sistem penceresinde onaylamadıkça uygulama klasörlerinize hiçbir şey yazılmaz.',
'set.p4': 'Test kullanıcısı e-postaları maskeli kalır; yorum taslakları her uygulama klasörünün .storebound/ klasöründe (gitignore) kalır.',
'set.reveal': 'Veri klasörünü göster',
'set.scQuit': 'Çık',
'set.updates': 'Güncellemeler',
'set.channel': 'Kanal',
'set.stable': 'Kararlı',
'set.beta': 'Beta',
'set.updatesText': 'storebound.dev\'den imzalı güncellemeler ilk herkese açık masaüstü sürümüyle gelir; kanal o zaman için saklanır.',
'set.reset': 'Sıfırla',
'set.resetText': '{accounts} hesabı (anahtarları anahtar zincirinden silinir), {studios} stüdyoyu, {folders} uygulama klasörünü (klasörler diskte kalır), eşleştirmeyi, yok sayılanları, ayarları ve kayıtlı okumaları unutur. Önce bir sistem penceresi sorar.',
'set.resetButton': 'Uygulamayı sıfırla',
'set.resetDone': 'storebound masaüstü sıfırlandı',
'set.footer': 'Bu bilgisayarın bildiği {n} uygulama',
'studio.counts_one': '1 hesap · {apps} uygulama · {store} yalnızca mağazada',
'portfolio.groupCount_one': '1 uygulama',
'portfolio.groupAccounts': '{count} hesap',
'portfolio.groupAccounts_one': '1 hesap',
}; };

View file

@ -1,225 +0,0 @@
// 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';
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 {
/** 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 }))] };
}
// ---- Portfolio list: filter, search, sort, group ----
export type SortBy = 'attention' | 'recent' | 'name';
export interface ListRow { app: UnifiedApp; attention: number; blockers: number; updated: string | null }
export function filterSort(rows: ListRow[], o: { studio: string | 'all' | 'none'; query: string; sort: SortBy }): ListRow[] {
const q = o.query.trim().toLowerCase();
const hit = (r: ListRow) => !q || [r.app.name, r.app.ios?.app.bundleId, r.app.android?.app.id, r.app.project?.path.split(/[\\/]/).pop()]
.some(s => s && s.toLowerCase().includes(q));
const inStudio = (r: ListRow) => o.studio === 'all' || (o.studio === 'none' ? !r.app.studio : r.app.studio === o.studio);
const by = {
attention: (a: ListRow, b: ListRow) => b.blockers - a.blockers || b.attention - a.attention || a.app.name.localeCompare(b.app.name),
recent: (a: ListRow, b: ListRow) => (b.updated ?? '').localeCompare(a.updated ?? '') || a.app.name.localeCompare(b.app.name),
name: (a: ListRow, b: ListRow) => a.app.name.localeCompare(b.app.name),
}[o.sort];
return rows.filter(r => !r.app.ignored && inStudio(r) && hit(r)).sort(by);
}
/** Groups by studio in the studios' order, apps without a studio last. */
export function groupByStudio<T extends { app: UnifiedApp }>(rows: T[], studios: { id: string }[]): { studio: string | null; rows: T[] }[] {
const order = [...studios.map(s => s.id as string | null), null];
const known = new Set(studios.map(s => s.id));
return order.map(id => ({ studio: id, rows: rows.filter(r => (id === null ? !r.app.studio || !known.has(r.app.studio) : r.app.studio === id)) })).filter(g => g.rows.length);
}
/** Per studio: visible apps (not ignored). */
export function studioCounts(apps: UnifiedApp[]): Record<string, number> {
const m: Record<string, number> = {};
for (const a of apps) if (!a.ignored) m[a.studio ?? ''] = (m[a.studio ?? ''] ?? 0) + 1;
return m;
}

View file

@ -1,41 +0,0 @@
// What deserves a desktop notification after a read (Settings > Notifications). Pure: compares the previous read with
// the new one and never fires on a first read (nothing to compare with = no flood).
import type { PortfolioResult } from '../api';
import { healthSeries, type HealthSnapshot, isError, PLAY_THRESHOLDS, type Review } from './model';
export interface ReleaseChange { project: string; name: string; store: 'ios' | 'android'; version: string; from: string; to: string }
/** Phase changes of the same version on the same store that the owner waits for: review in / out, approved, rejected, live, halted. */
export function releaseChanges(prev: PortfolioResult | null | undefined, next: PortfolioResult): ReleaseChange[] {
if (!prev) return [];
const WATCH = new Set(['review', 'approved', 'rejected', 'live', 'halted']);
const out: ReleaseChange[] = [];
for (const a of next.apps) {
const before = prev.apps.find(p => p.project === a.project);
if (!before || before.release.source !== 'live' || a.release.source !== 'live') continue;
for (const r of a.release.all ?? []) {
if (!r.version) continue;
const old = (before.release.all ?? []).find(x => x.store === r.store && x.version === r.version);
if (!old || old.phase === r.phase) continue;
if (WATCH.has(r.phase) || WATCH.has(old.phase)) out.push({ project: a.project, name: a.app?.name ?? a.project, store: r.store, version: r.version, from: old.phase, to: r.phase });
}
}
return out;
}
/** New 1-2 star reviews since the previous read. */
export function newLowReviews(prev: Review[] | null | undefined, next: Review[]): Review[] {
if (!prev) return [];
const seen = new Set(prev.map(r => `${r.store}:${r.id}`));
return next.filter(r => r.rating <= 2 && !seen.has(`${r.store}:${r.id}`));
}
/** Crash or ANR rate that went over the Play bad behavior threshold since the previous read. */
export function crashCrossed(prev: HealthSnapshot | null | undefined, next: HealthSnapshot): ('crash' | 'anr')[] {
if (!prev?.play || isError(prev.play) || !next.play || isError(next.play)) return [];
const out: ('crash' | 'anr')[] = [];
const was = { crash: healthSeries(prev.play.crash, 'userPerceivedCrashRate', PLAY_THRESHOLDS.crash), anr: healthSeries(prev.play.anr, 'userPerceivedAnrRate', PLAY_THRESHOLDS.anr) };
const now = { crash: healthSeries(next.play.crash, 'userPerceivedCrashRate', PLAY_THRESHOLDS.crash), anr: healthSeries(next.play.anr, 'userPerceivedAnrRate', PLAY_THRESHOLDS.anr) };
for (const k of ['crash', 'anr'] as const) if (now[k].tone === 'bad' && was[k].tone !== 'bad') out.push(k);
return out;
}

View file

@ -1,30 +1,25 @@
// Routes: Portfolio -> one App (tabs) plus the workspace screens. Pure, so tests can check the deep links. // Routes: Portfolio -> one App (tabs) plus the workspace screens. Pure, so tests can check the deep links.
// An app is keyed by its project id, or (store-only apps, no folder) by its store target ("store:...").
import { createContext, useContext } from 'react'; import { createContext, useContext } from 'react';
import type { Key } from './i18n'; import type { Key } from './i18n';
import type { IconName } from './ui/icons'; import type { IconName } from './ui/icons';
export const APP_TABS = ['releases', 'catalog', 'listings', 'health', 'reviews', 'testflight', 'checks'] as const; export const APP_TABS = ['releases', 'catalog', 'listings', 'health', 'reviews', 'testflight', 'checks'] as const;
export type AppTab = (typeof APP_TABS)[number]; export type AppTab = (typeof APP_TABS)[number];
/** Tabs of a store-only app: store reads only (catalog, listings and checks need the app folder). */
export const STORE_TABS: readonly AppTab[] = ['releases', 'health', 'reviews', 'testflight'];
export const tabsFor = (hasFolder: boolean): readonly AppTab[] => (hasFolder ? APP_TABS : STORE_TABS);
export const TAB_KEY: Record<AppTab, Key> = { releases: 'tab.releases', catalog: 'tab.catalog', listings: 'tab.listings', health: 'tab.health', reviews: 'tab.reviews', testflight: 'tab.testflight', checks: 'tab.checks' }; export const TAB_KEY: Record<AppTab, Key> = { releases: 'tab.releases', catalog: 'tab.catalog', listings: 'tab.listings', health: 'tab.health', reviews: 'tab.reviews', testflight: 'tab.testflight', checks: 'tab.checks' };
export const TAB_ICON: Record<AppTab, IconName> = { releases: 'rocket', catalog: 'tag', listings: 'text', health: 'activity', reviews: 'message', testflight: 'plane', checks: 'shield' }; export const TAB_ICON: Record<AppTab, IconName> = { releases: 'rocket', catalog: 'tag', listings: 'text', health: 'activity', reviews: 'message', testflight: 'plane', checks: 'shield' };
export const WORKSPACE = ['apps', 'accounts', 'ignored', 'dependencies', 'settings'] as const; export const WORKSPACE = ['apps', 'accounts', 'dependencies', 'settings'] as const;
export type WorkspaceScreen = (typeof WORKSPACE)[number]; export type WorkspaceScreen = (typeof WORKSPACE)[number];
export type Route = { screen: 'portfolio' } | { screen: 'app'; appId: string; tab: AppTab } | { screen: WorkspaceScreen; section?: string }; export type Route = { screen: 'portfolio' } | { screen: 'app'; appId: string; tab: AppTab } | { screen: WorkspaceScreen };
/** storebound://<screen> deep links and the dev-only start switch ("app:health" = first app, Health tab; /** storebound://<screen> deep links and the dev-only start switch ("app:health" = first app, Health tab;
* "app:health:2" = second app; "settings:refresh" = a Settings section). `apps` are the app keys in list order. */ * "app:health:2" = second app). `apps` are the project ids in list order. */
export function parseStart(v: string, apps: string[]): Route | null { export function parseStart(v: string, apps: string[]): Route | null {
const [screen, tab, n] = v.split(':'); const [screen, tab, n] = v.split(':');
const app = apps[Math.max(0, (Number(n) || 1) - 1)]; const app = apps[Math.max(0, (Number(n) || 1) - 1)];
if (screen === 'app' && app) return { screen: 'app', appId: app, tab: APP_TABS.includes(tab as AppTab) ? tab as AppTab : 'releases' }; if (screen === 'app' && app) return { screen: 'app', appId: app, tab: APP_TABS.includes(tab as AppTab) ? tab as AppTab : 'releases' };
if (screen === 'portfolio') return { screen: 'portfolio' }; if (screen === 'portfolio') return { screen: 'portfolio' };
if (!(WORKSPACE as readonly string[]).includes(screen ?? '')) return null; return (WORKSPACE as readonly string[]).includes(screen ?? '') ? { screen: screen as WorkspaceScreen } : null;
return tab ? { screen: screen as WorkspaceScreen, section: tab } : { screen: screen as WorkspaceScreen };
} }
export const sameRoute = (a: Route, b: Route): boolean => JSON.stringify(a) === JSON.stringify(b); export const sameRoute = (a: Route, b: Route): boolean => JSON.stringify(a) === JSON.stringify(b);

View file

@ -1,227 +1,88 @@
// Studios & accounts: studios (name, colour, logo) group store accounts; each account is a Google Play service account // Store accounts: the keys live in the system keychain; the app keeps a label only and hands a key to storebound in
// (one JSON key; it can be invited to several Play developer accounts) or an App Store Connect team key (key id, // memory for one call.
// issuer id, .p8). Keys live in the system keychain; the app keeps a label and the studio only. Per account: a health import { useState } from 'react';
// check (key works / permission missing / revoked, with the fix) and "Import apps" (every app the key can see). import { type Account, api, errorText } from '../api';
import { type FormEvent, useEffect, useState } from 'react'; import { t } from '../i18n';
import { type Account, type AccountCheck, api, errorText, STUDIO_COLORS, type Studio, type StudioColor } from '../api'; import { date } from '../lib/format';
import { type Key, t } from '../i18n'; import { useData } from '../store';
import { ago } from '../lib/format';
import { withIgnored } from '../lib/identity';
import { type AccountHealth, useData } from '../store';
import { Icon, StoreGlyph } from '../ui/icons'; import { Icon, StoreGlyph } from '../ui/icons';
import { Card, Chip, Empty, Notice, StudioMark } from '../ui/kit'; import { Card, Chip, Empty, Notice } from '../ui/kit';
import type { Tone } from '../lib/model';
const STATUS: Record<AccountCheck['status'], [Tone, Key]> = { export function Accounts() {
ok: ['ok', 'acct.ok'], 'no-apps': ['warn', 'acct.noApps'], permission: ['warn', 'acct.permission'], revoked: ['bad', 'acct.revoked'], 'api-disabled': ['warn', 'acct.apiDisabled'], error: ['bad', 'acct.error'],
};
export function HealthChip({ h }: { h: AccountHealth | undefined }) {
if (!h) return <Chip tone="neutral">{t('acct.notTested')}</Chip>;
if (h.error || !h.check) return <span title={h.error}><Chip tone="bad">{t('acct.error')}</Chip></span>;
const [tone, key] = STATUS[h.check.status];
return <span title={h.check.message}><Chip tone={tone}>{t(key)}</Chip></span>;
}
function Swatches({ value, onChange, name }: { value: StudioColor; onChange: (c: StudioColor) => void; name: string }) {
return (
<div className="swatches" role="radiogroup" aria-label={t('studio.color')}>
{STUDIO_COLORS.map(c => (
<button key={c} type="button" role="radio" aria-checked={value === c} className={`swatch studio-${c}`} onClick={() => onChange(c)} aria-label={t(`color.${c}` as Key)} title={t(`color.${c}` as Key)}>
{value === c && <Icon name="check" />}
</button>
))}
<span className="sr">{name}</span>
</div>
);
}
function AccountRow({ a, busy, setBusy, onError }: { a: Account; busy: string | null; setBusy: (b: string | null) => void; onError: (e: string | null) => void }) {
const d = useData();
const [edit, setEdit] = useState(false);
const [label, setLabel] = useState(a.label);
const [studio, setStudio] = useState(a.studio ?? '');
const h = d.accountHealth[a.id];
const list = d.storeApps[a.id];
const ignored = d.overrides.ignored.includes(`account:${a.id}`);
const used = d.projects.filter(p => p.playAccount === a.id || p.appleAccount === a.id).length;
const run = async (key: string, fn: () => Promise<unknown>) => {
setBusy(key); onError(null);
try { await fn(); } catch (e) { onError(errorText(e)); } finally { setBusy(null); }
};
const save = (e: FormEvent) => { e.preventDefault(); run(`ed-${a.id}`, async () => { await api.updateAccount(a.id, label, studio || null); await d.reload(); setEdit(false); }); };
const check = h?.check;
return (
<div className={`acct${ignored ? ' is-ignored' : ''}`}>
<div className="acct-row">
<span className={`acct-glyph ${a.kind}`}><StoreGlyph store={a.kind === 'play' ? 'android' : 'ios'} /></span>
<div className="acct-main">
<div className="row" style={{ gap: 8 }}><span className="strong">{a.label}</span><HealthChip h={h} />{ignored && <Chip tone="neutral" icon="eyeOff">{t('acct.ignored')}</Chip>}</div>
<div className="small muted">
{a.kind === 'play' ? t('acct.kindPlay') : t('acct.kindApple')}
{' · '}{list ? t('acct.appsRead', { count: list.value.apps.length, when: ago(list.at) }) : t('acct.notImported')}
{used ? ` · ${t('acct.folders', { count: used })}` : ''}
{check?.principal ? <> · <span className="mono-id selectable">{check.principal}</span></> : null}
</div>
</div>
<div className="actions">
<button className="btn btn-sm" onClick={() => run(`ck-${a.id}`, () => d.checkAccount(a.id))} disabled={!!busy}><Icon name="shield" className={busy === `ck-${a.id}` ? 'spin' : undefined} />{t('acct.test')}</button>
<button className="btn btn-sm" onClick={() => run(`im-${a.id}`, () => d.importApps(a.id))} disabled={!!busy || d.importBusy}><Icon name="download" />{t('acct.import')}</button>
<button className="btn btn-sm btn-ghost btn-icon" onClick={() => setEdit(x => !x)} aria-expanded={edit} aria-label={t('acct.editAria', { label: a.label })} title={t('acct.edit')}><Icon name="edit" /></button>
<button className="btn btn-sm btn-ghost btn-icon" onClick={() => d.updateOverrides(o => withIgnored(o, [`account:${a.id}`], !ignored))} aria-label={ignored ? t('acct.unignore') : t('acct.ignore')} title={ignored ? t('acct.unignore') : t('acct.ignoreHint')}><Icon name={ignored ? 'eye' : 'eyeOff'} /></button>
<button className="btn btn-sm btn-ghost btn-icon btn-danger" disabled={!!busy} onClick={() => run(`rm-${a.id}`, async () => { await api.removeAccount(a.id); await d.reload(); })} aria-label={t('accounts.removeAria', { label: a.label })} title={t('accounts.remove')}><Icon name="trash" /></button>
</div>
</div>
{edit && (
<form className="acct-edit" onSubmit={save}>
<div className="field"><label htmlFor={`al-${a.id}`}>{t('accounts.label')}</label><input id={`al-${a.id}`} className="input" value={label} onChange={e => setLabel(e.target.value)} maxLength={60} /></div>
<div className="field"><label htmlFor={`as-${a.id}`}>{t('studio.studio')}</label>
<select id={`as-${a.id}`} className="input" value={studio} onChange={e => setStudio(e.target.value)}>
<option value="">{t('studio.none')}</option>
{d.studios.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select></div>
<div className="actions"><button className="btn btn-primary btn-sm" type="submit" disabled={!label.trim() || !!busy}><Icon name="check" />{t('common.save')}</button><button type="button" className="btn btn-sm btn-ghost" onClick={() => setEdit(false)}>{t('common.cancel')}</button></div>
</form>
)}
{check && check.status !== 'ok' && check.fix && (
<div className="acct-fix">
<Notice tone={check.status === 'revoked' ? 'bad' : 'warn'} action={check.docs ? <button className="btn btn-sm" onClick={() => api.openExternal(check.docs!).catch(e => onError(errorText(e)))}><Icon name="external" />{t('acct.openFix')}</button> : undefined}>
<b>{check.message}</b><br />{check.fix}
</Notice>
</div>
)}
{h?.error && <div className="acct-fix"><Notice tone="bad">{h.error}</Notice></div>}
</div>
);
}
function StudioCard({ s, accounts, focus }: { s: Studio | null; accounts: Account[]; focus: boolean }) {
const d = useData();
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [edit, setEdit] = useState(false);
const [name, setName] = useState(s?.name ?? '');
const [color, setColor] = useState<StudioColor>(s?.color ?? 'indigo');
const apps = d.apps.filter(a => !a.ignored && (a.studio ?? null) === (s?.id ?? null));
const storeOnly = apps.filter(a => !a.project).length;
const act = async (key: string, fn: () => Promise<unknown>) => { setBusy(key); setError(null); try { await fn(); await d.reload(); } catch (e) { setError(errorText(e)); } finally { setBusy(null); } };
const id = s ? `studio-${s.id}` : 'studio-none';
useEffect(() => { if (focus) document.getElementById(id)?.scrollIntoView({ block: 'start' }); }, [focus, id]);
return (
<section className={`card studio-card${focus ? ' focus' : ''}`} id={id} aria-labelledby={`${id}-h`}>
<div className="card-head">
<div className="row" style={{ gap: 12, minWidth: 0 }}>
<StudioMark studio={s} size="lg" />
<div className="stack" style={{ gap: 2, minWidth: 0 }}>
<h2 id={`${id}-h`}>{s?.name ?? t('studio.none')}</h2>
<div className="sub">{s ? t('studio.counts', { count: accounts.length, apps: apps.length, store: storeOnly }) : t('studio.noneSub')}</div>
</div>
</div>
{s && (
<div className="actions">
<button className="btn btn-sm btn-ghost" onClick={() => setEdit(x => !x)} aria-expanded={edit}><Icon name="edit" />{t('studio.edit')}</button>
<button className="btn btn-sm btn-ghost" onClick={() => act('logo', () => api.studioLogo(s.id))} disabled={!!busy}><Icon name="image" />{t('studio.logo')}</button>
{s.logo && <button className="btn btn-sm btn-ghost" onClick={() => act('logo', () => api.studioLogo(s.id, true))} disabled={!!busy}>{t('studio.logoClear')}</button>}
<button className="btn btn-sm btn-ghost btn-danger" onClick={() => act('rm', () => api.removeStudio(s.id))} disabled={!!busy} title={t('studio.removeHint')}><Icon name="trash" />{t('studio.remove')}</button>
</div>
)}
</div>
{s && edit && (
<form className="card-body studio-edit" onSubmit={e => { e.preventDefault(); act('save', async () => { await api.saveStudio(s.id, name, color); setEdit(false); }); }}>
<div className="field"><label htmlFor={`${id}-n`}>{t('studio.name')}</label><input id={`${id}-n`} className="input" value={name} onChange={e => setName(e.target.value)} maxLength={48} /></div>
<div className="field"><span className="legend">{t('studio.color')}</span><Swatches value={color} onChange={setColor} name={name} /></div>
<div className="actions"><button className="btn btn-primary btn-sm" type="submit" disabled={!name.trim() || !!busy}><Icon name="check" />{t('common.save')}</button></div>
</form>
)}
{error && <div className="card-body"><Notice tone="bad">{error}</Notice></div>}
{accounts.length ? <div className="acct-list">{accounts.map(a => <AccountRow key={a.id} a={a} busy={busy} setBusy={setBusy} onError={setError} />)}</div>
: <div className="card-body"><p className="small muted">{s ? t('studio.noAccounts') : t('studio.allAssigned')}</p></div>}
</section>
);
}
export function Accounts({ focus }: { focus?: string }) {
const d = useData(); const d = useData();
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState<string | null>(null); const [busy, setBusy] = useState<string | null>(null);
const [studioName, setStudioName] = useState('');
const [studioColor, setStudioColor] = useState<StudioColor>('indigo');
const [playLabel, setPlayLabel] = useState(''); const [playLabel, setPlayLabel] = useState('');
const [playStudio, setPlayStudio] = useState('');
const [appleLabel, setAppleLabel] = useState(''); const [appleLabel, setAppleLabel] = useState('');
const [appleStudio, setAppleStudio] = useState('');
const [keyId, setKeyId] = useState(''); const [keyId, setKeyId] = useState('');
const [issuerId, setIssuerId] = useState(''); const [issuerId, setIssuerId] = useState('');
const act = async (key: string, fn: () => Promise<Account | Studio | null | void>, ok?: (r: Account | Studio) => string) => { const act = async (key: string, fn: () => Promise<Account | null | void>) => {
setBusy(key); setError(null); setBusy(key); setError(null);
try { try {
const r = await fn(); const r = await fn();
if (r && ok) d.toast({ kind: 'ok', title: ok(r), detail: 'kind' in r ? t('accounts.savedDetail') : undefined }); if (r) d.toast({ kind: 'ok', title: t('accounts.saved', { label: r.label }), detail: t('accounts.savedDetail') });
await d.reload(); await d.reload();
return r;
} catch (e) { setError(errorText(e)); } finally { setBusy(null); } } catch (e) { setError(errorText(e)); } finally { setBusy(null); }
}; };
const addStudio = () => act('studio', async () => { const s = await api.saveStudio(null, studioName, studioColor); setStudioName(''); return s; }, r => t('studio.added', { name: (r as Studio).name })); const addPlay = () => act('play', async () => { const a = await api.addPlayAccount(playLabel); if (a) setPlayLabel(''); return a; });
const addPlay = () => act('play', async () => { const a = await api.addPlayAccount(playLabel, playStudio || null); if (a) setPlayLabel(''); return a; }, r => t('accounts.saved', { label: (r as Account).label })); const addApple = () => act('apple', async () => { const a = await api.addAppleAccount(appleLabel, keyId, issuerId); if (a) { setAppleLabel(''); setKeyId(''); setIssuerId(''); } return a; });
const addApple = () => act('apple', async () => { const a = await api.addAppleAccount(appleLabel, keyId, issuerId, appleStudio || null); if (a) { setAppleLabel(''); setKeyId(''); setIssuerId(''); } return a; }, r => t('accounts.saved', { label: (r as Account).label })); const used = (a: Account) => d.projects.filter(p => p.playAccount === a.id || p.appleAccount === a.id).map(p => p.name);
const testAll = async () => { setBusy('all'); await Promise.all(d.accounts.map(a => d.checkAccount(a.id))); setBusy(null); };
const unassigned = d.accounts.filter(a => !a.studio || !d.studios.some(s => s.id === a.studio));
const studioSelect = (id: string, value: string, set: (v: string) => void) => (
<div className="field"><label htmlFor={id}>{t('studio.studio')}</label>
<select id={id} className="input" value={value} onChange={e => set(e.target.value)}>
<option value="">{t('studio.none')}</option>
{d.studios.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select></div>
);
return ( return (
<div className="page"> <div className="page">
<div className="ph"> <div className="ph"><div><h1>{t('nav.accounts')}</h1><p>{t('accounts.lead')}</p></div></div>
<div><h1>{t('nav.accounts')}</h1><p>{t('accounts.leadStudios')}</p></div>
<div className="actions">
<button className="btn" onClick={testAll} disabled={!!busy || !d.accounts.length}><Icon name="shield" className={busy === 'all' ? 'spin' : undefined} />{t('acct.testAll')}</button>
<button className="btn btn-primary" onClick={() => d.importApps()} disabled={d.importBusy || !d.accounts.length}><Icon name="download" className={d.importBusy ? 'spin' : undefined} />{t('action.importApps')}</button>
</div>
</div>
{error && <Notice tone="bad">{error}</Notice>} {error && <Notice tone="bad">{error}</Notice>}
{!d.accounts.length && !d.studios.length && <Card pad={false}><Empty illo="key" title={t('accounts.emptyTitle')}>{t('accounts.emptyTextStudios')}</Empty></Card>} <Card title={t('accounts.list')} icon="key" sub={t('accounts.listSub')} pad={false}>
{d.studios.map(s => <StudioCard key={s.id} s={s} accounts={d.accounts.filter(a => a.studio === s.id)} focus={focus === s.id} />)} {!d.accounts.length ? <Empty illo="key" title={t('accounts.emptyTitle')}>{t('accounts.emptyText')}</Empty> : (
{(unassigned.length > 0 || !d.studios.length) && d.accounts.length > 0 && <StudioCard s={null} accounts={unassigned} focus={focus === 'none'} />} <table className="table">
<thead><tr><th>{t('col.name')}</th><th>{t('col.store')}</th><th>{t('col.usedBy')}</th><th>{t('col.added')}</th><th><span className="sr">{t('col.actions')}</span></th></tr></thead>
<div className="grid g3" style={{ alignItems: 'start' }}> <tbody>
<Card title={t('studio.new')} icon="building" sub={t('studio.newSub')}> {d.accounts.map(a => (
<form className="form" onSubmit={e => { e.preventDefault(); addStudio(); }}> <tr key={a.id}>
<div className="field"><label htmlFor="studio-name">{t('studio.name')}</label><input id="studio-name" className="input" value={studioName} onChange={e => setStudioName(e.target.value)} maxLength={48} placeholder={t('studio.namePlaceholder')} autoComplete="off" /></div> <td className="strong">{a.label}</td>
<div className="field"><span className="legend">{t('studio.color')}</span><Swatches value={studioColor} onChange={setStudioColor} name={studioName} /></div> <td><span className="row" style={{ gap: 8 }}><StoreGlyph store={a.kind === 'play' ? 'android' : 'ios'} className="ic14" />{a.kind === 'play' ? 'Google Play' : 'App Store Connect'}</span></td>
<div><button className="btn btn-primary" type="submit" disabled={!studioName.trim() || !!busy}><Icon name="plus" />{t('studio.add')}</button></div> <td>{used(a).length ? used(a).join(', ') : <Chip tone="neutral">{t('accounts.unused')}</Chip>}</td>
</form> <td className="muted">{date(a.created)}</td>
<td className="right"><button className="btn btn-sm btn-ghost btn-danger" disabled={!!busy} onClick={() => act(`rm-${a.id}`, () => api.removeAccount(a.id))} aria-label={t('accounts.removeAria', { label: a.label })}><Icon name="trash" />{t('accounts.remove')}</button></td>
</tr>
))}
</tbody>
</table>
)}
</Card> </Card>
<Card title="Google Play" icon="key" sub={t('accounts.playSubMany')}> <div className="grid g2">
<Card title="Google Play" icon="key" sub={t('accounts.playSub')}>
<form className="form" onSubmit={e => { e.preventDefault(); addPlay(); }}> <form className="form" onSubmit={e => { e.preventDefault(); addPlay(); }}>
<div className="field"><label htmlFor="play-label">{t('accounts.label')}</label> <div className="field">
<input id="play-label" className="input" type="text" value={playLabel} onChange={e => setPlayLabel(e.target.value)} placeholder={t('accounts.playPlaceholder')} maxLength={60} autoComplete="off" /></div> <label htmlFor="play-label">{t('accounts.label')}</label>
{studioSelect('play-studio', playStudio, setPlayStudio)} <input id="play-label" className="input" type="text" value={playLabel} onChange={e => setPlayLabel(e.target.value)} placeholder={t('accounts.playPlaceholder')} maxLength={60} autoComplete="off" />
</div>
<p className="small muted">{t('accounts.playHow')}</p> <p className="small muted">{t('accounts.playHow')}</p>
<div><button className="btn btn-primary" type="submit" disabled={!playLabel.trim() || !!busy}><Icon name="key" />{t('accounts.choosePlay')}</button></div> <div><button className="btn btn-primary" type="submit" disabled={!playLabel.trim() || !!busy}><Icon name="key" />{t('accounts.choosePlay')}</button></div>
</form> </form>
</Card> </Card>
<Card title="App Store Connect" icon="key" sub={t('accounts.appleSubMany')}> <Card title="App Store Connect" icon="key" sub={t('accounts.appleSub')}>
<form className="form" onSubmit={e => { e.preventDefault(); addApple(); }}> <form className="form" onSubmit={e => { e.preventDefault(); addApple(); }}>
<div className="field"><label htmlFor="apple-label">{t('accounts.label')}</label> <div className="field">
<input id="apple-label" className="input" type="text" value={appleLabel} onChange={e => setAppleLabel(e.target.value)} placeholder={t('accounts.applePlaceholder')} maxLength={60} autoComplete="off" /></div> <label htmlFor="apple-label">{t('accounts.label')}</label>
{studioSelect('apple-studio', appleStudio, setAppleStudio)} <input id="apple-label" className="input" type="text" value={appleLabel} onChange={e => setAppleLabel(e.target.value)} placeholder={t('accounts.applePlaceholder')} maxLength={60} autoComplete="off" />
</div>
<div className="grid g2" style={{ gap: 12 }}> <div className="grid g2" style={{ gap: 12 }}>
<div className="field"><label htmlFor="key-id">{t('accounts.keyId')}</label> <div className="field">
<input id="key-id" className="input mono" type="text" value={keyId} onChange={e => setKeyId(e.target.value.toUpperCase())} placeholder="ABC123DEFG" maxLength={10} autoComplete="off" spellCheck={false} /></div> <label htmlFor="key-id">{t('accounts.keyId')}</label>
<div className="field"><label htmlFor="issuer-id">{t('accounts.issuerId')}</label> <input id="key-id" className="input mono" type="text" value={keyId} onChange={e => setKeyId(e.target.value.toUpperCase())} placeholder="ABC123DEFG" maxLength={10} autoComplete="off" spellCheck={false} />
<input id="issuer-id" className="input mono" type="text" value={issuerId} onChange={e => setIssuerId(e.target.value)} placeholder="UUID" maxLength={36} autoComplete="off" spellCheck={false} /></div> </div>
<div className="field">
<label htmlFor="issuer-id">{t('accounts.issuerId')}</label>
<input id="issuer-id" className="input mono" type="text" value={issuerId} onChange={e => setIssuerId(e.target.value)} placeholder="UUID" maxLength={36} autoComplete="off" spellCheck={false} />
</div>
</div> </div>
<div><button className="btn btn-primary" type="submit" disabled={!appleLabel.trim() || keyId.length !== 10 || issuerId.length < 36 || !!busy}><Icon name="key" />{t('accounts.chooseApple')}</button></div> <div><button className="btn btn-primary" type="submit" disabled={!appleLabel.trim() || keyId.length !== 10 || issuerId.length < 36 || !!busy}><Icon name="key" />{t('accounts.chooseApple')}</button></div>
</form> </form>
</Card> </Card>
</div> </div>
<Notice tone="info" icon="shield">{t('accounts.safetyStudios')}</Notice> <Notice tone="info" icon="shield">{t('accounts.safety')}</Notice>
</div> </div>
); );
} }

View file

@ -1,15 +1,12 @@
// One app across both stores: header (icon, studio, ids, store state, pairing), then the tabs. A store-only app (no // One app across both stores: header (icon, ids, store state), then the tabs.
// app folder) shows its store reads (releases, health, reviews, TestFlight) read-only, with "Link a folder" and import { type KeyboardEvent, useRef } from 'react';
// "Start an app folder here" to make it a full app. import { api, type Project } from '../api';
import { type KeyboardEvent, useRef, useState } from 'react'; import { t } from '../i18n';
import { api, errorText } from '../api'; import { APP_TABS, type AppTab, TAB_ICON, TAB_KEY, useNav } from '../nav';
import { type Key, t } from '../i18n';
import { pairCandidates, type UnifiedApp, withIgnored, withLink, withPair, withStudio, withUnpair } from '../lib/identity';
import { storeNow } from '../lib/model'; import { storeNow } from '../lib/model';
import { type AppTab, TAB_ICON, TAB_KEY, tabsFor, useNav } from '../nav';
import { useData } from '../store'; import { useData } from '../store';
import { Icon } from '../ui/icons'; import { Icon } from '../ui/icons';
import { AppIcon, Chip, Notice, PhaseChip, StoreBadge, StoreOnlyTag, StudioMark } from '../ui/kit'; import { AppIcon, Chip, PhaseChip, StoreBadge } from '../ui/kit';
import { CatalogTab } from './tabs/Catalog'; import { CatalogTab } from './tabs/Catalog';
import { ChecksTab } from './tabs/Checks'; import { ChecksTab } from './tabs/Checks';
import { HealthTab } from './tabs/Health'; import { HealthTab } from './tabs/Health';
@ -21,88 +18,23 @@ import { TestFlightTab } from './tabs/TestFlight';
export const ascUrl = (appId: string | null | undefined): string => (appId ? `https://appstoreconnect.apple.com/apps/${encodeURIComponent(appId)}/distribution` : 'https://appstoreconnect.apple.com/apps'); export const ascUrl = (appId: string | null | undefined): string => (appId ? `https://appstoreconnect.apple.com/apps/${encodeURIComponent(appId)}/distribution` : 'https://appstoreconnect.apple.com/apps');
export const PLAY_CONSOLE = 'https://play.google.com/console/'; export const PLAY_CONSOLE = 'https://play.google.com/console/';
const PAIRING: Record<UnifiedApp['pairing'], Key> = { folder: 'pair.folder', manual: 'pair.manual', id: 'pair.id', close: 'pair.close', name: 'pair.name', single: 'pair.single' }; export function AppView({ project, tab }: { project: Project; tab: AppTab }) {
/** Pairing, studio and ignore controls of one app. */
function AppControls({ app }: { app: UnifiedApp }) {
const d = useData(); const d = useData();
const nav = useNav(); const nav = useNav();
const cands = pairCandidates(app, d.apps); const e = d.statusOf(project);
const canUnpair = !app.project && !!app.ios && !!app.android; const l = d.liveOf(project);
return ( const ios = e?.app?.platforms.ios, android = e?.app?.platforms.android;
<div className="app-controls"> const name = e?.app?.name ?? project.name;
<span className="small muted row" style={{ gap: 6 }}><Icon name="link" className="ic13" />{t(PAIRING[app.pairing])}</span> const tabs = useRef<(HTMLButtonElement | null)[]>([]);
<label className="row small" style={{ gap: 6 }}><span className="muted">{t('studio.studio')}</span> const setTab = (x: AppTab) => nav.go({ screen: 'app', appId: project.id, tab: x });
<select className="input input-sm" value={app.studio ?? ''} onChange={e => d.updateOverrides(o => withStudio(o, app, e.target.value || null))} aria-label={t('app.moveStudio')}>
<option value="">{t('studio.none')}</option>
{d.studios.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select></label>
{cands.length > 0 && (
<label className="row small" style={{ gap: 6 }}><span className="muted">{t('app.pairWith')}</span>
<select className="input input-sm" value="" onChange={e => {
const other = cands.find(c => c.key === e.target.value);
if (!other) return;
const ios = (app.ios ?? other.ios)!.key, android = (app.android ?? other.android)!.key;
d.updateOverrides(o => withPair(o, ios, android)).then(() => nav.go({ screen: 'portfolio' }));
}} aria-label={t('app.pairWith')}>
<option value="">{t('app.pick')}</option>
{cands.slice(0, 30).map(c => <option key={c.key} value={c.key}>{c.name} · {(c.ios ?? c.android)!.app.bundleId}</option>)}
</select></label>
)}
{canUnpair && <button className="btn btn-sm btn-ghost" onClick={() => d.updateOverrides(o => withUnpair(o, app.ios!.key, app.android!.key)).then(() => nav.go({ screen: 'portfolio' }))}><Icon name="unlink" />{t('app.unpair')}</button>}
<button className="btn btn-sm btn-ghost" onClick={() => d.updateOverrides(o => withIgnored(o, app.ignoreKeys, true)).then(() => nav.go({ screen: 'portfolio' }))} title={t('app.ignoreHint')}><Icon name="eyeOff" />{t('app.ignore')}</button>
</div>
);
}
function StoreOnlyBanner({ app }: { app: UnifiedApp }) {
const d = useData();
const [busy, setBusy] = useState(false);
const [profile, setProfile] = useState<'app' | 'game' | 'subscription-app'>('app');
const link = async (init: boolean) => {
setBusy(true);
try {
const p = init ? await api.initProject(profile) : await api.addProject();
if (p) {
await d.updateOverrides(o => withLink(o, app, p.id));
await d.reload();
d.toast({ kind: 'ok', title: t('app.linked', { name: p.name }), detail: init ? t('folders.startedDetail') : undefined });
}
} catch (e) { d.toast({ kind: 'bad', title: t('app.linkFailed'), detail: errorText(e) }); } finally { setBusy(false); }
};
return (
<Notice tone="info" icon="cloud" action={<div className="actions">
<button className="btn btn-sm btn-primary" onClick={() => link(false)} disabled={busy}><Icon name="link" />{t('app.linkFolder')}</button>
<select className="input input-sm" value={profile} onChange={e => setProfile(e.target.value as typeof profile)} aria-label={t('folders.profile')}>
<option value="app">{t('profile.app')}</option><option value="game">{t('profile.game')}</option><option value="subscription-app">{t('profile.subscription-app')}</option>
</select>
<button className="btn btn-sm" onClick={() => link(true)} disabled={busy}><Icon name="folderPlus" />{t('app.initHere')}</button>
</div>}>
<b>{t('app.storeOnlyTitle')}</b> {t('app.storeOnlyText')}
</Notice>
);
}
export function AppView({ app, tab }: { app: UnifiedApp; tab: AppTab }) {
const d = useData();
const nav = useNav();
const e = d.statusFor(app);
const l = d.liveFor(app);
const ios = e?.app?.platforms.ios ?? (app.ios ? { bundleId: app.ios.app.bundleId, ascAppId: app.ios.app.id } : null);
const android = e?.app?.platforms.android ?? (app.android ? { packageName: app.android.app.id } : null);
const name = (app.project && e?.app?.name) || app.name;
const tabs = tabsFor(!!app.project);
const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);
const studio = d.studios.find(s => s.id === app.studio) ?? null;
const setTab = (x: AppTab) => nav.go({ screen: 'app', appId: app.key, tab: x });
const onKey = (ev: KeyboardEvent) => { const onKey = (ev: KeyboardEvent) => {
const i = tabs.indexOf(tab); const i = APP_TABS.indexOf(tab);
const j = ev.key === 'ArrowRight' ? i + 1 : ev.key === 'ArrowLeft' ? i - 1 : ev.key === 'Home' ? 0 : ev.key === 'End' ? tabs.length - 1 : null; const j = ev.key === 'ArrowRight' ? i + 1 : ev.key === 'ArrowLeft' ? i - 1 : ev.key === 'Home' ? 0 : ev.key === 'End' ? APP_TABS.length - 1 : null;
if (j === null) return; if (j === null) return;
ev.preventDefault(); ev.preventDefault();
const n = (j + tabs.length) % tabs.length; const n = (j + APP_TABS.length) % APP_TABS.length;
setTab(tabs[n]!); setTab(APP_TABS[n]!);
tabRefs.current[n]?.focus(); tabs.current[n]?.focus();
}; };
const all = l?.release.all ?? []; const all = l?.release.all ?? [];
const iosNow = l ? storeNow(all, 'ios').now : null, androidNow = l ? storeNow(all, 'android').now : null; const iosNow = l ? storeNow(all, 'ios').now : null, androidNow = l ? storeNow(all, 'android').now : null;
@ -112,17 +44,15 @@ export function AppView({ app, tab }: { app: UnifiedApp; tab: AppTab }) {
<div className="page"> <div className="page">
<div className="ph"> <div className="ph">
<div className="app-head"> <div className="app-head">
<AppIcon name={name} src={d.iconFor(app)} /> <AppIcon name={name} src={d.icons[project.id]} />
<div> <div>
<div className="row" style={{ gap: 10 }}> <div className="row" style={{ gap: 10 }}>
<h1>{name}</h1> <h1>{name}</h1>
{e?.summary?.profile && app.project && <Chip tone="outline">{t(`profile.${e.summary.profile}` as 'profile.app')}</Chip>} {e?.summary?.profile && <Chip tone="outline">{t(`profile.${e.summary.profile}` as 'profile.app')}</Chip>}
{!app.project && <StoreOnlyTag />}
<button className="studio-pill" onClick={() => nav.go({ screen: 'accounts', section: app.studio ?? 'none' })} title={t('app.studioHint')}><StudioMark studio={studio} size="sm" />{studio?.name ?? t('studio.none')}</button>
</div> </div>
<div className="ids"> <div className="ids">
<StoreBadge store="ios" id={ios?.bundleId} off={!ios && (!!e || !app.project)}>{iosNow && <><span className="num strong">{iosNow.version}</span><PhaseChip r={iosNow} /></>}</StoreBadge> <StoreBadge store="ios" id={ios?.bundleId} off={!!e && !ios}>{iosNow && <><span className="num strong">{iosNow.version}</span><PhaseChip r={iosNow} /></>}</StoreBadge>
<StoreBadge store="android" id={android?.packageName} off={!android && (!!e || !app.project)}>{androidNow && <><span className="num strong">{androidNow.version}</span><PhaseChip r={androidNow} /></>}</StoreBadge> <StoreBadge store="android" id={android?.packageName} off={!!e && !android}>{androidNow && <><span className="num strong">{androidNow.version}</span><PhaseChip r={androidNow} /></>}</StoreBadge>
</div> </div>
</div> </div>
</div> </div>
@ -131,24 +61,22 @@ export function AppView({ app, tab }: { app: UnifiedApp; tab: AppTab }) {
{android && <button className="btn btn-ghost" onClick={() => open(PLAY_CONSOLE)} title={t('app.consoleHint')}><Icon name="external" />Play Console</button>} {android && <button className="btn btn-ghost" onClick={() => open(PLAY_CONSOLE)} title={t('app.consoleHint')}><Icon name="external" />Play Console</button>}
</div> </div>
</div> </div>
<AppControls app={app} />
{!app.project && <StoreOnlyBanner app={app} />}
<div className="tabs" role="tablist" aria-label={t('app.sections', { name })} onKeyDown={onKey}> <div className="tabs" role="tablist" aria-label={t('app.sections', { name })} onKeyDown={onKey}>
{tabs.map((x, i) => ( {APP_TABS.map((x, i) => (
<button key={x} ref={el => { tabRefs.current[i] = el; }} role="tab" id={`tab-${x}`} aria-selected={tab === x} aria-controls="tabpanel" tabIndex={tab === x ? 0 : -1} className="tab" onClick={() => setTab(x)}> <button key={x} ref={el => { tabs.current[i] = el; }} role="tab" id={`tab-${x}`} aria-selected={tab === x} aria-controls="tabpanel" tabIndex={tab === x ? 0 : -1} className="tab" onClick={() => setTab(x)}>
<Icon name={TAB_ICON[x]} />{t(TAB_KEY[x])} <Icon name={TAB_ICON[x]} />{t(TAB_KEY[x])}
</button> </button>
))} ))}
</div> </div>
<div role="tabpanel" id="tabpanel" aria-labelledby={`tab-${tab}`} className="stack" style={{ gap: 16 }}> <div role="tabpanel" id="tabpanel" aria-labelledby={`tab-${tab}`} className="stack" style={{ gap: 16 }}>
{tab === 'releases' && <ReleasesTab app={app} />} {tab === 'releases' && <ReleasesTab project={project} />}
{tab === 'catalog' && app.project && <CatalogTab project={app.project} />} {tab === 'catalog' && <CatalogTab project={project} />}
{tab === 'listings' && app.project && <ListingsTab project={app.project} />} {tab === 'listings' && <ListingsTab project={project} />}
{tab === 'health' && <HealthTab app={app} />} {tab === 'health' && <HealthTab project={project} />}
{tab === 'reviews' && <ReviewsTab app={app} />} {tab === 'reviews' && <ReviewsTab project={project} />}
{tab === 'testflight' && <TestFlightTab app={app} />} {tab === 'testflight' && <TestFlightTab project={project} />}
{tab === 'checks' && app.project && <ChecksTab project={app.project} />} {tab === 'checks' && <ChecksTab project={project} />}
</div> </div>
</div> </div>
); );

View file

@ -1,66 +0,0 @@
// Ignored: apps and whole store accounts left out of the portfolio, the sidebar and store reads. Restore brings them
// back (nothing on the stores changes either way).
import { t } from '../i18n';
import { withIgnored } from '../lib/identity';
import { useNav } from '../nav';
import { useData } from '../store';
import { Icon, StoreGlyph } from '../ui/icons';
import { AppIcon, Card, Empty, StoreOnlyTag, StudioMark } from '../ui/kit';
export function Ignored() {
const d = useData();
const nav = useNav();
const apps = d.apps.filter(a => a.ignored).sort((a, b) => a.name.localeCompare(b.name));
const accounts = d.accounts.filter(a => d.overrides.ignored.includes(`account:${a.id}`));
const restoreAll = () => d.updateOverrides(o => ({ ...o, ignored: [] }));
const empty = !apps.length && !accounts.length;
return (
<div className="page">
<div className="ph">
<div><h1>{t('nav.ignored')}</h1><p>{t('ignored.lead')}</p></div>
{!empty && <div className="actions"><button className="btn" onClick={restoreAll}><Icon name="eye" />{t('ignored.restoreAll')}</button></div>}
</div>
{empty ? <Card pad={false}><Empty compact illo="shield" title={t('ignored.emptyTitle')}>{t('ignored.emptyText')}</Empty></Card> : (
<>
<Card title={t('ignored.apps')} icon="layers" sub={t('ignored.appsSub', { count: apps.length })} pad={false}>
{apps.length ? (
<div className="list">
{apps.map(a => {
const s = d.studios.find(x => x.id === a.studio) ?? null;
return (
<div className="li" key={a.key}>
<AppIcon name={a.name} src={d.iconFor(a)} />
<div className="li-main">
<span className="li-title row" style={{ gap: 8 }}>{a.name}{!a.project && <StoreOnlyTag />}</span>
<span className="li-sub row" style={{ gap: 8 }}>
<StudioMark studio={s} size="sm" />{s?.name ?? t('studio.none')}
{a.ios && <span className="row" style={{ gap: 4 }}><StoreGlyph store="ios" className="ic13" /><span className="mono-id">{a.ios.app.bundleId}</span></span>}
{a.android && <span className="row" style={{ gap: 4 }}><StoreGlyph store="android" className="ic13" /><span className="mono-id">{a.android.app.id}</span></span>}
</span>
</div>
<button className="btn btn-sm" onClick={() => d.updateOverrides(o => withIgnored(o, a.ignoreKeys, false))}><Icon name="eye" />{t('ignored.restore')}</button>
</div>
);
})}
</div>
) : <div className="card-body"><p className="small muted">{t('ignored.noApps')}</p></div>}
</Card>
<Card title={t('ignored.accounts')} icon="key" sub={t('ignored.accountsSub')} pad={false}>
{accounts.length ? (
<div className="list">
{accounts.map(a => (
<div className="li" key={a.id}>
<span className="li-icon tone-bg-neutral"><StoreGlyph store={a.kind === 'play' ? 'android' : 'ios'} /></span>
<div className="li-main"><span className="li-title">{a.label}</span><span className="li-sub">{a.kind === 'play' ? t('acct.kindPlay') : t('acct.kindApple')} · {t('ignored.accountApps', { count: d.storeApps[a.id]?.value.apps.length ?? 0 })}</span></div>
<button className="btn btn-sm" onClick={() => d.updateOverrides(o => withIgnored(o, [`account:${a.id}`], false))}><Icon name="eye" />{t('ignored.restore')}</button>
</div>
))}
</div>
) : <div className="card-body"><p className="small muted">{t('ignored.noAccounts')}</p></div>}
</Card>
</>
)}
<p className="small muted">{t('ignored.howTo')} <button className="link" onClick={() => nav.go({ screen: 'settings', section: 'pairing' })}>{t('ignored.toPairing')}</button></p>
</div>
);
}

View file

@ -1,16 +1,14 @@
// Portfolio: every app of every studio on both stores. KPIs, a toolbar (search, studio chips with counts, sort, // Portfolio: every app on both stores. KPIs, one row per app (live version and state per store with its place on
// grouping), one row per app (live version and state per store with its place on the release track, next version, // the release track, next version, catalog parity, config check), what needs attention, and the workspace state.
// crash rate, catalog parity, config check), grouped by studio; then what needs attention and the workspace state. import { useEffect, useState } from 'react';
import { useEffect, useMemo, useState } from 'react'; import { api, type AppStatus, type Project, type StoreRelease, type ToolResult } from '../api';
import { api, type AppStatus, type StoreRelease, type ToolResult } from '../api';
import { type Key, t } from '../i18n'; import { type Key, t } from '../i18n';
import { ago, pct, share } from '../lib/format'; import { ago, pct, share } from '../lib/format';
import { filterSort, groupByStudio, type ListRow, type SortBy, studioCounts, type UnifiedApp } from '../lib/identity';
import { type Attention, attention, healthSeries, type HealthSnapshot, isError, laneOf, PLAY_THRESHOLDS, STAGES, storeNow, type Tone } from '../lib/model'; import { type Attention, attention, healthSeries, type HealthSnapshot, isError, laneOf, PLAY_THRESHOLDS, STAGES, storeNow, type Tone } from '../lib/model';
import { useNav } from '../nav'; import { useNav } from '../nav';
import { useData } from '../store'; import { useData } from '../store';
import { Icon, StoreGlyph } from '../ui/icons'; import { Icon, StoreGlyph } from '../ui/icons';
import { AppIcon, Card, Chip, Empty, Kpi, Notice, PhaseChip, Seg, Skeleton, Sparkline, StudioMark } from '../ui/kit'; import { AppIcon, Card, Chip, Empty, Kpi, Notice, PhaseChip, Skeleton, Sparkline } from '../ui/kit';
/** Tag of one app's offline config check. */ /** Tag of one app's offline config check. */
export function checkState(e: Pick<AppStatus, 'errors' | 'check'> | undefined): { text: string; tone: Tone } { export function checkState(e: Pick<AppStatus, 'errors' | 'check'> | undefined): { text: string; tone: Tone } {
@ -31,8 +29,9 @@ export function Pips({ r, store }: { r: StoreRelease | null; store: 'ios' | 'and
); );
} }
function StoreCell({ e, store, on }: { e: AppStatus | undefined; store: 'ios' | 'android'; on: boolean }) { function StoreCell({ e, store, project }: { e: AppStatus | undefined; store: 'ios' | 'android'; project: AppStatus | undefined }) {
if (!on) return <span className="muted small">{t('app.notOnStore')}</span>; const on = store === 'ios' ? project?.app?.platforms.ios : project?.app?.platforms.android;
if (project && !on) return <span className="muted small">{t('app.notOnStore')}</span>;
if (!e) return <span className="muted small">{t('common.unknown')}</span>; if (!e) return <span className="muted small">{t('common.unknown')}</span>;
const err = e.storeErrors[store]; const err = e.storeErrors[store];
if (err) return <span title={err}><Chip tone="warn">{t('portfolio.unreadable')}</Chip></span>; if (err) return <span title={err}><Chip tone="warn">{t('portfolio.unreadable')}</Chip></span>;
@ -65,19 +64,18 @@ function NextCell({ e }: { e: AppStatus | undefined }) {
} }
/** Last cached health read of every app (the Health tab reads it; the portfolio only shows what is saved). */ /** Last cached health read of every app (the Health tab reads it; the portfolio only shows what is saved). */
function useCachedHealth(targets: string[]): Record<string, { h: HealthSnapshot; at: string } | null> { function useCachedHealth(projects: Project[]): Record<string, { h: HealthSnapshot; at: string } | null> {
const [m, set] = useState<Record<string, { h: HealthSnapshot; at: string } | null>>({}); const [m, set] = useState<Record<string, { h: HealthSnapshot; at: string } | null>>({});
const key = targets.join(); const key = projects.map(p => p.id).join();
useEffect(() => { useEffect(() => {
for (const id of targets) { for (const p of projects) {
api.cached<ToolResult>('health', id).then(c => set(x => ({ ...x, [id]: c?.value.data ? { h: c.value.data as HealthSnapshot, at: c.at } : null })), () => {}); api.cached<ToolResult>('health', p.id).then(c => set(x => ({ ...x, [p.id]: c?.value.data ? { h: c.value.data as HealthSnapshot, at: c.at } : null })), () => {});
} }
}, [key]); // eslint-disable-line react-hooks/exhaustive-deps }, [key]); // eslint-disable-line react-hooks/exhaustive-deps
return m; return m;
} }
function HealthCell({ c, android }: { c: { h: HealthSnapshot; at: string } | null | undefined; android: boolean }) { function HealthCell({ c }: { c: { h: HealthSnapshot; at: string } | null | undefined }) {
if (!android) return <span className="muted small">{t('portfolio.healthNoPlay')}</span>;
if (!c) return <span className="muted small">{t('portfolio.healthNotRead')}</span>; if (!c) return <span className="muted small">{t('portfolio.healthNotRead')}</span>;
const play = c.h.play; const play = c.h.play;
if (!play) return <span className="muted small">{t('portfolio.healthNoPlay')}</span>; if (!play) return <span className="muted small">{t('portfolio.healthNoPlay')}</span>;
@ -107,110 +105,44 @@ function AttentionList({ items }: { items: Attention[] }) {
); );
} }
/** Newest store activity of an app (release record date), else when its folder was added. */
function updatedAt(a: UnifiedApp, l: AppStatus | undefined): string | null {
const dates = (l?.release.all ?? []).map(r => r.date).filter((x): x is string => !!x);
return dates.sort().at(-1) ?? a.project?.added ?? null;
}
const VIEW_KEY = 'storebound.portfolio.v1';
interface View { studio: string; sort: SortBy; group: boolean }
function loadView(): View {
try {
const v = JSON.parse(localStorage.getItem(VIEW_KEY) ?? '{}') as Partial<View>;
return { studio: typeof v.studio === 'string' ? v.studio : 'all', sort: v.sort === 'recent' || v.sort === 'name' ? v.sort : 'attention', group: v.group !== false };
} catch { return { studio: 'all', sort: 'attention', group: true }; }
}
export function Portfolio() { export function Portfolio() {
const d = useData(); const d = useData();
const nav = useNav(); const nav = useNav();
const [view, setViewState] = useState<View>(loadView); const open = (p: Project) => nav.go({ screen: 'app', appId: p.id, tab: 'releases' });
const [query, setQuery] = useState('');
const setView = (v: Partial<View>) => setViewState(x => { const n = { ...x, ...v }; try { localStorage.setItem(VIEW_KEY, JSON.stringify(n)); } catch { /* private mode */ } return n; });
const visible = useMemo(() => d.apps.filter(a => !a.ignored), [d.apps]);
const health = useCachedHealth(visible.map(a => a.target));
const open = (a: UnifiedApp) => nav.go({ screen: 'app', appId: a.key, tab: 'releases' });
const all = useMemo(() => visible.map(app => { if (d.ready && !d.projects.length) {
const e = d.statusFor(app), l = d.liveFor(app);
const att = attention(app.key, app.name, e, l, health[app.target]?.h);
return { app, e, l, att, attention: att.length, blockers: att.filter(x => x.tone === 'bad').length, updated: updatedAt(app, l) };
}), [visible, d, health]);
const counts = useMemo(() => studioCounts(visible), [visible]);
const studioOk = view.studio === 'all' || view.studio === 'none' || d.studios.some(s => s.id === view.studio);
const rows = filterSort(all as (ListRow & typeof all[number])[], { studio: studioOk ? view.studio : 'all', query, sort: view.sort }) as typeof all;
const grouped = view.group && d.studios.length ? groupByStudio(rows, d.studios) : [{ studio: undefined as string | null | undefined, rows }];
if (d.ready && !visible.length) {
return ( return (
<div className="page"> <div className="page">
<div className="ph"><div><h1>{t('nav.portfolio')}</h1><p>{t('portfolio.lead')}</p></div></div> <div className="ph"><div><h1>{t('nav.portfolio')}</h1><p>{t('portfolio.lead')}</p></div></div>
<Card pad={false}> <Card pad={false}>
<Empty illo="apps" title={t('portfolio.emptyTitle')} actions={<> <Empty illo="apps" title={t('portfolio.emptyTitle')} actions={<>
<button className="btn btn-primary" onClick={() => nav.go({ screen: 'accounts' })}><Icon name="building" />{t('portfolio.emptyAccounts')}</button> <button className="btn btn-primary" onClick={() => nav.go({ screen: 'apps' })}><Icon name="folderPlus" />{t('action.addFolder')}</button>
<button className="btn" onClick={() => nav.go({ screen: 'apps' })}><Icon name="folderPlus" />{t('action.addFolder')}</button> <button className="btn" onClick={nav.openWelcome}><Icon name="sparkle" />{t('action.welcome')}</button>
<button className="btn btn-ghost" onClick={nav.openWelcome}><Icon name="sparkle" />{t('action.welcome')}</button>
</>}>{t('portfolio.emptyText')}</Empty> </>}>{t('portfolio.emptyText')}</Empty>
</Card> </Card>
</div> </div>
); );
} }
const shown = rows.map(r => r.l).filter((x): x is AppStatus => !!x); const health = useCachedHealth(d.projects);
const releases = shown.flatMap(l => l.release.all ?? [l.release.current?.ios, l.release.current?.android, l.release.next?.ios, l.release.next?.android].filter((x): x is StoreRelease => !!x)); const rows = d.projects.map(p => ({ p, e: d.statusOf(p), l: d.liveOf(p) }));
const stores = rows.reduce((n, r) => n + (r.app.ios || r.e?.app?.platforms.ios ? 1 : 0) + (r.app.android || r.e?.app?.platforms.android ? 1 : 0), 0); const lives = rows.map(r => r.l).filter((x): x is AppStatus => !!x);
const liveCount = shown.reduce((n, l) => n + (l.release.current?.ios ? 1 : 0) + (l.release.current?.android ? 1 : 0), 0); const all = lives.flatMap(l => l.release.all ?? [l.release.current?.ios, l.release.current?.android, l.release.next?.ios, l.release.next?.android].filter((x): x is StoreRelease => !!x));
const rolling = releases.filter(r => r.phase === 'rollout'); const stores = rows.reduce((n, r) => n + (r.e?.app?.platforms.ios ? 1 : 0) + (r.e?.app?.platforms.android ? 1 : 0), 0);
const review = releases.filter(r => r.phase === 'review'); const liveCount = lives.reduce((n, l) => n + (l.release.current?.ios ? 1 : 0) + (l.release.current?.android ? 1 : 0), 0);
const att = rows.flatMap(r => r.att); const rolling = all.filter(r => r.phase === 'rollout');
const review = all.filter(r => r.phase === 'review');
const att = rows.flatMap(r => attention(r.p.id, r.e?.app?.name ?? r.p.name, r.e, r.l, health[r.p.id]?.h));
const blockers = att.filter(a => a.tone === 'bad').length; const blockers = att.filter(a => a.tone === 'bad').length;
const known = shown.length > 0; const known = lives.length > 0;
const iosApps = rows.filter(r => r.app.ios || r.e?.app?.platforms.ios).length, androidApps = rows.filter(r => r.app.android || r.e?.app?.platforms.android).length; const iosApps = rows.filter(r => r.e?.app?.platforms.ios).length, androidApps = rows.filter(r => r.e?.app?.platforms.android).length;
const storeOnly = rows.filter(r => !r.app.project).length;
const neverImported = d.accounts.filter(a => !d.storeApps[a.id]).length;
const row = (r: typeof all[number]) => {
const { app, e, l } = r;
const st = app.project ? checkState(e) : null;
const cat = l?.catalog ?? e?.catalog;
const ios = !!(app.ios || e?.app?.platforms.ios), android = !!(app.android || e?.app?.platforms.android);
const sub = app.ios?.app.bundleId ?? e?.app?.platforms.ios?.bundleId ?? app.android?.app.id ?? e?.app?.platforms.android?.packageName ?? '';
return (
<tr key={app.key} className="clickable" onClick={() => open(app)}>
<td>
<div className="cell-app">
<AppIcon name={app.name} src={d.iconFor(app)} />
<div className="t">
<button className="link n" onClick={ev => { ev.stopPropagation(); open(app); }}>{e?.app?.name && app.project ? e.app.name : app.name}</button>
<div className="s"><span className="mono-id">{sub}</span>{!app.project && <span className="so-inline" title={t('apps.storeOnlyHint')}><Icon name="cloud" /><span className="sr">{t('apps.storeOnly')}</span></span>}</div>
</div>
</div>
</td>
<td>{e || !app.project ? <StoreCell e={l} store="ios" on={ios} /> : <Skeleton lines={2} />}</td>
<td>{e || !app.project ? <StoreCell e={l} store="android" on={android} /> : <Skeleton lines={2} />}</td>
<td><NextCell e={l} /></td>
<td><HealthCell c={health[app.target]} android={android} /></td>
<td>
{!app.project ? <span className="small muted">{t('portfolio.noConfig')}</span> : cat ? (
<div className="mini">
<span className="num small strong">{t('portfolio.products', { count: cat.products })} · {t('portfolio.subs', { count: cat.subscriptions })}</span>
{cat.checked === 'live' ? (cat.ok ? <Chip tone="ok">{t('portfolio.inParity')}</Chip> : <Chip tone="warn">{t('portfolio.differs', { count: cat.missingIos.length + cat.missingAndroid.length + cat.onlyIos.length + cat.onlyAndroid.length })}</Chip>)
: <span className="small muted">{t('portfolio.configOnly')}</span>}
</div>
) : <span className="muted small">–</span>}
</td>
<td className="right">{st ? <Chip tone={st.tone}>{st.text}</Chip> : <span className="muted small">–</span>}</td>
</tr>
);
};
return ( return (
<div className="page"> <div className="page">
<div className="ph"> <div className="ph">
<div><h1>{t('nav.portfolio')}</h1><p>{t('portfolio.subStudios', { count: visible.length, stores, studios: d.studios.length })}</p></div> <div><h1>{t('nav.portfolio')}</h1><p>{t('portfolio.sub', { count: d.projects.length, stores })}</p></div>
<div className="actions"> <div className="actions">
<button className="btn" onClick={() => d.importApps()} disabled={d.importBusy || !d.accounts.length} title={t('action.importAppsHint')}><Icon name="download" className={d.importBusy ? 'spin' : undefined} />{t('action.importApps')}</button> <button className="btn" onClick={() => d.refreshPortfolio(false)} disabled={!!d.portfolioBusy}><Icon name="shield" />{t('action.checkConfigs')}</button>
<button className="btn btn-primary" onClick={() => d.refreshPortfolio(true)} disabled={!!d.portfolioBusy} title={t('action.readStoresHint')}> <button className="btn btn-primary" onClick={() => d.refreshPortfolio(true)} disabled={!!d.portfolioBusy} title={t('action.readStoresHint')}>
<Icon name="refresh" className={d.portfolioBusy === 'live' ? 'spin' : undefined} />{d.portfolioBusy === 'live' ? t('action.reading') : t('action.readStores')} <Icon name="refresh" className={d.portfolioBusy === 'live' ? 'spin' : undefined} />{d.portfolioBusy === 'live' ? t('action.reading') : t('action.readStores')}
</button> </button>
@ -218,66 +150,67 @@ export function Portfolio() {
</div> </div>
{d.portfolioError && <Notice tone="bad">{d.portfolioError}</Notice>} {d.portfolioError && <Notice tone="bad">{d.portfolioError}</Notice>}
{neverImported > 0 && <Notice tone="info" icon="download" action={<button className="btn btn-sm" onClick={() => d.importApps()} disabled={d.importBusy}>{t('action.importApps')}</button>}>{t('portfolio.notImported', { count: neverImported })}</Notice>}
{!known && d.ready && <Notice tone="info" action={<button className="btn btn-sm" onClick={() => d.refreshPortfolio(true)}>{t('action.readStores')}</button>}>{t('portfolio.notReadNotice')}</Notice>} {!known && d.ready && <Notice tone="info" action={<button className="btn btn-sm" onClick={() => d.refreshPortfolio(true)}>{t('action.readStores')}</button>}>{t('portfolio.notReadNotice')}</Notice>}
<div className="kpis"> <div className="kpis">
<Kpi icon="layers" label={t('kpi.apps')} value={rows.length} sub={t('kpi.appsSubStore', { ios: iosApps, android: androidApps, store: storeOnly })} /> <Kpi icon="layers" label={t('kpi.apps')} value={d.projects.length} sub={t('kpi.appsSub', { ios: iosApps, android: androidApps })} />
<Kpi icon="check" label={t('kpi.live')} value={known ? liveCount : '–'} sub={known ? t('kpi.liveSub', { count: stores }) : t('kpi.notRead')} /> <Kpi icon="check" label={t('kpi.live')} value={known ? liveCount : '–'} sub={known ? t('kpi.liveSub', { count: stores }) : t('kpi.notRead')} />
<Kpi icon="rocket" label={t('kpi.rolling')} value={known ? rolling.length : '–'} sub={!known ? t('kpi.notRead') : rolling.length ? [...new Set(rolling.map(r => r.version))].map(v => `${v}: ${rolling.filter(r => r.version === v).map(r => `${r.store === 'ios' ? 'iOS' : 'Android'}${r.fraction !== null ? ` ${share(r.fraction)}` : ''}`).join(', ')}`).join(' · ') : t('kpi.none')} /> <Kpi icon="rocket" label={t('kpi.rolling')} value={known ? rolling.length : '–'} sub={!known ? t('kpi.notRead') : rolling.length ? [...new Set(rolling.map(r => r.version))].map(v => `${v}: ${rolling.filter(r => r.version === v).map(r => `${r.store === 'ios' ? 'iOS' : 'Android'}${r.fraction !== null ? ` ${share(r.fraction)}` : ''}`).join(', ')}`).join(' · ') : t('kpi.none')} />
<Kpi icon="clock" label={t('kpi.review')} value={known ? review.length : '–'} sub={!known ? t('kpi.notRead') : review.length ? review.map(r => `${r.store === 'ios' ? 'iOS' : 'Android'} ${r.version}`).join(' · ') : t('kpi.none')} tone={review.length ? 'warn' : undefined} /> <Kpi icon="clock" label={t('kpi.review')} value={known ? review.length : '–'} sub={!known ? t('kpi.notRead') : review.length ? review.map(r => `${r.store === 'ios' ? 'iOS' : 'Android'} ${r.version}`).join(' · ') : t('kpi.none')} tone={review.length ? 'warn' : undefined} />
<Kpi icon="alert" label={t('kpi.attention')} value={att.length} sub={blockers ? t('kpi.blockers', { count: blockers }) : t('kpi.noBlockers')} tone={blockers ? 'bad' : att.length ? 'warn' : undefined} /> <Kpi icon="alert" label={t('kpi.attention')} value={att.length} sub={blockers ? t('kpi.blockers', { count: blockers }) : t('kpi.noBlockers')} tone={blockers ? 'bad' : att.length ? 'warn' : undefined} />
</div> </div>
<div className="toolbar" role="toolbar" aria-label={t('portfolio.toolbar')}>
<div className="search-input grow-0"><Icon name="search" /><input className="input" value={query} onChange={e => setQuery(e.target.value)} placeholder={t('portfolio.search')} aria-label={t('portfolio.search')} /></div>
<div className="fchips" role="group" aria-label={t('portfolio.studioFilter')}>
<button className="fchip" aria-pressed={view.studio === 'all' || !studioOk} onClick={() => setView({ studio: 'all' })}>{t('portfolio.allStudios')}<span className="n">{visible.length}</span></button>
{d.studios.map(s => (
<button key={s.id} className="fchip" aria-pressed={view.studio === s.id} onClick={() => setView({ studio: s.id })}><StudioMark studio={s} size="sm" />{s.name}<span className="n">{counts[s.id] ?? 0}</span></button>
))}
{d.studios.length > 0 && (counts[''] ?? 0) > 0 && <button className="fchip" aria-pressed={view.studio === 'none'} onClick={() => setView({ studio: 'none' })}><StudioMark studio={null} size="sm" />{t('studio.none')}<span className="n">{counts['']}</span></button>}
</div>
<span className="grow" />
<Seg value={view.sort} onChange={sort => setView({ sort })} label={t('portfolio.sort')} options={[['attention', t('portfolio.sortAttention'), 'alert'], ['recent', t('portfolio.sortRecent'), 'clock'], ['name', t('portfolio.sortName')]]} />
{d.studios.length > 0 && <label className="check"><input type="checkbox" checked={view.group} onChange={e => setView({ group: e.target.checked })} />{t('portfolio.group')}</label>}
</div>
<Card title={t('portfolio.apps')} icon="portfolio" sub={known ? t('portfolio.appsSub', { when: ago(d.live?.at) }) : t('portfolio.appsSubOffline')} pad={false} <Card title={t('portfolio.apps')} icon="portfolio" sub={known ? t('portfolio.appsSub', { when: ago(d.live?.at) }) : t('portfolio.appsSubOffline')} pad={false}
actions={<div className="legend-row"><span><span className="pips"><b className="on" /></span>{t('legend.done')}</span><span>{t('legend.stages')}</span></div>}> actions={<div className="legend-row"><span><span className="pips"><b className="on" /></span>{t('legend.done')}</span><span>{t('legend.stages')}</span></div>}>
{rows.length ? (
<div className="table-wrap"> <div className="table-wrap">
<table className="table"> <table className="table">
<thead><tr> <thead><tr>
<th>{t('col.app')}</th><th>App Store</th><th>Google Play</th><th>{t('col.next')}</th><th>{t('col.crash')}</th><th>{t('col.catalog')}</th><th className="right">{t('col.config')}</th> <th>{t('col.app')}</th><th>App Store</th><th>Google Play</th><th>{t('col.next')}</th><th>{t('col.crash')}</th><th>{t('col.catalog')}</th><th className="right">{t('col.config')}</th>
</tr></thead> </tr></thead>
{grouped.map(g => { <tbody>
const s = g.studio === undefined ? undefined : d.studios.find(x => x.id === g.studio) ?? null; {rows.map(({ p, e, l }) => {
const st = checkState(e);
const cat = l?.catalog ?? e?.catalog;
return ( return (
<tbody key={g.studio ?? (g.studio === null ? 'none' : 'all')}> <tr key={p.id} className="clickable" onClick={() => open(p)}>
{s !== undefined && ( <td>
<tr className="group-row"><td colSpan={7}> <div className="cell-app">
<span className="row" style={{ gap: 10 }}><StudioMark studio={s} size="sm" /><b>{s?.name ?? t('studio.none')}</b><span className="muted small">{t('portfolio.groupCount', { count: g.rows.length })} · {t('portfolio.groupAccounts', { count: d.accounts.filter(a => (a.studio ?? null) === (g.studio ?? null)).length })}</span></span> <AppIcon name={e?.app?.name ?? p.name} src={d.icons[p.id]} />
</td></tr> <div className="t">
)} <button className="link n" onClick={ev => { ev.stopPropagation(); open(p); }}>{e?.app?.name ?? p.name}</button>
{g.rows.map(row)} <div className="s mono-id">{e?.app?.platforms.ios?.bundleId ?? e?.app?.platforms.android?.packageName ?? ''}</div>
</tbody> </div>
</div>
</td>
<td>{e ? <StoreCell e={l} store="ios" project={e} /> : <Skeleton lines={2} />}</td>
<td>{e ? <StoreCell e={l} store="android" project={e} /> : <Skeleton lines={2} />}</td>
<td><NextCell e={l} /></td>
<td><HealthCell c={health[p.id]} /></td>
<td>
{cat ? (
<div className="mini">
<span className="num small strong">{t('portfolio.products', { count: cat.products })} · {t('portfolio.subs', { count: cat.subscriptions })}</span>
{cat.checked === 'live' ? (cat.ok ? <Chip tone="ok">{t('portfolio.inParity')}</Chip> : <Chip tone="warn">{t('portfolio.differs', { count: cat.missingIos.length + cat.missingAndroid.length + cat.onlyIos.length + cat.onlyAndroid.length })}</Chip>)
: <span className="small muted">{t('portfolio.configOnly')}</span>}
</div>
) : <span className="muted small">–</span>}
</td>
<td className="right"><Chip tone={st.tone}>{st.text}</Chip></td>
</tr>
); );
})} })}
</tbody>
</table> </table>
</div> </div>
) : <Empty compact illo="unknown" title={t('portfolio.noMatch')}>{t('portfolio.noMatchText')}</Empty>}
</Card> </Card>
<div className="grid g-main-side"> <div className="grid g-main-side">
<Card title={t('portfolio.attention')} icon="alert" sub={t('portfolio.attentionSub')} pad={false}><AttentionList items={[...att].sort((a, b) => (a.tone === 'bad' ? 0 : 1) - (b.tone === 'bad' ? 0 : 1))} /></Card> <Card title={t('portfolio.attention')} icon="alert" sub={t('portfolio.attentionSub')} pad={false}><AttentionList items={att} /></Card>
<Card title={t('portfolio.workspace')} icon="settings"> <Card title={t('portfolio.workspace')} icon="settings">
<dl className="kv"> <dl className="kv">
<dt>{t('nav.studios')}</dt><dd>{d.studios.length ? t('portfolio.studiosN', { count: d.studios.length }) : <button className="link" onClick={() => nav.go({ screen: 'accounts' })}>{t('studio.add')}</button>}</dd>
<dt>{t('nav.accounts')}</dt><dd>{d.accounts.length ? t('portfolio.accounts', { play: d.accounts.filter(a => a.kind === 'play').length, apple: d.accounts.filter(a => a.kind === 'apple').length }) : <button className="link" onClick={() => nav.go({ screen: 'accounts' })}>{t('action.addAccount')}</button>}</dd> <dt>{t('nav.accounts')}</dt><dd>{d.accounts.length ? t('portfolio.accounts', { play: d.accounts.filter(a => a.kind === 'play').length, apple: d.accounts.filter(a => a.kind === 'apple').length }) : <button className="link" onClick={() => nav.go({ screen: 'accounts' })}>{t('action.addAccount')}</button>}</dd>
<dt>{t('portfolio.folders')}</dt><dd>{t('portfolio.foldersN', { count: d.projects.length, store: storeOnly })}</dd>
<dt>{t('nav.ignored')}</dt><dd>{d.apps.filter(a => a.ignored).length ? <button className="link" onClick={() => nav.go({ screen: 'ignored' })}>{t('portfolio.ignoredN', { count: d.apps.filter(a => a.ignored).length })}</button> : t('kpi.none')}</dd>
<dt>{t('portfolio.storesRead')}</dt><dd>{d.live ? ago(d.live.at) : t('time.never')}</dd> <dt>{t('portfolio.storesRead')}</dt><dd>{d.live ? ago(d.live.at) : t('time.never')}</dd>
<dt>{t('portfolio.tools')}</dt><dd>{d.sidecar?.tools ? t('portfolio.toolsFound', { found: d.sidecar.tools.tools.filter(x => x.found).length, total: d.sidecar.tools.tools.length }) : '–'}</dd>
<dt>CLI</dt><dd>{d.sidecar ? `storebound ${d.sidecar.version}` : d.sidecarError ?? '–'}</dd> <dt>CLI</dt><dd>{d.sidecar ? `storebound ${d.sidecar.version}` : d.sidecarError ?? '–'}</dd>
</dl> </dl>
</Card> </Card>

View file

@ -1,241 +1,65 @@
// Settings, every part of the app in one place: studios and accounts, app pairing and the ignore list, store reads import { useState } from 'react';
// (on launch, every N minutes, how many apps at once, icons), the offline cache, language and theme, notifications, import { api, errorText } from '../api';
// local tools, the CLI sidecar, privacy, keyboard shortcuts, updates and reset. A section list on the left jumps. import { t } from '../i18n';
import { useEffect, useState } from 'react';
import { api, type CacheInfo, errorText, type Settings as S } from '../api';
import { type Key, t } from '../i18n';
import { ago, bytes, date, num } from '../lib/format';
import { pairCandidates, type UnifiedApp, withPair, withUnpair } from '../lib/identity';
import { useNav } from '../nav'; import { useNav } from '../nav';
import { usePrefs } from '../prefs-ctx'; import { usePrefs } from '../prefs-ctx';
import { useData } from '../store'; import { useData } from '../store';
import { Icon, type IconName, StoreGlyph } from '../ui/icons'; import { Icon } from '../ui/icons';
import { AppIcon, Card, Chip, Kbd, MOD, Notice, Seg, StudioMark } from '../ui/kit'; import { Card, Kbd, MOD, Notice, Seg } from '../ui/kit';
export const SECTIONS: [string, IconName, Key][] = [ export function Settings({ onTheme: _onTheme }: { onTheme: () => void }) {
['studios', 'building', 'set.studios'], ['pairing', 'link', 'set.pairing'], ['refresh', 'refresh', 'set.refresh'], ['cache', 'database', 'set.cache'],
['appearance', 'sun', 'settings.appearance'], ['notifications', 'bell', 'set.notifications'], ['dependencies', 'package', 'nav.dependencies'], ['cli', 'terminal', 'set.cli'],
['privacy', 'shield', 'set.privacy'], ['shortcuts', 'keyboard', 'settings.shortcuts'], ['updates', 'download', 'set.updates'], ['reset', 'rotate', 'set.reset'],
];
function Toggle({ id, label, hint, checked, onChange }: { id: string; label: string; hint?: string; checked: boolean; onChange: (v: boolean) => void }) {
return (
<label className="toggle-row" htmlFor={id}>
<span className="grow"><span className="strong">{label}</span>{hint && <span className="small muted">{hint}</span>}</span>
<input id={id} type="checkbox" role="switch" className="switch" checked={checked} onChange={e => onChange(e.target.checked)} />
</label>
);
}
function PairRow({ app, all }: { app: UnifiedApp; all: UnifiedApp[] }) {
const d = useData();
const cands = pairCandidates(app, all);
const r = (app.ios ?? app.android)!;
return (
<tr>
<td><div className="cell-app"><AppIcon name={app.name} src={d.iconFor(app)} /><div className="t"><span className="n">{app.name}</span><div className="s mono-id">{r.app.bundleId}</div></div></div></td>
<td>{app.ios && app.android ? <span className="row" style={{ gap: 6 }}><StoreGlyph store="ios" className="ic13" /><StoreGlyph store="android" className="ic13" />{t(`pair.${app.pairing}` as Key)}</span>
: <span className="row" style={{ gap: 6 }}><StoreGlyph store={app.ios ? 'ios' : 'android'} className="ic13" />{t('pair.single')}</span>}</td>
<td className="right">
{app.ios && app.android ? <button className="btn btn-sm btn-ghost" onClick={() => d.updateOverrides(o => withUnpair(o, app.ios!.key, app.android!.key))}><Icon name="unlink" />{t('app.unpair')}</button>
: cands.length ? (
<select className="input input-sm" value="" aria-label={t('app.pairWithName', { name: app.name })} onChange={e => {
const other = cands.find(c => c.key === e.target.value);
if (other) d.updateOverrides(o => withPair(o, (app.ios ?? other.ios)!.key, (app.android ?? other.android)!.key));
}}>
<option value="">{t('app.pairWith')}</option>
{cands.slice(0, 30).map(c => <option key={c.key} value={c.key}>{c.name} · {(c.ios ?? c.android)!.app.bundleId}</option>)}
</select>
) : <span className="small muted">{t('set.noCandidates')}</span>}
</td>
</tr>
);
}
export function Settings({ onTheme: _onTheme, section }: { onTheme: () => void; section?: string }) {
const d = useData(); const d = useData();
const nav = useNav(); const nav = useNav();
const { prefs, update } = usePrefs(); const { prefs, update } = usePrefs();
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [cache, setCache] = useState<CacheInfo | null>(null);
const [active, setActive] = useState(section ?? 'studios');
const s = d.settings;
const tools = d.sidecar?.tools; const tools = d.sidecar?.tools;
const set = (patch: (x: S) => S) => d.updateSettings(patch(s)); const clear = () => api.clearCache().then(() => d.toast({ kind: 'ok', title: t('settings.cacheCleared') }), e => setError(errorText(e)));
const loadCache = () => api.cacheInfo().then(setCache, () => {});
useEffect(() => { loadCache(); }, []);
useEffect(() => { if (section) { setActive(section); document.getElementById(`set-${section}`)?.scrollIntoView({ block: 'start' }); } }, [section]);
const jump = (id: string) => { setActive(id); document.getElementById(`set-${id}`)?.scrollIntoView({ block: 'start', behavior: prefs.motion === 'reduce' ? 'auto' : 'smooth' }); };
const clear = () => api.clearCache().then(() => { d.toast({ kind: 'ok', title: t('settings.cacheCleared') }); loadCache(); }, e => setError(errorText(e)));
const reset = async () => {
try {
if (await api.reset()) {
try { localStorage.clear(); } catch { /* private mode */ }
await d.reload();
d.toast({ kind: 'ok', title: t('set.resetDone') });
nav.openWelcome();
}
} catch (e) { setError(errorText(e)); }
};
const storeOnly = d.apps.filter(a => !a.project && !a.ignored);
const paired = storeOnly.filter(a => a.ios && a.android);
const singles = storeOnly.filter(a => !(a.ios && a.android));
return ( return (
<div className="page"> <div className="page">
<div className="ph"><div><h1>{t('nav.settings')}</h1><p>{t('set.lead')}</p></div></div> <div className="ph"><div><h1>{t('nav.settings')}</h1><p>{t('settings.lead')}</p></div></div>
{error && <Notice tone="bad">{error}</Notice>} {error && <Notice tone="bad">{error}</Notice>}
<div className="set-layout"> <div className="grid g2" style={{ alignItems: 'start' }}>
<nav className="set-nav" aria-label={t('set.sections')}> <Card title={t('settings.appearance')} icon="sun">
{SECTIONS.map(([id, icon, key]) => (
<button key={id} className="nav" aria-current={active === id ? 'true' : undefined} onClick={() => jump(id)}><Icon name={icon} /><span className="grow">{t(key)}</span></button>
))}
</nav>
<div className="stack set-body" style={{ gap: 16 }}>
<Card id="set-studios" title={t('set.studios')} icon="building" sub={t('set.studiosSub')} className="set-card" actions={<button className="btn btn-sm" onClick={() => nav.go({ screen: 'accounts' })}>{t('set.manage')}<Icon name="arrowRight" /></button>}>
{d.studios.length ? (
<div className="studio-sum">
{d.studios.map(st => {
const accts = d.accounts.filter(a => a.studio === st.id);
return (
<button key={st.id} className="studio-sum-item" onClick={() => nav.go({ screen: 'accounts', section: st.id })}>
<StudioMark studio={st} size="md" />
<span className="stack" style={{ gap: 2 }}><b>{st.name}</b><span className="small muted">{t('set.studioLine', { play: accts.filter(a => a.kind === 'play').length, apple: accts.filter(a => a.kind === 'apple').length, apps: d.apps.filter(a => a.studio === st.id && !a.ignored).length })}</span></span>
</button>
);
})}
</div>
) : <p className="small muted">{t('set.noStudios')}</p>}
</Card>
<Card id="set-pairing" title={t('set.pairing')} icon="link" sub={t('set.pairingSub')} pad={false} className="set-card">
{storeOnly.length ? (
<table className="table">
<thead><tr><th>{t('col.app')}</th><th>{t('set.pairedHow')}</th><th className="right"><span className="sr">{t('col.actions')}</span></th></tr></thead>
<tbody>{[...paired, ...singles].map(a => <PairRow key={a.key} app={a} all={d.apps} />)}</tbody>
</table>
) : <div className="card-body"><p className="small muted">{t('set.noStoreOnly')}</p></div>}
<div className="card-foot"><Icon name="eyeOff" />{t('set.ignoredLine', { count: d.apps.filter(a => a.ignored).length, accounts: d.overrides.ignored.filter(i => i.startsWith('account:')).length })}
<button className="link" onClick={() => nav.go({ screen: 'ignored' })}>{t('set.openIgnored')}</button></div>
</Card>
<Card id="set-refresh" title={t('set.refresh')} icon="refresh" sub={t('set.refreshSub')} className="set-card">
<div className="form"> <div className="form">
<div className="field"><span className="legend">{t('set.autoRefresh')}</span>
<Seg value={String(s.refresh.autoMinutes) as '0'} label={t('set.autoRefresh')} onChange={v => set(x => ({ ...x, refresh: { ...x.refresh, autoMinutes: Number(v) as S['refresh']['autoMinutes'] } }))}
options={[['0', t('set.off')], ['15', t('set.min', { n: 15 })], ['30', t('set.min', { n: 30 })], ['60', t('set.hour', { n: 1 })], ['180', t('set.hour', { n: 3 })], ['720', t('set.hour', { n: 12 })]]} />
<span className="hint">{t('set.autoHint')}</span></div>
<Toggle id="on-launch" label={t('set.onLaunch')} hint={t('set.onLaunchHint')} checked={s.refresh.onLaunch} onChange={v => set(x => ({ ...x, refresh: { ...x.refresh, onLaunch: v } }))} />
<Toggle id="icons" label={t('set.icons')} hint={t('set.iconsHint')} checked={s.refresh.icons} onChange={v => set(x => ({ ...x, refresh: { ...x.refresh, icons: v } }))} />
<div className="field"><label htmlFor="parallel">{t('set.parallel')}</label>
<select id="parallel" className="input" style={{ width: 120 }} value={s.refresh.parallel} onChange={e => set(x => ({ ...x, refresh: { ...x.refresh, parallel: Number(e.target.value) } }))}>
{[1, 2, 3, 4, 6, 8].map(n => <option key={n} value={n}>{n}</option>)}
</select><span className="hint">{t('set.parallelHint')}</span></div>
<div className="actions">
<button className="btn btn-sm" onClick={() => d.importApps()} disabled={d.importBusy || !d.accounts.length}><Icon name="download" />{t('action.importApps')}</button>
<button className="btn btn-sm" onClick={() => d.refreshPortfolio(true)} disabled={!!d.portfolioBusy}><Icon name="refresh" />{t('action.readStores')}</button>
<span className="small muted">{d.live ? t('foot.lastRead', { when: ago(d.live.at) }) : t('foot.neverRead')}</span>
</div>
</div>
</Card>
<Card id="set-cache" title={t('set.cache')} icon="database" sub={t('set.cacheSub')} className="set-card">
<div className="form">
<dl className="kv">
<dt>{t('set.cacheSize')}</dt><dd>{cache ? `${bytes(cache.file_bytes)} · ${t('set.cacheRows', { count: cache.rows })}` : '–'}</dd>
<dt>{t('set.cacheOldest')}</dt><dd>{cache?.oldest ? `${date(cache.oldest)} (${ago(cache.oldest)})` : '–'}</dd>
</dl>
<div className="field"><span className="legend">{t('set.keep')}</span>
<Seg value={String(s.cache.keepDays) as '0'} label={t('set.keep')} onChange={v => set(x => ({ ...x, cache: { keepDays: Number(v) as S['cache']['keepDays'] } })).then(loadCache)}
options={[['7', t('set.days', { n: 7 })], ['30', t('set.days', { n: 30 })], ['90', t('set.days', { n: 90 })], ['365', t('set.year')], ['0', t('set.always')]]} /></div>
<div className="actions"><button className="btn btn-sm" onClick={clear}><Icon name="trash" />{t('settings.clearCache')}</button></div>
<p className="small muted">{t('settings.dataText')}</p>
</div>
</Card>
<Card id="set-appearance" title={t('settings.appearance')} icon="sun" className="set-card">
<div className="form">
<div className="field" role="group" aria-label={t('settings.language')}><span className="legend">{t('settings.language')}</span>
<Seg value={prefs.lang} onChange={lang => update({ ...prefs, lang })} label={t('settings.language')} options={[['system', t('settings.system')], ['en', 'English'], ['tr', 'Türkçe']]} /></div>
<div className="field" role="group" aria-label={t('settings.theme')}><span className="legend">{t('settings.theme')}</span> <div className="field" role="group" aria-label={t('settings.theme')}><span className="legend">{t('settings.theme')}</span>
<Seg value={prefs.theme} onChange={theme => update({ ...prefs, theme })} label={t('settings.theme')} options={[['system', t('settings.system'), 'settings'], ['light', t('settings.light'), 'sun'], ['dark', t('settings.dark'), 'moon']]} /></div> <Seg value={prefs.theme} onChange={theme => update({ ...prefs, theme })} label={t('settings.theme')} options={[['system', t('settings.system'), 'settings'], ['light', t('settings.light'), 'sun'], ['dark', t('settings.dark'), 'moon']]} /></div>
<div className="field" role="group" aria-label={t('settings.motion')}><span className="legend">{t('settings.motion')}</span> <div className="field" role="group" aria-label={t('settings.motion')}><span className="legend">{t('settings.motion')}</span>
<Seg value={prefs.motion} onChange={motion => update({ ...prefs, motion })} label={t('settings.motion')} options={[['system', t('settings.followSystem')], ['reduce', t('settings.reduce')]]} /></div> <Seg value={prefs.motion} onChange={motion => update({ ...prefs, motion })} label={t('settings.motion')} options={[['system', t('settings.followSystem')], ['reduce', t('settings.reduce')]]} /></div>
<div className="field" role="group" aria-label={t('settings.language')}><span className="legend">{t('settings.language')}</span>
<Seg value={prefs.lang} onChange={lang => update({ ...prefs, lang })} label={t('settings.language')} options={[['system', t('settings.system')], ['en', 'English'], ['tr', 'Türkçe']]} /></div>
</div> </div>
</Card> </Card>
<Card title={t('settings.shortcuts')} icon="keyboard">
<Card id="set-notifications" title={t('set.notifications')} icon="bell" sub={t('set.notificationsSub')} className="set-card">
<div className="form">
<Toggle id="n-review" label={t('set.nReview')} hint={t('set.nReviewHint')} checked={s.notify.reviewState} onChange={v => set(x => ({ ...x, notify: { ...x.notify, reviewState: v } }))} />
<Toggle id="n-low" label={t('set.nLow')} hint={t('set.nLowHint')} checked={s.notify.lowReviews} onChange={v => set(x => ({ ...x, notify: { ...x.notify, lowReviews: v } }))} />
<Toggle id="n-crash" label={t('set.nCrash')} hint={t('set.nCrashHint')} checked={s.notify.crash} onChange={v => set(x => ({ ...x, notify: { ...x.notify, crash: v } }))} />
<div className="actions"><button className="btn btn-sm" onClick={() => api.notify(t('set.testTitle'), t('set.testBody')).catch(e => setError(errorText(e)))}><Icon name="bell" />{t('set.testNotify')}</button></div>
</div>
</Card>
<Card id="set-dependencies" title={t('nav.dependencies')} icon="package" className="set-card" actions={<button className="btn btn-sm" onClick={() => nav.go({ screen: 'dependencies' })}>{t('set.manage')}<Icon name="arrowRight" /></button>}>
{tools ? (
<div className="dep-sum">
{tools.tools.map(x => <span key={x.id} className="row small" style={{ gap: 6 }}><i className={`dot ${x.found ? 'ok' : ''}`} />{x.name}{x.version ? <span className="muted num">{x.version}</span> : null}{x.source === 'app' && <Chip tone="outline">{t('set.appCopy')}</Chip>}</span>)}
</div>
) : <p className="small muted">–</p>}
<p className="small muted" style={{ marginTop: 10 }}>{t('set.depsText')}</p>
</Card>
<Card id="set-cli" title={t('set.cli')} icon="terminal" className="set-card">
<dl className="kv">
<dt>{t('settings.app')}</dt><dd>{d.info ? `storebound desktop ${d.info.version}${d.info.debug ? ` (${t('settings.debug')})` : ''} · ${d.info.platform}` : '–'}</dd>
<dt>CLI</dt><dd>{d.sidecar ? `storebound ${d.sidecar.version}` : d.sidecarError ?? t('foot.cliStarting')}</dd>
<dt>{t('set.protocol')}</dt><dd>{d.sidecar ? `${d.sidecar.protocol} · ${t('settings.methods', { count: d.sidecar.methods.length })}` : '–'}</dd>
<dt>{t('set.state')}</dt><dd><span className="row" style={{ gap: 6 }}><i className={`dot ${d.sidecar?.running ? 'ok' : d.sidecarError ? 'bad' : ''}`} />{d.sidecar?.running ? t('set.running') : d.sidecarError ? t('foot.cliDown') : t('foot.cliStarting')}</span></dd>
<dt>{t('set.writes')}</dt><dd>{t('set.writesText')}</dd>
</dl>
</Card>
<Card id="set-privacy" title={t('set.privacy')} icon="shield" className="set-card">
<ul className="plain-list">
<li><Icon name="check" />{t('set.p1')}</li>
<li><Icon name="check" />{t('set.p2')}</li>
<li><Icon name="check" />{t('set.p3')}</li>
<li><Icon name="check" />{t('set.p4')}</li>
</ul>
<div className="actions" style={{ marginTop: 12 }}>
<button className="btn btn-sm" onClick={() => api.revealData().catch(e => setError(errorText(e)))}><Icon name="folder" />{t('set.reveal')}</button>
<button className="btn btn-sm btn-ghost" onClick={() => api.openExternal('https://storebound.dev/').catch(e => setError(errorText(e)))}><Icon name="external" />storebound.dev</button>
</div>
</Card>
<Card id="set-shortcuts" title={t('settings.shortcuts')} icon="keyboard" className="set-card">
<dl className="shortcuts"> <dl className="shortcuts">
<dt>{t('settings.scPalette')}</dt><dd><Kbd keys={[MOD, 'K']} /></dd> <dt>{t('settings.scPalette')}</dt><dd><Kbd keys={[MOD, 'K']} /></dd>
<dt>{t('nav.portfolio')}</dt><dd><Kbd keys={[MOD, '1']} /></dd> <dt>{t('nav.portfolio')}</dt><dd><Kbd keys={[MOD, '1']} /></dd>
<dt>{t('settings.scWorkspace')}</dt><dd><Kbd keys={[MOD, '2']} /><span className="muted">–</span><Kbd keys={[MOD, '6']} /></dd> <dt>{t('settings.scWorkspace')}</dt><dd><Kbd keys={[MOD, '2']} /><span className="muted">–</span><Kbd keys={[MOD, '5']} /></dd>
<dt>{t('settings.scTabs')}</dt><dd><Kbd keys={[MOD, '⇧', '[']} /><Kbd keys={[MOD, '⇧', ']']} /></dd> <dt>{t('settings.scTabs')}</dt><dd><Kbd keys={[MOD, '⇧', '[']} /><Kbd keys={[MOD, '⇧', ']']} /></dd>
<dt>{t('settings.scTabArrows')}</dt><dd><Kbd keys={['←', '→']} /></dd> <dt>{t('settings.scTabArrows')}</dt><dd><Kbd keys={['←', '→']} /></dd>
<dt>{t('settings.scClose')}</dt><dd><Kbd keys={['Esc']} /></dd> <dt>{t('settings.scClose')}</dt><dd><Kbd keys={['Esc']} /></dd>
<dt>{t('set.scQuit')}</dt><dd><Kbd keys={[MOD, 'Q']} /></dd>
</dl> </dl>
</Card> </Card>
<Card title={t('settings.data')} icon="database">
<Card id="set-updates" title={t('set.updates')} icon="download" className="set-card">
<div className="form">
<div className="field"><span className="legend">{t('set.channel')}</span>
<Seg value={s.channel} label={t('set.channel')} onChange={channel => set(x => ({ ...x, channel }))} options={[['stable', t('set.stable')], ['beta', t('set.beta')]]} /></div>
<p className="small muted">{t('set.updatesText')}</p>
</div>
</Card>
<Card id="set-reset" title={t('set.reset')} icon="rotate" className="set-card danger-card">
<div className="stack"> <div className="stack">
<p className="small muted">{t('set.resetText', { accounts: d.accounts.length, studios: d.studios.length, folders: d.projects.length })}</p> <p className="small muted">{t('settings.dataText')}</p>
<div className="actions"> <div className="actions">
<button className="btn btn-sm" onClick={clear}><Icon name="trash" />{t('settings.clearCache')}</button>
<button className="btn btn-sm" onClick={nav.openWelcome}><Icon name="sparkle" />{t('action.welcome')}</button> <button className="btn btn-sm" onClick={nav.openWelcome}><Icon name="sparkle" />{t('action.welcome')}</button>
<button className="btn btn-sm btn-danger" onClick={reset}><Icon name="rotate" />{t('set.resetButton')}</button>
</div> </div>
</div> </div>
</Card> </Card>
<p className="small muted">{t('set.footer', { n: num(d.apps.length) })}</p> <Card title={t('settings.about')} icon="info">
<dl className="kv">
<dt>{t('settings.app')}</dt><dd>{d.info ? `storebound desktop ${d.info.version}${d.info.debug ? ` (${t('settings.debug')})` : ''}` : '–'}</dd>
<dt>CLI</dt><dd>{d.sidecar ? `storebound ${d.sidecar.version} · ${d.sidecar.protocol} · ${t('settings.methods', { count: d.sidecar.methods.length })}` : d.sidecarError ?? t('foot.cliStarting')}</dd>
<dt>{t('settings.tools')}</dt><dd>{tools ? t('portfolio.toolsFound', { found: tools.tools.filter(x => x.found).length, total: tools.tools.length }) : '–'}</dd>
<dt>{t('settings.telemetry')}</dt><dd>{t('settings.telemetryNone')}</dd>
</dl>
<div className="actions" style={{ marginTop: 12 }}>
<button className="btn btn-sm btn-ghost" onClick={() => api.openExternal('https://storebound.dev/').catch(e => setError(errorText(e)))}><Icon name="external" />storebound.dev</button>
</div> </div>
</Card>
</div> </div>
</div> </div>
); );

View file

@ -1,6 +1,6 @@
// Health: Google Play vitals (user-perceived crash and ANR rate per day against the bad behavior thresholds, worst // Health: Google Play vitals (user-perceived crash and ANR rate per day against the bad behavior thresholds, worst
// devices, top issues) and App Store diagnostics (power and performance metrics, signatures, TestFlight crashes). // devices, top issues) and App Store diagnostics (power and performance metrics, signatures, TestFlight crashes).
import type { UnifiedApp } from '../../lib/identity'; import type { Project } from '../../api';
import { t } from '../../i18n'; import { t } from '../../i18n';
import { ago, date, num, pct } from '../../lib/format'; import { ago, date, num, pct } from '../../lib/format';
import { type AppleHealth, healthSeries, type HealthSnapshot, isError, PLAY_THRESHOLDS, type PlayHealth, type Series } from '../../lib/model'; import { type AppleHealth, healthSeries, type HealthSnapshot, isError, PLAY_THRESHOLDS, type PlayHealth, type Series } from '../../lib/model';
@ -122,8 +122,8 @@ function Apple({ h }: { h: AppleHealth }) {
); );
} }
export function HealthTab({ app }: { app: UnifiedApp }) { export function HealthTab({ project }: { project: Project }) {
const r = useRead<HealthSnapshot>(app.target, 'health', { network: true, title: t('tab.health'), appName: app.name }); const r = useRead<HealthSnapshot>(project.id, 'health', { network: true, title: t('tab.health') });
const refresh = <button className="btn btn-sm" onClick={r.refresh} disabled={r.loading}><Icon name="refresh" className={r.loading && !r.data ? 'spin' : undefined} />{r.data ? t('action.refresh') : t('health.read')}</button>; const refresh = <button className="btn btn-sm" onClick={r.refresh} disabled={r.loading}><Icon name="refresh" className={r.loading && !r.data ? 'spin' : undefined} />{r.data ? t('action.refresh') : t('health.read')}</button>;
if (!r.data) { if (!r.data) {
if (r.loading && !r.error) return <Card><Skeleton lines={4} block /></Card>; if (r.loading && !r.error) return <Card><Skeleton lines={4} block /></Card>;

View file

@ -1,7 +1,6 @@
// Releases: the release timeline (one version on both stores on one track: build -> testing -> review -> live -> // Releases: the release timeline (one version on both stores on one track: build -> testing -> review -> live ->
// rollout %), then every version read from the stores. Submit and release stay in the consoles. // rollout %), then every version read from the stores. Submit and release stay in the consoles.
import { api, type ReleaseTrain } from '../../api'; import { api, type Project, type ReleaseTrain } from '../../api';
import type { UnifiedApp } from '../../lib/identity';
import { type Key, t } from '../../i18n'; import { type Key, t } from '../../i18n';
import { ago, date, share } from '../../lib/format'; import { ago, date, share } from '../../lib/format';
import { type Lane, STAGES, type TestFlightStatus, trainLanes, versionHistory } from '../../lib/model'; import { type Lane, STAGES, type TestFlightStatus, trainLanes, versionHistory } from '../../lib/model';
@ -61,11 +60,10 @@ function Train({ title, train, tf, tone }: { title: string; train: ReleaseTrain;
); );
} }
export function ReleasesTab({ app }: { app: UnifiedApp }) { export function ReleasesTab({ project }: { project: Project }) {
const d = useData(); const d = useData();
const l = d.liveFor(app); const l = d.liveOf(project);
const project = app.project; const tf = useRead<TestFlightStatus>(project.id, 'apple.testflight_status', { network: true, title: 'TestFlight' });
const tf = useRead<TestFlightStatus>(app.target, 'apple.testflight_status', { network: true, title: 'TestFlight', skip: !app.ios && !d.statusFor(app)?.app?.platforms.ios });
const open = (url: string) => { api.openExternal(url).catch(() => {}); }; const open = (url: string) => { api.openExternal(url).catch(() => {}); };
if (!l) { if (!l) {
@ -73,7 +71,7 @@ export function ReleasesTab({ app }: { app: UnifiedApp }) {
<Card pad={false}> <Card pad={false}>
<Empty illo="cloud" title={t('releases.notReadTitle')} actions={<> <Empty illo="cloud" title={t('releases.notReadTitle')} actions={<>
<button className="btn btn-primary" onClick={() => d.refreshPortfolio(true)} disabled={!!d.portfolioBusy}><Icon name="refresh" />{t('action.readStores')}</button> <button className="btn btn-primary" onClick={() => d.refreshPortfolio(true)} disabled={!!d.portfolioBusy}><Icon name="refresh" />{t('action.readStores')}</button>
{project && !project.playAccount && !project.appleAccount && <span className="small muted">{t('releases.noAccounts')}</span>} {!project.playAccount && !project.appleAccount && <span className="small muted">{t('releases.noAccounts')}</span>}
</>}>{t('releases.notReadText')}</Empty> </>}>{t('releases.notReadText')}</Empty>
</Card> </Card>
); );

View file

@ -2,8 +2,7 @@
// (.storebound/replies) with the send checks. Approving a draft is a local, confirmed write; sending stays in the // (.storebound/replies) with the send checks. Approving a draft is a local, confirmed write; sending stays in the
// terminal (`storebound reviews send`): replies are public. // terminal (`storebound reviews send`): replies are public.
import { useMemo, useState } from 'react'; import { useMemo, useState } from 'react';
import { api, type DraftsResult, errorText, newJob, type ReplyDraft } from '../../api'; import { api, type DraftsResult, errorText, newJob, type Project, type ReplyDraft } from '../../api';
import type { UnifiedApp } from '../../lib/identity';
import { t } from '../../i18n'; import { t } from '../../i18n';
import { ago, date, num } from '../../lib/format'; import { ago, date, num } from '../../lib/format';
import { draftName, filterReviews, type Review, type ReviewFilter, starStats } from '../../lib/model'; import { draftName, filterReviews, type Review, type ReviewFilter, starStats } from '../../lib/model';
@ -57,11 +56,10 @@ function Detail({ r, draft, onApprove, busy }: { r: Review; draft: ReplyDraft |
); );
} }
export function ReviewsTab({ app }: { app: UnifiedApp }) { export function ReviewsTab({ project }: { project: Project }) {
const d = useData(); const d = useData();
const project = app.project; const list = useRead<Review[]>(project.id, 'reviews.list', { network: true, args: { days: 30 }, title: t('tab.reviews') });
const list = useRead<Review[]>(app.target, 'reviews.list', { network: true, args: { days: 30 }, title: t('tab.reviews'), appName: app.name }); const drafts = useRead<DraftsResult>(project.id, 'reviews.drafts', { network: false });
const drafts = useRead<DraftsResult>(app.target, 'reviews.drafts', { network: false, skip: !project });
const [f, setF] = useState<ReviewFilter>({ store: 'all', stars: [], unanswered: false, query: '' }); const [f, setF] = useState<ReviewFilter>({ store: 'all', stars: [], unanswered: false, query: '' });
const [sel, setSel] = useState<string | null>(null); const [sel, setSel] = useState<string | null>(null);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
@ -76,7 +74,6 @@ export function ReviewsTab({ app }: { app: UnifiedApp }) {
setBusy(true); setBusy(true);
const job = newJob(method); const job = newJob(method);
try { try {
if (!project) return;
const o = await api.writeWithConfirm(method, project.id, args, job); const o = await api.writeWithConfirm(method, project.id, args, job);
if (o.confirmed && o.result?.ok) { d.toast({ kind: 'ok', title, detail: undefined }); await drafts.refresh(); } if (o.confirmed && o.result?.ok) { d.toast({ kind: 'ok', title, detail: undefined }); await drafts.refresh(); }
else if (o.stage === 'dry-run') d.toast({ kind: 'bad', title: t('write.dryFailed'), detail: o.dryRun.output.split('\n').filter(Boolean).at(-1) }); else if (o.stage === 'dry-run') d.toast({ kind: 'bad', title: t('write.dryFailed'), detail: o.dryRun.output.split('\n').filter(Boolean).at(-1) });

View file

@ -1,6 +1,6 @@
// TestFlight: beta groups (internal / external, testers, builds, public link) and the recent builds with their // TestFlight: beta groups (internal / external, testers, builds, public link) and the recent builds with their
// processing and beta review states. // processing and beta review states.
import type { UnifiedApp } from '../../lib/identity'; import type { Project } from '../../api';
import { t } from '../../i18n'; import { t } from '../../i18n';
import { ago, date, num } from '../../lib/format'; import { ago, date, num } from '../../lib/format';
import type { TestFlightStatus, Tone } from '../../lib/model'; import type { TestFlightStatus, Tone } from '../../lib/model';
@ -23,11 +23,11 @@ function State({ s }: { s: string | null }) {
return s ? <Chip tone={b.tone}>{b.text}</Chip> : <span className="muted small">–</span>; return s ? <Chip tone={b.tone}>{b.text}</Chip> : <span className="muted small">–</span>;
} }
export function TestFlightTab({ app }: { app: UnifiedApp }) { export function TestFlightTab({ project }: { project: Project }) {
const d = useData(); const d = useData();
const e = d.statusFor(app); const e = d.statusOf(project);
const r = useRead<TestFlightStatus>(app.target, 'apple.testflight_status', { network: true, title: 'TestFlight' }); const r = useRead<TestFlightStatus>(project.id, 'apple.testflight_status', { network: true, title: 'TestFlight' });
if ((e && !e.app?.platforms.ios) || (!e && !app.project && !app.ios)) return <Card pad={false}><Empty illo="plane" title={t('tf.noIos')}>{t('tf.noIosText')}</Empty></Card>; if (e && !e.app?.platforms.ios) return <Card pad={false}><Empty illo="plane" title={t('tf.noIos')}>{t('tf.noIosText')}</Empty></Card>;
if (!r.data) { if (!r.data) {
if (r.loading && !r.error) return <Card><Skeleton lines={4} block /></Card>; if (r.loading && !r.error) return <Card><Skeleton lines={4} block /></Card>;
return ( return (

View file

@ -1,15 +1,11 @@
// App data shared by every screen: app folders, studios, store accounts and the apps they see, the pairing / ignore // App data shared by every screen: app folders, accounts, the sidecar, the portfolio (offline check + the last live
// overrides, settings, the sidecar, the portfolio (offline check + the last live read from the cache), app icons, and // read from the cache), app icons, and background jobs shown as toasts with progress and cancel.
// background jobs shown as toasts with progress and cancel.
import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { import {
type Account, type AccountCheck, api, type AppInfo, type AppsListResult, type AppStatus, type CacheEntry, DEFAULT_SETTINGS, errorText, newJob, onDownload, type Account, api, type AppInfo, type AppStatus, type CacheEntry, errorText, newJob, onDownload, onProgress, type PortfolioResult, type Project, reads,
onProgress, type PortfolioResult, type Project, reads, type Settings, type SidecarStatus, type Studio, type ToolResult, type SidecarStatus, type ToolResult,
} from './api'; } from './api';
import { t } from './i18n'; import { t } from './i18n';
import { buildApps, NO_OVERRIDES, type Overrides, type UnifiedApp } from './lib/identity';
import { isError, type HealthSnapshot, type Review } from './lib/model';
import { crashCrossed, newLowReviews, releaseChanges } from './lib/notify';
export type ToastKind = 'job' | 'ok' | 'bad' | 'info'; export type ToastKind = 'job' | 'ok' | 'bad' | 'info';
export interface Toast { export interface Toast {
@ -23,22 +19,11 @@ export interface Toast {
job?: string; job?: string;
} }
export interface AccountHealth { check?: AccountCheck; error?: string; at: string }
export interface Data { export interface Data {
ready: boolean; ready: boolean;
info: AppInfo | null; info: AppInfo | null;
projects: Project[]; projects: Project[];
accounts: Account[]; accounts: Account[];
studios: Studio[];
overrides: Overrides;
settings: Settings;
/** Last app list read of each account (null: never read). */
storeApps: Record<string, CacheEntry<AppsListResult> | null>;
/** Last account check of this session. */
accountHealth: Record<string, AccountHealth>;
/** Every app across studios and accounts, ignored ones included (`ignored: true`). */
apps: UnifiedApp[];
sidecar: SidecarStatus | null; sidecar: SidecarStatus | null;
sidecarError: string | null; sidecarError: string | null;
/** Latest portfolio read (offline check, or live when just read). */ /** Latest portfolio read (offline check, or live when just read). */
@ -47,21 +32,11 @@ export interface Data {
live: CacheEntry<PortfolioResult> | null; live: CacheEntry<PortfolioResult> | null;
portfolioBusy: 'offline' | 'live' | null; portfolioBusy: 'offline' | 'live' | null;
portfolioError: string | null; portfolioError: string | null;
importBusy: boolean;
icons: Record<string, string | null>; icons: Record<string, string | null>;
refreshPortfolio: (live?: boolean) => Promise<void>; refreshPortfolio: (live?: boolean) => Promise<void>;
/** Reads the apps of one account (or all) from the stores. */
importApps: (account?: string) => Promise<void>;
checkAccount: (id: string) => Promise<void>;
reload: () => Promise<void>; reload: () => Promise<void>;
updateOverrides: (fn: (o: Overrides) => Overrides) => Promise<void>;
updateSettings: (s: Settings) => Promise<void>;
statusOf: (p: Project) => AppStatus | undefined; statusOf: (p: Project) => AppStatus | undefined;
liveOf: (p: Project) => AppStatus | undefined; liveOf: (p: Project) => AppStatus | undefined;
statusFor: (a: UnifiedApp) => AppStatus | undefined;
liveFor: (a: UnifiedApp) => AppStatus | undefined;
iconFor: (a: UnifiedApp) => string | null;
appByKey: (key: string) => UnifiedApp | undefined;
toasts: Toast[]; toasts: Toast[];
toast: (t: Omit<Toast, 'id'> & { id?: string }) => string; toast: (t: Omit<Toast, 'id'> & { id?: string }) => string;
updateToast: (id: string, patch: Partial<Toast>) => void; updateToast: (id: string, patch: Partial<Toast>) => void;
@ -83,25 +58,15 @@ export function DataProvider({ children }: { children: ReactNode }) {
const [info, setInfo] = useState<AppInfo | null>(null); const [info, setInfo] = useState<AppInfo | null>(null);
const [projects, setProjects] = useState<Project[]>([]); const [projects, setProjects] = useState<Project[]>([]);
const [accounts, setAccounts] = useState<Account[]>([]); const [accounts, setAccounts] = useState<Account[]>([]);
const [studios, setStudios] = useState<Studio[]>([]);
const [overrides, setOverrides] = useState<Overrides>(NO_OVERRIDES);
const [settings, setSettings] = useState<Settings>(DEFAULT_SETTINGS);
const [storeApps, setStoreApps] = useState<Record<string, CacheEntry<AppsListResult> | null>>({});
const [accountHealth, setAccountHealth] = useState<Record<string, AccountHealth>>({});
const [sidecar, setSidecar] = useState<SidecarStatus | null>(null); const [sidecar, setSidecar] = useState<SidecarStatus | null>(null);
const [sidecarError, setSidecarError] = useState<string | null>(null); const [sidecarError, setSidecarError] = useState<string | null>(null);
const [portfolio, setPortfolio] = useState<PortfolioResult | null>(null); const [portfolio, setPortfolio] = useState<PortfolioResult | null>(null);
const [live, setLive] = useState<CacheEntry<PortfolioResult> | null>(null); const [live, setLive] = useState<CacheEntry<PortfolioResult> | null>(null);
const [portfolioBusy, setBusy] = useState<Data['portfolioBusy']>(null); const [portfolioBusy, setBusy] = useState<Data['portfolioBusy']>(null);
const [portfolioError, setPortfolioError] = useState<string | null>(null); const [portfolioError, setPortfolioError] = useState<string | null>(null);
const [importBusy, setImportBusy] = useState(false);
const [icons, setIcons] = useState<Record<string, string | null>>({}); const [icons, setIcons] = useState<Record<string, string | null>>({});
const [toasts, setToasts] = useState<Toast[]>([]); const [toasts, setToasts] = useState<Toast[]>([]);
const timers = useRef(new Map<string, ReturnType<typeof setTimeout>>()); const timers = useRef(new Map<string, ReturnType<typeof setTimeout>>());
const liveRef = useRef(live);
liveRef.current = live;
const settingsRef = useRef(settings);
settingsRef.current = settings;
const dismiss = useCallback((id: string) => { const dismiss = useCallback((id: string) => {
setToasts(ts => ts.filter(x => x.id !== id)); setToasts(ts => ts.filter(x => x.id !== id));
@ -127,36 +92,20 @@ export function DataProvider({ children }: { children: ReactNode }) {
const cancelJob = useCallback((job: string) => { api.cancel(job).catch(() => {}); }, []); const cancelJob = useCallback((job: string) => { api.cancel(job).catch(() => {}); }, []);
const reload = useCallback(async () => { const reload = useCallback(async () => {
const [p, a, w, s] = await Promise.all([api.projects(), api.accounts(), api.workspace(), api.storeAppsCached()]); const [p, a] = await Promise.all([api.projects(), api.accounts()]);
setProjects(p); setProjects(p);
setAccounts(a); setAccounts(a);
setStudios(w.studios);
setOverrides(w.overrides);
setSettings(w.settings);
setStoreApps(Object.fromEntries(s.map(x => [x.account, x.entry])));
}, []); }, []);
const apps = useMemo(() => buildApps({
projects, accounts, overrides,
summaryOf: p => portfolio?.apps.find(a => a.project === p.path)?.summary ?? liveRef.current?.value.apps.find(a => a.project === p.path)?.summary,
storeApps: Object.entries(storeApps).filter(([, e]) => !!e).map(([account, e]) => ({ account, apps: e!.value.apps })),
}), [projects, accounts, overrides, portfolio, storeApps]);
const appsRef = useRef(apps);
appsRef.current = apps;
const refreshPortfolio = useCallback(async (liveRead = false) => { const refreshPortfolio = useCallback(async (liveRead = false) => {
const job = newJob(liveRead ? 'portfolio-live' : 'portfolio'); const job = newJob(liveRead ? 'portfolio-live' : 'portfolio');
setBusy(liveRead ? 'live' : 'offline'); setPortfolioError(null); setBusy(liveRead ? 'live' : 'offline'); setPortfolioError(null);
const tid = liveRead ? toast({ id: job, kind: 'job', title: t('toast.readingStores'), detail: t('toast.readingStoresDetail'), progress: null, job }) : null; const tid = liveRead ? toast({ id: job, kind: 'job', title: t('toast.readingStores'), detail: t('toast.readingStoresDetail'), progress: null, job }) : null;
try { try {
const stores = liveRead ? appsRef.current.filter(a => !a.project && !a.ignored).map(a => a.target) : []; const r = await api.portfolio(liveRead, job);
const r = await api.portfolio(liveRead, job, stores);
setPortfolio(r); setPortfolio(r);
if (liveRead) { if (liveRead) {
const changes = releaseChanges(liveRef.current?.value, r);
setLive({ value: r, at: r.at }); setLive({ value: r, at: r.at });
if (settingsRef.current.notify.reviewState) for (const c of changes.slice(0, 5))
api.notify(t('notify.releaseTitle', { name: c.name }), t('notify.releaseBody', { store: c.store === 'ios' ? 'App Store' : 'Google Play', version: c.version, phase: t(`phase.${c.to}` as 'phase.live') })).catch(() => {});
const failed = r.apps.filter(a => a.storeErrors.ios || a.storeErrors.android).length; const failed = r.apps.filter(a => a.storeErrors.ios || a.storeErrors.android).length;
if (tid) updateToast(tid, failed ? { kind: 'info', title: t('toast.readDonePartial'), detail: t('toast.readDonePartialDetail', { count: failed }), progress: undefined, job: undefined } if (tid) updateToast(tid, failed ? { kind: 'info', title: t('toast.readDonePartial'), detail: t('toast.readDonePartialDetail', { count: failed }), progress: undefined, job: undefined }
: { kind: 'ok', title: t('toast.readDone'), detail: t('toast.readDoneDetail', { count: r.apps.length }), progress: undefined, job: undefined }); : { kind: 'ok', title: t('toast.readDone'), detail: t('toast.readDoneDetail', { count: r.apps.length }), progress: undefined, job: undefined });
@ -168,54 +117,7 @@ export function DataProvider({ children }: { children: ReactNode }) {
} finally { setBusy(null); } } finally { setBusy(null); }
}, [toast, updateToast]); }, [toast, updateToast]);
const importApps = useCallback(async (account?: string) => { // start: app info, folders, accounts, sidecar, cached live portfolio
const ids = (account ? [account] : accounts.map(a => a.id)).filter(id => account || !overrides.ignored.includes(`account:${id}`));
if (!ids.length) return;
const job = newJob('import');
setImportBusy(true);
const tid = toast({ id: job, kind: 'job', title: t('toast.importing'), detail: t('toast.importingDetail'), progress: { done: 0, total: ids.length }, job });
let ok = 0, apps = 0;
const errors: string[] = [];
for (const [n, id] of ids.entries()) {
try {
const e = await api.refreshStoreApps(id, job);
setStoreApps(m => ({ ...m, [id]: e }));
ok++; apps += e.value.apps.length;
} catch (e) {
const msg = errorText(e);
if (/cancel/i.test(msg)) { updateToast(tid, { kind: 'info', title: t('toast.cancelled'), detail: undefined, progress: undefined, job: undefined }); setImportBusy(false); return; }
errors.push(`${accounts.find(a => a.id === id)?.label ?? id}: ${msg}`);
}
updateToast(tid, { progress: { done: n + 1, total: ids.length } });
}
setImportBusy(false);
updateToast(tid, errors.length ? { kind: ok ? 'info' : 'bad', title: t('toast.importPartial', { count: errors.length }), detail: errors[0], progress: undefined, job: undefined }
: { kind: 'ok', title: t('toast.importDone', { count: apps }), detail: t('toast.importDoneDetail', { count: ok }), progress: undefined, job: undefined });
}, [accounts, overrides.ignored, toast, updateToast]);
const checkAccount = useCallback(async (id: string) => {
try {
const check = await api.checkAccount(id, newJob('check'));
setAccountHealth(m => ({ ...m, [id]: { check, at: new Date().toISOString() } }));
} catch (e) { setAccountHealth(m => ({ ...m, [id]: { error: errorText(e), at: new Date().toISOString() } })); }
}, []);
const updateOverrides = useCallback(async (fn: (o: Overrides) => Overrides) => {
const next = fn(overrides);
setOverrides(next);
try { setOverrides(await api.setOverrides(next)); } catch (e) {
setOverrides(overrides);
toast({ kind: 'bad', title: t('toast.saveFailed'), detail: errorText(e) });
}
}, [overrides, toast]);
const updateSettings = useCallback(async (s: Settings) => {
const old = settings;
setSettings(s);
try { setSettings(await api.setSettings(s)); } catch (e) { setSettings(old); toast({ kind: 'bad', title: t('toast.saveFailed'), detail: errorText(e) }); }
}, [settings, toast]);
// start: app info, folders, accounts, workspace, sidecar, cached live portfolio
useEffect(() => { useEffect(() => {
api.appInfo().then(setInfo, () => {}); api.appInfo().then(setInfo, () => {});
reload().catch(() => {}).finally(() => setReady(true)); reload().catch(() => {}).finally(() => setReady(true));
@ -225,22 +127,6 @@ export function DataProvider({ children }: { children: ReactNode }) {
useEffect(() => { if (projects.length) refreshPortfolio(false); }, [projects.length, refreshPortfolio]); useEffect(() => { if (projects.length) refreshPortfolio(false); }, [projects.length, refreshPortfolio]);
// Settings > Refresh: on launch, then every N minutes (store reads use the accounts' API quota: off by default)
const launched = useRef(false);
useEffect(() => {
if (!ready || launched.current) return;
launched.current = true;
if (settings.refresh.onLaunch && (projects.length || accounts.length)) importApps().finally(() => refreshPortfolio(true));
}, [ready, settings.refresh.onLaunch, projects.length, accounts.length, importApps, refreshPortfolio]);
const busyRef = useRef(portfolioBusy);
busyRef.current = portfolioBusy;
useEffect(() => {
const m = settings.refresh.autoMinutes;
if (!m) return;
const tm = setInterval(() => { if (!busyRef.current) refreshPortfolio(true); }, m * 60_000);
return () => clearInterval(tm);
}, [settings.refresh.autoMinutes, refreshPortfolio]);
// icons: cached first, then read (offline, cheap) // icons: cached first, then read (offline, cheap)
useEffect(() => { useEffect(() => {
for (const p of projects) { for (const p of projects) {
@ -277,18 +163,11 @@ export function DataProvider({ children }: { children: ReactNode }) {
const cur = portfolio?.apps.find(a => (a.project === p.path || a.app?.id === p.path) && a.release.source === 'live'); const cur = portfolio?.apps.find(a => (a.project === p.path || a.app?.id === p.path) && a.release.source === 'live');
return cur ?? live?.value.apps.find(a => a.project === p.path || a.app?.id === p.path); return cur ?? live?.value.apps.find(a => a.project === p.path || a.app?.id === p.path);
}, [portfolio, live]); }, [portfolio, live]);
const statusFor = useCallback((a: UnifiedApp) => (a.project ? statusOf(a.project) : portfolio?.apps.find(x => x.project === a.target) ?? live?.value.apps.find(x => x.project === a.target)), [statusOf, portfolio, live]);
const liveFor = useCallback((a: UnifiedApp) => (a.project ? liveOf(a.project) : portfolio?.apps.find(x => x.project === a.target && x.release.source === 'live') ?? live?.value.apps.find(x => x.project === a.target)), [liveOf, portfolio, live]);
const iconFor = useCallback((a: UnifiedApp) => (a.project ? icons[a.project.id] ?? a.storeIcon : a.storeIcon), [icons]);
const appByKey = useCallback((key: string) => apps.find(a => a.key === key), [apps]);
const value = useMemo<Data>(() => ({ const value = useMemo<Data>(() => ({
ready, info, projects, accounts, studios, overrides, settings, storeApps, accountHealth, apps, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, ready, info, projects, accounts, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, icons,
importBusy, icons, refreshPortfolio, importApps, checkAccount, reload, updateOverrides, updateSettings, statusOf, liveOf, statusFor, liveFor, iconFor, appByKey, refreshPortfolio, reload, statusOf, liveOf, toasts, toast, updateToast, dismiss, cancelJob,
toasts, toast, updateToast, dismiss, cancelJob, }), [ready, info, projects, accounts, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError, icons, refreshPortfolio, reload, statusOf, liveOf, toasts, toast, updateToast, dismiss, cancelJob]);
}), [ready, info, projects, accounts, studios, overrides, settings, storeApps, accountHealth, apps, sidecar, sidecarError, portfolio, live, portfolioBusy, portfolioError,
importBusy, icons, refreshPortfolio, importApps, checkAccount, reload, updateOverrides, updateSettings, statusOf, liveOf, statusFor, liveFor, iconFor, appByKey,
toasts, toast, updateToast, dismiss, cancelJob]);
return <Ctx.Provider value={value}>{children}</Ctx.Provider>; return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
} }
@ -304,31 +183,16 @@ export interface ReadState<T> {
refresh: () => Promise<void>; refresh: () => Promise<void>;
} }
/** Notifications a fresh read may trigger (Settings > Notifications), compared with the read it replaces. */
function notifyAfterRead(method: string, prev: unknown, next: unknown, settings: Settings, appName: string | undefined): void {
const name = appName ?? '';
if (method === 'reviews.list' && settings.notify.lowReviews && Array.isArray(next)) {
const fresh = newLowReviews(prev as Review[] | null, next as Review[]);
if (fresh.length) api.notify(t('notify.lowTitle', { name, count: fresh.length }), `${'★'.repeat(fresh[0]!.rating)} ${fresh[0]!.title ?? ''} ${fresh[0]!.body}`.trim()).catch(() => {});
}
if (method === 'health' && settings.notify.crash && next && typeof next === 'object') {
const crossed = crashCrossed(prev as HealthSnapshot | null, next as HealthSnapshot);
if (crossed.length && !isError((next as HealthSnapshot).play)) api.notify(t('notify.crashTitle', { name }), crossed.map(k => (k === 'crash' ? t('health.crash') : t('health.anr'))).join(', ')).catch(() => {});
}
}
/** /**
* One read method of one app (a project id, or a store-only app's store target). The cached value shows at once with * One read method of one app. The cached value shows at once with its time; offline reads (`network: false`) then
* its time; offline reads (`network: false`) then refresh by themselves, store reads only on demand (they use the * refresh by themselves, store reads only on demand (they use the account's API quota). A failed read keeps the last
* account's API quota). A failed read keeps the last good value and says so: never an empty "all fine". * good value and says so: never an empty "all fine".
*/ */
export function useRead<T>(target: string, method: string, o: { network: boolean; args?: Record<string, unknown>; title?: string; appName?: string; skip?: boolean }): ReadState<T> { export function useRead<T>(projectId: string, method: string, o: { network: boolean; args?: Record<string, unknown>; title?: string }): ReadState<T> {
const d = useData(); const d = useData();
const argsKey = JSON.stringify(o.args ?? {}); const argsKey = JSON.stringify(o.args ?? {});
const [s, set] = useState<Omit<ReadState<T>, 'refresh'>>({ data: null, at: null, fromCache: false, loading: true, error: null, command: null }); const [s, set] = useState<Omit<ReadState<T>, 'refresh'>>({ data: null, at: null, fromCache: false, loading: true, error: null, command: null });
const seq = useRef(0); const seq = useRef(0);
const dataRef = useRef<T | null>(null);
dataRef.current = s.data;
const refresh = useCallback(async () => { const refresh = useCallback(async () => {
const my = ++seq.current; const my = ++seq.current;
@ -336,10 +200,9 @@ export function useRead<T>(target: string, method: string, o: { network: boolean
set(x => ({ ...x, loading: true, error: null })); set(x => ({ ...x, loading: true, error: null }));
const tid = o.network ? d.toast({ id: job, kind: 'job', title: o.title ?? t('toast.reading'), detail: t('toast.readingDetail'), progress: null, job }) : null; const tid = o.network ? d.toast({ id: job, kind: 'job', title: o.title ?? t('toast.reading'), detail: t('toast.readingDetail'), progress: null, job }) : null;
try { try {
const r = await api.call<ToolResult>(method, target, { args: JSON.parse(argsKey) as Record<string, unknown> }, job); const r = await api.call<ToolResult>(method, projectId, { args: JSON.parse(argsKey) as Record<string, unknown> }, job);
if (my !== seq.current) return; if (my !== seq.current) return;
if (r.ok && r.data !== undefined) { if (r.ok && r.data !== undefined) {
notifyAfterRead(method, dataRef.current, r.data, d.settings, o.appName);
set({ data: r.data as T, at: new Date().toISOString(), fromCache: false, loading: false, error: null, command: r.command }); set({ data: r.data as T, at: new Date().toISOString(), fromCache: false, loading: false, error: null, command: r.command });
if (tid) d.updateToast(tid, { kind: 'ok', title: t('toast.readOk', { what: o.title ?? method }), detail: undefined, progress: undefined, job: undefined }); if (tid) d.updateToast(tid, { kind: 'ok', title: t('toast.readOk', { what: o.title ?? method }), detail: undefined, progress: undefined, job: undefined });
} else { } else {
@ -353,20 +216,19 @@ export function useRead<T>(target: string, method: string, o: { network: boolean
set(x => ({ ...x, loading: false, error: msg })); set(x => ({ ...x, loading: false, error: msg }));
if (tid) d.updateToast(tid, { kind: /cancel/i.test(msg) ? 'info' : 'bad', title: /cancel/i.test(msg) ? t('toast.cancelled') : t('toast.readFailedWhat', { what: o.title ?? method }), detail: msg, progress: undefined, job: undefined }); if (tid) d.updateToast(tid, { kind: /cancel/i.test(msg) ? 'info' : 'bad', title: /cancel/i.test(msg) ? t('toast.cancelled') : t('toast.readFailedWhat', { what: o.title ?? method }), detail: msg, progress: undefined, job: undefined });
} }
}, [target, method, argsKey, o.network, o.title, o.appName, d.settings]); // eslint-disable-line react-hooks/exhaustive-deps }, [projectId, method, argsKey, o.network, o.title]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => { useEffect(() => {
let alive = true; let alive = true;
if (o.skip) { set({ data: null, at: null, fromCache: false, loading: false, error: null, command: null }); return; }
set({ data: null, at: null, fromCache: false, loading: true, error: null, command: null }); set({ data: null, at: null, fromCache: false, loading: true, error: null, command: null });
api.cached<ToolResult>(method, target, JSON.parse(argsKey) as Record<string, unknown>).then(c => { api.cached<ToolResult>(method, projectId, JSON.parse(argsKey) as Record<string, unknown>).then(c => {
if (!alive) return; if (!alive) return;
if (c && c.value.data !== undefined) set({ data: c.value.data as T, at: c.at, fromCache: true, loading: !o.network, error: null, command: c.value.command }); if (c && c.value.data !== undefined) set({ data: c.value.data as T, at: c.at, fromCache: true, loading: !o.network, error: null, command: c.value.command });
else set(x => ({ ...x, loading: !o.network })); else set(x => ({ ...x, loading: !o.network }));
if (!o.network) refresh(); if (!o.network) refresh();
}, () => { if (alive) { set(x => ({ ...x, loading: !o.network })); if (!o.network) refresh(); } }); }, () => { if (alive) { set(x => ({ ...x, loading: !o.network })); if (!o.network) refresh(); } });
return () => { alive = false; }; return () => { alive = false; };
}, [target, method, argsKey, o.skip]); // eslint-disable-line react-hooks/exhaustive-deps }, [projectId, method, argsKey]); // eslint-disable-line react-hooks/exhaustive-deps
return { ...s, refresh }; return { ...s, refresh };
} }

View file

@ -632,119 +632,3 @@ h2[tabindex="-1"]:focus, h2[tabindex="-1"]:focus-visible { outline: none; }
.tbad { color: var(--bad-ink); } .twarn { color: var(--warn-ink); } .tbad { color: var(--bad-ink); } .twarn { color: var(--warn-ink); }
.table .mini, .table .mini > * { white-space: nowrap; } .table .mini, .table .mini > * { white-space: nowrap; }
.table .mini .row { flex-wrap: nowrap; } .table .mini .row { flex-wrap: nowrap; }
/* ---- D3: studios, store-only apps, toolbar, accounts, settings ---- */
:root {
--st-indigo: #4f46e5; --st-violet: #7c3aed; --st-rose: #e11d48; --st-amber: #b45309;
--st-emerald: #047857; --st-teal: #0f766e; --st-sky: #0369a1; --st-slate: #475569;
}
.studio-indigo { --st: var(--st-indigo); } .studio-violet { --st: var(--st-violet); } .studio-rose { --st: var(--st-rose); } .studio-amber { --st: var(--st-amber); }
.studio-emerald { --st: var(--st-emerald); } .studio-teal { --st: var(--st-teal); } .studio-sky { --st: var(--st-sky); } .studio-slate { --st: var(--st-slate); }
.studio-mark { display: inline-grid; place-items: center; flex: none; overflow: hidden; color: #fff; font-weight: 760; letter-spacing: .02em;
background: linear-gradient(140deg, color-mix(in srgb, var(--st, var(--st-slate)) 82%, #fff), var(--st, var(--st-slate))); box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .08); }
.studio-mark img { width: 100%; height: 100%; object-fit: cover; }
.studio-mark.sm { width: 16px; height: 16px; border-radius: 5px; font-size: 7.5px; }
.studio-mark.md { width: 28px; height: 28px; border-radius: 8px; font-size: 11px; }
.studio-mark.lg { width: 40px; height: 40px; border-radius: 11px; font-size: 14px; }
.studio-mark.none { background: transparent; box-shadow: inset 0 0 0 1.5px var(--line-2); border: 0; }
.studio-mark.none.sm { box-shadow: inset 0 0 0 1.5px var(--faint); }
.so-tag { height: 20px; padding: 0 7px; font-size: 10.5px; gap: 4px; }
.so-tag svg { width: 12px; height: 12px; }
.so-dot { display: inline-grid; place-items: center; color: var(--faint); }
.so-dot svg { width: 13px; height: 13px; }
.nav[aria-current="page"] .so-dot svg { color: var(--faint); }
/* sidebar studio groups */
.side-group { margin-top: 2px; }
.side-group-head { all: unset; box-sizing: border-box; width: 100%; display: flex; align-items: center; gap: 8px; height: 28px; padding: 0 8px 0 6px; border-radius: 7px; cursor: pointer;
font-size: var(--t-meta); font-weight: 650; color: var(--ink-2); transition: background-color var(--speed) var(--ease); }
.side-group-head:hover { background: var(--hover); color: var(--ink); }
.side-group-head:focus-visible { outline: 2px solid var(--focus); outline-offset: -2px; }
.side-group-head .chev { width: 12px; height: 12px; color: var(--muted); transition: transform var(--speed) var(--ease); }
.side-group-head[aria-expanded="true"] .chev { transform: rotate(90deg); }
.side-group-head .grow { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.side-group-head .count { font-size: var(--t-micro); color: var(--muted); font-weight: 560; font-variant-numeric: tabular-nums; }
.side-group [role="list"] { padding-left: 12px; margin-left: 13px; border-left: 1px solid var(--line); }
.side-group .nav-app { height: 32px; }
/* portfolio toolbar */
.toolbar { display: flex; align-items: center; flex-wrap: wrap; gap: 10px 12px; }
.toolbar .search-input { width: 260px; }
.toolbar .search-input .input { height: 32px; }
.toolbar .grow { flex: 1; }
.fchips { display: flex; flex-wrap: wrap; gap: 6px; }
.fchip { all: unset; box-sizing: border-box; display: inline-flex; align-items: center; gap: 7px; height: 30px; padding: 0 11px 0 9px; border-radius: 999px; cursor: pointer;
background: var(--surface); border: 1px solid var(--line); color: var(--ink-2); font-size: var(--t-meta); font-weight: 600; box-shadow: var(--shadow-1);
transition: background-color var(--speed) var(--ease), border-color var(--speed) var(--ease); }
.fchip:hover { background: var(--hover); color: var(--ink); }
.fchip:focus-visible { outline: 2px solid var(--focus); outline-offset: 1px; }
.fchip .n { font-size: var(--t-micro); font-weight: 650; color: var(--muted); font-variant-numeric: tabular-nums; padding: 1px 6px; border-radius: 999px; background: var(--bg-sunken); }
.fchip[aria-pressed="true"] { background: var(--accent-soft); border-color: var(--accent-line); color: var(--accent); }
.fchip[aria-pressed="true"] .n { background: var(--surface); color: var(--accent); }
.table tbody tr.group-row td { background: var(--surface-2); padding-top: 9px; padding-bottom: 9px; border-top: 1px solid var(--line); }
.table tbody tr.group-row b { font-weight: 680; }
.table tbody tr.group-row:hover td { background: var(--surface-2); }
.table tbody + tbody tr.group-row td { border-top: 1px solid var(--line-2); }
/* studios & accounts */
.studio-card .card-head { align-items: center; }
.studio-card.focus { box-shadow: var(--shadow-2), 0 0 0 2px var(--accent-line); }
.studio-edit { display: grid; grid-template-columns: minmax(200px, 320px) 1fr auto; gap: 16px; align-items: end; border-bottom: 1px solid var(--line); }
.acct-list { display: grid; }
.acct { border-top: 1px solid var(--line); }
.acct.is-ignored .acct-row { opacity: .62; }
.acct-row { display: flex; align-items: center; gap: 14px; padding: 12px 18px; }
.acct-glyph { width: 32px; height: 32px; border-radius: 9px; display: grid; place-items: center; flex: none; background: var(--bg-sunken); border: 1px solid var(--line); }
.acct-glyph svg { width: 16px; height: 16px; }
.acct-main { flex: 1; min-width: 0; display: grid; gap: 3px; }
.acct-main .small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.acct-edit { display: grid; grid-template-columns: minmax(180px, 1fr) minmax(180px, 1fr) auto; gap: 12px; align-items: end; padding: 0 18px 14px 64px; }
.acct-fix { padding: 0 18px 14px 64px; }
.swatches { display: flex; flex-wrap: wrap; gap: 8px; }
.swatch { all: unset; box-sizing: border-box; width: 26px; height: 26px; border-radius: 8px; display: grid; place-items: center; cursor: pointer; color: #fff;
background: var(--st); box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .1); transition: transform var(--speed) var(--ease); }
.swatch:hover { transform: translateY(-1px); }
.swatch:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
.swatch[aria-checked="true"] { box-shadow: 0 0 0 2px var(--surface), 0 0 0 4px var(--st); }
.swatch svg { width: 14px; height: 14px; }
/* app page: studio pill, pairing controls */
.studio-pill { all: unset; box-sizing: border-box; display: inline-flex; align-items: center; gap: 7px; height: 24px; padding: 0 10px 0 5px; border-radius: 999px; cursor: pointer;
background: var(--surface); border: 1px solid var(--line); font-size: var(--t-micro); font-weight: 650; color: var(--ink-2); }
.studio-pill:hover { background: var(--hover); color: var(--ink); }
.studio-pill:focus-visible { outline: 2px solid var(--focus); }
.app-controls { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 16px; padding: 8px 12px; border: 1px solid var(--line); border-radius: var(--r); background: var(--surface-2); }
.input.input-sm, select.input.input-sm { height: 28px; padding: 0 8px; font-size: var(--t-meta); width: auto; max-width: 280px; }
/* settings */
.set-layout { display: grid; grid-template-columns: 210px minmax(0, 1fr); gap: 24px; align-items: start; }
.set-nav { position: sticky; top: 0; display: grid; gap: 1px; padding: 6px; border: 1px solid var(--line); border-radius: var(--r-lg); background: var(--surface); box-shadow: var(--shadow-1); }
.set-nav .nav { height: 30px; font-size: var(--t-meta); }
.set-nav .nav[aria-current="true"] { background: var(--accent-soft); color: var(--accent); font-weight: 650; }
.set-nav .nav[aria-current="true"] svg { color: var(--accent); }
.set-body .card { scroll-margin-top: 12px; }
.toggle-row { display: flex; align-items: center; gap: 16px; padding: 10px 0; border-top: 1px solid var(--line); cursor: pointer; }
.toggle-row:first-child { border-top: 0; padding-top: 0; }
.toggle-row .grow { display: grid; gap: 2px; }
.switch { appearance: none; -webkit-appearance: none; flex: none; width: 36px; height: 21px; border-radius: 999px; background: var(--line-2); position: relative; cursor: pointer; margin: 0;
transition: background-color var(--speed) var(--ease); }
.switch::after { content: ""; position: absolute; top: 2.5px; left: 2.5px; width: 16px; height: 16px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px rgba(0, 0, 0, .3); transition: transform var(--speed) var(--ease); }
.switch:checked { background: var(--accent-solid); }
.switch:checked::after { transform: translateX(15px); }
.switch:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
.studio-sum { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 10px; }
.studio-sum-item { all: unset; box-sizing: border-box; display: flex; align-items: center; gap: 12px; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--r); cursor: pointer; background: var(--surface-2); }
.studio-sum-item:hover { background: var(--hover); }
.studio-sum-item:focus-visible { outline: 2px solid var(--focus); }
.dep-sum { display: flex; flex-wrap: wrap; gap: 8px 20px; }
.plain-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 8px; }
.plain-list li { display: flex; gap: 10px; align-items: flex-start; font-size: var(--t-body); color: var(--ink-2); }
.plain-list svg { width: 15px; height: 15px; color: var(--ok-solid); flex: none; margin-top: 2px; }
.danger-card { border-color: color-mix(in srgb, var(--bad-solid) 35%, var(--line)); }
.btn.btn-danger:not(.btn-ghost) { color: var(--bad-ink); background: var(--bad-bg); border-color: color-mix(in srgb, var(--bad-solid) 40%, transparent); }
@media (max-width: 1100px) { .set-layout { grid-template-columns: 1fr; } .set-nav { position: static; grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); } .studio-edit, .acct-edit { grid-template-columns: 1fr; } }
.cell-app .s .so-inline { display: inline-flex; align-items: center; gap: 4px; margin-left: 8px; font-family: var(--font); font-size: var(--t-micro); font-weight: 650; color: var(--muted); }
.cell-app .s .so-inline svg { width: 12px; height: 12px; }
.toolbar .search-input { width: 240px; }

View file

@ -47,20 +47,6 @@ const P = {
keyboard: 'M3.5 6.5h17A1 1 0 0 1 21.5 7.5v9a1 1 0 0 1-1 1h-17a1 1 0 0 1-1-1v-9a1 1 0 0 1 1-1zM6.5 10h.1M10 10h.1M13.5 10h.1M17 10h.1M7.5 14h9', keyboard: 'M3.5 6.5h17A1 1 0 0 1 21.5 7.5v9a1 1 0 0 1-1 1h-17a1 1 0 0 1-1-1v-9a1 1 0 0 1 1-1zM6.5 10h.1M10 10h.1M13.5 10h.1M17 10h.1M7.5 14h9',
database: 'M12 8c4.4 0 8-1.3 8-3s-3.6-3-8-3-8 1.3-8 3 3.6 3 8 3zM4 5v14c0 1.7 3.6 3 8 3s8-1.3 8-3V5M4 12c0 1.7 3.6 3 8 3s8-1.3 8-3', database: 'M12 8c4.4 0 8-1.3 8-3s-3.6-3-8-3-8 1.3-8 3 3.6 3 8 3zM4 5v14c0 1.7 3.6 3 8 3s8-1.3 8-3V5M4 12c0 1.7 3.6 3 8 3s8-1.3 8-3',
wand: 'M14.5 6.5l3 3M4 20 17.5 6.5l-3-3L1 17zM19 2.5v3M20.5 4h-3M21 10v2M22 11h-2', wand: 'M14.5 6.5l3 3M4 20 17.5 6.5l-3-3L1 17zM19 2.5v3M20.5 4h-3M21 10v2M22 11h-2',
building: 'M4.5 20.5V5A1.5 1.5 0 0 1 6 3.5h7A1.5 1.5 0 0 1 14.5 5v15.5M14.5 9.5H18a1.5 1.5 0 0 1 1.5 1.5v9.5M3 20.5h18M8 7.5h3M8 11h3M8 14.5h3',
eye: 'M2.5 12c1-1.5 4.5-6 9.5-6s8.5 4.5 9.5 6c-1 1.5-4.5 6-9.5 6s-8.5-4.5-9.5-6zM12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z',
eyeOff: 'M3 3l18 18M10.6 6.1c.5-.1.9-.1 1.4-.1 5 0 8.5 4.5 9.5 6-.5.8-1.6 2.3-3.2 3.6M6.4 7.9C4.7 9.2 3.5 10.9 2.5 12c1 1.5 4.5 6 9.5 6 1.5 0 2.9-.4 4.1-1M9.9 9.9a3 3 0 0 0 4.2 4.2',
link: 'M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1',
unlink: 'M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1M4 4l16 16',
bell: 'M6 16.5V11a6 6 0 1 1 12 0v5.5l1.5 2h-15zM10 20.5a2 2 0 0 0 4 0',
filter: 'M4 5.5h16l-6 7.5v5.5l-4 1.5v-7z',
play: 'M8 5.5v13l10.5-6.5z',
send: 'M4 11.5 20 4l-6 16-3-6.5zM11 13.5 20 4',
edit: 'M4 20h4L19 9l-4-4L4 16zM13.5 6.5l4 4',
upload: 'M12 20V9M7.5 13.5 12 9l4.5 4.5M4.5 4.5h15',
sliders: 'M4 6.5h9M17 6.5h3M4 12h3M11 12h9M4 17.5h11M19 17.5h1M15 4.5v4M9 10v4M17 15.5v4',
rotate: 'M4 12a8 8 0 1 0 2.4-5.7L4 8.5M4 4v4.5h4.5',
cloud: 'M7 18.5h10.5a4 4 0 0 0 .6-8 6 6 0 0 0-11.6 1.6A3.3 3.3 0 0 0 7 18.5z',
} as const; } as const;
export type IconName = keyof typeof P; export type IconName = keyof typeof P;

View file

@ -137,9 +137,9 @@ export function Seg<T extends string>({ value, options, onChange, label }: { val
); );
} }
export function Card({ title, icon, sub, actions, children, foot, className = '', pad = true, id }: { title?: ReactNode; icon?: IconName; sub?: ReactNode; actions?: ReactNode; children: ReactNode; foot?: ReactNode; className?: string; pad?: boolean; id?: string }) { export function Card({ title, icon, sub, actions, children, foot, className = '', pad = true }: { title?: ReactNode; icon?: IconName; sub?: ReactNode; actions?: ReactNode; children: ReactNode; foot?: ReactNode; className?: string; pad?: boolean }) {
return ( return (
<section className={`card ${className}`} id={id}> <section className={`card ${className}`}>
{title !== undefined && ( {title !== undefined && (
<div className="card-head"> <div className="card-head">
<div className="stack" style={{ gap: 2 }}><h2>{icon && <Icon name={icon} />}{title}</h2>{sub && <div className="sub">{sub}</div>}</div> <div className="stack" style={{ gap: 2 }}><h2>{icon && <Icon name={icon} />}{title}</h2>{sub && <div className="sub">{sub}</div>}</div>
@ -158,15 +158,3 @@ export function Kbd({ keys }: { keys: string[] }) {
/** Platform modifier label (⌘ on macOS, Ctrl elsewhere). */ /** Platform modifier label (⌘ on macOS, Ctrl elsewhere). */
export const MOD = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform) ? '⌘' : 'Ctrl'; export const MOD = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform) ? '⌘' : 'Ctrl';
/** A studio's logo, or its monogram on the studio colour. `null` studio: "No studio" (dashed). */
export function StudioMark({ studio, size = 'md' }: { studio: { name: string; color: string; logo?: string | null } | null; size?: 'sm' | 'md' | 'lg' }) {
if (!studio) return <span className={`studio-mark none ${size}`} aria-hidden="true" />;
if (studio.logo) return <span className={`studio-mark ${size}`} aria-hidden="true"><img src={studio.logo} alt="" draggable={false} /></span>;
return <span className={`studio-mark studio-${studio.color} ${size}`} aria-hidden="true">{monogram(studio.name)}</span>;
}
/** Small "store only" marker (an app without an app folder). */
export function StoreOnlyTag() {
return <span className="chip outline so-tag" title={t('apps.storeOnlyHint')}><Icon name="cloud" />{t('apps.storeOnly')}</span>;
}

View file

@ -1,143 +0,0 @@
// One app card per product across studios and store accounts: folder matching, automatic pairing (same id, close id,
// same name), manual pair / unpair, links, studio moves, the ignore list, and the portfolio filter / sort / grouping.
import { describe, expect, test } from 'bun:test';
import type { Account, Project, ProjectSummary, StoreApp } from '../src/api';
import {
buildApps, filterSort, groupByStudio, type ListRow, NO_OVERRIDES, normId, normName, type Overrides, pairCandidates, storeTarget, studioCounts,
withIgnored, withLink, withPair, withStudio, withUnpair,
} from '../src/lib/identity';
import { crashCrossed, newLowReviews, releaseChanges } from '../src/lib/notify';
const P1 = '0a1b2c3d4e5f6071', A1 = '2c3d4e5f60718293', A2 = '3d4e5f6071829304';
const acc = (id: string, kind: 'play' | 'apple', studio: string | null): Account => ({ id, label: id, kind, created: '2026-10-01T00:00:00Z', studio });
const ios = (id: string, bundleId: string, name: string): StoreApp => ({ store: 'ios', id, bundleId, name, platforms: ['IOS'], icon: null });
const droid = (pkg: string, name: string): StoreApp => ({ store: 'android', id: pkg, bundleId: pkg, name, platforms: ['ANDROID'], icon: null });
const summary = (bundleId: string | null, pkg: string | null, appId: string | null = null): ProjectSummary => ({
dir: '/x', config: '/x/c', name: 'x', languages: ['en'], apple: bundleId ? { bundleId, appId } : null, play: pkg ? { packageName: pkg } : null,
platforms: [], products: 0, productIds: [], subscriptions: 0, subscriptionIds: [], catalog: { ios: [], android: [] }, shots: false, testflightGroups: 0,
});
const proj = (id: string, name: string, play: string | null, apple: string | null): Project => ({ id, path: `/apps/${id}`, name, playAccount: play, appleAccount: apple, added: '2026-10-01T00:00:00Z' });
const accounts = [acc(P1, 'play', 's1'), acc(A1, 'apple', 's1'), acc(A2, 'apple', 's2')];
const storeApps = [
{ account: P1, apps: [droid('com.example.prism', 'Prism'), droid('com.example.orbit', 'Orbit Hop'), droid('com.example.block', 'Block Garden'), droid('com.example.lantern.words', 'Word Lantern'), droid('com.example.tycoon', 'Pocket Tycoon')] },
{ account: A1, apps: [ios('101', 'com.example.prism', 'Prism'), ios('102', 'com.example.orbit', 'Orbit Hop'), ios('103', 'com.example.Block.ios', 'Block Garden HD'), ios('104', 'com.example.wordlantern', 'Word Lantern')] },
{ account: A2, apps: [ios('201', 'com.example.habit', 'Habit Hatch')] },
];
const prism = proj('p1', 'Prism Puddle', P1, A1);
const build = (o: Overrides = NO_OVERRIDES, projects = [prism]) => buildApps({ projects, accounts, storeApps, overrides: o, summaryOf: p => (p.id === 'p1' ? summary('com.example.prism', 'com.example.prism') : summary(null, null)) });
const byName = (apps: ReturnType<typeof build>, n: string) => apps.find(a => a.name === n)!;
describe('identity pairing', () => {
test('a folder takes the store apps its config names; the rest pair by id, close id, then name', () => {
const apps = build();
expect(apps.map(a => [a.name, a.pairing, !!a.ios, !!a.android])).toEqual([
['Prism Puddle', 'folder', true, true],
['Orbit Hop', 'id', true, true],
['Block Garden HD', 'close', true, true],
['Word Lantern', 'name', true, true],
['Pocket Tycoon', 'single', false, true],
['Habit Hatch', 'single', true, false],
]);
expect(byName(apps, 'Prism Puddle')).toMatchObject({ key: 'p1', target: 'p1', studio: 's1', ios: { key: `ios:${A1}:101` }, android: { key: `android:${P1}:com.example.prism` } });
const orbit = byName(apps, 'Orbit Hop');
expect(orbit.target).toBe(`store:ios:${A1}:102:com.example.orbit;android:${P1}:com.example.orbit`);
expect(orbit.key).toBe(orbit.target);
expect(orbit.ignoreKeys).toEqual([`app:ios:${A1}:102`, `app:android:${P1}:com.example.orbit`]);
expect(byName(apps, 'Habit Hatch').studio).toBe('s2');
});
test('the app id in the config wins over the bundle id; accounts mapped to the folder are preferred', () => {
const twin = [...storeApps, { account: A2, apps: [ios('999', 'com.example.prism', 'Prism (old team)')] }];
const apps = buildApps({ projects: [prism], accounts, storeApps: twin, overrides: NO_OVERRIDES, summaryOf: () => summary('com.example.prism', 'com.example.prism', '999') });
expect(apps[0]!.ios?.app.id).toBe('999');
const apps2 = buildApps({ projects: [prism], accounts, storeApps: twin, overrides: NO_OVERRIDES, summaryOf: () => summary('com.example.prism', 'com.example.prism') });
expect(apps2[0]!.ios?.account).toBe(A1);
});
test('unpair blocks the automatic pair; manual pair beats it', () => {
const o1 = withUnpair(NO_OVERRIDES, `ios:${A1}:102`, `android:${P1}:com.example.orbit`);
const apps1 = build(o1);
expect(apps1.filter(a => a.name === 'Orbit Hop').map(a => [!!a.ios, !!a.android, a.pairing])).toEqual([[false, true, 'single'], [true, false, 'single']]);
const o2 = withPair(o1, `ios:${A1}:102`, `android:${P1}:com.example.tycoon`);
expect(o2.unpairs).toHaveLength(1);
const apps2 = build(o2);
const manual = apps2.find(a => a.pairing === 'manual')!;
expect([manual.ios?.app.id, manual.android?.app.id]).toEqual(['102', 'com.example.tycoon']);
// pairing the unpaired two again drops the unpair
expect(withPair(o1, `ios:${A1}:102`, `android:${P1}:com.example.orbit`).unpairs).toEqual([]);
});
test('links: a store-only app joins a folder by hand', () => {
const orbit = byName(build(), 'Orbit Hop');
const fresh = proj('p2', 'Orbit (folder)', null, null);
const apps = build(withLink(NO_OVERRIDES, orbit, 'p2'), [prism, fresh]);
const linked = apps.find(a => a.key === 'p2')!;
expect([linked.ios?.app.id, linked.android?.app.id, linked.pairing]).toEqual(['102', 'com.example.orbit', 'folder']);
expect(apps.some(a => a.name === 'Orbit Hop' && !a.project)).toBe(false);
});
test('ignore: an app (all its store keys) or a whole account; studio moves', () => {
const tycoon = byName(build(), 'Pocket Tycoon');
const o = withIgnored(NO_OVERRIDES, tycoon.ignoreKeys, true);
expect(byName(build(o), 'Pocket Tycoon').ignored).toBe(true);
expect(withIgnored(o, tycoon.ignoreKeys, false).ignored).toEqual([]);
const noA1 = build(withIgnored(NO_OVERRIDES, [`account:${A1}`], true));
expect(noA1.some(a => a.ios?.account === A1)).toBe(false);
expect(byName(noA1, 'Orbit Hop').ios).toBeNull();
const moved = build(withStudio(NO_OVERRIDES, tycoon, 's2'));
expect(byName(moved, 'Pocket Tycoon').studio).toBe('s2');
const back = withStudio(withStudio(NO_OVERRIDES, tycoon, 's2'), tycoon, null);
expect(back.appStudio).toEqual([]);
expect(withStudio(NO_OVERRIDES, byName(build(), 'Prism Puddle'), 's9').appStudio).toEqual([{ key: 'project:p1', studio: 's9' }]);
expect(studioCounts(build(o))).toEqual({ s1: 4, s2: 1 });
});
test('accounts that are gone or never read add nothing', () => {
const apps = buildApps({ projects: [], accounts: [acc(P1, 'play', null)], storeApps: [{ account: 'deadbeefdeadbeef', apps: [droid('com.example.x', 'X')] }], overrides: NO_OVERRIDES, summaryOf: () => undefined });
expect(apps).toEqual([]);
});
test('helpers: normalised ids and names, store targets, pair candidates', () => {
expect(normId('com.Example.Block.ios')).toBe(normId('com.example.block'));
expect(normId('com.example.block-android')).toBe('comexampleblock');
expect(normName('Word Lantern!')).toBe(normName('word-lantern'));
expect(storeTarget(null, { key: 'k', account: P1, store: 'android', app: droid('com.a.b', 'B') })).toBe(`store:android:${P1}:com.a.b`);
const apps = build(withUnpair(NO_OVERRIDES, `ios:${A1}:102`, `android:${P1}:com.example.orbit`));
const lone = apps.find(a => a.name === 'Orbit Hop' && a.ios)!;
expect(pairCandidates(lone, apps)[0]!.android?.app.id).toBe('com.example.orbit');
expect(pairCandidates(byName(apps, 'Prism Puddle'), apps)).toEqual([]);
});
});
describe('portfolio list', () => {
const apps = build();
const rows: ListRow[] = apps.map((app, i) => ({ app, attention: [0, 3, 1, 0, 2, 0][i]!, blockers: [0, 1, 0, 0, 0, 0][i]!, updated: [`2026-10-0${i + 1}`, null, '2026-10-09', null, '2026-09-01', '2026-10-05'][i]! }));
test('filter by studio and search ids, sort by attention / recent / name', () => {
expect(filterSort(rows, { studio: 'all', query: '', sort: 'attention' }).map(r => r.app.name).slice(0, 3)).toEqual(['Orbit Hop', 'Pocket Tycoon', 'Block Garden HD']);
expect(filterSort(rows, { studio: 'all', query: '', sort: 'recent' }).map(r => r.app.name)[0]).toBe('Block Garden HD');
expect(filterSort(rows, { studio: 's2', query: '', sort: 'name' }).map(r => r.app.name)).toEqual(['Habit Hatch']);
expect(filterSort(rows, { studio: 'all', query: 'lantern.words', sort: 'name' }).map(r => r.app.name)).toEqual(['Word Lantern']);
expect(filterSort(rows, { studio: 'none', query: '', sort: 'name' })).toEqual([]);
});
test('groups follow the studios\' order, no studio last; ignored apps never listed', () => {
const g = groupByStudio(rows, [{ id: 's2' }, { id: 's1' }]);
expect(g.map(x => [x.studio, x.rows.length])).toEqual([['s2', 1], ['s1', 5]]);
const ignored = rows.map(r => (r.app.name === 'Habit Hatch' ? { ...r, app: { ...r.app, ignored: true } } : r));
expect(filterSort(ignored, { studio: 'all', query: '', sort: 'name' }).some(r => r.app.name === 'Habit Hatch')).toBe(false);
});
});
describe('notifications', () => {
const status = (phase: string) => ({ apps: [{ project: '/a', ok: true, app: { id: '/a', name: 'A', platforms: { ios: null, android: null } }, summary: null, check: null, catalog: null, storeErrors: {}, errors: [],
release: { source: 'live' as const, current: null, next: null, all: [{ store: 'ios' as const, version: '2.0', build: '1', state: phase, phase: phase as 'review', fraction: null, track: null }] } }], at: 'x' });
test('release phase changes, only against a previous read', () => {
expect(releaseChanges(null, status('review'))).toEqual([]);
expect(releaseChanges(status('review'), status('review'))).toEqual([]);
expect(releaseChanges(status('review'), status('approved'))).toEqual([{ project: '/a', name: 'A', store: 'ios', version: '2.0', from: 'review', to: 'approved' }]);
expect(releaseChanges(status('draft'), status('testing'))).toEqual([]);
});
test('new 1-2 star reviews and threshold crossings', () => {
const r = (id: string, rating: number) => ({ store: 'play' as const, id, rating, body: '', date: '2026-10-01' });
expect(newLowReviews(null, [r('a', 1)])).toEqual([]);
expect(newLowReviews([r('a', 1)], [r('a', 1), r('b', 2), r('c', 5)]).map(x => x.id)).toEqual(['b']);
const h = (crash: number) => ({ date: 'x', play: { window: { start: '', end: '', days: 28 }, anr: [], issues: [], crash: [{ date: '2026-10-01', dims: {}, values: { userPerceivedCrashRate: crash } }] } });
expect(crashCrossed(h(0.005), h(0.02))).toEqual(['crash']);
expect(crashCrossed(h(0.02), h(0.03))).toEqual([]);
expect(crashCrossed(null, h(0.03))).toEqual([]);
});
});

View file

@ -1,145 +0,0 @@
// The apps on a store account, and whether the account's key works. No storebound.config.ts needed: credentials come
// from the environment or .storebound/credentials.json of the current folder (the desktop app passes one account's
// key per call). Read-only.
// storebound apps list [--store apple|play] [--icons] [--json] every app the key can see (App Store Connect team /
// every Play developer account that invited the
// service account)
// storebound apps check [--store apple|play] [--json] auth OK / permission missing / key revoked, with the fix
import type { Args } from './lib/args';
import { ascKey, playServiceAccount } from './lib/credentials';
import type { AccountCheck, AppsListResult } from './lib/desktop-protocol';
import { PLAY_SCOPE, REPORTING_SCOPE, tokenSource } from './lib/google-auth';
import { log, printJson, warn } from './lib/log';
import { appleCheck, type Bytes, dataUrl, type Get, listAppleApps, listPlayApps, MAX_ICON_BYTES, playCheck } from './lib/store-apps';
import { textTable } from './lib/table';
import { ascClient } from './apple/asc';
import { REPORTING_API } from './play/google';
type Store = 'apple' | 'play';
function stores(args: Args, root: string): Store[] {
const s = args.get('store');
if (s === 'apple' || s === 'play') return [s];
if (s !== undefined) throw new Error('--store: apple or play');
// every store whose credentials are set (env, or .storebound/credentials.json in this folder)
const out: Store[] = [];
try { ascKey(root); out.push('apple'); } catch { /* not set */ }
try { playServiceAccount(root); out.push('play'); } catch { /* not set */ }
if (!out.length) throw new Error('no store credentials: set ASC_KEY_ID + ASC_ISSUER_ID + ASC_P8 and / or PLAY_SERVICE_ACCOUNT (env or .storebound/credentials.json)');
return out;
}
const bytes: Bytes = async url => {
const r = await fetch(url);
if (!r.ok) return null;
const len = Number(r.headers.get('content-length') ?? 0);
if (len > MAX_ICON_BYTES) { await r.body?.cancel(); return null; }
return { type: (r.headers.get('content-type') ?? 'image/png').split(';')[0]!, data: new Uint8Array(await r.arrayBuffer()) };
};
async function appleGet(root: string): Promise<Get> {
const c = await ascClient(root, '');
return path => c.asc('GET', path);
}
function googleGet(token: () => Promise<string>, base: string): Get {
return async path => {
for (let attempt = 0; ; attempt++) {
const r = await fetch(path.startsWith('http') ? path : base + path, { headers: { Authorization: 'Bearer ' + (await token()) } });
const t = await r.text();
if ((r.status === 429 || r.status >= 500) && attempt < 3) { await Bun.sleep(1500 * (attempt + 1)); continue; }
if (!r.ok) throw new Error(`GET ${path.replace(/^https:\/\/[^/]+/, '')} -> ${r.status} ${/^\s*</.test(t) ? '(HTML error page)' : t.slice(0, 800)}`);
return t ? JSON.parse(t) : {};
}
};
}
/** Play icon of one package: an edit is opened, the default language's icon listed, and the edit deleted (never committed). */
function playIcon(root: string): (pkg: string) => Promise<string | null> {
const token = tokenSource(playServiceAccount(root), PLAY_SCOPE);
const API = 'https://androidpublisher.googleapis.com/androidpublisher/v3/applications/';
const call = async (method: string, url: string) => {
const r = await fetch(url, { method, headers: { Authorization: 'Bearer ' + (await token()) } });
const t = await r.text();
if (!r.ok) throw new Error(`${method} -> ${r.status} ${t.slice(0, 300)}`);
return t ? JSON.parse(t) : {};
};
return async pkg => {
const base = API + encodeURIComponent(pkg);
const edit = await call('POST', `${base}/edits`);
try {
const details = await call('GET', `${base}/edits/${edit.id}/details`);
const lang = details.defaultLanguage ?? 'en-US';
const imgs = await call('GET', `${base}/edits/${edit.id}/listings/${encodeURIComponent(lang)}/icon`);
const url = imgs.images?.[0]?.url;
if (typeof url !== 'string' || !/^https:\/\/[^/]+\.googleusercontent\.com\//.test(url)) return null;
const img = await bytes(`${url}=s128`);
return img && img.data.length <= MAX_ICON_BYTES ? dataUrl(img.type, img.data) : null;
} finally {
await call('DELETE', `${base}/edits/${edit.id}`).catch(() => {});
}
};
}
export async function listApps(store: Store, root: string, icons: boolean): Promise<AppsListResult> {
const at = new Date().toISOString();
if (store === 'apple') {
const r = await listAppleApps(await appleGet(root), { icons, bytes });
return { store: 'ios', ...r, at };
}
const sa = playServiceAccount(root);
const r = await listPlayApps(googleGet(tokenSource(sa, REPORTING_SCOPE), REPORTING_API), icons ? { icon: playIcon(root) } : {});
return { store: 'android', ...r, at };
}
export async function checkAccount(store: Store, root: string): Promise<AccountCheck> {
if (store === 'apple') {
try {
const page = await (await appleGet(root))('/v1/apps?fields[apps]=bundleId&limit=200');
return appleCheck({ apps: (page.data ?? []).length });
} catch (e) { return appleCheck({ error: e }); }
}
let principal: string | null = null;
try {
const sa = playServiceAccount(root);
principal = sa.client_email;
const page = await googleGet(tokenSource(sa, REPORTING_SCOPE), REPORTING_API)('/apps:search?pageSize=1000');
return playCheck(principal, { apps: (page.apps ?? []).length });
} catch (e) { return playCheck(principal, { error: e }); }
}
export async function run(args: Args): Promise<void> {
const sub = args._[0];
const root = process.cwd();
const json = args.has('json');
if (sub === 'list') {
const out: AppsListResult[] = [];
for (const s of stores(args, root)) {
try { out.push(await listApps(s, root, args.has('icons'))); } catch (e) {
if (args.get('store')) throw e;
warn('apps', `${s}: ${(e as Error).message.split('\n')[0]}`);
}
}
if (json) { printJson(args.get('store') ? out[0] : out); return; }
for (const r of out) {
log('apps', `${r.store === 'ios' ? 'App Store Connect' : 'Google Play'}: ${r.apps.length} apps`);
console.log(textTable(['name', 'id', 'bundle / package', 'platforms', 'newest'], r.apps.map(a => [a.name, a.id, a.bundleId, a.platforms.join(' '), a.latest ? `${a.latest.version} ${a.latest.state}` : ''])));
for (const w of r.warnings) warn('apps', w);
}
return;
}
if (sub === 'check') {
const out: AccountCheck[] = [];
for (const s of stores(args, root)) out.push(await checkAccount(s, root));
if (json) { printJson(args.get('store') ? out[0] : out); return; }
for (const c of out) {
log('apps', `${c.store === 'ios' ? 'App Store Connect' : 'Google Play'}: ${c.status} · ${c.message}`);
if (c.fix) console.log(` fix: ${c.fix}`);
if (c.docs) console.log(` ${c.docs}`);
}
if (out.some(c => c.status !== 'ok')) process.exitCode = 1;
return;
}
console.error('usage: storebound apps list [--store apple|play] [--icons] [--json] | apps check [--store apple|play] [--json]');
process.exit(2);
}

View file

@ -13,7 +13,6 @@ const PLAIN: Record<string, [() => Promise<Plain>, string]> = {
'install': [() => import('./install'), 'skills + MCP server for --agent claude|codex|cursor|copilot|windsurf|gemini|opencode'], 'install': [() => import('./install'), 'skills + MCP server for --agent claude|codex|cursor|copilot|windsurf|gemini|opencode'],
'mcp': [async () => ({ run: async () => (await import('./mcp')).serve() }), 'stdio MCP server wrapping these commands (for any MCP-capable AI tool)'], 'mcp': [async () => ({ run: async () => (await import('./mcp')).serve() }), 'stdio MCP server wrapping these commands (for any MCP-capable AI tool)'],
'serve': [() => import('./serve'), '--stdio: JSON-RPC session for the storebound desktop app (dry runs; writes need a host confirm token)'], 'serve': [() => import('./serve'), '--stdio: JSON-RPC session for the storebound desktop app (dry runs; writes need a host confirm token)'],
'apps': [() => import('./apps'), 'list (every app the store keys can see: App Store Connect team, Play developer accounts; --icons) | check (key works / permission missing / revoked, with the fix); --store apple|play, --json; read-only'],
'doctor': [() => import('./doctor'), 'local tools for screenshots, previews, icons and captures (ffmpeg, Chrome, playwright, Xcode, adb, git) and how to install what is missing; --json'], 'doctor': [() => import('./doctor'), 'local tools for screenshots, previews, icons and captures (ffmpeg, Chrome, playwright, Xcode, adb, git) and how to install what is missing; --json'],
'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios <path>)'], 'privacy-manifest': [() => import('./privacy-manifest'), 'iOS PrivacyInfo.xcprivacy + required-reason API + SDK manifest scan (--ios <path>)'],
}; };

View file

@ -29,7 +29,7 @@ export interface MethodDescriptor {
method: string; method: string;
title: string; title: string;
description: string; description: string;
kind: 'read' | 'write' | 'session' | 'system' | 'portfolio' | 'account'; kind: 'read' | 'write' | 'session' | 'system' | 'portfolio';
/** Talks to a store API or the internet. */ /** Talks to a store API or the internet. */
network: boolean; network: boolean;
/** Replaces existing data on a store (screenshots, whole forms). */ /** Replaces existing data on a store (screenshots, whole forms). */
@ -154,8 +154,6 @@ export interface AppStatus {
/** Release trains; `source: none` offline (no store data read). `all`: every store release read (live only). */ /** Release trains; `source: none` offline (no store data read). `all`: every store release read (live only). */
release: { source: 'none' | 'live'; current: ReleaseTrain | null; next: ReleaseTrain | null; all?: StoreRelease[] }; release: { source: 'none' | 'live'; current: ReleaseTrain | null; next: ReleaseTrain | null; all?: StoreRelease[] };
catalog: CatalogParity | null; catalog: CatalogParity | null;
/** A store-only app read through a generated config (no app folder). */
virtual?: boolean;
/** live only: per-platform read errors ("unknown, never false"). */ /** live only: per-platform read errors ("unknown, never false"). */
storeErrors: { ios?: string; android?: string }; storeErrors: { ios?: string; android?: string };
errors: string[]; errors: string[];
@ -206,44 +204,3 @@ export interface DraftsResult { dir: string; drafts: ReplyDraft[]; problems: str
/** project.icon: the icon as a data: URL (PNG / JPEG / WebP / SVG, at most 1.5 MB), or null. */ /** project.icon: the icon as a data: URL (PNG / JPEG / WebP / SVG, at most 1.5 MB), or null. */
export interface IconResult { path: string | null; dataUrl: string | null } export interface IconResult { path: string | null; dataUrl: string | null }
// ---- Store accounts and the apps on them (D3: many studios, many accounts) ----
/** One app record on a store, as `storebound apps list` reads it. */
export interface StoreApp {
store: 'ios' | 'android';
/** App Store Connect app id (numeric) / Play package name. */
id: string;
/** iOS bundle id / Android package name. */
bundleId: string;
name: string;
/** App Store version platforms (IOS, MAC_OS, TV_OS, VISION_OS); ["ANDROID"] on Play. */
platforms: string[];
sku?: string | null;
primaryLocale?: string | null;
/** Newest App Store version and its state (App Store only). */
latest?: { version: string; state: string; platform?: string | null } | null;
/** 128 px icon as a data: URL (with --icons), else null. */
icon?: string | null;
}
export interface AppsListResult { store: 'ios' | 'android'; apps: StoreApp[]; warnings: string[]; at: string }
/** Health of one store account: does the key work, and can it see apps. */
export interface AccountCheck {
store: 'ios' | 'android';
status: 'ok' | 'no-apps' | 'permission' | 'revoked' | 'api-disabled' | 'error';
/** Play: the service account email (to invite in Play Console). Never a secret. */
principal: string | null;
apps: number | null;
message: string;
/** What to do, in words. */
fix: string | null;
docs: string | null;
}
/**
* A store-only app (no app folder yet): the sidecar reads it through a generated minimal config (store ids only) in
* its temp folder. Read methods only.
*/
export interface VirtualProject { name: string; apple?: { bundleId: string; appId?: string | null } | null; play?: { packageName: string } | null }

View file

@ -1,142 +0,0 @@
// Store-side app lists and account health, for `storebound apps list | check` and the desktop's "import from the
// stores". Pure over an injected HTTP getter, so tests run on recorded responses. Read-only: GET requests only, plus
// (Play icons, opt-in) an edit that is opened and deleted without a commit.
//
// App Store Connect: GET /v1/apps (paged), the newest appStoreVersions per app (platform, version, state) and, with
// icons, the newest build's iconAssetToken (an image template on Apple's CDN, fetched here and returned as a data URL:
// the desktop window loads no remote content).
// https://developer.apple.com/documentation/appstoreconnectapi/list_apps
// https://developer.apple.com/documentation/appstoreconnectapi/build (attribute iconAssetToken)
// Google Play: the Play Developer Reporting API `apps:search` lists every app the service account can see, across all
// developer accounts it was invited to.
// https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/apps/search
import type { AccountCheck, StoreApp } from './desktop-protocol';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type J = any;
/** GET a JSON path (ASC: relative to the API root, or a full `links.next` URL). Throws Error("... -> <status> <body>"). */
export type Get = (path: string) => Promise<J>;
/** Bytes of an image URL (icons). */
export type Bytes = (url: string) => Promise<{ type: string; data: Uint8Array } | null>;
/** Largest icon kept as a data URL; bigger ones are dropped (the window shows a monogram instead). */
export const MAX_ICON_BYTES = 200_000;
export const dataUrl = (type: string, data: Uint8Array): string => `data:${type};base64,${Buffer.from(data).toString('base64')}`;
/** ASC iconAssetToken.templateUrl -> a 128 px PNG URL. */
export const iconUrl = (templateUrl: string, px = 128): string =>
templateUrl.replace('{w}', String(px)).replace('{h}', String(px)).replace('{c}', 'bb').replace('{f}', 'png');
const ASC_STATE = (v: J): string => v?.attributes?.appVersionState ?? v?.attributes?.appStoreState ?? '';
/** Every App Store Connect app the key's team can see, with platforms, newest version and (opt-in) icon. */
export async function listAppleApps(get: Get, o: { icons?: boolean; bytes?: Bytes; limit?: number } = {}): Promise<{ apps: StoreApp[]; warnings: string[] }> {
const warnings: string[] = [];
const raw: J[] = [];
let url: string | null = '/v1/apps?fields[apps]=name,bundleId,sku,primaryLocale&limit=200';
while (url && raw.length < (o.limit ?? 1000)) {
const page: J = await get(url);
raw.push(...(page.data ?? []));
url = page.links?.next ?? null;
}
const apps: StoreApp[] = [];
for (const a of raw) {
const app: StoreApp = {
store: 'ios', id: String(a.id), bundleId: String(a.attributes?.bundleId ?? ''), name: String(a.attributes?.name ?? a.attributes?.bundleId ?? a.id),
platforms: [], sku: a.attributes?.sku ?? null, primaryLocale: a.attributes?.primaryLocale ?? null, latest: null, icon: null,
};
try {
const vs: J[] = (await get(`/v1/apps/${a.id}/appStoreVersions?limit=5&fields[appStoreVersions]=platform,versionString,appStoreState,appVersionState,createdDate`)).data ?? [];
app.platforms = [...new Set(vs.map(v => String(v.attributes?.platform ?? '')).filter(Boolean))];
const v = vs[0];
if (v) app.latest = { version: String(v.attributes?.versionString ?? ''), state: ASC_STATE(v), platform: v.attributes?.platform ?? null };
} catch (e) { warnings.push(`${app.bundleId}: versions not read (${short(e)})`); }
if (o.icons && o.bytes) {
try {
const b: J = (await get(`/v1/builds?filter[app]=${a.id}&sort=-uploadedDate&limit=1&fields[builds]=iconAssetToken,version`)).data?.[0];
const tpl = b?.attributes?.iconAssetToken?.templateUrl;
if (typeof tpl === 'string' && /^https:\/\/[^/]+\.mzstatic\.com\//.test(tpl)) {
const img = await o.bytes(iconUrl(tpl));
if (img && img.data.length <= MAX_ICON_BYTES) app.icon = dataUrl(img.type, img.data);
}
} catch (e) { warnings.push(`${app.bundleId}: icon not read (${short(e)})`); }
}
apps.push(app);
}
return { apps: apps.sort((x, y) => x.name.localeCompare(y.name)), warnings };
}
/** Every app a Play service account can see (all developer accounts that invited it), from the Reporting API. */
export async function listPlayApps(get: Get, o: { icon?: (pkg: string) => Promise<string | null> } = {}): Promise<{ apps: StoreApp[]; warnings: string[] }> {
const warnings: string[] = [];
const raw: J[] = [];
let token = '';
for (let i = 0; i < 50; i++) {
const page: J = await get(`/apps:search?pageSize=1000${token ? `&pageToken=${encodeURIComponent(token)}` : ''}`);
raw.push(...(page.apps ?? []));
token = page.nextPageToken ?? '';
if (!token) break;
}
const apps: StoreApp[] = [];
for (const a of raw) {
const pkg = String(a.packageName ?? String(a.name ?? '').replace(/^apps\//, ''));
if (!pkg) continue;
const app: StoreApp = { store: 'android', id: pkg, bundleId: pkg, name: String(a.displayName || pkg), platforms: ['ANDROID'], sku: null, primaryLocale: null, latest: null, icon: null };
if (o.icon) {
try { app.icon = await o.icon(pkg); } catch (e) { warnings.push(`${pkg}: icon not read (${short(e)})`); }
}
apps.push(app);
}
return { apps: apps.sort((x, y) => x.name.localeCompare(y.name)), warnings };
}
const short = (e: unknown): string => String((e as Error)?.message ?? e).split('\n')[0]!.slice(0, 200);
const statusOf = (e: unknown): number | null => { const m = /-> (\d{3})\b/.exec(String((e as Error)?.message ?? e)); return m ? Number(m[1]) : null; };
export const ASC_KEYS_URL = 'https://appstoreconnect.apple.com/access/integrations/api';
export const PLAY_USERS_URL = 'https://play.google.com/console/developers/users-and-permissions';
export const REPORTING_API_URL = 'https://console.cloud.google.com/apis/library/playdeveloperreporting.googleapis.com';
/** App Store Connect key health from a GET /v1/apps?limit=1 outcome. */
export function appleCheck(outcome: { apps: number } | { error: unknown }): AccountCheck {
if ('apps' in outcome) {
return outcome.apps > 0
? { store: 'ios', status: 'ok', principal: null, apps: outcome.apps, message: 'The key works and can read the team\'s apps.', fix: null, docs: null }
: { store: 'ios', status: 'no-apps', principal: null, apps: 0, message: 'The key works, but the team has no apps it can see.', fix: 'Create the app record in App Store Connect (Apps > + > New App), or check that this is the team you meant.', docs: null };
}
const code = statusOf(outcome.error), msg = short(outcome.error);
if (/not set|not found|PRIVATE KEY|asn1|decoder|key/i.test(msg) && code === null)
return { store: 'ios', status: 'error', principal: null, apps: null, message: `The key could not be used: ${msg}`, fix: 'Add the key again: key id, issuer id and the AuthKey_<id>.p8 file from App Store Connect.', docs: ASC_KEYS_URL };
if (code === 401)
return { store: 'ios', status: 'revoked', principal: null, apps: null, message: 'App Store Connect refused the key (401): it was revoked, or the key id / issuer id do not belong to this .p8.',
fix: 'Users and Access > Integrations > App Store Connect API: check the key is still active, or generate a new one (role App Manager or Admin) and add it here again.', docs: ASC_KEYS_URL };
if (code === 403)
return { store: 'ios', status: 'permission', principal: null, apps: null, message: 'The key works but its role may not read apps (403).',
fix: 'Use a team key with the App Manager or Admin role (Users and Access > Integrations > App Store Connect API), or ask the Account Holder for one.', docs: ASC_KEYS_URL };
return { store: 'ios', status: 'error', principal: null, apps: null, message: `Could not reach App Store Connect: ${msg}`, fix: 'Check the connection and try again.', docs: null };
}
/** Play service account health from the token exchange and an `apps:search` outcome. */
export function playCheck(principal: string | null, outcome: { apps: number } | { error: unknown }): AccountCheck {
const who = principal ?? 'the service account';
const invite = `Play Console > Users and permissions > Invite new users: add ${who}. Account permissions: "View app information and download bulk reports (read-only)"; per app, as needed: "Manage store presence", "Manage testing tracks", "Release to production, exclude devices and use Play App Signing" (rollouts), "Reply to reviews", "Manage orders and subscriptions". One service account can be invited to several developer accounts.`;
if ('apps' in outcome) {
return outcome.apps > 0
? { store: 'android', status: 'ok', principal, apps: outcome.apps, message: `The service account can see ${outcome.apps} app${outcome.apps === 1 ? '' : 's'}.`, fix: null, docs: null }
: { store: 'android', status: 'permission', principal, apps: 0, message: 'The key works, but no developer account has invited this service account (it sees no apps).', fix: invite, docs: PLAY_USERS_URL };
}
const code = statusOf(outcome.error), msg = short(outcome.error);
if (code === 403 && /SERVICE_DISABLED|has not been used|is disabled|accessNotConfigured/i.test(msg))
return { store: 'android', status: 'api-disabled', principal, apps: null, message: 'The Google Play Developer Reporting API is off in this service account\'s Google Cloud project.',
fix: 'Google Cloud console > APIs & Services > Library: enable "Google Play Developer Reporting API" (and "Google Play Android Developer API") in the service account\'s project, wait a few minutes, test again.', docs: REPORTING_API_URL };
if (code === null && /invalid_grant|Invalid JWT|account not found|disabled/i.test(msg))
return { store: 'android', status: 'revoked', principal, apps: null, message: `Google refused the key: ${msg}`,
fix: 'The JSON key was deleted or the service account disabled. Google Cloud console > IAM & Admin > Service accounts > Keys: add a new JSON key, then add it here again.', docs: null };
if (code === 403 || code === 401)
return { store: 'android', status: 'permission', principal, apps: null, message: `The service account is missing a permission (${code}).`, fix: invite, docs: PLAY_USERS_URL };
if (/not a Google service account|PLAY_SERVICE_ACCOUNT/i.test(msg))
return { store: 'android', status: 'error', principal, apps: null, message: msg, fix: 'Add the service account JSON key again (Google Cloud console > IAM & Admin > Service accounts > Keys > Add key > JSON).', docs: null };
return { store: 'android', status: 'error', principal, apps: null, message: `Could not reach Google: ${msg}`, fix: 'Check the connection and try again.', docs: null };
}

View file

@ -9,15 +9,13 @@
// - writes that are dry runs unless the host sends a confirm token (lib/confirm-token.ts) it minted after the owner // - writes that are dry runs unless the host sends a confirm token (lib/confirm-token.ts) it minted after the owner
// confirmed a native dialog showing that dry run. // confirmed a native dialog showing that dry run.
// Nothing here submits for review, releases or publishes: those methods do not exist (tests/serve.test.ts). // Nothing here submits for review, releases or publishes: those methods do not exist (tests/serve.test.ts).
import { createHash } from 'node:crypto'; import { existsSync, statSync } from 'node:fs';
import { existsSync, mkdirSync, mkdtempSync, statSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { isAbsolute, join, resolve } from 'node:path'; import { isAbsolute, join, resolve } from 'node:path';
import pkg from '../package.json' with { type: 'json' }; import pkg from '../package.json' with { type: 'json' };
import { canonical, parseSecret, TokenGuard } from './lib/confirm-token'; import { parseSecret, TokenGuard } from './lib/confirm-token';
import { CONFIG_NAMES } from './lib/config'; import { CONFIG_NAMES } from './lib/config';
import { import {
DESKTOP_PROTOCOL, ERR, type AppStatus, type MethodDescriptor, type PortfolioResult, type ProjectSummary, type ToolResult, type VirtualProject, DESKTOP_PROTOCOL, ERR, type AppStatus, type MethodDescriptor, type PortfolioResult, type ProjectSummary, type ToolResult,
} from './lib/desktop-protocol'; } from './lib/desktop-protocol';
import { appIdentity, appleProductIds, appleReleases, catalogParity, playProductIds, playReleases, releaseTrains } from './lib/portfolio'; import { appIdentity, appleProductIds, appleReleases, catalogParity, playProductIds, playReleases, releaseTrains } from './lib/portfolio';
import { detectTools } from './lib/tools'; import { detectTools } from './lib/tools';
@ -88,20 +86,10 @@ const SYSTEM: MethodDescriptor[] = [
{ method: 'system.tools', title: 'Local tools', description: 'Optional local tools with versions and where they come from (ffmpeg, ffprobe, Chrome, Xcode / simctl, adb, git); screenshot, video and capture features need them.', kind: 'system', network: false, destructive: false, json: true, args: obj({}) }, { method: 'system.tools', title: 'Local tools', description: 'Optional local tools with versions and where they come from (ffmpeg, ffprobe, Chrome, Xcode / simctl, adb, git); screenshot, video and capture features need them.', kind: 'system', network: false, destructive: false, json: true, args: obj({}) },
{ method: 'project.inspect', title: 'Inspect a project', description: 'Offline summary of a folder\'s storebound.config.ts (name, store ids, languages, products).', kind: 'read', network: false, destructive: false, json: true, { method: 'project.inspect', title: 'Inspect a project', description: 'Offline summary of a folder\'s storebound.config.ts (name, store ids, languages, products).', kind: 'read', network: false, destructive: false, json: true,
args: obj({ project: { type: 'string', description: 'Absolute folder path' } }, ['project']) }, args: obj({ project: { type: 'string', description: 'Absolute folder path' } }, ['project']) },
{ method: 'apps.list', title: 'Apps on a store account', description: 'Every app one store account can see (App Store Connect team: GET /v1/apps with platforms and the newest version; Google Play: Reporting API apps:search over every developer account that invited the service account), optional 128 px icons. Credentials of exactly one account in params.credentials. Read-only.', kind: 'account', network: true, destructive: false, json: true,
args: obj({ credentials: { type: 'object' }, args: { type: 'object' } }, ['credentials']) },
{ method: 'account.check', title: 'Check a store account', description: 'Does the key work, and can it see apps: ok, no-apps, permission (with the Play Console / App Store Connect fix), revoked, api-disabled. Read-only.', kind: 'account', network: true, destructive: false, json: true,
args: obj({ credentials: { type: 'object' } }, ['credentials']) },
{ method: 'portfolio.status', title: 'Portfolio status', description: 'Apps (one per project folder) across iOS and Android: identity, offline config check, catalog parity; with live, release trains (current / next version on both stores) and live catalog parity from App Store and Google Play status (read-only).', kind: 'portfolio', network: true, destructive: false, json: true, { method: 'portfolio.status', title: 'Portfolio status', description: 'Apps (one per project folder) across iOS and Android: identity, offline config check, catalog parity; with live, release trains (current / next version on both stores) and live catalog parity from App Store and Google Play status (read-only).', kind: 'portfolio', network: true, destructive: false, json: true,
args: obj({ projects: { type: 'array' }, live: { type: 'boolean', default: false } }, ['projects']) }, args: obj({ projects: { type: 'array' }, live: { type: 'boolean', default: false } }, ['projects']) },
]; ];
/** Read methods a store-only app (params.virtual, no app folder) may use: store reads that need only the store ids. */
export const VIRTUAL_READS = new Set(['apple_status', 'play_status', 'health', 'reviews_list', 'apple_testflight_status', 'apple_ppo_status']);
const PKG_RE = /^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z0-9_]+)+$/;
const BUNDLE_RE = /^[A-Za-z0-9][A-Za-z0-9.-]{0,154}$/;
export function describeMethods(): MethodDescriptor[] { export function describeMethods(): MethodDescriptor[] {
return [...SYSTEM, ...DESKTOP_TOOLS.map(t => ({ return [...SYSTEM, ...DESKTOP_TOOLS.map(t => ({
method: methodName(t.name), title: t.title, description: t.description, kind: t.write ? 'write' as const : 'read' as const, method: methodName(t.name), title: t.title, description: t.description, kind: t.write ? 'write' as const : 'read' as const,
@ -125,55 +113,6 @@ export function checkProject(p: unknown): string {
return dir; return dir;
} }
/** Checks a params.virtual object (store ids only). */
export function checkVirtual(v: unknown): VirtualProject {
if (typeof v !== 'object' || v === null || Array.isArray(v)) throw new RpcError(ERR.invalidParams, 'virtual: object expected');
const o = v as Record<string, unknown>;
for (const k of Object.keys(o)) if (!['name', 'apple', 'play'].includes(k)) throw new RpcError(ERR.invalidParams, `virtual.${k}: unknown`);
const name = typeof o.name === 'string' && o.name.trim() && o.name.length <= 120 ? o.name.trim() : null;
if (!name) throw new RpcError(ERR.invalidParams, 'virtual.name: 1-120 characters');
const a = o.apple as Record<string, unknown> | null | undefined, p = o.play as Record<string, unknown> | null | undefined;
if (!a && !p) throw new RpcError(ERR.invalidParams, 'virtual: apple and / or play');
const out: VirtualProject = { name };
if (a) {
if (typeof a.bundleId !== 'string' || !BUNDLE_RE.test(a.bundleId) || !a.bundleId.includes('.')) throw new RpcError(ERR.invalidParams, 'virtual.apple.bundleId: a bundle id');
if (a.appId !== undefined && a.appId !== null && (typeof a.appId !== 'string' || !/^\d{1,20}$/.test(a.appId))) throw new RpcError(ERR.invalidParams, 'virtual.apple.appId: digits');
out.apple = { bundleId: a.bundleId, appId: (a.appId as string | null | undefined) ?? null };
}
if (p) {
if (typeof p.packageName !== 'string' || !PKG_RE.test(p.packageName)) throw new RpcError(ERR.invalidParams, 'virtual.play.packageName: a package name');
out.play = { packageName: p.packageName };
}
return out;
}
/** The minimal config of a store-only app (store ids, placeholder links), as storebound.config.json. */
export function virtualConfig(v: VirtualProject): Record<string, unknown> {
return {
app: { name: v.name, privacyPolicyUrl: 'https://example.com/privacy', supportUrl: 'https://example.com/support', website: 'https://example.com/',
contactEmail: 'store-only@example.com', platforms: [...(v.apple ? ['ios'] : []), ...(v.play ? ['android'] : [])] },
languages: [{ id: 'en', play: 'en-US', apple: 'en-US' }],
...(v.apple ? { apple: { bundleId: v.apple.bundleId, ...(v.apple.appId ? { appId: v.apple.appId } : {}) } } : {}),
...(v.play ? { play: { packageName: v.play.packageName } } : {}),
};
}
let virtualRoot: string | null = null;
/** A folder (in this session's temp folder) holding the generated config of a store-only app. */
export function virtualDir(v: VirtualProject): string {
virtualRoot ??= mkdtempSync(join(tmpdir(), 'storebound-virtual-'));
const dir = join(virtualRoot, createHash('sha256').update(canonical(v as unknown as Record<string, unknown>)).digest('hex').slice(0, 20));
if (!existsSync(join(dir, 'storebound.config.json'))) {
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, 'storebound.config.json'), JSON.stringify(virtualConfig(v), null, 2) + '\n');
}
return dir;
}
/** An empty folder for commands that need no project (apps list / check): no stray .storebound/credentials.json. */
let neutral: string | null = null;
const neutralDir = (): string => (neutral ??= mkdtempSync(join(tmpdir(), 'storebound-account-')));
const cut = (s: string): string => (s.length > MAX_OUTPUT ? `[... first ${s.length - MAX_OUTPUT} characters cut ...]\n` + s.slice(-MAX_OUTPUT) : s); const cut = (s: string): string => (s.length > MAX_OUTPUT ? `[... first ${s.length - MAX_OUTPUT} characters cut ...]\n` + s.slice(-MAX_OUTPUT) : s);
function credentialsOf(v: unknown): Record<string, string> { function credentialsOf(v: unknown): Record<string, string> {
@ -258,8 +197,6 @@ export class Session {
case 'system.tools': return localTools(); case 'system.tools': return localTools();
case 'project.inspect': return this.inspect(checkProject(params.project), {}, id); case 'project.inspect': return this.inspect(checkProject(params.project), {}, id);
case 'portfolio.status': return this.portfolio(params, id); case 'portfolio.status': return this.portfolio(params, id);
case 'apps.list': return this.account(['apps', 'list'], params, id, true);
case 'account.check': return this.account(['apps', 'check'], params, id, false);
} }
const tool = byMethod.get(method); const tool = byMethod.get(method);
if (!tool) throw new RpcError(ERR.methodNotFound, `Method not found: ${method}`); if (!tool) throw new RpcError(ERR.methodNotFound, `Method not found: ${method}`);
@ -267,13 +204,8 @@ export class Session {
} }
private async tool(method: string, t: ToolDef, params: Json, id: Id): Promise<ToolResult> { private async tool(method: string, t: ToolDef, params: Json, id: Id): Promise<ToolResult> {
for (const k of Object.keys(params)) if (!['project', 'args', 'dryRun', 'confirmToken', 'credentials', 'virtual'].includes(k)) throw new RpcError(ERR.invalidParams, `unknown param: ${k}`); for (const k of Object.keys(params)) if (!['project', 'args', 'dryRun', 'confirmToken', 'credentials'].includes(k)) throw new RpcError(ERR.invalidParams, `unknown param: ${k}`);
let project: string; const project = NEW_PROJECT.has(t.name) ? checkNewProject(params.project) : checkProject(params.project);
if (params.virtual !== undefined) {
if (params.project !== undefined) throw new RpcError(ERR.invalidParams, 'project or virtual, not both');
if (t.write || !VIRTUAL_READS.has(t.name)) throw new RpcError(ERR.invalidParams, `${method}: needs an app folder (store-only apps have store reads only)`);
project = virtualDir(checkVirtual(params.virtual));
} else project = NEW_PROJECT.has(t.name) ? checkNewProject(params.project) : checkProject(params.project);
const args = (params.args ?? {}) as Json; const args = (params.args ?? {}) as Json;
if (typeof args !== 'object' || args === null || Array.isArray(args)) throw new RpcError(ERR.invalidParams, 'args must be an object'); if (typeof args !== 'object' || args === null || Array.isArray(args)) throw new RpcError(ERR.invalidParams, 'args must be an object');
if ('dry_run' in args) throw new RpcError(ERR.invalidParams, 'args.dry_run: use params.dryRun'); if ('dry_run' in args) throw new RpcError(ERR.invalidParams, 'args.dry_run: use params.dryRun');
@ -304,23 +236,6 @@ export class Session {
}; };
} }
/** apps.list / account.check: one account's credentials, no project folder. */
private async account(cmd: string[], params: Json, id: Id, list: boolean): Promise<unknown> {
for (const k of Object.keys(params)) if (!['credentials', 'args'].includes(k)) throw new RpcError(ERR.invalidParams, `unknown param: ${k}`);
const env = credentialsOf(params.credentials);
const play = !!env.PLAY_SERVICE_ACCOUNT, apple = !!(env.ASC_KEY_ID || env.ASC_ISSUER_ID || env.ASC_P8);
if (play === apple) throw new RpcError(ERR.invalidParams, 'credentials: exactly one store account (a Play service account, or an App Store Connect key)');
const args = (params.args ?? {}) as Json;
if (typeof args !== 'object' || args === null || Array.isArray(args)) throw new RpcError(ERR.invalidParams, 'args must be an object');
for (const k of Object.keys(args)) if (!(list && k === 'icons')) throw new RpcError(ERR.invalidParams, `args.${k}: unknown`);
if (args.icons !== undefined && typeof args.icons !== 'boolean') throw new RpcError(ERR.invalidParams, 'args.icons: boolean');
const argv = [...cmd, '--store', play ? 'play' : 'apple', ...(args.icons === true ? ['--icons'] : []), '--json'];
const r = await this.track(id, this.run(argv, { cwd: neutralDir(), env, machine: true, onLine: (line, stream) => this.progress(id, { line, stream }) })).result;
if (r.cancelled || this.cancelled.has(id)) throw new RpcError(ERR.cancelled, 'Request cancelled');
if (r.data === undefined) throw new RpcError(ERR.internal, lastLine(r.out) || `exit ${r.code}`);
return r.data;
}
private progress(id: Id, p: Json): void { private progress(id: Id, p: Json): void {
this.send({ jsonrpc: '2.0', method: 'progress', params: { requestId: id, ...p } }); this.send({ jsonrpc: '2.0', method: 'progress', params: { requestId: id, ...p } });
} }
@ -340,27 +255,18 @@ export class Session {
const out: AppStatus[] = new Array(list.length); const out: AppStatus[] = new Array(list.length);
let done = 0; let done = 0;
const one = async (i: number): Promise<void> => { const one = async (i: number): Promise<void> => {
const raw = list[i] as unknown; const raw = list[i];
// a store-only app: { key: "store:...", virtual: { name, apple?, play? } } const e: AppStatus = { project: String(raw), ok: false, app: null, summary: null, check: null, release: { source: 'none', current: null, next: null }, catalog: null, storeErrors: {}, errors: [] };
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: [] };
out[i] = e; out[i] = e;
try { try {
let dir: string; const dir = checkProject(raw);
if (virt) { e.project = dir;
if (typeof virt.key !== 'string' || !STORE_KEY_RE.test(virt.key)) throw new RpcError(ERR.invalidParams, 'projects[].key: a store target key');
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); const summary = e.summary = await this.inspect(dir, env, id);
e.app = appIdentity(summary); e.app = appIdentity(summary);
e.catalog = catalogParity(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 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; 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: [] }; 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) { if (live) {
const store = async (argv: string[]): Promise<{ data?: unknown; error?: string }> => { 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; const r = await this.track(id, this.run(argv, { cwd: dir, env, machine: true })).result;
@ -388,9 +294,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*/, '') ?? ''; 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. */ /** Optional local tools with versions; app-managed copies (STOREBOUND_TOOL_PATH / STOREBOUND_CHROME) included. */

View file

@ -1,256 +0,0 @@
// storebound apps list / check (D3: many studios, many store accounts): parsing of recorded App Store Connect and
// Play Reporting API responses, account health classification, the CLI over a mocked fetch, and the serve methods
// (apps.list, account.check, store-only apps through a generated config).
import { afterEach, describe, expect, test } from 'bun:test';
import { generateKeyPairSync } from 'node:crypto';
import { existsSync, mkdtempSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { checkAccount, listApps } from '../cli/apps';
import { ERR } from '../cli/lib/desktop-protocol';
import type { RunOptions, Running } from '../cli/lib/runner';
import { appleCheck, iconUrl, listAppleApps, listPlayApps, playCheck } from '../cli/lib/store-apps';
import { checkVirtual, describeMethods, Session, STORE_KEY_RE, VIRTUAL_READS, virtualConfig, virtualDir } from '../cli/serve';
import { validateConfig } from '../cli/lib/config';
type J = Record<string, unknown>;
// ---- recorded responses (shapes as the APIs return them; ids and names are placeholders) ----
const ASC_APPS_1 = {
data: [
{ type: 'apps', id: '6400000101', attributes: { name: 'Example Puzzle', bundleId: 'com.example.puzzle', sku: 'PUZZLE1', primaryLocale: 'en-US' } },
{ type: 'apps', id: '6400000102', attributes: { name: 'Example Notes', bundleId: 'com.example.notes', sku: 'NOTES1', primaryLocale: 'en-GB' } },
],
links: { self: 'https://api.appstoreconnect.apple.com/v1/apps?limit=200', next: 'https://api.appstoreconnect.apple.com/v1/apps?cursor=Mg&limit=200' },
meta: { paging: { total: 3, limit: 200 } },
};
const ASC_APPS_2 = { data: [{ type: 'apps', id: '6400000103', attributes: { name: 'A Mac Tool', bundleId: 'com.example.mactool', sku: 'MAC1', primaryLocale: 'en-US' } }], links: { self: '' } };
const ASC_VERSIONS: Record<string, J> = {
'6400000101': { data: [
{ type: 'appStoreVersions', id: 'v1', attributes: { platform: 'IOS', versionString: '2.4.0', appStoreState: 'WAITING_FOR_REVIEW', appVersionState: 'WAITING_FOR_REVIEW' } },
{ type: 'appStoreVersions', id: 'v0', attributes: { platform: 'IOS', versionString: '2.3.0', appStoreState: 'READY_FOR_SALE', appVersionState: 'READY_FOR_DISTRIBUTION' } },
] },
'6400000102': { data: [] },
'6400000103': { data: [{ type: 'appStoreVersions', id: 'v9', attributes: { platform: 'MAC_OS', versionString: '1.0', appStoreState: 'PREPARE_FOR_SUBMISSION' } }] },
};
const ASC_BUILD = { data: [{ type: 'builds', id: 'b1', attributes: { version: '52', iconAssetToken: { templateUrl: 'https://is1-ssl.mzstatic.com/image/thumb/Purple/v4/ab/cd/AppIcon.png/{w}x{h}bb.{f}', width: 1024, height: 1024 } } }] };
const PLAY_SEARCH_1 = { apps: [{ name: 'apps/com.example.puzzle', packageName: 'com.example.puzzle', displayName: 'Example Puzzle' }, { name: 'apps/com.example.runner', packageName: 'com.example.runner', displayName: 'Runner' }], nextPageToken: 'tok2' };
const PLAY_SEARCH_2 = { apps: [{ name: 'apps/com.example.ledger', packageName: 'com.example.ledger', displayName: '' }] };
function ascGet(calls: string[]) {
return async (path: string): Promise<J> => {
calls.push(path);
if (path.startsWith('/v1/apps?fields')) return ASC_APPS_1;
if (path.includes('cursor=Mg')) return ASC_APPS_2;
const v = /^\/v1\/apps\/(\d+)\/appStoreVersions/.exec(path);
if (v) return ASC_VERSIONS[v[1]!]!;
if (path.startsWith('/v1/builds?filter[app]=6400000101')) return ASC_BUILD;
if (path.startsWith('/v1/builds')) return { data: [] };
throw new Error(`GET ${path} -> 404 not recorded`);
};
}
describe('apps list: App Store Connect', () => {
test('pages through /v1/apps, platforms and newest version per app, icon as a data URL', async () => {
const calls: string[] = [];
const icons: string[] = [];
const r = await listAppleApps(ascGet(calls), { icons: true, bytes: async url => { icons.push(url); return { type: 'image/png', data: new Uint8Array([137, 80, 78, 71]) }; } });
expect(r.apps.map(a => a.name)).toEqual(['A Mac Tool', 'Example Notes', 'Example Puzzle']);
const p = r.apps.find(a => a.bundleId === 'com.example.puzzle')!;
expect(p).toMatchObject({ store: 'ios', id: '6400000101', platforms: ['IOS'], latest: { version: '2.4.0', state: 'WAITING_FOR_REVIEW', platform: 'IOS' }, sku: 'PUZZLE1' });
expect(p.icon).toBe('data:image/png;base64,iVBORw==');
expect(icons).toEqual(['https://is1-ssl.mzstatic.com/image/thumb/Purple/v4/ab/cd/AppIcon.png/128x128bb.png']);
expect(r.apps.find(a => a.id === '6400000103')!.platforms).toEqual(['MAC_OS']);
expect(r.apps.find(a => a.id === '6400000102')!).toMatchObject({ platforms: [], latest: null, icon: null });
expect(calls.filter(c => c.startsWith('/v1/builds')).length).toBe(3);
expect(r.warnings).toEqual([]);
});
test('no icons unless asked; a failing version read is a warning, not a failure', async () => {
const calls: string[] = [];
const get = ascGet(calls);
const r = await listAppleApps(async p => { if (p.includes('6400000102/appStoreVersions')) throw new Error(`GET ${p} -> 500 boom`); return get(p); });
expect(calls.some(c => c.startsWith('/v1/builds'))).toBe(false);
expect(r.apps.every(a => a.icon === null)).toBe(true);
expect(r.warnings).toEqual([expect.stringContaining('com.example.notes: versions not read')]);
});
test('icon templates only from Apple\'s CDN', async () => {
const r = await listAppleApps(async p => {
if (p.startsWith('/v1/apps?fields')) return { data: [ASC_APPS_1.data[0]] };
if (p.includes('appStoreVersions')) return { data: [] };
return { data: [{ attributes: { iconAssetToken: { templateUrl: 'https://evil.example.com/{w}x{h}bb.{f}' } } }] };
}, { icons: true, bytes: async () => { throw new Error('must not fetch'); } });
expect(r.apps[0]!.icon).toBeNull();
expect(iconUrl('https://a.mzstatic.com/x/{w}x{h}{c}.{f}', 64)).toBe('https://a.mzstatic.com/x/64x64bb.png');
});
});
describe('apps list: Google Play', () => {
test('apps:search pages, display name falls back to the package', async () => {
const calls: string[] = [];
const r = await listPlayApps(async p => { calls.push(p); return p.includes('pageToken=tok2') ? PLAY_SEARCH_2 : PLAY_SEARCH_1; });
expect(calls).toEqual(['/apps:search?pageSize=1000', '/apps:search?pageSize=1000&pageToken=tok2']);
expect(r.apps.map(a => [a.name, a.id, a.store])).toEqual([['com.example.ledger', 'com.example.ledger', 'android'], ['Example Puzzle', 'com.example.puzzle', 'android'], ['Runner', 'com.example.runner', 'android']]);
});
});
describe('account health', () => {
test('App Store Connect: ok, no apps, revoked (401), permission (403), unreachable', () => {
expect(appleCheck({ apps: 3 })).toMatchObject({ status: 'ok', apps: 3, fix: null });
expect(appleCheck({ apps: 0 }).status).toBe('no-apps');
const revoked = appleCheck({ error: new Error('GET /v1/apps -> 401 {"errors":[{"status":"401","code":"NOT_AUTHORIZED"}]}') });
expect(revoked.status).toBe('revoked');
expect(revoked.fix).toContain('Integrations');
expect(appleCheck({ error: new Error('GET /v1/apps -> 403 {"errors":[{"code":"FORBIDDEN_ERROR"}]}') }).status).toBe('permission');
expect(appleCheck({ error: new Error('fetch failed') }).status).toBe('error');
});
test('Play: ok, not invited (0 apps), API off, revoked key, missing permission; the hint names the service account', () => {
const who = 'storebound@example-project.iam.gserviceaccount.com';
expect(playCheck(who, { apps: 2 })).toMatchObject({ status: 'ok', apps: 2, principal: who });
const none = playCheck(who, { apps: 0 });
expect(none.status).toBe('permission');
expect(none.fix).toContain(`Invite new users: add ${who}`);
expect(none.fix).toContain('several developer accounts');
expect(playCheck(who, { error: new Error('GET /v1beta1/apps:search -> 403 {"error":{"code":403,"status":"PERMISSION_DENIED","details":[{"reason":"SERVICE_DISABLED"}],"message":"Google Play Developer Reporting API has not been used in project 123 before or it is disabled."}}') }).status).toBe('api-disabled');
expect(playCheck(who, { error: new Error('Google token: Invalid JWT Signature.') }).status).toBe('revoked');
expect(playCheck(who, { error: new Error('Google token: invalid_grant') }).status).toBe('revoked');
expect(playCheck(who, { error: new Error('GET /apps:search -> 403 {"error":{"status":"PERMISSION_DENIED","message":"The caller does not have permission"}}') }).status).toBe('permission');
});
});
// ---- the CLI over a mocked fetch (real JWT signing with throwaway keys) ----
const realFetch = globalThis.fetch;
const saved = { ...process.env };
afterEach(() => { globalThis.fetch = realFetch; for (const k of ['ASC_KEY_ID', 'ASC_ISSUER_ID', 'ASC_P8', 'PLAY_SERVICE_ACCOUNT']) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; } });
function mockFetch(routes: (url: string, init?: RequestInit) => Response | null): string[] {
const seen: string[] = [];
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
const url = String(input instanceof Request ? input.url : input);
seen.push(`${init?.method ?? 'GET'} ${url}`);
const r = routes(url, init);
if (!r) return new Response('{"error":"not recorded"}', { status: 404 });
return r;
}) as typeof fetch;
return seen;
}
const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status, headers: { 'content-type': 'application/json' } });
describe('storebound apps (CLI functions, mocked HTTP)', () => {
const root = mkdtempSync(join(tmpdir(), 'sb-apps-'));
test('apple: list with icons, check', async () => {
const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
process.env.ASC_KEY_ID = 'ABCDE12345';
process.env.ASC_ISSUER_ID = '00000000-0000-4000-8000-000000000000';
process.env.ASC_P8 = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
const get = ascGet([]);
const seen = mockFetch(url => {
if (url.startsWith('https://is1-ssl.mzstatic.com/')) return new Response(new Uint8Array([1, 2, 3]), { headers: { 'content-type': 'image/png' } });
if (url.startsWith('https://api.appstoreconnect.apple.com')) return null;
return null;
});
// route ASC through the recorded getter
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
const url = String(input);
seen.push(url);
const auth = new Headers(init?.headers).get('Authorization') ?? '';
if (url.startsWith('https://api.appstoreconnect')) expect(auth).toMatch(/^Bearer [\w-]+\.[\w-]+\.[\w-]+$/);
if (url.startsWith('https://is1-ssl.mzstatic.com/')) return new Response(new Uint8Array([1, 2, 3]), { headers: { 'content-type': 'image/png' } });
try { return json(await get(url.replace('https://api.appstoreconnect.apple.com', ''))); } catch { return json({ errors: [{ status: '404' }] }, 404); }
}) as typeof fetch;
const r = await listApps('apple', root, true);
expect(r.store).toBe('ios');
expect(r.apps.length).toBe(3);
expect(r.apps.find(a => a.id === '6400000101')!.icon).toBe('data:image/png;base64,AQID');
expect(await checkAccount('apple', root)).toMatchObject({ status: 'ok', apps: 2 });
globalThis.fetch = (async () => json({ errors: [{ status: '401', code: 'NOT_AUTHORIZED' }] }, 401)) as unknown as typeof fetch;
expect((await checkAccount('apple', root)).status).toBe('revoked');
});
test('play: token exchange, apps:search, check; no apps = not invited', async () => {
const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
process.env.PLAY_SERVICE_ACCOUNT = JSON.stringify({ client_email: 'sb@example-project.iam.gserviceaccount.com', private_key: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), token_uri: 'https://oauth2.googleapis.com/token' });
let apps: unknown[] = PLAY_SEARCH_2.apps;
const seen = mockFetch(url => {
if (url === 'https://oauth2.googleapis.com/token') return json({ access_token: 'ya29.test', expires_in: 3600 });
if (url.startsWith('https://playdeveloperreporting.googleapis.com/v1beta1/apps:search')) return json({ apps });
return null;
});
const r = await listApps('play', root, false);
expect(r.apps.map(a => a.id)).toEqual(['com.example.ledger']);
expect(seen.some(s => s.startsWith('POST https://oauth2.googleapis.com/token'))).toBe(true);
expect(await checkAccount('play', root)).toMatchObject({ status: 'ok', principal: 'sb@example-project.iam.gserviceaccount.com' });
apps = [];
expect((await checkAccount('play', root)).status).toBe('permission');
});
});
// ---- serve: apps.list, account.check, store-only apps ----
const SECRET_HEX = Array.from({ length: 32 }, (_, i) => i.toString(16).padStart(2, '0')).join('');
async function session(reply: (argv: string[], o: RunOptions) => { code?: number; out?: string; data?: unknown } = () => ({})) {
const calls: { argv: string[]; o: RunOptions }[] = [];
const run = (argv: string[], o: RunOptions): Running => { calls.push({ argv, o }); const r = reply(argv, o); return { result: Promise.resolve({ code: r.code ?? 0, out: r.out ?? '', ...(r.data === undefined ? {} : { data: r.data }), cancelled: false }), cancel: () => {} }; };
const s = new Session(() => {}, run);
let id = 0;
const call = async (method: string, params: unknown = {}) => (await s.handle({ jsonrpc: '2.0', id: ++id, method, params }))! as J;
await call('session.hello', { secret: SECRET_HEX });
return { calls, call };
}
const PLAY = { PLAY_SERVICE_ACCOUNT: '{"client_email":"x@example.com","private_key":"-----BEGIN PRIVATE KEY-----"}' };
const APPLE = { ASC_KEY_ID: 'ABCDE12345', ASC_ISSUER_ID: '00000000-0000-4000-8000-000000000000', ASC_P8: '-----BEGIN PRIVATE KEY-----\nx\n-----END PRIVATE KEY-----' };
describe('serve: account methods', () => {
test('described as kind "account", network reads', () => {
const m = describeMethods().filter(x => x.kind === 'account').map(x => x.method).sort();
expect(m).toEqual(['account.check', 'apps.list']);
});
test('apps.list: one account, its store from the credentials, icons on request, in an empty folder', async () => {
const s = await session(() => ({ data: { store: 'android', apps: [], warnings: [], at: 'x' } }));
const r = await s.call('apps.list', { credentials: PLAY, args: { icons: true } });
expect(r.result).toEqual({ store: 'android', apps: [], warnings: [], at: 'x' });
expect(s.calls[0]!.argv).toEqual(['apps', 'list', '--store', 'play', '--icons', '--json']);
expect(s.calls[0]!.o.env).toEqual(PLAY);
expect(existsSync(join(s.calls[0]!.o.cwd, '.storebound'))).toBe(false);
await s.call('account.check', { credentials: APPLE });
expect(s.calls[1]!.argv).toEqual(['apps', 'check', '--store', 'apple', '--json']);
});
test('apps.list: refuses no account, two accounts, unknown args', async () => {
const s = await session();
for (const p of [{ credentials: {} }, { credentials: { ...PLAY, ...APPLE } }, { credentials: PLAY, args: { only: 'x' } }, { credentials: PLAY, project: '/tmp' }, { credentials: APPLE, args: { icons: 'yes' } }])
expect((await s.call('apps.list', p)).error).toMatchObject({ code: ERR.invalidParams });
expect((await s.call('account.check', { credentials: PLAY, args: { icons: true } })).error).toMatchObject({ code: ERR.invalidParams });
expect(s.calls.length).toBe(0);
});
});
describe('serve: store-only apps (virtual)', () => {
const V = { name: 'Example Puzzle', apple: { bundleId: 'com.example.puzzle', appId: '6400000101' }, play: { packageName: 'com.example.puzzle' } };
test('generated config validates and only carries store ids and placeholders', () => {
expect(validateConfig(virtualConfig(V))).toEqual([]);
expect(validateConfig(virtualConfig({ name: 'Only Play', play: { packageName: 'com.example.runner' } }))).toEqual([]);
const dir = virtualDir(V);
expect(JSON.parse(readFileSync(join(dir, 'storebound.config.json'), 'utf8')).apple).toEqual({ bundleId: 'com.example.puzzle', appId: '6400000101' });
expect(virtualDir(V)).toBe(dir);
for (const bad of [{}, { name: '' }, { name: 'x' }, { name: 'x', apple: { bundleId: '../etc' } }, { name: 'x', play: { packageName: 'nope' } }, { name: 'x', apple: { bundleId: 'com.a.b', appId: '12a' } }, { name: 'x', play: { packageName: 'com.a.b' }, path: '/etc' }])
expect(() => checkVirtual(bad)).toThrow();
});
test('store reads run in the generated folder; writes and offline project reads are refused', async () => {
const s = await session(() => ({ data: { ok: true } }));
const r = await s.call('reviews.list', { virtual: V, args: { days: 30 }, credentials: APPLE });
expect(r.error).toBeUndefined();
expect(existsSync(join(s.calls[0]!.o.cwd, 'storebound.config.json'))).toBe(true);
expect([...VIRTUAL_READS].sort()).toEqual(['apple_ppo_status', 'apple_status', 'apple_testflight_status', 'health', 'play_status', 'reviews_list']);
for (const m of ['play.listing', 'catalog.diff', 'project.listings', 'check', 'reviews.approve'])
expect((await s.call(m, { virtual: V, args: m === 'reviews.approve' ? { file: 'apple-1.md' } : {} })).error).toMatchObject({ code: ERR.invalidParams });
expect((await s.call('health', { virtual: V, project: '/tmp' })).error).toMatchObject({ code: ERR.invalidParams });
});
test('portfolio.status takes store-only entries by key: inspected, no config check, keyed back', async () => {
const s = await session(argv => (argv[0] === 'inspect' ? { data: { dir: '/x', config: '/x/c', name: 'Example Puzzle', languages: ['en'], play: { packageName: 'com.example.puzzle' }, apple: { bundleId: 'com.example.puzzle', appId: '6400000101' }, platforms: ['ios', 'android'], products: 0, productIds: [], subscriptions: 0, subscriptionIds: [], catalog: { ios: [], android: [] }, shots: false, testflightGroups: 0 } } : { data: {} }));
const key = 'store:ios:a1b2:6400000101:com.example.puzzle;android:c3d4:com.example.puzzle';
expect(STORE_KEY_RE.test(key)).toBe(true);
const r = await s.call('portfolio.status', { projects: [{ key, virtual: V }] });
const app = (r.result as { apps: J[] }).apps[0]!;
expect(app).toMatchObject({ project: key, virtual: true, check: { ok: true, problems: [], warnings: [] } });
expect(s.calls.map(c => c.argv[0])).toEqual(['inspect']);
const bad = await s.call('portfolio.status', { projects: [{ key: 'store:../x y', virtual: V }] });
expect(((bad.result as { apps: J[] }).apps[0]!.errors as string[])[0]).toContain('store target key');
});
});