Merge remote-tracking branch 'origin/main' into apple-name

# Conflicts:
#	CHANGELOG.md
This commit is contained in:
CRTkafa 2026-10-11 19:29:53 +00:00
commit 953a7c5489
25 changed files with 951 additions and 82 deletions

View file

@ -1,35 +1,95 @@
// Upload the App Review screenshot of every in-app purchase (idempotent: a screenshot whose MD5 matches is kept) and
// print each product's state. Nothing is submitted.
// Upload the App Review screenshot of every in-app purchase (idempotent: a screenshot whose MD5 matches and that
// Apple processed is kept) and print each product's state with what is still missing. Nothing is submitted.
// storebound apple iap-review [--dry]
// Screenshot per product: products[].reviewScreenshot, else apple.reviewShots/<product id>.(png|jpg).
// Size: a real device screenshot size (e.g. 1290 x 2796); other sizes fail with IMAGE_INCORRECT_DIMENSIONS.
// Size: an App Store screenshot size (iPhone or iPad, e.g. 1320 x 2868 or 1290 x 2796); Apple processes the upload
// after it is committed and fails other sizes with IMAGE_INCORRECT_DIMENSIONS, so the size is checked before the
// upload and the delivery state is read back after it (an upload is only "done" when Apple says COMPLETE).
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { join, relative } from 'node:path';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { done, log, warn } from '../lib/log';
import { IMAGE_SPECS, imageInfo } from '../shots/spec';
import { ascClient, md5 } from './asc';
/** Every iPhone / iPad screenshot size App Store Connect accepts (portrait and landscape). */
export const REVIEW_SHOT_SIZES: [number, number][] = Object.values(IMAGE_SPECS)
.filter(s => s.store === 'apple' && /^APP_(IPHONE|IPAD)/.test(s.type))
.flatMap(s => s.sizes.flatMap(([w, h]) => [[w, h], [h, w]] as [number, number][]));
/** null when the image can be used as an App Review screenshot, else why not. Pure. */
export function reviewShotProblem(buf: Uint8Array): string | null {
const i = imageInfo(buf);
if (i.format === 'unknown') return 'not a PNG or JPEG';
if (!REVIEW_SHOT_SIZES.some(([w, h]) => w === i.w && h === i.h))
return `${i.w} x ${i.h} is not an App Store screenshot size (use e.g. 1320 x 2868 or 1290 x 2796 for iPhone, 2064 x 2752 for iPad; Apple fails other sizes with IMAGE_INCORRECT_DIMENSIONS)`;
return null;
}
type Shot = { id: string; attributes: { sourceFileChecksum?: string; fileName?: string; assetDeliveryState?: { state?: string; errors?: { code?: string; description?: string }[] } } };
const stateOf = (s: Shot | undefined): string => s?.attributes.assetDeliveryState?.state ?? 'NONE';
const errorsOf = (s: Shot | undefined): string => (s?.attributes.assetDeliveryState?.errors ?? []).map(e => e.code ?? e.description).filter(Boolean).join(', ');
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const dry = ctx.args.has('dry');
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
const appId = await c.app();
const defs = new Map((config.products ?? []).map(p => [p.id, p]));
for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)) {
const shotOf = (id: string) => c.maybe(`/v2/inAppPurchases/${id}/appStoreReviewScreenshot`).then(r => r?.data as Shot | undefined);
const iaps = await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`);
const seen = new Set(iaps.map((p: any) => p.attributes.productId));
const missingInStore = [...defs.keys()].filter(id => !seen.has(id));
if (missingInStore.length)
warn('apple', `not in App Store Connect yet: ${missingInStore.join(', ')} (created moments ago? the store's list can lag a minute; run again)`);
let problems = 0;
for (const p of iaps) {
const sku: string = p.attributes.productId;
const def = defs.get(sku);
const file = def?.reviewScreenshot ? resolve(def.reviewScreenshot)
: ['png', 'jpg', 'jpeg'].map(e => resolve(join(config.apple?.reviewShots ?? 'store/iap-review', `${sku}.${e}`))).find(existsSync);
if (!file || !existsSync(file)) { warn('apple', `${sku}: no review screenshot (set products[].reviewScreenshot)`); continue; }
if (!file || !existsSync(file)) { warn('apple', `${sku}: no review screenshot (set products[].reviewScreenshot)`); problems++; continue; }
const buf = readFileSync(file);
const cur = (await c.maybe(`/v2/inAppPurchases/${p.id}/appStoreReviewScreenshot`))?.data;
if (cur && cur.attributes.sourceFileChecksum === md5(buf) && cur.attributes.assetDeliveryState?.state !== 'FAILED') { log('apple', `${sku}: screenshot up to date`); continue; }
if (ctx.args.has('dry')) { log('apple', `${sku}: would upload ${file}`); continue; }
const bad = reviewShotProblem(buf);
const cur = await shotOf(p.id);
const curState = stateOf(cur);
if (bad) {
warn('apple', `${sku}: ${relative(root, file)}: ${bad}${cur ? `; App Store Connect has ${curState}${errorsOf(cur) ? ` (${errorsOf(cur)})` : ''}` : ''}`);
problems++; continue;
}
if (cur && cur.attributes.sourceFileChecksum === md5(buf) && curState !== 'FAILED') { log('apple', `${sku}: screenshot up to date (${curState})`); continue; }
const why = !cur ? 'none in App Store Connect' : curState === 'FAILED' ? `the one there FAILED${errorsOf(cur) ? ` (${errorsOf(cur)})` : ''}` : 'a different file is there';
if (dry) { log('apple', `${sku}: would upload ${relative(root, file)} (${why})`); continue; }
if (cur) await c.asc('DELETE', `/v1/inAppPurchaseAppStoreReviewScreenshots/${cur.id}`);
await c.uploadAsset('inAppPurchaseAppStoreReviewScreenshots', { inAppPurchaseV2: { data: { type: 'inAppPurchases', id: p.id } } }, file);
log('apple', `${sku}: screenshot uploaded`);
// Apple processes the asset after the commit: read the state back (COMPLETE, or FAILED with the reason)
let after: Shot | undefined, state = 'UPLOAD_COMPLETE';
for (let i = 0; i < 10; i++) {
await Bun.sleep(i ? 3000 : 1500);
after = await shotOf(p.id); state = stateOf(after);
if (state === 'COMPLETE' || state === 'FAILED') break;
}
if (state === 'FAILED') { warn('apple', `${sku}: Apple rejected the screenshot: ${errorsOf(after) || 'FAILED'}`); problems++; }
else log('apple', `${sku}: screenshot uploaded (${state})`);
}
await Bun.sleep(3000);
for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)) log('apple', `${p.attributes.productId}: ${p.attributes.state}`);
done('apple', 'iap-review done (READY_TO_SUBMIT = complete; first IAPs go to review with a version, from the IAP page)');
// what keeps a product in MISSING_METADATA (Apple's rule: a localization, a price, availability and the screenshot)
for (const p of await c.all(`/v1/apps/${appId}/inAppPurchasesV2?limit=200`)) {
const state: string = p.attributes.state;
if (state !== 'MISSING_METADATA') { log('apple', `${p.attributes.productId}: ${state}`); continue; }
const lack: string[] = [];
const locs = await c.maybe(`/v2/inAppPurchases/${p.id}/inAppPurchaseLocalizations?limit=50`);
if (!locs?.data?.length) lack.push('a localization (name + description)');
const price = await c.maybe(`/v2/inAppPurchases/${p.id}/iapPriceSchedule`);
if (!price?.data) lack.push('a price');
const avail = await c.maybe(`/v2/inAppPurchases/${p.id}/inAppPurchaseAvailability`);
if (!avail?.data) lack.push('availability (territories)');
const shot = await shotOf(p.id);
if (!shot) lack.push('the review screenshot');
else if (stateOf(shot) === 'FAILED') lack.push(`a working review screenshot (FAILED: ${errorsOf(shot) || 'unknown'})`);
else if (stateOf(shot) !== 'COMPLETE') lack.push(`Apple to finish processing the screenshot (${stateOf(shot)}; check again in a minute)`);
log('apple', `${p.attributes.productId}: MISSING_METADATA${lack.length ? `: needs ${lack.join(', ')}` : ' (all parts present: Apple may still be updating the state)'}`);
}
if (problems) process.exitCode = 1;
done('apple', dry ? 'iap-review dry run (nothing uploaded)' : 'iap-review done (READY_TO_SUBMIT = complete; first IAPs go to review with a version, from the IAP page)');
}

