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

View file

@ -10,6 +10,7 @@
// text, screenshots, config): the days before vs after each change. Read-only on both stores except `setup`.
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { createOnce } from './lib/upsert';
import { ascClient, type Asc, type J } from './apple/asc';
import type { Ctx } from './lib/ctx';
import {
@ -102,7 +103,9 @@ export async function run(ctx: Ctx): Promise<void> {
if (cur) { done(TAG, `apple: ONGOING report request exists (${cur.id})`); return; }
const body = { data: { type: 'analyticsReportRequests', attributes: { accessType: 'ONGOING' }, relationships: { app: { data: { type: 'apps', id: appId } } } } };
if (dry) { log(TAG, 'would POST /v1/analyticsReportRequests {accessType=ONGOING} (dry)'); return; }
await c.asc('POST', '/v1/analyticsReportRequests', body);
// one ONGOING request per app: a 409 or an unclear answer is checked by reading it back, never re-sent blindly
await createOnce({ what: 'ONGOING analytics report request', tag: TAG, unique: true, find: () => ongoingRequest(c, appId),
create: async () => (await c.asc('POST', '/v1/analyticsReportRequests', body)).data });
done(TAG, 'apple: ONGOING report request created; the first reports appear after 1-2 days, then daily');
return;
}

View file

@ -1,8 +1,10 @@
// Generic client for every App Store Connect and Google Play operation: the generated rows (apple.gen.ts, play.gen.ts)
// plus a few helpers instead of a function per endpoint. Request building is pure (tests cover URLs and parameters);
// sending retries 429 / 5xx with backoff (Retry-After honoured) and follows pages.
// sending retries 429 (and 5xx / network errors of requests that are safe to send twice: not a POST create) with
// backoff (Retry-After honoured) and follows pages.
// Auth: the App Store Connect team key JWT from cli/apple/asc.ts, the Play service account token from
// cli/lib/google-auth.ts (one scope per Google API). Credentials only come from env or .storebound/.
import { AmbiguousWriteError, retrySafe } from '../lib/upsert';
import { APPLE_OPS, APPLE_SPEC } from './apple.gen';
import { PLAY_APIS, PLAY_OPS } from './play.gen';
import type { AppleBody, AppleOp, AppleParams, AppleResponse, ParamValue, PlayBody, PlayOp, PlayParams, PlayResponse } from './types';
@ -207,15 +209,20 @@ export async function send(req: BuiltRequest, auth: Auth, o: SendOptions = {}):
const headers: Record<string, string> = { Authorization: await auth(req) };
if (req.contentType) headers['Content-Type'] = req.contentType;
if (req.accept) headers.Accept = req.accept;
// 5xx and network errors are retried only for requests that end the same when sent twice: a POST create without
// a clear answer may have been applied, so it is reported (AmbiguousWriteError) and never sent again by itself
const safe = retrySafe(req.method, req.url);
let r: Response;
try {
r = await doFetch(req.url, { method: req.method, headers, body: req.body as BodyInit | undefined });
} catch (e) {
if (!safe) throw new AmbiguousWriteError(`${req.method} ${short(req.url)}: no answer (${(e as Error).message}); not sent again: it may have been applied, check with a GET before you run it again`);
if (attempt >= attempts) throw e;
o.onRetry?.(`${req.method} ${short(req.url)}: ${(e as Error).message}, retry ${attempt}/${attempts - 1}`);
await sleep(backoffMs(attempt));
continue;
}
if (r.status >= 500 && !safe) throw new AmbiguousWriteError(`${req.method} ${short(req.url)} -> ${r.status} ${errorBody(await r.text())}; not sent again: it may have been applied, check with a GET before you run it again`, r.status);
if ((r.status === 429 || r.status >= 500) && attempt < attempts) {
const wait = backoffMs(attempt, r.headers.get('retry-after'));
await r.body?.cancel();

View file

@ -16,6 +16,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'appCustomProductPageVersions_updateInstance': 'apple/cpp',
'appCustomProductPages_appCustomProductPageVersions_getToManyRelated': 'apple/cpp',
'appCustomProductPages_createInstance': 'apple/cpp',
'appCustomProductPages_getInstance': 'apple/cpp',
'appCustomProductPages_updateInstance': 'apple/cpp',
'appEncryptionDeclarations_getCollection': 'apple/encryption',
'appEventLocalizations_appEventScreenshots_getToManyRelated': 'apple/events',
@ -25,6 +26,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'appEventScreenshots_deleteInstance': 'apple/events',
'appEventScreenshots_updateInstance': 'apple/events',
'appEvents_createInstance': 'apple/events',
'appEvents_getInstance': 'apple/events',
'appEvents_localizations_getToManyRelated': 'apple/events',
'appInfos_ageRatingDeclaration_getToOneRelated': 'apple/appinfo validate',
'appInfos_appInfoLocalizations_getToManyRelated': 'apple/listing validate',
@ -32,23 +34,20 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'appInfos_updateInstance': 'apple/appinfo',
'appPreviewSets_appPreviews_getToManyRelated': 'apple/previews',
'appPreviewSets_createInstance': 'apple/previews',
'appPreviews_createInstance': 'apple/previews',
'appPreviews_deleteInstance': 'apple/previews',
'appPreviews_updateInstance': 'apple/previews',
'appPriceSchedules_createInstance': 'apple/appinfo',
'appScreenshotSets_appScreenshots_getToManyRelated': 'apple/ppo apple/screenshots validate',
'appScreenshotSets_createInstance': 'apple/screenshots',
'appScreenshots_createInstance': 'apple/screenshots',
'appScreenshots_deleteInstance': 'apple/screenshots',
'appScreenshots_updateInstance': 'apple/screenshots',
'appStoreReviewDetails_createInstance': 'apple/review-details',
'appStoreReviewDetails_updateInstance': 'apple/review-details',
'appStoreVersionExperimentTreatmentLocalizations_appScreenshotSets_getToManyRelated': 'apple/ppo',
'appStoreVersionExperimentTreatmentLocalizations_createInstance': 'lib/ppo',
'appStoreVersionExperimentTreatments_appStoreVersionExperimentTreatmentLocalizations_getToManyRelated': 'apple/ppo',
'appStoreVersionExperimentTreatments_createInstance': 'lib/ppo',
'appStoreVersionExperimentTreatments_getInstance': 'apple/ppo',
'appStoreVersionExperimentsV2_appStoreVersionExperimentTreatments_getToManyRelated': 'apple/ppo',
'appStoreVersionExperimentsV2_createInstance': 'lib/ppo',
'appStoreVersionExperimentsV2_getInstance': 'apple/ppo',
'appStoreVersionExperimentsV2_updateInstance': 'lib/ppo',
'appStoreVersionLocalizations_appPreviewSets_getToManyRelated': 'apple/previews',
'appStoreVersionLocalizations_appScreenshotSets_getToManyRelated': 'apple/screenshots validate',
@ -61,6 +60,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'appStoreVersions_build_getToOneRelated': 'apple/listing validate',
'appStoreVersions_build_updateToOneRelationship': 'apple/listing',
'appStoreVersions_createInstance': 'apple/listing',
'appStoreVersions_getInstance': 'apple/listing',
'appStoreVersions_updateInstance': 'apple/listing',
'apps_analyticsReportRequests_getToManyRelated': 'analytics',
'apps_appAvailabilityV2_getToOneRelated': 'apple/appinfo apple/preorder validate',
@ -75,6 +75,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'apps_betaAppReviewDetail_getToOneRelated': 'apple/testflight',
'apps_betaFeedbackCrashSubmissions_getToManyRelated': 'health',
'apps_betaGroups_getToManyRelated': 'apple/testflight',
'apps_buildUploads_getToManyRelated': 'apple/upload',
'apps_customerReviews_getToManyRelated': 'reviews',
'apps_getCollection': 'apple/asc apple/bundle apps lib/store-apps',
'apps_getInstance': 'apple/appinfo apple/status',
@ -98,11 +99,13 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'betaGroups_builds_getToManyRelated': 'apple/testflight',
'betaGroups_createInstance': 'lib/testflight',
'betaGroups_getCollection': 'apple/testflight',
'betaGroups_getInstance': 'apple/testflight',
'betaTesterInvitations_createInstance': 'lib/testflight',
'betaTesters_createInstance': 'lib/testflight',
'betaTesters_getCollection': 'apple/testflight',
'buildUploadFiles_createInstance': 'lib/xcode',
'buildUploadFiles_updateInstance': 'lib/xcode',
'buildUploads_buildUploadFiles_getToManyRelated': 'apple/upload',
'buildUploads_createInstance': 'lib/xcode',
'buildUploads_getInstance': 'apple/upload',
'builds_appEncryptionDeclaration_getToOneRelated': 'validate',
@ -132,6 +135,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'inAppPurchaseOfferCodeOneTimeUseCodes_values_getToOneRelated': 'apple/offer-codes',
'inAppPurchaseOfferCodes_createInstance': 'apple/offer-codes',
'inAppPurchaseOfferCodes_customCodes_getToManyRelated': 'apple/offer-codes',
'inAppPurchaseOfferCodes_getInstance': 'apple/offer-codes',
'inAppPurchaseOfferCodes_oneTimeUseCodes_getToManyRelated': 'apple/offer-codes',
'inAppPurchasePricePoints_equalizations_getToManyRelated': 'apple/offer-codes',
'inAppPurchasePriceSchedules_automaticPrices_getToManyRelated': 'prices',
@ -141,6 +145,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'inAppPurchaseVersions_createInstance': 'lib/review-submit',
'inAppPurchasesV2_appStoreReviewScreenshot_getToOneRelated': 'apple/iap-review validate',
'inAppPurchasesV2_createInstance': 'apple/iap',
'inAppPurchasesV2_getInstance': 'apple/iap',
'inAppPurchasesV2_iapPriceSchedule_getToOneRelated': 'apple/iap apple/iap-review catalog',
'inAppPurchasesV2_inAppPurchaseAvailability_getToOneRelated': 'apple/iap apple/iap-review',
'inAppPurchasesV2_inAppPurchaseLocalizations_getToManyRelated': 'apple/iap apple/iap-review catalog',
@ -153,17 +158,20 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'profiles_getInstance': 'apple/signing',
'promotedPurchases_createInstance': 'lib/offers',
'promotedPurchases_updateInstance': 'lib/offers',
'reviewSubmissionItems_createInstance': 'apple/events lib/cpp-events lib/review-submit',
'reviewSubmissions_createInstance': 'apple/cpp apple/events lib/review-submit',
'reviewSubmissions_getCollection': 'apple/cpp apple/events apple/iap-submit apple/status',
'reviewSubmissions_items_getToManyRelated': 'apple/iap-submit',
'reviewSubmissionItems_createInstance': 'apple/submission lib/cpp-events lib/review-submit',
'reviewSubmissions_createInstance': 'apple/cpp apple/events apple/submission lib/review-submit',
'reviewSubmissions_getCollection': 'apple/events apple/iap-submit apple/status apple/submission',
'reviewSubmissions_getInstance': 'apple/submission',
'reviewSubmissions_items_getToManyRelated': 'apple/iap-submit apple/submission',
'reviewSubmissions_updateInstance': 'apple/cpp apple/events apple/iap-submit apple/status lib/review-submit',
'salesReports_getCollection': 'lib/reports',
'subscriptionAppStoreReviewScreenshots_createInstance': 'apple/subscriptions',
'subscriptionAppStoreReviewScreenshots_deleteInstance': 'apple/subscriptions',
'subscriptionAppStoreReviewScreenshots_updateInstance': 'apple/subscriptions',
'subscriptionAvailabilities_createInstance': 'apple/subscriptions',
'subscriptionGroupLocalizations_createInstance': 'apple/subscriptions',
'subscriptionGroups_createInstance': 'apple/subscriptions',
'subscriptionGroups_getInstance': 'apple/subscriptions',
'subscriptionGroups_subscriptionGroupLocalizations_getToManyRelated': 'apple/subscriptions validate',
'subscriptionGroups_subscriptions_getToManyRelated': 'apple/iap-submit apple/promoted apple/subscriptions apple/win-back catalog prices validate',
'subscriptionGroups_versions_getToManyRelated': 'apple/iap-submit',
@ -171,11 +179,13 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'subscriptionOfferCodeCustomCodes_createInstance': 'apple/subscriptions',
'subscriptionOfferCodes_createInstance': 'apple/subscriptions',
'subscriptionOfferCodes_customCodes_getToManyRelated': 'apple/subscriptions',
'subscriptionOfferCodes_getInstance': 'apple/subscriptions',
'subscriptionPricePoints_equalizations_getToManyRelated': 'apple/subscriptions apple/win-back',
'subscriptionPromotionalOffers_createInstance': 'apple/subscriptions',
'subscriptionVersions_createInstance': 'lib/review-submit',
'subscriptions_appStoreReviewScreenshot_getToOneRelated': 'apple/subscriptions validate',
'subscriptions_createInstance': 'apple/subscriptions',
'subscriptions_getInstance': 'apple/subscriptions',
'subscriptions_introductoryOffers_getToManyRelated': 'apple/subscriptions catalog',
'subscriptions_offerCodes_getToManyRelated': 'apple/subscriptions catalog',
'subscriptions_pricePoints_getToManyRelated': 'apple/subscriptions apple/win-back',
@ -205,7 +215,7 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'androidpublisher.edits.insert': 'apps play/client validate',
'androidpublisher.edits.listings.list': 'play/listing play/status validate',
'androidpublisher.edits.listings.update': 'play/listing',
'androidpublisher.edits.tracks.get': 'play/rollout play/upload',
'androidpublisher.edits.tracks.get': 'play/release play/rollout play/upload',
'androidpublisher.edits.tracks.list': 'play/next-version-code play/status validate',
'androidpublisher.edits.tracks.update': 'play/release play/rollout play/upload',
'androidpublisher.edits.validate': 'play/client',
@ -216,11 +226,9 @@ export const WRAPPED: { apple: Record<string, string>; play: Record<string, stri
'androidpublisher.monetization.onetimeproducts.patch': 'play/products prices',
'androidpublisher.monetization.onetimeproducts.purchaseOptions.batchUpdateStates': 'play/products',
'androidpublisher.monetization.subscriptions.basePlans.activate': 'play/subscriptions',
'androidpublisher.monetization.subscriptions.basePlans.offers.activate': 'play/subscriptions',
'androidpublisher.monetization.subscriptions.basePlans.offers.create': 'play/subscriptions',
'androidpublisher.monetization.subscriptions.basePlans.offers.list': 'catalog play/subscriptions',
'androidpublisher.monetization.subscriptions.create': 'play/subscriptions',
'androidpublisher.monetization.subscriptions.get': 'prices',
'androidpublisher.monetization.subscriptions.get': 'play/subscriptions prices',
'androidpublisher.monetization.subscriptions.list': 'catalog play/subscriptions validate',
'androidpublisher.monetization.subscriptions.patch': 'play/subscriptions',
'androidpublisher.reviews.list': 'reviews',

View file

@ -32,6 +32,7 @@ import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { done, log, printJson, warn } from '../lib/log';
import { textTable } from '../lib/table';
import { createOnce } from '../lib/upsert';
import { type Asc, ascClient, type J } from './asc';
const TAG = 'adhoc';
@ -86,8 +87,11 @@ async function register(ctx: Ctx, c: () => Promise<Asc>): Promise<void> {
let failed = 0;
for (const d of plan.add) {
try {
await api.asc('POST', '/v1/devices', deviceCreateReq(d));
log(TAG, `registered ${d.name} (${maskUdid(d.udid)})`);
// a UDID is registered once per team: a 409 or an unclear answer is checked by a direct lookup, never re-sent blindly
const r = await createOnce({ what: `device ${d.name} (${maskUdid(d.udid)})`, tag: TAG, unique: true,
find: async () => (await api.all(`/v1/devices?filter[udid]=${encodeURIComponent(d.udid)}&limit=10`)).find((x: J) => String(x.attributes?.udid ?? '').toLowerCase() === d.udid.toLowerCase()) ?? null,
create: async () => (await api.asc('POST', '/v1/devices', deviceCreateReq(d))).data });
log(TAG, `${r.created ? 'registered' : 'already registered:'} ${d.name} (${maskUdid(d.udid)})`);
} catch (e) {
failed++;
warn(TAG, `${d.name} (${maskUdid(d.udid)}) not registered: ${scrubUdids((e as Error).message, udids)}`);
@ -110,13 +114,16 @@ async function profile(ctx: Ctx, c: () => Promise<Asc>): Promise<void> {
const devices = profileDevices(await registered(api, 'IOS'));
if (!devices.length) throw new Error('no enabled iOS devices: register them first (storebound apple adhoc register)');
const want = devices.map(d => d.id);
const existing = (await api.all(`/v1/bundleIds/${bid.id}/profiles?limit=200`)).filter((p: J) => p.attributes?.profileType === 'IOS_APP_ADHOC' && p.attributes?.name === name);
// the profile and the dated ones an earlier run made when it had to replace it ("<name> YYYY-MM-DD"), newest first
const dated = new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}( \\d{4}-\\d{2}-\\d{2}( \\d{2}-\\d{2})?)?$`);
const existing = (await api.all(`/v1/bundleIds/${bid.id}/profiles?limit=200`)).filter((p: J) => p.attributes?.profileType === 'IOS_APP_ADHOC' && dated.test(p.attributes?.name ?? ''))
.sort((x: J, y: J) => String(y.attributes.name).localeCompare(String(x.attributes.name)));
let newName = name;
for (const p of existing) {
const has = (await api.all(`/v1/profiles/${p.id}/devices?limit=200`)).map((d: J) => d.id as string);
const st = profileCurrent(p.attributes.profileState, has, want);
if (st.current) { done(TAG, `profile "${name}" is current (${has.length} devices, expires ${String(p.attributes.expirationDate ?? '').slice(0, 10)})`); return; }
log(TAG, `profile "${name}" is ${p.attributes.profileState === 'ACTIVE' ? `missing ${st.missing} device(s)` : 'invalid'}; profiles cannot be changed, so a new one is created`);
if (st.current) { done(TAG, `profile "${p.attributes.name}" is current (${has.length} devices, expires ${String(p.attributes.expirationDate ?? '').slice(0, 10)})`); return; }
log(TAG, `profile "${p.attributes.name}" is ${p.attributes.profileState === 'ACTIVE' ? `missing ${st.missing} device(s)` : 'invalid'}; profiles cannot be changed, so a new one is created`);
newName = `${name} ${new Date().toISOString().slice(0, 10)}`;
}
const classes = new Map<string, number>();
@ -124,7 +131,10 @@ async function profile(ctx: Ctx, c: () => Promise<Asc>): Promise<void> {
log(TAG, `plan: create IOS_APP_ADHOC "${newName}" for ${bundleId}: ${devices.length} devices (${[...classes].map(([k, v]) => `${v} ${k}`).join(', ')}), ${certs.length} distribution certificate(s)`);
if (ctx.args.has('dry')) { log(TAG, 'dry run: nothing created'); return; }
if (!(await confirm(ctx, `Create the ad-hoc provisioning profile "${newName}"?`))) { log(TAG, 'not confirmed, nothing created'); return; }
const res = (await api.asc('POST', '/v1/profiles', profileCreateReq(newName, bid.id, certs, want))).data;
if (existing.some((p: J) => p.attributes.name === newName)) newName = `${name} ${new Date().toISOString().slice(0, 16).replace('T', ' ').replace(':', '-')}`;
const res = (await createOnce<J>({ what: `profile "${newName}"`, tag: TAG,
find: async () => (await api.all(`/v1/bundleIds/${bid.id}/profiles?limit=200`)).find((p: J) => p.attributes?.name === newName) ?? null,
create: async () => (await api.asc('POST', '/v1/profiles', profileCreateReq(newName, bid.id, certs, want))).data })).value;
const content = res?.attributes?.profileContent as string | undefined;
if (content) {
const out = resolve(`build/adhoc/${newName.replace(/[^\w.-]+/g, '_')}.mobileprovision`);

View file

@ -4,6 +4,7 @@ import { createHash, createPrivateKey, sign } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { ascKey } from '../lib/credentials';
import { errorBody } from '../lib/http';
import { AmbiguousWriteError, retrySafe } from '../lib/upsert';
const b64 = (b: Buffer | string): string => Buffer.from(b).toString('base64url');
export const md5 = (b: Buffer | Uint8Array): string => createHash('md5').update(b).digest('hex');
@ -24,6 +25,14 @@ export function setUpToDate(existing: { checksum?: string | null; state?: string
return existing.length === want.length && existing.every((e, i) => e.checksum === want[i] && DELIVERED.includes(e.state ?? ''));
}
/** How many leading assets of a set already hold the wanted files (same MD5 at the same position, delivered): those
* stay when the set is synced. Pure. */
export function keptPrefix(existing: { checksum?: string | null; state?: string | null }[], want: string[]): number {
let k = 0;
while (k < existing.length && k < want.length && existing[k]!.checksum === want[k] && DELIVERED.includes(existing[k]!.state ?? '')) k++;
return k;
}
/** Cached ES256 token getter for the team API key (env or .storebound/): valid 18 minutes, renewed after 15. Shared by
* ascClient and the generic `storebound api apple` client (cli/api/client.ts). */
export function ascJwt(root: string): { jwt: () => string; keyId: string } {
@ -45,12 +54,28 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri
const k = ascJwt(root);
const jwt = k.jwt;
/**
* One API request. 429 is retried (the request was refused, not applied). 5xx and network errors are retried only
* for requests that end the same when sent twice (retrySafe: GET, PATCH, DELETE, relationship adds, the "create or
* replace" singletons); a POST create then throws AmbiguousWriteError instead, so callers look before they create
* again (cli/lib/upsert.ts). A DELETE answered 404 after a retry was applied by the first attempt.
*/
async function asc(method: string, path: string, body?: unknown, attempt = 1): Promise<J> {
const r = await fetch(path.startsWith('http') ? path : 'https://api.appstoreconnect.apple.com' + path, {
method, headers: { Authorization: 'Bearer ' + jwt(), 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined,
});
const safe = retrySafe(method, path);
let r: Response;
try {
r = await fetch(path.startsWith('http') ? path : 'https://api.appstoreconnect.apple.com' + path, {
method, headers: { Authorization: 'Bearer ' + jwt(), 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined,
});
} catch (e) {
if (safe && attempt < 5) { await Bun.sleep(2000 * attempt); return asc(method, path, body, attempt + 1); }
if (!safe) throw new AmbiguousWriteError(`${method} ${path} -> no answer (${(e as Error).message})`);
throw e;
}
const t = await r.text();
if ((r.status >= 500 || r.status === 429) && attempt < 5) { await Bun.sleep(2000 * attempt); return asc(method, path, body, attempt + 1); }
if ((r.status === 429 || (r.status >= 500 && safe)) && attempt < 5) { await Bun.sleep(2000 * attempt); return asc(method, path, body, attempt + 1); }
if (r.status >= 500 && !safe) throw new AmbiguousWriteError(`${method} ${path} -> ${r.status} ${errorBody(t)}`, r.status);
if (r.status === 404 && method === 'DELETE' && attempt > 1) return {};
if (!r.ok) throw new Error(`${method} ${path} -> ${r.status} ${errorBody(t)}`);
return t ? JSON.parse(t) : {};
}
@ -127,5 +152,38 @@ export async function ascClient(root: string, bundleId: string, appIdHint?: stri
return res.id;
}
return { asc, all, maybe, getAs, bytes, app, editableVersion, editableAppInfo, uploadAsset, keyId: k.keyId };
/**
* Makes a screenshot or preview set hold exactly `files`, in this order, touching as little as possible: the leading
* assets that already match stay, everything after them is deleted, the rest is uploaded in order. A crash midway
* leaves a prefix of the wanted files (plus maybe one half-uploaded asset), which the next run keeps or removes, so
* re-runs converge and never duplicate. A reservation with an unknown outcome is cleaned up (the set is read again and
* any asset this run does not know is deleted) and sent once more. At the end the order is read back and, if Apple
* shows another one, set through the set's relationship.
*/
async function syncAssets(o: { set: { type: 'appScreenshotSets' | 'appPreviewSets'; id: string }; existing: J[]; files: string[]; want: string[];
state: (x: J) => string | undefined; attrs?: (file: string) => Record<string, unknown>; onUpload?: (file: string) => void }): Promise<{ uploaded: number; removed: number; kept: number }> {
const asset = o.set.type === 'appScreenshotSets' ? 'appScreenshots' : 'appPreviews';
const rel = { [o.set.type === 'appScreenshotSets' ? 'appScreenshotSet' : 'appPreviewSet']: { data: { type: o.set.type, id: o.set.id } } };
const k = keptPrefix(o.existing.map(x => ({ checksum: x.attributes?.sourceFileChecksum, state: o.state(x) })), o.want);
const ids: string[] = o.existing.slice(0, k).map(x => x.id);
const extra = o.existing.slice(k);
for (const x of extra) await asc('DELETE', `/v1/${asset}/${x.id}`);
for (const f of o.files.slice(k)) {
o.onUpload?.(f);
try { ids.push(await uploadAsset(asset, rel, f, o.attrs?.(f) ?? {})); } catch (e) {
if (!(e as { ambiguous?: boolean }).ambiguous) throw e;
// the reservation may exist: remove whatever this run does not know, then upload this file once more
for (const x of await all(`/v1/${o.set.type}/${o.set.id}/${asset}?limit=50`)) if (!ids.includes(x.id)) await asc('DELETE', `/v1/${asset}/${x.id}`);
ids.push(await uploadAsset(asset, rel, f, o.attrs?.(f) ?? {}));
}
}
if (o.files.length > k) {
const now = (await all(`/v1/${o.set.type}/${o.set.id}/${asset}?limit=50`)).map(x => x.id as string);
if (now.join() !== ids.join() && ids.every(id => now.includes(id)))
await asc('PATCH', `/v1/${o.set.type}/${o.set.id}/relationships/${asset}`, { data: ids.map(id => ({ type: asset, id })) });
}
return { uploaded: o.files.length - k, removed: extra.length, kept: k };
}
return { asc, all, maybe, getAs, bytes, app, editableVersion, editableAppInfo, uploadAsset, syncAssets, keyId: k.keyId };
}

View file

@ -5,6 +5,7 @@
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
import { done, log } from '../lib/log';
import { createOnce } from '../lib/upsert';
import { ascClient } from './asc';
export async function run(ctx: Ctx): Promise<void> {
@ -16,8 +17,11 @@ export async function run(ctx: Ctx): Promise<void> {
if (found.length) { log('apple', `bundle id ${bundleId} already registered (${found[0].attributes.platform})`); }
else if (ctx.args.has('dry')) { log('apple', `bundle id ${bundleId} missing (dry run, not registering)`); return; }
else {
await c.asc('POST', '/v1/bundleIds', { data: { type: 'bundleIds', attributes: { identifier: bundleId, name: ctx.args.str('name', config.app.name).replace(/[^A-Za-z0-9 ]/g, ' ').trim(), platform: 'IOS' } } });
log('apple', `bundle id ${bundleId} registered`);
// identifiers are unique per team: a 409 (or an unclear answer) is checked by a direct lookup, never re-sent blindly
const r = await createOnce({ what: `bundle id ${bundleId}`, tag: 'apple', unique: true,
find: async () => (await c.asc('GET', `/v1/bundleIds?filter[identifier]=${encodeURIComponent(bundleId)}`)).data?.find((b: { attributes: { identifier: string } }) => b.attributes.identifier === bundleId) ?? null,
create: async () => (await c.asc('POST', '/v1/bundleIds', { data: { type: 'bundleIds', attributes: { identifier: bundleId, name: ctx.args.str('name', config.app.name).replace(/[^A-Za-z0-9 ]/g, ' ').trim(), platform: 'IOS' } } })).data });
log('apple', `bundle id ${bundleId} ${r.created ? 'registered' : 'already registered'}`);
}
const apps = (await c.asc('GET', `/v1/apps?filter[bundleId]=${encodeURIComponent(bundleId)}`)).data;
if (apps.length) log('apple', `app record: ${apps[0].attributes.name} (Apple ID ${apps[0].id}); put it in apple.appId`);

View file

@ -18,6 +18,8 @@ import { numberedImages } from '../play/images';
import { variantRoot } from '../shots/lib';
import { type Asc, ascClient, type J } from './asc';
import { describeReq, execute, one, type Req } from './jsonapi';
import { addItem, draftSubmission, findDraft } from './submission';
import { findOrCreate, getById } from '../lib/upsert';
import { displaySets, syncScreenshotSet } from './screenshots';
const TAG = 'cpp';
@ -35,11 +37,6 @@ async function pagesOf(c: Asc, appId: string): Promise<Page[]> {
return out;
}
/** A draft review submission of the app (READY_FOR_REVIEW), or the request that creates one. */
async function draftSubmission(c: Asc, appId: string): Promise<string | null> {
return (await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&filter[platform]=IOS&filter[state]=READY_FOR_REVIEW&limit=10`))[0]?.id ?? null;
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const a = ctx.args;
@ -82,7 +79,18 @@ export async function run(ctx: Ctx): Promise<void> {
if (pages.length + reqs.filter(r => r.path === '/v1/appCustomProductPages').length > CPP_LIMITS.pages) throw new Error(`more than ${CPP_LIMITS.pages} custom product pages`);
if (a.has('json')) printJson({ dryRun: dry, requests: reqs.map(r => describeReq(r)) });
if (!reqs.length) { done(TAG, 'custom product pages up to date'); return; }
await execute(c.asc, reqs, { dry, tag: TAG });
if (dry) { await execute(c.asc, reqs, { dry, tag: TAG }); done(TAG, `dry run: ${reqs.length} change(s)`); return; }
// page names are not known to be unique on Apple's side: each new page is looked up right before it is created
// (fresh list, then the journal of recent creates for the list lag) and never sent twice
for (const r of reqs) {
if (r.path !== '/v1/appCustomProductPages') { await execute(c.asc, [r], { dry, tag: TAG }); continue; }
const name = (r.body as J).data.attributes.name as string;
const made = await findOrCreate<J>({ what: `custom product page "${name}"`, tag: TAG,
find: async () => (await c.all(`/v1/apps/${appId}/appCustomProductPages?limit=200`)).find((p: J) => p.attributes.name === name) ?? null,
journal: { root, key: `apple:${appId}:cpp:${name}`, byId: id => getById(c.asc, `/v1/appCustomProductPages/${id}`) as Promise<J | null>, idOf: v => v.id },
create: async () => (await c.asc('POST', r.path, r.body)).data });
log(TAG, `${describeReq(r)}: ${made.created ? 'done' : 'exists already'}`);
}
done(TAG, dry ? `dry run: ${reqs.length} change(s)` : `${reqs.length} change(s); next: storebound apple cpp upload --name "<page>"`);
return;
}
@ -117,13 +125,13 @@ export async function run(ctx: Ctx): Promise<void> {
const { def, page } = pick();
if (!page?.version) throw new Error(`"${def.name}" is not on App Store Connect yet (storebound apple cpp create)`);
if (!['PREPARE_FOR_SUBMISSION', 'REJECTED'].includes(page.version.state)) { done(TAG, `"${def.name}": version is ${page.version.state}, nothing to submit`); return; }
const draft = await draftSubmission(c, appId);
const draft = await findDraft(c, appId);
const create: Req = { method: 'POST', path: '/v1/reviewSubmissions', note: 'new draft review submission', body: { data: { type: 'reviewSubmissions', attributes: { platform: 'IOS' }, relationships: { app: one('apps', appId) } } } };
const item = reviewItemReq(draft ?? '${submission}', 'appCustomProductPageVersion', page.version.id, `custom product page "${def.name}"`);
if (dry) { await execute(c.asc, [...(draft ? [] : [create]), item, { method: 'PATCH', path: `/v1/reviewSubmissions/${draft ?? '${submission}'}`, note: 'submit for App Review' }], { dry, tag: TAG }); return; }
if (!(await confirm(ctx, `Send custom product page "${def.name}" to App Review now?`))) return;
const sid = draft ?? ((await c.asc('POST', create.path, create.body)).data.id as string);
await c.asc('POST', item.path, reviewItemReq(sid, 'appCustomProductPageVersion', page.version.id, '').body);
const sid = draft ?? await draftSubmission(c, appId, root, TAG);
await addItem(c, sid, 'appCustomProductPageVersion', page.version.id, `custom product page "${def.name}"`, TAG);
await c.asc('PATCH', `/v1/reviewSubmissions/${sid}`, { data: { type: 'reviewSubmissions', id: sid, attributes: { submitted: true } } });
done(TAG, `"${def.name}" submitted (review submission ${sid}); after approval: storebound apple cpp visible --name "${def.name}"`);
return;

View file

@ -15,6 +15,8 @@ import { textTable } from '../lib/table';
import { imageInfo } from '../shots/spec';
import { ascClient, type J } from './asc';
import { describeReq, execute, one, type Req } from './jsonapi';
import { addItem, draftSubmission } from './submission';
import { findOrCreate, getById } from '../lib/upsert';
const TAG = 'events';
const USAGE = 'usage: storebound apple events list | create [--name n] | upload --name n | submit --name n';
@ -69,11 +71,21 @@ export async function run(ctx: Ctx): Promise<void> {
done(TAG, 'dry run: nothing changed');
return;
}
const out = await execute(c.asc, reqs, { dry: false, tag: TAG }) as J[];
for (const x of created) {
const id = out[x.index].data.id as string;
// reference names are not known to be unique on Apple's side: each new event is looked up right before it is
// created (fresh list, then the journal of recent creates for the list lag) and never sent twice
for (const [i, r] of reqs.entries()) {
const x = created.find(e => e.index === i);
if (!x) { await execute(c.asc, [r], { dry: false, tag: TAG }); continue; }
const name = x.def.referenceName;
const made = await findOrCreate<J>({ what: `in-app event "${name}"`, tag: TAG,
find: async () => (await c.all(`/v1/apps/${appId}/appEvents?limit=200`)).find((e: J) => e.attributes.referenceName === name) ?? null,
journal: { root, key: `apple:${appId}:event:${name}`, byId: id => getById(c.asc, `/v1/appEvents/${id}`) as Promise<J | null>, idOf: v => v.id },
create: async () => (await c.asc('POST', r.path, r.body)).data });
log(TAG, `${describeReq(r)}: ${made.created ? 'done' : 'exists already'}`);
const id = made.value.id as string;
const want = Object.entries(x.def.listings).flatMap(([lang, t]) => { const locale = localeOf(lang); return locale ? [{ locale, ...t }] : []; });
await execute(c.asc, planEventLocales(id, [], want), { dry: false, tag: TAG });
const have = made.created ? [] : (await c.all(`/v1/appEvents/${id}/localizations?limit=200`)).map((l: J) => ({ id: l.id, ...l.attributes }));
await execute(c.asc, planEventLocales(id, have, want), { dry: false, tag: TAG });
}
done(TAG, 'in-app events created / updated; next: storebound apple events upload --name "<event>"');
return;
@ -96,7 +108,7 @@ export async function run(ctx: Ctx): Promise<void> {
const info = imageInfo(readFileSync(file));
const problems = checkEventMedia(kind, info.w, info.h, info.format);
if (problems.length) throw new Error(`${file}: ${problems.join('; ')}`);
if (have.some((s: J) => s.attributes.appEventAssetType === kind && s.attributes.fileSize === info.bytes)) { log(TAG, `${loc.attributes.locale} ${kind}: up to date`); continue; }
if (have.some((s: J) => s.attributes.appEventAssetType === kind && s.attributes.fileSize === info.bytes && ['COMPLETE', 'UPLOAD_COMPLETE'].includes(s.attributes.assetDeliveryState?.state ?? 'COMPLETE'))) { log(TAG, `${loc.attributes.locale} ${kind}: up to date`); continue; }
if (dry) { log(TAG, `${loc.attributes.locale} ${kind}: would upload ${file} (${info.w}x${info.h})`); n++; continue; }
for (const s of have.filter((x: J) => x.attributes.appEventAssetType === kind)) await c.asc('DELETE', `/v1/appEventScreenshots/${s.id}`);
await c.uploadAsset('appEventScreenshots', { appEventLocalization: { data: { type: 'appEventLocalizations', id: loc.id } } }, file, { appEventAssetType: kind });
@ -116,8 +128,8 @@ export async function run(ctx: Ctx): Promise<void> {
const create: Req = { method: 'POST', path: '/v1/reviewSubmissions', note: 'new draft review submission', body: { data: { type: 'reviewSubmissions', attributes: { platform: 'IOS' }, relationships: { app: one('apps', appId) } } } };
if (dry) { await execute(c.asc, [...(draft ? [] : [create]), reviewItemReq(draft ?? '${submission}', 'appEvent', ev.id, `in-app event "${def.referenceName}"`), { method: 'PATCH', path: `/v1/reviewSubmissions/${draft ?? '${submission}'}`, note: 'submit for App Review' }], { dry, tag: TAG }); return; }
if (!(await confirm(ctx, `Send in-app event "${def.referenceName}" to App Review? Once approved it is published on ${def.schedule.publishStart} by its schedule.`))) return;
const sid = draft ?? ((await c.asc('POST', create.path, create.body)).data.id as string);
await c.asc('POST', '/v1/reviewSubmissionItems', reviewItemReq(sid, 'appEvent', ev.id, '').body);
const sid = draft ?? await draftSubmission(c, appId, root, TAG);
await addItem(c, sid, 'appEvent', ev.id, `in-app event "${def.referenceName}"`, TAG);
await c.asc('PATCH', `/v1/reviewSubmissions/${sid}`, { data: { type: 'reviewSubmissions', id: sid, attributes: { submitted: true } } });
done(TAG, `"${def.referenceName}" submitted (review submission ${sid})`);
return;

View file

@ -14,6 +14,7 @@ import { allSubscriptions } from '../lib/subscriptions';
import { bindIds, latestVersion, newVersionReq, type PIap, planIapSubmission, type PSub, type SubmitState, versionsOf } from '../lib/review-submit';
import { type Asc, ascClient, type J } from './asc';
import { describeReq, execute } from './jsonapi';
import { addItem, draftSubmission } from './submission';
const TAG = 'iap-submit';
@ -95,10 +96,18 @@ export async function run(ctx: Ctx): Promise<void> {
}
const what = `${plan.items.length} item(s)${plan.appVersion ? `, including app version ${plan.appVersion.versionString}` : ''}`;
if (!(await confirm(ctx, `Add ${what} to ${state.draft ? 'the draft' : 'a new draft'} review submission?`))) return;
let sid = state.draft?.id;
// the draft is reused (or created once); the plan left out items already in it (readSubmitState read them), and an
// item the store says is in there already (409) is not added twice (cli/apple/submission.ts)
const sid = state.draft?.id ?? await draftSubmission(c, appId, root, TAG);
for (const r of prepare) {
const out = await c.asc(r.method, r.path, bindIds(r, { submission: sid }).body);
if (r.path === '/v1/reviewSubmissions') sid = out.data.id;
if (r.path === '/v1/reviewSubmissions') continue;
if (r.path === '/v1/reviewSubmissionItems') {
const rels = (r.body as J).data.relationships as Record<string, { data: { id: string } }>;
const kind = Object.keys(rels).find(k => k !== 'reviewSubmission')!;
if (await addItem(c, sid, kind, rels[kind]!.data.id, r.note ?? kind, TAG, { checked: true })) log(TAG, `${describeReq(bindIds(r, { submission: sid }))}: done`);
continue;
}
await c.asc(r.method, r.path, bindIds(r, { submission: sid }).body);
log(TAG, `${describeReq(bindIds(r, { submission: sid }))}: done`);
}
if (a.has('no-submit')) { done(TAG, `draft review submission ${sid} ready: press "Submit for Review" in App Store Connect (Apps > Distribution > App Review)`); return; }

View file

@ -15,6 +15,7 @@ import { dryPlan, type PlanRow } from '../lib/dry';
import { done, log, step } from '../lib/log';
import { LAG_HINT, reportMissing } from '../lib/store-lag';
import { appleTerritory, nearestPrices, samePrice } from '../lib/money';
import { createOnce, findOrCreate, getById } from '../lib/upsert';
import { ascClient, type J } from './asc';
/** Product type -> InAppPurchaseType (POST /v2/inAppPurchases). */
@ -44,26 +45,31 @@ export async function run(ctx: Ctx): Promise<void> {
const created: string[] = [];
for (const [i, p] of products.entries()) {
const tag = step(i + 1, products.length, p.id);
const found = await c.asc('GET', `/v1/apps/${appId}/inAppPurchasesV2?filter[productId]=${encodeURIComponent(p.id)}`);
let id: string = found.data[0]?.id;
if (dry) { rows.push(await planProduct(p, id, found.data[0]?.attributes?.state)); continue; }
if (!id) {
const first = Object.values(p.listings)[0]!;
id = (await c.asc('POST', '/v2/inAppPurchases', { data: { type: 'inAppPurchases',
const lookup = async (): Promise<J | null> => (await c.asc('GET', `/v1/apps/${appId}/inAppPurchasesV2?filter[productId]=${encodeURIComponent(p.id)}`)).data
?.find((x: J) => x.attributes?.productId === p.id) ?? null;
if (dry) { const f = await lookup(); rows.push(await planProduct(p, f?.id, f?.attributes?.state)); continue; }
// product ids are unique per app: a 409 finds the existing one; the journal covers the list lag after a create
const first = Object.values(p.listings)[0]!;
const made = await findOrCreate<J>({ what: `in-app purchase ${p.id}`, tag: 'apple', unique: true, find: lookup,
journal: { root, key: `apple:${bundleId}:iap:${p.id}`, byId: id => getById(c.asc, `/v2/inAppPurchases/${id}`) as Promise<J | null>, idOf: v => v.id },
create: async () => (await c.asc('POST', '/v2/inAppPurchases', { data: { type: 'inAppPurchases',
attributes: { name: p.referenceName ?? first.title, productId: p.id, inAppPurchaseType: APPLE_IAP_TYPE[p.type],
familySharable: p.familySharable ?? false, ...(p.reviewNote ? { reviewNote: p.reviewNote } : {}) },
relationships: { app: { data: { type: 'apps', id: appId } } } } })).data.id;
created.push(p.id);
log('apple', `${tag}: created`);
} else log('apple', `${tag}: exists`);
relationships: { app: { data: { type: 'apps', id: appId } } } } })).data });
const id: string = made.value.id;
if (made.created) created.push(p.id);
log('apple', `${tag}: ${made.created ? 'created' : 'exists'}`);
const have = new Set((await c.all(`/v2/inAppPurchases/${id}/inAppPurchaseLocalizations`)).map((l: J) => l.attributes.locale));
const locsOf = async () => await c.all(`/v2/inAppPurchases/${id}/inAppPurchaseLocalizations`);
const have = new Set((await locsOf()).map((l: J) => l.attributes.locale));
for (const [langId, l] of Object.entries(p.listings)) {
const locale = langs.get(langId)?.apple;
if (!locale || have.has(locale)) continue;
if ([...l.description].length > APPLE_IAP_LIMITS.description) throw new Error(`${p.id} ${locale}: description over ${APPLE_IAP_LIMITS.description} characters (Apple limit)`);
await c.asc('POST', '/v1/inAppPurchaseLocalizations', { data: { type: 'inAppPurchaseLocalizations', attributes: { locale, name: l.title, description: l.description },
relationships: { inAppPurchaseV2: { data: { type: 'inAppPurchases', id } } } } });
await createOnce({ what: `${p.id} localization ${locale}`, tag: 'apple', unique: true,
find: async () => (await locsOf()).find((x: J) => x.attributes.locale === locale) ?? null,
create: async () => (await c.asc('POST', '/v1/inAppPurchaseLocalizations', { data: { type: 'inAppPurchaseLocalizations', attributes: { locale, name: l.title, description: l.description },
relationships: { inAppPurchaseV2: { data: { type: 'inAppPurchases', id } } } } })).data });
log('apple', ` localization ${locale}`);
}

View file

@ -1,6 +1,7 @@
// JSON:API request builders for App Store Connect. Pure: commands build `Req`s, print them on --dry and send them
// with the client otherwise. Request / response format: https://developer.apple.com/documentation/appstoreconnectapi
import { log } from '../lib/log';
import { log, warn } from '../lib/log';
import { isAmbiguous, isConflict } from '../lib/upsert';
export interface Req { method: 'GET' | 'POST' | 'PATCH' | 'DELETE'; path: string; body?: unknown; note?: string }
@ -16,13 +17,23 @@ export function describeReq(r: Req, hide: string[] = ['email', 'demoAccountPassw
return `${r.method} ${r.path}${keys.length ? ` {${keys.join(', ')}}` : ''}${r.note ? ` # ${r.note}` : ''}`;
}
/** Logs every planned request; sends them in order unless dry. Returns the responses (empty on dry). */
/**
* Logs every planned request; sends them in order unless dry. Returns the responses (empty on dry). The plans come
* from a fresh read of the store, so a create the store refuses as a duplicate (409 already exists) means an earlier
* run made it: it is logged and skipped (its slot in the result is null), never sent again. A create with an unknown
* outcome (timeout, 5xx) stops the run without a retry: running the command again reads the store and plans only
* what is still missing.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export async function execute(asc: (m: string, p: string, b?: unknown) => Promise<any>, reqs: Req[], o: { dry: boolean; tag: string }): Promise<unknown[]> {
const out: unknown[] = [];
for (const r of reqs) {
for (const [i, r] of reqs.entries()) {
if (o.dry) { log(o.tag, `would ${describeReq(r)}`); continue; }
out.push(await asc(r.method, r.path, r.body));
try { out.push(await asc(r.method, r.path, r.body)); } catch (e) {
if (r.method === 'POST' && isConflict(e)) { warn(o.tag, `${describeReq(r)}: already exists, left as it is`); out.push(null); continue; }
if (isAmbiguous(e)) throw new Error(`${describeReq(r)}: no clear answer (${(e as Error).message.slice(0, 200)}). Not sent again, so nothing is created twice; ${reqs.length - i - 1} later request(s) not sent. Run the command again: it reads the store and does only what is still missing.`);
throw e;
}
log(o.tag, `${describeReq(r)}: done`);
}
return out;

View file

@ -16,12 +16,13 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { type AppleCopy, parseAppStoreListing } from '../lib/copy';
import { compactDiff } from '../lib/diff';
import { mergeAppleListing, overLimits } from '../lib/listing-pull';
import { counts, draftReason, draftSections, type ItemPlan, itemLines, planLocales, planVersion, short, type Skipped, type VersionPlan } from '../lib/listing-plan';
import { counts, draftReason, draftSections, type ItemPlan, itemLines, planItem, planLocales, planVersion, short, type Skipped, type VersionPlan } from '../lib/listing-plan';
import { createOnce, findOrCreate, getById } from '../lib/upsert';
import { appleName } from '../lib/config';
import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { done, log, printJson, warn } from '../lib/log';
import { ascClient, type J } from './asc';
import { ascClient, EDITABLE, type J } from './asc';
export function readAppleCopy(ctx: Ctx) {
const { config, resolve } = ctx.loaded;
@ -156,15 +157,21 @@ export function listingPlanLines(p: AppleListingPlan): string[] {
return out;
}
async function applyLocales(c: Asc, type: string, parentRel: string, parentType: string, parentId: string, plan: ItemPlan[]): Promise<void> {
async function applyLocales(c: Asc, type: string, parentRel: string, parentType: string, parentId: string, listPath: string, plan: ItemPlan[]): Promise<void> {
const patch = async (key: string, id: string, changes: ItemPlan['changes']) => {
await c.asc('PATCH', `/v1/${type}/${id}`, { data: { type, id, attributes: Object.fromEntries(changes.map(ch => [ch.field, ch.to ?? ''])) } });
log('apple', `${type} ${key}: updated ${changes.map(ch => ch.field).join(', ')}`);
};
for (const l of plan) {
if (l.action === 'create') {
await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { locale: l.key, ...l.attributes }, relationships: { [parentRel]: { data: { type: parentType, id: parentId } } } } });
log('apple', `${type} ${l.key}: created`);
} else if (l.action === 'update') {
await c.asc('PATCH', `/v1/${type}/${l.id}`, { data: { type, id: l.id, attributes: Object.fromEntries(l.changes.map(ch => [ch.field, ch.to ?? ''])) } });
log('apple', `${type} ${l.key}: updated ${l.changes.map(ch => ch.field).join(', ')}`);
}
// a locale is unique per parent: a 409 (or a lost answer) finds the existing one, which is then updated, never created twice
const made = await createOnce<J>({ what: `${type} ${l.key}`, tag: 'apple', unique: true,
find: async () => (await c.all(`${listPath}?limit=200`)).find((x: J) => x.attributes.locale === l.key) ?? null,
create: async () => (await c.asc('POST', `/v1/${type}`, { data: { type, attributes: { locale: l.key, ...l.attributes }, relationships: { [parentRel]: { data: { type: parentType, id: parentId } } } } })).data });
if (made.created) { log('apple', `${type} ${l.key}: created`); continue; }
const again = planItem(l.key, { id: made.value.id, attributes: made.value.attributes ?? {} }, l.attributes);
if (again.action === 'update') await patch(l.key, made.value.id, again.changes);
} else if (l.action === 'update') await patch(l.key, l.id!, l.changes);
}
}
@ -189,9 +196,21 @@ export async function run(ctx: Ctx): Promise<void> {
const vp = p.versionPlan;
let versionId = vp.id;
if (vp.action === 'create') {
versionId = (await c.asc('POST', '/v1/appStoreVersions', { data: { type: 'appStoreVersions',
attributes: Object.fromEntries(Object.entries(vp.attributes)), relationships: { app: { data: { type: 'apps', id: appId } } } } })).data.id;
log('apple', `version ${version} created`);
// look again right before the create (another run, or a lost answer), then the journal for the list lag
const made = await findOrCreate<J>({ what: `App Store version ${version}`, tag: 'apple', unique: true,
find: async () => (await c.all(`/v1/apps/${appId}/appStoreVersions?filter[platform]=IOS&limit=50`))
.find((x: J) => x.attributes.versionString === version && EDITABLE.has(x.attributes.appVersionState ?? x.attributes.appStoreState)) ?? null,
journal: { root, key: `apple:${appId}:version:IOS:${version}`, byId: id => getById(c.asc, `/v1/appStoreVersions/${id}`) as Promise<J | null>, idOf: v => v.id },
create: async () => (await c.asc('POST', '/v1/appStoreVersions', { data: { type: 'appStoreVersions',
attributes: Object.fromEntries(Object.entries(vp.attributes)), relationships: { app: { data: { type: 'apps', id: appId } } } } })).data });
versionId = made.value.id;
if (made.created) log('apple', `version ${version} created`);
else {
const { platform: _p, ...want } = vp.attributes;
const again = planItem(version, { id: versionId!, attributes: made.value.attributes ?? {} }, want);
if (again.action === 'update') await c.asc('PATCH', `/v1/appStoreVersions/${versionId}`, { data: { type: 'appStoreVersions', id: versionId, attributes: Object.fromEntries(again.changes.map(ch => [ch.field, ch.to])) } });
log('apple', `version ${version} exists already (an earlier run made it): using it${again.action === 'update' ? `, updated ${again.changes.map(ch => ch.field).join(', ')}` : ''}`);
}
} else if (vp.action === 'update') {
await c.asc('PATCH', `/v1/appStoreVersions/${versionId}`, { data: { type: 'appStoreVersions', id: versionId, attributes: Object.fromEntries(vp.changes.map(ch => [ch.field, ch.to])) } });
log('apple', `version: ${vp.changes.map(ch => `${ch.field} ${ch.from ?? '(none)'} -> ${ch.to}`).join(', ')}`);
@ -200,8 +219,9 @@ export async function run(ctx: Ctx): Promise<void> {
await c.asc('PATCH', `/v1/appStoreVersions/${versionId}/relationships/build`, { data: { type: 'builds', id: p.build.id } });
log('apple', `build ${version} (${p.build.number}) attached`);
}
await applyLocales(c, 'appInfoLocalizations', 'appInfo', 'appInfos', p.appInfo.id, p.appInfo.locales);
const vl = p.versionLocales ?? planLocales(await c.all(`/v1/appStoreVersions/${versionId}/appStoreVersionLocalizations?limit=200`), p.wanted);
await applyLocales(c, 'appStoreVersionLocalizations', 'appStoreVersion', 'appStoreVersions', versionId!, vl);
await applyLocales(c, 'appInfoLocalizations', 'appInfo', 'appInfos', p.appInfo.id, `/v1/appInfos/${p.appInfo.id}/appInfoLocalizations`, p.appInfo.locales);
const vlPath = `/v1/appStoreVersions/${versionId}/appStoreVersionLocalizations`;
const vl = p.versionLocales ?? planLocales(await c.all(`${vlPath}?limit=200`), p.wanted);
await applyLocales(c, 'appStoreVersionLocalizations', 'appStoreVersion', 'appStoreVersions', versionId!, vlPath, vl);
done('apple', 'listing done');
}

View file

@ -17,6 +17,7 @@ import { applePoints, pickPoint } from '../lib/subscriptions';
import { pages } from '../prices';
import { ascClient, type J } from './asc';
import { describeReq, execute, type Req } from './jsonapi';
import { findOrCreate, getById } from '../lib/upsert';
const TAG = 'offer-codes';
@ -60,7 +61,16 @@ export async function run(ctx: Ctx): Promise<void> {
const body = iapOfferCodeBody(iap.id, oc, await prices(oc));
const req: Req = { method: 'POST', path: '/v1/inAppPurchaseOfferCodes', body, note: `${p.id}: campaign "${oc.name}" (${oc.free ? 'free' : `USD ${oc.usd}`}, ${body.included.length} territories)` };
if (dry) log(TAG, `would ${describeReq(req)}`);
else { id = ((await execute(c.asc, [req], { dry, tag: TAG }))[0] as J).data.id; active++; }
else {
// campaign names are not known to be unique: looked up right before the create, never sent twice
const made = await findOrCreate<J>({ what: `${p.id} campaign "${oc.name}"`, tag: TAG,
find: async () => (await c.all(`/v2/inAppPurchases/${iap.id}/offerCodes?limit=200`)).find((x: J) => x.attributes.name === oc.name) ?? null,
journal: { root, key: `apple:${appId}:iapOfferCode:${p.id}:${oc.name}`, byId: x => getById(c.asc, `/v1/inAppPurchaseOfferCodes/${x}`) as Promise<J | null>, idOf: v => v.id },
create: async () => (await c.asc('POST', req.path, req.body)).data });
id = made.value.id;
log(TAG, `${describeReq(req)}: ${made.created ? 'done' : 'exists already'}`);
if (made.created) active++;
}
} else log(TAG, `${p.id}: campaign "${oc.name}" exists (${cur.attributes.active ? 'active' : 'inactive'}, ${cur.attributes.productionCodeCount ?? 0} production codes)`);
const haveCustom = new Set(cur ? (await c.all(`/v1/inAppPurchaseOfferCodes/${cur.id}/customCodes?limit=200`)).map((x: J) => x.attributes.customCode) : []);
for (const cc of oc.customCodes ?? []) if (!haveCustom.has(cc.code)) codeReqs.push({ req: iapCustomCodeReq(id ?? '${new campaign}', cc), product: p.id, campaign: oc.name, oneTime: false });
@ -78,8 +88,8 @@ export async function run(ctx: Ctx): Promise<void> {
if (!(await confirm(ctx, `Create ${codeReqs.length} code request(s) (${codeReqs.map(x => x.req.note).join('; ')})? Codes count against the 1 million per quarter and can be redeemed by anyone who gets them.`))) return;
const dir = resolve('.storebound/offer-codes');
for (const x of codeReqs) {
const out = (await execute(c.asc, [x.req], { dry: false, tag: TAG }))[0] as J;
if (!x.oneTime) continue;
const out = (await execute(c.asc, [x.req], { dry: false, tag: TAG }))[0] as J | null;
if (!x.oneTime || !out) continue;
// the codes of a one-time-use batch (text/csv); saved locally, never printed
const values = await c.bytes(`/v1/inAppPurchaseOfferCodeOneTimeUseCodes/${out.data.id}/values`, 'text/csv');
if (!values) { warn(TAG, `${x.product} "${x.campaign}": codes not ready yet; download them in App Store Connect`); continue; }

View file

@ -21,7 +21,8 @@ import { textTable } from '../lib/table';
import { numberedImages } from '../play/images';
import { variantRoot } from '../shots/lib';
import { type Asc, ascClient, type J } from './asc';
import { execute } from './jsonapi';
import { describeReq, execute } from './jsonapi';
import { findOrCreate, getById } from '../lib/upsert';
import { displaySets, syncScreenshotSet } from './screenshots';
const TAG = 'ppo';
@ -78,12 +79,29 @@ export async function run(ctx: Ctx): Promise<void> {
let exp = pickExperiment(list, name);
if (!exp) {
if (dry) { await execute(c.asc, [createExperimentReq(appId, name, traffic)], { dry, tag: TAG }); log(TAG, `then: ${variants.length} treatment(s) x ${locales.length} locale(s)`); done(TAG, 'create checked (dry run)'); return; }
const r = (await execute(c.asc, [createExperimentReq(appId, name, traffic)], { dry, tag: TAG }))[0] as J;
exp = experimentFromApi(r.data);
// test names are not known to be unique: looked up right before the create (and in the journal), never sent twice
const req = createExperimentReq(appId, name, traffic);
const made = await findOrCreate<J>({ what: `experiment "${name}"`, tag: TAG,
find: async () => (await c.all(`/v1/apps/${appId}/appStoreVersionExperimentsV2?limit=50`)).find((x: J) => x.attributes.name === name && !['COMPLETED', 'STOPPED'].includes(x.attributes.state)) ?? null,
journal: { root, key: `apple:${appId}:ppo:${name}`, byId: id => getById(c.asc, `/v2/appStoreVersionExperiments/${id}`) as Promise<J | null>, idOf: v => v.id },
create: async () => (await c.asc('POST', req.path, req.body)).data });
log(TAG, `${describeReq(req)}: ${made.created ? 'done' : 'exists already'}`);
exp = experimentFromApi(made.value);
} else log(TAG, `experiment "${name}": exists (${exp.state})`);
const ts = await treatments(c, exp.id);
const created = (await execute(c.asc, planTreatments(exp.id, ts.map((t: J) => ({ id: t.id, name: t.attributes.name })), variants), { dry, tag: TAG })) as J[];
const all = [...ts, ...created.map(r => r.data)].filter(t => variants.includes(t.attributes.name));
const planned = planTreatments(exp.id, ts.map((t: J) => ({ id: t.id, name: t.attributes.name })), variants);
const all: J[] = ts.filter((t: J) => variants.includes(t.attributes.name));
if (dry) await execute(c.asc, planned, { dry, tag: TAG });
else for (const r of planned) {
const tname = (r.body as J).data.attributes.name as string;
const expId = exp.id;
const made = await findOrCreate<J>({ what: `treatment "${tname}"`, tag: TAG,
find: async () => (await treatments(c, expId)).find((t: J) => t.attributes.name === tname) ?? null,
journal: { root, key: `apple:${appId}:ppoTreatment:${expId}:${tname}`, byId: id => getById(c.asc, `/v1/appStoreVersionExperimentTreatments/${id}`) as Promise<J | null>, idOf: v => v.id },
create: async () => (await c.asc('POST', r.path, r.body)).data });
log(TAG, `${describeReq(r)}: ${made.created ? 'done' : 'exists already'}`);
all.push(made.value);
}
for (const t of all) await execute(c.asc, planTreatmentLocales(t.id, (await treatmentLocs(c, t.id)).map((l: J) => l.attributes.locale), locales), { dry, tag: TAG });
done(TAG, dry ? 'create checked (dry run)' : `test "${name}" ready: storebound apple ppo upload --variant ${variants[0]}`);
return;

View file

@ -16,7 +16,8 @@ import { done, log, warn } from '../lib/log';
import { ffprobe } from '../shots/report';
import { checkVideo, PREVIEW_RULES, VIDEO_TARGETS } from '../shots/spec';
import { timeCode } from '../shots/video';
import { ascClient, md5, setUpToDate, type J } from './asc';
import { findOrCreate } from '../lib/upsert';
import { ascClient, keptPrefix, md5, setUpToDate, type J } from './asc';
/** Video target folder -> ASC previewType, for this project (iPad only with apple.ipad). */
export const previewSets = (apple: { ipad?: boolean } | undefined): Record<string, string> =>
@ -100,15 +101,22 @@ export async function run(ctx: Ctx): Promise<void> {
log('apple', `${tag}: poster frame ${tc}`);
continue;
}
if (dry) { log('apple', `${tag}: would replace ${existing.length} with ${fs.length}`); continue; }
if (!set) set = (await c.asc('POST', '/v1/appPreviewSets', { data: { type: 'appPreviewSets', attributes: { previewType: type },
relationships: { appStoreVersionLocalization: { data: { type: 'appStoreVersionLocalizations', id: loc.id } } } } })).data;
for (const p of existing) await c.asc('DELETE', `/v1/appPreviews/${p.id}`);
for (const f of fs) {
log('apple', `${tag}: uploading ${f.slice(src.length + 1)}`);
await c.uploadAsset('appPreviews', { appPreviewSet: { data: { type: 'appPreviewSets', id: set.id } } }, f, previewAttrs(f, poster));
const kept = keptPrefix(existing.map(p => ({ checksum: p.attributes.sourceFileChecksum, state: state(p) })), want);
if (dry) { log('apple', `${tag}: would keep ${kept}, replace ${existing.length - kept} with ${fs.length - kept}`); continue; }
if (!set) {
const r = await findOrCreate<J>({ what: `${tag} preview set`, tag: 'apple', unique: true,
find: async () => (await c.all(`/v1/appStoreVersionLocalizations/${loc.id}/appPreviewSets`)).find((s: J) => s.attributes.previewType === type) ?? null,
create: async () => (await c.asc('POST', '/v1/appPreviewSets', { data: { type: 'appPreviewSets', attributes: { previewType: type },
relationships: { appStoreVersionLocalization: { data: { type: 'appStoreVersionLocalizations', id: loc.id } } } } })).data });
set = r.value;
if (!r.created) existing.push(...await c.all(`/v1/appPreviewSets/${set.id}/appPreviews`));
}
log('apple', `${tag}: uploaded ${fs.length} (removed ${existing.length})`);
const r = await c.syncAssets({ set: { type: 'appPreviewSets', id: set.id }, existing, files: fs, want, state, attrs: f => previewAttrs(f, poster),
onUpload: f => log('apple', `${tag}: uploading ${f.slice(src.length + 1)}`) });
const tc = timeCode(poster);
for (const p of existing.slice(0, r.kept).filter(p => p.attributes.previewFrameTimeCode && p.attributes.previewFrameTimeCode !== tc))
await c.asc('PATCH', `/v1/appPreviews/${p.id}`, { data: { type: 'appPreviews', id: p.id, attributes: { previewFrameTimeCode: tc } } });
log('apple', `${tag}: uploaded ${r.uploaded}${r.kept ? `, kept ${r.kept}` : ''} (removed ${r.removed})`);
}
}
if (dry) return done('apple', 'previews checked (dry run, nothing sent)');

View file

@ -10,6 +10,7 @@ import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { done, log } from '../lib/log';
import { type PhasedAction, phasedRequest } from '../lib/release';
import { createOnce } from '../lib/upsert';
import { ascClient, type J } from './asc';
export async function run(ctx: Ctx): Promise<void> {
@ -50,8 +51,11 @@ export async function run(ctx: Ctx): Promise<void> {
if (dry) { log('apple', `${tag}: would ${req.method === 'POST' ? 'turn phased release on' : `set phased release ${req.state}`} (dry)`); return; }
if ((phased === 'resume' || phased === 'complete') && !(await confirm(ctx, `${phased === 'complete' ? 'Release' : 'Resume the phased release of'} ${tag} ${phased === 'complete' ? 'to every user now' : ''}?`))) return;
if (req.method === 'POST') {
await c.asc('POST', '/v1/appStoreVersionPhasedReleases', { data: { type: 'appStoreVersionPhasedReleases',
relationships: { appStoreVersion: { data: { type: 'appStoreVersions', id: v.id } } } } });
// one phased release per version: a 409 or an unclear answer is checked by reading it back, never re-sent blindly
await createOnce({ what: `phased release of ${tag}`, tag: 'apple', unique: true,
find: async () => (await c.maybe(`/v1/appStoreVersions/${v.id}/appStoreVersionPhasedRelease`))?.data ?? null,
create: async () => (await c.asc('POST', '/v1/appStoreVersionPhasedReleases', { data: { type: 'appStoreVersionPhasedReleases',
relationships: { appStoreVersion: { data: { type: 'appStoreVersions', id: v.id } } } } })).data });
} else {
await c.asc('PATCH', `/v1/appStoreVersionPhasedReleases/${cur!.id}`, { data: { type: 'appStoreVersionPhasedReleases', id: cur!.id, attributes: { phasedReleaseState: req.state } } });
}

View file

@ -10,6 +10,7 @@ import { need } from '../lib/ctx';
import { reviewContact, reviewDemoAccount } from '../lib/credentials';
import { reviewDetailPlan } from '../lib/review-details';
import { done, log } from '../lib/log';
import { createOnce } from '../lib/upsert';
import { ascClient } from './asc';
export async function run(ctx: Ctx): Promise<void> {
@ -34,9 +35,17 @@ export async function run(ctx: Ctx): Promise<void> {
const { attributes, summary } = reviewDetailPlan(config, contact, reviewDemoAccount(root));
if (ctx.args.has('dry')) { log('apple', `would set review details (contact ${from ? 'copied from ' + from : 'from credentials'}, ${summary})`); return; }
const cur = (await c.maybe(`/v1/appStoreVersions/${version.id}/appStoreReviewDetail`))?.data;
if (cur) await c.asc('PATCH', `/v1/appStoreReviewDetails/${cur.id}`, { data: { type: 'appStoreReviewDetails', id: cur.id, attributes } });
else await c.asc('POST', '/v1/appStoreReviewDetails', { data: { type: 'appStoreReviewDetails', attributes,
relationships: { appStoreVersion: { data: { type: 'appStoreVersions', id: version.id } } } } });
const read = async () => (await c.maybe(`/v1/appStoreVersions/${version.id}/appStoreReviewDetail`))?.data ?? null;
const cur = await read();
// one review detail per version: only changed fields are sent; a new one is created once (a 409 finds it)
const changed = cur ? Object.fromEntries(Object.entries(attributes).filter(([k, v]) => (cur.attributes?.[k] ?? null) !== (v ?? null))) : attributes;
if (cur && !Object.keys(changed).length) { done('apple', `review details on ${version.attributes.versionString} up to date (${summary})`); return; }
if (cur) await c.asc('PATCH', `/v1/appStoreReviewDetails/${cur.id}`, { data: { type: 'appStoreReviewDetails', id: cur.id, attributes: changed } });
else {
const r = await createOnce({ what: 'App Review details', tag: 'apple', unique: true, find: read,
create: async () => (await c.asc('POST', '/v1/appStoreReviewDetails', { data: { type: 'appStoreReviewDetails', attributes,
relationships: { appStoreVersion: { data: { type: 'appStoreVersions', id: version.id } } } } })).data });
if (!r.created) await c.asc('PATCH', `/v1/appStoreReviewDetails/${r.value.id}`, { data: { type: 'appStoreReviewDetails', id: r.value.id, attributes } });
}
done('apple', `review details set on ${version.attributes.versionString} (${summary})`);
}

View file

@ -14,7 +14,8 @@ import { byAppleLocale, need } from '../lib/ctx';
import { done, log, warn } from '../lib/log';
import { numberedImages } from '../play/images';
import { variantRoot } from '../shots/lib';
import { type Asc, ascClient, md5, setUpToDate, type J } from './asc';
import { findOrCreate } from '../lib/upsert';
import { type Asc, ascClient, keptPrefix, md5, setUpToDate, type J } from './asc';
/** Render size key -> ASC screenshotDisplayType (iPhone sets). */
export const DISPLAY: Record<string, string> = { ios69: 'APP_IPHONE_67', ios65: 'APP_IPHONE_65' };
@ -33,19 +34,32 @@ export const displaySets = (apple: { ipad?: boolean; iphoneMedium?: boolean } |
export const requiredDisplayTypes = (apple: { ipad?: boolean; screenshotTypes?: string[] } | undefined): string[] =>
apple?.screenshotTypes ?? ['APP_IPHONE_67', ...(apple?.ipad ? ['APP_IPAD_PRO_3GEN_129'] : [])];
/** Makes one screenshot set (of a version localization, or of a Product Page Optimization treatment localization)
* hold exactly `files`, in order: left alone when the MD5s match, else emptied and re-uploaded. Creates the set. */
/** Makes one screenshot set (of a version localization, a custom product page localization or a Product Page
* Optimization treatment localization) hold exactly `files`, in order: left alone when the MD5s match, else the
* matching leading screenshots stay and the rest is replaced (c.syncAssets). The set is created when missing, after a
* fresh look (one set per display type: a 409 finds the existing one). */
export async function syncScreenshotSet(c: Asc, parent: { rel: string; type: string; id: string }, sets: J[], type: string, files: string[], tag: string, dry: boolean): Promise<void> {
let set = sets.find(s => s.attributes.screenshotDisplayType === type);
const existing = set ? await c.all(`/v1/appScreenshotSets/${set.id}/appScreenshots`) : [];
const existing = set ? await c.all(`/v1/appScreenshotSets/${set.id}/appScreenshots?limit=50`) : [];
const want = files.map(f => md5(readFileSync(f)));
if (set && setUpToDate(existing.map(s => ({ checksum: s.attributes.sourceFileChecksum, state: s.attributes.assetDeliveryState?.state })), want)) { log('apple', `${tag}: ${files.length} up to date`); return; }
if (dry) { log('apple', `${tag}: would ${set ? `replace ${existing.length}` : 'create the set and upload'} with ${files.length}`); return; }
if (!set) set = (await c.asc('POST', '/v1/appScreenshotSets', { data: { type: 'appScreenshotSets', attributes: { screenshotDisplayType: type },
relationships: { [parent.rel]: { data: { type: parent.type, id: parent.id } } } } })).data;
for (const s of existing) await c.asc('DELETE', `/v1/appScreenshots/${s.id}`);
for (const f of files) await c.uploadAsset('appScreenshots', { appScreenshotSet: { data: { type: 'appScreenshotSets', id: set.id } } }, f);
log('apple', `${tag}: uploaded ${files.length} (removed ${existing.length})`);
const state = (s: J) => s.attributes.assetDeliveryState?.state;
if (set && setUpToDate(existing.map(s => ({ checksum: s.attributes.sourceFileChecksum, state: state(s) })), want)) { log('apple', `${tag}: ${files.length} up to date`); return; }
if (dry) {
const k = keptPrefix(existing.map(s => ({ checksum: s.attributes.sourceFileChecksum, state: state(s) })), want);
log('apple', `${tag}: would ${set ? `keep ${k}, replace ${existing.length - k}` : 'create the set and upload'} with ${files.length - k} new`);
return;
}
if (!set) {
const find = async () => (await c.all(`/v1/${parent.type}/${parent.id}/appScreenshotSets?limit=50`)).find((s: J) => s.attributes.screenshotDisplayType === type) ?? null;
const r = await findOrCreate<J>({ what: `${tag} screenshot set`, tag: 'apple', unique: true, find,
create: async () => (await c.asc('POST', '/v1/appScreenshotSets', { data: { type: 'appScreenshotSets', attributes: { screenshotDisplayType: type },
relationships: { [parent.rel]: { data: { type: parent.type, id: parent.id } } } } })).data });
set = r.value;
// a set found now (made by an earlier run the first read missed) may already hold screenshots
if (!r.created) existing.push(...await c.all(`/v1/appScreenshotSets/${set.id}/appScreenshots?limit=50`));
}
const r = await c.syncAssets({ set: { type: 'appScreenshotSets', id: set.id }, existing, files, want, state });
log('apple', `${tag}: uploaded ${r.uploaded}${r.kept ? `, kept ${r.kept}` : ''} (removed ${r.removed})`);
}
export async function run(ctx: Ctx): Promise<void> {

View file

@ -23,6 +23,7 @@ import {
import { textTable } from '../lib/table';
import { type Asc, ascClient, type J } from './asc';
import { describeReq, execute, type Req } from './jsonapi';
import { createOnce, isAmbiguous, upsertTiming } from '../lib/upsert';
const TAG = 'signing';
const USAGE = 'usage: storebound apple signing status | ensure [--dry] [--keychain [path]] [--no-install]';
@ -194,9 +195,23 @@ export async function run(ctx: Ctx): Promise<void> {
const csr = buildCsr(key, { commonName: `storebound ${config.app.name}`.slice(0, 64) });
created = (await c.asc('POST', '/v1/certificates', certificateReq(certType, csrContent(csr)).body)).data;
} catch (e) {
rmSync(pending, { force: true });
const why = explainCertError(e, certType);
throw new Error(why ? `${(e as Error).message}\n\n${why}` : (e as Error).message);
if (isAmbiguous(e)) {
// the certificate may exist: it is the one whose public key is this pending key's. The key stays on disk either
// way (a later run finds the certificate through it), so no certificate is ever orphaned or made twice.
const mine = spkiOfKey(readFileSync(pending, 'utf8'));
let found: J | undefined;
for (let i = 0; i < 4 && !found; i++) {
if (i) await upsertTiming.sleep(upsertTiming.waitMs * i);
found = (await c.all(`/v1/certificates?filter[certificateType]=${certType}&limit=200`)).find((x: ApiCert) => !!x.attributes.certificateContent && certSpki(x.attributes.certificateContent) === mine);
}
if (!found) throw new Error(`${(e as Error).message}\n\nThe certificate request got no clear answer and App Store Connect does not list a certificate for the new key (yet). The key is kept in ${pending.replace(root + '/', '')}; run \`storebound apple signing ensure\` again in a minute: it finds the certificate through that key instead of making another one.`);
created = found;
log(TAG, 'the certificate request went through (found by its public key)');
} else {
rmSync(pending, { force: true });
const why = explainCertError(e, certType);
throw new Error(why ? `${(e as Error).message}\n\n${why}` : (e as Error).message);
}
}
const keyFile = join(dir, `${created.id}.key`), cerFile = join(dir, `${created.id}.cer`);
renameSync(pending, keyFile);
@ -212,7 +227,14 @@ export async function run(ctx: Ctx): Promise<void> {
const p = planProfile(list, { bundleId: id, bundleIdId: b.id, certId: cert!.id, type: profileType });
let prof: ApiProfile;
if (p.create) {
const r = (await c.asc('POST', p.create.path, p.create.body)).data;
// an unclear answer is checked by reading the bundle id's profiles again (one active profile with this
// certificate is reused), never re-sent blindly
const r = (await createOnce<J>({ what: `${id} profile`, tag: TAG,
find: async () => {
const again = planProfile(await profilesOf(c, b.id, profileType), { bundleId: id, bundleIdId: b.id, certId: cert!.id, type: profileType });
return again.reuse ? { id: again.reuse.id, attributes: (await c.asc('GET', `/v1/profiles/${again.reuse.id}`)).data.attributes } : null;
},
create: async () => (await c.asc('POST', p.create!.path, p.create!.body)).data })).value;
prof = { id: r.id, attributes: r.attributes };
log(TAG, `${id}: profile "${prof.attributes.name}" created (${prof.attributes.uuid})`);
} else {

47
cli/apple/submission.ts Normal file
View file

@ -0,0 +1,47 @@
// The app's one draft review submission and the items in it, without duplicates: a draft (READY_FOR_REVIEW) is
// reused, a new one is created only after a fresh look (Apple keeps one open draft per app and platform), and an item
// already in the draft is not added again (a 409 or a re-read finds it). Used by iap-submit, cpp submit and events
// submit. Submitting itself (PATCH submitted: true) stays the owner's confirmed step in those commands.
import { log } from '../lib/log';
import { createOnce, findOrCreate } from '../lib/upsert';
import type { Asc, J } from './asc';
import { one } from './jsonapi';
/** The draft review submission of the app (READY_FOR_REVIEW, iOS), or null. */
export async function findDraft(c: Asc, appId: string): Promise<string | null> {
return (await c.all(`/v1/reviewSubmissions?filter[app]=${appId}&filter[platform]=IOS&filter[state]=READY_FOR_REVIEW&limit=10`))[0]?.id ?? null;
}
/** The draft's id: the existing one, else a new draft created once. */
export async function draftSubmission(c: Asc, appId: string, root: string, tag: string): Promise<string> {
const r = await findOrCreate<string>({ what: 'draft review submission', tag, unique: true,
find: () => findDraft(c, appId),
journal: { root, key: `apple:${appId}:reviewSubmission:draft`, idOf: id => id,
byId: async id => { const d = (await c.maybe(`/v1/reviewSubmissions/${id}`))?.data; return d?.attributes?.state === 'READY_FOR_REVIEW' ? id : null; } },
create: async () => (await c.asc('POST', '/v1/reviewSubmissions', { data: { type: 'reviewSubmissions', attributes: { platform: 'IOS' }, relationships: { app: one('apps', appId) } } })).data.id as string });
if (r.created) log(tag, `draft review submission ${r.value} created`);
return r.value;
}
const TYPE: Record<string, string> = {
appStoreVersion: 'appStoreVersions', inAppPurchaseVersion: 'inAppPurchaseVersions', subscriptionVersion: 'subscriptionVersions',
subscriptionGroupVersion: 'subscriptionGroupVersions', appCustomProductPageVersion: 'appCustomProductPageVersions', appEvent: 'appEvents',
appStoreVersionExperiment: 'appStoreVersionExperiments',
};
/** Whether the draft already holds `id` as `kind` (e.g. inAppPurchaseVersion). */
export async function inDraft(c: Asc, sid: string, kind: string, id: string): Promise<boolean> {
const items = await c.all(`/v1/reviewSubmissions/${sid}/items?include=${kind}&limit=200`);
return items.some((it: J) => it.relationships?.[kind]?.data?.id === id);
}
/** Adds one item to the draft unless it is in there already (`checked`: the caller read the draft's items a moment
* ago). true when it was added now. */
export async function addItem(c: Asc, sid: string, kind: string, id: string, label: string, tag: string, o: { checked?: boolean } = {}): Promise<boolean> {
if (!o.checked && await inDraft(c, sid, kind, id)) { log(tag, `${label}: already in draft ${sid}`); return false; }
const r = await createOnce({ what: `${label} in draft ${sid}`, tag, unique: true,
find: async () => ((await inDraft(c, sid, kind, id)) ? id : null),
create: async () => (await c.asc('POST', '/v1/reviewSubmissionItems', { data: { type: 'reviewSubmissionItems',
relationships: { reviewSubmission: one('reviewSubmissions', sid), [kind]: one(TYPE[kind] ?? `${kind}s`, id) } } })).data?.id ?? id });
return r.created;
}

View file

@ -25,7 +25,8 @@ import {
type ApplePoint, pickPoint,
} from '../lib/subscriptions';
import { pages } from '../prices';
import { type Asc, ascClient, type J } from './asc';
import { createOnce, findOrCreate, getById } from '../lib/upsert';
import { type Asc, ascClient, md5, type J } from './asc';
const TAG = 'apple';
@ -68,7 +69,8 @@ export async function run(ctx: Ctx): Promise<void> {
.map(g => ({ ...g, subscriptions: g.subscriptions.filter(s => (!only.length || only.includes(s.id)) && sellsOn(config, s, 'apple')) })).filter(g => g.subscriptions.length);
const dry = ctx.args.has('dry');
const csv = subscriptionCsv(ctx, 'apple');
const c = await ascClient(root, need(config.apple?.bundleId, 'apple.bundleId'), config.apple?.appId);
const bundleId = need(config.apple?.bundleId, 'apple.bundleId');
const c = await ascClient(root, bundleId, config.apple?.appId);
const appId = await c.app();
log(TAG, 'reading subscription groups, subscriptions, localizations, prices, offers');
const state = await readState(c, appId);
@ -87,33 +89,57 @@ export async function run(ctx: Ctx): Promise<void> {
const territories: string[] = (await c.all('/v1/territories?limit=200')).map((t: J) => t.id);
for (const g of groups) {
let gid = state.groups.find(x => x.referenceName === g.name)?.id;
if (!gid) { gid = (await c.asc('POST', '/v1/subscriptionGroups', appleGroupBody(appId, g))).data.id as string; log(TAG, `group "${g.name}" created`); }
const gLocs = state.groups.find(x => x.id === gid)?.locales ?? [];
if (!gid) {
const r = await findOrCreate<J>({ what: `subscription group "${g.name}"`, tag: TAG, unique: true,
find: async () => (await c.all(`/v1/apps/${appId}/subscriptionGroups?limit=200`)).find((x: J) => x.attributes.referenceName === g.name) ?? null,
journal: { root, key: `apple:${bundleId}:subscriptionGroup:${g.name}`, byId: id => getById(c.asc, `/v1/subscriptionGroups/${id}`) as Promise<J | null>, idOf: v => v.id },
create: async () => (await c.asc('POST', '/v1/subscriptionGroups', appleGroupBody(appId, g))).data });
gid = r.value.id as string;
log(TAG, `group "${g.name}" ${r.created ? 'created' : 'exists'}`);
}
const groupId = gid;
const gLocs = state.groups.find(x => x.id === gid)?.locales ?? (await c.all(`/v1/subscriptionGroups/${gid}/subscriptionGroupLocalizations?limit=200`)).map((l: J) => l.attributes.locale);
for (const [lang, l] of Object.entries(g.listings)) {
const loc = locale.get(lang);
if (!loc || gLocs.includes(loc)) continue;
await c.asc('POST', '/v1/subscriptionGroupLocalizations', appleGroupLocBody(gid, loc, l));
await createOnce({ what: `group "${g.name}" ${loc}`, tag: TAG, unique: true,
find: async () => (await c.all(`/v1/subscriptionGroups/${groupId}/subscriptionGroupLocalizations?limit=200`)).find((x: J) => x.attributes.locale === loc) ?? null,
create: async () => (await c.asc('POST', '/v1/subscriptionGroupLocalizations', appleGroupLocBody(groupId, loc, l))).data });
log(TAG, ` group ${loc}`);
}
for (const [i, s] of g.subscriptions.entries()) {
const tag = step(i + 1, g.subscriptions.length, s.id);
const cur = state.subscriptions.find(x => x.productId === s.id);
let id = cur?.id;
if (!id) { id = (await c.asc('POST', '/v1/subscriptions', appleSubscriptionBody(gid, s))).data.id as string; log(TAG, `${tag}: created`); }
let subLocs = cur?.locales;
if (!id) {
const r = await findOrCreate<J>({ what: `subscription ${s.id}`, tag: TAG, unique: true,
find: async () => (await c.all(`/v1/subscriptionGroups/${groupId}/subscriptions?limit=200`)).find((x: J) => x.attributes.productId === s.id) ?? null,
journal: { root, key: `apple:${bundleId}:subscription:${s.id}`, byId: x => getById(c.asc, `/v1/subscriptions/${x}`) as Promise<J | null>, idOf: v => v.id },
create: async () => (await c.asc('POST', '/v1/subscriptions', appleSubscriptionBody(groupId, s))).data });
id = r.value.id as string;
if (!r.created) subLocs = (await c.all(`/v1/subscriptions/${id}/subscriptionLocalizations?limit=200`)).map((l: J) => l.attributes.locale);
log(TAG, `${tag}: ${r.created ? 'created' : 'exists'}`);
}
const subId = id;
for (const [lang, l] of Object.entries(s.listings)) {
const loc = locale.get(lang);
if (!loc || cur?.locales.includes(loc)) continue;
await c.asc('POST', '/v1/subscriptionLocalizations', appleSubLocBody(id, loc, l));
if (!loc || subLocs?.includes(loc)) continue;
await createOnce({ what: `${s.id} ${loc}`, tag: TAG, unique: true,
find: async () => (await c.all(`/v1/subscriptions/${subId}/subscriptionLocalizations?limit=200`)).find((x: J) => x.attributes.locale === loc) ?? null,
create: async () => (await c.asc('POST', '/v1/subscriptionLocalizations', appleSubLocBody(subId, loc, l))).data });
log(TAG, ` ${loc}`);
}
if (!cur?.availability) { await c.asc('POST', '/v1/subscriptionAvailabilities', appleAvailabilityBody(id, territories)); log(TAG, ` available in ${territories.length} territories + new ones`); }
if (!cur?.availability && !(await c.maybe(`/v1/subscriptions/${id}/subscriptionAvailability`))?.data) { await c.asc('POST', '/v1/subscriptionAvailabilities', appleAvailabilityBody(id, territories)); log(TAG, ` available in ${territories.length} territories + new ones`); }
// prices: USA point -> equalizations -> overrides / CSV; only what differs from today's prices
const usaPoints = applePoints(await pages(c, `/v1/subscriptions/${id}/pricePoints?filter[territory]=USA&include=territory&limit=200`));
const usa = pickPoint(usaPoints, 'USA', s.usd);
const equalized = applePoints(await pages(c, `/v1/subscriptionPricePoints/${usa.id}/equalizations?include=territory&limit=200`));
const known: ApplePoint[] = [usa, ...equalized];
const current = cur?.hasPrices ? appleSubPrices(await pages(c, `/v1/subscriptions/${id}/prices?include=subscriptionPricePoint,territory&limit=200`)) : [];
// a subscription the first read missed (list lag) is read live, so nothing is sent twice
const hasPrices = cur ? cur.hasPrices : !!(await c.asc('GET', `/v1/subscriptions/${id}/prices?limit=1`)).data?.length;
const current = hasPrices ? appleSubPrices(await pages(c, `/v1/subscriptions/${id}/prices?include=subscriptionPricePoint,territory&limit=200`)) : [];
const changes = applePriceChanges(current, appleWantedPrices(s, equalized, csv), csv.filter(r => r.product === s.id));
if (!changes.length) log(TAG, ' prices up to date');
else if (current.length && !liveOk) warn(TAG, ` ${changes.length} price change(s) skipped: run in a terminal to confirm`);
@ -140,27 +166,42 @@ export async function run(ctx: Ctx): Promise<void> {
const eq = applePoints(await pages(c, `/v1/subscriptionPricePoints/${ip.id}/equalizations?include=territory&limit=200`));
return [{ territory: 'USA', pointId: ip.id }, ...eq.filter(p => p.territory !== 'USA').map(p => ({ territory: p.territory, pointId: p.id }))];
};
if (s.intro && !cur?.introTerritories) {
if (s.intro && !(cur ? cur.introTerritories : (await c.asc('GET', `/v1/subscriptions/${id}/introductoryOffers?limit=1`)).data?.length)) {
const offers = await offerPrices(s.intro);
await c.asc('PATCH', `/v1/subscriptions/${id}`, appleIntroPatch(id, s, offers));
log(TAG, ` introductory offer in ${offers.length} territories`);
}
for (const o of s.offers ?? []) {
if (cur?.promoOffers?.includes(o.id)) continue;
await c.asc('POST', '/v1/subscriptionPromotionalOffers', applePromoOfferBody(id, s, o, await offerPrices(o)));
log(TAG, ` promotional offer ${o.id}`);
// offer codes (the offer's identifier) are unique per subscription: a 409 finds the existing one
const r = await createOnce({ what: `${s.id} promotional offer ${o.id}`, tag: TAG, unique: true,
find: async () => (await c.all(`/v1/subscriptions/${subId}/promotionalOffers?limit=200`)).find((x: J) => x.attributes.offerCode === o.id) ?? null,
create: async () => (await c.asc('POST', '/v1/subscriptionPromotionalOffers', applePromoOfferBody(subId, s, o, await offerPrices(o)))).data });
if (r.created) log(TAG, ` promotional offer ${o.id}`);
}
for (const oc of s.offerCodes ?? []) {
let ocId: string | undefined;
if (!cur?.offerCodes?.includes(oc.name)) {
ocId = (await c.asc('POST', '/v1/subscriptionOfferCodes', appleOfferCodeBody(id, s, oc, await offerPrices(oc)))).data.id as string;
log(TAG, ` offer code campaign "${oc.name}"`);
// campaign names are not known to be unique: look right before, never send the create twice
const r = await findOrCreate<J>({ what: `${s.id} offer code campaign "${oc.name}"`, tag: TAG,
find: async () => (await c.all(`/v1/subscriptions/${subId}/offerCodes?limit=200`)).find((x: J) => x.attributes.name === oc.name) ?? null,
journal: { root, key: `apple:${bundleId}:subscriptionOfferCode:${s.id}:${oc.name}`, byId: x => getById(c.asc, `/v1/subscriptionOfferCodes/${x}`) as Promise<J | null>, idOf: v => v.id },
create: async () => (await c.asc('POST', '/v1/subscriptionOfferCodes', appleOfferCodeBody(subId, s, oc, await offerPrices(oc)))).data });
ocId = r.value.id as string;
if (r.created) log(TAG, ` offer code campaign "${oc.name}"`);
}
if (oc.customCodes?.length) await customCodes(c, ctx, id, s, oc, ocId);
if (oc.customCodes?.length) await customCodes(c, ctx, subId, s, oc, ocId);
}
if (s.reviewScreenshot && !cur?.reviewScreenshot) {
await c.uploadAsset('subscriptionAppStoreReviewScreenshots', { subscription: { data: { type: 'subscriptions', id } } }, resolve(s.reviewScreenshot));
log(TAG, ` review screenshot ${s.reviewScreenshot}`);
if (s.reviewScreenshot) {
// one screenshot per subscription: kept when Apple has these bytes (MD5) and did not fail them, else replaced
const file = resolve(s.reviewScreenshot);
const shot = cur?.reviewScreenshot || !cur ? (await c.maybe(`/v1/subscriptions/${subId}/appStoreReviewScreenshot`))?.data : null;
const ok = shot && shot.attributes?.sourceFileChecksum === md5(readFileSync(file)) && shot.attributes?.assetDeliveryState?.state !== 'FAILED';
if (!ok) {
if (shot) await c.asc('DELETE', `/v1/subscriptionAppStoreReviewScreenshots/${shot.id}`);
await c.uploadAsset('subscriptionAppStoreReviewScreenshots', { subscription: { data: { type: 'subscriptions', id: subId } } }, file);
log(TAG, ` review screenshot ${s.reviewScreenshot}`);
}
}
}
}
@ -178,5 +219,11 @@ async function customCodes(c: Asc, ctx: Ctx, subId: string, s: Subscription, oc:
const todo = oc.customCodes!.filter(cc => !have.has(cc.code));
if (!todo.length) return;
if (!(await confirm({ ...ctx, args: { ...ctx.args, has: (n: string) => n !== 'yes' && ctx.args.has(n) } }, `Create ${todo.length} custom offer code(s) for ${s.id} (${todo.map(x => `${x.code} x${x.count}`).join(', ')})? Anyone with a code can redeem it.`))) return;
for (const cc of todo) { await c.asc('POST', '/v1/subscriptionOfferCodeCustomCodes', appleCustomCodeBody(id, cc)); log(TAG, ` custom code ${cc.code} (${cc.count})`); }
for (const cc of todo) {
// a custom code is unique: a 409 finds the existing one
await createOnce({ what: `custom code ${cc.code}`, tag: TAG, unique: true,
find: async () => (await c.all(`/v1/subscriptionOfferCodes/${id}/customCodes?limit=200`)).find((x: J) => x.attributes.customCode === cc.code) ?? null,
create: async () => (await c.asc('POST', '/v1/subscriptionOfferCodeCustomCodes', appleCustomCodeBody(id, cc))).data });
log(TAG, ` custom code ${cc.code} (${cc.count})`);
}
}

View file

@ -27,7 +27,8 @@ import {
parseTesters, pickBuild, planBetaInfo, planBetaReviewDetail, planDistribute, planGroups, planTesters, planWhatToTest, whatToTestFromListing,
} from '../lib/testflight';
import { type Asc, ascClient, type J } from './asc';
import { execute } from './jsonapi';
import { describeReq, execute } from './jsonapi';
import { findOrCreate, getById } from '../lib/upsert';
const TAG = 'testflight';
const USAGE = 'usage: storebound apple testflight status | groups | testers | what-to-test --build N | info | distribute --build N --group <names> | wait --build N | expire --keep N | --older-than D';
@ -138,7 +139,16 @@ export async function run(ctx: Ctx): Promise<void> {
const plan = planGroups(appId, await groups(c, appId), tf?.groups ?? []);
if (!tf?.groups?.length) warn(TAG, 'apple.testflight.groups is empty: nothing to create');
for (const n of plan.existing) log(TAG, `group "${n}": exists`);
await execute(c.asc, plan.create, { dry, tag: TAG });
if (dry) await execute(c.asc, plan.create, { dry, tag: TAG });
else for (const r of plan.create) {
// looked up right before the create (fresh list, then the journal for the list lag); a 409 finds it
const name = (r.body as J).data.attributes.name as string;
const made = await findOrCreate<J>({ what: `beta group "${name}"`, tag: TAG, unique: true,
find: async () => (await c.all(`/v1/apps/${appId}/betaGroups?limit=200`)).find((g: J) => g.attributes.name === name) ?? null,
journal: { root, key: `apple:${appId}:betaGroup:${name}`, byId: id => getById(c.asc, `/v1/betaGroups/${id}`) as Promise<J | null>, idOf: v => v.id },
create: async () => (await c.asc('POST', r.path, r.body)).data });
log(TAG, `${describeReq(r)}: ${made.created ? 'done' : 'exists already'}`);
}
done(TAG, dry ? `groups checked (dry run): ${plan.create.length} to create` : `groups done (${plan.create.length} created)`);
return;
}

View file

@ -23,6 +23,7 @@ import { BUILD_WAIT_EXIT } from '../lib/build-ops';
import { type Asc, ascClient, type J } from './asc';
import { waitForBuild, waitMessage } from './testflight';
import { describeReq } from './jsonapi';
import { createOnce } from '../lib/upsert';
const TAG = 'upload';
@ -44,9 +45,20 @@ function slice(path: string, offset: number, length: number): Buffer {
async function apiUpload(c: Asc, appId: string, ipa: string, info: ReturnType<typeof ipaInfo>, deadline: number): Promise<void> {
const size = statSync(ipa).size;
const reqs = buildUploadReqs(appId, info, basename(ipa), size);
const up = (await c.asc('POST', reqs.upload.path, reqs.upload.body)).data;
log(TAG, `build upload ${up.id} created`);
const file = (await c.asc('POST', reqs.file(up.id).path, reqs.file(up.id).body)).data;
// one build upload per version + build number: an earlier one that did not fail is resumed, never doubled
const prior = (await uploadsOf(c, appId, info)).find((u: J) => u.attributes?.state?.state !== 'FAILED');
const made = prior ? { value: prior, created: false } : await createOnce<J>({ what: `build upload ${info.version} (${info.build})`, tag: TAG,
find: async () => (await uploadsOf(c, appId, info)).find((u: J) => u.attributes?.state?.state !== 'FAILED') ?? null,
create: async () => (await c.asc('POST', reqs.upload.path, reqs.upload.body)).data });
const up = made.value;
log(TAG, made.created ? `build upload ${up.id} created` : `build upload ${up.id} exists (${up.attributes?.state?.state ?? '?'}): resuming it`);
const filesOf = async () => (await c.all(`/v1/buildUploads/${up.id}/buildUploadFiles?limit=10`)).filter((f: J) => f.attributes?.fileName === basename(ipa));
const fileNow = made.created ? undefined : (await filesOf())[0];
const file = fileNow ?? (await createOnce<J>({ what: `file reservation of build upload ${up.id}`, tag: TAG,
find: async () => (await filesOf())[0] ?? null,
create: async () => (await c.asc('POST', reqs.file(up.id).path, reqs.file(up.id).body)).data })).value;
if (fileNow && !(fileNow.attributes?.uploadOperations ?? []).length)
throw new Error(`build upload ${up.id} already has ${basename(ipa)} (${fileNow.attributes?.assetDeliveryState?.state ?? 'state unknown'}) and App Store Connect gives no upload parts for it: wait for it (storebound apple testflight wait --build ${info.build}), or raise the build number (storebound apple build)`);
const ops = (file.attributes.uploadOperations ?? []) as J[];
log(TAG, `uploading ${(size / 1048576).toFixed(1)} MB in ${ops.length} part(s)`);
let sent = 0;
@ -82,6 +94,10 @@ async function apiUpload(c: Asc, appId: string, ipa: string, info: ReturnType<ty
}
}
/** Build uploads of this version + build number (any state), newest first. */
const uploadsOf = (c: Asc, appId: string, info: { version: string; build: string }): Promise<J[]> =>
c.all(`/v1/apps/${appId}/buildUploads?filter[cfBundleShortVersionString]=${encodeURIComponent(info.version)}&filter[cfBundleVersion]=${encodeURIComponent(info.build)}&filter[platform]=IOS&limit=20`);
async function altoolUpload(root: string, ipa: string): Promise<void> {
if (process.platform !== 'darwin' || !Bun.which('xcrun')) throw new Error('--via altool needs macOS with Xcode; use --via api elsewhere');
const k = ascKeyFile(root);
@ -122,6 +138,16 @@ export async function run(ctx: Ctx): Promise<void> {
const builds = await c.all(`/v1/builds?filter[app]=${appId}&limit=200&fields[builds]=version`);
const numbers = builds.map(b => String(b.attributes.version));
const next = nextBuildNumber(numbers);
// the same IPA uploaded by an earlier run: nothing to send again, only the wait
const already = via === 'api' && !dry ? (await uploadsOf(c, appId, info).catch(() => [])).find((u: J) => u.attributes?.state?.state === 'COMPLETE') : undefined;
if (already) {
log(TAG, `build ${info.version} (${info.build}) was uploaded already (build upload ${already.id}); not sending it again`);
if (!wait) { if (json) printJson({ ...{ ipa: relative(root, ipa), version: info.version, build: info.build }, uploaded: true, alreadyUploaded: true }); done(TAG, `build ${info.build} already uploaded`); return; }
const r = await waitForBuild(c, appId, info.build, { marketing: info.version, timeoutMs: timeout, tag: TAG });
if (json) printJson({ ipa: relative(root, ipa), version: info.version, build: info.build, uploaded: true, alreadyUploaded: true, processingState: r.seen.processingState ?? null });
if (r.outcome === 'valid') { done(TAG, waitMessage(info.build, r)); return; }
process.exit(r.outcome === 'failed' ? BUILD_WAIT_EXIT.failed : BUILD_WAIT_EXIT.timeout);
}
if (numbers.includes(info.build)) throw new Error(`build ${info.build} is already on App Store Connect: rebuild with --build-number ${next} (storebound apple build)`);
if (numbers.length && compareBuild(info.build, next) < 0) warn(TAG, `build ${info.build} is lower than the highest uploaded one (next free: ${next}); Apple accepts it only if this version train has no higher build`);
const reqs = buildUploadReqs(appId, info, basename(ipa), size);

View file

@ -49,7 +49,7 @@ const COMMANDS: Record<string, [() => Promise<Mod>, string]> = {
'play subscriptions': [() => import('./play/subscriptions'), 'auto-renewable subscriptions: listings, base plan, regional prices, intro offer, activate (--csv prices sheet; asks first)'],
'play listing': [() => import('./play/listing'), 'app details + title / short / full description per language; pull [--write]: live listings back into the listing file (diff first)'],
'play images': [() => import('./play/images'), 'icon, feature graphic, phone / 7" / 10" screenshots per language; --variant <id>'],
'play data-safety': [() => import('./play/data-safety'), 'Data safety form (CSV import through the API)'],
'play data-safety': [() => import('./play/data-safety'), '[--force] Data safety form (CSV import through the API; skipped when unchanged since the last upload)'],
'play release': [() => import('./play/release'), 'upload an AAB and put it on tracks with release notes'],
'play build': [() => import('./play/build'), 'gradle bundleRelease (Flutter: flutter build appbundle) with the next free versionCode and the upload key from env / .storebound; --dry'],
'play upload': [() => import('./play/upload'), 'upload an AAB to a testing track (--track internal|alpha|beta), versionCode checked first; --dry read-only, asks first'],
@ -130,6 +130,9 @@ async function main(): Promise<void> {
if (!key) { console.error(`unknown command: ${argv.slice(0, 2).join(' ')}\n`); help(); process.exit(2); }
const args = parseArgs(argv.slice(key.split(' ').length));
const loaded = await loadConfig(args.get('config'));
// one writer per app and store (cli/lib/lock.ts): dry runs and reads take no lock
const { acquireLock, lockKeys } = await import('./lib/lock');
for (const k of lockKeys(key, args, loaded.config)) acquireLock(loaded.root, k, argv.filter(x => x !== '--force-unlock').join(' '), { force: args.has('force-unlock') });
await (await COMMANDS[key]![0]()).run({ loaded, args });
}

View file

@ -15,7 +15,7 @@ export function parseArgs(argv: string[], booleans: string[] = []): Args {
const repeated = new Map<string, string[]>();
const set = (k: string, v: string) => { flags.set(k, v); repeated.set(k, [...(repeated.get(k) ?? []), v]); };
const _: string[] = [];
const bool = new Set(['dry', 'yes', 'help', 'json', 'verbose', 'all-pages', 'apply', 'resume', 'force', 'include-drafts', ...booleans]);
const bool = new Set(['dry', 'yes', 'help', 'json', 'verbose', 'all-pages', 'apply', 'resume', 'force', 'force-unlock', 'include-drafts', ...booleans]);
for (let i = 0; i < argv.length; i++) {
const a = argv[i]!;
if (!a.startsWith('--')) { _.push(a); continue; }

View file

@ -100,6 +100,12 @@ export interface ShotFrame { src: string; x?: number; dy?: number; scale?: numbe
export interface Palette { bg: [string, string, string]; glow: string; ink: string; shadow: string }
export interface ShotScene { id: string; palette: string | Palette; hero?: boolean; frames: ShotFrame[]; badges?: ShotBadgeSlot[]; over?: number }
/** A local font file for shots.fonts. license: 'OFL-1.1', 'proprietary' or a short note (shown by `shots fonts`;
* `shots check` warns without one). weight / style: the @font-face descriptors (default: all weights, normal). */
export interface LocalFontSpec { family?: string; file: string; weight?: number | string; style?: 'normal' | 'italic'; license?: string }
/** A Google Fonts family name, a local font path (relative to the config) or a LocalFontSpec. */
export type FontSpec = string | LocalFontSpec;
export interface ShotsConfig {
/** Look of the rendered screenshots: game (sunburst, sparkles, badges, bold outlined titles) or app (calm gradient,
* device frame, headline + subline, no sparkles or badges). Default: app for the app / subscription-app profiles,
@ -113,11 +119,12 @@ 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`). 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[] };
/** Fonts for titles / body text: a Google Fonts family (downloaded and subset by `shots fonts`), or your own font file
* (a path relative to the config, TTF / OTF / WOFF / WOFF2, or { family, file, weight?, style?, license? }).
* Default: game Paytone One + Montserrat, app Inter (all cover Latin Extended and Vietnamese). `fallback`: fonts you
* accept for characters the title / body font lacks, tried in order before the automatic Noto fallbacks (e.g.
* ['Noto Sans Display'] or a local file); a render that needs an automatic fallback is an ERROR in `shots check`. */
fonts?: { title?: FontSpec; body?: FontSpec; fallback?: FontSpec[] };
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).
@ -146,6 +153,10 @@ export interface ShotSpec {
/** Web: JS run in the page before the screenshot. */
eval?: string[];
device?: 'phone' | 'tablet' | 'both';
/** Web, capture.session "per-language": how this shot is reached in the already booted page. "spa" (default):
* history.pushState to its path + a popstate event, then waitFor / eval (switch scenes from those); "reload":
* page.goto in the same page. A failing waitFor there falls back to a fresh page. */
navigate?: 'spa' | 'reload';
/** ios-sim: extra launch arguments, e.g. ["-shotScene", "{shot}", "-seed", "1"] (read them with UserDefaults / your engine). */
args?: string[];
/** android-emu: intent extras for `am start` (string / int / float / boolean), "{lang}" replaced in strings. */
@ -194,6 +205,18 @@ export interface ShotsCapture {
* every device, or per device class. Default: the frame's bar share of the height (phone 54 / 956 = 162 px on a 6.9"
* iPhone, 13" iPad 24 / 1376 = 48 px). */
cropTop?: number | { phone?: number; tablet?: number };
/** Web: parallel browser contexts (one headless Chromium). Default min(3, CPU cores / 4): game boots are GPU-heavy.
* `--concurrency N` overrides. */
concurrency?: number;
/** Web: "per-shot" (default: new context + full boot per frame) or "per-language" (one page per language and
* device, booted once; shots switch in it, see ShotSpec.navigate). */
session?: 'per-shot' | 'per-language';
/** Web, per-language: how long a reused page may take to reach a shot's waitFor before a fresh page is used.
* Default 15000 ms. */
reuseTimeoutMs?: number;
/** Web: files or folders of the app build (e.g. "apps/game/src" or "apps/game/dist") hashed into the capture cache,
* so a code change re-captures. Default: the HTML at baseUrl and the scripts it loads. */
build?: string | string[];
shots: Record<string, ShotSpec>;
}
@ -831,6 +854,19 @@ export function validateConfig(c: unknown): string[] {
for (const k of ['copy', 'frames', 'out'] as const) if (!s[k]) e.push(`shots.${k}: missing`);
if (s.style !== undefined && s.style !== 'game' && s.style !== 'app') e.push('shots.style: game | app');
if (!s.scenes?.length) e.push('shots.scenes: at least one scene');
const fontKeys: [string, unknown][] = [['title', s.fonts?.title], ['body', s.fonts?.body], ...(Array.isArray(s.fonts?.fallback) ? s.fonts!.fallback! : s.fonts?.fallback !== undefined ? [s.fonts.fallback] : []).map((f, i) => [`fallback[${i}]`, f] as [string, unknown])];
if (s.fonts?.fallback !== undefined && !Array.isArray(s.fonts.fallback)) e.push('shots.fonts.fallback: a list');
for (const [k, f] of fontKeys) {
if (f === undefined) continue;
if (typeof f === 'string') { if (!f.trim()) e.push(`shots.fonts.${k}: empty`); else if (/[\\/]|\.[a-z0-9]{2,5}$/i.test(f) && !/\.(ttf|otf|woff2?)$/i.test(f)) e.push(`shots.fonts.${k}: ${f}: a font file must be TTF, OTF, WOFF or WOFF2`); continue; }
const o = f as Partial<LocalFontSpec>;
if (!o || typeof o !== 'object' || typeof o.file !== 'string') { e.push(`shots.fonts.${k}: a Google Fonts family, a font file path or { family, file, weight?, style?, license? }`); continue; }
if (!/\.(ttf|otf|woff2?)$/i.test(o.file)) e.push(`shots.fonts.${k}.file: ${o.file}: TTF, OTF, WOFF or WOFF2`);
if (o.family !== undefined && (typeof o.family !== 'string' || !o.family.trim())) e.push(`shots.fonts.${k}.family: a name`);
if (o.style !== undefined && o.style !== 'normal' && o.style !== 'italic') e.push(`shots.fonts.${k}.style: normal | italic`);
if (o.weight !== undefined && !/^\d{3}( \d{3})?$/.test(String(o.weight))) e.push(`shots.fonts.${k}.weight: e.g. 400, 800 or "100 900"`);
if (o.license !== undefined && typeof o.license !== 'string') e.push(`shots.fonts.${k}.license: text ('OFL-1.1', 'proprietary', ...)`);
}
for (const sc of s.scenes ?? []) if (!sc.frames?.length) e.push(`shots.scenes[${sc.id}].frames: at least one frame`);
e.push(...validateCapture(s.capture));
const sceneIds = new Set((s.scenes ?? []).map(x => x.id));

View file

@ -129,7 +129,9 @@ export function normalizeKeywords(text: string, o: { name?: string; subtitle?: s
return { text: kept.join(','), dropped };
}
export interface FieldCheck { store: 'apple' | 'play'; field: string; chars: number; limit: number; problems: string[] }
/** `chars` is what the store counts: characters, except App Store keywords, which App Store Connect limits in UTF-8 bytes
* (`unit` says which). */
export interface FieldCheck { store: 'apple' | 'play'; field: string; chars: number; unit: 'chars' | 'bytes'; limit: number; problems: string[] }
/** Limits and rules of one translated section. `source` = the source language's fields (identical text is flagged). */
export function checkFields(store: 'apple' | 'play', f: Record<string, string | undefined>, source: Record<string, string | undefined> = {}, status?: TStatus): FieldCheck[] {
@ -139,10 +141,11 @@ export function checkFields(store: 'apple' | 'play', f: Record<string, string |
const v = f[k];
if (v === undefined) continue;
const limit = (FIELD_LIMITS[store] as Record<string, number>)[k]!;
const c: FieldCheck = { store, field: k, chars: len(v), limit, problems: [] };
if (len(v) > limit) c.problems.push(`${len(v)} > ${limit} characters`);
if (store === 'apple' && k === 'keywords') {
if (Buffer.byteLength(v) > limit) c.problems.push(`${Buffer.byteLength(v)} bytes > ${limit}`);
const bytes = store === 'apple' && k === 'keywords';
const n = bytes ? Buffer.byteLength(v, 'utf8') : len(v);
const c: FieldCheck = { store, field: k, chars: n, unit: bytes ? 'bytes' : 'chars', limit, problems: [] };
if (n > limit) c.problems.push(`${n} > ${limit} ${bytes ? 'bytes' : 'characters'}`);
if (bytes) {
if (/,\s|\s,/.test(v)) c.problems.push('spaces around commas');
const words = v.split(',').map(w => w.trim().toLocaleLowerCase()).filter(Boolean);
const dup = words.filter((w, i) => words.indexOf(w) !== i);

90
cli/lib/lock.ts Normal file
View file

@ -0,0 +1,90 @@
// One writer per app and store: a write command takes .storebound/locks/<store>-<app>.lock before it changes
// anything, so two storebound runs (two terminals, an agent and a CI job, a flow and a hand run) never write to the
// same app at once and race each other into duplicates. Dry runs and reads take no lock.
// A lock whose process is gone (same machine) is taken over; a live one stops the run with who holds it. A lock
// left by a crash on another machine (shared folder) stays until --force-unlock or 12 hours.
import { hostname } from 'node:os';
import { mkdirSync, openSync, readFileSync, rmSync, writeSync, closeSync } from 'node:fs';
import { join } from 'node:path';
import type { ShipConfig } from './config';
import type { Args } from './args';
export interface LockInfo { pid: number; host: string; command: string; startedAt: string }
const STALE_MS = 12 * 3600_000;
export const lockPath = (root: string, key: string): string => join(root, '.storebound', 'locks', `${key.replace(/[^A-Za-z0-9._-]+/g, '_')}.lock`);
function alive(pid: number): boolean {
try { process.kill(pid, 0); return true; } catch (e) { return (e as NodeJS.ErrnoException).code === 'EPERM'; }
}
/** Whether a lock may be taken over: its process is gone (same host) or it is older than 12 hours. Pure apart from
* the process check. */
export function staleLock(l: LockInfo | null, now = Date.now(), host = hostname(), isAlive = alive): boolean {
if (!l) return true;
if (now - Date.parse(l.startedAt) > STALE_MS) return true;
return l.host === host && !isAlive(l.pid);
}
const held = new Set<string>();
let hooked = false;
/** Takes the lock `key` for `command` (`apple iap`); throws with the holder when another run has it. Released when the
* process exits. `force` removes a lock first (--force-unlock). */
export function acquireLock(root: string, key: string, command: string, o: { force?: boolean } = {}): () => void {
const path = lockPath(root, key);
mkdirSync(join(root, '.storebound', 'locks'), { recursive: true });
if (o.force) rmSync(path, { force: true });
for (let attempt = 0; ; attempt++) {
try {
const fd = openSync(path, 'wx', 0o600);
const info: LockInfo = { pid: process.pid, host: hostname(), command, startedAt: new Date().toISOString() };
writeSync(fd, JSON.stringify(info) + '\n');
closeSync(fd);
break;
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'EEXIST' || attempt > 2) throw e;
let cur: LockInfo | null = null;
try { cur = JSON.parse(readFileSync(path, 'utf8')) as LockInfo; } catch { /* half written or unreadable: treat as stale */ }
if (!staleLock(cur)) {
throw new Error(`another storebound run is writing to ${key.replace(/^(\w+)-/, '$1 ')}: \`storebound ${cur!.command}\` (pid ${cur!.pid} on ${cur!.host}, since ${cur!.startedAt.slice(0, 16).replace('T', ' ')} UTC). `
+ `Two writers at once can create duplicates, so this run stops. Wait for it to finish; if it is no longer running, re-run with --force-unlock (removes ${join('.storebound', 'locks', path.split('/').pop()!)}).`);
}
rmSync(path, { force: true });
}
}
held.add(path);
if (!hooked) { hooked = true; process.on('exit', () => { for (const p of held) rmSync(p, { force: true }); }); }
return () => { rmSync(path, { force: true }); held.delete(path); };
}
/** Read-only subcommands and flags: no lock. */
const READ_SUBS = new Set(['status', 'list', 'devices', 'diff', 'export', 'pull', 'wait', 'options', 'coverage', 'report', 'campaigns', 'check', 'help']);
/**
* The lock keys a command run needs: none for dry runs and reads, `apple-<bundle id>` / `play-<package>` for store
* writes, both for `prices import`, `revenuecat-<project>` for revenuecat sync. Pure.
*/
export function lockKeys(command: string, args: Args, config: ShipConfig): string[] {
// a dry run never writes, so it never waits for (or blocks) a writer
const readOnly = args.has('dry');
if (readOnly) return [];
const sub = args._[0];
const apple = config.apple?.bundleId ? [`apple-${config.apple.bundleId}`] : [];
const play = config.play?.packageName ? [`play-${config.play.packageName}`] : [];
if (command.startsWith('apple ')) {
if (['apple status', 'apple next-build', 'apple build'].includes(command)) return [];
if (command === 'apple listing' && sub === 'pull') return [];
if (sub && READ_SUBS.has(sub)) return [];
if (command === 'apple adhoc' && ['options', 'export'].includes(sub ?? '')) return [];
return apple;
}
if (command.startsWith('play ')) {
if (['play status', 'play next-version-code', 'play build'].includes(command)) return [];
if (command === 'play listing' && sub === 'pull') return [];
return play;
}
if (command === 'prices') return sub === 'import' && !args.has('json') ? [...apple, ...play] : [];
if (command === 'revenuecat') return sub === 'sync' ? [`revenuecat-${config.apple?.bundleId ?? config.play?.packageName ?? 'project'}`] : [];
return [];
}

152
cli/lib/upsert.ts Normal file
View file

@ -0,0 +1,152 @@
// Idempotent writes against the stores. Every create in storebound goes through here or follows the same rules
// (docs/idempotency.md):
// 1. Look the thing up by its stable key first (product id, locale, version string, display type, name) and update or
// leave it instead of creating it again.
// 2. Right before a create, look again with a fresh GET (findOrCreate), and ask a journal of recent creates
// (.storebound/created.json) for an id the store's list may not show yet: a direct GET by id is not subject to the
// minute of list lag right after a create.
// 3. A create answered with 409 / ALREADY_EXISTS is "found": look it up and use it, never create again (createOnce).
// 4. A create whose outcome is unknown (timeout, connection reset, 5xx on a POST) is never sent blindly again: look
// first; only when the store itself refuses duplicates of that key (unique) is a second attempt safe (its 409
// then finds the first one). Otherwise stop with a message: re-running reads the store and converges.
// Retries of 429 / 5xx in the API clients are only for requests that end the same when sent twice (retrySafe).
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { log, warn } from './log';
/** A write whose outcome is unknown: it may or may not have been applied (timeout, connection reset, 5xx answer to a
* POST). The API clients throw this instead of retrying such a request. */
export class AmbiguousWriteError extends Error {
readonly ambiguous = true;
constructor(message: string, readonly status: number | null = null) { super(message); this.name = 'AmbiguousWriteError'; }
}
export const isAmbiguous = (e: unknown): boolean => e instanceof AmbiguousWriteError || (e as { ambiguous?: boolean } | null)?.ambiguous === true;
/**
* The store refused a create because the thing already exists: Google ALREADY_EXISTS / 409, App Store Connect 409 with
* a "duplicate / already / unique / in use / taken" detail (Apple also answers 409 for plain validation errors, which
* are not conflicts), RevenueCat 409. Pure.
*/
export function isConflict(e: unknown): boolean {
const s = String((e as Error)?.message ?? e);
if (/ALREADY_EXISTS/.test(s)) return true;
if (!/(-> |: )409\b/.test(s)) return false;
return /duplicate|already|unique|in use|taken|exists/i.test(s.replace(/^.*?409/, ''));
}
/** POSTs that end the same when sent twice: relationship adds, Google custom actions that set a state, and the App
* Store "create or replace" singletons (price schedules, availability). */
const IDEMPOTENT_POST: RegExp[] = [
/\/relationships\//,
/:(validate|convertRegionPrices|batchUpdateStates|activate|deactivate|query|batchGet|reply)(\?|$)/,
/\/edits(\?|$)/, // a new edit; an unused one expires on its own and changes nothing
/\/dataSafety(\?|$)/,
/^\/v1\/(inAppPurchasePriceSchedules|appPriceSchedules|inAppPurchaseAvailabilities|subscriptionAvailabilities)(\?|$)/,
/^\/v2\/appAvailabilities(\?|$)/,
];
/** Whether a request may be sent again after a 5xx or a network error. GET, HEAD, PUT, PATCH and DELETE set a state;
* a POST creates unless its path is a known idempotent action. `path` may be a full URL. Pure. */
export function retrySafe(method: string, path: string): boolean {
const m = method.toUpperCase();
if (m !== 'POST') return true;
const p = path.replace(/^https:\/\/[^/]+/, '').replace(/^\/(androidpublisher|upload\/androidpublisher)\/v3\/applications\/[^/]+/, '');
return IDEMPOTENT_POST.some(re => re.test(p));
}
/** Waits between re-checks (STOREBOUND_UPSERT_WAIT_MS; the test preload sets 0). */
export const upsertTiming = { waitMs: Number(process.env.STOREBOUND_UPSERT_WAIT_MS ?? 3000), tries: 4, sleep: (ms: number): Promise<void> => (ms > 0 ? Bun.sleep(ms) : Promise.resolve()) };
export interface CreateOnce<T> {
/** what is being created, for log lines and errors: `in-app purchase com.example.gems` */
what: string;
/** the create request; returns the created thing */
create: () => Promise<T>;
/** a fresh lookup by the stable key (GET with a filter, or the list), null when it is not there */
find: () => Promise<T | null | undefined>;
/** the store refuses a second one with this key (409): a create may then be tried again after an unknown outcome */
unique?: boolean;
/** log tag */
tag?: string;
}
async function recheck<T>(o: CreateOnce<T>): Promise<T | null> {
for (let i = 0; i < upsertTiming.tries; i++) {
const v = await o.find();
if (v) return v;
if (i < upsertTiming.tries - 1) await upsertTiming.sleep(upsertTiming.waitMs * (i + 1));
}
return null;
}
/** One create, never two: a conflict finds the existing one, an unknown outcome looks before (maybe) trying again. */
export async function createOnce<T>(o: CreateOnce<T>, attempt = 1): Promise<{ value: T; created: boolean }> {
try {
return { value: await o.create(), created: true };
} catch (e) {
const msg = (e as Error).message;
if (isConflict(e)) {
const v = await recheck(o);
if (v) { log(o.tag ?? 'upsert', `${o.what}: already exists, using it (not created again)`); return { value: v, created: false }; }
throw new Error(`${o.what}: the store says it already exists but does not list it yet (its lists lag right after a create). Nothing was created twice; run the command again in a minute.\n${msg}`);
}
if (!isAmbiguous(e)) throw e;
warn(o.tag ?? 'upsert', `${o.what}: no clear answer to the create (${msg.slice(0, 160)}); checking whether it exists before anything else`);
const v = await recheck(o);
if (v) { log(o.tag ?? 'upsert', `${o.what}: the create went through`); return { value: v, created: true }; }
if (o.unique && attempt < 2) return createOnce(o, attempt + 1);
throw new Error(`${o.what}: the create got no clear answer and the store does not list it (yet). It was not sent again, so nothing is created twice: run the command again in a minute (it reads the store first).\n${msg}`);
}
}
// ---------------------------------------------------------------------------------------------- journal of creates
/** Creates of the last day, keyed by store + kind + stable key: { id, at }. Lives in .storebound/created.json. */
type Journal = Record<string, { id: string; at: string }>;
const JOURNAL_MS = 24 * 3600_000;
const journalPath = (root: string): string => join(root, '.storebound', 'created.json');
export function readJournal(root: string, now = Date.now()): Journal {
try {
const j = JSON.parse(readFileSync(journalPath(root), 'utf8')) as Journal;
return Object.fromEntries(Object.entries(j).filter(([, v]) => v && now - Date.parse(v.at) < JOURNAL_MS));
} catch { return {}; }
}
export function remember(root: string, key: string, id: string, now = new Date()): void {
try {
const j = readJournal(root, now.getTime());
j[key] = { id, at: now.toISOString() };
mkdirSync(join(root, '.storebound'), { recursive: true });
const tmp = journalPath(root) + `.${process.pid}.tmp`;
writeFileSync(tmp, JSON.stringify(j, null, 2) + '\n');
renameSync(tmp, journalPath(root));
} catch (e) { warn('upsert', `could not note the create in .storebound/created.json: ${(e as Error).message}`); }
}
export interface FindOrCreate<T> extends CreateOnce<T> {
/** journal of recent creates: guards against the list lag right after a create of an earlier run */
journal?: { root: string; key: string; byId: (id: string) => Promise<T | null | undefined>; idOf: (v: T) => string };
}
/** Looks with a fresh GET, then in the journal (direct GET by id), and only then creates (createOnce). */
export async function findOrCreate<T>(o: FindOrCreate<T>): Promise<{ value: T; created: boolean }> {
const found = await o.find();
if (found) return { value: found, created: false };
if (o.journal && existsSync(join(o.journal.root, '.storebound'))) {
const hit = readJournal(o.journal.root)[o.journal.key];
if (hit) {
const v = await o.journal.byId(hit.id).catch(() => null);
if (v) { log(o.tag ?? 'upsert', `${o.what}: created ${hit.at.slice(11, 16)} UTC by an earlier run (${hit.id}); the store's list does not show it yet, using it`); return { value: v, created: false }; }
}
}
const r = await createOnce(o);
if (o.journal && r.created) remember(o.journal.root, o.journal.key, o.journal.idOf(r.value));
return r;
}
/** Apple: GET of one resource by id, null on 404. For FindOrCreate.journal.byId. */
export async function getById(asc: (m: string, p: string) => Promise<{ data?: unknown }>, path: string): Promise<unknown | null> {
try { return (await asc('GET', path)).data ?? null; } catch (e) { if (/-> 404/.test(String(e))) return null; throw e; }
}

View file

@ -127,7 +127,7 @@ async function translate(ctx: Ctx): Promise<void> {
if (a.has('json')) printJson({ source: src.id, dryRun: dry, hook: !!hook, files: { apple: files.apple?.path ?? null, play: files.play?.path ?? null }, results: rows.map(r => ({ ...r, problems: problemsOf(r) })) });
else {
console.log(textTable(['language', 'store', 'section', 'fields', 'problems'], rows.map(r => [r.lang, r.store === 'apple' ? 'App Store' : 'Google Play', r.action,
r.checks.map(c => `${c.field} ${c.chars}/${c.limit}`).join(', '), problemsOf(r).join('; ')])));
r.checks.map(c => `${c.field} ${c.chars}/${c.limit}${c.unit === 'bytes' ? ' B' : ''}`).join(', '), problemsOf(r).join('; ')])));
}
const json = a.has('json');
if (dry) { if (!json) done(TAG, 'dry run: listing files not written'); return; }
@ -167,7 +167,7 @@ function check(ctx: Ctx): void {
if (ctx.args.has('json')) printJson({ sections: r, ok: !bad.length, drafts: drafts.map(d => `${d.store}:${d.lang}`) });
else {
console.log(textTable(['store', 'language', 'status', 'fields', 'problems'], r.map(x => [x.store === 'apple' ? 'App Store' : 'Google Play', x.lang,
x.status === 'draft' ? 'DRAFT (review)' : x.status === 'translate' ? 'TO TRANSLATE' : 'reviewed', x.checks.map(c => `${c.field} ${c.chars}/${c.limit}`).join(', '),
x.status === 'draft' ? 'DRAFT (review)' : x.status === 'translate' ? 'TO TRANSLATE' : 'reviewed', x.checks.map(c => `${c.field} ${c.chars}/${c.limit}${c.unit === 'bytes' ? ' B' : ''}`).join(', '),
x.checks.flatMap(c => c.problems.map(p => `${c.field}: ${p}`)).join('; ')])));
if (drafts.length) warn(TAG, `${drafts.length} machine-translated draft(s) not reviewed yet: ${drafts.map(d => `${d.store}:${d.lang}`).join(', ')} (storebound listing reviewed --lang <ids> after reading them)`);
done(TAG, bad.length ? `${bad.length} section(s) with problems` : `${r.length} section(s) within the store limits`);

View file

@ -163,7 +163,8 @@ export const TOOLS: ToolDef[] = [
props: { only, csv: { type: 'string', description: 'Prices CSV with rows for subscription ids' } },
args: i => [...opt('only', i.only), ...opt('csv', i.csv)] },
{ name: 'play_data_safety', title: 'Push Play Data safety', command: ['play', 'data-safety'], write: true, destructive: true, network: true, idempotent: true,
description: 'Replace the whole Play Data safety form with the answers from the config (CSV import). dry_run prints the CSV.' },
description: 'Replace the whole Play Data safety form with the answers from the config (CSV import). Skipped when the CSV equals the last upload of this project (hash in .storebound/; force: true sends it anyway). dry_run prints the CSV.',
props: { force: { type: 'boolean', default: false, description: 'Upload even when the CSV equals the last upload (after a manual change in Play Console)' } }, args: i => flag('force', i.force) },
{ name: 'play_release_testing', title: 'Release to a Play testing track', command: ['play', 'release'], write: true, network: true,
description: 'Upload an AAB (or reuse a versionCode) to a TESTING track (internal, alpha, beta) with release notes. Production is not available here.',
props: { aab: { type: 'string', description: 'Path to the .aab' }, version_code: { type: 'integer', minimum: 1 },
@ -200,13 +201,18 @@ export const TOOLS: ToolDef[] = [
args: i => ['--phased', String(i.action), ...opt('version', i.version)] },
{ name: 'shots_capture', title: 'Capture raw frames', command: ['shots', 'capture'], write: true, network: false, idempotent: true,
description: 'Raw app or game frames per language into shots.frames from a web build (Playwright), the iOS Simulator (simctl), an Android emulator / device (adb) or a folder check. Local files only; a simulator it boots is shut down again, an emulator is never booted. dry_run lists the plan and the simctl / adb commands.',
props: { lang, only: { type: 'string', description: 'Comma-separated shot names' }, device: { type: 'string', enum: ['phone', 'tablet'] }, source },
args: i => [...opt('lang', i.lang), ...opt('only', i.only), ...opt('device', i.device), ...opt('source', i.source)] },
props: { lang, only: { type: 'string', description: 'Comma-separated shot names' }, device: { type: 'string', enum: ['phone', 'tablet'] }, source,
concurrency: { type: 'integer', minimum: 1, maximum: 32, description: 'Web: parallel browser contexts (default from the CPU count)' },
mode: { type: 'string', enum: ['changed', 'only-missing', 'force'], default: 'changed', description: 'Web: skip frames with unchanged inputs (default), only missing ones, or capture all' } },
args: i => [...opt('lang', i.lang), ...opt('only', i.only), ...opt('device', i.device), ...opt('source', i.source),
...(i.concurrency ? ['--concurrency', String(i.concurrency)] : []), ...(i.mode === 'force' ? ['--force'] : i.mode === 'only-missing' ? ['--only-missing'] : [])] },
{ name: 'shots_render', title: 'Render store screenshots', command: ['shots', 'render'], write: true, network: false, idempotent: true,
description: 'Store screenshots + Play feature graphic in every size and language from the frames and the copy file (local PNGs, needs Playwright + ffmpeg; slow for many languages). dry_run lists what would be rendered.',
props: { lang, size: { type: 'string', description: 'Comma-separated size keys: ios69, ios65, iphone-medium, ipad13, play, tab7, tab10, feature' },
scenes: { type: 'string', description: 'Comma-separated scene ids' }, variant, all_variants: { type: 'boolean', default: false, description: 'Base + every variant' } },
args: i => [...opt('lang', i.lang), ...opt('size', i.size), ...opt('scenes', i.scenes), ...(i.all_variants === true ? ['--variants'] : opt('variant', i.variant))] },
scenes: { type: 'string', description: 'Comma-separated scene ids' }, variant, all_variants: { type: 'boolean', default: false, description: 'Base + every variant' },
concurrency: { type: 'integer', minimum: 1, maximum: 32, description: 'Parallel pages (default min(4, CPU cores / 2))' } },
args: i => [...opt('lang', i.lang), ...opt('size', i.size), ...opt('scenes', i.scenes), ...(i.all_variants === true ? ['--variants'] : opt('variant', i.variant)),
...(i.concurrency ? ['--concurrency', String(i.concurrency)] : [])] },
{ name: 'shots_gallery', title: 'Review gallery', command: ['shots', 'gallery'], write: true, network: false, idempotent: true,
description: 'Write <renders>/index.html: one self-contained page with every language, size, scene, variant and app preview, store check issues highlighted. Open it in a browser to review before uploading.',
props: { lang }, args: i => opt('lang', i.lang) },

View file

@ -3,6 +3,7 @@ import { playServiceAccount } from '../lib/credentials';
import { tokenSource } from '../lib/google-auth';
import { log, warn } from '../lib/log';
import { errorBody } from '../lib/http';
import { AmbiguousWriteError, isAmbiguous, retrySafe } from '../lib/upsert';
export type PlayClient = Awaited<ReturnType<typeof playClient>>;
@ -11,41 +12,88 @@ export async function playClient(root: string, packageName: string) {
const API = `https://androidpublisher.googleapis.com/androidpublisher/v3/applications/${packageName}`;
const UPLOAD = `https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications/${packageName}`;
/** JSON call (object body) or media upload (Uint8Array body + Content-Type). Throws with the API's text. */
/**
* JSON call (object body) or media upload (Uint8Array body + Content-Type). Throws with the API's text. 429 is
* retried (refused, not applied); 5xx and network errors only for requests that end the same when sent twice
* (retrySafe). A create or upload POST then throws AmbiguousWriteError instead of being sent again.
*/
async function call<T = unknown>(method: string, url: string, body?: unknown, headers: Record<string, string> = {}): Promise<T> {
const bin = body instanceof Uint8Array;
const safe = retrySafe(method, url);
const short = (): string => url.replace(API, '').replace(UPLOAD, '');
for (let attempt = 0; ; attempt++) {
const r = await fetch(url, {
method,
headers: { Authorization: 'Bearer ' + (await token()), ...(body === undefined || bin ? {} : { 'Content-Type': 'application/json' }), ...headers },
body: body === undefined ? undefined : bin ? (body as unknown as BodyInit) : JSON.stringify(body),
});
let r: Response;
try {
r = await fetch(url, {
method,
headers: { Authorization: 'Bearer ' + (await token()), ...(body === undefined || bin ? {} : { 'Content-Type': 'application/json' }), ...headers },
body: body === undefined ? undefined : bin ? (body as unknown as BodyInit) : JSON.stringify(body),
});
} catch (e) {
if (safe && attempt < 4) { await Bun.sleep(2000 * (attempt + 1)); continue; }
if (!safe) throw new AmbiguousWriteError(`${method} ${short()} -> no answer (${(e as Error).message})`);
throw e;
}
const text = await r.text();
if (r.ok) return (text ? JSON.parse(text) : {}) as T;
if ((r.status === 429 || r.status >= 500) && attempt < 4) { await Bun.sleep(2000 * (attempt + 1)); continue; }
const short = url.replace(API, '').replace(UPLOAD, '');
if ((r.status === 429 || (r.status >= 500 && safe)) && attempt < 4) { await Bun.sleep(2000 * (attempt + 1)); continue; }
// A wrong path casing answers with an HTML 404 page, not JSON: say so instead of dumping the HTML.
const msg = /^\s*</.test(text) ? `(HTML ${r.status} page: wrong path or casing?)` : errorBody(text);
throw new Error(`${method} ${short} -> ${r.status} ${msg}`);
if (r.status >= 500 && !safe) throw new AmbiguousWriteError(`${method} ${short()} -> ${r.status} ${msg}`, r.status);
if (r.status === 404 && method === 'DELETE' && attempt > 0) return {} as T;
throw new Error(`${method} ${short()} -> ${r.status} ${msg}`);
}
}
async function editOnce<T>(fn: (id: string) => Promise<T>, o: { dry?: boolean; commitQuery?: string }): Promise<T> {
/** At most one open edit per run: a second one would be invalidated by the first commit (or invalidate it). */
let openEdit: string | null = null;
async function openOne(): Promise<string> {
if (openEdit) throw new Error(`a Play edit (${openEdit}) is already open in this run: storebound never opens a second one`);
const e = await call<{ id: string }>('POST', `${API}/edits`, {});
log('play', `edit ${e.id} opened`);
openEdit = e.id;
return e.id;
}
async function closeOne(id: string, what: string): Promise<void> {
try { await call('DELETE', `${API}/edits/${id}`); } catch (err) {
// an edit that was committed or expired is gone already; anything else is reported (Play drops it later)
if (!/-> 404|not found|has been deleted|already been committed/i.test(String(err))) warn('play', `${what} edit ${id} not deleted: ${(err as Error).message.slice(0, 200)}`);
} finally { if (openEdit === id) openEdit = null; }
}
/** Thrown when a commit got no clear answer: the edit may be live, so it is never redone. */
class CommitUnknown extends Error { readonly noRedo = true; }
/** Controls of an edit: `unchanged()` when fn found nothing to change; the edit is then deleted, not committed. */
interface EditCtl { unchanged(): void }
async function editOnce<T>(fn: (id: string, ctl: EditCtl) => Promise<T>, o: { dry?: boolean; commitQuery?: string }): Promise<T> {
const id = await openOne();
log('play', `edit ${id} opened`);
let same = false;
let committing = false;
try {
const out = await fn(e.id);
const out = await fn(id, { unchanged: () => { same = true; } });
if (o.dry) {
await call('POST', `${API}/edits/${e.id}:validate`);
await call('POST', `${API}/edits/${id}:validate`);
log('play', 'dry run: edit validated, discarding');
await call('DELETE', `${API}/edits/${e.id}`);
await closeOne(id, 'dry run');
} else if (same) {
log('play', 'nothing to change: edit discarded, not committed');
await closeOne(id, 'unchanged');
} else {
await call('POST', `${API}/edits/${e.id}:commit${o.commitQuery ?? ''}`);
log('play', `edit ${e.id} committed`);
committing = true;
try { await call('POST', `${API}/edits/${id}:commit${o.commitQuery ?? ''}`); } catch (err) {
if (!isAmbiguous(err)) throw err;
openEdit = null;
throw new CommitUnknown(`the commit of edit ${id} got no clear answer (${(err as Error).message.slice(0, 200)}): it may be live. Not redone, so nothing is applied twice; check with \`storebound play status\` (or the dry run of this command) before running it again.`);
}
openEdit = null;
log('play', `edit ${id} committed`);
}
return out;
} catch (err) {
await call('DELETE', `${API}/edits/${e.id}`).catch(() => {});
// nothing of an uncommitted edit is live: delete it (also after a failed commit, which leaves the edit open)
if (!(err instanceof CommitUnknown)) await closeOne(id, committing ? 'failed commit' : 'failed');
throw err;
}
}
@ -57,21 +105,23 @@ export async function playClient(root: string, packageName: string) {
* A failed delete is reported (Play drops an unused edit on its own after a while, but it should not linger).
*/
async read<T>(fn: (id: string) => Promise<T>): Promise<T> {
const e = await call<{ id: string }>('POST', `${API}/edits`, {});
try { return await fn(e.id); } finally {
await call('DELETE', `${API}/edits/${e.id}`).catch(err => warn('play', `read-only edit not deleted: ${(err as Error).message.slice(0, 200)}`));
}
const id = await openOne();
try { return await fn(id); } finally { await closeOne(id, 'read-only'); }
},
/**
* Opens an edit, runs fn, then commits (or validates and discards when dry). Any Console save or other edit commit
* invalidates an open edit ("A change was made to the application outside of this Edit"); then the whole edit is
* redone, up to `retries` times. Keep edits small (e.g. one per language for images) so a retry is cheap.
*/
async edit<T>(fn: (id: string) => Promise<T>, o: { dry?: boolean; commitQuery?: string; retries?: number } = {}): Promise<T> {
async edit<T>(fn: (id: string, ctl: EditCtl) => Promise<T>, o: { dry?: boolean; commitQuery?: string; retries?: number } = {}): Promise<T> {
for (let left = o.retries ?? 3; ; left--) {
try { return await editOnce(fn, o); } catch (err) {
if (left <= 0 || !/outside of this Edit|Edit has been deleted|edit.*(expired|not found)/i.test(String(err))) throw err;
log('play', `app changed outside the edit (Console?), redoing it (${left} retries left)`);
// redo only what never went live: an edit invalidated before or at its commit, or a request inside the edit
// without a clear answer (the edit was deleted, so nothing of it applies). Never after an unclear commit.
if (left <= 0 || (err as { noRedo?: boolean }).noRedo) throw err;
const outside = /outside of this Edit|Edit has been deleted|edit.*(expired|not found)/i.test(String(err));
if (!outside && !isAmbiguous(err)) throw err;
log('play', `${outside ? 'app changed outside the edit (Console?)' : 'a request got no clear answer; the edit was discarded'}, redoing it (${left} retries left)`);
}
}
},

View file

@ -1,7 +1,10 @@
// Play Data safety form through applications.dataSafety (CSV import; replaces every earlier answer).
// storebound play data-safety [--csv out.csv] [--dry]
// storebound play data-safety [--csv out.csv] [--dry] [--force]
// Answers come from `dataSafety` in storebound.config.ts. --dry only writes / prints the CSV.
import { mkdirSync, writeFileSync } from 'node:fs';
// Play cannot read the form back, so a run compares with what this project uploaded last: the sha256 of that CSV
// (per package) is kept in .storebound/data-safety.sha256 (gitignored). The same CSV is not sent again; --force sends it
// anyway (e.g. after the form was changed in Play Console by hand).
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { Ctx } from '../lib/ctx';
import { need } from '../lib/ctx';
@ -10,6 +13,27 @@ import { DATA_SAFETY_UPLOADED } from '../lib/declarations';
import { done, log } from '../lib/log';
import { playClient } from './client';
export const DATA_SAFETY_HASH = '.storebound/data-safety.sha256';
/** sha256 of the CSV for one package. Pure. */
export const dataSafetyHash = (pkg: string, csv: string): string => new Bun.CryptoHasher('sha256').update(`${pkg}\n${csv}`).digest('hex');
/** The hash of the last upload of this package, null when none is recorded. */
export function lastUpload(root: string, pkg: string): { sha256: string; at: string } | null {
const f = join(root, DATA_SAFETY_HASH);
if (!existsSync(f)) return null;
try { return (JSON.parse(readFileSync(f, 'utf8')) as Record<string, { sha256: string; at: string }>)[pkg] ?? null; } catch { return null; }
}
function rememberUpload(root: string, pkg: string, sha256: string): void {
const f = join(root, DATA_SAFETY_HASH);
let all: Record<string, { sha256: string; at: string }> = {};
try { if (existsSync(f)) all = JSON.parse(readFileSync(f, 'utf8')); } catch { all = {}; }
all[pkg] = { sha256, at: new Date().toISOString() };
mkdirSync(join(root, '.storebound'), { recursive: true });
writeFileSync(f, JSON.stringify(all, null, 2) + '\n');
}
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
const csv = dataSafetyCsv(need(config.dataSafety, 'dataSafety'));
@ -17,10 +41,25 @@ export async function run(ctx: Ctx): Promise<void> {
if (out) { writeFileSync(resolve(out), csv); log('play', `wrote ${out}`); }
const types = Object.keys(config.dataSafety!.data);
log('play', `data safety: ${types.length} data types declared (${types.join(', ') || 'none'})`);
if (ctx.args.has('dry')) { if (!out) process.stdout.write(csv); return; }
const play = await playClient(root, need(config.play?.packageName, 'play.packageName'));
const pkg = need(config.play?.packageName, 'play.packageName');
const hash = dataSafetyHash(pkg, csv);
const last = lastUpload(root, pkg);
const same = last?.sha256 === hash;
if (ctx.args.has('dry')) {
if (!out) process.stdout.write(csv);
log('play', same ? `the same CSV was uploaded ${last!.at.slice(0, 16).replace('T', ' ')} UTC: a real run sends nothing (--force sends it again)` : 'a real run uploads it (it differs from the last upload, or none is recorded)');
return;
}
if (same && !ctx.args.has('force')) {
done('play', `data safety unchanged since the upload of ${last!.at.slice(0, 16).replace('T', ' ')} UTC: nothing sent (--force sends it again, e.g. after a change in Play Console)`);
return;
}
const play = await playClient(root, pkg);
await play.call('POST', `${play.API}/dataSafety`, { safetyLabels: csv });
// Play cannot read the form back: keep what went up, so the desktop app can show what changed since (gitignored).
try { mkdirSync(join(root, '.storebound'), { recursive: true }); writeFileSync(join(root, DATA_SAFETY_UPLOADED), csv); } catch { /* the upload itself worked */ }
// keep what went up: the hash skips the next identical upload, the CSV lets the desktop app show what changed since
try {
rememberUpload(root, pkg, hash);
writeFileSync(join(root, DATA_SAFETY_UPLOADED), csv);
} catch { /* the upload itself worked */ }
done('play', `data safety updated (${csv.split('\n').length - 2} rows)`);
}

View file

@ -3,8 +3,9 @@
// storebound play images [--dry] [--only en-US,de-DE] [--src store/renders] [--variant b]
// Per Play language, from <renders>/<language id>/: icon (play.icon, 512x512), featureGraphic (feature/1024x500.*),
// phoneScreenshots (play/NN.*), sevenInchScreenshots (tab7/NN.*), tenInchScreenshots (tab10/NN.*). A .jpg next to a
// .png wins (JPEG q92 uploads about 4x faster; `storebound shots jpeg` makes them). Each image type is cleared
// before uploading, so re-runs are idempotent. --variant <id> uploads <renders>/<id>/<lang>/... (an A/B variant from
// .png wins (JPEG q92 uploads about 4x faster; `storebound shots jpeg` makes them). Play's images are compared with
// the local files first (sha256, in order): only a changed image type is cleared and uploaded, in one edit per
// language that is committed whole or not at all, so a re-run changes nothing and never doubles an image. --variant <id> uploads <renders>/<id>/<lang>/... (an A/B variant from
// shots.variants) to the main listing: Play store listing experiments themselves are set up in Play Console (no API).
// Uploads are slow: run in the background with a log file.
// --dry is read-only: one throwaway edit, the images Play has now (their sha256) compared with the local files per
@ -71,36 +72,51 @@ export async function run(ctx: Ctx): Promise<void> {
log('play', `${codes.length} languages, ${[...sets.values()][0]?.reduce((n, [, f]) => n + f.length, 0) ?? 0} images each`);
const play = await playClient(root, pkg);
// one read-only edit: what Play has now (sha256 per image, in order) against the local files, per language and type
const plan = new Map<string, ImageChange[]>();
await play.read(async id => {
for (const code of codes) {
const out: ImageChange[] = [];
for (const [type, files] of sets.get(code)!) {
const remote = (await play.call<{ images?: { sha256?: string }[] }>('GET', `${play.API}/edits/${id}/listings/${code}/${type}`)).images ?? [];
out.push(imageChange(type, remote, files.map(sha256)));
}
plan.set(code, out);
}
});
const changedTypes = (code: string) => plan.get(code)!.filter(c => c.change === 'replace');
if (ctx.args.has('dry')) {
let changed = 0;
await play.read(async id => {
for (const [i, code] of codes.entries()) {
const out: ImageChange[] = [];
for (const [type, files] of sets.get(code)!) {
const remote = (await play.call<{ images?: { sha256?: string }[] }>('GET', `${play.API}/edits/${id}/listings/${code}/${type}`)).images ?? [];
out.push(imageChange(type, remote, files.map(sha256)));
}
const rep = out.filter(c => c.change === 'replace');
changed += rep.length;
log('play', `${step(i + 1, codes.length, code)}: ${rep.length ? 'would replace ' + rep.map(c => `${c.type} (${c.remote} -> ${c.local})`).join(', ') : 'unchanged'}`);
}
});
for (const [i, code] of codes.entries()) {
const rep = changedTypes(code);
changed += rep.length;
log('play', `${step(i + 1, codes.length, code)}: ${rep.length ? 'would replace ' + rep.map(c => `${c.type} (${c.remote} -> ${c.local})`).join(', ') : 'unchanged'}`);
}
done('play', `dry run: ${changed ? changed + ' image set(s) would be replaced' : 'every image set is already on Play'}; read-only, nothing uploaded`);
return;
}
for (const [i, code] of codes.entries()) {
// only languages with a changed image type get an edit, and in it only the changed types are cleared and uploaded.
// The edit is all or nothing: a failure (or an upload without a clear answer) deletes it, and the redo starts from
// what Play has, so a re-run never doubles an image.
const todo = codes.filter(code => changedTypes(code).length);
if (!todo.length) { done('play', 'every image set is already on Play: nothing uploaded'); return; }
for (const [i, code] of todo.entries()) {
const set = sets.get(code)!;
await play.edit(async id => {
let n = 0;
await play.edit(async (id, ctl) => {
let n = 0, types = 0;
await Promise.all(set.map(async ([type, files]) => {
await play.call('DELETE', `${play.API}/edits/${id}/listings/${code}/${type}`);
const remote = (await play.call<{ images?: { sha256?: string }[] }>('GET', `${play.API}/edits/${id}/listings/${code}/${type}`)).images ?? [];
if (imageChange(type, remote, files.map(sha256)).change === 'same') return;
types++;
if (remote.length) await play.call('DELETE', `${play.API}/edits/${id}/listings/${code}/${type}`);
for (const f of files) {
await play.call('POST', `${play.UPLOAD}/edits/${id}/listings/${code}/${type}?uploadType=media`, new Uint8Array(readFileSync(f)),
{ 'Content-Type': /\.png$/i.test(f) ? 'image/png' : 'image/jpeg' });
n++;
}
}));
log('play', `${step(i + 1, codes.length, code)}: ${n} images`);
if (!types) ctl.unchanged();
log('play', `${step(i + 1, todo.length, code)}: ${n} images in ${types} set(s)`);
});
}
done('play', 'images done');

View file

@ -140,16 +140,24 @@ export async function run(ctx: Ctx): Promise<void> {
if (dry) { done('play', `dry run: ${p.changes ? `${p.changes} change(s)` : 'nothing to change'}; read-only, nothing written`); return; }
if (!p.changes) { done('play', 'listing already up to date'); return; }
if (process.stdin.isTTY && !(await confirm(ctx, `Apply these ${p.changes} change(s) to Google Play (one edit, committed)?`))) { warn('play', 'nothing written'); return; }
const todo = p.listings.filter(l => l.action !== 'same').map(l => bodies.find(b => b.language === l.key)!);
await play.edit(async id => {
if (p.details.action !== 'same') {
// The edit compares again with what it holds (a Console save or another run since the plan): only differing details
// and languages are PUT; nothing left to change = the edit is deleted, not committed. Commit only after every PUT worked.
let sent = 0;
await play.edit(async (id, ctl) => {
const cur = await play.call<Record<string, string>>('GET', `${play.API}/edits/${id}/details`);
const now = (await play.call<{ listings?: PlayListing[] }>('GET', `${play.API}/edits/${id}/listings`)).listings ?? [];
const q = playPlan(cur, details, now, bodies, { only: a.has('only') });
const todo = q.listings.filter(l => l.action !== 'same').map(l => bodies.find(b => b.language === l.key)!);
sent = q.changes;
if (!q.changes) { ctl.unchanged(); return; }
if (q.details.action !== 'same') {
await play.call('PUT', `${play.API}/edits/${id}/details`, details);
log('play', `details: ${p.details.changes.map(ch => ch.field).join(', ')}`);
log('play', `details: ${q.details.changes.map(ch => ch.field).join(', ')}`);
}
for (const [i, b] of todo.entries()) {
await play.call('PUT', `${play.API}/edits/${id}/listings/${b.language}`, b);
log('play', step(i + 1, todo.length, b.language!));
}
});
done('play', 'listing done');
done('play', sent ? 'listing done' : 'listing already up to date (the edit was deleted, nothing committed)');
}

View file

@ -10,10 +10,26 @@ import { readFileSync, statSync } from 'node:fs';
import type { Ctx } from '../lib/ctx';
import { confirm, need } from '../lib/ctx';
import { done, log } from '../lib/log';
import { aabInfo } from '../lib/gradle';
import { playClient } from './client';
import { usedVersionCodes } from './next-version-code';
import { readPlayCopy } from './listing';
const TRACKS = ['internal', 'alpha', 'beta', 'production'];
export interface PlayTrackRelease { versionCodes?: string[]; status?: string; userFraction?: number; name?: string; releaseNotes?: { language: string; text: string }[] }
/** The track holds exactly this release already (one release, same codes, status, fraction, name and notes): a PUT
* would change nothing. Pure. */
export function sameRelease(cur: PlayTrackRelease[], want: PlayTrackRelease): boolean {
if (cur.length !== 1) return false;
const c = cur[0]!;
const notes = (n?: { language: string; text: string }[]) => JSON.stringify([...(n ?? [])].sort((x, y) => x.language.localeCompare(y.language)).map(x => [x.language, x.text.trim()]));
return (c.versionCodes ?? []).map(String).join() === (want.versionCodes ?? []).join() && c.status === want.status
&& (want.userFraction === undefined || Math.abs((c.userFraction ?? -1) - want.userFraction) < 1e-9)
&& (want.name === undefined || c.name === want.name)
&& (want.releaseNotes === undefined || notes(c.releaseNotes) === notes(want.releaseNotes));
}
const STATUSES = ['completed', 'draft', 'inProgress', 'halted'];
export async function run(ctx: Ctx): Promise<void> {
@ -33,23 +49,37 @@ export async function run(ctx: Ctx): Promise<void> {
const notes = readPlayCopy(ctx).filter(c => c.whatsNew).map(c => ({ language: c.lang, text: c.whatsNew }));
const play = await playClient(root, pkg);
try {
await play.edit(async id => {
await play.edit(async (id, ctl) => {
let code = fixed ?? '';
let uploaded = false;
if (aab) {
log('play', `uploading ${aab} (${(statSync(aab).size / 1048576).toFixed(1)} MB), this can take minutes`);
const b = await play.call<{ versionCode: number }>('POST', `${play.UPLOAD}/edits/${id}/bundles?uploadType=media`,
new Uint8Array(readFileSync(aab)), { 'Content-Type': 'application/octet-stream' });
code = String(b.versionCode);
log('play', `uploaded versionCode ${code}`);
// a versionCode Play already has (an earlier run uploaded it) is reused, never uploaded twice
const info = aabInfo(aab);
if ((await usedVersionCodes(play, id)).includes(info.versionCode)) {
code = String(info.versionCode);
log('play', `versionCode ${code} is on Play already: not uploaded again`);
} else {
log('play', `uploading ${aab} (${(statSync(aab).size / 1048576).toFixed(1)} MB), this can take minutes`);
const b = await play.call<{ versionCode: number }>('POST', `${play.UPLOAD}/edits/${id}/bundles?uploadType=media`,
new Uint8Array(readFileSync(aab)), { 'Content-Type': 'application/octet-stream' });
code = String(b.versionCode);
uploaded = true;
log('play', `uploaded versionCode ${code}`);
}
}
let changed = 0;
for (const t of tracks) {
const release: Record<string, unknown> = { versionCodes: [code], status: t.status };
const release: PlayTrackRelease = { versionCodes: [code], status: t.status };
if (notes.length) release.releaseNotes = notes;
if (a.get('name')) release.name = a.get('name');
if (t.status === 'inProgress') release.userFraction = Number(fraction ?? 0.1);
const cur = (await play.call<{ releases?: PlayTrackRelease[] }>('GET', `${play.API}/edits/${id}/tracks/${t.track}`).catch(() => ({ releases: [] }))).releases ?? [];
if (sameRelease(cur, release)) { log('play', `${t.track}: already ${t.status} ${code}, unchanged`); continue; }
await play.call('PUT', `${play.API}/edits/${id}/tracks/${t.track}`, { track: t.track, releases: [release] });
changed++;
log('play', `${t.track} <- ${code} (${t.status}, notes in ${notes.length} languages)`);
}
if (!changed && !uploaded) ctl.unchanged();
}, { dry: a.has('dry'), retries: aab ? 0 : 3 });
} catch (e) {
if (/draft app|status draft/i.test(String(e)))

View file

@ -10,6 +10,13 @@ import { done, log } from '../lib/log';
import { type PlayRelease, type RolloutAction, rolloutReleases } from '../lib/release';
import { playClient } from './client';
/** Same releases on the track, whatever their order and key order. Pure. */
export function sameReleases(a: PlayRelease[], b: PlayRelease[]): boolean {
const canon = (x: unknown): unknown => (Array.isArray(x) ? x.map(canon) : x && typeof x === 'object' ? Object.fromEntries(Object.entries(x).sort(([k], [l]) => k.localeCompare(l)).map(([k, v]) => [k, canon(v)])) : x);
const key = (rs: PlayRelease[]) => JSON.stringify(rs.map(r => JSON.stringify(canon(r))).sort());
return key(a) === key(b);
}
export function rolloutAction(a: Ctx['args']): RolloutAction {
const picked = ['halt', 'resume', 'complete'].filter(k => a.has(k));
if (picked.length > 1) throw new Error('pick one of --halt, --resume, --complete');
@ -30,10 +37,12 @@ export async function run(ctx: Ctx): Promise<void> {
const dry = ctx.args.has('dry');
const play = await playClient(root, need(config.play?.packageName, 'play.packageName'));
let confirmed = dry || action.kind === 'halt' || track !== 'production';
await play.edit(async id => {
await play.edit(async (id, ctl) => {
const cur = await play.call<{ releases?: PlayRelease[] }>('GET', `${play.API}/edits/${id}/tracks/${track}`);
const next = rolloutReleases(cur.releases ?? [], action);
log('play', `${track}: ${next.summary}${dry ? ' (dry)' : ''}`);
// already like that (a re-run, or the same command twice): nothing is committed
if (sameReleases(next.releases, cur.releases ?? [])) { ctl.unchanged(); return; }
if (!confirmed) confirmed = await confirm(ctx, `${track}: ${next.summary}. Apply?`);
if (!confirmed) throw new Error('not confirmed, nothing changed');
await play.call('PUT', `${play.API}/edits/${id}/tracks/${track}`, { track, releases: next.releases });

View file

@ -20,7 +20,13 @@ import {
playSubscriptionBody,
} from '../lib/subscriptions';
import { subscriptionCsv } from '../apple/subscriptions';
import { playClient } from './client';
import { createOnce } from '../lib/upsert';
import { playClient, type PlayClient } from './client';
/** GET of one Play resource, null on 404. */
export async function getOrNull<T>(play: PlayClient, url: string): Promise<T | null> {
try { return await play.call<T>('GET', url); } catch (e) { if (/-> 404/.test(String(e))) return null; throw e; }
}
const TAG = 'play';
interface Converted { convertedRegionPrices?: Record<string, { regionCode: string; price: Money }>; convertedOtherRegionsPrice?: { usdPrice: Money; eurPrice: Money }; regionVersion?: { version: string } }
@ -86,8 +92,12 @@ export async function run(ctx: Ctx): Promise<void> {
const id = encodeURIComponent(s.id);
const cur = existing.get(s.id);
if (diff.create) {
await play.call('POST', `${play.API}/subscriptions?productId=${id}&regionsVersion.version=${v}`, body);
log(TAG, `${s.id}: created`);
// product ids are unique: a 409 (or an unclear answer, then a fresh GET) finds the existing one, never a second
const r = await createOnce({ what: `subscription ${s.id}`, tag: TAG, unique: true,
find: () => getOrNull<PlaySubscription>(play, `${play.API}/subscriptions/${id}`),
create: () => play.call<PlaySubscription>('POST', `${play.API}/subscriptions?productId=${id}&regionsVersion.version=${v}`, body) });
log(TAG, `${s.id}: ${r.created ? 'created' : 'exists already (made by an earlier run); run again to compare it with the config'}`);
if (!r.created) continue;
} else if (diff.listings.length || diff.basePlan !== 'same') {
if (diff.basePlan === 'changed' && diff.priceChanges.length && !liveOk) warn(TAG, `${s.id}: ${diff.priceChanges.length} price change(s) skipped (run in a terminal to confirm)`);
else {
@ -107,10 +117,14 @@ export async function run(ctx: Ctx): Promise<void> {
offerRegions = { regions: Object.values(oc.convertedRegionPrices).map(r => ({ regionCode: r.regionCode, price: r.price })), other: oc.convertedOtherRegionsPrice };
}
const ob = playOfferBody(pkg, s, regions, offerRegions, extra);
await play.call('POST', `${play.API}/subscriptions/${id}/basePlans/${basePlanId(s)}/offers?offerId=${encodeURIComponent(ob.offerId)}&regionsVersion.version=${v}`, ob);
await play.call('POST', `${play.API}/subscriptions/${id}/basePlans/${basePlanId(s)}/offers/${encodeURIComponent(ob.offerId)}:activate`,
{ packageName: pkg, productId: s.id, basePlanId: basePlanId(s), offerId: ob.offerId });
log(TAG, `${s.id}: offer ${ob.offerId} created and activated`);
const offerUrl = `${play.API}/subscriptions/${id}/basePlans/${basePlanId(s)}/offers`;
// offer ids are unique per base plan: a 409 or an unclear answer finds the existing offer, never a second one
const r = await createOnce({ what: `${s.id} offer ${ob.offerId}`, tag: TAG, unique: true,
find: () => getOrNull<{ state?: string }>(play, `${offerUrl}/${encodeURIComponent(ob.offerId)}`),
create: () => play.call<{ state?: string }>('POST', `${offerUrl}?offerId=${encodeURIComponent(ob.offerId)}&regionsVersion.version=${v}`, ob) });
if (r.value.state !== 'ACTIVE')
await play.call('POST', `${offerUrl}/${encodeURIComponent(ob.offerId)}:activate`, { packageName: pkg, productId: s.id, basePlanId: basePlanId(s), offerId: ob.offerId });
log(TAG, `${s.id}: offer ${ob.offerId} ${r.created ? 'created and activated' : 'exists already, active'}`);
};
if (s.intro && offerMissing) await createOffer(s.intro);
for (const o of (s.offers ?? []).filter(x => extraMissing.includes(x.id))) await createOffer(o, o);

View file

@ -48,6 +48,12 @@ export async function run(ctx: Ctx): Promise<void> {
used: await usedVersionCodes(play, id),
current: (await play.call<{ releases?: { status: string; versionCodes?: string[] }[] }>('GET', `${play.API}/edits/${id}/tracks/${track}`).catch(() => ({ releases: [] }))).releases ?? [],
}));
// an earlier run did it already (the bundle is on Play and on this track): nothing to send again
if (used.includes(info.versionCode) && current.some(r => (r.versionCodes ?? []).includes(String(info.versionCode)) && r.status === status)) {
if (json) { printJson({ aab: relative(root, aab), packageName: info.packageName, versionCode: info.versionCode, track, status, uploaded: true, alreadyThere: true }); return; }
done(TAG, `versionCode ${info.versionCode} is on ${track} (${status}) already: nothing uploaded`);
return;
}
if (used.includes(info.versionCode)) throw new Error(`versionCode ${info.versionCode} is already on Google Play: rebuild with --version-code ${nextVersionCode(used)} (storebound play build)`);
const summary = { aab: relative(root, aab), packageName: info.packageName, versionCode: info.versionCode, versionName: info.versionName ?? null, sizeMB: Math.round(size / 104857.6) / 10,
track, status, notes: notes.map(n => n.language), replaces: current.map(r => `${r.status} ${(r.versionCodes ?? []).join(',')}`) };

View file

@ -22,6 +22,7 @@
// POST .../packages/{id}/actions/attach_products
import { credentialValue } from './lib/credentials';
import { confirm, type Ctx, need } from './lib/ctx';
import { AmbiguousWriteError, createOnce } from './lib/upsert';
import { errorBody } from './lib/http';
import { done, log, printJson, warn } from './lib/log';
import {
@ -46,11 +47,18 @@ export function rcClient(key: string, o: { retries?: number } = {}): RcClient {
const u = new URL(url, ORIGIN);
if (u.origin !== ORIGIN) throw new Error(`RevenueCat: refusing to send the key to ${u.origin}`);
for (let attempt = 0; ; attempt++) {
const r = await fetch(u, {
method, signal: AbortSignal.timeout(30_000),
headers: { 'Authorization': `Bearer ${key}`, 'Accept': 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },
body: body === undefined ? undefined : JSON.stringify(body),
});
let r: Response;
try {
r = await fetch(u, {
method, signal: AbortSignal.timeout(30_000),
headers: { 'Authorization': `Bearer ${key}`, 'Accept': 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },
body: body === undefined ? undefined : JSON.stringify(body),
});
} catch (e) {
// a POST without an answer may have been applied: callers look before sending it again (createOnce)
if (method === 'POST') throw new AmbiguousWriteError(redact(`RevenueCat ${method} ${u.pathname}: no answer (${(e as Error).message})`));
throw e;
}
if (r.status === 429 && attempt < (o.retries ?? 3)) {
const s = Math.min(60, Math.max(0, Number(r.headers.get('retry-after') ?? '5') || 0));
warn(TAG, `rate limited, waiting ${s}s`);
@ -59,6 +67,7 @@ export function rcClient(key: string, o: { retries?: number } = {}): RcClient {
continue;
}
const text = await r.text();
if (!r.ok && r.status >= 500 && method === 'POST') throw new AmbiguousWriteError(redact(`RevenueCat ${method} ${u.pathname}: ${r.status} ${errorBody(text, 500)}`), r.status);
if (!r.ok) {
const hint = r.status === 401 || r.status === 403 ? ' (REVENUECAT_SECRET_KEY: a v2 secret key with project configuration permissions for this project)' : '';
throw new Error(redact(`RevenueCat ${method} ${u.pathname}: ${r.status} ${errorBody(text, 500)}${hint}`));
@ -172,15 +181,22 @@ export async function execute(c: RcClient, projectId: string, plan: RcStep[], st
let offering = current?.id ?? '';
const pkgId = new Map((current?.packages ?? []).map(p => [p.lookup_key, p.id] as const));
const pid = (k: string) => { const id = productId.get(k); if (!id) throw new Error(`RevenueCat product ${k} was not created`); return id; };
// creates go through createOnce: a 409 (lookup key / store identifier taken) or an unclear answer finds the existing
// one by its key with a fresh list, never a second one; attaching and is_current are the same when sent twice
const once = async (what: string, list: string, match: (x: J) => boolean, create: () => Promise<J>): Promise<string> =>
(await createOnce<J>({ what, tag: TAG, unique: true, find: async () => (await c.all(list)).find(match) ?? null, create })).value.id as string;
for (const [i, s] of plan.entries()) {
log(TAG, `${i + 1}/${plan.length} ${s.what}`);
switch (s.op) {
case 'create-product': productId.set(s.key, (await c.post(`${P}/products`, s.body)).id); break;
case 'create-entitlement': entId.set(s.lookupKey, (await c.post(`${P}/entitlements`, s.body)).id); break;
case 'create-product': productId.set(s.key, await once(s.what, `${P}/products?limit=100`, x => x.app_id === s.body.app_id && x.store_identifier === s.body.store_identifier, () => c.post(`${P}/products`, s.body))); break;
case 'create-entitlement': entId.set(s.lookupKey, await once(s.what, `${P}/entitlements?limit=100`, x => x.lookup_key === s.lookupKey, () => c.post(`${P}/entitlements`, s.body))); break;
case 'attach-entitlement':
await c.post(`${P}/entitlements/${encodeURIComponent(entId.get(s.lookupKey)!)}/actions/attach_products`, { product_ids: s.products.map(pid) }); break;
case 'create-offering': offering = (await c.post(`${P}/offerings`, s.body)).id; break;
case 'create-package': pkgId.set(s.lookupKey, (await c.post(`${P}/offerings/${encodeURIComponent(offering)}/packages`, s.body)).id); break;
case 'create-offering': offering = await once(s.what, `${P}/offerings?limit=100`, x => x.lookup_key === s.lookupKey, () => c.post(`${P}/offerings`, s.body)); break;
case 'create-package': {
const pkgs = `${P}/offerings/${encodeURIComponent(offering)}/packages`;
pkgId.set(s.lookupKey, await once(s.what, `${pkgs}?limit=100`, x => x.lookup_key === s.lookupKey, () => c.post(pkgs, s.body))); break;
}
case 'attach-package':
await c.post(`${P}/packages/${encodeURIComponent(pkgId.get(s.lookupKey)!)}/actions/attach_products`, { products: s.products.map(k => ({ product_id: pid(k), eligibility_criteria: 'all' })) }); break;
case 'set-current': await c.post(`${P}/offerings/${encodeURIComponent(offering)}`, { is_current: true }); break;

View file

@ -14,6 +14,7 @@
// Google Play's API only returns reviews created or edited in the last 7 days.
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join, relative, resolve } from 'node:path';
import { isConflict } from './lib/upsert';
import { ascClient, type J } from './apple/asc';
import type { Ctx } from './lib/ctx';
import { confirm } from './lib/ctx';
@ -138,8 +139,14 @@ export async function run(ctx: Ctx): Promise<void> {
for (const d of plan.send) {
const req = replyRequest(d, config.play?.packageName);
try {
if (d.store === 'apple') await c!.asc(req.method, req.url, req.body);
else await play!.call(req.method, req.url, req.body);
// Play's :reply replaces the reply (safe to send again); Apple keeps one response per review and answers a
// second one with 409: then an earlier run sent it (and stopped before noting it), so it is noted now
if (d.store === 'apple') {
try { await c!.asc(req.method, req.url, req.body); } catch (e) {
if (!isConflict(e)) throw e;
warn(TAG, `${d.file.split('/').pop()}: the review already has a response on the App Store (an earlier run sent it); noted as sent, not sent again`);
}
} else await play!.call(req.method, req.url, req.body);
writeFileSync(d.file, markSent(texts.get(d.file)!, new Date().toISOString()));
sent++;
log(TAG, `sent ${d.file.split('/').pop()}`);

231
cli/shots/capture-web.ts Normal file
View file

@ -0,0 +1,231 @@
// Web capture (shots.capture.source "web"), parallel and incremental:
// --concurrency N browser contexts in one headless Chromium (default shots.capture.concurrency, else from the CPU
// count: a WebGL game is GPU-bound, so capture defaults lower than render). Files do not depend on
// the order: every frame has its own path.
// session shots.capture.session "per-shot" (default: a new context + page and a full boot per frame) or
// "per-language": one page per language and device, booted once; the next shots switch scenes in
// that page (navigate "spa": history.pushState + popstate to the shot's path, then waitFor / eval;
// navigate "reload": page.goto in the same page). A precondition that fails there (waitFor times out
// after reuseTimeoutMs) falls back to a fresh page.
// cache .storebound/capture-cache.json: per frame a hash of its inputs (shot entry, URL + query, frame
// size, session, the copy text of its language, the app build (shots.capture.build files, else
// the HTML and scripts at baseUrl), fonts.css). Unchanged frames that exist are skipped;
// --only-missing only captures frames that do not exist; --force captures everything.
// timing per frame: goto, waitFor, eval, delay, screenshot, total, in the progress line and in
// .storebound/capture-report.json, with the slowest frames and steps at the end.
import { createHash } from 'node:crypto';
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
import { availableParallelism, cpus } from 'node:os';
import { join } from 'node:path';
import type { ShotSpec, ShotsCapture } from '../lib/config';
import { log, warn } from '../lib/log';
import { shotsFor } from './devices';
import type { FrameDims } from './lib';
type Device = 'phone' | 'tablet';
export const STEPS = ['goto', 'waitFor', 'eval', 'delay', 'screenshot'] as const;
export type Step = typeof STEPS[number];
export type Timing = Record<Step | 'total', number>;
/** frame = path relative to shots.frames (cache and report key), out = absolute file. */
export interface WebJob { lang: string; device: Device; name: string; spec: ShotSpec; url: string; path: string; out: string; frame: string; hash: string }
/** CPU cores (availableParallelism where Bun has it). */
export const coreCount = (): number => { try { return availableParallelism(); } catch { return cpus().length || 2; } };
/** Default parallel workers: render min(4, cores / 2); capture (GPU-heavy WebGL / game boots) min(3, cores / 4). */
export function defaultConcurrency(kind: 'render' | 'capture', cores = coreCount()): number {
return Math.max(1, kind === 'render' ? Math.min(4, Math.floor(cores / 2)) : Math.min(3, Math.floor(cores / 4)));
}
/** Runs fn over items with at most n at a time; results keep the input order. */
export async function pool<T, R>(items: T[], n: number, fn: (item: T, index: number) => Promise<R>): Promise<R[]> {
const out = new Array<R>(items.length);
let next = 0;
const worker = async (): Promise<void> => { while (next < items.length) { const i = next++; out[i] = await fn(items[i]!, i); } };
await Promise.all(Array.from({ length: Math.max(1, Math.min(n, items.length)) }, worker));
return out;
}
const fmtS = (ms: number): string => (ms >= 60_000 ? `${Math.floor(ms / 60_000)}m${String(Math.round((ms % 60_000) / 1000)).padStart(2, '0')}s` : `${(ms / 1000).toFixed(1)}s`);
/** "n/total, ETA" progress for parallel work: ETA = remaining items x average wall time per finished item. */
export function progressLine(done: number, total: number, startedMs: number, nowMs = Date.now()): string {
const w = String(total).length;
const eta = done ? ((nowMs - startedMs) / done) * (total - done) : 0;
return `${String(done).padStart(w)}/${total}${done < total && done ? ` ETA ${fmtS(eta)}` : ''}`;
}
export const timingText = (t: Timing): string => `goto ${fmtS(t.goto)} wait ${fmtS(t.waitFor)} eval ${fmtS(t.eval)} delay ${fmtS(t.delay)} shot ${fmtS(t.screenshot)} = ${fmtS(t.total)}`;
/** Slowest frames and the time per step over all frames (for the end of the log and the report). */
export function timingSummary(frames: { frame: string; timing: Timing }[], top = 5): { slowest: { frame: string; total: number; step: Step }[]; steps: Record<Step, number>; total: number } {
const steps = Object.fromEntries(STEPS.map(s => [s, 0])) as Record<Step, number>;
for (const f of frames) for (const s of STEPS) steps[s] += f.timing[s];
const slowest = [...frames].sort((a, b) => b.timing.total - a.timing.total).slice(0, top)
.map(f => ({ frame: f.frame, total: f.timing.total, step: STEPS.reduce((m, s) => (f.timing[s] > f.timing[m] ? s : m), STEPS[0] as Step) }));
return { slowest, steps, total: frames.reduce((t, f) => t + f.timing.total, 0) };
}
const sha = (s: string | Uint8Array): string => createHash('sha256').update(s).digest('hex').slice(0, 16);
/** Content hash of build files (a file or folder; node_modules / dot folders skipped): paths, sizes and mtimes. */
export function hashPaths(paths: string[]): string {
const h = createHash('sha256');
const walk = (p: string): void => {
if (!existsSync(p)) { h.update(`missing:${p}`); return; }
const st = statSync(p);
if (st.isDirectory()) { for (const e of readdirSync(p).sort()) if (e !== 'node_modules' && !e.startsWith('.')) walk(join(p, e)); return; }
h.update(`${p}:${st.size}:${st.mtimeMs}\n`);
};
for (const p of paths) walk(p);
return h.digest('hex').slice(0, 16);
}
/** App build fingerprint from the running server: the HTML at baseUrl and the scripts it loads (dev servers too). */
export async function hashServed(baseUrl: string): Promise<string> {
try {
const html = await (await fetch(baseUrl, { signal: AbortSignal.timeout(10_000) })).text();
const h = createHash('sha256').update(html);
for (const m of html.matchAll(/<script[^>]+src=["']([^"']+)["']/g)) {
try { h.update(await (await fetch(new URL(m[1]!, baseUrl), { signal: AbortSignal.timeout(10_000) })).text()); } catch { h.update(`unreachable:${m[1]}`); }
}
return h.digest('hex').slice(0, 16);
} catch { return 'unreachable'; }
}
/** Every web frame to capture, in a fixed order (lang, device, shot), with its URL and its input hash. */
export function planWeb(cap: ShotsCapture, o: { langs: string[]; devices: Device[]; only: string[]; dims: Record<Device, FrameDims>; framesDir: string;
build: string; copyText?: (lang: string) => string; fonts?: string }): WebJob[] {
const jobs: WebJob[] = [];
for (const lang of o.langs) for (const device of o.devices) for (const [name, spec] of shotsFor(cap, device, o.only)) {
const q = (cap.query ?? '').replaceAll('{lang}', lang);
const path = (spec.path ?? '/').replaceAll('{lang}', lang) + (q ? ((spec.path ?? '/').includes('?') ? '&' : '?') + q : '');
const url = (cap.baseUrl ?? '').replace(/\/$/, '') + path;
const hash = sha(JSON.stringify({ spec, url, dims: o.dims[device], session: cap.session ?? 'per-shot', build: o.build, copy: o.copyText?.(lang) ?? '', fonts: o.fonts ?? '' }));
const frame = `${lang}/${device}/${name}.png`;
jobs.push({ lang, device, name, spec, url, path, out: join(o.framesDir, frame), frame, hash });
}
return jobs;
}
export type Cache = Record<string, string>;
export const cachePath = (root: string): string => join(root, '.storebound', 'capture-cache.json');
export function readCache(root: string): Cache { try { return JSON.parse(readFileSync(cachePath(root), 'utf8')) as Cache; } catch { return {}; } }
/** Which jobs to run: --force all; --only-missing the ones whose file is missing; else missing or changed inputs. */
export function selectJobs(jobs: WebJob[], cache: Cache, mode: 'force' | 'only-missing' | 'changed', exists: (file: string) => boolean = existsSync): { run: WebJob[]; skipped: WebJob[] } {
const run: WebJob[] = [], skipped: WebJob[] = [];
for (const j of jobs) {
const keep = mode === 'force' ? false : mode === 'only-missing' ? exists(j.out) : exists(j.out) && cache[j.frame] === j.hash;
(keep ? skipped : run).push(j);
}
return { run, skipped };
}
export interface CaptureReport {
at: string; concurrency: number; session: string; wallMs: number;
frames: { frame: string; ok: boolean; reused: boolean; timing: Timing; error?: string }[];
skipped: string[];
summary: ReturnType<typeof timingSummary>;
}
/* eslint-disable @typescript-eslint/no-explicit-any */
/** Captures the jobs in a browser: per-shot contexts, or one page per language + device in per-language sessions. */
export async function captureWeb(browser: any, cap: ShotsCapture, jobs: WebJob[], o: { concurrency: number; dims: Record<Device, FrameDims> }): Promise<CaptureReport> {
const started = Date.now();
const perLang = cap.session === 'per-language';
const report: CaptureReport['frames'] = [];
let finished = 0;
const total = jobs.length;
const newPage = async (j: WebJob): Promise<{ c: any; page: any; errs: string[] }> => {
const d = o.dims[j.device];
const c = await browser.newContext({ viewport: { width: d.w, height: d.h }, deviceScaleFactor: d.dpr, hasTouch: true, isMobile: true, serviceWorkers: 'block', locale: j.lang });
const page = await c.newPage();
const errs: string[] = [];
page.on('pageerror', (e: Error) => errs.push(e.message));
return { c, page, errs };
};
const shoot = async (s: { page: any; errs: string[] }, j: WebJob, how: 'goto' | 'spa', waitTimeout: number): Promise<Timing> => {
const t: Timing = { goto: 0, waitFor: 0, eval: 0, delay: 0, screenshot: 0, total: 0 };
let t0 = Date.now();
if (how === 'goto') await s.page.goto(j.url, { waitUntil: 'domcontentloaded', timeout: 90000 });
else await s.page.evaluate(`(p => { if (location.pathname + location.search !== p) { history.pushState(null, '', p); dispatchEvent(new PopStateEvent('popstate', { state: null })); } })(${JSON.stringify(j.path)})`);
t.goto = Date.now() - t0; t0 = Date.now();
if (j.spec.waitFor) await s.page.waitForFunction(j.spec.waitFor, null, { timeout: waitTimeout, polling: 50 });
t.waitFor = Date.now() - t0; t0 = Date.now();
for (const js of j.spec.eval ?? []) await s.page.evaluate(js);
t.eval = Date.now() - t0; t0 = Date.now();
await s.page.waitForTimeout(j.spec.delayMs ?? 1000);
t.delay = Date.now() - t0; t0 = Date.now();
mkdirSync(join(j.out, '..'), { recursive: true });
await s.page.screenshot({ path: j.out });
t.screenshot = Date.now() - t0;
t.total = t.goto + t.waitFor + t.eval + t.delay + t.screenshot;
return t;
};
const record = (j: WebJob, r: { ok: boolean; reused: boolean; timing: Timing; error?: string; errs?: string[] }): void => {
finished++;
report.push({ frame: j.frame, ok: r.ok, reused: r.reused, timing: r.timing, ...(r.error ? { error: r.error } : {}) });
const head = `${progressLine(finished, total, started)} ${j.lang}/${j.device}/${j.name}`;
if (r.ok) log('shots', `${head}.png ${r.reused ? '(reused page) ' : ''}${timingText(r.timing)}${r.errs?.length ? ' (page errors: ' + r.errs.join(' | ').slice(0, 200) + ')' : ''}`);
else warn('shots', `${head}: ${r.error}`);
};
const zero = (): Timing => ({ goto: 0, waitFor: 0, eval: 0, delay: 0, screenshot: 0, total: 0 });
if (!perLang) {
await pool(jobs, o.concurrency, async j => {
const s = await newPage(j);
try { const timing = await shoot(s, j, 'goto', 120000); record(j, { ok: true, reused: false, timing, errs: s.errs }); }
catch (e) { record(j, { ok: false, reused: false, timing: zero(), error: (e as Error).message.split('\n')[0]!.slice(0, 300) }); }
await s.c.close();
});
} else {
// one group per language + device, its shots in order on one booted page
const groups = new Map<string, WebJob[]>();
for (const j of jobs) { const k = `${j.lang}/${j.device}`; groups.set(k, [...(groups.get(k) ?? []), j]); }
await pool([...groups.values()], o.concurrency, async group => {
let s: Awaited<ReturnType<typeof newPage>> | null = null;
for (const j of group) {
const nav = j.spec.navigate ?? 'spa';
if (s) {
try {
const timing = await shoot(s, j, nav === 'reload' ? 'goto' : 'spa', cap.reuseTimeoutMs ?? 15000);
record(j, { ok: true, reused: true, timing, errs: s.errs });
continue;
} catch (e) {
warn('shots', `${j.lang}/${j.device}/${j.name}: reused page failed (${(e as Error).message.split('\n')[0]!.slice(0, 120)}), fresh page`);
await s.c.close(); s = null;
}
}
s = await newPage(j);
try { const timing = await shoot(s, j, 'goto', 120000); record(j, { ok: true, reused: false, timing, errs: s.errs }); }
catch (e) { record(j, { ok: false, reused: false, timing: zero(), error: (e as Error).message.split('\n')[0]!.slice(0, 300) }); await s.c.close(); s = null; }
}
if (s) await s.c.close();
});
}
const order = new Map(jobs.map((j, i) => [j.frame, i] as const));
report.sort((a, b) => order.get(a.frame)! - order.get(b.frame)!);
const ok = report.filter(f => f.ok);
return { at: new Date().toISOString(), concurrency: o.concurrency, session: cap.session ?? 'per-shot', wallMs: Date.now() - started, frames: report, skipped: [],
summary: timingSummary(ok.map(f => ({ frame: f.frame, timing: f.timing }))) };
}
/* eslint-enable @typescript-eslint/no-explicit-any */
/** Log lines for the end of a capture: wall time, sum of frame time, slowest frames and steps. */
export function summaryLines(r: CaptureReport): string[] {
const s = r.summary;
const lines = [`${r.frames.filter(f => f.ok).length} frames in ${fmtS(r.wallMs)} wall (${fmtS(s.total)} of frame time, ${r.concurrency} at a time, session ${r.session})`];
if (s.total) lines.push('time per step: ' + STEPS.map(st => `${st} ${fmtS(s.steps[st])} (${Math.round((100 * s.steps[st]) / s.total)} %)`).join(', '));
for (const f of s.slowest) lines.push(`slowest: ${f.frame} ${fmtS(f.total)} (mostly ${f.step})`);
return lines;
}
export function writeCaptureState(root: string, report: CaptureReport, cache: Cache, captured: WebJob[]): void {
mkdirSync(join(root, '.storebound'), { recursive: true });
const okFrames = new Set(report.frames.filter(f => f.ok).map(f => f.frame));
for (const j of captured) if (okFrames.has(j.frame)) cache[j.frame] = j.hash;
writeFileSync(cachePath(root), JSON.stringify(Object.fromEntries(Object.entries(cache).sort()), null, 1) + '\n');
writeFileSync(join(root, '.storebound', 'capture-report.json'), JSON.stringify(report, null, 1) + '\n');
}

View file

@ -1,11 +1,12 @@
// Raw frames from a running build of your app or game, from any engine.
// storebound shots capture [--lang en,tr] [--only hero,shop] [--device phone|tablet] [--source web|ios-sim|android-emu|folder]
// [--dry] [--keep-booted]
// [--dry] [--keep-booted] [--concurrency N] [--only-missing | --force]
// Frames go to <shots.frames>/<lang>/<device>/<name>.png: the screen BELOW the status bar (the template draws one).
// shots.capture.source (default web):
// web headless Chromium (playwright), mobile viewport + touch at phone / tablet size. Each shot:
// { path, waitFor?: JS expression that turns true, eval?: [JS], delayMs?, device? }; URL = baseUrl + path +
// query, "{lang}" replaced.
// query, "{lang}" replaced. Parallel contexts, per-language page reuse, the input-hash cache and the
// per-frame timing (goto / waitFor / eval / delay / screenshot): capture-web.ts.
// ios-sim xcrun simctl: boots the simulator (ios.device / ios.devices.tablet), optional install of ios.app, status
// bar 9:41 / full battery / full bars, one warm-up launch after a cold boot (ios.warmupMs), then per shot:
// launch ios.bundleId with -AppleLanguages (xx) -AppleLocale + ios.args + shot.args, open shot.url
@ -33,7 +34,8 @@ import { checkFrameFolder } from './check';
import { adbAppLocaleArgs, adbDemoExitArgs, adbDemoModeArgs, adbForceStopArgs, adbInstallArgs, adbScreencapArgs, adbStartArgs, adbStateArgs, adbTarget,
cropArgs, cropTopFor, fill, pickSimulator, shotsFor, simBootArgs, simBootStatusArgs, simInstallArgs, simLaunchArgs, simOpenUrlArgs,
simScreenshotArgs, simShutdownArgs, simStatusBarArgs, simStatusBarClearArgs, simTarget, SOURCES, type Source, TOOL_HINTS, validateCapture } from './devices';
import { type FrameDims, frameDims } from './lib';
import { type CopyFile, copyText, type FrameDims, frameDims } from './lib';
import { captureWeb, defaultConcurrency, hashPaths, hashServed, planWeb, readCache, selectJobs, summaryLines, writeCaptureState } from './capture-web';
import { imageInfo } from './spec';
type Device = 'phone' | 'tablet';
@ -120,29 +122,29 @@ export async function run(ctx: Ctx): Promise<void> {
for (const lang of langs) for (const device of devices) for (const [name, s] of shotsFor(cap, device, only)) progress(`${lang}/${device}/${name}.png <- ${cap.baseUrl}${(s.path ?? '/').replaceAll('{lang}', lang)}`);
return done('shots', `capture planned (dry run): ${total} frames from web`);
}
const browser = await launch(root, { headless: true, args: ['--mute-audio', '--ignore-gpu-blocklist', '--enable-webgl', '--enable-gpu'] });
try {
for (const lang of langs) for (const device of devices) for (const [name, s] of shotsFor(cap, device, only)) {
const d = dims[device];
const q = (cap.query ?? '').replaceAll('{lang}', lang);
const path = (s.path ?? '/').replaceAll('{lang}', lang);
const url = need(cap.baseUrl, 'shots.capture.baseUrl').replace(/\/$/, '') + path + (q ? (path.includes('?') ? '&' : '?') + q : '');
const c = await browser.newContext({ viewport: { width: d.w, height: d.h }, deviceScaleFactor: d.dpr, hasTouch: true, isMobile: true, serviceWorkers: 'block', locale: lang });
const page = await c.newPage();
const errs: string[] = [];
page.on('pageerror', (e: Error) => errs.push(e.message));
try {
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 90000 });
if (s.waitFor) await page.waitForFunction(s.waitFor, null, { timeout: 120000, polling: 50 });
for (const js of s.eval ?? []) await page.evaluate(js);
await page.waitForTimeout(s.delayMs ?? 1000);
await page.screenshot({ path: target(lang, device, name) });
n++;
progress(`${lang}/${device}/${name}.png${errs.length ? ' (page errors: ' + errs.join(' | ').slice(0, 200) + ')' : ''}`);
} catch (e) { failed++; warn('shots', `${lang}/${device}/${name}: ${(e as Error).message.slice(0, 300)}`); }
await c.close();
}
} finally { await browser.close(); }
need(cap.baseUrl, 'shots.capture.baseUrl');
const concurrency = a.num('concurrency', cap.concurrency ?? defaultConcurrency('capture'));
const builds = cap.build ? (Array.isArray(cap.build) ? cap.build : [cap.build]).map(p => resolve(p)) : [];
const build = builds.length ? hashPaths(builds) : await hashServed(cap.baseUrl!);
let copy: CopyFile = {};
try { copy = JSON.parse(readFileSync(resolve(shots.copy), 'utf8')) as CopyFile; } catch { /* no copy yet */ }
const fontsCss = join(root, '.storebound', 'fonts', 'fonts.css');
const jobs = planWeb(cap, { langs, devices, only, dims, framesDir, build, copyText: l => copyText(l, copy[l]),
fonts: existsSync(fontsCss) ? readFileSync(fontsCss, 'utf8') : '' });
const cache = readCache(root);
const { run: todo, skipped } = selectJobs(jobs, cache, a.has('force') ? 'force' : a.has('only-missing') ? 'only-missing' : 'changed');
if (skipped.length) log('shots', `${skipped.length} of ${jobs.length} frames unchanged, skipped (${a.has('only-missing') ? '--only-missing' : 'same inputs as last time'}; --force captures them again)`);
log('shots', `capturing ${todo.length} frames, ${Math.min(concurrency, todo.length) || 0} at a time${cap.session === 'per-language' ? ', one page per language' : ''}`);
if (todo.length) {
const browser = await launch(root, { headless: true, args: ['--mute-audio', '--ignore-gpu-blocklist', '--enable-webgl', '--enable-gpu'] });
let report;
try { report = await captureWeb(browser, cap, todo, { concurrency, dims }); } finally { await browser.close(); }
report.skipped = skipped.map(j => j.frame);
writeCaptureState(root, report, cache, todo);
for (const l of summaryLines(report)) log('shots', l);
n += report.frames.filter(f => f.ok).length;
failed += report.frames.filter(f => !f.ok).length;
}
}
if (source === 'ios-sim') {

View file

@ -6,7 +6,8 @@
// Per set: Play 2-8 phone screenshots, Apple 1-10 per display type, 13" iPad set when apple.ipad, feature graphic.
// Per app preview: 886x1920 / 1200x1600, H.264, <= 30 fps, 15-30 s, stereo AAC track, <= 500 MB, <= 3 per set.
// Text overflow flags come from the last `shots render` (report.json). Frames: with capture.source "folder" every frame
// the scenes use must exist with the right aspect. Exit 1 on any error (warnings do not fail).
// the scenes use must exist with the right aspect. Local font files (shots.fonts paths) without a license note: warn.
// Exit 1 on any error (warnings do not fail).
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import type { ShipConfig } from '../lib/config';
@ -17,6 +18,8 @@ import { defaultSizes, frameDims, SIZES } from './lib';
import type { LocalIssue, RendersCheck } from '../lib/validate-rules';
import { allIssues, requiredSets, type RendersScan, scanRenders, storeOf } from './report';
import { imageInfo } from './spec';
import { fontsDirOf, readManifest } from './fonts';
import { localFontIssues } from './local-fonts';
/** Frame files the scenes (and the feature graphic) use, per language and device class. */
export function framesNeeded(config: ShipConfig, langs: string[]): { lang: string; device: 'phone' | 'tablet'; name: string }[] {
@ -58,9 +61,9 @@ export function rendersCheck(config: ShipConfig, dir: string): Record<'apple' |
}
export async function run(ctx: Ctx): Promise<void> {
const { config, resolve } = ctx.loaded;
const { config, resolve, root } = ctx.loaded;
const scan = scanProject(ctx);
const issues = allIssues(scan);
const issues = [...allIssues(scan), ...localFontIssues(readManifest(fontsDirOf(root))).map(issue => ({ where: '.storebound/fonts/fonts.json', issue }))];
const cap = config.shots?.capture;
const frameIssues = cap?.source === 'folder' ? checkFrameFolder(config, resolve(cap.folder ?? config.shots!.frames), scan.langs) : [];
if (ctx.args.has('json')) {

View file

@ -8,20 +8,25 @@ const tag = (d: DataView, o: number): string => String.fromCharCode(d.getUint8(o
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 {
export const cmapTable = (file: Uint8Array): Uint8Array => fontTable(file, 'cmap');
/** One raw (untransformed) table of a font file, e.g. 'cmap' or 'name'. Throws when the file is not a font or the
* table is missing. */
export function fontTable(file: Uint8Array, want: string): Uint8Array {
const d = view(file);
if (file.byteLength < 12) throw new Error('not a font file (too short)');
const sig = tag(d, 0);
if (sig === 'wOF2') return woff2Cmap(file);
if (sig === 'wOF2') return woff2Table(file, want);
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;
if (tag(d, o) !== want) 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');
throw new Error(`woff: no ${want} table`);
}
let base = 0;
if (sig === 'ttcf') base = d.getUint32(12);
@ -29,9 +34,9 @@ export function cmapTable(file: Uint8Array): Uint8Array {
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)); }
if (tag(d, o) === want) { const off = d.getUint32(o + 8); return file.subarray(off, off + d.getUint32(o + 12)); }
}
throw new Error('sfnt: no cmap table');
throw new Error(`sfnt: no ${want} table`);
}
const WOFF2_TAGS = ['cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'post', 'cvt ', 'fpgm', 'glyf', 'loca', 'prep', 'CFF ', 'VORG',
@ -39,7 +44,7 @@ const WOFF2_TAGS = ['cmap', 'head', 'hhea', 'hmtx', 'maxp', 'name', 'OS/2', 'pos
'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 {
function woff2Table(file: Uint8Array, want: string): Uint8Array {
const d = view(file);
const n = d.getUint16(12), compLen = d.getUint32(20);
let p = 48;
@ -56,10 +61,10 @@ function woff2Cmap(file: Uint8Array): Uint8Array {
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];
if (t === want) found = [off, orig];
off += len;
}
if (!found) throw new Error('woff2: no cmap table');
if (!found) throw new Error(`woff2: no ${want} 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; };
@ -110,6 +115,28 @@ function readSub(d: DataView, o: number, out: Set<number>): void {
}
}
/** Family name from the name table (typographic family 16, else family 1; Windows Unicode, else Mac Roman), or null. */
export function fontFamilyName(file: Uint8Array): string | null {
let t: Uint8Array;
try { t = fontTable(file, 'name'); } catch { return null; }
const d = view(t);
const count = d.getUint16(2), strings = d.getUint16(4);
const recs: { pid: number; lang: number; id: number; text: string }[] = [];
for (let i = 0; i < count && 6 + i * 12 + 12 <= t.byteLength; i++) {
const o = 6 + i * 12;
const pid = d.getUint16(o), lang = d.getUint16(o + 4), id = d.getUint16(o + 6), len = d.getUint16(o + 8), off = strings + d.getUint16(o + 10);
if ((id !== 1 && id !== 16) || off + len > t.byteLength) continue;
const raw = t.subarray(off, off + len);
let text = '';
if (pid === 3 || pid === 0) for (let k = 0; k + 1 < raw.length; k += 2) text += String.fromCharCode((raw[k]! << 8) | raw[k + 1]!);
else if (pid === 1) text = String.fromCharCode(...raw);
else continue;
recs.push({ pid, lang, id, text: text.trim() });
}
const score = (r: { pid: number; lang: number; id: number }): number => (r.id === 16 ? 10 : 0) + (r.pid === 3 ? 4 : r.pid === 0 ? 3 : 1) + (r.lang === 0x409 || r.lang === 0 ? 1 : 0);
return recs.filter(r => r.text).sort((a, b) => score(b) - score(a))[0]?.text ?? null;
}
/** Code points a font file covers. */
export const fontCodepoints = (file: Uint8Array): Set<number> => cmapCodepoints(cmapTable(file));

View file

@ -28,10 +28,14 @@ export function validateCapture(c: ShotsCapture | undefined): string[] {
if (!c.ios?.device && !c.ios?.devices?.phone) e.push('shots.capture.ios.device: simulator name or UDID, e.g. "iPhone 17 Pro Max"');
}
if (c.ios?.warmupMs !== undefined && !(Number.isInteger(c.ios.warmupMs) && c.ios.warmupMs >= 0)) e.push('shots.capture.ios.warmupMs: milliseconds (integer >= 0)');
if (c.concurrency !== undefined && !(Number.isInteger(c.concurrency) && c.concurrency >= 1 && c.concurrency <= 32)) e.push('shots.capture.concurrency: integer 1-32');
if (c.session !== undefined && !['per-shot', 'per-language'].includes(c.session)) e.push('shots.capture.session: per-shot | per-language');
if (c.reuseTimeoutMs !== undefined && !(Number.isInteger(c.reuseTimeoutMs) && c.reuseTimeoutMs > 0)) e.push('shots.capture.reuseTimeoutMs: milliseconds (integer > 0)');
if (src === 'android-emu' && !c.android?.package) e.push('shots.capture.android.package: application id (source android-emu)');
if (src !== 'folder' && (!c.shots || !Object.keys(c.shots).length)) e.push('shots.capture.shots: at least one shot');
for (const [name, s] of Object.entries(c.shots ?? {})) {
if (!/^[A-Za-z0-9._-]+$/.test(name)) e.push(`shots.capture.shots.${name}: name must be a file name (letters, digits, . _ -)`);
if (s.navigate && !['spa', 'reload'].includes(s.navigate)) e.push(`shots.capture.shots.${name}.navigate: spa | reload`);
if (s.device && !['phone', 'tablet', 'both'].includes(s.device)) e.push(`shots.capture.shots.${name}.device: phone | tablet | both`);
if (src === 'web' && s.path === undefined) e.push(`shots.capture.shots.${name}.path: URL path (source web)`);
if ((src === 'web' || src === 'folder') && (s.args || s.extras)) e.push(`shots.capture.shots.${name}: args / extras only apply to ios-sim / android-emu`);

View file

@ -8,14 +8,16 @@
// 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.
// The Google fonts are SIL Open Font License 1.1. A local font file in shots.fonts (local-fonts.ts) gets the same cmap
// check, is read in place (never copied) and recorded with its path, sha256 and license note.
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, printJson, warn } from '../lib/log';
import { shotsStyle } from '../lib/config';
import { type CopyFile, shotFonts } from './lib';
import type { CopyFile } from './lib';
import { localByFamily, resolveShotFonts } from './local-fonts';
import { fontCodepoints } from './cmap';
import { type FaceJob, type FontManifest, fontsCss, planFonts, roleTexts, type RoleTexts } from './glyphs';
@ -54,14 +56,24 @@ export async function run(ctx: Ctx): Promise<void> {
const dir = fontsDirOf(root);
mkdirSync(dir, { recursive: true });
const style = shotsStyle(config);
const { title, body, titleVariable } = shotFonts(shots, style);
const sf = resolveShotFonts(shots, style, resolve, root);
const { titleVariable } = sf;
const title = sf.title.family, body = sf.body.family;
const local = localByFamily([sf.title, sf.body, ...sf.fallback]);
const texts = langTexts(copy, config.languages.map(l => l.id), config.app.name);
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,
fallbackTitleAxis: style === 'app' ? 'wght@100..900' : 'wght@800', chosen: sf.fallback.map(f => f.family), base: ASCII, local,
}, async (job: FaceJob) => {
if (job.local) { // read in place: the whole file's cmap
const bin = new Uint8Array(readFileSync(join(root, job.local.path)));
const cps = fontCodepoints(bin);
const line = `${job.local.path} ${job.family}, ${(bin.byteLength / 1024).toFixed(1)} KB, ${cps.size} in the cmap, sha256 ${job.local.hash}, license: ${job.local.license ?? 'none noted (add license to the shots.fonts entry)'}`;
if (!sizes.includes(line)) sizes.push(line);
return cps;
}
let bin: Uint8Array;
try { bin = new Uint8Array(await fetchSubset(job.family, job.chars, job.axis)); } catch (e) {
if (job.kind !== 'fallback') throw e;
@ -77,12 +89,13 @@ export async function run(ctx: Ctx): Promise<void> {
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);
for (const f of Object.values(local)) if (!f.license) warn('shots', `local font ${f.path} has no license note: add license ('OFL-1.1', 'proprietary', ...) to its shots.fonts entry`);
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)'}`);
(ok ? log : warn)('shots', `${lang} ${f.role}: ${[...f.chars].join(' ')} not in ${base} -> ${f.family}${ok ? ' (shots.fonts.fallback)' : ' (automatic fallback)'}${manifest.faces[f.face]?.local ? ' (local file)' : ''}`);
}
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');

View file

@ -16,6 +16,7 @@
import type { SceneCopy } from './lib';
import { scriptFont } from './lib';
import { needsGlyph } from './cmap';
import { type LocalFontInfo, localFile, slug } from './local-fonts';
export type Role = 'title' | 'body';
export interface RoleTexts { title: string; body: string }
@ -61,16 +62,16 @@ export function fallbackFamilies(ch: string, lang: string, role: Role): string[]
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 FaceJob { face: string; family: string; file: string; kind: FaceKind; role?: Role; axis: string | null; chars: string; local?: LocalFontInfo }
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 }>;
/** local: a local font file (shots.fonts entry with a path), read in place, never copied; file = its served path. */
faces: Record<string, { family: string; file: string; kind: FaceKind; role?: Role; chosen: boolean; local?: LocalFontInfo }>;
langs: Record<string, LangFonts>;
}
@ -81,8 +82,11 @@ export interface PlanInput {
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. */
/** shots.fonts.fallback: families the owner accepts as fallbacks, in order. Families that are not one of the automatic
* Noto fallbacks (another Google family, a local file) are tried first, for every character the stack lacks. */
chosen?: string[];
/** Local font files by family (title, body or fallback). */
local?: Record<string, LocalFontInfo>;
/** Extra characters for the title / body downloads (ASCII, so later copy edits rarely need a new download). */
base?: string;
}
@ -100,6 +104,11 @@ export class GlyphError extends Error {
* 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 local = input.local ?? {};
const extra = [...new Set(input.chosen ?? [])].filter(f => !FALLBACK_ORDER.some(n => n.toLowerCase() === f.toLowerCase()));
const order = [...extra, ...FALLBACK_ORDER];
const fileOf = (family: string, google: string): string => local[family] ? localFile(family, local[family]!) : google;
const loc = (family: string): { local?: LocalFontInfo } => (local[family] ? { local: local[family] } : {});
const base = input.base ?? '';
const scripts = new Map<string, { family: string; chars: Set<string> }>();
const langScript = new Map<string, string | null>();
@ -121,13 +130,13 @@ export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise
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 };
faces[job.face] = { family: job.family, file: job.file, kind: job.kind, ...(job.role ? { role: job.role } : {}), chosen: isChosen, ...(job.local ? { local: job.local } : {}) };
};
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);
await add({ face: input.title, family: input.title, file: fileOf(input.title, 'title.woff2'), kind: 'title', role: 'title', axis: input.titleAxis, chars: sorted(roleChars.title), ...loc(input.title) }, true);
if (input.body !== input.title) await add({ face: input.body, family: input.body, file: fileOf(input.body, 'body.woff2'), kind: 'body', role: 'body', axis: input.bodyAxis, chars: sorted(roleChars.body), ...loc(input.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]) }));
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]), ...loc(input.title) }));
}
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);
@ -139,17 +148,17 @@ export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise
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) });
for (const ch of uncoveredChars(t[role], stack)) pending.push({ lang, role, ch, tries: [...extra, ...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) {
for (const role of ['title', 'body'] as const) for (const family of 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()));
await add({ face, family, file: fileOf(family, `fb-${slug(family)}-${role}.woff2`), kind: 'fallback', role, axis, chars: sorted(want.map(p => p.ch)), ...loc(family) }, chosen.has(family.toLowerCase()));
const got = cps.get(face)!;
for (const p of want) {
p.tries = p.tries.filter(f => f !== family);
@ -165,14 +174,14 @@ export async function planFonts(input: PlanInput, get: (job: FaceJob) => Promise
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)] };
const g = gaps.get(k) ?? { lang: p.lang, role: p.role, chars: [], tried: [...langs[p.lang]![p.role].map(f => faces[f]?.family ?? f), ...extra, ...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))) {
for (const face of [...m.keys()].sort((a, b) => order.indexOf(faces[a]!.family) - 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('') });
}
@ -187,6 +196,12 @@ export function fontsCss(m: FontManifest): string {
for (const [face, f] of Object.entries(m.faces)) {
if (seen.has(face)) continue;
seen.add(face);
if (f.local) { // the project's own font file, served in place; ?v= changes with its content
const l = f.local;
css += `/* ${f.family}: local file ${l.path} (${l.license ? 'license: ' + l.license.replace(/\*\//g, '') : 'no license note'}) */\n`;
css += `@font-face { font-family: '${face}'; font-weight: ${l.weight ?? '100 900'}; font-style: ${l.style ?? 'normal'}; font-synthesis: none; src: url(${f.file}?v=${l.hash}) format('${l.format}'); }\n`;
continue;
}
css += `@font-face { font-family: '${face}'; font-weight: 100 900; font-synthesis: none; src: url(${f.file}) format('woff2'); }\n`;
}
return css;

View file

@ -1,4 +1,5 @@
// Pure parts of the screenshot pipeline: store sizes, palettes, per-language script fonts, copy validation, job data.
import { specFamily } from './local-fonts';
import type { Palette, ShipConfig, ShotScene, ShotsConfig } from '../lib/config';
/** Store image sizes. ios69 = 6.9" (APP_IPHONE_67), ios65 = 6.5" (APP_IPHONE_65), iphone-medium = 6.3" iPhone with
@ -54,7 +55,8 @@ export const palette = (p: string | Palette | undefined, style: 'game' | 'app' =
* 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: 'Paytone One', body: 'Montserrat' };
return { title: shots?.fonts?.title ?? d.title, body: shots?.fonts?.body ?? d.body, titleVariable: style === 'app' };
// local files: the family given in the config, else the file name (resolveShotFonts reads the real name table)
return { title: specFamily(shots?.fonts?.title ?? d.title), body: specFamily(shots?.fonts?.body ?? d.body), titleVariable: style === 'app' };
}
export interface SceneCopy { eyebrow?: string; title: [string, string]; sub?: string; badges?: [string, string?][] }

130
cli/shots/local-fonts.ts Normal file
View file

@ -0,0 +1,130 @@
// A game's or app's own brand font as a local file, next to the Google Fonts families:
// shots.fonts.title / body / fallback[] = 'Paytone One' (Google Fonts family)
// | 'assets/fonts/er-display.woff2' (local file, family from its name table)
// | { family, file, weight?, style?, license? }
// Paths are relative to the config. TTF / OTF / WOFF / WOFF2 (checked by extension and signature). The file is never
// copied: `shots fonts` reads its cmap and records it in fonts.json (path relative to the project, sha256, license),
// fonts.css points at /fonts/local/<slug>.<ext>?v=<hash> and the render / video servers serve that route from the
// original file. A changed file changes fonts.css (capture cache) and fails render until `shots fonts` runs again.
import { createHash } from 'node:crypto';
import { existsSync, readFileSync, statSync } from 'node:fs';
import { basename, join, relative } from 'node:path';
import { fontFamilyName } from './cmap';
import type { FontManifest } from './glyphs';
import type { FontSpec, LocalFontSpec, ShotsConfig } from '../lib/config';
export type { FontSpec, LocalFontSpec };
export type FontFormat = 'truetype' | 'opentype' | 'woff' | 'woff2';
/** A local font as fonts.json records it. path: relative to the project root. */
export interface LocalFontInfo { path: string; format: FontFormat; hash: string; bytes: number; weight?: string; style?: string; license?: string }
/** A resolved font of shots.fonts: the family name the templates use, plus the file for a local font. */
export interface FontRef { family: string; local?: LocalFontInfo & { abs: string } }
const EXT: Record<string, FontFormat> = { ttf: 'truetype', otf: 'opentype', woff: 'woff', woff2: 'woff2' };
/** A string spec is a local file when it ends in a font extension or contains a path separator. */
export const isLocalSpec = (s: FontSpec): boolean => typeof s !== 'string' || /\.(ttf|otf|woff2?)$/i.test(s) || /[\\/]/.test(s);
/** Format from the file signature (null = not a font file storebound reads). */
export function sniffFormat(bin: Uint8Array): FontFormat | null {
if (bin.byteLength < 12) return null;
const sig = String.fromCharCode(bin[0]!, bin[1]!, bin[2]!, bin[3]!);
if (sig === 'wOF2') return 'woff2';
if (sig === 'wOFF') return 'woff';
if (sig === 'OTTO') return 'opentype';
if (sig === 'true' || (bin[0] === 0 && bin[1] === 1 && bin[2] === 0 && bin[3] === 0)) return 'truetype';
return null;
}
export const fileHash = (bin: Uint8Array): string => createHash('sha256').update(bin).digest('hex').slice(0, 16);
/** Resolves and validates one local font spec (file exists, TTF / OTF / WOFF / WOFF2). Throws with the config key. */
export function loadLocalFont(spec: FontSpec, key: string, resolve: (p: string) => string, root: string): FontRef {
const o: LocalFontSpec = typeof spec === 'string' ? { file: spec } : spec;
if (!o.file || typeof o.file !== 'string') throw new Error(`${key}: { family, file } needs a file path (relative to the config)`);
const ext = o.file.split('.').pop()!.toLowerCase();
if (!EXT[ext]) throw new Error(`${key}: ${o.file}: not a font file (TTF, OTF, WOFF or WOFF2)`);
const abs = resolve(o.file);
if (!existsSync(abs) || !statSync(abs).isFile()) throw new Error(`${key}: ${o.file} not found (paths are relative to the config: ${abs})`);
const bin = new Uint8Array(readFileSync(abs));
const format = sniffFormat(bin);
if (!format) throw new Error(`${key}: ${o.file} is not a TTF / OTF / WOFF / WOFF2 font (unknown signature)`);
const sfnt = (f: FontFormat): boolean => f === 'truetype' || f === 'opentype';
if (format !== EXT[ext] && !(sfnt(format) && sfnt(EXT[ext]!))) throw new Error(`${key}: ${o.file} is ${format.toUpperCase()} inside, but named .${ext}: rename it`);
const family = (o.family ?? fontFamilyName(bin) ?? basename(o.file).replace(/\.[^.]+$/, '')).trim();
if (!family) throw new Error(`${key}: ${o.file}: no family name (give { family, file })`);
return { family, local: { abs, path: relative(root, abs), format, hash: fileHash(bin), bytes: bin.byteLength,
...(o.weight !== undefined ? { weight: String(o.weight) } : {}), ...(o.style ? { style: o.style } : {}), ...(o.license ? { license: o.license } : {}) } };
}
/** shots.fonts resolved: Google families as names, local files loaded and validated (throws on a bad file). */
export function resolveShotFonts(shots: Pick<ShotsConfig, 'fonts'> | undefined, style: 'game' | 'app', resolve: (p: string) => string, root: string): { title: FontRef; body: FontRef; fallback: FontRef[]; titleVariable: boolean } {
const d = style === 'app' ? { title: 'Inter', body: 'Inter' } : { title: 'Paytone One', body: 'Montserrat' };
const ref = (s: FontSpec, key: string): FontRef => isLocalSpec(s) ? loadLocalFont(s, key, resolve, root) : { family: s as string };
const fallback = (shots?.fonts?.fallback ?? []).map((f, i) => ref(f, `shots.fonts.fallback[${i}]`));
return { title: ref(shots?.fonts?.title ?? d.title, 'shots.fonts.title'), body: ref(shots?.fonts?.body ?? d.body, 'shots.fonts.body'), fallback, titleVariable: style === 'app' };
}
/** Local files by family for planFonts (one family, one file). */
export function localByFamily(refs: FontRef[]): Record<string, LocalFontInfo> {
const out: Record<string, LocalFontInfo> = {};
for (const r of refs) if (r.local) {
const { abs: _abs, ...info } = r.local;
if (out[r.family] && out[r.family]!.hash !== info.hash) throw new Error(`shots.fonts: two different files for the family "${r.family}" (give each a distinct family)`);
out[r.family] = info;
}
return out;
}
/** Family name of a spec without reading files (Google family, { family }, else the file name). For callers that only
* need a name and never a local file's name table. */
export const specFamily = (s: FontSpec): string => typeof s !== 'string' ? s.family ?? basename(s.file).replace(/\.[^.]+$/, '')
: isLocalSpec(s) ? basename(s).replace(/\.[^.]+$/, '') : s;
export const slug = (s: string): string => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
/** fonts.json file name of a local face: served at /fonts/local/<slug>.<ext>. */
export const localFile = (family: string, l: Pick<LocalFontInfo, 'format'>): string =>
`local/${slug(family)}.${l.format === 'truetype' ? 'ttf' : l.format === 'opentype' ? 'otf' : l.format}`;
/** Absolute file of a face: the downloaded subset in .storebound/fonts, or the local font file itself. */
export function faceFilePath(fontsDir: string, root: string, f: FontManifest['faces'][string]): string {
return f.local ? join(root, f.local.path) : join(fontsDir, f.file);
}
/** File for a /fonts/<rel> request of the render / video page (null = not ours). */
export function fontsRoute(rel: string, fontsDir: string, root: string, m: FontManifest | null): string | null {
rel = rel.split('?')[0]!;
if (rel.includes('..')) return null;
if (rel.startsWith('local/')) {
const f = Object.values(m?.faces ?? {}).find(x => x.local && x.file === rel);
return f ? faceFilePath(fontsDir, root, f) : null;
}
return join(fontsDir, rel);
}
export const FONT_TYPES: Record<string, string> = { woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', css: 'text/css' };
/** Local faces whose file changed (or vanished) since `shots fonts`. */
export function staleLocalFonts(m: FontManifest, root: string): string[] {
const out: string[] = [];
for (const f of new Map(Object.values(m.faces).filter(x => x.local).map(x => [x.local!.path, x] as const)).values()) {
const abs = join(root, f.local!.path);
if (!existsSync(abs)) out.push(`${f.family}: ${f.local!.path} is gone`);
else if (fileHash(new Uint8Array(readFileSync(abs))) !== f.local!.hash) out.push(`${f.family}: ${f.local!.path} changed`);
}
return out;
}
/** `shots check` warnings for local fonts without a license note. */
export function localFontIssues(m: FontManifest | null): { level: 'warn'; code: 'font-license'; msg: string }[] {
const seen = new Set<string>();
const out: { level: 'warn'; code: 'font-license'; msg: string }[] = [];
for (const f of Object.values(m?.faces ?? {})) {
if (!f.local || f.local.license || seen.has(f.local.path)) continue;
seen.add(f.local.path);
out.push({ level: 'warn', code: 'font-license', msg: `local font ${f.family} (${f.local.path}) has no license note: add license ('OFL-1.1', 'proprietary', or a short note) to its shots.fonts entry, and make sure you may embed it in store graphics` });
}
return out;
}

View file

@ -1,6 +1,6 @@
// Store screenshots + Play feature graphic at exact pixel sizes, from raw app or game frames and per-language copy.
// storebound shots render [--lang en,tr] [--size ios69,play,feature] [--scenes 1,3] [--variant b | --variants]
// [--no-sheet] [--port 8792] [--dry]
// [--no-sheet] [--port 8792] [--concurrency N] [--dry]
// Out: <shots.out>/<lang>/<size>/NN.png (24-bit RGB: Play rejects alpha / palette PNGs), <lang>/feature/1024x500.png,
// <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>/...
@ -8,7 +8,8 @@
// 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`.
// image (`fonts`: faces used, automatic fallbacks, system-font glyphs) for `shots check`. Local font files (shots.fonts
// paths) are served from where they are at /fonts/local/... (local-fonts.ts); a file changed since `shots fonts` fails.
// 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';
@ -16,17 +17,18 @@ 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';
import { need } from '../lib/ctx';
import { done, log, warn } from '../lib/log';
import { launch } from './browser';
import { defaultConcurrency, pool, progressLine } from './capture-web';
import { shotsStyle } from '../lib/config';
import { type CopyFile, SIZES, copyText, defaultSizes, frameDims, mergeCopy, palette, renderDir, scriptFont, sheetLayout, shotFonts, validateCopy, variantScenes } from './lib';
import { type CopyFile, SIZES, copyText, defaultSizes, frameDims, mergeCopy, palette, renderDir, scriptFont, sheetLayout, validateCopy, variantScenes } from './lib';
import { faceFilePath, fontsRoute, resolveShotFonts, staleLocalFonts } from './local-fonts';
import { type RenderReport, mergeReport, readReport } from './report';
const TYPES: Record<string, string> = { html: 'text/html; charset=utf-8', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',
webp: 'image/webp', woff2: 'font/woff2', css: 'text/css', svg: 'image/svg+xml' };
webp: 'image/webp', woff2: 'font/woff2', woff: 'font/woff', ttf: 'font/ttf', otf: 'font/otf', css: 'text/css', svg: 'image/svg+xml' };
export async function run(ctx: Ctx): Promise<void> {
const { config, root, resolve } = ctx.loaded;
@ -62,7 +64,8 @@ export async function run(ctx: Ctx): Promise<void> {
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 rf = resolveShotFonts(shots, style, resolve, root);
const sf = { title: rf.title.family, body: rf.body.family };
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');
@ -79,10 +82,14 @@ export async function run(ctx: Ctx): Promise<void> {
const x = stacks(lang, job.copy).script;
if (x) faces[x] = { family: x, file: '', kind: 'script', chosen: true };
}
if (manifest) {
const stale = staleLocalFonts(manifest, root);
if (stale.length) throw new Error(`shots render: local font files changed since \`shots fonts\`: run \`storebound shots fonts\`\n ${stale.join('\n ')}`);
}
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()); }
if (!cmaps.has(face)) { const f = manifest.faces[face]; const file = f && faceFilePath(fontsDir, root, f); cmaps.set(face, file && existsSync(file) ? fontCodepoints(readFileSync(file)) : new Set()); }
return cmaps.get(face)!;
};
const gaps: string[] = [];
@ -121,7 +128,7 @@ export async function run(ctx: Ctx): Promise<void> {
let file = '';
if (p === '/logo' && shots.logo) file = resolve(shots.logo);
else if (p.startsWith('/frames/')) file = join(framesDir, p.slice(8));
else if (p.startsWith('/fonts/')) file = join(fontsDir, p.slice(7));
else if (p.startsWith('/fonts/')) file = fontsRoute(p.slice(7), fontsDir, root, manifest) ?? '';
else if (p.startsWith('/out/')) file = join(outDir, p.slice(5));
else if (/^\/(template|feature)(-app)?\.html$/.test(p)) file = join(tpl, p.slice(1));
if (!file || file.includes('..')) return new Response('no', { status: 404 });
@ -132,14 +139,24 @@ export async function run(ctx: Ctx): Promise<void> {
});
const base = `http://127.0.0.1:${server.port}`;
const browser = await launch(root, { headless: true });
const page = await (await browser.newContext({ deviceScaleFactor: 1 })).newPage();
const errs: string[] = [];
page.on('pageerror', (e: Error) => errs.push(e.message));
page.on('response', (r: { status(): number; url(): string }) => { if (r.status() >= 400 && !r.url().includes('/fonts/')) errs.push(`${r.status()} ${r.url()}`); });
let warnings = 0;
const concurrency = a.num('concurrency', defaultConcurrency('render'));
// one page per worker, each with its own error list
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const pages: { page: any; errs: string[] }[] = [];
const pageFor = async (k: number): Promise<{ page: any; errs: string[] }> => { // eslint-disable-line @typescript-eslint/no-explicit-any
if (pages[k]) return pages[k]!;
const page = await (await browser.newContext({ deviceScaleFactor: 1 })).newPage(); // own context: no background-tab throttling
const errs: string[] = [];
page.on('pageerror', (e: Error) => errs.push(e.message));
page.on('response', (r: { status(): number; url(): string }) => { if (r.status() >= 400 && !r.url().includes('/fonts/')) errs.push(`${r.status()} ${r.url()}`); });
return (pages[k] = { page, errs });
};
let warnings = 0, finished = 0, total = 0;
const started = Date.now();
const report: RenderReport = {};
async function shoot(url: string, w: number, h: number, out: string): Promise<void> {
async function shoot(p: { page: any; errs: string[] }, url: string, w: number, h: number, out: string): Promise<void> { // eslint-disable-line @typescript-eslint/no-explicit-any
const { page, errs } = p;
errs.length = 0;
mkdirSync(join(out, '..'), { recursive: true });
await page.setViewportSize({ width: w, height: h });
@ -157,47 +174,63 @@ export async function run(ctx: Ctx): Promise<void> {
}
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]);
const ff = Bun.spawn(['ffmpeg', '-v', 'error', '-y', '-i', tmp, '-pix_fmt', 'rgb24', out], { stderr: 'pipe' });
const code = await ff.exited;
rmSync(tmp, { force: true });
if (r.status !== 0) throw new Error('ffmpeg: ' + r.stderr);
if (code !== 0) throw new Error('ffmpeg: ' + await new Response(ff.stderr).text());
if (errs.length) warnings++;
log('shots', `${errs.length ? 'WARN ' : ''}${relative(root, out)}${errs.length ? ' ' + errs.join(' | ') : ''}`);
finished++;
log('shots', `${progressLine(finished, total, started)} ${errs.length ? 'WARN ' : ''}${relative(root, out)}${errs.length ? ' ' + errs.join(' | ') : ''}`);
}
try {
for (const [v, job] of jobs) for (const lang of langs) {
const sceneIds = a.list('scenes').length ? a.list('scenes') : job.scenes.map(s => s.id);
const vq = v ? `&v=${encodeURIComponent(v)}` : '';
const dir = renderDir(outDir, lang, v || undefined);
const rows: { size: string; files: string[] }[] = [];
for (const size of sizes) {
const s = SIZES[size]!;
if (s.feature) {
const f = join(dir, 'feature', '1024x500.png');
await shoot(`${base}/${style === 'app' ? 'feature-app' : 'feature'}.html?lang=${encodeURIComponent(lang)}${vq}`, s.w, s.h, f);
rows.push({ size, files: [f] });
continue;
}
const files: string[] = [];
for (const [i, id] of sceneIds.entries()) {
const f = join(dir, size, `${String(i + 1).padStart(2, '0')}.png`);
await shoot(`${base}/${style === 'app' ? 'template-app' : 'template'}.html?s=${encodeURIComponent(id)}&w=${s.w}&h=${s.h}&lang=${encodeURIComponent(lang)}${s.device ? '&device=tablet' : ''}${size === 'tab7' || size === 'tab10' ? '&style=android' : ''}${vq}`, s.w, s.h, f);
files.push(f);
}
rows.push({ size, files });
// every image first (in parallel), then one contact sheet per language from its finished images
const items: { url: string; w: number; h: number; out: string }[] = [];
const sheets: { dir: string; rows: { size: string; files: string[] }[] }[] = [];
for (const [v, job] of jobs) for (const lang of langs) {
const sceneIds = a.list('scenes').length ? a.list('scenes') : job.scenes.map(s => s.id);
const vq = v ? `&v=${encodeURIComponent(v)}` : '';
const dir = renderDir(outDir, lang, v || undefined);
const rows: { size: string; files: string[] }[] = [];
for (const size of sizes) {
const s = SIZES[size]!;
if (s.feature) {
const f = join(dir, 'feature', '1024x500.png');
items.push({ url: `${base}/${style === 'app' ? 'feature-app' : 'feature'}.html?lang=${encodeURIComponent(lang)}${vq}`, w: s.w, h: s.h, out: f });
rows.push({ size, files: [f] });
continue;
}
if (!a.has('no-sheet') && rows.length) {
const lay = sheetLayout(rows);
const imgs = lay.tiles.map(t => `<img src="/out/${relative(outDir, t.file)}" style="position:absolute;left:${t.x}px;top:${t.y}px;width:${t.w}px;height:${t.h}px;border-radius:14px">`).join('');
const W = lay.w, y = lay.h;
const sheet = join(dir, '.sheet.html');
await Bun.write(sheet, `<!doctype html><body style="margin:0;background:#141418;width:${W}px;height:${y}px;position:relative">${imgs}
<script>Promise.all([...document.images].map(i=>i.decode())).then(()=>document.body.dataset.ready='1')</script></body>`);
await shoot(`${base}/out/${relative(outDir, sheet)}`, W, y, join(dir, 'sheet.png'));
rmSync(sheet, { force: true });
const files: string[] = [];
for (const [i, id] of sceneIds.entries()) {
const f = join(dir, size, `${String(i + 1).padStart(2, '0')}.png`);
items.push({ url: `${base}/${style === 'app' ? 'template-app' : 'template'}.html?s=${encodeURIComponent(id)}&w=${s.w}&h=${s.h}&lang=${encodeURIComponent(lang)}${s.device ? '&device=tablet' : ''}${size === 'tab7' || size === 'tab10' ? '&style=android' : ''}${vq}`, w: s.w, h: s.h, out: f });
files.push(f);
}
rows.push({ size, files });
}
if (!a.has('no-sheet') && rows.length) sheets.push({ dir, rows });
}
total = items.length + sheets.length;
log('shots', `rendering ${items.length} images${sheets.length ? ` + ${sheets.length} contact sheets` : ''}, ${Math.min(concurrency, items.length)} at a time (--concurrency)`);
try {
const slot = new Map<number, number>();
let nextSlot = 0;
const withPage = async (fn: (p: { page: any; errs: string[] }) => Promise<void>): Promise<void> => { // eslint-disable-line @typescript-eslint/no-explicit-any
const free = [...Array(concurrency).keys()].find(k => !slot.has(k)) ?? nextSlot++ % concurrency;
slot.set(free, 1);
try { await fn(await pageFor(free)); } finally { slot.delete(free); }
};
await pool(items, concurrency, it => withPage(p => shoot(p, it.url, it.w, it.h, it.out)));
await pool(sheets, concurrency, async ({ dir, rows }) => {
const lay = sheetLayout(rows);
const imgs = lay.tiles.map(t => `<img src="/out/${relative(outDir, t.file)}" style="position:absolute;left:${t.x}px;top:${t.y}px;width:${t.w}px;height:${t.h}px;border-radius:14px">`).join('');
const sheet = join(dir, '.sheet.html');
await Bun.write(sheet, `<!doctype html><body style="margin:0;background:#141418;width:${lay.w}px;height:${lay.h}px;position:relative">${imgs}
<script>Promise.all([...document.images].map(i=>i.decode())).then(()=>document.body.dataset.ready='1')</script></body>`);
await withPage(p => shoot(p, `${base}/out/${relative(outDir, sheet)}`, lay.w, lay.h, join(dir, 'sheet.png')));
rmSync(sheet, { force: true });
});
} finally {
for (const p of pages) await p?.page.context().close().catch(() => {});
await browser.close();
server.stop(true);
if (Object.keys(report).length) await Bun.write(join(outDir, 'report.json'), JSON.stringify(mergeReport(readReport(outDir), report), null, 1) + '\n');

View file

@ -17,7 +17,8 @@ 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 { captionsFor, type CopyFile, copyText, palette, renderDir, scriptFont } from './lib';
import { FONT_TYPES, fontsRoute, resolveShotFonts } from './local-fonts';
import { ffprobe } from './report';
import { checkVideo, PREVIEW_RULES, VIDEO_TARGETS } from './spec';
@ -159,12 +160,13 @@ 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, titleStack: readManifest(fontsDir)?.langs[lang]?.title } });
fonts: { title: resolveShotFonts(shots, style, ctx.loaded.resolve, root).title.family, 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('..')) {
const f = Bun.file(join(fontsDir, url.pathname.slice(7)));
if (await f.exists()) return new Response(f, { headers: { 'content-type': url.pathname.endsWith('.css') ? 'text/css' : 'font/woff2' } });
if (url.pathname.startsWith('/fonts/')) {
const file = fontsRoute(decodeURIComponent(url.pathname.slice(7)), fontsDir, root, readManifest(fontsDir));
const f = file ? Bun.file(file) : null;
if (f && await f.exists()) return new Response(f, { headers: { 'content-type': FONT_TYPES[file!.split('.').pop()!.toLowerCase()] ?? 'font/woff2' } });
}
return new Response('no', { status: 404 });
} });