Merge remote-tracking branch 'origin/main' into flaky-console

# Conflicts:
#	tests/site-overflow.test.ts
This commit is contained in:
CRTkafa 2026-10-11 20:54:13 +00:00
commit 24748de60c
68 changed files with 3422 additions and 385 deletions

179
tests/capture-web.test.ts Normal file
View file

@ -0,0 +1,179 @@
// `shots capture` (web) against a local fixture web app: parallel contexts give the same files as serial, the
// per-language session boots the app once per language, the input-hash cache skips unchanged frames and re-runs changed
// ones, and every frame has a timing breakdown. Pure helpers are tested without a browser. Skips the browser part when
// no Chromium can launch. The browser runs run in a `storebound` child process (its own Chromium), like a real run.
import { afterAll, describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { ShipConfig, ShotsCapture } from '../cli/lib/config';
import { type CaptureReport, defaultConcurrency, planWeb, pool, progressLine, selectJobs, timingSummary } from '../cli/shots/capture-web';
import { BASE } from './helpers/store-mock';
const CLI = join(import.meta.dir, '..', 'cli', 'index.ts');
describe('capture helpers', () => {
test('default concurrency: render min(4, cores/2), capture (GPU-heavy) min(3, cores/4), at least 1', () => {
expect(defaultConcurrency('render', 10)).toBe(4);
expect(defaultConcurrency('capture', 10)).toBe(2);
expect(defaultConcurrency('capture', 2)).toBe(1);
expect(defaultConcurrency('render', 1)).toBe(1);
});
test('pool keeps the input order and never runs more than n at once', async () => {
let now = 0, peak = 0;
const out = await pool([5, 1, 3, 2, 4], 2, async x => { now++; peak = Math.max(peak, now); await Bun.sleep(x * 3); now--; return x * 10; });
expect(out).toEqual([50, 10, 30, 20, 40]);
expect(peak).toBe(2);
});
test('progress line with an ETA', () => {
expect(progressLine(5, 20, 0, 10_000)).toBe(' 5/20 ETA 30.0s');
expect(progressLine(20, 20, 0, 10_000)).toBe('20/20');
});
test('cache selection: changed inputs and missing files run; --only-missing; --force', () => {
const cap: ShotsCapture = { source: 'web', baseUrl: 'http://x', shots: { a: { path: '/a' }, b: { path: '/b' } } };
const dims = { phone: { w: 10, h: 20, dpr: 1, bar: 0 }, tablet: { w: 10, h: 20, dpr: 1, bar: 0 } };
const jobs = planWeb(cap, { langs: ['en', 'tr'], devices: ['phone'], only: [], dims, framesDir: '/f', build: 'b1' });
expect(jobs.map(j => j.frame)).toEqual(['en/phone/a.png', 'en/phone/b.png', 'tr/phone/a.png', 'tr/phone/b.png']);
const cache = Object.fromEntries(jobs.map(j => [j.frame, j.hash]));
const all = () => true;
expect(selectJobs(jobs, cache, 'changed', all).run).toEqual([]);
const jobs2 = planWeb({ ...cap, shots: { ...cap.shots, b: { path: '/b', delayMs: 5 } } }, { langs: ['en', 'tr'], devices: ['phone'], only: [], dims, framesDir: '/f', build: 'b1' });
expect(selectJobs(jobs2, cache, 'changed', all).run.map(j => j.frame)).toEqual(['en/phone/b.png', 'tr/phone/b.png']);
const jobs3 = planWeb(cap, { langs: ['en', 'tr'], devices: ['phone'], only: [], dims, framesDir: '/f', build: 'b2' });
expect(selectJobs(jobs3, cache, 'changed', all).run.length).toBe(4);
expect(selectJobs(jobs3, cache, 'only-missing', (f: string) => !f.endsWith('tr/phone/a.png')).run.map(j => j.frame)).toEqual(['tr/phone/a.png']);
expect(selectJobs(jobs, cache, 'force', all).run.length).toBe(4);
});
test('timing summary: slowest frames with their slowest step, time per step', () => {
const t = (goto: number, waitFor: number) => ({ goto, waitFor, eval: 0, delay: 100, screenshot: 50, total: goto + waitFor + 150 });
const s = timingSummary([{ frame: 'en/phone/a.png', timing: t(1000, 200) }, { frame: 'en/phone/b.png', timing: t(100, 5000) }], 1);
expect(s.slowest).toEqual([{ frame: 'en/phone/b.png', total: 5250, step: 'waitFor' }]);
expect(s.steps).toEqual({ goto: 1100, waitFor: 5200, eval: 0, delay: 200, screenshot: 100 });
});
});
// ---- a local fixture web app: /scene/<name>?lang=xx, a SPA (popstate) that counts its boots ----
let boots = 0;
const server = Bun.serve({
port: 0, hostname: '127.0.0.1',
fetch(req) {
const u = new URL(req.url);
if (u.pathname === '/app.js') {
boots++;
return new Response(`
const COLORS = { en: '#1e66f5', de: '#40a02b', tr: '#d20f39' };
function show() {
const name = location.pathname.split('/').pop() || 'home', lang = new URLSearchParams(location.search).get('lang');
document.body.style.cssText = 'margin:0;background:' + (COLORS[lang] || '#000') + ';font:24px sans-serif;color:#fff';
document.body.innerHTML = '<div style="padding:20px">' + lang + ' ' + name + '</div><div style="margin:20px;width:' + (40 * name.length) + 'px;height:60px;background:#fff"></div>';
window.scene = null;
window.shows = (window.shows || 0) + 1;
setTimeout(() => { window.scene = name; }, 30);
}
addEventListener('popstate', show);
show();`, { headers: { 'content-type': 'text/javascript' } });
}
return new Response('<!doctype html><html><head><meta charset="utf-8"><script src="/app.js" defer></script></head><body></body></html>', { headers: { 'content-type': 'text/html' } });
},
});
afterAll(() => server.stop(true));
const canLaunch = spawnSync('bun', ['-e', `const { launch } = await import(${JSON.stringify(join(import.meta.dir, '..', 'cli', 'shots', 'browser.ts'))}); await (await launch(${JSON.stringify(join(import.meta.dir, '..'))}, { headless: true })).close();`], { timeout: 60_000 }).status === 0;
if (!canLaunch) console.warn('capture-web browser tests skipped: no Chromium could launch (bunx playwright install chromium)');
/** A temp project with this config; cli() runs `storebound shots capture <args>` in it. */
function project(cfg: ShipConfig, files: Record<string, string>): { root: string; setConfig: (c: ShipConfig) => void; cli: (args: string[]) => Promise<{ out: string; err: string; code: number }> } {
const root = mkdtempSync(join(tmpdir(), 'sb-cap-'));
for (const [p, t] of Object.entries(files)) { mkdirSync(join(root, p, '..'), { recursive: true }); writeFileSync(join(root, p), t); }
const setConfig = (c: ShipConfig) => writeFileSync(join(root, 'storebound.config.json'), JSON.stringify(c));
setConfig(cfg);
// async: the fixture server lives in this process and must keep answering while the child captures
return { root, setConfig, cli: async args => {
const r = Bun.spawn(['bun', CLI, 'shots', 'capture', ...args], { cwd: root, stdout: 'pipe', stderr: 'pipe', env: { ...process.env, NO_COLOR: '1' } });
const [out, err, code] = await Promise.all([new Response(r.stdout).text(), new Response(r.stderr).text(), r.exited]);
return { out, err, code };
} };
}
const shot = (name: string, extra: object = {}) => ({ path: `/scene/${name}`, waitFor: `window.scene === '${name}'`, delayMs: 20, ...extra });
function config(capture: Partial<ShotsCapture> = {}): ShipConfig {
return { ...BASE, shots: { copy: 'store/shots/copy.json', frames: 'store/shots/frames', out: 'store/renders', scenes: [{ id: 'hero', palette: 'fire', frames: [{ src: 'hero.png' }] }], phone: { w: 180, h: 240, dpr: 1 },
capture: { source: 'web', baseUrl: `http://127.0.0.1:${server.port}`, query: 'lang={lang}', build: 'src', shots: { hero: shot('hero'), battle: shot('battle'), king: shot('king') }, ...capture } } };
}
const files = { 'store/shots/copy.json': '{}', 'src/main.js': 'v1' };
const frames = (root: string) => ['en', 'de', 'tr'].flatMap(l => ['hero', 'battle', 'king'].map(n => join(root, 'store/shots/frames', l, 'phone', `${n}.png`)));
describe.skipIf(!canLaunch)('shots capture (web) with a fixture app', () => {
test('concurrency 3 gives the same files as serial', async () => {
const p = project(config(), files);
try {
await p.cli(['--device', 'phone', '--concurrency', '1', '--force']);
const serial = frames(p.root).map(f => readFileSync(f));
const r = await p.cli(['--device', 'phone', '--concurrency', '3', '--force']);
expect(r.out).toContain('capturing 9 frames, 3 at a time');
const parallel = frames(p.root).map(f => readFileSync(f));
expect(parallel.length).toBe(9);
for (const [i, b] of parallel.entries()) expect(Buffer.compare(b, serial[i]!)).toBe(0);
} finally { rmSync(p.root, { recursive: true, force: true }); }
}, 120_000);
test('per-language session boots the app once per language; per-shot once per frame', async () => {
const p = project(config({ session: 'per-language' }), files);
try {
boots = 0;
const r = await p.cli(['--device', 'phone', '--concurrency', '2', '--force']);
expect(boots).toBe(3);
expect(r.out).toContain('(reused page)');
const report = JSON.parse(readFileSync(join(p.root, '.storebound/capture-report.json'), 'utf8')) as CaptureReport;
expect(report.frames.filter(f => f.reused).length).toBe(6);
expect(frames(p.root).every(f => existsSync(f))).toBe(true);
// a shot whose precondition fails in the reused page (it needs a freshly booted page) falls back to a fresh page
const bad = project(config({ session: 'per-language', reuseTimeoutMs: 300, shots: { hero: shot('hero'), fresh: { path: '/scene/fresh', waitFor: "window.scene === 'fresh' && window.shows === 1", delayMs: 20 } } }), files);
try {
boots = 0;
const r2 = await bad.cli(['--device', 'phone', '--lang', 'en', '--force']);
expect(r2.err).toContain('en/phone/fresh: reused page failed');
expect(r2.out).toContain('capture done: 2 frames');
expect(boots).toBe(2);
} finally { rmSync(bad.root, { recursive: true, force: true }); }
boots = 0;
const q = project(config(), files);
await q.cli(['--device', 'phone', '--lang', 'en', '--force']);
rmSync(q.root, { recursive: true, force: true });
expect(boots).toBe(3);
} finally { rmSync(p.root, { recursive: true, force: true }); }
}, 180_000);
test('cache skips unchanged frames, re-runs changed ones; --only-missing; timing breakdown', async () => {
const p = project(config(), files);
try {
let r = await p.cli(['--device', 'phone']);
expect(r.out).toContain('capturing 9 frames');
expect(r.out).toMatch(/tr\/phone\/king\.png goto [\d.]+s wait [\d.]+s eval [\d.]+s delay [\d.]+s shot [\d.]+s = [\d.]+s/);
expect(r.out).toContain('time per step: goto');
expect(r.out).toContain('slowest: ');
const report = JSON.parse(readFileSync(join(p.root, '.storebound/capture-report.json'), 'utf8')) as CaptureReport;
expect(Object.keys(report.frames[0]!.timing).sort()).toEqual(['delay', 'eval', 'goto', 'screenshot', 'total', 'waitFor']);
expect(report.summary.slowest.length).toBe(5);
r = await p.cli(['--device', 'phone']);
expect(r.out).toContain('9 of 9 frames unchanged, skipped');
expect(r.out).toContain('capturing 0 frames');
// a changed shot entry re-runs only that shot (3 languages)
p.setConfig(config({ shots: { hero: shot('hero'), battle: shot('battle', { delayMs: 40 }), king: shot('king') } }));
r = await p.cli(['--device', 'phone']);
expect(r.out).toContain('6 of 9 frames unchanged');
expect(r.out).toContain('capturing 3 frames');
// a build change re-runs everything; --only-missing only the missing file
await Bun.write(join(p.root, 'src/main.js'), 'v2 changed');
rmSync(frames(p.root)[0]!);
r = await p.cli(['--device', 'phone', '--only-missing']);
expect(r.out).toContain('capturing 1 frames');
r = await p.cli(['--device', 'phone']);
expect(r.out).toContain('capturing 8 frames'); // the one just captured already has the new inputs
} finally { rmSync(p.root, { recursive: true, force: true }); }
}, 180_000);
});

View file

@ -0,0 +1,439 @@
// Stateful doubles of App Store Connect and Google Play for the idempotency tests (tests/idempotency.test.ts): what a
// command creates is there on the next read, so running a command twice shows whether the second run writes again.
// Shapes follow the recorded answers in store-mock.ts and the APIs' documented JSON:API / androidpublisher formats;
// every id and name is a placeholder. Faults can be injected per request (a 5xx after the write was applied = an
// unclear answer; a 5xx before it; a failing upload part), and new resources can be hidden from list reads for a
// while (the stores' list lag right after a create). Nothing here reaches the network.
import { json, type Call } from './store-mock';
export type R = { type: string; id: string; attributes: Record<string, unknown>; rels: Record<string, string | string[]>; order: number; hiddenReads?: number };
export interface Fault { method: string; match: RegExp; when: 'before' | 'after'; status?: number; times?: number }
const ASC = 'https://api.appstoreconnect.apple.com';
const UPLOAD_HOST = 'https://upload.example.com/';
/** list relationship -> resource type of its items (parent type / relationship name); `one` for to-one relationships. */
const LISTS: Record<string, { type: string; one?: boolean }> = {
'apps/inAppPurchasesV2': { type: 'inAppPurchases' },
'inAppPurchases/inAppPurchaseLocalizations': { type: 'inAppPurchaseLocalizations' },
'inAppPurchases/iapPriceSchedule': { type: 'inAppPurchasePriceSchedules', one: true },
'inAppPurchases/inAppPurchaseAvailability': { type: 'inAppPurchaseAvailabilities', one: true },
'inAppPurchases/appStoreReviewScreenshot': { type: 'inAppPurchaseAppStoreReviewScreenshots', one: true },
'inAppPurchases/offerCodes': { type: 'inAppPurchaseOfferCodes' },
'inAppPurchaseOfferCodes/customCodes': { type: 'inAppPurchaseOfferCodeCustomCodes' },
'inAppPurchaseOfferCodes/oneTimeUseCodes': { type: 'inAppPurchaseOfferCodeOneTimeUseCodes' },
'apps/appStoreVersions': { type: 'appStoreVersions' },
'appStoreVersions/appStoreVersionLocalizations': { type: 'appStoreVersionLocalizations' },
'appStoreVersions/appStoreReviewDetail': { type: 'appStoreReviewDetails', one: true },
'appStoreVersions/appStoreVersionPhasedRelease': { type: 'appStoreVersionPhasedReleases', one: true },
'appStoreVersionLocalizations/appScreenshotSets': { type: 'appScreenshotSets' },
'appStoreVersionLocalizations/appPreviewSets': { type: 'appPreviewSets' },
'appScreenshotSets/appScreenshots': { type: 'appScreenshots' },
'appPreviewSets/appPreviews': { type: 'appPreviews' },
'apps/appCustomProductPages': { type: 'appCustomProductPages' },
'appCustomProductPages/appCustomProductPageVersions': { type: 'appCustomProductPageVersions' },
'appCustomProductPageVersions/appCustomProductPageLocalizations': { type: 'appCustomProductPageLocalizations' },
'appCustomProductPageLocalizations/appScreenshotSets': { type: 'appScreenshotSets' },
'apps/appEvents': { type: 'appEvents' },
'appEvents/localizations': { type: 'appEventLocalizations' },
'apps/betaGroups': { type: 'betaGroups' },
'apps/subscriptionGroups': { type: 'subscriptionGroups' },
'subscriptionGroups/subscriptionGroupLocalizations': { type: 'subscriptionGroupLocalizations' },
'subscriptionGroups/subscriptions': { type: 'subscriptions' },
'subscriptions/subscriptionLocalizations': { type: 'subscriptionLocalizations' },
'subscriptions/subscriptionAvailability': { type: 'subscriptionAvailabilities', one: true },
'subscriptions/appStoreReviewScreenshot': { type: 'subscriptionAppStoreReviewScreenshots', one: true },
'subscriptions/promotionalOffers': { type: 'subscriptionPromotionalOffers' },
'subscriptions/offerCodes': { type: 'subscriptionOfferCodes' },
'subscriptions/prices': { type: 'subscriptionPrices' },
'subscriptions/introductoryOffers': { type: 'subscriptionIntroductoryOffers' },
'subscriptionOfferCodes/customCodes': { type: 'subscriptionOfferCodeCustomCodes' },
'apps/appStoreVersionExperimentsV2': { type: 'appStoreVersionExperiments' },
'appStoreVersionExperiments/appStoreVersionExperimentTreatments': { type: 'appStoreVersionExperimentTreatments' },
'appStoreVersionExperimentTreatments/appStoreVersionExperimentTreatmentLocalizations': { type: 'appStoreVersionExperimentTreatmentLocalizations' },
'appStoreVersionExperimentTreatmentLocalizations/appScreenshotSets': { type: 'appScreenshotSets' },
'reviewSubmissions/items': { type: 'reviewSubmissionItems' },
'apps/buildUploads': { type: 'buildUploads' },
'inAppPurchases/versions': { type: 'inAppPurchaseVersions' },
'subscriptions/versions': { type: 'subscriptionVersions' },
'subscriptionGroups/versions': { type: 'subscriptionGroupVersions' },
'appStoreVersions/build': { type: 'builds', one: true },
'apps/appInfos': { type: 'appInfos' },
'appInfos/appInfoLocalizations': { type: 'appInfoLocalizations' },
'appInfos/ageRatingDeclaration': { type: 'ageRatingDeclarations', one: true },
'apps/appPriceSchedule': { type: 'appPriceSchedules', one: true },
'apps/appPricePoints': { type: 'appPricePoints' },
'apps/appAvailabilityV2': { type: 'appAvailabilities', one: true },
'appAvailabilities/territoryAvailabilities': { type: 'territoryAvailabilities' },
'apps/promotedPurchases': { type: 'promotedPurchases' },
'subscriptions/winBackOffers': { type: 'winBackOffers' },
'betaGroups/betaTesters': { type: 'betaTesters' },
};
/** Stores refuse a second resource with the same key (409 ENTITY_ERROR ... already exists). */
const UNIQUE: Record<string, (r: R) => string> = {
inAppPurchases: r => String(r.attributes.productId),
inAppPurchaseLocalizations: r => `${r.rels.inAppPurchaseV2}|${r.attributes.locale}`,
appScreenshotSets: r => `${Object.values(r.rels).join()}|${r.attributes.screenshotDisplayType}`,
appPreviewSets: r => `${Object.values(r.rels).join()}|${r.attributes.previewType}`,
betaGroups: r => String(r.attributes.name),
subscriptionGroups: r => String(r.attributes.referenceName),
subscriptions: r => String(r.attributes.productId),
subscriptionLocalizations: r => `${r.rels.subscription}|${r.attributes.locale}`,
subscriptionGroupLocalizations: r => `${r.rels.subscriptionGroup}|${r.attributes.locale}`,
appCustomProductPageLocalizations: r => `${r.rels.appCustomProductPageVersion}|${r.attributes.locale}`,
appEventLocalizations: r => `${r.rels.appEvent}|${r.attributes.locale}`,
appStoreReviewDetails: r => String(r.rels.appStoreVersion),
devices: r => String(r.attributes.udid).toLowerCase(),
reviewSubmissions: r => `${r.rels.app}|${r.attributes.state}`,
appStoreVersionPhasedReleases: r => String(r.rels.appStoreVersion),
bundleIds: r => String(r.attributes.identifier),
appStoreVersions: r => `${r.rels.app}|${r.attributes.platform}|${r.attributes.versionString}`,
appInfoLocalizations: r => `${r.rels.appInfo}|${r.attributes.locale}`,
appStoreVersionLocalizations: r => `${r.rels.appStoreVersion}|${r.attributes.locale}`,
promotedPurchases: r => String(r.rels.inAppPurchaseV2 ?? r.rels.subscription),
winBackOffers: r => `${r.rels.subscription}|${r.attributes.offerId}`,
betaTesters: r => String(r.attributes.email).toLowerCase(),
};
const ASSETS = /Screenshots$|^appPreviews$|^appScreenshots$/;
/** Attributes a new resource of a type starts with. */
const DEFAULTS: Record<string, Record<string, unknown>> = {
inAppPurchases: { state: 'MISSING_METADATA' }, subscriptions: { state: 'MISSING_METADATA' }, reviewSubmissions: { state: 'READY_FOR_REVIEW' },
appCustomProductPageVersions: { state: 'PREPARE_FOR_SUBMISSION' }, devices: { status: 'ENABLED', deviceClass: 'IPHONE' },
appStoreVersionPhasedReleases: { phasedReleaseState: 'INACTIVE' }, appEvents: { eventState: 'DRAFT' }, appStoreVersionExperiments: { state: 'PREPARE_FOR_SUBMISSION' },
appStoreVersions: { appVersionState: 'PREPARE_FOR_SUBMISSION' }, betaTesters: { state: 'NOT_INVITED' },
};
const singular = (t: string): string => t.replace(/s$/, '');
export class FakeAsc {
res = new Map<string, R>();
next = 1;
/** new resources of these types stay out of list reads for that many reads */
lag: Record<string, number> = {};
/** every uploaded part, by asset id */
parts: string[] = [];
constructor(readonly appId = '6400000101') {
this.put({ type: 'apps', id: appId, attributes: { bundleId: 'com.example.notes', name: 'Example Notes' }, rels: {} });
for (const t of ['USA', 'DEU', 'TUR']) this.put({ type: 'territories', id: t, attributes: { currency: t === 'USA' ? 'USD' : t === 'DEU' ? 'EUR' : 'TRY' }, rels: {} });
}
put(r: Omit<R, 'order'>): R { const x = { ...r, order: this.next++ } as R; this.res.set(x.id, x); return x; }
all(type: string): R[] { return [...this.res.values()].filter(r => r.type === type).sort((a, b) => a.order - b.order); }
view(r: R): Record<string, unknown> {
const relationships: Record<string, unknown> = {};
for (const [k, v] of Object.entries(r.rels)) relationships[k] = { data: Array.isArray(v) ? v.map(id => ({ type: this.res.get(id)?.type, id })) : { type: this.res.get(v)?.type, id: v } };
return { type: r.type, id: r.id, attributes: r.attributes, relationships };
}
children(parent: string, type: string): R[] {
return this.all(type).filter(r => Object.values(r.rels).some(v => (Array.isArray(v) ? v.includes(parent) : v === parent)));
}
private visible(rs: R[]): R[] {
return rs.filter(r => { if (r.hiddenReads && r.hiddenReads > 0) { r.hiddenReads--; return false; } return true; });
}
private filtered(rs: R[], q: URLSearchParams): R[] {
let out = rs;
for (const [k, v] of q) {
const m = /^filter\[([\w.]+)\]$/.exec(k);
if (!m) continue;
const f = m[1]!, vals = v.split(',');
if (f.includes('.')) continue;
out = out.filter(r => (f in r.attributes ? vals.includes(String(r.attributes[f])) : Object.entries(r.rels).some(([rk, rv]) => (rk === f || rk === singular(f)) && vals.some(x => (Array.isArray(rv) ? rv.includes(x) : rv === x)))));
}
return out;
}
create(body: { data: { type: string; attributes?: Record<string, unknown>; relationships?: Record<string, { data: unknown }> }; included?: { type: string; id: string; attributes?: Record<string, unknown>; relationships?: Record<string, { data: unknown }> }[] }): R | Response {
const temp = new Map<string, string>();
const idFor = (t: string) => `${singular(t).replace(/[A-Z]/g, c => c.toLowerCase()).slice(0, 12)}-${this.next}`;
for (const inc of body.included ?? []) temp.set(inc.id, `${idFor(inc.type)}-${temp.size}`);
const relsOf = (rel?: Record<string, { data: unknown }>): Record<string, string | string[]> => Object.fromEntries(Object.entries(rel ?? {}).filter(([, v]) => v?.data).map(([k, v]) => [k,
Array.isArray(v.data) ? (v.data as { id: string }[]).map(d => temp.get(d.id) ?? d.id) : temp.get((v.data as { id: string }).id) ?? (v.data as { id: string }).id]));
const d = body.data;
const main: Omit<R, 'order'> = { type: d.type, id: idFor(d.type), attributes: { ...DEFAULTS[d.type], ...(d.attributes ?? {}) }, rels: relsOf(d.relationships) };
const u = UNIQUE[d.type];
if (u && this.all(d.type).some(r => u(r) === u(main as R)))
return json({ errors: [{ status: '409', code: 'ENTITY_ERROR.ATTRIBUTE.INVALID.DUPLICATE', title: 'The provided entity includes an attribute with a value that has already been used', detail: 'already exists' }] }, 409);
if (ASSETS.test(d.type) && d.attributes?.fileName) {
main.attributes.uploadOperations = [{ method: 'PUT', url: `${UPLOAD_HOST}${main.id}`, offset: 0, length: Number(d.attributes.fileSize ?? 0), requestHeaders: [{ name: 'Content-Type', value: 'image/png' }] }];
main.attributes.assetDeliveryState = { state: 'AWAITING_UPLOAD' };
}
// a tester belongs to the app of its groups (GET /v1/betaTesters?filter[apps]=)
if (d.type === 'betaTesters') { const g = [main.rels.betaGroups].flat()[0]; const app = g ? this.res.get(String(g))?.rels.app : undefined; if (app) main.rels.app = app; }
const r = this.put(main);
if (this.lag[d.type]) r.hiddenReads = this.lag[d.type];
for (const inc of body.included ?? []) {
// included resources are linked back to whatever points at them
this.put({ type: inc.type, id: temp.get(inc.id)!, attributes: { ...DEFAULTS[inc.type], ...(inc.attributes ?? {}) }, rels: relsOf(inc.relationships) });
}
for (const holder of [r, ...(body.included ?? []).map(i => this.res.get(temp.get(i.id)!)!)]) {
for (const [k, v] of Object.entries(holder.rels)) for (const cid of Array.isArray(v) ? v : [v]) {
const child = this.res.get(cid);
if (child && [...temp.values()].includes(cid) && !child.rels[singular(holder.type)]) child.rels[singular(holder.type)] = holder.id;
void k;
}
}
return r;
}
handle(method: string, path: string, body: unknown): Response {
const u = new URL(ASC + path);
const parts = u.pathname.split('/').filter(Boolean); // v1, type, id?, rel?
const [, type, id, rel, rel2] = parts;
if (method === 'GET') {
if (type === 'territories') return json({ data: this.all('territories').map(r => this.view(r)), links: {} });
if (rel === 'pricePoints') {
const t = u.searchParams.get('filter[territory]') ?? 'USA';
return json({ data: [0.99, 1.99, 2.99, 4.99, 9.99].map(p => ({ type: 'inAppPurchasePricePoints', id: `pp-${t}-${p}`, attributes: { customerPrice: String(p) }, relationships: { territory: { data: { type: 'territories', id: t } } } })),
included: [{ type: 'territories', id: t, attributes: { currency: 'USD' } }], links: {} });
}
if (rel === 'equalizations') {
// every other territory at the same price (enough for the comparisons the commands make)
const [, , price] = id!.split('-');
return json({ data: ['DEU', 'TUR'].map(t => ({ type: 'subscriptionPricePoints', id: `pp-${t}-${price}`, attributes: { customerPrice: price }, relationships: { territory: { data: { type: 'territories', id: t } } } })), links: {} });
}
if (!id) return json({ data: this.visible(this.filtered(this.all(type!), u.searchParams)).map(r => this.view(r)), links: {} });
const self = this.res.get(id);
if (!rel) return self && self.type === type ? json({ data: this.view(self) }) : json({ errors: [{ status: '404' }] }, 404);
if (rel === 'relationships') return json({ data: this.children(id, rel2!).map(r => ({ type: r.type, id: r.id })) });
const l = LISTS[`${type}/${rel}`];
if (!l) return json({ errors: [{ status: '599', detail: `fake: no list ${type}/${rel}` }] }, 599);
const kids = this.filtered(this.children(id, l.type), u.searchParams);
if (l.one) {
const one = kids[0];
if (!one) return json({ errors: [{ status: '404' }] }, 404);
const included = (u.searchParams.get('include') ?? '').split(',').filter(Boolean).flatMap(() => [...this.res.values()].filter(r => Object.values(r.rels).some(v => v === one.id || (Array.isArray(v) && v.includes(one.id))) && r.id !== one.id).map(r => this.view(r)));
return json({ data: this.view(one), included });
}
const shown = this.visible(kids);
// price lists carry their price points (customerPrice from the placeholder id pp-<territory>-<price>)
const points = [...new Set(shown.map(r => r.rels.subscriptionPricePoint ?? r.rels.inAppPurchasePricePoint).filter((x): x is string => typeof x === 'string'))];
const included = points.map(pid => ({ type: 'subscriptionPricePoints', id: pid, attributes: { customerPrice: pid.split('-')[2] } }));
return json({ data: shown.map(r => this.view(r)), included, links: {} });
}
if (method === 'POST') {
if (rel === 'relationships') { return new Response(null, { status: 204 }); }
const out = this.create(body as Parameters<FakeAsc['create']>[0]);
return out instanceof Response ? out : json({ data: this.view(out) }, 201);
}
if (method === 'PATCH') {
if (rel === 'relationships' && type && id) {
const data = (body as { data: { id: string } | { id: string }[] | null }).data;
if (data && !Array.isArray(data)) {
// a to-one relationship (the build of a version): the target points back at the patched resource
for (const r of this.children(id, this.res.get(data.id)?.type ?? '')) delete r.rels[singular(type)];
const t = this.res.get(data.id);
if (t) t.rels[singular(type)] = id;
return new Response(null, { status: 204 });
}
// order of a screenshot / preview set
const ids = ((data ?? []) as { id: string }[]).map(d => d.id);
const base = Math.min(...ids.map(i => this.res.get(i)?.order ?? 0));
ids.forEach((i, k) => { const r = this.res.get(i); if (r) r.order = base + k; });
return new Response(null, { status: 204 });
}
let self = id ? this.res.get(id) : undefined;
// the age rating declaration is addressed by its app info's id
if (self && type && self.type !== type) self = this.children(self.id, type)[0];
if (!self) return json({ errors: [{ status: '404' }] }, 404);
const attrs = (body as { data: { attributes?: Record<string, unknown> } }).data.attributes ?? {};
for (const [k, v] of Object.entries((body as { data: { relationships?: Record<string, { data: { id: string } | null }> } }).data.relationships ?? {})) {
if (v.data) self.rels[k] = v.data.id; else delete self.rels[k];
}
// inline creates (subscription prices, introductory offers) become children of the patched resource
for (const inc of (body as { included?: { type: string; attributes?: Record<string, unknown>; relationships?: Record<string, { data: { id: string } }> }[] }).included ?? [])
this.put({ type: inc.type, id: `${inc.type.slice(0, 8)}-${this.next}`, attributes: { ...(inc.attributes ?? {}) },
rels: { [singular(self.type)]: self.id, ...Object.fromEntries(Object.entries(inc.relationships ?? {}).map(([k, v]) => [k, v.data.id])) } });
if (attrs.uploaded === true && ASSETS.test(self.type)) {
const { uploaded: _u, ...rest } = attrs;
Object.assign(self.attributes, rest, { assetDeliveryState: { state: this.parts.includes(self.id) ? 'COMPLETE' : 'FAILED' } });
delete self.attributes.uploadOperations;
} else Object.assign(self.attributes, attrs);
return json({ data: this.view(self) });
}
if (method === 'DELETE') {
if (!id || !this.res.has(id)) return json({ errors: [{ status: '404' }] }, 404);
this.res.delete(id);
return new Response(null, { status: 204 });
}
return json({ errors: [{ status: '599' }] }, 599);
}
}
// ------------------------------------------------------------------------------------------------------------ Play
type PlayState = { details: Record<string, unknown>; listings: Record<string, Record<string, unknown>>; images: Record<string, string[]>; tracks: Record<string, { releases: unknown[] }>; bundles: number[] };
const clone = <T>(x: T): T => JSON.parse(JSON.stringify(x)) as T;
export class FakePlay {
live: PlayState = { details: {}, listings: {}, images: {}, tracks: {}, bundles: [] };
edits = new Map<string, PlayState>();
committed: string[] = [];
products = new Map<string, Record<string, unknown>>();
subs = new Map<string, Record<string, unknown>>();
offers = new Map<string, Record<string, unknown>>();
next = 1;
/** every Data safety CSV that was posted */
dataSafety: string[] = [];
/** versionCode the next bundle upload reports */
bundleCode = 42;
handle(method: string, url: string, body: unknown): Response {
const u = new URL(url);
const p = u.pathname.replace(/^\/(upload\/)?androidpublisher\/v3\/applications\/[^/]+/, '');
const err = (code: number, status: string, message: string) => json({ error: { code, status, message } }, code);
let m: RegExpExecArray | null;
if (method === 'POST' && p === '/edits') { const id = `edit-${this.next++}`; this.edits.set(id, clone(this.live)); return json({ id, expiryTimeSeconds: '9999999999' }); }
if ((m = /^\/edits\/([^/:]+)(.*)$/.exec(p))) {
const [, id, rest] = m;
const e = this.edits.get(id!);
if (!e) return err(404, 'NOT_FOUND', 'Edit has been deleted');
if (method === 'DELETE' && rest === '') { this.edits.delete(id!); return new Response(null, { status: 204 }); }
if (method === 'POST' && rest === ':validate') return json({ id });
if (method === 'POST' && rest === ':commit') { this.live = e; this.edits.delete(id!); this.committed.push(id!); return json({ id }); }
if (rest === '/details') { if (method === 'PUT') e.details = body as Record<string, unknown>; return json(e.details); }
if (rest === '/listings') return json({ listings: Object.values(e.listings) });
if ((m = /^\/listings\/([^/]+)$/.exec(rest!))) { if (method === 'PUT') e.listings[m[1]!] = body as Record<string, unknown>; return json(e.listings[m[1]!] ?? {}); }
if ((m = /^\/listings\/([^/]+)\/(\w+)$/.exec(rest!))) {
const k = `${m[1]}/${m[2]}`;
if (method === 'DELETE') { e.images[k] = []; return json({ deleted: [] }); }
if (method === 'POST') { const h = new Bun.CryptoHasher('sha256').update(body as Uint8Array).digest('hex'); (e.images[k] ??= []).push(h); return json({ image: { sha256: h } }); }
return json({ images: (e.images[k] ?? []).map(sha256 => ({ sha256 })) });
}
if (rest === '/tracks') return json({ tracks: Object.entries(e.tracks).map(([track, t]) => ({ track, ...t })) });
if ((m = /^\/tracks\/(\w+)$/.exec(rest!))) {
if (method === 'PUT') e.tracks[m[1]!] = { releases: (body as { releases: unknown[] }).releases };
return json({ track: m[1], releases: e.tracks[m[1]!]?.releases ?? [] });
}
if (rest === '/bundles') {
if (method === 'POST') { const code = this.bundleCode; e.bundles.push(code); return json({ versionCode: code }); }
return json({ bundles: e.bundles.map(versionCode => ({ versionCode })) });
}
if (rest === '/apks') return json({ apks: [] });
return err(599, 'UNKNOWN', `fake play: ${method} ${p}`);
}
if (method === 'POST' && p === '/pricing:convertRegionPrices') {
const usd = body as { price: { units?: string; nanos?: number } };
const price = { currencyCode: 'USD', units: usd.price.units ?? '0', nanos: usd.price.nanos ?? 0 };
return json({ convertedRegionPrices: { US: { regionCode: 'US', price }, DE: { regionCode: 'DE', price: { ...price, currencyCode: 'EUR' } } },
convertedOtherRegionsPrice: { usdPrice: price, eurPrice: { ...price, currencyCode: 'EUR' } }, regionVersion: { version: '2022/02' } });
}
if (method === 'GET' && p === '/oneTimeProducts') return json({ oneTimeProducts: [...this.products.values()] });
if ((m = /^\/(?:oneTimeProducts|onetimeproducts)\/([^/:]+)$/.exec(p))) {
const id = decodeURIComponent(m[1]!);
if (method === 'PATCH') {
const cur = this.products.get(id);
if (!cur && u.searchParams.get('allowMissing') !== 'true') return err(404, 'NOT_FOUND', 'no product');
const b = clone(body as Record<string, unknown>);
const mask = (u.searchParams.get('updateMask') ?? '').split(',');
const next = cur ? { ...cur, ...(mask.includes('listings') ? { listings: b.listings } : {}), ...(mask.includes('purchaseOptions') ? { purchaseOptions: b.purchaseOptions } : {}) } : b;
for (const o of (next.purchaseOptions as { state?: string; purchaseOptionId: string }[] | undefined) ?? []) {
const was = (cur?.purchaseOptions as { state?: string; purchaseOptionId: string }[] | undefined)?.find(x => x.purchaseOptionId === o.purchaseOptionId)?.state;
o.state = was ?? 'DRAFT';
}
this.products.set(id, next);
return json(next);
}
const cur = this.products.get(id);
return cur ? json(cur) : err(404, 'NOT_FOUND', 'no product');
}
if ((m = /^\/oneTimeProducts\/([^/]+)\/purchaseOptions:batchUpdateStates$/.exec(p))) {
const cur = this.products.get(decodeURIComponent(m[1]!));
for (const o of (cur?.purchaseOptions as { state?: string }[] | undefined) ?? []) o.state = 'ACTIVE';
return json({});
}
if (method === 'GET' && p === '/subscriptions') return json({ subscriptions: [...this.subs.values()] });
if (method === 'POST' && p === '/subscriptions') {
const id = u.searchParams.get('productId')!;
if (this.subs.has(id)) return err(409, 'ALREADY_EXISTS', `Subscription ${id} already exists`);
const b = clone(body as Record<string, unknown>);
for (const bp of (b.basePlans as { state?: string }[] | undefined) ?? []) bp.state = 'DRAFT';
this.subs.set(id, b);
return json(b);
}
if ((m = /^\/subscriptions\/([^/:]+)$/.exec(p))) {
const id = decodeURIComponent(m[1]!);
const cur = this.subs.get(id);
if (!cur) return err(404, 'NOT_FOUND', 'no subscription');
if (method === 'PATCH') {
const b = clone(body as Record<string, unknown>);
const states = new Map(((cur.basePlans as { basePlanId: string; state?: string }[] | undefined) ?? []).map(x => [x.basePlanId, x.state]));
for (const bp of (b.basePlans as { basePlanId: string; state?: string }[] | undefined) ?? []) bp.state = states.get(bp.basePlanId) ?? 'DRAFT';
this.subs.set(id, { ...cur, ...b });
}
return json(this.subs.get(id));
}
if ((m = /^\/subscriptions\/([^/]+)\/basePlans\/([^/:]+):activate$/.exec(p))) {
const cur = this.subs.get(decodeURIComponent(m[1]!));
for (const bp of (cur?.basePlans as { basePlanId: string; state?: string }[] | undefined) ?? []) if (bp.basePlanId === m[2]) bp.state = 'ACTIVE';
return json(cur ?? {});
}
if ((m = /^\/subscriptions\/([^/]+)\/basePlans\/([^/]+)\/offers$/.exec(p))) {
const key = `${decodeURIComponent(m[1]!)}/${m[2]}`;
if (method === 'GET') return json({ subscriptionOffers: [...this.offers.entries()].filter(([k]) => k.startsWith(key + '/')).map(([, v]) => v) });
const oid = u.searchParams.get('offerId')!;
if (this.offers.has(`${key}/${oid}`)) return err(409, 'ALREADY_EXISTS', `Offer ${oid} already exists`);
const b = { ...clone(body as Record<string, unknown>), state: 'DRAFT' };
this.offers.set(`${key}/${oid}`, b);
return json(b);
}
if ((m = /^\/subscriptions\/([^/]+)\/basePlans\/([^/]+)\/offers\/([^/:]+)(:activate)?$/.exec(p))) {
const o = this.offers.get(`${decodeURIComponent(m[1]!)}/${m[2]}/${decodeURIComponent(m[3]!)}`);
if (!o) return err(404, 'NOT_FOUND', 'no offer');
if (m[4]) o.state = 'ACTIVE';
return json(o);
}
if (method === 'POST' && p === '/dataSafety') { this.dataSafety.push(String((body as { safetyLabels?: string }).safetyLabels ?? '')); return json({}); }
return err(599, 'UNKNOWN', `fake play: ${method} ${p}`);
}
}
// ------------------------------------------------------------------------------------------------- fetch + counting
export interface Stores { asc: FakeAsc; play: FakePlay; calls: Call[]; faults: Fault[]; failPart?: (n: number) => boolean }
const realFetch = globalThis.fetch;
/** Installs both fakes as fetch. Faults apply in order (`times`, default 1). */
export function installStores(): Stores {
const s: Stores = { asc: new FakeAsc(), play: new FakePlay(), calls: [], faults: [] };
let partNo = 0;
globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {
const url = String(input instanceof Request ? input.url : input);
const method = (init?.method ?? 'GET').toUpperCase();
const raw = init?.body;
let body: unknown = raw;
if (typeof raw === 'string') { try { body = JSON.parse(raw); } catch { body = raw; } }
if (url === 'https://oauth2.googleapis.com/token') return json({ access_token: 'ya29.test', expires_in: 3600 });
const path = url.replace(/^https:\/\/[^/]+/, '');
s.calls.push({ method, url, path, body });
const f = s.faults.find(x => (x.times ?? 1) > 0 && x.method === method && x.match.test(decodeURIComponent(path)));
if (f) f.times = (f.times ?? 1) - 1;
if (f?.when === 'before') return json({ errors: [{ status: String(f.status ?? 503), detail: 'injected' }] }, f.status ?? 503);
let res: Response;
if (url.startsWith(UPLOAD_HOST)) {
partNo++;
if (s.failPart?.(partNo)) return new Response('injected part failure', { status: 400 });
s.asc.parts.push(url.slice(UPLOAD_HOST.length));
res = new Response(null, { status: 200 });
} else if (url.startsWith(ASC)) res = s.asc.handle(method, path, body);
else if (url.startsWith('https://androidpublisher.googleapis.com/')) res = s.play.handle(method, url, body instanceof Uint8Array ? body : body);
else res = new Response(`fake: no route ${method} ${url}`, { status: 599 });
if (f?.when === 'after') return json({ errors: [{ status: String(f.status ?? 502), detail: 'injected after the write' }] }, f.status ?? 502);
return res;
}) as typeof fetch;
return s;
}
export function uninstallStores(): void { globalThis.fetch = realFetch; }
/** Store writes in a call log: every non-GET request, except Play's edit bookkeeping (opening and deleting a
* throwaway edit, validating it) and the price conversion, which change nothing on the store. */
export function writes(calls: Call[]): Call[] {
return calls.filter(c => c.method !== 'GET' && !(c.method === 'POST' && /\/edits$/.test(c.path)) && !(c.method === 'DELETE' && /\/edits\/[^/]+$/.test(c.path))
&& !/:validate$|pricing:convertRegionPrices$/.test(c.path));
}

