Merge remote-tracking branch 'origin/main' into play-app-record

# Conflicts:
#	CHANGELOG.md
#	docs/pitfalls.md
#	skills/store-pitfalls/SKILL.md
This commit is contained in:
CRTkafa 2026-10-11 20:13:35 +00:00
commit 457aa98800
53 changed files with 2551 additions and 305 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',
@ -75,6 +74,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 +98,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 +134,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 +144,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 +157,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 +178,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 +214,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 +225,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

@ -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

@ -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

@ -147,6 +147,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. */
@ -195,6 +199,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>;
}

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

@ -200,13 +200,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

@ -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

@ -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

@ -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

@ -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>/...
@ -16,11 +16,11 @@ 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 RenderReport, mergeReport, readReport } from './report';
@ -132,14 +132,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 +167,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');