View file

@ -14,6 +14,7 @@ import { dataSafetyRows } from './lib/data-safety';
import { reviewDemoAccount } from './lib/credentials';
import { log, printJson, warn } from './lib/log';
import { profileIssues } from './lib/profile';
import { reviewShotProblem } from './apple/iap-review';
import { allSubscriptions } from './lib/subscriptions';
import { type CopyFile, validateCopy } from './shots/lib';
@ -82,6 +83,13 @@ export async function run(ctx: Ctx): Promise<void> {
if (config.apple && len(l.description) > APPLE_IAP_LIMITS.description) problems.push(`product ${p.id} ${lang}: description ${len(l.description)} > ${APPLE_IAP_LIMITS.description} (App Store limit)`);
if (len(l.description) > 200) problems.push(`product ${p.id} ${lang}: description ${len(l.description)} > 200 (Play limit)`);
}
// App Review screenshots of in-app purchases: Apple fails any non-screenshot size after upload (IMAGE_INCORRECT_DIMENSIONS)
if (config.apple) for (const f of new Set((config.products ?? []).map(p => p.reviewScreenshot).filter((x): x is string => !!x))) {
const file = resolve(f);
if (!existsSync(file)) continue; // reported with the other missing files below
const bad = reviewShotProblem(readFileSync(file));
if (bad) problems.push(`products[].reviewScreenshot ${f}: ${bad}`);
}
if (config.shots) tryDo('shots copy', () => {
const copy = JSON.parse(readFileSync(resolve(config.shots!.copy), 'utf8')) as CopyFile;
const e = validateCopy(copy, config.shots!, config.languages.map(l => l.id));

View file

@ -113,8 +113,11 @@ export interface ShotsConfig {
out: string;
/** Optional logo image for the hero scene and the feature graphic. */
logo?: string;
/** Google Fonts families for titles / body text (downloaded and subset by `shots fonts`). */
fonts?: { title?: string; body?: string };
/** Google Fonts families for titles / body text (downloaded and subset by `shots fonts`). Default: game Paytone One +
* Montserrat, app Inter (all cover Latin Extended and Vietnamese). `fallback`: Noto families you accept for
* characters the title / body font lacks (e.g. ['Noto Sans Display']); without it a render that needs an automatic
* fallback is an ERROR in `shots check`. */
fonts?: { title?: string; body?: string; fallback?: string[] };
scenes: ShotScene[];
feature?: { frame: string; palette?: string | Palette };
/** Phone screen size of the raw frames in CSS px (default 440 x 902 @3x, iPhone 6.9" minus the 54 px status bar).

View file

@ -28,7 +28,7 @@ document.documentElement.lang = LANG;
R.setProperty('--W', W + 'px'); R.setProperty('--H', H + 'px'); R.setProperty('--u', u + 'px');
R.setProperty('--ink', job.ink); R.setProperty('--fs', W > H ? 6.4 : 8.2);
const X = job.fonts.script;
R.setProperty('--tf', X ? `'${X}', '${job.fonts.title}', sans-serif` : `'${job.fonts.title}', sans-serif`);
R.setProperty('--tf', (job.fonts.titleStack ?? (X ? [X, job.fonts.title] : [job.fonts.title])).map(f => `'${f}'`).join(', ') + ', sans-serif');
R.setProperty('--tw', X ? 900 : 400);
const el = document.createElement('div');
el.className = 'cap';

125
cli/shots/cmap.ts Normal file
View file

@ -0,0 +1,125 @@
// Character coverage of a font file, read from its cmap table in pure TypeScript (no font library):
// TrueType / OpenType (sfnt), TrueType collections (first font), WOFF 1 (zlib) and WOFF 2 (brotli, cmap is never
// transformed so it is read straight from the decompressed stream). node:zlib ships with Bun, so no dependency.
// cmap subtables: formats 0, 4, 6, 12 and 13 of the Unicode / Windows Unicode encodings.
import { brotliDecompressSync, inflateSync } from 'node:zlib';
const tag = (d: DataView, o: number): string => String.fromCharCode(d.getUint8(o), d.getUint8(o + 1), d.getUint8(o + 2), d.getUint8(o + 3));
const view = (b: Uint8Array): DataView => new DataView(b.buffer, b.byteOffset, b.byteLength);
/** The raw cmap table of a font file (any of the formats above). Throws on anything else. */
export function cmapTable(file: Uint8Array): Uint8Array {
const d = view(file);
const sig = tag(d, 0);
if (sig === 'wOF2') return woff2Cmap(file);
if (sig === 'wOFF') {
const n = d.getUint16(12);
for (let i = 0; i < n; i++) {
const o = 44 + i * 20;
if (tag(d, o) !== 'cmap') continue;
const off = d.getUint32(o + 4), comp = d.getUint32(o + 8), orig = d.getUint32(o + 12);
const raw = file.subarray(off, off + comp);
return comp < orig ? new Uint8Array(inflateSync(raw)) : raw;
}
throw new Error('woff: no cmap table');
}
let base = 0;
if (sig === 'ttcf') base = d.getUint32(12);
else if (!(d.getUint32(0) === 0x00010000 || sig === 'OTTO' || sig === 'true')) throw new Error(`not a font file (signature ${JSON.stringify(sig)})`);
const n = d.getUint16(base + 4);
for (let i = 0; i < n; i++) {
const o = base + 12 + i * 16;
if (tag(d, o) === 'cmap') { const off = d.getUint32(o + 8); return file.subarray(off, off + d.getUint32(o + 12)); }
}
throw new Error('sfnt: no cmap table');
}
const WOFF2_TAGS = ['cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'post', 'cvt ', 'fpgm', 'glyf', 'loca', 'prep', 'CFF ', 'VORG',
'EBDT', 'EBLC', 'gasp', 'hdmx', 'kern', 'LTSH', 'PCLT', 'VDMX', 'vhea', 'vmtx', 'BASE', 'GDEF', 'GPOS', 'GSUB', 'EBSC', 'JSTF', 'MATH',
'CBDT', 'CBLC', 'COLR', 'CPAL', 'SVG ', 'sbix', 'acnt', 'avar', 'bdat', 'bloc', 'bsln', 'cvar', 'fdsc', 'feat', 'fmtx', 'fvar', 'gvar',
'hsty', 'just', 'lcar', 'mort', 'morx', 'opbd', 'prop', 'trak', 'Zapf', 'Silf', 'Glat', 'Gloc', 'Feat', 'Sill'];
function woff2Cmap(file: Uint8Array): Uint8Array {
const d = view(file);
const n = d.getUint16(12), compLen = d.getUint32(20);
let p = 48;
const base128 = (): number => {
let v = 0;
for (let i = 0; i < 5; i++) { const b = d.getUint8(p++); v = v * 128 + (b & 0x7f); if (!(b & 0x80)) return v; }
throw new Error('woff2: bad UIntBase128');
};
let off = 0, found: [number, number] | null = null;
for (let i = 0; i < n; i++) {
const flags = d.getUint8(p++);
const t = (flags & 0x3f) === 63 ? (p += 4, tag(d, p - 4)) : WOFF2_TAGS[flags & 0x3f]!;
const orig = base128();
const version = (flags >> 6) & 3;
const transformed = t === 'glyf' || t === 'loca' ? version === 0 : version !== 0;
const len = transformed ? base128() : orig;
if (t === 'cmap') found = [off, orig];
off += len;
}
if (!found) throw new Error('woff2: no cmap table');
if (tag(d, 4) === 'ttcf') { // collection directory: skip it (version, numFonts 255UInt16, per font numTables + indices)
p += 4;
const u16 = (): number => { const c = d.getUint8(p++); return c === 253 ? (p += 2, d.getUint16(p - 2)) : c === 255 ? 253 + d.getUint8(p++) : c === 254 ? 506 + d.getUint8(p++) : c; };
const fonts = u16();
for (let f = 0; f < fonts; f++) { const k = u16(); p += 4; for (let j = 0; j < k; j++) u16(); }
}
const data = new Uint8Array(brotliDecompressSync(file.subarray(p, p + compLen)));
return data.subarray(found[0], found[0] + found[1]);
}
/** Every Unicode code point the cmap maps to a real glyph (glyph id > 0). */
export function cmapCodepoints(cmap: Uint8Array): Set<number> {
const d = view(cmap);
const n = d.getUint16(2);
const subs: { pid: number; eid: number; off: number }[] = [];
for (let i = 0; i < n; i++) subs.push({ pid: d.getUint16(4 + i * 8), eid: d.getUint16(6 + i * 8), off: d.getUint32(8 + i * 8) });
const rank = (s: { pid: number; eid: number }): number => (s.pid === 3 && s.eid === 10) || (s.pid === 0 && (s.eid === 4 || s.eid === 6)) ? 3
: (s.pid === 3 && s.eid === 1) || (s.pid === 0 && s.eid <= 3) ? 2 : s.pid === 3 && s.eid === 0 ? 1 : 0;
const out = new Set<number>();
for (const s of subs.filter(x => rank(x) > 0).sort((a, b) => rank(b) - rank(a))) readSub(d, s.off, out);
return out;
}
function readSub(d: DataView, o: number, out: Set<number>): void {
const fmt = d.getUint16(o);
if (fmt === 0) { for (let c = 0; c < 256; c++) if (d.getUint8(o + 6 + c)) out.add(c); return; }
if (fmt === 6) { const first = d.getUint16(o + 6), cnt = d.getUint16(o + 8); for (let i = 0; i < cnt; i++) if (d.getUint16(o + 10 + i * 2)) out.add(first + i); return; }
if (fmt === 4) {
const segs = d.getUint16(o + 6) / 2;
const ends = o + 14, starts = ends + segs * 2 + 2, deltas = starts + segs * 2, ranges = deltas + segs * 2;
for (let i = 0; i < segs; i++) {
const end = d.getUint16(ends + i * 2), start = d.getUint16(starts + i * 2), delta = d.getInt16(deltas + i * 2), ro = d.getUint16(ranges + i * 2);
for (let c = start; c <= end && c !== 0xffff; c++) {
let g: number;
if (!ro) g = (c + delta) & 0xffff;
else { g = d.getUint16(ranges + i * 2 + ro + (c - start) * 2); if (g) g = (g + delta) & 0xffff; }
if (g) out.add(c);
}
}
return;
}
if (fmt === 12 || fmt === 13) {
const groups = d.getUint32(o + 12);
for (let i = 0; i < groups; i++) {
const g = o + 16 + i * 12, start = d.getUint32(g), end = d.getUint32(g + 4), gid = d.getUint32(g + 8);
for (let c = start; c <= end && c <= 0x10ffff; c++) if (fmt === 13 ? gid : gid + (c - start)) out.add(c);
}
}
}
/** Code points a font file covers. */
export const fontCodepoints = (file: Uint8Array): Set<number> => cmapCodepoints(cmapTable(file));
/** Characters that need a glyph: everything except whitespace, controls, joiners and variation selectors (those
* render without one or are handled by shaping). */
export const needsGlyph = (ch: string): boolean => !/^[\s\p{Cc}\p{Cf}\u{FE00}-\u{FE0F}\u{E0100}-\u{E01EF}]$/u.test(ch);
/** Characters of `text` (unique, in first-seen order) a font with `cps` does not cover. */
export function missingChars(text: string, cps: Set<number>): string[] {
const out = new Set<string>();
for (const ch of text) if (needsGlyph(ch) && !cps.has(ch.codePointAt(0)!)) out.add(ch);
return [...out];
}

View file

@ -36,7 +36,7 @@ const P = job.palette, R = document.documentElement.style, dev = job.phone;
const rgba = (hex, a) => { const m = /^#?([0-9a-f]{6})$/i.exec(hex); if (!m) return hex; const n = parseInt(m[1], 16); return `rgba(${n >> 16},${(n >> 8) & 255},${n & 255},${a})`; };
R.setProperty('--bg', `linear-gradient(135deg, ${P.bg[0]} 0%, ${P.bg[1]} 55%, ${P.bg[2]} 100%)`);
R.setProperty('--ink', P.ink); R.setProperty('--shadow', P.shadow); R.setProperty('--accentSoft', rgba(P.glow, .18));
R.setProperty('--tf', `'${job.fonts.title}', sans-serif`);
R.setProperty('--tf', (job.fonts.titleStack ?? [job.fonts.title]).map(f => `'${f}'`).join(', ') + ', sans-serif');
R.setProperty('--ar', `${dev.w} / ${dev.h + dev.bar}`);
R.setProperty('--appH', `${100 * dev.h / (dev.h + dev.bar)}%`);
R.setProperty('--barH', `${100 * dev.bar / (dev.h + dev.bar)}%`);

View file

@ -44,7 +44,7 @@ const job = await (await fetch(`/job.json?lang=${encodeURIComponent(lang)}&featu
const P = job.palette, R = document.documentElement.style, dev = job.phone;
R.setProperty('--bg', `linear-gradient(160deg, ${P.bg[0]} 0%, ${P.bg[1]} 50%, ${P.bg[2]} 100%)`);
R.setProperty('--glow', P.glow); R.setProperty('--ink', P.ink); R.setProperty('--shadow', P.shadow);
R.setProperty('--tf', `'${job.fonts.title}', sans-serif`);
R.setProperty('--tf', (job.fonts.titleStack ?? [job.fonts.title]).map(f => `'${f}'`).join(', ') + ', sans-serif');
R.setProperty('--ar', `${dev.w} / ${dev.h + dev.bar}`);
R.setProperty('--appH', `${100 * dev.h / (dev.h + dev.bar)}%`);
R.setProperty('--barH', `${100 * dev.bar / (dev.h + dev.bar)}%`);

View file

@ -1,62 +1,89 @@
// Downloads the fonts the screenshot template needs, subset by Google Fonts (css2 `text=`) to exactly the characters
// your copy uses, so even CJK stays small: title + body family for Latin text, plus one Noto family per non-Latin
// script found in the copy (CJK, Arabic, Hebrew, Devanagari, Thai, Cyrillic / Greek).
// storebound shots fonts (re-run after editing the copy)
// Out: <project>/.storebound/fonts/*.woff2 + fonts.css. All of these fonts are SIL Open Font License 1.1.
// your copy uses, so even CJK stays small. `text=` pulls the glyphs from every subset the family has (latin, latin-ext,
// vietnamese, cyrillic, greek ...), so a missing glyph means the family itself lacks it.
// Then the glyph coverage check: every character of every language's copy (copy.json languages + config languages)
// is looked up in the cmap of the faces that draw it (title font: titles, badge values, app name; body font: eyebrows,
// sublines, badge labels; plus the Noto face of a non-Latin script). A character the stack lacks gets an automatic
// Noto fallback (logged; `shots check` errors on renders that used it unless shots.fonts.fallback lists it); a
// character no fallback covers fails with the language and the characters.
// storebound shots fonts [--json] (re-run after editing the copy or the fonts)
// Out: <project>/.storebound/fonts/*.woff2 + fonts.css + fonts.json (faces and the per-language stacks, read by render).
// All of these fonts are SIL Open Font License 1.1.
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { done, log } from '../lib/log';
import { done, log, printJson, warn } from '../lib/log';
import { shotsStyle } from '../lib/config';
import { type CopyFile, copyText, scriptFont, shotFonts } from './lib';
import { type CopyFile, shotFonts } from './lib';
import { fontCodepoints } from './cmap';
import { type FaceJob, type FontManifest, fontsCss, planFonts, roleTexts, type RoleTexts } from './glyphs';
const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36';
const ASCII = Array.from({ length: 95 }, (_, i) => String.fromCharCode(32 + i)).join('') + '·';
async function fetchSubset(family: string, chars: string, variable: boolean): Promise<ArrayBuffer> {
const fam = encodeURIComponent(family) + (variable ? ':wght@100..900' : '');
export async function fetchSubset(family: string, chars: string, axis: string | null): Promise<ArrayBuffer> {
const fam = encodeURIComponent(family) + (axis ? ':' + axis : '');
let res = await fetch(`https://fonts.googleapis.com/css2?family=${fam}&text=${encodeURIComponent(chars)}&display=block`, { headers: { 'user-agent': UA } });
if (!res.ok && variable) return fetchSubset(family, chars, false);
if (!res.ok) throw new Error(`${family}: ${res.status} ${await res.text()}`);
if (!res.ok && axis) return fetchSubset(family, chars, null);
if (!res.ok) throw new Error(`${family}: ${res.status} ${(await res.text()).slice(0, 200)}`);
const src = /url\((https:[^)]+)\)/.exec(await res.text())?.[1];
if (!src) throw new Error(`${family}: no font url`);
res = await fetch(src, { headers: { 'user-agent': UA } });
if (!res.ok) throw new Error(`${family}: ${res.status} for ${src}`);
return res.arrayBuffer();
}
/** Per-language role texts for every language of the copy and the config. */
export function langTexts(copy: CopyFile, langs: string[], appName: string): Record<string, RoleTexts> {
const out: Record<string, RoleTexts> = {};
for (const lang of [...new Set([...Object.keys(copy), ...langs])]) out[lang] = roleTexts(lang, copy[lang], appName);
return out;
}
export const fontsDirOf = (root: string): string => join(root, '.storebound', 'fonts');
export function readManifest(dir: string): FontManifest | null {
try { return JSON.parse(readFileSync(join(dir, 'fonts.json'), 'utf8')) as FontManifest; } catch { return null; }
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const shots = need(config.shots, 'shots');
const copy = JSON.parse(readFileSync(resolve(shots.copy), 'utf8')) as CopyFile;
const dir = join(root, '.storebound', 'fonts');
const dir = fontsDirOf(root);
mkdirSync(dir, { recursive: true });
const { title, body, titleVariable } = shotFonts(shots, shotsStyle(config));
const style = shotsStyle(config);
const { title, body, titleVariable } = shotFonts(shots, style);
const texts = langTexts(copy, config.languages.map(l => l.id), config.app.name);
const latin = new Set(ASCII);
const scripts = new Map<string, { family: string; chars: Set<string> }>();
for (const [lang, c] of Object.entries(copy)) {
const text = copyText(lang, c);
const s = scriptFont(lang, text);
if (!s) { for (const ch of text) latin.add(ch); continue; }
const cur = scripts.get(s.slug) ?? { family: s.family, chars: new Set(ASCII) };
for (const ch of text) cur.chars.add(ch);
scripts.set(s.slug, cur);
const sizes: string[] = [];
const manifest = await planFonts({
langs: texts, title, body, titleAxis: titleVariable ? 'wght@100..900' : null, bodyAxis: 'wght@100..900',
fallbackTitleAxis: style === 'app' ? 'wght@100..900' : 'wght@800', chosen: shots.fonts?.fallback, base: ASCII,
}, async (job: FaceJob) => {
let bin: Uint8Array;
try { bin = new Uint8Array(await fetchSubset(job.family, job.chars, job.axis)); } catch (e) {
if (job.kind !== 'fallback') throw e;
log('shots', `${job.family} has none of ${[...job.chars].join(' ')} (${(e as Error).message.split(' for ')[0]}), trying the next fallback`);
return new Set<number>();
}
writeFileSync(join(dir, job.file), bin);
const cps = fontCodepoints(bin);
sizes.push(`${job.file.padEnd(28)} ${job.family.padEnd(22)} ${(bin.byteLength / 1024).toFixed(1)} KB, ${[...job.chars].length} chars asked, ${cps.size} in the cmap`);
return cps;
});
writeFileSync(join(dir, 'fonts.css'), fontsCss(manifest));
writeFileSync(join(dir, 'fonts.json'), JSON.stringify(manifest, null, 1) + '\n');
if (ctx.args.has('json')) return printJson(manifest);
for (const s of sizes) log('shots', s);
let auto = 0;
for (const [lang, l] of Object.entries(manifest.langs)) for (const f of l.fallbacks) {
const ok = manifest.faces[f.face]?.chosen;
if (!ok) auto++;
const base = f.role === 'title' ? title : body;
(ok ? log : warn)('shots', `${lang} ${f.role}: ${[...f.chars].join(' ')} not in ${base} -> ${f.family}${ok ? ' (shots.fonts.fallback)' : ' (automatic fallback)'}`);
}
for (const ch of config.app.name) latin.add(ch);
const latinChars = [...latin].sort().join('');
let css = '/* Generated by storebound shots fonts (Google Fonts, SIL Open Font License 1.1), subset to the copy. */\n';
const jobs: [string, string, string, boolean][] = [[title, 'title', latinChars, titleVariable], [body, 'body', latinChars, true],
...[...scripts.entries()].map(([slug, s]) => [s.family, slug, [...s.chars].sort().join(''), true] as [string, string, string, boolean])];
for (const [family, slug, chars, variable] of jobs) {
const bin = await fetchSubset(family, chars, variable);
const file = `${slug}.woff2`;
writeFileSync(join(dir, file), Buffer.from(bin));
const face = slug === 'title' ? title : slug === 'body' ? body : `Store ${slug}`;
css += `@font-face { font-family: '${face}'; font-weight: 100 900; src: url(${file}) format('woff2'); }\n`;
log('shots', `${file.padEnd(18)} ${family.padEnd(22)} ${(bin.byteLength / 1024).toFixed(1)} KB, ${[...chars].length} chars`);
}
writeFileSync(join(dir, 'fonts.css'), css);
if (auto) warn('shots', `${auto} automatic fallbacks: renders that use them fail \`shots check\`. Pick title / body fonts that cover them${style === 'game' ? ' (titles: e.g. Paytone One, Baloo 2, Rowdies)' : ''} or accept the fallback with shots.fonts.fallback: ['<family>']`);
done('shots', 'fonts done');
}

317
cli/shots/glyphs.ts Normal file
View file

@ -0,0 +1,317 @@
// Glyph coverage of the screenshot fonts, per language and role (title / body), and the automatic Noto fallbacks.
// `shots fonts` plans the faces with planFonts() (downloads through an injected getter, so tests run offline) and
// writes .storebound/fonts/fonts.json; `shots render` re-checks coverage against the local files before rendering
// (uncoveredChars) and measures, in the page, which face drew every character (measureFonts). `shots check` turns a
// glyph drawn by a fallback the config did not choose, or by a system font, into an ERROR.
//
// Default stack per script (the template defaults, documented in the README and the store-screenshots skill):
// Latin incl. Latin Extended-A / B and Vietnamese, Cyrillic, Greek: the configured title / body font
// (defaults: game Paytone One + Montserrat, app Inter + Inter; all four cover Latin Extended and Vietnamese;
// Inter and Montserrat cover Cyrillic too). A Cyrillic or Greek line switches to Noto Sans as a whole.
// Arabic / Hebrew / Devanagari / Bengali / Thai: Noto Sans Arabic / Hebrew / Devanagari / Bengali / Thai (whole line).
// Japanese / Korean / Chinese: Noto Sans JP / KR / SC (TC for zh-Hant, TW, HK) (whole line).
// Any character the stack lacks: Noto Sans Display (titles) or Noto Sans (body text) for Latin / Cyrillic / Greek,
// Noto Sans <Script> for other scripts, then Noto Sans Symbols 2, Noto Sans Symbols, Noto Sans Math and Noto Color
// Emoji, added per character (logged, and an ERROR in `shots check` unless listed in shots.fonts.fallback).
import type { SceneCopy } from './lib';
import { scriptFont } from './lib';
import { needsGlyph } from './cmap';
export type Role = 'title' | 'body';
export interface RoleTexts { title: string; body: string }
/** The text each font role draws for one language: titles, badge values and the app name (feature graphic) use the
* title font; eyebrows (also upper-cased, as the template shows them), sublines, badge labels and scene numbers the
* body font. */
export function roleTexts(lang: string, c: Record<string, SceneCopy> | undefined, appName = ''): RoleTexts {
const title: string[] = [appName], body: string[] = ['0123456789'];
for (const s of Object.values(c ?? {})) {
title.push(...(s.title ?? []).filter(Boolean));
body.push(s.eyebrow ?? '', (s.eyebrow ?? '').toLocaleUpperCase(lang), s.sub ?? '');
for (const [big, small] of s.badges ?? []) { title.push(big ?? ''); body.push(small ?? ''); }
}
return { title: title.join('').normalize('NFC'), body: body.join('').normalize('NFC') };
}
/** Unique characters of a text that need a glyph, in first-seen order. */
export const glyphChars = (text: string): string[] => [...new Set([...text.normalize('NFC')].filter(needsGlyph))];
/** Characters of `text` that none of the faces covers. */
export function uncoveredChars(text: string, faces: Set<number>[]): string[] {
return glyphChars(text).filter(ch => { const cp = ch.codePointAt(0)!; return !faces.some(f => f.has(cp)); });
}
const NOTO_SCRIPTS = ['Arabic', 'Hebrew', 'Devanagari', 'Bengali', 'Thai', 'Armenian', 'Georgian', 'Ethiopic', 'Tamil', 'Telugu',
'Kannada', 'Malayalam', 'Gujarati', 'Gurmukhi', 'Oriya', 'Khmer', 'Lao', 'Myanmar', 'Sinhala', 'Thaana', 'Syriac'];
const SYMBOLS = ['Noto Sans Symbols 2', 'Noto Sans Symbols', 'Noto Sans Math', 'Noto Color Emoji'];
/** Noto families to try, in order, for a character the configured stack lacks. */
export function fallbackFamilies(ch: string, lang: string, role: Role): string[] {
const latin = role === 'title' ? ['Noto Sans Display', 'Noto Sans'] : ['Noto Sans'];
if (/\p{Extended_Pictographic}/u.test(ch) && !/[©®™]/u.test(ch)) return SYMBOLS;
if (/[\p{Script=Latin}\p{Script=Cyrillic}\p{Script=Greek}]/u.test(ch)) return latin;
if (/\p{Script=Hangul}/u.test(ch)) return ['Noto Sans KR'];
if (/[\p{Script=Hiragana}\p{Script=Katakana}]/u.test(ch)) return ['Noto Sans JP'];
if (/\p{Script=Han}/u.test(ch)) return /Hant|TW|HK/.test(lang) ? ['Noto Sans TC', 'Noto Sans JP'] : ['Noto Sans SC', 'Noto Sans JP'];
for (const s of NOTO_SCRIPTS) if (new RegExp(`\\p{Script=${s}}`, 'u').test(ch)) return [`Noto Sans ${s}`];
return [...latin, ...SYMBOLS];
}
/** Global order the fallback families are tried in (every per-character list above is a subsequence of it). */
export const FALLBACK_ORDER = ['Noto Sans Display', 'Noto Sans', 'Noto Sans KR', 'Noto Sans JP', 'Noto Sans SC', 'Noto Sans TC',
...NOTO_SCRIPTS.map(s => `Noto Sans ${s}`), ...SYMBOLS];
const slug = (s: string): string => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
export type FaceKind = 'title' | 'body' | 'script' | 'fallback';
/** One downloaded face: `face` is the @font-face family name the templates use. axis: css2 axis spec ("wght@800",
* "wght@100..900") or null for the font's default instance. */
export interface FaceJob { face: string; family: string; file: string; kind: FaceKind; role?: Role; axis: string | null; chars: string }
export interface LangFonts { title: string[]; body: string[]; fallbacks: { role: Role; face: string; family: string; chars: string }[] }
export interface FontManifest {
v: 1;
faces: Record<string, { family: string; file: string; kind: FaceKind; role?: Role; chosen: boolean }>;
langs: Record<string, LangFonts>;
}
export interface PlanInput {
langs: Record<string, RoleTexts>;
title: string; body: string;
/** css2 axis for the title / body family (null = default instance). */
titleAxis: string | null; bodyAxis: string | null;
/** Weight axis for automatic title fallbacks (game titles are heavy display faces: "wght@800"). */
fallbackTitleAxis: string | null;
/** shots.fonts.fallback: families the owner accepts as fallbacks. */
chosen?: string[];
/** Extra characters for the title / body downloads (ASCII, so later copy edits rarely need a new download). */
base?: string;
}
/** No font covers these characters: listed per language and role. */
export class GlyphError extends Error {
constructor(public readonly gaps: { lang: string; role: Role; chars: string[]; tried: string[] }[]) {
super('no font covers these characters (pick fonts that do, or change the copy):\n' + gaps.map(g =>
` ${g.lang} (${g.role}): ${g.chars.map(c => `"${c}" U+${c.codePointAt(0)!.toString(16).toUpperCase().padStart(4, '0')}`).join(', ')}; tried ${g.tried.join(', ')}`).join('\n'));
}
}
/** Faces for every language's copy: title + body, one Noto face per non-Latin script (whole lines, as before), and an
* automatic Noto fallback for each character the stack still lacks. `get` downloads a face (only the listed chars)
* and returns the code points its cmap covers. Throws GlyphError when no fallback covers a character. */
export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise<Set<number>>): Promise<FontManifest> {
const chosen = new Set((input.chosen ?? []).map(s => s.toLowerCase()));
const base = input.base ?? '';
const scripts = new Map<string, { family: string; chars: Set<string> }>();
const langScript = new Map<string, string | null>();
const roleChars: Record<Role, Set<string>> = { title: new Set(base), body: new Set(base) };
for (const [lang, t] of Object.entries(input.langs)) {
const s = scriptFont(lang, t.title + t.body);
langScript.set(lang, s ? `Store ${s.slug}` : null);
if (s) {
const cur = scripts.get(s.slug) ?? { family: s.family, chars: new Set(base) };
for (const ch of t.title + t.body) cur.chars.add(ch);
scripts.set(s.slug, cur);
}
// the title / body faces get every Latin / common character (and every character of Latin-only copy)
for (const r of ['title', 'body'] as const) for (const ch of t[r]) if (!s || !/[^\p{Script=Latin}\p{Script=Common}\p{Script=Inherited}]/u.test(ch)) roleChars[r].add(ch);
}
const sorted = (s: Iterable<string>): string => [...new Set(s)].sort().join('');
const faces: FontManifest['faces'] = {};
const cps = new Map<string, Set<number>>();
const add = async (job: FaceJob, isChosen: boolean): Promise<void> => {
cps.set(job.face, await get(job));
if (job.kind === 'fallback' && ![...job.chars].some(ch => cps.get(job.face)!.has(ch.codePointAt(0)!))) return; // covers none: not a face
faces[job.face] = { family: job.family, file: job.file, kind: job.kind, ...(job.role ? { role: job.role } : {}), chosen: isChosen };
};
await add({ face: input.title, family: input.title, file: 'title.woff2', kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted(roleChars.title) }, true);
if (input.body !== input.title) await add({ face: input.body, family: input.body, file: 'body.woff2', kind: 'body', role: 'body', axis: input.bodyAxis, chars: sorted(roleChars.body) }, true);
else { // same family: one download (title axis) with both roles' characters
const t = faces[input.title]!;
cps.set(input.title, await get({ face: input.title, family: input.title, file: t.file, kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted([...roleChars.title, ...roleChars.body]) }));
}
for (const [s, v] of scripts) await add({ face: `Store ${s}`, family: v.family, file: `${s}.woff2`, kind: 'script', axis: 'wght@100..900', chars: sorted(v.chars) }, true);
// per language and role: the stack, and what it lacks
const langs: FontManifest['langs'] = {};
const pending: { lang: string; role: Role; ch: string; tries: string[] }[] = [];
for (const [lang, t] of Object.entries(input.langs)) {
const x = langScript.get(lang);
langs[lang] = { title: [...(x ? [x] : []), input.title], body: [...(x ? [x] : []), input.body], fallbacks: [] };
for (const role of ['title', 'body'] as const) {
const stack = langs[lang]![role].map(f => cps.get(f)!);
for (const ch of uncoveredChars(t[role], stack)) pending.push({ lang, role, ch, tries: fallbackFamilies(ch, lang, role) });
}
}
const gaps = new Map<string, { lang: string; role: Role; chars: string[]; tried: string[] }>();
const hits = new Map<string, Map<string, Set<string>>>(); // lang|role -> face -> chars
for (const role of ['title', 'body'] as const) for (const family of FALLBACK_ORDER) {
const want = pending.filter(p => p.role === role && p.tries.includes(family));
if (!want.length) continue;
const face = `Store fb ${slug(family)} ${role}`;
const axis = family === 'Noto Color Emoji' ? null : role === 'title' ? input.fallbackTitleAxis : 'wght@100..900';
await add({ face, family, file: `fb-${slug(family)}-${role}.woff2`, kind: 'fallback', role, axis, chars: sorted(want.map(p => p.ch)) }, chosen.has(family.toLowerCase()));
const got = cps.get(face)!;
for (const p of want) {
p.tries = p.tries.filter(f => f !== family);
if (!got.has(p.ch.codePointAt(0)!)) continue;
const k = `${p.lang}|${role}`;
const m = hits.get(k) ?? new Map<string, Set<string>>();
m.set(face, (m.get(face) ?? new Set()).add(p.ch));
hits.set(k, m);
p.tries = [];
(p as { done?: boolean }).done = true;
}
}
for (const p of pending) {
if ((p as { done?: boolean }).done) continue;
const k = `${p.lang}|${p.role}`;
const g = gaps.get(k) ?? { lang: p.lang, role: p.role, chars: [], tried: [...langs[p.lang]![p.role].map(f => faces[f]?.family ?? f), ...fallbackFamilies(p.ch, p.lang, p.role)] };
g.chars.push(p.ch);
gaps.set(k, g);
}
if (gaps.size) throw new GlyphError([...gaps.values()]);
for (const [k, m] of hits) {
const [lang, role] = k.split('|') as [string, Role];
for (const face of [...m.keys()].sort((a, b) => FALLBACK_ORDER.indexOf(faces[a]!.family) - FALLBACK_ORDER.indexOf(faces[b]!.family))) {
langs[lang]![role].push(face);
langs[lang]!.fallbacks.push({ role, face, family: faces[face]!.family, chars: [...m.get(face)!].join('') });
}
}
return { v: 1, faces, langs };
}
/** fonts.css for a manifest (every face covers all weights: static faces are never synthesised bolder). */
export function fontsCss(m: FontManifest): string {
const seen = new Set<string>();
let css = '/* Generated by storebound shots fonts (Google Fonts, SIL Open Font License 1.1), subset to the copy. */\n';
for (const [face, f] of Object.entries(m.faces)) {
if (seen.has(face)) continue;
seen.add(face);
css += `@font-face { font-family: '${face}'; font-weight: 100 900; font-synthesis: none; src: url(${f.file}) format('woff2'); }\n`;
}
return css;
}
// ---- render time ------------------------------------------------------------------------------------------------
/** Per text element of a rendered page: which face drew which characters ("(system)" = none of ours). */
export interface MeasuredText { el: string; text: string; faces: Record<string, string> }
/** Runs in the page (`(${COLLECT_TEXT})(faceNames)`): every element with its own text whose font stack starts with one
* of our faces, with the characters it shows (after text-transform) and its stack of our faces; plus one hidden probe
* span per (face, weight, style, character) in #sb-glyph-probes, whose fonts `measureFonts` reads over CDP. Marks and
* whitespace are skipped (checked offline against the cmaps). */
export const COLLECT_TEXT = `(ours) => {
const OURS = new Set(ours);
const label = el => {
const me = el.tagName.toLowerCase() + (el.classList.length ? '.' + [...el.classList].join('.') : '');
if (!/^(span|b|small|i|em|strong)$/.test(el.tagName.toLowerCase()) || !el.parentElement) return me;
const p = el.parentElement, sib = [...p.children].filter(c => c.tagName === el.tagName);
return label(p) + ' ' + me + (sib.length > 1 ? ':' + (sib.indexOf(el) + 1) : '');
};
const lang = document.documentElement.lang || undefined;
const els = [], probes = [], seen = new Map();
for (const el of document.body.querySelectorAll('*')) {
if (/^(SCRIPT|STYLE|SVG)$/i.test(el.tagName) || el.closest('#sb-glyph-probes')) continue;
let text = [...el.childNodes].filter(n => n.nodeType === 3).map(n => n.data).join('').normalize('NFC');
if (!text.trim()) continue;
const cs = getComputedStyle(el);
if (cs.display === 'none' || cs.visibility === 'hidden') continue;
const fams = cs.fontFamily.split(',').map(s => s.trim().replace(/^["']|["']$/g, ''));
if (!OURS.has(fams[0])) continue;
const stack = [];
for (const f of fams) { if (!OURS.has(f)) break; stack.push(f); }
if (cs.textTransform === 'uppercase') text = text.toLocaleUpperCase(lang);
else if (cs.textTransform === 'lowercase') text = text.toLocaleLowerCase(lang);
const chars = [...new Set([...text])].filter(ch => !/^[\\s\\p{Cc}\\p{Cf}\\p{M}\\u{FE00}-\\u{FE0F}]$/u.test(ch));
const probe = {};
for (const ch of chars) for (const face of stack) {
const k = [face, cs.fontWeight, cs.fontStyle, ch].join('|');
if (!seen.has(k)) { seen.set(k, probes.length); probes.push({ face, weight: cs.fontWeight, style: cs.fontStyle, ch }); }
probe[face + '|' + ch] = seen.get(k);
}
els.push({ el: label(el), text: text.trim().slice(0, 60), stack, chars, probe });
}
const box = document.createElement('div');
box.id = 'sb-glyph-probes';
box.style.cssText = 'position:absolute;left:-20000px;top:0;white-space:pre';
for (const p of probes) {
const s = document.createElement('span');
s.style.cssText = 'font-size:32px;font-family:"' + p.face.replace(/"/g, '') + '";font-weight:' + p.weight + ';font-style:' + p.style;
s.textContent = p.ch;
box.append(s);
}
document.body.append(box);
return { els, probes: probes.length };
}`;
export interface CollectedText { el: string; text: string; stack: string[]; chars: string[]; probe: Record<string, number> }
/** Which face drew each character: the first face of the element's stack whose probe span used a web font (the probe
* span names that face only, so a web font in its platform fonts can only be that face). Pure. */
export function attribute(els: CollectedText[], covered: boolean[]): MeasuredText[] {
return els.map(e => {
const faces: Record<string, string> = {};
for (const ch of e.chars) {
const f = e.stack.find(face => covered[e.probe[face + '|' + ch]!]) ?? '(system)';
faces[f] = (faces[f] ?? '') + ch;
}
return { el: e.el, text: e.text, faces };
});
}
/** Measures a rendered page (Playwright chromium page): collects the text, then asks Chrome over CDP
* (CSS.getPlatformFontsForNode) which fonts drew each probe. Removes the probes afterwards. */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function measureFonts(page: any, ours: string[]): Promise<MeasuredText[]> {
const { els } = await page.evaluate(`(${COLLECT_TEXT})(${JSON.stringify(ours)})`) as { els: CollectedText[] };
await page.evaluate('document.fonts.ready.then(() => 0)');
const cdp = await page.context().newCDPSession(page);
try {
await cdp.send('DOM.enable'); await cdp.send('CSS.enable');
const { root } = await cdp.send('DOM.getDocument', { depth: 0 });
const { nodeIds } = await cdp.send('DOM.querySelectorAll', { nodeId: root.nodeId, selector: '#sb-glyph-probes > span' }) as { nodeIds: number[] };
const covered: boolean[] = [];
for (const nodeId of nodeIds) {
const { fonts } = await cdp.send('CSS.getPlatformFontsForNode', { nodeId }) as { fonts: { isCustomFont: boolean; glyphCount: number }[] };
covered.push(fonts.some(f => f.isCustomFont && f.glyphCount > 0));
}
return attribute(els, covered);
} finally {
await cdp.detach().catch(() => {});
await page.evaluate("document.getElementById('sb-glyph-probes')?.remove()");
}
}
/** Font usage of one rendered image, as stored in report.json. fallback = drawn by a face the config did not choose;
* missing = drawn by a system font (no face of ours has the glyph, or the font file did not load). */
export interface FontUsage {
used: Record<string, number>;
fallback: { el: string; text: string; face: string; family: string; chars: string }[];
missing: { el: string; text: string; chars: string }[];
}
/** Classifies what the page measured: faces of kind title / body / script and chosen fallbacks are fine. */
export function fontUsage(measured: MeasuredText[], faces: FontManifest['faces']): FontUsage {
const u: FontUsage = { used: {}, fallback: [], missing: [] };
for (const m of measured) for (const [face, chars] of Object.entries(m.faces)) {
const n = [...chars].length;
const fam = face === '(system)' ? '(system)' : faces[face]?.family ?? face;
u.used[fam] = (u.used[fam] ?? 0) + n;
if (face === '(system)') u.missing.push({ el: m.el, text: m.text, chars });
else if (faces[face] && !faces[face]!.chosen) u.fallback.push({ el: m.el, text: m.text, face, family: faces[face]!.family, chars });
}
return u;
}
/** check messages for an image's font usage (all errors). */
export function fontIssues(u: FontUsage | undefined): { level: 'error'; code: 'font-fallback' | 'glyph-missing'; msg: string }[] {
if (!u) return [];
const sp = (s: string): string => [...s].join(' ');
return [
...u.fallback.map(f => ({ level: 'error' as const, code: 'font-fallback' as const,
msg: `${f.el} "${f.text}": ${sp(f.chars)} drawn with ${f.family}, an automatic fallback the config did not choose (use a title / body font that covers them, or add '${f.family}' to shots.fonts.fallback, then shots fonts + render)` })),
...u.missing.map(f => ({ level: 'error' as const, code: 'glyph-missing' as const,
msg: `${f.el} "${f.text}": ${sp(f.chars)} drawn with a system font (no downloaded font has them or the fonts did not load: storebound shots fonts, then render again)` })),
];
}

View file

@ -49,10 +49,11 @@ export const palette = (p: string | Palette | undefined, style: 'game' | 'app' =
return hit;
};
/** Screenshot fonts: shots.fonts, else per style (game: Lilita One titles + Montserrat; app: Inter for both). The app
* title is a variable font (bold headline weights). */
/** Screenshot fonts: shots.fonts, else per style (game: Paytone One titles + Montserrat; app: Inter for both). All
* three cover Latin Extended-A / B (Turkish, Polish, Czech, Romanian ...) and Vietnamese; Montserrat and Inter also
* Cyrillic. The app title is a variable font (bold headline weights). Per-script stack: glyphs.ts. */
export function shotFonts(shots: Pick<ShotsConfig, 'fonts'> | undefined, style: 'game' | 'app'): { title: string; body: string; titleVariable: boolean } {
const d = style === 'app' ? { title: 'Inter', body: 'Inter' } : { title: 'Lilita One', body: 'Montserrat' };
const d = style === 'app' ? { title: 'Inter', body: 'Inter' } : { title: 'Paytone One', body: 'Montserrat' };
return { title: shots?.fonts?.title ?? d.title, body: shots?.fonts?.body ?? d.body, titleVariable: style === 'app' };
}

View file

@ -5,9 +5,16 @@
// <lang>/sheet.png (contact sheet of every size packed into a grid, for a quick review) and <shots.out>/report.json (text overflow flags
// per image, read by `shots check` and `shots gallery`). Variants go to <shots.out>/<variant>/<lang>/...
// Default sizes: defaultSizes() (ipad13 only with apple.ipad). Needs playwright + ffmpeg.
// Fonts: the per-language stacks from .storebound/fonts/fonts.json (`shots fonts`). Before rendering, every character
// of the copy is checked against the cmaps of the downloaded faces (stale fonts fail with the language and the
// characters); while rendering, the page measures which face drew every character, and report.json records it per
// image (`fonts`: faces used, automatic fallbacks, system-font glyphs) for `shots check`.
// Style: shotsStyle() = shots.style, else app for the app / subscription-app profiles (template-app.html,
// feature-app.html: calm gradient, device frame, headline + subline), else game (template.html, feature.html).
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
import { fontCodepoints } from './cmap';
import { readManifest } from './fonts';
import { type FontManifest, fontUsage, measureFonts, roleTexts, uncoveredChars } from './glyphs';
import { join, relative } from 'node:path';
import { spawnSync } from 'node:child_process';
import type { Ctx } from '../lib/ctx';
@ -51,12 +58,46 @@ export async function run(ctx: Ctx): Promise<void> {
return done('shots', `render planned (dry run): ${n} images`);
}
const fontsDir = join(root, '.storebound', 'fonts');
if (!existsSync(join(fontsDir, 'fonts.css'))) warn('shots', 'no .storebound/fonts/fonts.css: run `storebound shots fonts` first (falling back to system fonts)');
if (!existsSync(join(fontsDir, 'fonts.css'))) warn('shots', 'no .storebound/fonts/fonts.css: run `storebound shots fonts` first (falling back to system fonts; shots check will fail)');
const { phone, tablet } = frameDims(config);
const rtl = new Map(config.languages.map(l => [l.id, !!l.rtl] as const));
const style = shotsStyle(config);
const sf = shotFonts(shots, style);
const fonts = { title: sf.title, body: sf.body };
const manifest = existsSync(join(fontsDir, 'fonts.css')) ? readManifest(fontsDir) : null;
if (existsSync(join(fontsDir, 'fonts.css')) && !manifest) warn('shots', 'fonts from an older storebound (no fonts.json): run `storebound shots fonts` again for the glyph coverage check');
if (manifest && (!manifest.faces[sf.title] || !manifest.faces[sf.body])) throw new Error(`shots render: .storebound/fonts has other fonts than shots.fonts (${sf.title} / ${sf.body}): run \`storebound shots fonts\``);
const stacks = (lang: string, copy: CopyFile): { title: string[]; body: string[]; script: string | null } => {
const m = manifest?.langs[lang];
if (m) return { title: m.title, body: m.body, script: m.title[0]?.startsWith('Store ') && !m.title[0].startsWith('Store fb ') ? m.title[0] : null };
const sc = scriptFont(lang, copyText(lang, copy[lang]));
const x = sc ? `Store ${sc.slug}` : null;
return { title: [...(x ? [x] : []), sf.title], body: [...(x ? [x] : []), sf.body], script: x };
};
const faces: FontManifest['faces'] = manifest?.faces ?? { [sf.title]: { family: sf.title, file: '', kind: 'title', chosen: true }, [sf.body]: { family: sf.body, file: '', kind: 'body', chosen: true } };
if (!manifest) for (const [, job] of jobs) for (const lang of langs) {
const x = stacks(lang, job.copy).script;
if (x) faces[x] = { family: x, file: '', kind: 'script', chosen: true };
}
if (manifest) { // glyph coverage of the local font files, before rendering anything
const cmaps = new Map<string, Set<number>>();
const cps = (face: string): Set<number> => {
if (!cmaps.has(face)) { const f = manifest.faces[face]; cmaps.set(face, f && existsSync(join(fontsDir, f.file)) ? fontCodepoints(readFileSync(join(fontsDir, f.file))) : new Set()); }
return cmaps.get(face)!;
};
const gaps: string[] = [];
for (const [, job] of jobs) for (const lang of langs) {
if (!manifest.langs[lang]) { gaps.push(`${lang}: no font stack (language added after \`shots fonts\`)`); continue; }
const t = roleTexts(lang, job.copy[lang], config.app.name);
for (const role of ['title', 'body'] as const) {
const miss = uncoveredChars(t[role], manifest.langs[lang]![role].map(cps));
if (miss.length) gaps.push(`${lang} (${role}): ${miss.join(' ')}`);
}
}
if (gaps.length) throw new Error(`shots render: the downloaded fonts do not cover the copy (edited since \`shots fonts\`?): run \`storebound shots fonts\`\n ${[...new Set(gaps)].join('\n ')}`);
for (const lang of langs) for (const f of manifest.langs[lang]?.fallbacks ?? [])
(manifest.faces[f.face]?.chosen ? log : warn)('shots', `${lang} ${f.role}: ${[...f.chars].join(' ')} from ${f.family}${manifest.faces[f.face]?.chosen ? '' : ' (automatic fallback: shots check will fail)'}`);
}
const tpl = import.meta.dir;
const server = Bun.serve({
@ -67,10 +108,9 @@ export async function run(ctx: Ctx): Promise<void> {
if (p === '/job.json') {
const lang = url.searchParams.get('lang') ?? '';
const { scenes, copy } = jobs.get(url.searchParams.get('v') ?? '') ?? jobs.values().next().value!;
const text = copyText(lang, copy[lang]);
const script = scriptFont(lang, text);
const st = stacks(lang, copy);
const base = { style, phone, tablet, rtl: rtl.get(lang), logo: !!shots.logo, appName: config.app.name,
fonts: { ...fonts, script: script ? `Store ${script.slug}` : null } };
fonts: { ...fonts, script: st.script, titleStack: st.title, bodyStack: st.body } };
if (url.searchParams.has('feature'))
return Response.json({ ...base, frame: shots.feature?.frame ?? scenes[0]!.frames[0]!.src, palette: palette(shots.feature?.palette ?? scenes[0]!.palette, style) });
const sid = url.searchParams.get('s') ?? '';
@ -108,7 +148,13 @@ export async function run(ctx: Ctx): Promise<void> {
await page.waitForTimeout(200);
const tmp = out + '.tmp.png';
const overflow = JSON.parse((await page.evaluate('document.body.dataset.overflow')) ?? '[]') as string[];
if (!out.endsWith('sheet.png')) report[relative(outDir, out)] = { overflow, missing: errs.filter(e => e.startsWith('404')) };
if (!out.endsWith('sheet.png')) {
const measured = await measureFonts(page, Object.keys(faces));
const usage = fontUsage(measured, faces);
report[relative(outDir, out)] = { overflow, missing: errs.filter(e => e.startsWith('404')), fonts: usage };
for (const f of usage.fallback) warn('shots', `${relative(root, out)}: ${f.el} ${[...f.chars].join(' ')} drawn with ${f.family} (automatic fallback)`);
for (const f of usage.missing) warn('shots', `${relative(root, out)}: ${f.el} ${[...f.chars].join(' ')} drawn with a system font`);
}
if (overflow.length) warn('shots', `${relative(root, out)}: ${overflow.join('; ')}`);
await page.screenshot({ path: tmp, clip: { x: 0, y: 0, width: w, height: h } });
const r = spawnSync('ffmpeg', ['-v', 'error', '-y', '-i', tmp, '-pix_fmt', 'rgb24', out]);

View file

@ -4,10 +4,12 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';
import { SIZES } from './lib';
import { fontIssues, type FontUsage } from './glyphs';
import { checkCount, checkImage, checkVideo, type ImageInfo, imageInfo, type Issue, IMAGE_SPECS, parseProbe, PREVIEW_RULES, type ProbeInfo, VIDEO_TARGETS } from './spec';
/** <renders>/report.json: path relative to the renders dir -> flags found while rendering. */
export type RenderReport = Record<string, { overflow: string[]; missing?: string[] }>;
/** <renders>/report.json: path relative to the renders dir -> flags found while rendering. missing = 404s (frames);
* fonts = which face drew the text (glyphs.ts FontUsage): automatic fallbacks and system-font glyphs are errors. */
export type RenderReport = Record<string, { overflow: string[]; missing?: string[]; fonts?: FontUsage }>;
export function readReport(dir: string): RenderReport {
try { return JSON.parse(readFileSync(join(dir, 'report.json'), 'utf8')) as RenderReport; } catch { return {}; }
@ -49,7 +51,10 @@ export function scanRenders(dir: string, o: { langs: string[]; variants?: string
const info = imageInfo(readFileSync(file));
const rel = (variant ? `${variant}/` : '') + `${lang}/${size}/${f}`;
const issues = checkImage(info, size);
for (const msg of report[rel.replace(/\.jpe?g$/i, '.png')]?.overflow ?? []) issues.push({ level: 'warn', code: 'overflow', msg });
const entry = report[rel.replace(/\.jpe?g$/i, '.png')];
for (const msg of entry?.overflow ?? []) issues.push({ level: 'warn', code: 'overflow', msg });
issues.push(...fontIssues(entry?.fonts));
if (entry && !entry.fonts) issues.push({ level: 'warn', code: 'fonts', msg: 'font usage not recorded (rendered by an older storebound): run shots fonts + shots render again so missing glyphs are caught' });
out.images.push({ rel, lang, variant, size, file, info, issues });
}
const required = req[size] ?? false;

View file

@ -90,7 +90,7 @@ export function imageInfo(b: Uint8Array): ImageInfo {
}
export type IssueLevel = 'error' | 'warn';
export interface Issue { level: IssueLevel; code: 'size' | 'alpha' | 'format' | 'bytes' | 'count' | 'overflow' | 'video'; msg: string }
export interface Issue { level: IssueLevel; code: 'size' | 'alpha' | 'format' | 'bytes' | 'count' | 'overflow' | 'video' | 'font-fallback' | 'glyph-missing' | 'fonts'; msg: string }
/** Problems with one image for a size key. */
export function checkImage(info: ImageInfo, sizeKey: string): Issue[] {

View file

@ -89,8 +89,10 @@ R.setProperty('--line2', dark ? P.glow : P.ink);
R.setProperty('--accentSoft', rgba(P.glow, dark ? .28 : .14));
R.setProperty('--bg', P.bg[0] === P.bg[2] && P.bg[1] === P.bg[0] ? P.bg[0] : `linear-gradient(180deg, ${P.bg[0]} 0%, ${P.bg[1]} 55%, ${P.bg[2]} 100%)`);
const T = job.fonts.title, B = job.fonts.body, X = job.fonts.script;
R.setProperty('--tf', X ? `'${X}', '${T}', sans-serif` : `'${T}', sans-serif`);
R.setProperty('--bf', X ? `'${X}', '${B}', sans-serif` : `'${B}', sans-serif`);
// titleStack / bodyStack (from shots fonts): script face, the configured font, then any automatic Noto fallback
const fstack = (st, def) => (st ?? (X ? [X, def] : [def])).map(f => `'${f}'`).join(', ') + ', sans-serif';
R.setProperty('--tf', fstack(job.fonts.titleStack, T));
R.setProperty('--bf', fstack(job.fonts.bodyStack, B));
R.setProperty('--tw', 750);
const CJK = /^(ja|ko|zh)/.test(LANG);
R.setProperty('--lh', /^(ar|hi|fa|ur|th)/.test(LANG) ? 1.3 : CJK ? 1.18 : 1.06);

View file

@ -126,8 +126,10 @@ R.setProperty('--bg', `linear-gradient(180deg, ${P.bg[0]} 0%, ${P.bg[1]} 48%, ${
// A script the title font lacks (CJK, Arabic, Cyrillic, ...): the whole line switches to the Noto subset so a word
// never mixes two typefaces.
const T = job.fonts.title, B = job.fonts.body, X = job.fonts.script;
R.setProperty('--tf', X ? `'${X}', '${T}', sans-serif` : `'${T}', sans-serif`);
R.setProperty('--bf', X ? `'${X}', '${B}', sans-serif` : `'${B}', sans-serif`);
// titleStack / bodyStack (from shots fonts): script face, the configured font, then any automatic Noto fallback
const fstack = (st, def) => (st ?? (X ? [X, def] : [def])).map(f => `'${f}'`).join(', ') + ', sans-serif';
R.setProperty('--tf', fstack(job.fonts.titleStack, T));
R.setProperty('--bf', fstack(job.fonts.bodyStack, B));
R.setProperty('--tw', X ? 900 : job.fonts.titleWeight ?? 400);
const CJK = /^(ja|ko|zh)/.test(LANG);
R.setProperty('--lh', /^(ar|hi|fa|ur|th)/.test(LANG) ? 1.28 : CJK ? 1.12 : .98);

View file

@ -16,6 +16,7 @@ import { need } from '../lib/ctx';
import { done, log, warn } from '../lib/log';
import { launch } from './browser';
import { shotsStyle } from '../lib/config';
import { readManifest } from './fonts';
import { captionsFor, type CopyFile, copyText, palette, renderDir, scriptFont, shotFonts } from './lib';
import { ffprobe } from './report';
import { checkVideo, PREVIEW_RULES, VIDEO_TARGETS } from './spec';
@ -158,7 +159,7 @@ export async function run(ctx: Ctx): Promise<void> {
const style = shotsStyle(ctx.loaded.config);
const pal = palette(shots.scenes[0]?.palette, style);
return Response.json({ text: texts[Number(url.searchParams.get('i'))] ?? '', ink: style === 'app' ? '#111827' : pal.ink, rtl: rtl.get(lang),
fonts: { title: shotFonts(shots, style).title, script: script ? `Store ${script.slug}` : null } });
fonts: { title: shotFonts(shots, style).title, script: script ? `Store ${script.slug}` : null, titleStack: readManifest(fontsDir)?.langs[lang]?.title } });
}
if (url.pathname === '/caption.html') return new Response(Bun.file(join(import.meta.dir, 'caption.html')), { headers: { 'content-type': 'text/html; charset=utf-8' } });
if (url.pathname.startsWith('/fonts/') && !url.pathname.includes('..')) {