4
tests/helpers/preload.ts Normal file
View file

@ -0,0 +1,4 @@
// Loaded before every test file (bunfig.toml): no real waiting between the re-checks of cli/lib/upsert.ts or for
// the store's list to settle after a create (cli/apple/iap.ts).
process.env.STOREBOUND_UPSERT_WAIT_MS = '0';
process.env.STOREBOUND_LIST_SETTLE_MS ??= '0';

640
tests/idempotency.test.ts Normal file
View file

@ -0,0 +1,640 @@
// Idempotency of every store write (docs/idempotency.md): each write command runs twice against stateful doubles of
// App Store Connect and Google Play (tests/helpers/fake-stores.ts) and the second run must not write anything. Plus
// the failure cases: a crash in the middle of a screenshot set, a create whose answer is lost (5xx after the store
// applied it), a create the store refuses as a duplicate (409), the list lag right after a create, Play edits on
// error paths and an unclear commit, the lock between two runs, and the retry rules of the API clients.
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { hostname } from 'node:os';
import { join } from 'node:path';
import type { ShipConfig } from '../cli/lib/config';
import { parseArgs } from '../cli/lib/args';
import { acquireLock, lockKeys, staleLock } from '../cli/lib/lock';
import { AmbiguousWriteError, createOnce, findOrCreate, isConflict, readJournal, retrySafe, upsertTiming } from '../cli/lib/upsert';
import { keptPrefix } from '../cli/apple/asc';
import { sameRelease } from '../cli/play/release';
import { sameReleases } from '../cli/play/rollout';
import { playClient } from '../cli/play/client';
import { run as appleIap } from '../cli/apple/iap';
import { run as appleScreenshots } from '../cli/apple/screenshots';
import { run as appleSubscriptions } from '../cli/apple/subscriptions';
import { run as appleCpp } from '../cli/apple/cpp';
import { run as appleEvents } from '../cli/apple/events';
import { run as appleTestflight } from '../cli/apple/testflight';
import { run as appleReviewDetails } from '../cli/apple/review-details';
import { run as appleBundle } from '../cli/apple/bundle';
import { run as appleOfferCodes } from '../cli/apple/offer-codes';
import { run as applePpo } from '../cli/apple/ppo';
import { run as appleIapSubmit } from '../cli/apple/iap-submit';
import { run as appleRelease } from '../cli/apple/release';
import { run as appleEncryption } from '../cli/apple/encryption';
import { run as appleAdhoc } from '../cli/apple/adhoc';
import { run as playProducts } from '../cli/play/products';
import { run as playSubscriptions } from '../cli/play/subscriptions';
import { run as playImages } from '../cli/play/images';
import { run as playRollout } from '../cli/play/rollout';
import { run as playRelease } from '../cli/play/release';
import { run as appleListing } from '../cli/apple/listing';
import { run as appleAppinfo } from '../cli/apple/appinfo';
import { run as applePromoted } from '../cli/apple/promoted';
import { run as appleWinBack } from '../cli/apple/win-back';
import { run as applePreorder } from '../cli/apple/preorder';
import { run as playListing } from '../cli/play/listing';
import { run as playDataSafety } from '../cli/play/data-safety';
import { run as playUpload } from '../cli/play/upload';
import { run as prices } from '../cli/prices';
import { makeAab } from './build-fixtures';
import { ascEnv, BASE, capture, playEnv, project, restore } from './helpers/store-mock';
import { installStores, type Stores, uninstallStores, writes } from './helpers/fake-stores';
let s: Stores;
beforeAll(() => { ascEnv(); playEnv(); });
afterAll(restore);
beforeEach(() => { upsertTiming.waitMs = 0; s = installStores(); });
afterEach(() => { uninstallStores(); });
const APP = '6400000101';
const LISTING = '# Play\n\n## English\n<!-- play: en-US -->\n\n### Play short description\n```\nNotes.\n```\n\n### Play full description\n```\nNotes for everyone.\n```\n\n### What\'s new\n```\nFixes.\n```\n';
const png = (n: number): Uint8Array => new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, n, n + 1, n + 2]);
const CONFIG: ShipConfig = {
...BASE,
languages: [{ id: 'en', apple: 'en-US', play: 'en-US' }, { id: 'de', apple: 'de-DE', play: 'de-DE' }],
products: [
{ id: 'com.example.notes.pro', type: 'non_consumable', usd: 2.99, listings: { en: { title: 'Pro', description: 'Every feature.' }, de: { title: 'Pro', description: 'Alles.' } } },
{ id: 'com.example.notes.tip', type: 'consumable', usd: 0.99, listings: { en: { title: 'Tip', description: 'Say thanks.' } },
offerCodes: [{ name: 'Launch', free: true, eligibility: ['NON_SPENDER'] } as never] },
],
apple: {
...BASE.apple!, testflight: { groups: [{ name: 'Friends' }, { name: 'Public', internal: false } as never] } as never,
customProductPages: [{ name: 'Spring', promotionalText: { en: 'Spring sale' } } as never],
events: [{ referenceName: 'Spring event', badge: 'SPECIAL_EVENT', listings: { en: { name: 'Spring', shortDescription: 'Short', longDescription: 'Long text' } },
schedule: { publishStart: '2030-03-01T00:00:00Z', eventStart: '2030-03-02T00:00:00Z', eventEnd: '2030-03-09T00:00:00Z' } } as never],
},
};
/** Runs a command twice; returns the writes of each run. The second must be empty. */
async function twice(run: () => Promise<void>): Promise<{ first: string[]; second: string[] }> {
const a = s.calls.length;
const r1 = await capture(run);
if (r1.exit) throw new Error(`first run exit ${r1.exit}:\n${r1.out}\n${r1.err}`);
const b = s.calls.length;
const r2 = await capture(run);
if (r2.exit) throw new Error(`second run exit ${r2.exit}:\n${r2.out}\n${r2.err}`);
const show = (from: number, to?: number) => writes(s.calls.slice(from, to)).map(c => `${c.method} ${decodeURIComponent(c.path).replace(/\?.*/, '')}`);
return { first: show(a, b), second: show(b) };
}
const count = (type: string): number => s.asc.all(type).length;
describe('App Store Connect: a second run writes nothing', () => {
test('apple iap: product, localizations, price schedule, availability once', async () => {
const p = project(CONFIG);
const r = await twice(() => appleIap(p.ctx([])));
expect(r.first).toContain('POST /v2/inAppPurchases');
expect(r.second).toEqual([]);
expect(count('inAppPurchases')).toBe(2);
expect(count('inAppPurchaseLocalizations')).toBe(3);
expect(count('inAppPurchasePriceSchedules')).toBe(2);
expect(count('inAppPurchaseAvailabilities')).toBe(2);
});
test('apple screenshots: sets and screenshots once, in order', async () => {
const files: Record<string, Uint8Array> = {};
for (const l of ['en', 'de']) for (const d of ['ios69', 'ios65']) for (const n of [1, 2, 3]) files[`store/renders/${l}/${d}/0${n}.png`] = png(n + (d === 'ios65' ? 10 : 0) + (l === 'de' ? 20 : 0));
const p = project(CONFIG, files);
const v = s.asc.put({ type: 'appStoreVersions', id: 'ver-1', attributes: { versionString: '1.0.0', appVersionState: 'PREPARE_FOR_SUBMISSION', platform: 'IOS' }, rels: { app: APP } });
for (const loc of ['en-US', 'de-DE']) s.asc.put({ type: 'appStoreVersionLocalizations', id: `loc-${loc}`, attributes: { locale: loc }, rels: { appStoreVersion: v.id } });
const r = await twice(() => appleScreenshots(p.ctx([])));
expect(r.first.filter(x => x === 'POST /v1/appScreenshotSets')).toHaveLength(4);
expect(r.second).toEqual([]);
expect(count('appScreenshotSets')).toBe(4);
expect(count('appScreenshots')).toBe(12);
});
test('apple cpp create, events create, testflight groups, review-details, bundle, offer-codes, ppo create', async () => {
const p = project({ ...CONFIG, shots: { variants: { b: {} } } as never }, { '.storebound/credentials.json': JSON.stringify({ reviewContact: { firstName: 'Ex', lastName: 'Ample', phone: '+1 555 0100', email: 'review@example.com' } }) });
s.asc.put({ type: 'appStoreVersions', id: 'ver-1', attributes: { versionString: '1.0.0', appVersionState: 'PREPARE_FOR_SUBMISSION', platform: 'IOS' }, rels: { app: APP } });
s.asc.put({ type: 'inAppPurchases', id: 'iap-tip', attributes: { productId: 'com.example.notes.tip', state: 'READY_TO_SUBMIT' }, rels: { app: APP } });
for (const [name, run] of [
['cpp', () => appleCpp(p.ctx(['create']))],
['events', () => appleEvents(p.ctx(['create']))],
['testflight', () => appleTestflight(p.ctx(['groups']))],
['review-details', () => appleReviewDetails(p.ctx([]))],
['bundle', () => appleBundle(p.ctx([]))],
['offer-codes', () => appleOfferCodes(p.ctx([]))],
['ppo', () => applePpo(p.ctx(['create', '--variant', 'b']))],
] as [string, () => Promise<void>][]) {
const r = await twice(run);
expect([name, r.first.length > 0]).toEqual([name, true]);
expect([name, r.second]).toEqual([name, []]);
}
expect(count('appCustomProductPages')).toBe(1);
expect(count('appEvents')).toBe(1);
expect(count('appEventLocalizations')).toBe(1);
expect(count('betaGroups')).toBe(2);
expect(count('appStoreReviewDetails')).toBe(1);
expect(count('bundleIds')).toBe(1);
expect(count('inAppPurchaseOfferCodes')).toBe(1);
expect(count('appStoreVersionExperiments')).toBe(1);
expect(count('appStoreVersionExperimentTreatments')).toBe(1);
});
});
describe('App Store Connect: more commands, twice', () => {
test('apple subscriptions: group, subscription, localizations, availability, prices once', async () => {
const cfg: ShipConfig = { ...CONFIG, subscriptions: [{ name: 'Pro', listings: { en: { name: 'Pro' } }, subscriptions: [
{ id: 'com.example.notes.monthly', period: 'P1M', level: 1, usd: 4.99, listings: { en: { title: 'Monthly', description: 'Pro every month.' }, de: { title: 'Monatlich', description: 'Pro jeden Monat.' } } },
] } as never] };
const p = project(cfg);
const r = await twice(() => appleSubscriptions(p.ctx(['--yes'])));
expect(r.first).toContain('POST /v1/subscriptions');
expect(r.second).toEqual([]);
expect([count('subscriptionGroups'), count('subscriptions'), count('subscriptionLocalizations'), count('subscriptionAvailabilities'), count('subscriptionPrices')]).toEqual([1, 1, 2, 1, 3]);
});
test('apple iap-submit --no-submit: one draft, the item once', async () => {
const p = project({ ...CONFIG, products: [CONFIG.products![1]!] });
s.asc.put({ type: 'appStoreVersions', id: 'ver-1', attributes: { versionString: '1.0.0', appVersionState: 'READY_FOR_SALE', platform: 'IOS' }, rels: { app: APP } });
s.asc.put({ type: 'inAppPurchases', id: 'iap-old', attributes: { productId: 'com.example.notes.old', inAppPurchaseType: 'CONSUMABLE', state: 'APPROVED' }, rels: { app: APP } });
s.asc.put({ type: 'inAppPurchases', id: 'iap-tip', attributes: { productId: 'com.example.notes.tip', inAppPurchaseType: 'CONSUMABLE', state: 'READY_TO_SUBMIT' }, rels: { app: APP } });
s.asc.put({ type: 'inAppPurchaseVersions', id: 'iapv-tip', attributes: { version: 1, state: 'PREPARE_FOR_SUBMISSION' }, rels: { inAppPurchase: 'iap-tip' } });
const r = await twice(() => appleIapSubmit(p.ctx(['--no-submit', '--yes'])));
expect(r.first).toEqual(['POST /v1/reviewSubmissions', 'POST /v1/reviewSubmissionItems']);
expect(r.second).toEqual([]);
expect([count('reviewSubmissions'), count('reviewSubmissionItems')]).toEqual([1, 1]);
});
test('apple release --phased on, apple encryption, apple adhoc register', async () => {
const p = project({ ...CONFIG, apple: { ...CONFIG.apple!, usesNonExemptEncryption: false } }, { '.storebound/devices.csv': 'name,udid,platform\nTest phone,00008101-001A2B3C4D5E6F70,IOS\n' });
s.asc.put({ type: 'appStoreVersions', id: 'ver-2', attributes: { versionString: '1.1.0', appVersionState: 'PREPARE_FOR_SUBMISSION', platform: 'IOS' }, rels: { app: APP } });
s.asc.put({ type: 'builds', id: 'b-7', attributes: { version: '7', usesNonExemptEncryption: null, expired: false }, rels: { app: APP } });
for (const [name, run] of [
['release', () => appleRelease(p.ctx(['--phased', 'on']))],
['encryption', () => appleEncryption(p.ctx([]))],
['adhoc', () => appleAdhoc(p.ctx(['register', '--yes']))],
] as [string, () => Promise<void>][]) {
const r = await twice(run);
expect([name, r.first.length]).toEqual([name, 1]);
expect([name, r.second]).toEqual([name, []]);
}
expect([count('appStoreVersionPhasedReleases'), count('devices')]).toEqual([1, 1]);
});
});
describe('Google Play: a second run writes nothing', () => {
test('play products: created, activated, then unchanged', async () => {
const p = project(CONFIG);
const r = await twice(() => playProducts(p.ctx([])));
expect(r.first.some(x => x.startsWith('PATCH /androidpublisher/v3/applications/com.example.notes/onetimeproducts/'))).toBe(true);
expect(r.second).toEqual([]);
expect(s.play.products.size).toBe(2);
});
test('play images: uploaded once; the second run compares and commits nothing', async () => {
const files: Record<string, string | Uint8Array> = { 'store/listing.md': LISTING, 'store/icons/play-512.png': png(1) };
files['store/renders/en/feature/1024x500.png'] = png(2);
for (const [sub, base] of [['play', 10], ['tab7', 20], ['tab10', 30]] as const) for (const n of [1, 2]) files[`store/renders/en/${sub}/0${n}.png`] = png(base + n);
const p = project(CONFIG, files);
const r = await twice(() => playImages(p.ctx([])));
expect(r.first.filter(x => x.startsWith('POST /upload/'))).toHaveLength(8);
expect(r.second).toEqual([]);
expect(s.play.committed).toHaveLength(1);
expect(s.play.edits.size).toBe(0);
});
test('play subscriptions: created with base plan and intro offer once', async () => {
const cfg: ShipConfig = { ...CONFIG, subscriptions: [{ name: 'Pro', listings: { en: { name: 'Pro' } }, subscriptions: [
{ id: 'com.example.notes.monthly', period: 'P1M', level: 1, usd: 4.99, listings: { en: { title: 'Monthly', description: 'Pro every month.', benefits: ['Sync'] } }, intro: { type: 'free', duration: 'P1W' } },
] } as never] };
const p = project(cfg);
const r = await twice(() => playSubscriptions(p.ctx(['--yes'])));
expect(r.first.some(x => x.endsWith('/subscriptions'))).toBe(true);
expect(r.second).toEqual([]);
expect(s.play.subs.size).toBe(1);
expect(s.play.offers.size).toBe(1);
});
test('play rollout and play release --version-code: the same state is not committed again', async () => {
s.play.live.tracks.production = { releases: [{ versionCodes: ['41'], status: 'inProgress', userFraction: 0.1 }] };
s.play.live.bundles = [41, 42];
const p = project(CONFIG, { 'store/listing.md': LISTING });
let r = await twice(() => playRollout(p.ctx(['--fraction', '0.2', '--yes'])));
expect(r.first).toContain('PUT /androidpublisher/v3/applications/com.example.notes/edits/edit-1/tracks/production');
expect(r.second).toEqual([]);
r = await twice(() => playRelease(p.ctx(['--version-code', '42', '--internal', 'completed'])));
expect(r.first.some(x => x.endsWith('/tracks/internal'))).toBe(true);
expect(r.second).toEqual([]);
expect(s.play.edits.size).toBe(0);
});
});
const APPLE_MD = '# App Store\n\n## en-US · English\n\n### subtitle\n```\nNotes that sync\n```\n\n### keywords\n```\nnotes,lists\n```\n\n### description\n```\nNotes for everyone.\n```\n\n### promotionalText\n```\nNow with lists.\n```\n\n### whatsNew\n```\nFaster sync.\n```\n';
/** An app with a released 1.0.0, an editable app info and a processed build 9 of 1.1.0. */
function appleListingStore(): void {
s.asc.put({ type: 'appStoreVersions', id: 'ver-old', attributes: { versionString: '1.0.0', appVersionState: 'READY_FOR_SALE', platform: 'IOS' }, rels: { app: APP } });
s.asc.put({ type: 'appInfos', id: 'info-1', attributes: { state: 'PREPARE_FOR_SUBMISSION' }, rels: { app: APP } });
s.asc.put({ type: 'builds', id: 'b-9', attributes: { version: '9', processingState: 'VALID' }, rels: { app: APP } });
}
describe('listing, appinfo, data safety and the owner commands: a second run writes nothing', () => {
test('apple listing: version created (re-checked first), build attached, localizations created once; then nothing', async () => {
appleListingStore();
const p = project(CONFIG, { 'store/appstore.md': APPLE_MD });
const r = await twice(() => appleListing(p.ctx(['--version', '1.1.0', '--build', '9'])));
expect(r.first).toEqual(['POST /v1/appStoreVersions', expect.stringMatching(/^PATCH \/v1\/appStoreVersions\/.+\/relationships\/build$/), 'POST /v1/appInfoLocalizations', 'POST /v1/appStoreVersionLocalizations']);
expect(r.second).toEqual([]);
expect([count('appStoreVersions'), count('appInfoLocalizations'), count('appStoreVersionLocalizations')]).toEqual([2, 1, 1]);
// a changed text: only that field of that localization is PATCHed, the build is not attached again
const q = project(CONFIG, { 'store/appstore.md': APPLE_MD.replace('Notes for everyone.', 'Notes for all.') });
const before = s.calls.length;
await capture(() => appleListing(q.ctx(['--version', '1.1.0', '--build', '9'])));
const w = writes(s.calls.slice(before));
expect(w.map(c => `${c.method} ${c.path.replace(/\/[^/]+$/, '/:id')}`)).toEqual(['PATCH /v1/appStoreVersionLocalizations/:id']);
expect(Object.keys((w[0]!.body as { data: { attributes: object } }).data.attributes)).toEqual(['description']);
});
test('apple listing: a lost answer on the version create is found by the re-check, not created twice', async () => {
appleListingStore();
const p = project(CONFIG, { 'store/appstore.md': APPLE_MD });
s.faults.push({ method: 'POST', match: /^\/v1\/appStoreVersions$/, when: 'after', status: 502 });
const r = await capture(() => appleListing(p.ctx(['--version', '1.1.0'])));
expect(r.exit).toBe(null);
expect(r.err).toContain('no clear answer');
expect(count('appStoreVersions')).toBe(2);
expect(s.calls.filter(c => c.method === 'POST' && c.path === '/v1/appStoreVersions')).toHaveLength(1);
expect(count('appStoreVersionLocalizations')).toBe(1);
});
test('apple listing: a localization the list does not show yet answers 409; it is used and updated, not created twice', async () => {
appleListingStore();
s.asc.put({ type: 'appStoreVersions', id: 'ver-2', attributes: { versionString: '1.1.0', appVersionState: 'PREPARE_FOR_SUBMISSION', platform: 'IOS', copyright: `${new Date().getFullYear()} Example Notes`, releaseType: 'MANUAL' }, rels: { app: APP } });
s.asc.put({ type: 'appStoreVersionLocalizations', id: 'vloc-en', attributes: { locale: 'en-US', description: 'Old.' }, rels: { appStoreVersion: 'ver-2' }, hiddenReads: 1 } as never);
const p = project(CONFIG, { 'store/appstore.md': APPLE_MD });
const r = await capture(() => appleListing(p.ctx(['--version', '1.1.0'])));
expect(r.exit).toBe(null);
expect(r.out).toContain('already exists, using it');
expect(count('appStoreVersionLocalizations')).toBe(1);
expect(s.asc.res.get('vloc-en')!.attributes.description).toBe('Notes for everyone.');
});
test('play listing: one committed edit with only what differs; the second run opens no write edit and commits nothing', async () => {
s.play.live.listings['de-DE'] = { language: 'de-DE', title: 'Notizen' };
const p = project(CONFIG, { 'store/listing.md': LISTING });
const r = await twice(() => playListing(p.ctx([])));
expect(r.first).toEqual(['PUT /androidpublisher/v3/applications/com.example.notes/edits/edit-2/details', 'PUT /androidpublisher/v3/applications/com.example.notes/edits/edit-2/listings/en-US',
'POST /androidpublisher/v3/applications/com.example.notes/edits/edit-2:commit']);
expect(r.second).toEqual([]);
expect(s.play.committed).toHaveLength(1);
expect(s.play.edits.size).toBe(0);
expect(s.play.live.listings['de-DE']).toEqual({ language: 'de-DE', title: 'Notizen' }); // a language not in the file is left alone
});
test('play listing: the store reached the wanted state between plan and edit: the edit is deleted, not committed', async () => {
const p = project(CONFIG, { 'store/listing.md': LISTING });
// the plan sees an empty listing; right after it (before the write edit opens) another run makes it current
const orig = s.play.handle.bind(s.play);
let planned = false;
s.play.handle = (method, url, body) => {
if (method === 'DELETE' && /\/edits\/edit-1$/.test(url) && !planned) {
planned = true;
s.play.live.details = { defaultLanguage: 'en-US', contactEmail: 'support@example.com', contactWebsite: 'https://example.com' };
s.play.live.listings['en-US'] = { language: 'en-US', title: 'Example Notes', shortDescription: 'Notes.', fullDescription: 'Notes for everyone.' };
}
return orig(method, url, body);
};
const r = await capture(() => playListing(p.ctx([])));
expect(r.out).toContain('nothing committed');
expect(s.play.committed).toEqual([]);
expect(writes(s.calls)).toEqual([]);
expect(s.play.edits.size).toBe(0);
});
test('apple appinfo: categories, age rating, content rights, price and availability set once, then compared and left', async () => {
s.asc.put({ type: 'appInfos', id: 'info-1', attributes: { state: 'PREPARE_FOR_SUBMISSION' }, rels: { app: APP } });
s.asc.put({ type: 'ageRatingDeclarations', id: 'age-1', attributes: {}, rels: { appInfo: 'info-1' } });
s.asc.put({ type: 'appPricePoints', id: 'app-pp-free', attributes: { customerPrice: '0.0' }, rels: { app: APP, territory: 'USA' } });
const cfg: ShipConfig = { ...CONFIG, apple: { ...CONFIG.apple!, info: { categories: { primary: 'PRODUCTIVITY' }, contentRights: 'DOES_NOT_USE_THIRD_PARTY_CONTENT', ageRating: { advertising: true } } as never } };
const p = project(cfg);
const r = await twice(() => appleAppinfo(p.ctx([])));
expect(r.first).toEqual(['PATCH /v1/appInfos/info-1', 'PATCH /v1/ageRatingDeclarations/info-1', `PATCH /v1/apps/${APP}`, 'POST /v1/appPriceSchedules', 'POST /v2/appAvailabilities']);
expect(r.second).toEqual([]);
expect(s.asc.res.get('age-1')!.attributes.advertising).toBe(true);
// one answer changed in the config: only the age rating is PATCHed
const q = project({ ...cfg, apple: { ...cfg.apple!, info: { ...cfg.apple!.info!, ageRating: { advertising: true, contests: 'INFREQUENT_OR_MILD' } } as never } });
const before = s.calls.length;
await capture(() => appleAppinfo(q.ctx([])));
expect(writes(s.calls.slice(before)).map(c => `${c.method} ${c.path}`)).toEqual(['PATCH /v1/ageRatingDeclarations/info-1']);
});
test('play data-safety: the same CSV is not sent again (hash in .storebound/); a changed one or --force is', async () => {
const ds = { collectsData: true, encryptedInTransit: true, deletionRequest: false, data: { PSL_DEVICE_ID: { shared: false, collect: ['analytics'] } } };
const p = project({ ...CONFIG, dataSafety: ds as never });
const r = await twice(() => playDataSafety(p.ctx([])));
expect(r.first).toEqual(['POST /androidpublisher/v3/applications/com.example.notes/dataSafety']);
expect(r.second).toEqual([]);
expect(existsSync(join(p.root, '.storebound', 'data-safety.sha256'))).toBe(true);
let before = s.calls.length;
await capture(() => playDataSafety(p.ctx(['--force'])));
expect(writes(s.calls.slice(before))).toHaveLength(1);
const q = project({ ...CONFIG, dataSafety: { ...ds, data: { ...ds.data, PSL_EMAIL: { shared: false, collect: ['functionality'] } } } as never });
mkdirSync(join(q.root, '.storebound'), { recursive: true });
writeFileSync(join(q.root, '.storebound', 'data-safety.sha256'), readFileSync(join(p.root, '.storebound', 'data-safety.sha256')));
before = s.calls.length;
await capture(() => playDataSafety(q.ctx([])));
expect(writes(s.calls.slice(before))).toHaveLength(1);
expect(s.play.dataSafety).toHaveLength(3);
});
test('apple promoted: created and ordered once', async () => {
s.asc.put({ type: 'inAppPurchases', id: 'iap-pro', attributes: { productId: 'com.example.notes.pro', state: 'APPROVED' }, rels: { app: APP } });
s.asc.put({ type: 'inAppPurchases', id: 'iap-tip', attributes: { productId: 'com.example.notes.tip', state: 'APPROVED' }, rels: { app: APP } });
const p = project({ ...CONFIG, apple: { ...CONFIG.apple!, promoted: { products: ['com.example.notes.tip', 'com.example.notes.pro'] } } });
const r = await twice(() => applePromoted(p.ctx(['--yes'])));
expect(r.first.filter(x => x === 'POST /v1/promotedPurchases')).toHaveLength(2);
expect(r.second).toEqual([]);
expect(count('promotedPurchases')).toBe(2);
});
test('apple win-back: the missing offer is created once', async () => {
const g = s.asc.put({ type: 'subscriptionGroups', id: 'grp-1', attributes: { referenceName: 'Pro' }, rels: { app: APP } });
s.asc.put({ type: 'subscriptions', id: 'sub-1', attributes: { productId: 'com.example.notes.monthly', state: 'APPROVED' }, rels: { subscriptionGroup: g.id } });
const cfg: ShipConfig = { ...CONFIG, subscriptions: [{ name: 'Pro', listings: { en: { name: 'Pro' } }, subscriptions: [
{ id: 'com.example.notes.monthly', period: 'P1M', level: 1, usd: 4.99, listings: { en: { title: 'Monthly', description: 'Pro every month.' } },
winBack: [{ id: 'come-back', type: 'free', duration: 'P1M', paidMonths: 1, lapsedMonths: { min: 1, max: 6 }, start: '2099-01-01' }] },
] } as never] };
const p = project(cfg);
const r = await twice(() => appleWinBack(p.ctx(['--yes'])));
expect(r.first).toEqual(['POST /v1/winBackOffers']);
expect(r.second).toEqual([]);
expect(count('winBackOffers')).toBe(1);
});
test('apple preorder enable: territories set once; the same date again changes nothing', async () => {
const av = s.asc.put({ type: 'appAvailabilities', id: 'avail-1', attributes: { availableInNewTerritories: true }, rels: { app: APP } });
for (const t of ['USA', 'DEU']) s.asc.put({ type: 'territoryAvailabilities', id: `ta-${t}`, attributes: { available: true, contentStatuses: ['CANNOT_SELL'] }, rels: { appAvailability: av.id, territory: t } });
const p = project(CONFIG);
const date = new Date(Date.now() + 30 * 86400_000).toISOString().slice(0, 10);
const r = await twice(() => applePreorder(p.ctx(['enable', '--release-date', date, '--yes'])));
expect(r.first).toEqual(['PATCH /v1/territoryAvailabilities/ta-USA', 'PATCH /v1/territoryAvailabilities/ta-DEU']);
expect(r.second).toEqual([]);
});
test('apple testflight testers: created in their groups once', async () => {
s.asc.put({ type: 'betaGroups', id: 'grp-friends', attributes: { name: 'Friends', isInternalGroup: false }, rels: { app: APP } });
const p = project(CONFIG, { '.storebound/testers.csv': 'email,first_name,groups\ntester1@example.com,Ex,Friends\ntester2@example.com,Am,Friends\n' });
const r = await twice(() => appleTestflight(p.ctx(['testers', '--yes'])));
expect(r.first).toEqual(['POST /v1/betaTesters', 'POST /v1/betaTesters']);
expect(r.second).toEqual([]);
expect(count('betaTesters')).toBe(2);
});
test('play upload: uploaded once; the same versionCode on the same track is not sent again', async () => {
const p = project(CONFIG, { 'store/listing.md': LISTING, 'build/android/app.aab': makeAab('com.example.notes', 42) });
const r = await twice(() => playUpload(p.ctx(['--yes'])));
expect(r.first).toEqual(['POST /upload/androidpublisher/v3/applications/com.example.notes/edits/edit-2/bundles', 'PUT /androidpublisher/v3/applications/com.example.notes/edits/edit-2/tracks/internal',
'POST /androidpublisher/v3/applications/com.example.notes/edits/edit-2:commit']);
expect(r.second).toEqual([]);
expect(s.play.committed).toHaveLength(1);
});
test('prices import (Play): changed regions written once, then the diff is empty', async () => {
const p = project({ ...CONFIG, products: [CONFIG.products![0]!] }, { 'store/prices.csv': 'product,store,region,currency,price\ncom.example.notes.pro,play,DE,EUR,3.49\n' });
await capture(() => playProducts(p.ctx([])));
const r = await twice(() => prices(p.ctx(['import', '--store', 'play', '--yes'])));
expect(r.first.some(x => x.startsWith('PATCH /androidpublisher/v3/applications/com.example.notes/onetimeproducts/'))).toBe(true);
expect(r.second).toEqual([]);
});
});
describe('crash midway and unclear answers', () => {
test('screenshot set: an upload that dies on the 3rd file leaves a prefix; the re-run finishes it without duplicates, in order', async () => {
const files: Record<string, Uint8Array> = {};
for (const n of [1, 2, 3, 4]) files[`store/renders/en/ios69/0${n}.png`] = png(n);
const cfg = { ...CONFIG, languages: [{ id: 'en', apple: 'en-US', play: 'en-US' }] };
const p = project(cfg, files);
const v = s.asc.put({ type: 'appStoreVersions', id: 'ver-1', attributes: { versionString: '1.0.0', appVersionState: 'PREPARE_FOR_SUBMISSION', platform: 'IOS' }, rels: { app: APP } });
s.asc.put({ type: 'appStoreVersionLocalizations', id: 'loc-en', attributes: { locale: 'en-US' }, rels: { appStoreVersion: v.id } });
// an older set: two screenshots, the first already the wanted 01.png
const set = s.asc.put({ type: 'appScreenshotSets', id: 'set-old', attributes: { screenshotDisplayType: 'APP_IPHONE_67' }, rels: { appStoreVersionLocalization: 'loc-en' } });
const md5 = (b: Uint8Array) => new Bun.CryptoHasher('md5').update(b).digest('hex');
s.asc.put({ type: 'appScreenshots', id: 'shot-a', attributes: { sourceFileChecksum: md5(png(1)), assetDeliveryState: { state: 'COMPLETE' }, fileName: '01.png' }, rels: { appScreenshotSet: set.id } });
s.asc.put({ type: 'appScreenshots', id: 'shot-x', attributes: { sourceFileChecksum: 'stale', assetDeliveryState: { state: 'COMPLETE' }, fileName: 'old.png' }, rels: { appScreenshotSet: set.id } });
s.failPart = n => n === 2; // the 2nd uploaded part (03.png) fails
const r1 = await capture(() => appleScreenshots(p.ctx(['--only', 'en-US']))).catch(e => ({ out: String(e), err: '', exit: 1 }));
expect(r1.out + r1.err).toContain('03.png part 0 -> 400');
expect(s.asc.children(set.id, 'appScreenshots').map(x => x.id)).toContain('shot-a');
s.failPart = undefined;
const r2 = await capture(() => appleScreenshots(p.ctx(['--only', 'en-US'])));
expect(r2.exit).toBe(null);
const shots = s.asc.children(set.id, 'appScreenshots');
expect(shots.map(x => x.attributes.sourceFileChecksum)).toEqual([1, 2, 3, 4].map(n => md5(png(n))));
expect(shots.every(x => (x.attributes.assetDeliveryState as { state: string }).state === 'COMPLETE')).toBe(true);
expect(shots[0]!.id).toBe('shot-a'); // the matching first screenshot was kept, not uploaded again
expect(count('appScreenshotSets')).toBe(1);
const before = s.calls.length;
await capture(() => appleScreenshots(p.ctx(['--only', 'en-US'])));
expect(writes(s.calls.slice(before))).toEqual([]);
});
test('IAP create: a 5xx after Apple created it is found, not created again', async () => {
const p = project({ ...CONFIG, products: [CONFIG.products![0]!] });
s.faults.push({ method: 'POST', match: /^\/v2\/inAppPurchases$/, when: 'after', status: 502 });
const r = await capture(() => appleIap(p.ctx([])));
expect(r.exit).toBe(null);
expect(r.err).toContain('no clear answer');
expect(count('inAppPurchases')).toBe(1);
expect(s.calls.filter(c => c.method === 'POST' && c.path === '/v2/inAppPurchases')).toHaveLength(1);
expect(count('inAppPurchaseLocalizations')).toBe(2);
});
test('IAP create: a 5xx before anything happened is tried once more (product ids are unique, so that is safe)', async () => {
const p = project({ ...CONFIG, products: [CONFIG.products![0]!] });
s.faults.push({ method: 'POST', match: /^\/v2\/inAppPurchases$/, when: 'before', status: 503 });
const r = await capture(() => appleIap(p.ctx([])));
expect(r.exit).toBe(null);
expect(count('inAppPurchases')).toBe(1);
expect(s.calls.filter(c => c.method === 'POST' && c.path === '/v2/inAppPurchases')).toHaveLength(2);
});
test('IAP create: crash right after the create (process gone); the re-run during the list lag uses the journal, no duplicate', async () => {
const p = project({ ...CONFIG, products: [CONFIG.products![0]!] });
// first run: the product is created, then the run dies on the localization
s.faults.push({ method: 'POST', match: /^\/v1\/inAppPurchaseLocalizations$/, when: 'before', status: 400 });
s.asc.lag.inAppPurchases = 50;
await capture(() => appleIap(p.ctx([]))).catch(e => expect(String(e)).toContain('injected'));
expect(count('inAppPurchases')).toBe(1);
expect(Object.keys(readJournal(p.root))).toEqual(['apple:com.example.notes:iap:com.example.notes.pro']);
const r = await capture(() => appleIap(p.ctx([])));
expect(r.out).toContain('does not show it yet, using it');
expect(count('inAppPurchases')).toBe(1);
expect(count('inAppPurchaseLocalizations')).toBe(2);
});
test('a 409 duplicate is treated as found (no second create, no error)', async () => {
const p = project({ ...CONFIG, products: [CONFIG.products![0]!] });
s.asc.put({ type: 'inAppPurchases', id: 'iap-old', attributes: { productId: 'com.example.notes.pro', state: 'MISSING_METADATA' }, rels: { app: APP }, hiddenReads: 1 } as never);
const r = await capture(() => appleIap(p.ctx([])));
expect(r.exit).toBe(null);
expect(r.out).toContain('already exists, using it');
expect(count('inAppPurchases')).toBe(1);
});
test('apple subscriptions: a lost answer on the subscription create is found again; the second run creates nothing', async () => {
const cfg: ShipConfig = { ...CONFIG, subscriptions: [{ name: 'Pro', listings: { en: { name: 'Pro' } }, subscriptions: [
{ id: 'com.example.notes.monthly', period: 'P1M', level: 1, usd: 4.99, listings: { en: { title: 'Monthly', description: 'Pro every month.' } } },
] } as never] };
const p = project(cfg);
s.faults.push({ method: 'POST', match: /^\/v1\/subscriptions$/, when: 'after', status: 504 });
await capture(() => appleSubscriptions(p.ctx(['--yes'])));
expect(count('subscriptions')).toBe(1);
expect(count('subscriptionGroups')).toBe(1);
const before = s.calls.length;
await capture(() => appleSubscriptions(p.ctx(['--yes'])));
expect(writes(s.calls.slice(before)).filter(c => c.method === 'POST' && /subscription(Group)?s$|Localizations$/.test(c.path))).toEqual([]);
expect(count('subscriptions')).toBe(1);
expect(count('subscriptionLocalizations')).toBe(1);
});
test('Play subscription create: 409 ALREADY_EXISTS is found, offers are not created twice', async () => {
const cfg: ShipConfig = { ...CONFIG, subscriptions: [{ name: 'Pro', listings: { en: { name: 'Pro' } }, subscriptions: [
{ id: 'com.example.notes.yearly', period: 'P1Y', level: 1, usd: 29.99, listings: { en: { title: 'Yearly', description: 'Pro every year.', benefits: ['Sync'] } } },
] } as never] };
const p = project(cfg);
s.faults.push({ method: 'POST', match: /\/subscriptions\?productId=/, when: 'after', status: 500 });
const r = await capture(() => playSubscriptions(p.ctx(['--yes'])));
expect(r.err).toContain('no clear answer');
expect(s.play.subs.size).toBe(1);
expect(s.calls.filter(c => c.method === 'POST' && /\/subscriptions\?productId=/.test(c.path))).toHaveLength(1);
});
});
describe('Play edits', () => {
test('an error inside the edit deletes it; nothing is committed; no second edit is ever open', async () => {
const play = await playClient(project().root, 'com.example.notes');
await expect(play.edit(async () => { throw new Error('boom'); })).rejects.toThrow('boom');
expect(s.play.edits.size).toBe(0);
expect(s.play.committed).toEqual([]);
await expect(play.edit(async () => { await play.read(async () => 1); })).rejects.toThrow('already open');
expect(s.play.edits.size).toBe(0);
});
test('an upload without a clear answer inside an edit: the edit is discarded and redone from scratch, one image', async () => {
const play = await playClient(project().root, 'com.example.notes');
s.faults.push({ method: 'POST', match: /phoneScreenshots\?uploadType=media/, when: 'after', status: 503 });
await play.edit(async id => {
await play.call('POST', `${play.UPLOAD}/edits/${id}/listings/en-US/phoneScreenshots?uploadType=media`, png(1), { 'Content-Type': 'image/png' });
});
expect(s.play.live.images['en-US/phoneScreenshots']).toHaveLength(1);
expect(s.play.committed).toHaveLength(1);
expect(s.play.edits.size).toBe(0);
});
test('a commit without a clear answer is never redone', async () => {
const play = await playClient(project().root, 'com.example.notes');
s.faults.push({ method: 'POST', match: /:commit$/, when: 'after', status: 502 });
let runs = 0;
await expect(play.edit(async id => { runs++; await play.call('PUT', `${play.API}/edits/${id}/details`, { defaultLanguage: 'en-US' }); })).rejects.toThrow('may be live');
expect(runs).toBe(1);
expect(s.play.committed).toHaveLength(1);
});
test('unchanged(): the edit is deleted, not committed', async () => {
const play = await playClient(project().root, 'com.example.notes');
await play.edit(async (_id, ctl) => { ctl.unchanged(); });
expect(s.play.committed).toEqual([]);
expect(s.play.edits.size).toBe(0);
});
});
describe('helpers', () => {
test('retrySafe: POST creates are not retried, idempotent actions are', () => {
expect(retrySafe('GET', '/v1/apps')).toBe(true);
expect(retrySafe('PATCH', '/v1/apps/1')).toBe(true);
expect(retrySafe('DELETE', '/v1/appScreenshots/1')).toBe(true);
expect(retrySafe('POST', '/v2/inAppPurchases')).toBe(false);
expect(retrySafe('POST', '/v1/appScreenshots')).toBe(false);
expect(retrySafe('POST', '/v1/betaGroups/1/relationships/builds')).toBe(true);
expect(retrySafe('POST', '/v1/inAppPurchasePriceSchedules')).toBe(true);
const play = 'https://androidpublisher.googleapis.com/androidpublisher/v3/applications/com.example.notes';
expect(retrySafe('POST', `${play}/edits`)).toBe(true);
expect(retrySafe('POST', `${play}/edits/e1:commit`)).toBe(false);
expect(retrySafe('POST', `${play}/edits/e1:validate`)).toBe(true);
expect(retrySafe('POST', `${play}/pricing:convertRegionPrices`)).toBe(true);
expect(retrySafe('POST', `${play}/subscriptions?productId=x`)).toBe(false);
expect(retrySafe('POST', 'https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/com.example.notes/edits/e1/bundles?uploadType=media')).toBe(false);
});
test('isConflict: duplicates only, not Apple validation errors', () => {
expect(isConflict(new Error('POST /v2/inAppPurchases -> 409 {"errors":[{"code":"ENTITY_ERROR.ATTRIBUTE.INVALID.DUPLICATE","detail":"already been used"}]}'))).toBe(true);
expect(isConflict(new Error('POST /v2/inAppPurchases -> 409 {"errors":[{"code":"ENTITY_ERROR.ATTRIBUTE.INVALID","detail":"name is too long"}]}'))).toBe(false);
expect(isConflict(new Error('POST /subscriptions -> 409 {"error":{"status":"ALREADY_EXISTS"}}'))).toBe(true);
expect(isConflict(new Error('RevenueCat POST /v2/projects/p/products: 409 {"message":"resource already exists"}'))).toBe(true);
expect(isConflict(new Error('GET /v1/apps -> 404'))).toBe(false);
});
test('createOnce / findOrCreate: unknown outcome without a unique key stops instead of creating twice', async () => {
let made = 0;
const lost = () => { made++; throw new AmbiguousWriteError('POST /v1/appEvents -> 504'); };
await expect(createOnce({ what: 'event', find: async () => null, create: lost })).rejects.toThrow('not sent again');
expect(made).toBe(1);
made = 0;
await expect(createOnce({ what: 'group', unique: true, find: async () => null, create: lost })).rejects.toThrow('not sent again');
expect(made).toBe(2);
const root = project().root;
const one = await findOrCreate({ what: 'x', find: async () => null, create: async () => ({ id: 'n1' }),
journal: { root, key: 'k', byId: async () => null, idOf: v => v.id } });
expect(one).toEqual({ value: { id: 'n1' }, created: true });
const again = await findOrCreate({ what: 'x', find: async () => null, create: async () => { throw new Error('must not create'); },
journal: { root, key: 'k', byId: async id => ({ id }), idOf: v => v.id } });
expect(again).toEqual({ value: { id: 'n1' }, created: false });
});
test('keptPrefix, sameRelease, sameReleases', () => {
const d = (checksum: string, state = 'COMPLETE') => ({ checksum, state });
expect(keptPrefix([d('a'), d('b'), d('x')], ['a', 'b', 'c'])).toBe(2);
expect(keptPrefix([d('a', 'AWAITING_UPLOAD'), d('b')], ['a', 'b'])).toBe(0);
expect(keptPrefix([], ['a'])).toBe(0);
const notes = [{ language: 'en-US', text: 'Fixes' }];
expect(sameRelease([{ versionCodes: ['42'], status: 'completed', releaseNotes: notes }], { versionCodes: ['42'], status: 'completed', releaseNotes: notes })).toBe(true);
expect(sameRelease([{ versionCodes: ['42'], status: 'draft' }], { versionCodes: ['42'], status: 'completed' })).toBe(false);
expect(sameReleases([{ status: 'completed', versionCodes: ['1'] }, { versionCodes: ['2'], status: 'inProgress', userFraction: 0.2 }],
[{ userFraction: 0.2, status: 'inProgress', versionCodes: ['2'] }, { versionCodes: ['1'], status: 'completed' }])).toBe(true);
});
});
describe('one writer per app and store', () => {
test('a second run is refused with the holder; a dead holder is taken over; --force-unlock removes it', () => {
const root = project().root;
const release = acquireLock(root, 'apple-com.example.notes', 'apple iap');
expect(() => acquireLock(root, 'apple-com.example.notes', 'apple screenshots')).toThrow('`storebound apple iap`');
release();
acquireLock(root, 'apple-com.example.notes', 'apple screenshots')();
// a lock held by another live process
mkdirSync(join(root, '.storebound', 'locks'), { recursive: true });
const file = join(root, '.storebound', 'locks', 'play-com.example.notes.lock');
writeFileSync(file, JSON.stringify({ pid: process.ppid, host: hostname(), command: 'play images', startedAt: new Date().toISOString() }));
expect(() => acquireLock(root, 'play-com.example.notes', 'play listing')).toThrow('another storebound run is writing to play com.example.notes: `storebound play images`');
const free = acquireLock(root, 'play-com.example.notes', 'play listing', { force: true });
expect(JSON.parse(readFileSync(file, 'utf8')).command).toBe('play listing');
free();
expect(existsSync(file)).toBe(false);
expect(staleLock({ pid: 999999999, host: 'h', command: 'x', startedAt: new Date().toISOString() }, Date.now(), 'h', () => false)).toBe(true);
expect(staleLock({ pid: 1, host: 'other', command: 'x', startedAt: new Date().toISOString() }, Date.now(), 'h', () => false)).toBe(false);
expect(staleLock({ pid: 1, host: 'other', command: 'x', startedAt: new Date(Date.now() - 13 * 3600_000).toISOString() }, Date.now(), 'h')).toBe(true);
});
test('which runs take a lock', () => {
const k = (cmd: string, argv: string[]) => lockKeys(cmd, parseArgs(argv), CONFIG);
expect(k('apple iap', [])).toEqual(['apple-com.example.notes']);
expect(k('apple iap', ['--dry'])).toEqual([]);
expect(k('apple testflight', ['status'])).toEqual([]);
expect(k('apple listing', ['pull'])).toEqual([]);
expect(k('play images', [])).toEqual(['play-com.example.notes']);
expect(k('play status', [])).toEqual([]);
expect(k('prices', ['import'])).toEqual(['apple-com.example.notes', 'play-com.example.notes']);
expect(k('prices', ['export'])).toEqual([]);
expect(k('validate', [])).toEqual([]);
});
});

