storebound/cli/lib/registry.ts

145 lines
9.5 KiB
TypeScript

// The app folders of this machine: one list shared by the CLI and the desktop app, ~/.storebound/projects.json
// (STOREBOUND_REGISTRY names another file). `storebound desktop` in an app folder, `storebound apps add`, `ws init` and
// the desktop's App folders screen add to it; `storebound apps folders` and the desktop show it; `storebound ws ...`
// without a storebound.workspace.json works over it. The desktop keeps its per-folder extras (mapped accounts, saved
// reads) in its own state by the same id. Only paths and names: no keys, nothing from inside the folders.
// { "version": 1, "projects": [{ "id": "<16 hex>", "path": "/abs/folder", "name": "Star Dash", "added": "<iso>" }],
// "storeApps": [{ "id": "<16 hex>", "store": "apple", "appId": "6400000000", "account": "teamA", "name": "Demo App",
// "bundleId": "com.example.demo", "added": "<iso>" }] }
// storeApps: apps that are live on a store but have no project on this machine (`storebound apps add --store apple
// --app-id <id> --account <profile>`). The desktop shows them read-only (status, reviews, analytics) under that
// profile's account, noted "no local project"; they carry no path. Absent when there are none (older readers ignore it).
// Written atomically (temp file, rename); a missing or unreadable file reads as empty (an unreadable one is kept).
import { createHash } from 'node:crypto';
import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { basename, dirname, join, resolve } from 'node:path';
export interface RegistryProject { id: string; path: string; name: string; added: string }
/** A store app without a local project: store + app id (Apple: the numeric app id; Play: the package name), the
* credential profile that reads it. */
export interface StoreOnlyApp { id: string; store: 'apple' | 'play'; appId: string; account: string | null; name: string; bundleId: string | null; added: string }
export interface Registry { version: 1; projects: RegistryProject[]; storeApps?: StoreOnlyApp[] }
export const registryFile = (env: Record<string, string | undefined> = process.env): string => env.STOREBOUND_REGISTRY || join(homedir(), '.storebound', 'projects.json');
/** The id of a folder the CLI adds: stable per absolute path (the same as `ws desktop export`'s project ids). */
export const folderId = (absPath: string): string => createHash('sha256').update(`project:${absPath}`).digest('hex').slice(0, 16);
const ID = /^[0-9a-f]{16}$/;
/** The id of a store-only entry: stable per store and app id. */
export const storeAppId = (store: 'apple' | 'play', appId: string): string => createHash('sha256').update(`store:${store}:${appId}`).digest('hex').slice(0, 16);
export const APPLE_APP_ID = /^\d{6,12}$/;
export const PACKAGE_NAME = /^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+$/;
/** Store-only entries of the file's JSON; malformed ones are dropped. Pure. */
function parseStoreApps(list: unknown): StoreOnlyApp[] {
const out: StoreOnlyApp[] = [];
if (Array.isArray(list)) for (const x of list) {
const o = x as Partial<StoreOnlyApp>;
if (o?.store !== 'apple' && o?.store !== 'play') continue;
const appId = typeof o.appId === 'string' ? o.appId.trim() : '';
if (!(o.store === 'apple' ? APPLE_APP_ID : PACKAGE_NAME).test(appId) || out.some(a => a.store === o.store && a.appId === appId)) continue;
out.push({ id: storeAppId(o.store, appId), store: o.store, appId, account: typeof o.account === 'string' && o.account ? o.account : null,
name: typeof o.name === 'string' && o.name.trim() ? o.name : appId, bundleId: typeof o.bundleId === 'string' && o.bundleId ? o.bundleId : o.store === 'play' ? appId : null,
added: typeof o.added === 'string' ? o.added : '' });
}
return out;
}
/** Parses the file's text; drops entries that are not well formed (an id, an absolute path). Pure. */
export function parseRegistry(text: string): Registry {
let raw: unknown;
try { raw = JSON.parse(text); } catch { return { version: 1, projects: [] }; }
const list = (raw as { projects?: unknown })?.projects;
const out: RegistryProject[] = [];
if (Array.isArray(list)) for (const p of list) {
const o = p as Partial<RegistryProject>;
if (typeof o?.path !== 'string' || !o.path.startsWith('/') && !/^[A-Za-z]:[\\/]/.test(o.path)) continue;
if (out.some(x => x.path === o.path)) continue;
out.push({ id: typeof o.id === 'string' && ID.test(o.id) && !out.some(x => x.id === o.id) ? o.id : folderId(o.path), path: o.path,
name: typeof o.name === 'string' && o.name.trim() ? o.name : basename(o.path), added: typeof o.added === 'string' ? o.added : '' });
}
const storeApps = parseStoreApps((raw as { storeApps?: unknown })?.storeApps);
return storeApps.length ? { version: 1, projects: out, storeApps } : { version: 1, projects: out };
}
export function readRegistry(file = registryFile()): Registry {
if (!existsSync(file)) return { version: 1, projects: [] };
return parseRegistry(readFileSync(file, 'utf8'));
}
export function writeRegistry(r: Registry, file = registryFile()): void {
mkdirSync(dirname(file), { recursive: true });
if (existsSync(file)) {
// a file this version cannot read is kept once instead of being replaced silently
try { JSON.parse(readFileSync(file, 'utf8')); } catch { copyFileSync(file, `${file}.unreadable`); }
}
const tmp = `${file}.tmp-${process.pid}`;
writeFileSync(tmp, JSON.stringify({ version: 1, projects: r.projects, ...(r.storeApps?.length ? { storeApps: r.storeApps } : {}) }, null, 2) + '\n');
renameSync(tmp, file);
}
/** Adds a folder (by absolute path; the same path again only updates an empty name). Pure on the registry. */
export function withFolder(r: Registry, path: string, name: string | undefined, now: string): { registry: Registry; project: RegistryProject; added: boolean } {
const abs = resolve(path);
const have = r.projects.find(p => p.path === abs);
if (have) return { registry: r, project: have, added: false };
const project = { id: folderId(abs), path: abs, name: name?.trim() || basename(abs), added: now };
return { registry: { ...r, version: 1, projects: [...r.projects, project] }, project, added: true };
}
/** Adds a store-only app (the same store + app id again updates its account, name and bundle id). Pure. */
export function withStoreApp(r: Registry, a: { store: 'apple' | 'play'; appId: string; account?: string | null; name?: string; bundleId?: string | null }, now: string): { registry: Registry; app: StoreOnlyApp; added: boolean } {
const appId = a.appId.trim();
if (!(a.store === 'apple' ? APPLE_APP_ID : PACKAGE_NAME).test(appId)) throw new Error(a.store === 'apple' ? `--app-id ${appId}: the numeric Apple ID of the app (App Store Connect > App Information)` : `--app-id ${appId}: the Play package name (com.example.app)`);
const list = r.storeApps ?? [];
const have = list.find(x => x.store === a.store && x.appId === appId);
const app: StoreOnlyApp = { id: storeAppId(a.store, appId), store: a.store, appId, account: a.account ?? have?.account ?? null, name: a.name?.trim() || have?.name || appId,
bundleId: a.bundleId ?? have?.bundleId ?? (a.store === 'play' ? appId : null), added: have?.added ?? now };
if (have && JSON.stringify(have) === JSON.stringify(app)) return { registry: r, app: have, added: false };
return { registry: { ...r, version: 1, storeApps: [...list.filter(x => x !== have), app] }, app, added: !have };
}
/** Removes a store-only app by id or "<store>:<app id>". Pure. */
export function withoutStoreApp(r: Registry, key: string): { registry: Registry; removed: StoreOnlyApp | null } {
const removed = (r.storeApps ?? []).find(x => x.id === key || `${x.store}:${x.appId}` === key) ?? null;
if (!removed) return { registry: r, removed };
const rest = (r.storeApps ?? []).filter(x => x !== removed);
const { storeApps: _, ...base } = r;
return { registry: rest.length ? { ...base, storeApps: rest } : base, removed };
}
export function addStoreApp(a: Parameters<typeof withStoreApp>[1], file = registryFile()): { app: StoreOnlyApp; added: boolean; changed: boolean } {
const cur = readRegistry(file);
const { registry, app, added } = withStoreApp(cur, a, new Date().toISOString());
if (registry !== cur) writeRegistry(registry, file);
return { app, added, changed: registry !== cur };
}
export function removeStoreApp(key: string, file = registryFile()): StoreOnlyApp | null {
const { registry, removed } = withoutStoreApp(readRegistry(file), key);
if (removed) writeRegistry(registry, file);
return removed;
}
/** Removes a folder by path or id. Pure. */
export function withoutFolder(r: Registry, pathOrId: string): { registry: Registry; removed: RegistryProject | null } {
const abs = ID.test(pathOrId) ? '' : resolve(pathOrId);
const removed = r.projects.find(p => p.id === pathOrId || p.path === abs) ?? null;
return { registry: removed ? { ...r, version: 1, projects: r.projects.filter(p => p !== removed) } : r, removed };
}
/** Reads, adds and writes (only when it changed). */
export function addFolder(path: string, name?: string, file = registryFile()): { project: RegistryProject; added: boolean } {
const { registry, project, added } = withFolder(readRegistry(file), path, name, new Date().toISOString());
if (added) writeRegistry(registry, file);
return { project, added };
}
export function removeFolder(pathOrId: string, file = registryFile()): RegistryProject | null {
const { registry, removed } = withoutFolder(readRegistry(file), pathOrId);
if (removed) writeRegistry(registry, file);
return removed;
}