@goosetools/goose-tools 0.0.0-stage → 0.1.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/README.md +98 -2
- package/bin/goose-tools.js +61 -0
- package/lib/check/src/agent.js +90 -0
- package/lib/check/src/analyze.js +311 -0
- package/lib/check/src/client.js +136 -0
- package/lib/check/src/copy.js +355 -0
- package/lib/check/src/fixes.js +153 -0
- package/lib/check/src/frame.js +92 -0
- package/lib/check/src/guard.js +441 -0
- package/lib/check/src/index.js +18 -0
- package/lib/check/src/mcp-http.js +169 -0
- package/lib/check/src/mcp.js +153 -0
- package/lib/check/src/scan.js +55 -0
- package/lib/check/src/stack.js +61 -0
- package/lib/check/src/tlds.js +3 -0
- package/lib/check/src/view.js +130 -0
- package/lib/check/src/worker.js +257 -0
- package/lib/engine/src/bots.js +146 -0
- package/lib/engine/src/directives.js +131 -0
- package/lib/engine/src/exposure.js +70 -0
- package/lib/engine/src/frontend.js +157 -0
- package/lib/engine/src/headers.js +76 -0
- package/lib/engine/src/hidden-text.js +425 -0
- package/lib/engine/src/html.js +794 -0
- package/lib/engine/src/index.js +20 -0
- package/lib/engine/src/php.js +316 -0
- package/lib/engine/src/policies.js +234 -0
- package/lib/engine/src/reach.js +199 -0
- package/lib/engine/src/robots.js +275 -0
- package/lib/engine/src/secrets.js +142 -0
- package/lib/engine/src/signals.js +144 -0
- package/lib/rules/data/bots.json.js +1 -0
- package/lib/rules/data/exposure.json.js +1 -0
- package/lib/rules/data/frontend.json.js +1 -0
- package/lib/rules/data/headers.json.js +1 -0
- package/lib/rules/data/secrets.json.js +1 -0
- package/lib/ui/LICENSE-Inter.txt +93 -0
- package/lib/ui/assets.js +5 -0
- package/package.json +37 -4
- package/src/local.js +61 -0
- package/src/mcp.js +61 -0
- package/src/setup.js +395 -0
- package/src/site/auth.js +287 -0
- package/src/site/beacon.js +462 -0
- package/src/site/collect.js +484 -0
- package/src/site/handler.js +405 -0
- package/src/site/index.js +88 -0
- package/src/site/limits.js +48 -0
- package/src/site/pages.js +75 -0
- package/src/site/qr.js +318 -0
- package/src/site/reports.js +1117 -0
- package/src/site/source.js +68 -0
- package/src/site/store-pg.js +225 -0
- package/src/site/store.js +249 -0
|
@@ -0,0 +1,1117 @@
|
|
|
1
|
+
// The dashboard's Insights and Performance overviews, and the Insights Pages and Sources tabs, from the day totals
|
|
2
|
+
// collect.js writes. Each is in the shape the WordPress plugin's REST routes return (goose-tools/includes/src/Admin/
|
|
3
|
+
// Overviews.php, InsightsPages.php, InsightsSources.php), so the plugin's React apps draw it as they are (InsightsApp,
|
|
4
|
+
// PerformanceApp, InsightsPagesApp, InsightsSourcesApp), as in the approved mockup (check/design/build/data.js, level 2).
|
|
5
|
+
//
|
|
6
|
+
// Ports, with the same rules and limits:
|
|
7
|
+
// - Insights/Exits.php, Summary.php, PagesReport.php (the earlier period to compare with) and Overview/Visits.php;
|
|
8
|
+
// - Insights/PagesReport.php and SourcesReport.php, with Admin/InsightsPages.php and InsightsSources.php, for the tabs;
|
|
9
|
+
// - Speed/Metrics.php (75th percentile, verdicts), Summary.php and Overview/Performance.php;
|
|
10
|
+
// - Signals/ActivityPattern.php for the weekday and hour grid;
|
|
11
|
+
// - Overview/Shape.php and Report/Check.php for parts, axes and "What to do".
|
|
12
|
+
//
|
|
13
|
+
// What the package has no source for, and what it reports instead:
|
|
14
|
+
// - modules: on from the first day anything was counted (the package counts once its route is in place);
|
|
15
|
+
// - warning and waiting: null and false (no buffer folder, no merge job);
|
|
16
|
+
// - pro: null (the Pro Edition's panel);
|
|
17
|
+
// - slow: from the page script's slow scripts (collect.js attribution), as goose-tools-pro Speed/Report.php and
|
|
18
|
+
// Overview/Performance.php slow() shape it. Each script on this site is its own row; each other site is one row;
|
|
19
|
+
// code in the page itself is one row;
|
|
20
|
+
// - cache and server: the edge cache off and no caches found (the plugin's Cloudflare and server cache modules);
|
|
21
|
+
// - countries: names in English, the top five and "Other countries", as the approved mockup shows them;
|
|
22
|
+
// - days and hours are UTC (the plugin uses the site's time zone from WordPress settings).
|
|
23
|
+
import { CORE, EDGES, METRICS, PAGE_KINDS, RATINGS, THRESHOLDS, rate } from './collect.js';
|
|
24
|
+
import { KINDS } from './source.js';
|
|
25
|
+
import { shiftDay, today, CAP } from './limits.js';
|
|
26
|
+
|
|
27
|
+
/** Kinds each overview sums (store.sums); hours are read by day (rowsOf). */
|
|
28
|
+
const INSIGHTS_KINDS = ['page', 'continued', 'source', 'country', 'device'];
|
|
29
|
+
const SPEED_KINDS = ['speed', 'speed.element', 'speed.hist', ...METRICS.flatMap((m) => RATINGS.map((r) => `speed.${m}.${r}`))];
|
|
30
|
+
const SLOW_KINDS = ['speed.named', 'script.ms', 'script.views', 'script.inp'];
|
|
31
|
+
const DEEP_KINDS = ['load.lcp', 'load.n', 'load.ms', 'ttfb.ms', 'ttfb.n', 'call.ms', 'call.n'];
|
|
32
|
+
|
|
33
|
+
/** Default sign-up steps: pricing, sign-up, and the page after sign-up (spec/standalone.md section 4). */
|
|
34
|
+
export const STEPS = ['/pricing', '/signup', '/welcome'];
|
|
35
|
+
|
|
36
|
+
/** Visits in the period before the caption says anything. */
|
|
37
|
+
export const CAPTION_MIN = 100;
|
|
38
|
+
|
|
39
|
+
/** @param {number} h 0 to 24 */
|
|
40
|
+
const clock = (h) => {
|
|
41
|
+
h %= 24;
|
|
42
|
+
return h === 0 ? 'midnight' : h === 12 ? 'noon' : h < 12 ? `${h} am` : `${h - 12} pm`;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Caption under "When visits come", wording and rule approved by the owner 2026-11-24 (from the approved mockup: "Most visits come on weekdays, between 8 am and 6 pm."): the
|
|
47
|
+
* busy hours, when they hold more than half the visits, and weekdays or weekends when one gets at least 1.5 times the
|
|
48
|
+
* visits per day of the other. Hours are UTC, so the caption says so. '' with fewer than CAPTION_MIN visits.
|
|
49
|
+
* @param {number[][]} grid hourGrid(), Monday first.
|
|
50
|
+
*/
|
|
51
|
+
export function hoursCaption(grid) {
|
|
52
|
+
const byHour = Array(24).fill(0);
|
|
53
|
+
let weekday = 0;
|
|
54
|
+
let weekend = 0;
|
|
55
|
+
grid.forEach((row, d) => row.forEach((n, h) => {
|
|
56
|
+
byHour[h] += n;
|
|
57
|
+
if (d < 5) weekday += n;
|
|
58
|
+
else weekend += n;
|
|
59
|
+
}));
|
|
60
|
+
const total = weekday + weekend;
|
|
61
|
+
if (total < CAPTION_MIN) return '';
|
|
62
|
+
// Busy hours get more than an even share. The caption's hours run from the first busy hour to the last, around the
|
|
63
|
+
// longest stretch of quiet ones (it may cross midnight).
|
|
64
|
+
const busy = byHour.map((n) => n > total / 24);
|
|
65
|
+
let gap = { start: 0, len: 0 };
|
|
66
|
+
for (let start = 0; start < 24; start++) {
|
|
67
|
+
if (busy[start] || busy[(start + 23) % 24] === false) continue; // a quiet stretch starts after a busy hour
|
|
68
|
+
let len = 0;
|
|
69
|
+
while (len < 24 && !busy[(start + len) % 24]) len++;
|
|
70
|
+
if (len > gap.len) gap = { start, len };
|
|
71
|
+
}
|
|
72
|
+
const start = (gap.start + gap.len) % 24;
|
|
73
|
+
const len = 24 - gap.len;
|
|
74
|
+
let n = 0;
|
|
75
|
+
for (let i = 0; i < len; i++) n += byHour[(start + i) % 24];
|
|
76
|
+
const days = weekday / 5 >= 1.5 * (weekend / 2) ? ' on weekdays' : weekend / 2 >= 1.5 * (weekday / 5) ? ' on weekends' : '';
|
|
77
|
+
if (len >= 20 || n <= total / 2) return `Visits come at all hours${days}.`;
|
|
78
|
+
return `Most visits come${days ? days + ',' : ''} between ${clock(start)} and ${clock(start + len)} UTC.`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Name of the row that sums the countries past the top five (approved mockup). */
|
|
82
|
+
export const OTHER_COUNTRIES = 'Other countries';
|
|
83
|
+
|
|
84
|
+
/** Rows per overview list (Overview\Visits::ROWS). */
|
|
85
|
+
const ROWS = 8;
|
|
86
|
+
/** Countries named before "Other countries". */
|
|
87
|
+
const COUNTRIES = 5;
|
|
88
|
+
/** Days of hour totals the usual hours come from (Wp\Activity::HISTORY_DAYS). */
|
|
89
|
+
export const HISTORY_DAYS = 90;
|
|
90
|
+
/** Visits on record before usual hours are given (Signals\ActivityPattern::MIN_HISTORY). */
|
|
91
|
+
export const MIN_HISTORY = 20;
|
|
92
|
+
/** Pages drawn in the page map (Overview\Performance::PAGES). */
|
|
93
|
+
const MAP_PAGES = 400;
|
|
94
|
+
/** "What slows your pages": at most 8 scripts; 50 ms or more of script time per view is marked (Performance.php SLOW_MS). */
|
|
95
|
+
const SLOW_ROWS = 8;
|
|
96
|
+
const SLOW_MS = 50;
|
|
97
|
+
/** "Load time by file": 5 files per kind of page; 500 ms or more is marked. "Server response by page": 6 rows. */
|
|
98
|
+
const LOAD_ROWS = 5;
|
|
99
|
+
const LOAD_HOT_MS = 500;
|
|
100
|
+
const SERVER_ROWS = 6;
|
|
101
|
+
/** Source kinds that are arrivals, in the order the screen shows them (Overview\Visits::ARRIVALS). */
|
|
102
|
+
const ARRIVALS = ['search', 'ai', 'social', 'campaign', 'other', 'direct'];
|
|
103
|
+
/** Parts measured by Speed check: part => measure (Overview\Performance::MEASURES). */
|
|
104
|
+
const MEASURES = { server: 'ttfb', lcp: 'lcp', inp: 'inp', cls: 'cls' };
|
|
105
|
+
/** "What to do" order within one state (Overview\Performance::RANK). */
|
|
106
|
+
const RANK = { money: 7000000, product: 6000000, home: 5000000, pages: 4000000, scripts: 3000000 };
|
|
107
|
+
/** State order (Report\Check::ORDER). */
|
|
108
|
+
const ORDER = { risk: 3, attention: 2, unknown: 1, ok: 0 };
|
|
109
|
+
/** Checks listed in "What to do" (Overview\Shape::FIX_LIST). */
|
|
110
|
+
const FIX_LIST = 5;
|
|
111
|
+
|
|
112
|
+
/* ------------------------------------------------------------------ Helpers */
|
|
113
|
+
|
|
114
|
+
/** PHP's round( x, 3 ): to 15 significant digits first, so 0.1235 is 0.124 as in the plugin. */
|
|
115
|
+
const round3 = (x) => Math.round(Number((x * 1000).toPrecision(15))) / 1000;
|
|
116
|
+
/** PHP's strcmp() order for ASCII keys. */
|
|
117
|
+
const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* First and last day of the last `days` days, today included, and the number of days (Insights\Days::range()).
|
|
121
|
+
* @param {number} now
|
|
122
|
+
* @param {number} days
|
|
123
|
+
* @returns {[string, string, number]}
|
|
124
|
+
*/
|
|
125
|
+
function period(now, days) {
|
|
126
|
+
const n = Math.max(1, Math.floor(Number(days)) || 1);
|
|
127
|
+
const to = today(now);
|
|
128
|
+
return [shiftDay(to, -(n - 1)), to, n];
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The note shown above a report when the daily limit on counted views was reached on a day in the period
|
|
133
|
+
* (spec/standalone-database.md section 5): the shared Messages line, as `warning`. Null without such a day.
|
|
134
|
+
* @param {{rows: (kind: string, from: string, to: string) => any}} store
|
|
135
|
+
* @param {string} from
|
|
136
|
+
* @param {string} to
|
|
137
|
+
* @param {number} now
|
|
138
|
+
*/
|
|
139
|
+
export async function limitWarning(store, from, to, now) {
|
|
140
|
+
if (typeof store.rows !== 'function') return null;
|
|
141
|
+
/** @type {Map<string, number>} */
|
|
142
|
+
const byDay = new Map();
|
|
143
|
+
for (const r of await store.rows(CAP, from, to)) byDay.set(r.day, Math.max(byDay.get(r.day) ?? 0, Number(r.key) || 0));
|
|
144
|
+
if (!byDay.size) return null;
|
|
145
|
+
const days = [...byDay.keys()].sort();
|
|
146
|
+
const limits = new Set(byDay.values());
|
|
147
|
+
const limit = limits.size === 1 ? ` of ${[...limits][0].toLocaleString('en-US')} counted views` : '';
|
|
148
|
+
const name = (d) => new Date(`${d}T00:00:00Z`).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });
|
|
149
|
+
const raise = 'You can raise the limit in your route file.';
|
|
150
|
+
if (days.length === 1 && days[0] === today(now)) return { code: 'daily_limit', message: `Today, your site reached its daily limit${limit}. Counting starts again at midnight UTC. ${raise}` };
|
|
151
|
+
if (days.length === 1) return { code: 'daily_limit', message: `On ${name(days[0])}, your site reached its daily limit${limit}. Later views that day aren't counted. ${raise}` };
|
|
152
|
+
const list = days.length === 2 ? `${name(days[0])} and ${name(days[1])}` : `${days.slice(0, -1).map(name).join(', ')} and ${name(days.at(-1))}`;
|
|
153
|
+
return { code: 'daily_limit', message: `Your site reached its daily limit${limit} on ${list}. Later views on those days aren't counted. ${raise}` };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* First and last day of the period of the same length just before (Insights\PagesReport::previous()).
|
|
158
|
+
* @param {string} from
|
|
159
|
+
* @param {number} days
|
|
160
|
+
*/
|
|
161
|
+
export function previous(from, days) {
|
|
162
|
+
return [shiftDay(from, -Math.max(1, days)), shiftDay(from, -1)];
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Totals summed over days, by kind then key.
|
|
167
|
+
* @param {{kind: string, key: string, n: number}[]} rows
|
|
168
|
+
*/
|
|
169
|
+
function byKind(rows) {
|
|
170
|
+
/** @type {Map<string, Map<string, number>>} */
|
|
171
|
+
const out = new Map();
|
|
172
|
+
for (const { kind, key, n } of rows) {
|
|
173
|
+
let m = out.get(kind);
|
|
174
|
+
if (!m) out.set(kind, (m = new Map()));
|
|
175
|
+
m.set(key, (m.get(key) ?? 0) + n);
|
|
176
|
+
}
|
|
177
|
+
return out;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** @param {Map<string, Map<string, number>>} t @param {string} kind */
|
|
181
|
+
const of = (t, kind) => t.get(kind) ?? new Map();
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Rows of one kind between two days.
|
|
185
|
+
* @param {any} store
|
|
186
|
+
* @param {string} kind
|
|
187
|
+
* @param {string} from
|
|
188
|
+
* @param {string} to
|
|
189
|
+
* @returns {Promise<{day: string, key: string, n: number}[]>}
|
|
190
|
+
*/
|
|
191
|
+
async function rowsOf(store, kind, from, to) {
|
|
192
|
+
return store.rows(kind, from, to);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* The first day any total is stored, or ''.
|
|
197
|
+
* @param {any} store
|
|
198
|
+
* @returns {Promise<string>}
|
|
199
|
+
*/
|
|
200
|
+
async function firstDay(store) {
|
|
201
|
+
return store.firstDay();
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Unix seconds at the start of a day (UTC). @param {string} day */
|
|
205
|
+
const dayStart = (day) => (day ? Date.parse(day + 'T00:00:00Z') / 1000 : 0);
|
|
206
|
+
|
|
207
|
+
/* ------------------------------------------------------------------ Shape (Overview/Shape.php, Report/Check.php) */
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* @param {string} id
|
|
211
|
+
* @param {number} passed
|
|
212
|
+
* @param {number} total
|
|
213
|
+
* @param {string} state
|
|
214
|
+
*/
|
|
215
|
+
function axis(id, passed, total, state) {
|
|
216
|
+
return { id, passed: Math.max(0, passed), total: Math.max(0, total), state: state in ORDER ? state : 'unknown', before: {} };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** @param {{state: string}[]} list */
|
|
220
|
+
function worst(list) {
|
|
221
|
+
let w = 'ok';
|
|
222
|
+
for (const c of list) if (ORDER[c.state] > ORDER[w]) w = c.state;
|
|
223
|
+
return w;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* A part from its axes: passed and total summed, the worst state; without axes it is "unknown", never "ok".
|
|
228
|
+
* @param {string} id
|
|
229
|
+
* @param {ReturnType<typeof axis>[]} axes
|
|
230
|
+
*/
|
|
231
|
+
function part(id, axes) {
|
|
232
|
+
return {
|
|
233
|
+
id,
|
|
234
|
+
axes,
|
|
235
|
+
passed: axes.reduce((s, a) => s + a.passed, 0),
|
|
236
|
+
total: axes.reduce((s, a) => s + a.total, 0),
|
|
237
|
+
state: axes.length ? worst(axes) : 'unknown',
|
|
238
|
+
before: {},
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* A finding for "What to do". The screen words it from its ID and args (assets/src/words.js).
|
|
244
|
+
* @param {string} id
|
|
245
|
+
* @param {string} area
|
|
246
|
+
* @param {string} state
|
|
247
|
+
* @param {object} args
|
|
248
|
+
* @param {number} weight
|
|
249
|
+
*/
|
|
250
|
+
function finding(id, area, state, args, weight) {
|
|
251
|
+
return { id, area, state: state in ORDER ? state : 'unknown', title: '', verdict: '', evidence: [], action: null, weight, args, items: [] };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Areas, the top of the list, the count and the overall state.
|
|
256
|
+
* @param {ReturnType<typeof finding>[]} findings
|
|
257
|
+
* @param {boolean} measured
|
|
258
|
+
*/
|
|
259
|
+
function finish(findings, measured) {
|
|
260
|
+
const open = [...findings].sort((a, b) => ORDER[b.state] - ORDER[a.state] || b.weight - a.weight);
|
|
261
|
+
/** @type {Map<string, {id: string, checks: object[]}>} */
|
|
262
|
+
const areas = new Map();
|
|
263
|
+
for (const f of open) {
|
|
264
|
+
if (!areas.has(f.area)) areas.set(f.area, { id: f.area, checks: [] });
|
|
265
|
+
areas.get(f.area)?.checks.push(f);
|
|
266
|
+
}
|
|
267
|
+
const w = worst(findings);
|
|
268
|
+
return {
|
|
269
|
+
areas: [...areas.values()],
|
|
270
|
+
fixes: open.slice(0, FIX_LIST),
|
|
271
|
+
open_count: open.length,
|
|
272
|
+
state: w === 'risk' || w === 'attention' ? w : measured ? 'good' : 'unchecked',
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/* ------------------------------------------------------------------ Insights (Insights/Exits.php, Summary.php) */
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Exits per page: views minus the views it sent on to another page of the site, never below 0. Most viewed first,
|
|
280
|
+
* then by path. exit_rate is exits / views, three decimals.
|
|
281
|
+
* @param {Map<string, number>} views
|
|
282
|
+
* @param {Map<string, number>} continued
|
|
283
|
+
*/
|
|
284
|
+
export function exitPages(views, continued) {
|
|
285
|
+
const out = [];
|
|
286
|
+
for (const [p, v] of views) {
|
|
287
|
+
if (v <= 0) continue;
|
|
288
|
+
const c = Math.min(v, Math.max(0, continued.get(p) ?? 0));
|
|
289
|
+
out.push({ path: p, views: v, continued: c, exits: v - c, exit_rate: round3((v - c) / v) });
|
|
290
|
+
}
|
|
291
|
+
return out.sort((a, b) => b.views - a.views || cmp(a.path, b.path));
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Key => views as rows with a share, most first, then by key.
|
|
296
|
+
* @param {Map<string, number>} counts
|
|
297
|
+
* @param {string} field
|
|
298
|
+
* @param {number} limit
|
|
299
|
+
*/
|
|
300
|
+
function shareRows(counts, field, limit) {
|
|
301
|
+
let total = 0;
|
|
302
|
+
for (const n of counts.values()) total += n;
|
|
303
|
+
const out = [...counts].map(([k, n]) => ({ [field]: k, views: n, share: total ? round3(n / total) : 0 }));
|
|
304
|
+
out.sort((a, b) => b.views - a.views || cmp(a[field], b[field]));
|
|
305
|
+
return out.slice(0, limit);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* The visitor insights report for a range of days (Insights\Summary::build()).
|
|
310
|
+
* @param {{from: string, to: string, days: number, pages?: Map<string, [number, number]>, sources?: [string, string, number][], countries?: Map<string, number>, devices?: Map<string, number>}} data
|
|
311
|
+
* @param {number} [limit]
|
|
312
|
+
*/
|
|
313
|
+
export function insightsSummary(data, limit = 25) {
|
|
314
|
+
const views = new Map();
|
|
315
|
+
const continued = new Map();
|
|
316
|
+
for (const [p, [v, c]] of data.pages ?? new Map()) {
|
|
317
|
+
views.set(p, v);
|
|
318
|
+
continued.set(p, c);
|
|
319
|
+
}
|
|
320
|
+
const pages = exitPages(views, continued);
|
|
321
|
+
/** @type {Record<string, number>} */
|
|
322
|
+
const kinds = Object.fromEntries(KINDS.map((k) => [k, 0]));
|
|
323
|
+
const sources = [];
|
|
324
|
+
for (const [kind, name, n] of data.sources ?? []) {
|
|
325
|
+
if (!(kind in kinds)) continue;
|
|
326
|
+
kinds[kind] += n;
|
|
327
|
+
if (name !== '') sources.push({ kind, name, views: n });
|
|
328
|
+
}
|
|
329
|
+
const sourceTotal = Object.values(kinds).reduce((s, n) => s + n, 0);
|
|
330
|
+
sources.sort((a, b) => b.views - a.views || cmp(`${a.kind}|${a.name}`, `${b.kind}|${b.name}`));
|
|
331
|
+
return {
|
|
332
|
+
from: data.from,
|
|
333
|
+
to: data.to,
|
|
334
|
+
days: data.days,
|
|
335
|
+
views: pages.reduce((s, p) => s + p.views, 0),
|
|
336
|
+
exits: pages.reduce((s, p) => s + p.exits, 0),
|
|
337
|
+
pages: pages.slice(0, limit),
|
|
338
|
+
kinds: KINDS.map((kind) => ({ kind, views: kinds[kind], share: sourceTotal ? round3(kinds[kind] / sourceTotal) : 0 })),
|
|
339
|
+
sources: sources.slice(0, limit),
|
|
340
|
+
ai_minimum: kinds.ai,
|
|
341
|
+
countries: shareRows(data.countries ?? new Map(), 'country', limit),
|
|
342
|
+
devices: shareRows(data.devices ?? new Map(), 'device', limit),
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* A source key as stored ('kind|name') as [kind, name]. The key past the day's cap, '(other)', is an other site.
|
|
348
|
+
* @param {string} key
|
|
349
|
+
* @returns {[string, string]}
|
|
350
|
+
*/
|
|
351
|
+
function splitSource(key) {
|
|
352
|
+
const i = key.indexOf('|');
|
|
353
|
+
return i < 0 ? ['other', key] : [key.slice(0, i), key.slice(i + 1)];
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const REGIONS = (() => {
|
|
357
|
+
try {
|
|
358
|
+
return new Intl.DisplayNames(['en'], { type: 'region' });
|
|
359
|
+
} catch {
|
|
360
|
+
return null;
|
|
361
|
+
}
|
|
362
|
+
})();
|
|
363
|
+
|
|
364
|
+
/** A country's name in English, or its code when there is none (T1, Tor). '' stays '' (unknown). @param {string} code */
|
|
365
|
+
export function countryName(code) {
|
|
366
|
+
if (!code) return '';
|
|
367
|
+
try {
|
|
368
|
+
return REGIONS?.of(code) || code;
|
|
369
|
+
} catch {
|
|
370
|
+
return code;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Countries as the dashboard shows them: the five with the most views by name, the rest as "Other countries".
|
|
376
|
+
* Unknown stays a row with the name '', which the screen calls Unknown.
|
|
377
|
+
* @param {Map<string, number>} counts
|
|
378
|
+
*/
|
|
379
|
+
function countryRows(counts) {
|
|
380
|
+
const all = shareRows(counts, 'country', Infinity);
|
|
381
|
+
const total = all.reduce((s, r) => s + r.views, 0);
|
|
382
|
+
const share = (n) => (total ? round3(n / total) : 0);
|
|
383
|
+
const keep = all.length > COUNTRIES + 1 ? all.slice(0, COUNTRIES) : all;
|
|
384
|
+
const rows = keep.map((r) => ({ name: countryName(r.country), share: r.share, views: r.views }));
|
|
385
|
+
if (keep.length < all.length) {
|
|
386
|
+
const rest = all.slice(COUNTRIES).reduce((s, r) => s + r.views, 0);
|
|
387
|
+
rows.push({ name: OTHER_COUNTRIES, share: share(rest), views: rest });
|
|
388
|
+
}
|
|
389
|
+
return rows;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/* ------------------------------------------------------------------ Hours (Signals/ActivityPattern.php) */
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Visits by weekday (Monday first) and hour, from hour totals.
|
|
396
|
+
* @param {{day: string, key: string, n: number}[]} rows
|
|
397
|
+
*/
|
|
398
|
+
export function hourGrid(rows) {
|
|
399
|
+
const grid = Array.from({ length: 7 }, () => Array(24).fill(0));
|
|
400
|
+
for (const { day, key, n } of rows) {
|
|
401
|
+
const h = Number(key);
|
|
402
|
+
if (!Number.isInteger(h) || h < 0 || h > 23) continue;
|
|
403
|
+
const weekday = (new Date(day + 'T12:00:00Z').getUTCDay() + 6) % 7;
|
|
404
|
+
grid[weekday][h] += n;
|
|
405
|
+
}
|
|
406
|
+
return grid;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* The usual hours of day: from the 5th to the 95th percentile of all visits on record by hour, or null when fewer
|
|
411
|
+
* than MIN_HISTORY are on record (ActivityPattern::usual_hours(), from counts instead of a list of every hour).
|
|
412
|
+
* @param {number[][]} grid
|
|
413
|
+
* @returns {[number, number] | null}
|
|
414
|
+
*/
|
|
415
|
+
export function usualHours(grid) {
|
|
416
|
+
const byHour = Array(24).fill(0);
|
|
417
|
+
for (const row of grid) row.forEach((n, h) => (byHour[h] += n));
|
|
418
|
+
const count = byHour.reduce((s, n) => s + n, 0);
|
|
419
|
+
if (count < MIN_HISTORY) return null;
|
|
420
|
+
const last = count - 1;
|
|
421
|
+
const at = (i) => {
|
|
422
|
+
let seen = 0;
|
|
423
|
+
for (let h = 0; h < 24; h++) {
|
|
424
|
+
seen += byHour[h];
|
|
425
|
+
if (i < seen) return h;
|
|
426
|
+
}
|
|
427
|
+
return 23;
|
|
428
|
+
};
|
|
429
|
+
return [at(Math.floor(last * 0.05)), at(Math.ceil(last * 0.95))];
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/* ------------------------------------------------------------------ Insights overview (Overview/Visits.php) */
|
|
433
|
+
|
|
434
|
+
/** A path without its trailing slash, so /pricing and /pricing/ are one step. @param {string} p */
|
|
435
|
+
const stepKey = (p) => (p.length > 1 ? p.replace(/\/+$/, '') || '/' : p);
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* The Insights overview.
|
|
439
|
+
* @param {any} store From openStore().
|
|
440
|
+
* @param {{days?: number, now?: number, steps?: string[], site?: string}} [options] site: the site's name for the header.
|
|
441
|
+
*/
|
|
442
|
+
export async function insightsOverview(store, { days = 30, now = Date.now(), steps = STEPS, site = '' } = {}) {
|
|
443
|
+
const [from, to, n] = period(now, days);
|
|
444
|
+
const t = byKind(await store.sums(from, to, INSIGHTS_KINDS));
|
|
445
|
+
const first = await firstDay(store);
|
|
446
|
+
const [prevFrom, prevTo] = previous(from, n);
|
|
447
|
+
const since = dayStart(first);
|
|
448
|
+
|
|
449
|
+
const viewed = of(t, 'page');
|
|
450
|
+
const continued = of(t, 'continued');
|
|
451
|
+
/** @type {Map<string, [number, number]>} */
|
|
452
|
+
const pages = new Map();
|
|
453
|
+
for (const p of new Set([...viewed.keys(), ...continued.keys()])) pages.set(p, [viewed.get(p) ?? 0, continued.get(p) ?? 0]);
|
|
454
|
+
const r = insightsSummary({
|
|
455
|
+
from,
|
|
456
|
+
to,
|
|
457
|
+
days: n,
|
|
458
|
+
pages,
|
|
459
|
+
sources: [...of(t, 'source')].map(([key, v]) => [...splitSource(key), v]),
|
|
460
|
+
countries: of(t, 'country'),
|
|
461
|
+
devices: of(t, 'device'),
|
|
462
|
+
});
|
|
463
|
+
|
|
464
|
+
const byKindViews = Object.fromEntries(r.kinds.map((k) => [k.kind, k.views]));
|
|
465
|
+
const arrivals = ARRIVALS.reduce((s, k) => s + (byKindViews[k] ?? 0), 0);
|
|
466
|
+
const measured = r.views > 0;
|
|
467
|
+
|
|
468
|
+
const history = await rowsOf(store, 'hour', shiftDay(to, -(HISTORY_DAYS - 1)), to);
|
|
469
|
+
const grid = hourGrid(await rowsOf(store, 'hour', from, to));
|
|
470
|
+
const hours = {
|
|
471
|
+
grid,
|
|
472
|
+
unusual: [],
|
|
473
|
+
usual: usualHours(hourGrid(history)),
|
|
474
|
+
days_recorded: new Set(history.map((h) => h.day)).size,
|
|
475
|
+
caption: hoursCaption(grid),
|
|
476
|
+
};
|
|
477
|
+
|
|
478
|
+
return {
|
|
479
|
+
from,
|
|
480
|
+
to,
|
|
481
|
+
days: n,
|
|
482
|
+
compare: first && first <= prevFrom ? { from: prevFrom, to: prevTo } : null,
|
|
483
|
+
on: true,
|
|
484
|
+
since,
|
|
485
|
+
warning: await limitWarning(store, from, to, now),
|
|
486
|
+
waiting: false,
|
|
487
|
+
site,
|
|
488
|
+
checked: Math.floor(now / 1000),
|
|
489
|
+
section: 'insights',
|
|
490
|
+
modules: { insights: { on: true, since } },
|
|
491
|
+
visits: arrivals,
|
|
492
|
+
views: r.views,
|
|
493
|
+
exits: r.exits,
|
|
494
|
+
kinds: ARRIVALS.map((kind) => ({ kind, views: byKindViews[kind] ?? 0, share: arrivals ? round3((byKindViews[kind] ?? 0) / arrivals) : 0, minimum: kind === 'ai' })),
|
|
495
|
+
ai_minimum: r.ai_minimum,
|
|
496
|
+
pages: r.pages.slice(0, ROWS).map((p) => ({ path: p.path, views: p.views, exits: p.exits, exit_rate: p.exit_rate })),
|
|
497
|
+
sources: r.sources.filter((s) => s.kind !== 'internal').slice(0, ROWS).map((s) => ({ kind: s.kind, name: s.name, views: s.views })),
|
|
498
|
+
countries: countryRows(of(t, 'country')),
|
|
499
|
+
devices: r.devices.slice(0, ROWS).map((d) => ({ name: d.device, share: d.share, views: d.views })),
|
|
500
|
+
pro: null,
|
|
501
|
+
parts: [],
|
|
502
|
+
measured,
|
|
503
|
+
...finish([], measured),
|
|
504
|
+
pro_installed: false,
|
|
505
|
+
hours,
|
|
506
|
+
signup: (Array.isArray(steps) ? steps : STEPS).filter((s) => typeof s === 'string').map((step) => {
|
|
507
|
+
let v = 0;
|
|
508
|
+
for (const [p, c] of viewed) if (stepKey(p) === stepKey(step)) v += c;
|
|
509
|
+
return { name: step, path: step, views: v };
|
|
510
|
+
}),
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/* ------------------------------------------------------------------ Pages and Sources tabs (PagesReport, SourcesReport) */
|
|
515
|
+
|
|
516
|
+
/** Most rows in the Pages and Sources tabs (Insights\PagesReport::LIMIT, SourcesReport::LIMIT). */
|
|
517
|
+
export const TAB_ROWS = 500;
|
|
518
|
+
|
|
519
|
+
/** Names people know: source name as counted => name shown (Insights\SourcesReport::TITLES). */
|
|
520
|
+
export const SOURCE_TITLES = {
|
|
521
|
+
'google.com': 'Google', 'bing.com': 'Bing', 'duckduckgo.com': 'DuckDuckGo', 'search.yahoo.com': 'Yahoo', 'yandex.com': 'Yandex',
|
|
522
|
+
'baidu.com': 'Baidu', 'ecosia.org': 'Ecosia', 'search.brave.com': 'Brave Search', 'startpage.com': 'Startpage', 'qwant.com': 'Qwant',
|
|
523
|
+
'naver.com': 'Naver', 'seznam.cz': 'Seznam', 'chatgpt.com': 'ChatGPT', 'chat.openai.com': 'ChatGPT', 'perplexity.ai': 'Perplexity',
|
|
524
|
+
'claude.ai': 'Claude', 'copilot.microsoft.com': 'Copilot', 'gemini.google.com': 'Gemini', 'facebook.com': 'Facebook',
|
|
525
|
+
'messenger.com': 'Messenger', 'instagram.com': 'Instagram', 'threads.net': 'Threads', 'threads.com': 'Threads', 'x.com': 'X',
|
|
526
|
+
'twitter.com': 'X', 't.co': 'X', 'linkedin.com': 'LinkedIn', 'lnkd.in': 'LinkedIn', 'reddit.com': 'Reddit', 'youtube.com': 'YouTube',
|
|
527
|
+
'tiktok.com': 'TikTok', 'pinterest.com': 'Pinterest', 'bsky.app': 'Bluesky', 'news.ycombinator.com': 'Hacker News', 'quora.com': 'Quora',
|
|
528
|
+
'tumblr.com': 'Tumblr', 'vk.com': 'VK', 'mastodon.social': 'Mastodon', 't.me': 'Telegram', 'discord.com': 'Discord', 'snapchat.com': 'Snapchat',
|
|
529
|
+
};
|
|
530
|
+
|
|
531
|
+
/** The name shown for a source: the name people know for a search engine, AI assistant or social network, else ''. @param {string} kind @param {string} name */
|
|
532
|
+
export function sourceTitle(kind, name) {
|
|
533
|
+
return ['search', 'ai', 'social'].includes(kind) && Object.hasOwn(SOURCE_TITLES, name) ? SOURCE_TITLES[/** @type {keyof typeof SOURCE_TITLES} */ (name)] : '';
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/** The days of a period, first day first. @param {string} from @param {number} days */
|
|
537
|
+
const datesOf = (from, days) => Array.from({ length: days }, (_, i) => shiftDay(from, i));
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* Day totals of one kind for some keys, between two days.
|
|
541
|
+
* @param {any} store
|
|
542
|
+
* @param {string} kind
|
|
543
|
+
* @param {string} from
|
|
544
|
+
* @param {string} to
|
|
545
|
+
* @param {string[]} keys
|
|
546
|
+
* @returns {Promise<{day: string, key: string, n: number}[]>}
|
|
547
|
+
*/
|
|
548
|
+
async function keyDays(store, kind, from, to, keys) {
|
|
549
|
+
if (!keys.length) return [];
|
|
550
|
+
return store.daily(from, to, kind, keys);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** The earlier period to compare with, or null when the totals do not reach back to its first day. @param {string} first @param {string} from @param {number} n */
|
|
554
|
+
function compareWith(first, from, n) {
|
|
555
|
+
const [prevFrom, prevTo] = previous(from, n);
|
|
556
|
+
return first && first <= prevFrom ? { from: prevFrom, to: prevTo } : null;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** What both tabs add to their report (Admin\InsightsPages::read(), InsightsSources::read()). @param {string} first @param {number} now @param {string} site */
|
|
560
|
+
const tabHeader = (first, now, site) => ({ on: true, since: dayStart(first), warning: null, waiting: false, site, checked: Math.floor(now / 1000) });
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* Insights > Pages: every page viewed in the period, with its change against the period before, exits and the views
|
|
564
|
+
* and exits of each day (Insights\PagesReport::build(), Admin\InsightsPages::read()). Pages have no title here: the
|
|
565
|
+
* package counts paths only, so the screen shows the path.
|
|
566
|
+
* @param {any} store From openStore().
|
|
567
|
+
* @param {{days?: number, now?: number, site?: string}} [options]
|
|
568
|
+
*/
|
|
569
|
+
export async function insightsPages(store, { days = 30, now = Date.now(), site = '' } = {}) {
|
|
570
|
+
const [from, to, n] = period(now, days);
|
|
571
|
+
const [prevFrom, prevTo] = previous(from, n);
|
|
572
|
+
const t = byKind(await store.sums(from, to, ['page', 'continued']));
|
|
573
|
+
const before = of(byKind(await store.sums(prevFrom, prevTo, ['page'])), 'page');
|
|
574
|
+
const first = await firstDay(store);
|
|
575
|
+
const compare = compareWith(first, from, n);
|
|
576
|
+
const all = exitPages(of(t, 'page'), of(t, 'continued'));
|
|
577
|
+
const kept = all.slice(0, TAB_ROWS);
|
|
578
|
+
const keys = kept.map((p) => p.path);
|
|
579
|
+
|
|
580
|
+
const index = new Map(datesOf(from, n).map((d, i) => [d, i]));
|
|
581
|
+
/** @type {Map<string, [number[], number[]]>} views and continued, one number per day */
|
|
582
|
+
const series = new Map(keys.map((k) => [k, [Array(n).fill(0), Array(n).fill(0)]]));
|
|
583
|
+
for (const [kind, slot] of /** @type {[string, 0 | 1][]} */ ([['page', 0], ['continued', 1]])) {
|
|
584
|
+
for (const r of await keyDays(store, kind, from, to, keys)) {
|
|
585
|
+
const i = index.get(r.day);
|
|
586
|
+
const s = series.get(r.key);
|
|
587
|
+
if (i !== undefined && s) s[slot][i] += Math.max(0, r.n);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
const rows = kept.map((p) => {
|
|
592
|
+
const was = compare ? Math.max(0, before.get(p.path) ?? 0) : null;
|
|
593
|
+
const [v, c] = /** @type {[number[], number[]]} */ (series.get(p.path));
|
|
594
|
+
return {
|
|
595
|
+
...p,
|
|
596
|
+
title: '',
|
|
597
|
+
previous: was,
|
|
598
|
+
change: was === null ? null : p.views - was,
|
|
599
|
+
new: was === 0,
|
|
600
|
+
// A day's exits are its views minus what it sent on, never below 0 (continued can belong to the day before).
|
|
601
|
+
daily: { views: v, exits: v.map((x, i) => Math.max(0, x - c[i])) },
|
|
602
|
+
};
|
|
603
|
+
});
|
|
604
|
+
|
|
605
|
+
return {
|
|
606
|
+
from,
|
|
607
|
+
to,
|
|
608
|
+
days: n,
|
|
609
|
+
compare,
|
|
610
|
+
pages: all.length,
|
|
611
|
+
views: all.reduce((s, p) => s + p.views, 0),
|
|
612
|
+
exits: all.reduce((s, p) => s + p.exits, 0),
|
|
613
|
+
shown: rows.length,
|
|
614
|
+
capped: all.length > TAB_ROWS,
|
|
615
|
+
limit: TAB_ROWS,
|
|
616
|
+
rows,
|
|
617
|
+
...tabHeader(first, now, site),
|
|
618
|
+
warning: await limitWarning(store, from, to, now),
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/** A stored source key's row key: direct has no name. @param {string} key */
|
|
623
|
+
function sourceKey(key) {
|
|
624
|
+
const [kind, name] = splitSource(key);
|
|
625
|
+
return `${kind}|${kind === 'direct' ? '' : name}`;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/**
|
|
629
|
+
* Sources summed per kind and name, internal views and unknown kinds left out, the most visits first, then in the
|
|
630
|
+
* order of kinds, then by name (Insights\SourcesReport::rows()).
|
|
631
|
+
* @param {Map<string, number>} counts Stored key ('kind|name') => views.
|
|
632
|
+
*/
|
|
633
|
+
function sourceRows(counts) {
|
|
634
|
+
/** @type {Map<string, {kind: string, name: string, visits: number}>} */
|
|
635
|
+
const sum = new Map();
|
|
636
|
+
for (const [key, v] of counts) {
|
|
637
|
+
const [kind, raw] = splitSource(key);
|
|
638
|
+
if (!ARRIVALS.includes(kind)) continue;
|
|
639
|
+
const name = kind === 'direct' ? '' : raw;
|
|
640
|
+
const r = sum.get(`${kind}|${name}`) ?? { kind, name, visits: 0 };
|
|
641
|
+
r.visits += Math.max(0, v);
|
|
642
|
+
sum.set(`${kind}|${name}`, r);
|
|
643
|
+
}
|
|
644
|
+
return [...sum.values()].filter((r) => r.visits > 0).sort((a, b) => b.visits - a.visits || ARRIVALS.indexOf(a.kind) - ARRIVALS.indexOf(b.kind) || cmp(a.name, b.name));
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* Insights > Sources: every source that sent visits in the period, with its share of all visits, its change against
|
|
649
|
+
* the period before and its visits each day (Insights\SourcesReport::build(), Admin\InsightsSources::read()).
|
|
650
|
+
* @param {any} store From openStore().
|
|
651
|
+
* @param {{days?: number, now?: number, site?: string}} [options]
|
|
652
|
+
*/
|
|
653
|
+
export async function insightsSources(store, { days = 30, now = Date.now(), site = '' } = {}) {
|
|
654
|
+
const [from, to, n] = period(now, days);
|
|
655
|
+
const [prevFrom, prevTo] = previous(from, n);
|
|
656
|
+
const counted = of(byKind(await store.sums(from, to, ['source'])), 'source');
|
|
657
|
+
const all = sourceRows(counted);
|
|
658
|
+
const total = all.reduce((s, r) => s + r.visits, 0);
|
|
659
|
+
const first = await firstDay(store);
|
|
660
|
+
const compare = compareWith(first, from, n);
|
|
661
|
+
const before = new Map(sourceRows(of(byKind(await store.sums(prevFrom, prevTo, ['source'])), 'source')).map((r) => [`${r.kind}|${r.name}`, r.visits]));
|
|
662
|
+
const kept = all.slice(0, TAB_ROWS);
|
|
663
|
+
|
|
664
|
+
const index = new Map(datesOf(from, n).map((d, i) => [d, i]));
|
|
665
|
+
/** @type {Map<string, number[]>} */
|
|
666
|
+
const series = new Map(kept.map((r) => [`${r.kind}|${r.name}`, Array(n).fill(0)]));
|
|
667
|
+
// The stored keys behind the kept rows.
|
|
668
|
+
const stored = [...counted.keys()].filter((key) => series.has(sourceKey(key)));
|
|
669
|
+
for (const r of await keyDays(store, 'source', from, to, stored)) {
|
|
670
|
+
const s = series.get(sourceKey(r.key));
|
|
671
|
+
const i = index.get(r.day);
|
|
672
|
+
if (s && i !== undefined) s[i] += Math.max(0, r.n);
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
const kinds = ARRIVALS.map((kind) => {
|
|
676
|
+
const list = all.filter((r) => r.kind === kind);
|
|
677
|
+
return { kind, sources: list.length, visits: list.reduce((s, r) => s + r.visits, 0) };
|
|
678
|
+
});
|
|
679
|
+
const rows = kept.map((r) => {
|
|
680
|
+
const key = `${r.kind}|${r.name}`;
|
|
681
|
+
const was = compare ? (before.get(key) ?? 0) : null;
|
|
682
|
+
return {
|
|
683
|
+
kind: r.kind,
|
|
684
|
+
name: r.name,
|
|
685
|
+
title: sourceTitle(r.kind, r.name),
|
|
686
|
+
visits: r.visits,
|
|
687
|
+
share: total ? round3(r.visits / total) : 0,
|
|
688
|
+
previous: was,
|
|
689
|
+
change: was === null ? null : r.visits - was,
|
|
690
|
+
new: was === 0,
|
|
691
|
+
daily: series.get(key),
|
|
692
|
+
};
|
|
693
|
+
});
|
|
694
|
+
|
|
695
|
+
return {
|
|
696
|
+
from,
|
|
697
|
+
to,
|
|
698
|
+
days: n,
|
|
699
|
+
compare,
|
|
700
|
+
sources: all.length,
|
|
701
|
+
visits: total,
|
|
702
|
+
kinds,
|
|
703
|
+
shown: rows.length,
|
|
704
|
+
capped: all.length > TAB_ROWS,
|
|
705
|
+
limit: TAB_ROWS,
|
|
706
|
+
rows,
|
|
707
|
+
...tabHeader(first, now, site),
|
|
708
|
+
warning: await limitWarning(store, from, to, now),
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/* ------------------------------------------------------------------ Speed (Speed/Metrics.php, Summary.php) */
|
|
713
|
+
|
|
714
|
+
/**
|
|
715
|
+
* Rating of the 75th percentile, exactly, from good, needs improvement and poor counts: good when at least 75% of the
|
|
716
|
+
* values are good, needs improvement when at least 75% are good or need improvement. '' without values.
|
|
717
|
+
* @param {number} good
|
|
718
|
+
* @param {number} ni
|
|
719
|
+
* @param {number} poor
|
|
720
|
+
*/
|
|
721
|
+
export function verdict(good, ni, poor) {
|
|
722
|
+
const n = good + ni + poor;
|
|
723
|
+
if (n <= 0) return '';
|
|
724
|
+
if (4 * good >= 3 * n) return 'good';
|
|
725
|
+
return 4 * (good + ni) >= 3 * n ? 'ni' : 'poor';
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/**
|
|
729
|
+
* The 75th percentile (nearest rank) from bucket counts, interpolated linearly inside its bucket. over: the value
|
|
730
|
+
* lies in the last, open bucket and is reported as its lower edge. Null without values.
|
|
731
|
+
* @param {string} metric
|
|
732
|
+
* @param {Map<number, number> | Record<number, number>} buckets
|
|
733
|
+
* @returns {{value: number, over: boolean, views: number} | null}
|
|
734
|
+
*/
|
|
735
|
+
export function p75(metric, buckets) {
|
|
736
|
+
const edges = EDGES[metric];
|
|
737
|
+
const last = edges.length;
|
|
738
|
+
/** @type {Map<number, number>} */
|
|
739
|
+
const clean = new Map();
|
|
740
|
+
let n = 0;
|
|
741
|
+
for (const [k, views] of buckets instanceof Map ? buckets : Object.entries(buckets)) {
|
|
742
|
+
const b = Number(k);
|
|
743
|
+
if (!Number.isInteger(b) || b < 0 || b > last || views <= 0) continue;
|
|
744
|
+
clean.set(b, (clean.get(b) ?? 0) + views);
|
|
745
|
+
n += views;
|
|
746
|
+
}
|
|
747
|
+
if (n === 0) return null;
|
|
748
|
+
const rank = Math.ceil(0.75 * n);
|
|
749
|
+
let before = 0;
|
|
750
|
+
for (const b of [...clean.keys()].sort((x, y) => x - y)) {
|
|
751
|
+
const views = /** @type {number} */ (clean.get(b));
|
|
752
|
+
if (before + views >= rank) {
|
|
753
|
+
if (b === last) return { value: edges[last - 1], over: true, views: n };
|
|
754
|
+
const lo = b === 0 ? 0 : edges[b - 1];
|
|
755
|
+
const hi = edges[b];
|
|
756
|
+
return { value: Math.round(lo + ((hi - lo) * (rank - before)) / views), over: false, views: n };
|
|
757
|
+
}
|
|
758
|
+
before += views;
|
|
759
|
+
}
|
|
760
|
+
return null;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
/**
|
|
764
|
+
* Core Web Vitals status of a page from its verdicts: fail when one of the three needs improvement or is poor, pass
|
|
765
|
+
* when LCP and CLS are good (INP needs an interaction), else unknown ("not assessed").
|
|
766
|
+
* @param {Record<string, string>} v
|
|
767
|
+
*/
|
|
768
|
+
export function status(v) {
|
|
769
|
+
for (const m of CORE) if (v[m] === 'ni' || v[m] === 'poor') return 'fail';
|
|
770
|
+
return v.lcp === 'good' && v.cls === 'good' ? 'pass' : 'unknown';
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/**
|
|
774
|
+
* The Speed check report for a range of days (Speed\Summary::build()).
|
|
775
|
+
* @param {{from: string, to: string, days: number, pages: Map<string, {kind: string, counts: Record<string, number>}>, kinds: Map<string, {views: number, img: number, text: number, video: number}>, hist: Map<string, Map<string, Map<number, number>>>}} data
|
|
776
|
+
* @param {number} [limit]
|
|
777
|
+
*/
|
|
778
|
+
export function speedSummary(data, limit = 25) {
|
|
779
|
+
const pages = [];
|
|
780
|
+
const tally = { pass: 0, fail: 0, unknown: 0 };
|
|
781
|
+
for (const [p, { kind, counts: c }] of data.pages) {
|
|
782
|
+
/** @type {Record<string, string>} */
|
|
783
|
+
const v = {};
|
|
784
|
+
for (const m of METRICS) v[m] = verdict(c[`${m}_good`] ?? 0, c[`${m}_ni`] ?? 0, c[`${m}_poor`] ?? 0);
|
|
785
|
+
const s = status(v);
|
|
786
|
+
tally[s]++;
|
|
787
|
+
pages.push({ path: p, kind, views: c.views ?? 0, status: s, lcp: v.lcp, inp: v.inp, cls: v.cls, ttfb: v.ttfb });
|
|
788
|
+
}
|
|
789
|
+
pages.sort((a, b) => b.views - a.views || cmp(a.path, b.path));
|
|
790
|
+
const kinds = [];
|
|
791
|
+
let views = 0;
|
|
792
|
+
for (const kind of PAGE_KINDS) {
|
|
793
|
+
const k = data.kinds.get(kind);
|
|
794
|
+
if (!k || !k.views) continue;
|
|
795
|
+
views += k.views;
|
|
796
|
+
/** @type {Record<string, object | null>} */
|
|
797
|
+
const metrics = {};
|
|
798
|
+
for (const m of METRICS) {
|
|
799
|
+
const p = p75(m, data.hist.get(kind)?.get(m) ?? new Map());
|
|
800
|
+
metrics[m] = p === null ? null : { p75: p.value, over: p.over, views: p.views, rating: rate(m, p.over ? p.value + 1 : p.value) };
|
|
801
|
+
}
|
|
802
|
+
kinds.push({ kind, views: k.views, metrics, lcp_elements: { img: k.img, text: k.text, video: k.video } });
|
|
803
|
+
}
|
|
804
|
+
return {
|
|
805
|
+
from: data.from,
|
|
806
|
+
to: data.to,
|
|
807
|
+
days: data.days,
|
|
808
|
+
views,
|
|
809
|
+
passing: { pages: pages.length, pass: tally.pass, fail: tally.fail, not_assessed: tally.unknown },
|
|
810
|
+
pages: pages.slice(0, limit),
|
|
811
|
+
kinds,
|
|
812
|
+
};
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
/**
|
|
816
|
+
* Speed totals of a period in speedSummary()'s input shape. A page's kind is the one most of its views had. Ratings of
|
|
817
|
+
* a path with no measured views that period (past the day's cap of keys) are left out.
|
|
818
|
+
* @param {Map<string, Map<string, number>>} t
|
|
819
|
+
*/
|
|
820
|
+
function speedData(t) {
|
|
821
|
+
/** @type {Map<string, Map<string, number>>} */
|
|
822
|
+
const kindsOf = new Map();
|
|
823
|
+
/** @type {Map<string, {views: number, img: number, text: number, video: number}>} */
|
|
824
|
+
const kinds = new Map();
|
|
825
|
+
for (const [key, n] of of(t, 'speed')) {
|
|
826
|
+
const i = key.indexOf('|');
|
|
827
|
+
const [kind, p] = i < 0 ? ['other', key] : [key.slice(0, i), key.slice(i + 1)];
|
|
828
|
+
if (!PAGE_KINDS.includes(kind)) continue;
|
|
829
|
+
if (!kindsOf.has(p)) kindsOf.set(p, new Map());
|
|
830
|
+
const m = /** @type {Map<string, number>} */ (kindsOf.get(p));
|
|
831
|
+
m.set(kind, (m.get(kind) ?? 0) + n);
|
|
832
|
+
if (!kinds.has(kind)) kinds.set(kind, { views: 0, img: 0, text: 0, video: 0 });
|
|
833
|
+
/** @type {any} */ (kinds.get(kind)).views += n;
|
|
834
|
+
}
|
|
835
|
+
for (const [key, n] of of(t, 'speed.element')) {
|
|
836
|
+
const [kind, e] = key.split('|');
|
|
837
|
+
const k = kinds.get(kind);
|
|
838
|
+
if (k && (e === 'img' || e === 'text' || e === 'video')) k[e] += n;
|
|
839
|
+
}
|
|
840
|
+
/** @type {Map<string, {kind: string, counts: Record<string, number>}>} */
|
|
841
|
+
const pages = new Map();
|
|
842
|
+
for (const [p, m] of kindsOf) {
|
|
843
|
+
let kind = '';
|
|
844
|
+
let most = -1;
|
|
845
|
+
let views = 0;
|
|
846
|
+
for (const k of PAGE_KINDS) {
|
|
847
|
+
const v = m.get(k) ?? 0;
|
|
848
|
+
views += v;
|
|
849
|
+
if (v > most) [kind, most] = [k, v];
|
|
850
|
+
}
|
|
851
|
+
/** @type {Record<string, number>} */
|
|
852
|
+
const counts = { views };
|
|
853
|
+
for (const metric of METRICS) for (const r of RATINGS) counts[`${metric}_${r}`] = of(t, `speed.${metric}.${r}`).get(p) ?? 0;
|
|
854
|
+
pages.set(p, { kind, counts });
|
|
855
|
+
}
|
|
856
|
+
/** @type {Map<string, Map<string, Map<number, number>>>} */
|
|
857
|
+
const hist = new Map();
|
|
858
|
+
for (const [key, n] of of(t, 'speed.hist')) {
|
|
859
|
+
const [kind, metric, b] = key.split('|');
|
|
860
|
+
if (!METRICS.includes(metric)) continue;
|
|
861
|
+
if (!hist.has(kind)) hist.set(kind, new Map());
|
|
862
|
+
const byMetric = /** @type {Map<string, Map<number, number>>} */ (hist.get(kind));
|
|
863
|
+
if (!byMetric.has(metric)) byMetric.set(metric, new Map());
|
|
864
|
+
const buckets = /** @type {Map<number, number>} */ (byMetric.get(metric));
|
|
865
|
+
buckets.set(Number(b), (buckets.get(Number(b)) ?? 0) + n);
|
|
866
|
+
}
|
|
867
|
+
return { pages, kinds, hist };
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
/* ------------------------------------------------------------------ Performance overview (Overview/Performance.php) */
|
|
871
|
+
|
|
872
|
+
/** Whether a page fails because one of the three is poor. @param {Record<string, string>} p */
|
|
873
|
+
const poor = (p) => CORE.some((m) => p[m] === 'poor');
|
|
874
|
+
|
|
875
|
+
/**
|
|
876
|
+
* One axis per kind of page for a measure: pages of that kind rated good, of those with a value.
|
|
877
|
+
* @param {ReturnType<typeof speedSummary>['pages']} pages
|
|
878
|
+
* @param {string} metric
|
|
879
|
+
*/
|
|
880
|
+
function kindAxes(pages, metric) {
|
|
881
|
+
/** @type {Map<string, Record<string, number>>} */
|
|
882
|
+
const tally = new Map();
|
|
883
|
+
for (const p of pages) {
|
|
884
|
+
const v = /** @type {any} */ (p)[metric];
|
|
885
|
+
if (!v) continue;
|
|
886
|
+
if (!tally.has(p.kind)) tally.set(p.kind, { good: 0, ni: 0, poor: 0 });
|
|
887
|
+
const t = /** @type {Record<string, number>} */ (tally.get(p.kind));
|
|
888
|
+
if (v in t) t[v]++;
|
|
889
|
+
}
|
|
890
|
+
const axes = [];
|
|
891
|
+
for (const kind of PAGE_KINDS) {
|
|
892
|
+
const t = tally.get(kind);
|
|
893
|
+
if (!t) continue;
|
|
894
|
+
let state = t.poor ? 'risk' : t.ni ? 'attention' : 'ok';
|
|
895
|
+
if (metric === 'ttfb' && state === 'risk') state = 'attention'; // Not a Core Web Vital.
|
|
896
|
+
axes.push(axis(kind, t.good, t.good + t.ni + t.poor, state));
|
|
897
|
+
}
|
|
898
|
+
return axes;
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
/** Rank of a kind of page in "What to do". @param {string} kind */
|
|
902
|
+
function kindRank(kind) {
|
|
903
|
+
if (kind === 'cart') return RANK.money;
|
|
904
|
+
if (kind === 'product') return RANK.product;
|
|
905
|
+
return kind === 'home' ? RANK.home : RANK.pages;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
/**
|
|
909
|
+
* Findings: each kind of page whose 75th percentile needs improvement or is poor.
|
|
910
|
+
* @param {ReturnType<typeof speedSummary>['kinds']} kinds
|
|
911
|
+
*/
|
|
912
|
+
function kindFindings(kinds) {
|
|
913
|
+
const out = [];
|
|
914
|
+
for (const k of kinds) {
|
|
915
|
+
for (const [area, metric] of Object.entries(MEASURES)) {
|
|
916
|
+
const m = /** @type {any} */ (k.metrics[metric]);
|
|
917
|
+
if (!m || m.rating === 'good') continue;
|
|
918
|
+
const state = m.rating === 'poor' && metric !== 'ttfb' ? 'risk' : 'attention';
|
|
919
|
+
out.push(finding(`speed.${metric}.${k.kind}`, area, state, { kind: k.kind, metric, p75: m.p75, over: m.over, rating: m.rating, good: THRESHOLDS[metric][0], views: m.views }, kindRank(k.kind) + Math.min(999999, k.views)));
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
return out;
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
/**
|
|
926
|
+
* The keys with the most total, most first, without '(other)' (keys past the daily cap).
|
|
927
|
+
* @param {Map<string, number>} m
|
|
928
|
+
* @param {number} max
|
|
929
|
+
*/
|
|
930
|
+
function most(m, max) {
|
|
931
|
+
return [...m].filter(([a]) => a !== '(other)').sort((x, y) => y[1] - x[1] || cmp(x[0], y[0])).slice(0, max);
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
/**
|
|
935
|
+
* Names for the addresses the page script sends: a file on this site by its file name (its path when two shown share
|
|
936
|
+
* a name, or when the last part has no dot, as a data call's), another site by its host, code in the page itself as
|
|
937
|
+
* "Code in the page", and waiting for the page's HTML as the site's own host.
|
|
938
|
+
* @param {string[]} shown The addresses shown together.
|
|
939
|
+
* @param {string} [site]
|
|
940
|
+
*/
|
|
941
|
+
function namer(shown, site = '') {
|
|
942
|
+
const file = (/** @type {string} */ a) => a.slice(a.lastIndexOf('/') + 1);
|
|
943
|
+
const own = (/** @type {string} */ a) => a.startsWith('/') && !a.startsWith('//');
|
|
944
|
+
/** @type {Map<string, number>} */
|
|
945
|
+
const seen = new Map();
|
|
946
|
+
for (const a of shown) if (own(a)) seen.set(file(a), (seen.get(file(a)) ?? 0) + 1);
|
|
947
|
+
return (/** @type {string} */ a) => {
|
|
948
|
+
if (a === 'inline') return 'Code in the page';
|
|
949
|
+
if (a === 'html') return site;
|
|
950
|
+
if (!own(a)) return a.slice(2);
|
|
951
|
+
const f = file(a);
|
|
952
|
+
return f.includes('.') && seen.get(f) === 1 ? f : a;
|
|
953
|
+
};
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/**
|
|
957
|
+
* "What slows your pages": script time per view for each script, the views where it ran in the slowest tap or click,
|
|
958
|
+
* and how many views could name scripts (Chrome and Edge) or not. Most total time first (Speed/Report.php order).
|
|
959
|
+
* Names: a file on this site by its file name (its path when two share a name), another site by its host, and code
|
|
960
|
+
* in the page itself as "Code in the page". Scripts past the daily cap ('(other)') are left out.
|
|
961
|
+
* @param {Map<string, Map<string, number>>} t
|
|
962
|
+
*/
|
|
963
|
+
export function slowScripts(t) {
|
|
964
|
+
const ms = of(t, 'script.ms');
|
|
965
|
+
const views = of(t, 'script.views');
|
|
966
|
+
const inp = of(t, 'script.inp');
|
|
967
|
+
const named = of(t, 'speed.named');
|
|
968
|
+
const top = most(ms, SLOW_ROWS);
|
|
969
|
+
const name = namer(top.map(([a]) => a));
|
|
970
|
+
return {
|
|
971
|
+
owners: top.map(([a, total]) => {
|
|
972
|
+
const per = Math.round(total / Math.max(1, views.get(a) ?? 0));
|
|
973
|
+
return { name: name(a), ms: per, inp: inp.get(a) ?? 0, views: views.get(a) ?? 0, hot: per >= SLOW_MS };
|
|
974
|
+
}),
|
|
975
|
+
attributed: named.get('1') ?? 0,
|
|
976
|
+
unattributed: named.get('0') ?? 0,
|
|
977
|
+
};
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
/**
|
|
981
|
+
* "What to do": scripts adding SLOW_MS or more of script time per view, at most three, most total time first
|
|
982
|
+
* (Overview/Performance.php script_findings()). The plugin's words say "Measured on N views in Chrome and Edge."
|
|
983
|
+
* @param {{name: string, ms: number, views: number}[]} owners slowScripts().owners
|
|
984
|
+
*/
|
|
985
|
+
export function scriptFindings(owners) {
|
|
986
|
+
return owners.filter((o) => o.ms >= SLOW_MS).slice(0, 3).map((o) =>
|
|
987
|
+
finding(`speed.script.${o.name}`, 'inp', 'attention', { name: o.name, ms: o.ms, views: o.views, file: '' }, RANK.scripts + Math.min(999999, o.ms * Math.max(1, o.views))));
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
/**
|
|
991
|
+
* The Performance overview.
|
|
992
|
+
* @param {any} store From openStore().
|
|
993
|
+
* @param {{days?: number, now?: number, site?: string}} [options] site: the site's name for the header.
|
|
994
|
+
*/
|
|
995
|
+
export async function performanceOverview(store, { days = 30, now = Date.now(), site = '' } = {}) {
|
|
996
|
+
const [from, to, n] = period(now, days);
|
|
997
|
+
const t = byKind(await store.sums(from, to, [...SPEED_KINDS, ...SLOW_KINDS]));
|
|
998
|
+
const slow = slowScripts(t);
|
|
999
|
+
const first = await firstDay(store);
|
|
1000
|
+
const report = speedSummary({ from, to, days: n, ...speedData(t) }, 5000);
|
|
1001
|
+
const pages = report.pages;
|
|
1002
|
+
const measured = report.views > 0;
|
|
1003
|
+
let risk = 0;
|
|
1004
|
+
for (const p of pages) if (p.status === 'fail' && poor(p)) risk++;
|
|
1005
|
+
risk = Math.min(risk, report.passing.fail);
|
|
1006
|
+
return {
|
|
1007
|
+
section: 'performance',
|
|
1008
|
+
days: n,
|
|
1009
|
+
modules: { speed: { on: true, since: dayStart(first) }, edge: { mode: 'off', host: '' } },
|
|
1010
|
+
warning: await limitWarning(store, from, to, now),
|
|
1011
|
+
visits: report.views,
|
|
1012
|
+
summary: { passed: report.passing.pass, total: report.passing.pages, attention: report.passing.fail - risk, risk, unknown: report.passing.not_assessed },
|
|
1013
|
+
parts: Object.entries(MEASURES).map(([id, metric]) => part(id, kindAxes(pages, metric))),
|
|
1014
|
+
pages: pages.slice(0, MAP_PAGES).map((p) => ({
|
|
1015
|
+
name: p.path,
|
|
1016
|
+
group: p.kind,
|
|
1017
|
+
state: p.status === 'pass' ? 'ok' : p.status === 'fail' ? (poor(p) ? 'risk' : 'attention') : 'unknown',
|
|
1018
|
+
views: p.views,
|
|
1019
|
+
lcp: p.lcp,
|
|
1020
|
+
inp: p.inp,
|
|
1021
|
+
cls: p.cls,
|
|
1022
|
+
})),
|
|
1023
|
+
slow,
|
|
1024
|
+
cache: { mode: 'off', host: '', rule: false, waiting_pages: 0, last_clear: null, problem: null },
|
|
1025
|
+
server: { caches: [], pagecache: false, offer: false, problem: null },
|
|
1026
|
+
measured,
|
|
1027
|
+
...finish([...kindFindings(report.kinds), ...scriptFindings(slow.owners)], measured),
|
|
1028
|
+
pro_installed: false,
|
|
1029
|
+
site,
|
|
1030
|
+
checked: Math.floor(now / 1000),
|
|
1031
|
+
};
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
/**
|
|
1035
|
+
* Performance > Deep dives, "Speed by kind of page" (the approved prototype's Mekko, check/design/build/app.jsx
|
|
1036
|
+
* PerformanceDeep): one part per kind of page with a page that can be judged, in PAGE_KINDS order. total is the
|
|
1037
|
+
* kind's measured page views; axes are its judged pages, each by its worst Core Web Vital, as on the overview's page
|
|
1038
|
+
* map. left: pages with too few views to judge.
|
|
1039
|
+
* @param {any} store From openStore().
|
|
1040
|
+
* @param {{days?: number, now?: number, site?: string}} [options]
|
|
1041
|
+
*/
|
|
1042
|
+
export async function performanceKinds(store, { days = 30, now = Date.now(), site = '' } = {}) {
|
|
1043
|
+
const [from, to, n] = period(now, days);
|
|
1044
|
+
const t = byKind(await store.sums(from, to, SPEED_KINDS));
|
|
1045
|
+
const pages = speedSummary({ from, to, days: n, ...speedData(t) }, 5000).pages;
|
|
1046
|
+
const state = (/** @type {any} */ p) => (p.status === 'pass' ? 'ok' : poor(p) ? 'risk' : 'attention');
|
|
1047
|
+
const parts = PAGE_KINDS.map((kind) => {
|
|
1048
|
+
const list = pages.filter((p) => p.kind === kind);
|
|
1049
|
+
const judged = list.filter((p) => p.status === 'pass' || p.status === 'fail');
|
|
1050
|
+
return { id: kind, total: list.reduce((s, p) => s + p.views, 0), axes: judged.map((p) => ({ id: p.path, state: state(p) })) };
|
|
1051
|
+
}).filter((p) => p.axes.length);
|
|
1052
|
+
const left = pages.filter((p) => p.status !== 'pass' && p.status !== 'fail').length;
|
|
1053
|
+
const d = byKind(await store.sums(from, to, DEEP_KINDS));
|
|
1054
|
+
return { from, to, days: n, parts, left, load: loadTime(d, site), server: serverTime(d), warning: await limitWarning(store, from, to, now), site, checked: Math.floor(now / 1000) };
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
/**
|
|
1058
|
+
* "Load time by file" (the prototype's LoadTimePanel): for each kind of page with views that measured it, the average
|
|
1059
|
+
* LCP time and the 5 files or hosts with the most time before it, as an average per view and a share of the LCP time.
|
|
1060
|
+
* Orange marks 500 ms or more. requests: the views measured, all kinds.
|
|
1061
|
+
* @param {Map<string, Map<string, number>>} t
|
|
1062
|
+
* @param {string} site
|
|
1063
|
+
*/
|
|
1064
|
+
export function loadTime(t, site) {
|
|
1065
|
+
const lcp = of(t, 'load.lcp');
|
|
1066
|
+
const n = of(t, 'load.n');
|
|
1067
|
+
/** @type {Map<string, Map<string, number>>} */
|
|
1068
|
+
const files = new Map();
|
|
1069
|
+
for (const [key, ms] of of(t, 'load.ms')) {
|
|
1070
|
+
const i = key.indexOf('|');
|
|
1071
|
+
const kind = key.slice(0, i);
|
|
1072
|
+
if (!files.has(kind)) files.set(kind, new Map());
|
|
1073
|
+
/** @type {Map<string, number>} */ (files.get(kind)).set(key.slice(i + 1), ms);
|
|
1074
|
+
}
|
|
1075
|
+
const kinds = PAGE_KINDS.filter((k) => (n.get(k) ?? 0) > 0).map((kind) => {
|
|
1076
|
+
const views = /** @type {number} */ (n.get(kind));
|
|
1077
|
+
const ms = Math.round((lcp.get(kind) ?? 0) / views);
|
|
1078
|
+
const top = most(files.get(kind) ?? new Map(), LOAD_ROWS);
|
|
1079
|
+
const name = namer(top.map(([a]) => a), site);
|
|
1080
|
+
return {
|
|
1081
|
+
kind,
|
|
1082
|
+
ms,
|
|
1083
|
+
requests: views,
|
|
1084
|
+
owners: top.map(([a, total]) => {
|
|
1085
|
+
const per = Math.round(total / views);
|
|
1086
|
+
return { name: name(a), note: a === 'html' ? 'HTML' : '', ms: per, share: ms ? per / ms : 0, hot: per >= LOAD_HOT_MS };
|
|
1087
|
+
}),
|
|
1088
|
+
};
|
|
1089
|
+
});
|
|
1090
|
+
return { requests: kinds.reduce((s, k) => s + k.requests, 0), kinds };
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
/**
|
|
1094
|
+
* "Server response by page" (the prototype's ServerTimePanel): pages by time to first byte, and data calls by how long
|
|
1095
|
+
* they take: the 6 with the most total time (so a page seen once cannot top the list), slowest average first. A kind
|
|
1096
|
+
* with nothing measured is left out.
|
|
1097
|
+
* @param {Map<string, Map<string, number>>} t
|
|
1098
|
+
*/
|
|
1099
|
+
export function serverTime(t) {
|
|
1100
|
+
const kinds = [];
|
|
1101
|
+
for (const [kind, label, msKind, nKind] of [['pages', 'Pages', 'ttfb.ms', 'ttfb.n'], ['data', 'Data calls', 'call.ms', 'call.n']]) {
|
|
1102
|
+
const ms = of(t, msKind);
|
|
1103
|
+
const n = of(t, nKind);
|
|
1104
|
+
const calls = [...n.values()].reduce((s, x) => s + x, 0);
|
|
1105
|
+
if (!calls) continue;
|
|
1106
|
+
const rows = most(ms, SERVER_ROWS).map(([a, total]) => {
|
|
1107
|
+
const avg = Math.round(total / Math.max(1, n.get(a) ?? 0));
|
|
1108
|
+
if (kind === 'data' && a.startsWith('//')) {
|
|
1109
|
+
const i = a.indexOf('/', 2);
|
|
1110
|
+
return i < 0 ? { name: a.slice(2), ms: avg } : { name: a.slice(i), note: a.slice(2, i), ms: avg };
|
|
1111
|
+
}
|
|
1112
|
+
return { name: a, ms: avg };
|
|
1113
|
+
}).sort((x, y) => y.ms - x.ms);
|
|
1114
|
+
kinds.push({ kind, label, ms: Math.round([...ms.values()].reduce((s, x) => s + x, 0) / calls), requests: calls, rows });
|
|
1115
|
+
}
|
|
1116
|
+
return { kinds };
|
|
1117
|
+
}
|