View file

@ -97,3 +97,12 @@ describe('listing commands', () => {
expect(sb(dir, 'listing', 'translate', '--to', 'xx').stderr.toString()).toContain('not a language of the config');
});
});
test('listing check counts App Store keywords in UTF-8 bytes, the other fields in characters', () => {
const ru = 'игра,бег,прыжки,монеты,уровни,рекорд,аркада,быстро'; // 50 characters, 93 bytes
const kw = checkFields('apple', { keywords: ru, subtitle: 'Быстрая аркада' }).find(c => c.field === 'keywords')!;
expect(kw).toMatchObject({ chars: 93, unit: 'bytes', problems: [] });
expect(checkFields('apple', { keywords: ru + ',звук' }).find(c => c.field === 'keywords')!.problems).toContain('102 > 100 bytes');
expect(checkFields('apple', { subtitle: 'Быстрая аркада' })[0]).toMatchObject({ chars: 14, unit: 'chars' });
});

216
tests/local-fonts.test.ts Normal file
View file

@ -0,0 +1,216 @@
// A game's own brand font as a local file in shots.fonts: validation, cmap coverage with listed + Noto fallbacks,
// @font-face served in place, `shots check` (local + listed fallback pass, license warning) and the content hash that
// invalidates the capture cache and stale renders. Fonts are tiny hand-made sfnt / WOFF2 files (cmap + name only).
import { afterAll, describe, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { brotliCompressSync } from 'node:zlib';
import { fontCodepoints, fontFamilyName } from '../cli/shots/cmap';
import { type FaceJob, fontIssues, fontsCss, fontUsage, type FontManifest, GlyphError, planFonts } from '../cli/shots/glyphs';
import { langTexts } from '../cli/shots/fonts';
import { faceFilePath, fontsRoute, loadLocalFont, localByFamily, localFontIssues, resolveShotFonts, staleLocalFonts } from '../cli/shots/local-fonts';
import { planWeb } from '../cli/shots/capture-web';
import { validateConfig } from '../cli/lib/config';
// ---- minimal font writer: an sfnt (or WOFF2) with a format 12 cmap and a name table ----
function cmapBytes(cps: number[]): Uint8Array {
const sorted = [...new Set(cps)].sort((a, b) => a - b);
const len = 16 + sorted.length * 12;
const b = new DataView(new ArrayBuffer(12 + len));
b.setUint16(2, 1); b.setUint16(4, 3); b.setUint16(6, 10); b.setUint32(8, 12);
b.setUint16(12, 12); b.setUint32(16, len); b.setUint32(24, sorted.length);
sorted.forEach((c, i) => { b.setUint32(28 + i * 12, c); b.setUint32(32 + i * 12, c); b.setUint32(36 + i * 12, i + 1); });
return new Uint8Array(b.buffer);
}
function nameBytes(family: string): Uint8Array {
const str = new Uint8Array(family.length * 2);
[...family].forEach((c, i) => { str[i * 2] = 0; str[i * 2 + 1] = c.charCodeAt(0); });
const b = new DataView(new ArrayBuffer(6 + 12 + str.length));
b.setUint16(2, 1); b.setUint16(4, 18);
b.setUint16(6, 3); b.setUint16(8, 1); b.setUint16(10, 0x409); b.setUint16(12, 1); b.setUint16(14, str.length); b.setUint16(16, 0);
new Uint8Array(b.buffer).set(str, 18);
return new Uint8Array(b.buffer);
}
function sfnt(cps: number[], family: string, sig = 0x00010000): Uint8Array {
const tables: [string, Uint8Array][] = [['cmap', cmapBytes(cps)], ['name', nameBytes(family)]];
let off = 12 + tables.length * 16;
const out = new Uint8Array(off + tables.reduce((n, [, t]) => n + t.length, 0));
const d = new DataView(out.buffer);
d.setUint32(0, sig); d.setUint16(4, tables.length);
tables.forEach(([tag, t], i) => {
out.set([...tag].map(c => c.charCodeAt(0)), 12 + i * 16);
d.setUint32(12 + i * 16 + 8, off); d.setUint32(12 + i * 16 + 12, t.length);
out.set(t, off); off += t.length;
});
return out;
}
function woff2(cps: number[], family: string): Uint8Array {
const cmap = cmapBytes(cps), name = nameBytes(family);
const stream = new Uint8Array(brotliCompressSync(Buffer.concat([cmap, name])));
const b128 = (n: number): number[] => { const b = [n & 0x7f]; n = Math.floor(n / 128); while (n) { b.unshift(0x80 | (n & 0x7f)); n = Math.floor(n / 128); } return b; };
const dir = [0, ...b128(cmap.length), 5, ...b128(name.length)]; // known-table indices: 0 = cmap, 5 = name
const out = new Uint8Array(48 + dir.length + stream.length);
const d = new DataView(out.buffer);
out.set([...'wOF2'].map(c => c.charCodeAt(0)), 0); d.setUint32(4, 0x00010000); d.setUint32(8, out.length);
d.setUint16(12, 2); d.setUint32(20, stream.length);
out.set(dir, 48); out.set(stream, 48 + dir.length);
return out;
}
const range = (a: number, b: number): number[] => Array.from({ length: b - a + 1 }, (_, i) => a + i);
const cpsOf = (s: string): number[] => [...s].map(c => c.codePointAt(0)!);
// "ER Display": ASCII, Latin-1 and Latin Extended-A without ą ę Ł ł; no Vietnamese (ơ ư, U+1EA0..)
const ER = [...range(0x20, 0x7e), ...range(0xa0, 0xff), ...range(0x100, 0x17f).filter(c => ![0x105, 0x119, 0x141, 0x142].includes(c))];
const root = mkdtempSync(join(tmpdir(), 'sb-localfonts-'));
afterAll(() => rmSync(root, { recursive: true, force: true }));
const fontsDir = join(root, '.storebound', 'fonts');
mkdirSync(join(root, 'assets', 'fonts'), { recursive: true });
mkdirSync(fontsDir, { recursive: true });
writeFileSync(join(root, 'assets/fonts/er-display.woff2'), woff2(ER, 'ER Display'));
writeFileSync(join(root, 'assets/fonts/er-pl.ttf'), sfnt([0x105, 0x119, 0x141, 0x142], 'ER Polish'));
const resolve = (p: string): string => join(root, p);
describe('local font files: config and validation', () => {
test('a path reads the family from the name table (WOFF2 and TTF); the object form sets family, weight, license', () => {
expect(fontFamilyName(woff2(ER, 'ER Display'))).toBe('ER Display');
const a = loadLocalFont('assets/fonts/er-display.woff2', 'shots.fonts.title', resolve, root);
expect(a.family).toBe('ER Display');
expect(a.local).toMatchObject({ path: 'assets/fonts/er-display.woff2', format: 'woff2' });
expect(a.local!.hash).toMatch(/^[0-9a-f]{16}$/);
const b = loadLocalFont({ family: 'ER Pl', file: 'assets/fonts/er-pl.ttf', weight: 800, license: 'OFL-1.1' }, 'k', resolve, root);
expect(b).toMatchObject({ family: 'ER Pl', local: { format: 'truetype', weight: '800', license: 'OFL-1.1' } });
expect(fontCodepoints(readFileSync(join(root, 'assets/fonts/er-display.woff2'))).size).toBe(ER.length);
});
test('missing file, wrong extension, not a font, mismatched format', () => {
writeFileSync(join(root, 'assets/fonts/bad.ttf'), new Uint8Array(64));
writeFileSync(join(root, 'assets/fonts/fake.ttf'), woff2(ER, 'X'));
expect(() => loadLocalFont('assets/fonts/nope.ttf', 'shots.fonts.title', resolve, root)).toThrow('shots.fonts.title: assets/fonts/nope.ttf not found');
expect(() => loadLocalFont({ file: 'assets/fonts/er.svg' }, 'k', resolve, root)).toThrow('not a font file (TTF, OTF, WOFF or WOFF2)');
expect(() => loadLocalFont('assets/fonts/bad.ttf', 'k', resolve, root)).toThrow('unknown signature');
expect(() => loadLocalFont('assets/fonts/fake.ttf', 'k', resolve, root)).toThrow('is WOFF2 inside, but named .ttf');
});
test('validateConfig: font entry shapes', () => {
const base = { app: { name: 'X', privacyPolicyUrl: 'https://example.com/p', supportUrl: 'https://example.com', website: 'https://example.com', contactEmail: 'a@example.com' }, languages: [{ id: 'en' }] };
const shots = (fonts: unknown) => ({ ...base, shots: { copy: 'c.json', frames: 'f', out: 'o', scenes: [{ id: 'a', palette: 'fire', frames: [{ src: 'a' }] }], fonts } });
expect(validateConfig(shots({ title: 'assets/er.woff2', body: 'Montserrat', fallback: [{ family: 'ER Pl', file: 'a/er-pl.ttf', license: 'OFL-1.1' }, 'Noto Sans Display'] }))).toEqual([]);
const errs = validateConfig(shots({ title: 'assets/er.svg', body: { family: 'B' }, fallback: [{ file: 'x.otf', style: 'oblique', weight: 'bold' }] }));
expect(errs).toEqual([
'shots.fonts.title: assets/er.svg: a font file must be TTF, OTF, WOFF or WOFF2',
'shots.fonts.body: a Google Fonts family, a font file path or { family, file, weight?, style?, license? }',
'shots.fonts.fallback[0].style: normal | italic',
'shots.fonts.fallback[0].weight: e.g. 400, 800 or "100 900"',
]);
});
});
// Copy: ER Display covers tr / de / fr titles; Polish needs ą ę Ł ł, Vietnamese needs ơ ư ạ ...
const COPY = {
tr: { s1: { title: ["Taş Devri'nden", 'İleri!'] as [string, string], sub: 'Kasabaları yağmala' } },
de: { s1: { title: ['Größer', 'schöner'] as [string, string] } },
pl: { s1: { title: ['Gęsi łąka', 'Łódź'] as [string, string], sub: 'Szybka gra' } },
vi: { s1: { title: ['Chiến đấu', 'Thế giới'] as [string, string], sub: 'Trận nhanh' } },
};
const NOTO: Record<string, (cp: number) => boolean> = {
Montserrat: () => true, // body: covers everything here
'Noto Sans Display': cp => cp < 0x250 || (cp >= 0x1ea0 && cp <= 0x1ef9),
};
/** Getter like `shots fonts`: local files read in place, Google families faked. */
function getter(asked: FaceJob[]): (job: FaceJob) => Promise<Set<number>> {
return async job => {
asked.push(job);
if (job.local) return fontCodepoints(readFileSync(join(root, job.local.path)));
const f = NOTO[job.family] ?? (() => false);
return new Set(cpsOf(job.chars).filter(f));
};
}
async function plan(fallback: (string | { family?: string; file: string; license?: string })[] = [], asked: FaceJob[] = []): Promise<FontManifest> {
const sf = resolveShotFonts({ fonts: { title: 'assets/fonts/er-display.woff2', body: 'Montserrat', fallback } }, 'game', resolve, root);
return planFonts({ langs: langTexts(COPY, [], 'STAR DASH'), title: sf.title.family, body: sf.body.family, titleAxis: null, bodyAxis: 'wght@100..900',
fallbackTitleAxis: 'wght@800', chosen: sf.fallback.map(f => f.family), local: localByFamily([sf.title, sf.body, ...sf.fallback]) }, getter(asked));
}
const fb = (m: FontManifest, lang: string) => m.langs[lang]!.fallbacks.filter(f => f.role === 'title').map(f => `${f.family}:${[...f.chars].join(' ')}`);
describe('coverage of a local title font', () => {
test('pl / vi titles: the characters ER Display lacks go to Noto Sans Display (automatic); tr / de need nothing', async () => {
const asked: FaceJob[] = [];
const m = await plan([], asked);
expect(fb(m, 'pl')).toEqual(['Noto Sans Display:ę ł ą Ł']);
expect(fb(m, 'vi')).toEqual(['Noto Sans Display:ế ấ ớ']);
for (const l of ['tr', 'de']) expect(m.langs[l]!.fallbacks).toEqual([]);
expect(m.faces['ER Display']).toMatchObject({ family: 'ER Display', kind: 'title', chosen: true, file: 'local/er-display.woff2', local: { path: 'assets/fonts/er-display.woff2', format: 'woff2' } });
expect(m.faces['Store fb noto-sans-display title']!.chosen).toBe(false);
expect(asked.find(j => j.family === 'ER Display')!.local).toBeDefined(); // read in place, not downloaded
});
test('listed fallbacks first (a local file), then Noto; chosen, so check passes', async () => {
const m = await plan([{ file: 'assets/fonts/er-pl.ttf', license: 'OFL-1.1' }, 'Noto Sans Display']);
expect(fb(m, 'pl')).toEqual(['ER Polish:ę ł ą Ł']);
expect(fb(m, 'vi')).toEqual(['Noto Sans Display:ế ấ ớ']);
expect(m.langs.pl!.title).toEqual(['ER Display', 'Store fb er-polish title']);
expect(m.faces['Store fb er-polish title']).toMatchObject({ kind: 'fallback', chosen: true, file: 'local/er-polish.ttf', local: { license: 'OFL-1.1' } });
expect(m.faces['Store fb noto-sans-display title']!.chosen).toBe(true);
});
test('nothing covers it: GlyphError names the local font and the fallbacks tried', async () => {
const err = await planFonts({ langs: langTexts({ pl: { s1: { title: ['ą', 'x'] } } }, [], ''), title: 'ER Display', body: 'Montserrat', titleAxis: null, bodyAxis: null,
fallbackTitleAxis: null, local: localByFamily([loadLocalFont('assets/fonts/er-display.woff2', 'k', resolve, root)]) },
async job => job.local ? fontCodepoints(readFileSync(join(root, job.local.path))) : new Set()).catch(e => e);
expect(err).toBeInstanceOf(GlyphError);
expect(err.message).toContain('pl (title): "ą" U+0105; tried ER Display, Noto Sans Display, Noto Sans');
});
});
describe('render and check with a local font', () => {
test('fonts.css: @font-face for the local file, served in place at /fonts/local/... with its hash', async () => {
const m = await plan([{ file: 'assets/fonts/er-pl.ttf', license: 'OFL-1.1' }]);
const css = fontsCss(m);
const h = m.faces['ER Display']!.local!.hash;
expect(css).toContain(`@font-face { font-family: 'ER Display'; font-weight: 100 900; font-style: normal; font-synthesis: none; src: url(local/er-display.woff2?v=${h}) format('woff2'); }`);
expect(css).toContain("src: url(local/er-polish.ttf?v=");
expect(css).toContain("format('truetype')");
expect(css).toContain('/* ER Polish: local file assets/fonts/er-pl.ttf (license: OFL-1.1) */');
expect(fontsRoute(`local/er-display.woff2?v=${h}`, fontsDir, root, m)).toBe(join(root, 'assets/fonts/er-display.woff2'));
expect(fontsRoute('local/other.ttf', fontsDir, root, m)).toBeNull();
expect(fontsRoute('local/../../x.ttf', fontsDir, root, m)).toBeNull();
expect(fontsRoute('fb-noto-sans-display-title.woff2', fontsDir, root, m)).toBe(join(fontsDir, 'fb-noto-sans-display-title.woff2'));
expect(faceFilePath(fontsDir, root, m.faces['ER Display']!)).toBe(join(root, 'assets/fonts/er-display.woff2'));
// nothing is copied into .storebound/fonts
expect(Object.values(m.faces).filter(f => f.local).every(f => f.file.startsWith('local/'))).toBe(true);
});
test('check: the local font and the listed fallback are not fallbacks the config did not choose; an automatic Noto is', async () => {
const m = await plan([{ file: 'assets/fonts/er-pl.ttf' }]);
const ok = fontUsage([
{ el: 'h1 span:1', text: 'Gęsi łąka', faces: { 'ER Display': 'Gsika', 'Store fb er-polish title': 'ęłą' } },
{ el: 'p.sub', text: 'Szybka gra', faces: { Montserrat: 'Szybkagr' } },
], m.faces);
expect(ok.used).toEqual({ 'ER Display': 5, 'ER Polish': 3, Montserrat: 8 });
expect(fontIssues(ok)).toEqual([]);
const bad = fontUsage([{ el: 'h1 span:1', text: 'Chiến', faces: { 'ER Display': 'Chin', 'Store fb noto-sans-display title': 'ế' } }], m.faces);
expect(fontIssues(bad).map(i => i.code)).toEqual(['font-fallback']);
// license note: warn for the local file without one
expect(localFontIssues(m).map(i => i.msg.split(' has')[0])).toEqual(['local font ER Display (assets/fonts/er-display.woff2)', 'local font ER Polish (assets/fonts/er-pl.ttf)']);
const licensed = await plan([{ file: 'assets/fonts/er-pl.ttf', license: 'proprietary' }]);
expect(localFontIssues(licensed).length).toBe(1);
});
test('a changed font file changes the content hash: capture cache misses, render refuses the stale fonts.json', async () => {
const m1 = await plan();
const cap = { source: 'web' as const, baseUrl: 'http://x', shots: { a: { path: '/a' } } };
const dims = { phone: { w: 10, h: 20, dpr: 1, bar: 0 }, tablet: { w: 10, h: 20, dpr: 1, bar: 0 } };
const job = (m: FontManifest) => planWeb(cap, { langs: ['tr'], devices: ['phone'], only: [], dims, framesDir: '/f', build: 'b', fonts: fontsCss(m) })[0]!.hash;
expect(staleLocalFonts(m1, root)).toEqual([]);
writeFileSync(join(root, 'assets/fonts/er-display.woff2'), woff2([...ER, 0x105], 'ER Display'));
try {
expect(staleLocalFonts(m1, root)).toEqual(['ER Display: assets/fonts/er-display.woff2 changed']);
const m2 = await plan();
expect(m2.faces['ER Display']!.local!.hash).not.toBe(m1.faces['ER Display']!.local!.hash);
expect(job(m2)).not.toBe(job(m1));
expect(fb(m2, 'pl')).toEqual(['Noto Sans Display:ę ł Ł']); // ą now in the font
} finally { writeFileSync(join(root, 'assets/fonts/er-display.woff2'), woff2(ER, 'ER Display')); }
});
});

View file

@ -154,6 +154,8 @@ describe('IAP review submission plan', () => {
{ method: 'POST', match: /^\/v1\/reviewSubmissions$/, answer: { data: { type: 'reviewSubmissions', id: 'rs-new', attributes: { state: 'READY_FOR_REVIEW' } } } },
{ method: 'POST', match: /^\/v1\/reviewSubmissionItems$/, answer: { data: { type: 'reviewSubmissionItems', id: 'it-1' } } },
{ method: 'PATCH', match: /^\/v1\/reviewSubmissions\/rs-new$/, answer: { data: { type: 'reviewSubmissions', id: 'rs-new', attributes: { state: 'WAITING_FOR_REVIEW' } } } },
// the journal of recent creates (.storebound/created.json) names rs-new: read by id, it was submitted, so a new draft is made
{ match: /^\/v1\/reviewSubmissions\/rs-new$/, answer: { data: { type: 'reviewSubmissions', id: 'rs-new', attributes: { state: 'WAITING_FOR_REVIEW' } } } },
]);
let calls = routes();
let r = await capture(() => iapSubmit(p.ctx(['--dry', '--json'])));