@sprid/release 1.2.2 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/README.md +86 -0
- package/package.json +1 -1
- package/src/annotate.ts +4 -1
- package/src/asc/client.ts +16 -4
- package/src/asc/creative.ts +248 -0
- package/src/asc/index.ts +8 -0
- package/src/asc/page-results.ts +218 -0
- package/src/asc/product-pages.ts +513 -0
- package/src/asc/submissions.ts +64 -0
- package/src/cli.ts +75 -5
- package/src/config.ts +75 -0
- package/src/copy.ts +11 -0
- package/src/play/metadata.ts +2 -1
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How each App Store page performs, from Apple's Analytics Reports.
|
|
3
|
+
*
|
|
4
|
+
* Custom product pages are only split out in the *Detailed* reports, where a row
|
|
5
|
+
* names its page in `Page Title` (the page's name in App Store Connect, never its
|
|
6
|
+
* ppid). Views come from "App Store Discovery and Engagement Detailed", downloads
|
|
7
|
+
* from "App Downloads Detailed", joined by page name.
|
|
8
|
+
*
|
|
9
|
+
* Product page optimization results are not in Apple's API at all, so for a test
|
|
10
|
+
* this reads its state and dates and says where Apple shows the result.
|
|
11
|
+
*
|
|
12
|
+
* Daily report instances overlap: each re-delivers the last two or three dates,
|
|
13
|
+
* and the latest processing date replaces a date's whole batch. Each date is
|
|
14
|
+
* taken from exactly one instance, or every day would count two or three times.
|
|
15
|
+
* https://developer.apple.com/documentation/analytics-reports/data-completeness-corrections
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { gunzipSync } from 'node:zlib';
|
|
19
|
+
import type { AppReleaseConfig } from '../config.ts';
|
|
20
|
+
import { createAscClient, type AscClient } from './client.ts';
|
|
21
|
+
import { findTest, listAll, testStatus, type TestStatus } from './product-pages.ts';
|
|
22
|
+
|
|
23
|
+
export interface PageRow {
|
|
24
|
+
title: string;
|
|
25
|
+
type: string;
|
|
26
|
+
impressions: number;
|
|
27
|
+
pageViews: number;
|
|
28
|
+
firstTimeDownloads: number;
|
|
29
|
+
redownloads: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface PageResults {
|
|
33
|
+
status: 'ok' | 'unconfigured' | 'pending';
|
|
34
|
+
note?: string;
|
|
35
|
+
window: { start: string; end: string; days: number };
|
|
36
|
+
/** Distinct dates with data in each report; Apple lags two to three days. */
|
|
37
|
+
coverage: { views: number; downloads: number };
|
|
38
|
+
rows: PageRow[];
|
|
39
|
+
/** The app's custom product pages, so a row can be matched to its URL. */
|
|
40
|
+
pages: { id: string; name: string; url?: string }[];
|
|
41
|
+
test?: TestStatus;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
type Row = Record<string, string>;
|
|
45
|
+
|
|
46
|
+
export function parseTsv(text: string): Row[] {
|
|
47
|
+
const lines = text.split('\n').filter(l => l.length);
|
|
48
|
+
if (!lines.length) return [];
|
|
49
|
+
const header = lines[0].split('\t').map(h => h.trim());
|
|
50
|
+
return lines.slice(1).map(line => {
|
|
51
|
+
const cells = line.split('\t');
|
|
52
|
+
return Object.fromEntries(header.map((h, i) => [h, (cells[i] ?? '').trim()]));
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The first column matching any pattern, most specific first ("Event" before "Engagement Type"). */
|
|
57
|
+
function col(row: Row, ...patterns: RegExp[]): string | undefined {
|
|
58
|
+
const keys = Object.keys(row);
|
|
59
|
+
for (const re of patterns) { const k = keys.find(x => re.test(x)); if (k) return k; }
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
const count = (row: Row) => Number((row[col(row, /^Counts?$/i) ?? ''] ?? '0').replace(/,/g, '')) || 0;
|
|
63
|
+
const pageOf = (row: Row) => ({
|
|
64
|
+
title: row[col(row, /^Page Title$/i) ?? ''] || '(none)',
|
|
65
|
+
type: row[col(row, /^Page Type$/i) ?? ''] || '(none)',
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
/** Rows of one report dated in [start, end), each date from the latest instance that carries it. */
|
|
69
|
+
export async function readReport(client: AscClient, reportId: string, start: string, end: string,
|
|
70
|
+
download: (url: string) => Promise<Buffer> = defaultDownload): Promise<{ rows: Row[]; dates: string[] }> {
|
|
71
|
+
const instances = await listAll(client, `/analyticsReports/${reportId}/instances?filter[granularity]=DAILY&limit=200`);
|
|
72
|
+
// processingDate is delivery time: a batch delivered after `end` can still hold dates inside the window.
|
|
73
|
+
const relevant = instances.filter((i: any) => (i.attributes?.processingDate ?? '') >= start);
|
|
74
|
+
const byDate = new Map<string, { revision: string; id: string; rows: Row[] }>();
|
|
75
|
+
for (const inst of relevant) {
|
|
76
|
+
const own = new Map<string, Row[]>();
|
|
77
|
+
for (const seg of await listAll(client, `/analyticsReportInstances/${inst.id}/segments`)) {
|
|
78
|
+
if (!seg.attributes?.url) continue;
|
|
79
|
+
for (const row of parseTsv(gunzipSync(await download(seg.attributes.url), { maxOutputLength: 64 * 1024 * 1024 }).toString('utf8'))) {
|
|
80
|
+
const date = row[col(row, /^Date$/i) ?? ''];
|
|
81
|
+
if (!date || date < start || date >= end) continue;
|
|
82
|
+
if (!own.has(date)) own.set(date, []);
|
|
83
|
+
own.get(date)!.push(row);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const revision = String(inst.attributes?.processingDate ?? '');
|
|
87
|
+
for (const [date, rows] of own) {
|
|
88
|
+
const held = byDate.get(date);
|
|
89
|
+
if (held && (revision < held.revision || (revision === held.revision && String(inst.id) < held.id))) continue;
|
|
90
|
+
byDate.set(date, { revision, id: String(inst.id), rows });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
const dates = [...byDate.keys()].sort();
|
|
94
|
+
return { rows: dates.flatMap(d => byDate.get(d)!.rows), dates };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function defaultDownload(url: string): Promise<Buffer> {
|
|
98
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(60_000) });
|
|
99
|
+
if (!res.ok) throw new Error(`Report segment download: HTTP ${res.status}`);
|
|
100
|
+
return Buffer.from(await res.arrayBuffer());
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Fold Discovery and Downloads rows into one row per page. */
|
|
104
|
+
export function foldPages(views: Row[], downloads: Row[]): PageRow[] {
|
|
105
|
+
const pages = new Map<string, PageRow>();
|
|
106
|
+
const get = (row: Row) => {
|
|
107
|
+
const { title, type } = pageOf(row);
|
|
108
|
+
const key = `${type}\u0000${title}`;
|
|
109
|
+
if (!pages.has(key)) pages.set(key, { title, type, impressions: 0, pageViews: 0, firstTimeDownloads: 0, redownloads: 0 });
|
|
110
|
+
return pages.get(key)!;
|
|
111
|
+
};
|
|
112
|
+
for (const row of views) {
|
|
113
|
+
const event = (row[col(row, /^Event$/i) ?? ''] ?? '').toLowerCase();
|
|
114
|
+
if (/impression/.test(event)) get(row).impressions += count(row);
|
|
115
|
+
else if (/page view/.test(event)) get(row).pageViews += count(row);
|
|
116
|
+
}
|
|
117
|
+
for (const row of downloads) {
|
|
118
|
+
const type = (row[col(row, /Download Type/i) ?? ''] ?? '').toLowerCase();
|
|
119
|
+
if (/first.time/.test(type)) get(row).firstTimeDownloads += count(row);
|
|
120
|
+
else if (/re.?download/.test(type)) get(row).redownloads += count(row);
|
|
121
|
+
}
|
|
122
|
+
return [...pages.values()].filter(p => p.pageViews || p.firstTimeDownloads || p.impressions)
|
|
123
|
+
.sort((a, b) => b.pageViews - a.pageViews || b.firstTimeDownloads - a.firstTimeDownloads);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** First-time downloads per page view, the number a page changes. Null below 1 view. */
|
|
127
|
+
export const downloadsPerView = (p: PageRow): number | null => (p.pageViews ? p.firstTimeDownloads / p.pageViews : null);
|
|
128
|
+
const pct = (v: number | null) => (v === null ? '-' : `${(v * 100).toFixed(1)}%`);
|
|
129
|
+
export const isDefaultPage = (p: PageRow) => /default/i.test(p.title);
|
|
130
|
+
|
|
131
|
+
/** One line for a Sprid annotation: each custom page against the default page. At most 200 characters. */
|
|
132
|
+
export function resultsLabel(results: PageResults): string {
|
|
133
|
+
const names = new Set(results.pages.map(p => p.name));
|
|
134
|
+
const custom = results.rows.filter(r => names.has(r.title));
|
|
135
|
+
const base = results.rows.find(isDefaultPage);
|
|
136
|
+
const parts = custom.map(r => `"${r.title}" ${pct(downloadsPerView(r))} of ${r.pageViews} views`);
|
|
137
|
+
if (base) parts.push(`default ${pct(downloadsPerView(base))}`);
|
|
138
|
+
const label = `Product pages, ${results.window.days} days: ${parts.join('; ') || 'no custom page traffic yet'}`;
|
|
139
|
+
return label.length > 200 ? `${label.slice(0, 199)}…` : label;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export interface PageResultsOptions {
|
|
143
|
+
config: AppReleaseConfig;
|
|
144
|
+
/** Days back from today. Default 28. */
|
|
145
|
+
days?: number;
|
|
146
|
+
/** Create the ONGOING report request when there is none (needs the Admin role). Only with execute. */
|
|
147
|
+
requestReports?: boolean;
|
|
148
|
+
execute?: boolean;
|
|
149
|
+
/** Injected for tests. */
|
|
150
|
+
download?: (url: string) => Promise<Buffer>;
|
|
151
|
+
today?: Date;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export async function readPageResults({ config, days = 28, requestReports = false, execute = false, download, today = new Date() }: PageResultsOptions): Promise<PageResults> {
|
|
155
|
+
if (!Number.isInteger(days) || days < 1 || days > 365) throw new Error('--days takes a whole number from 1 to 365.');
|
|
156
|
+
const end = today.toISOString().slice(0, 10);
|
|
157
|
+
const start = new Date(Date.parse(end) - days * 86_400_000).toISOString().slice(0, 10);
|
|
158
|
+
const client = createAscClient(config);
|
|
159
|
+
const app = await client.findApp();
|
|
160
|
+
const pages = (await listAll(client, `/apps/${app.id}/appCustomProductPages?limit=200`))
|
|
161
|
+
.map((p: any) => ({ id: p.id, name: p.attributes?.name, url: p.attributes?.url }));
|
|
162
|
+
let test: TestStatus | undefined;
|
|
163
|
+
const testName = config.ascProductPageTest?.name;
|
|
164
|
+
if (testName) {
|
|
165
|
+
const found = await findTest(client, app.id, testName);
|
|
166
|
+
if (found) test = await testStatus(client, found);
|
|
167
|
+
}
|
|
168
|
+
const base: PageResults = { status: 'ok', window: { start, end, days }, coverage: { views: 0, downloads: 0 }, rows: [], pages, test };
|
|
169
|
+
|
|
170
|
+
const requests = await listAll(client, `/apps/${app.id}/analyticsReportRequests`);
|
|
171
|
+
let request = requests.find((r: any) => r.attributes?.accessType === 'ONGOING' && !r.attributes?.stoppedDueToInactivity);
|
|
172
|
+
if (!request) {
|
|
173
|
+
if (!(requestReports && execute)) {
|
|
174
|
+
return { ...base, status: 'unconfigured', note: 'Apple generates no analytics reports for this app yet. Run once with --request-reports --execute (the key needs the Admin role); the first data arrives one to two days later.' };
|
|
175
|
+
}
|
|
176
|
+
const created = await client.api('/analyticsReportRequests', { method: 'POST', body: JSON.stringify({ data: {
|
|
177
|
+
type: 'analyticsReportRequests', attributes: { accessType: 'ONGOING' }, relationships: { app: { data: { type: 'apps', id: app.id } } },
|
|
178
|
+
} }) });
|
|
179
|
+
request = created.data;
|
|
180
|
+
return { ...base, status: 'pending', note: 'Report request created. Apple delivers the first reports in one to two days; run page-results again then.' };
|
|
181
|
+
}
|
|
182
|
+
const reports = await listAll(client, `/analyticsReportRequests/${request.id}/reports?limit=200`);
|
|
183
|
+
const named = (re: RegExp) => reports.find((r: any) => re.test(r.attributes?.name ?? ''));
|
|
184
|
+
const viewsReport = named(/^App Store Discovery and Engagement Detailed$/);
|
|
185
|
+
const downloadsReport = named(/^App (Store )?Downloads Detailed$/);
|
|
186
|
+
if (!viewsReport || !downloadsReport) {
|
|
187
|
+
return { ...base, status: 'pending', note: 'The Detailed reports are not listed yet; Apple adds them one to two days after the request.' };
|
|
188
|
+
}
|
|
189
|
+
const views = await readReport(client, viewsReport.id, start, end, download);
|
|
190
|
+
const downloads = await readReport(client, downloadsReport.id, start, end, download);
|
|
191
|
+
return { ...base, coverage: { views: views.dates.length, downloads: downloads.dates.length }, rows: foldPages(views.rows, downloads.rows) };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function printPageResults(results: PageResults): void {
|
|
195
|
+
const { start, end } = results.window;
|
|
196
|
+
console.log(`App Store pages, ${start} to ${end} (exclusive)`);
|
|
197
|
+
if (results.note) console.log(`\n${results.note}`);
|
|
198
|
+
if (results.status === 'ok') {
|
|
199
|
+
console.log(`Data on ${results.coverage.views} days (views) and ${results.coverage.downloads} days (downloads); Apple lags two to three days.\n`);
|
|
200
|
+
const names = new Set(results.pages.map(p => p.name));
|
|
201
|
+
const shown = results.rows.filter(r => names.has(r.title) || isDefaultPage(r)).concat(results.rows.filter(r => !names.has(r.title) && !isDefaultPage(r)).slice(0, 5));
|
|
202
|
+
const w = Math.max(12, ...shown.map(r => r.title.length));
|
|
203
|
+
console.log(`${'Page'.padEnd(w)} ${'Views'.padStart(8)} ${'Downloads'.padStart(9)} ${'Per view'.padStart(8)}`);
|
|
204
|
+
for (const r of shown) {
|
|
205
|
+
console.log(`${r.title.padEnd(w)} ${String(r.pageViews).padStart(8)} ${String(r.firstTimeDownloads).padStart(9)} ${pct(downloadsPerView(r)).padStart(8)}${names.has(r.title) ? ' custom' : ''}`);
|
|
206
|
+
}
|
|
207
|
+
if (!shown.length) console.log('No page views in the window.');
|
|
208
|
+
console.log('\nDownloads are first-time downloads. Apple drops rows under five users and adds noise, so small pages read low or not at all.');
|
|
209
|
+
}
|
|
210
|
+
for (const p of results.pages) console.log(` ${p.name}: ${p.url ?? '(no URL yet)'}`);
|
|
211
|
+
if (results.test) {
|
|
212
|
+
const t = results.test;
|
|
213
|
+
console.log(`\nProduct page test "${t.name}": ${t.state}${t.startDate ? `, started ${t.startDate}` : ''}${t.endDate ? `, ended ${t.endDate}` : ''}`);
|
|
214
|
+
console.log(` ${t.trafficProportion ?? '?'}% of visitors in treatments: ${t.treatments.map(x => x.name).join(', ') || 'none'}`);
|
|
215
|
+
console.log(" Apple's API has no test results. Read them in App Store Connect → Analytics → Acquisition → Product Page Optimization,");
|
|
216
|
+
console.log(' then record them with: page-test --result "<what Apple shows>" --annotate');
|
|
217
|
+
}
|
|
218
|
+
}
|