@jonandev/longbeard 0.11.2 → 0.12.1

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.
Files changed (94) hide show
  1. package/AGENTS.md +4 -5
  2. package/CHANGELOG.md +72 -0
  3. package/README.md +64 -43
  4. package/beard.json +124 -28
  5. package/bin/long-beard.js +171 -36
  6. package/package.json +1 -1
  7. package/skills/design/SKILL.md +51 -126
  8. package/skills/design-brief/SKILL.md +146 -0
  9. package/skills/design-brief/references/graphic.md +59 -0
  10. package/skills/design-check/SKILL.md +27 -11
  11. package/skills/design-check/references/design-rules.md +21 -7
  12. package/skills/design-check/scripts/capture.mjs +121 -37
  13. package/skills/design-check/scripts/contrast.mjs +23 -9
  14. package/skills/design-check/scripts/rules.mjs +613 -0
  15. package/skills/design-check/scripts/screen-contrast.mjs +428 -0
  16. package/skills/design-check/scripts/tokens.mjs +346 -0
  17. package/skills/design-content/SKILL.md +118 -0
  18. package/skills/design-content/scripts/contact-sheet.mjs +259 -0
  19. package/skills/design-content/scripts/pictures.mjs +197 -0
  20. package/skills/design-direction/SKILL.md +115 -200
  21. package/skills/design-direction/references/controls.md +58 -0
  22. package/skills/{design → design-direction}/references/design-rules.md +21 -7
  23. package/skills/design-direction/references/five-second.md +47 -0
  24. package/skills/design-direction/references/full-build.md +19 -0
  25. package/skills/design-direction/references/graphic.md +35 -0
  26. package/skills/design-direction/references/grid.md +114 -0
  27. package/skills/design-direction/references/library.md +75 -0
  28. package/skills/design-direction/references/screen-template.html +233 -0
  29. package/skills/design-direction/references/subject.md +33 -0
  30. package/skills/design-direction/scripts/capture.mjs +121 -37
  31. package/skills/design-direction/scripts/contact-sheet.mjs +18 -7
  32. package/skills/design-direction/scripts/fonts.mjs +276 -0
  33. package/skills/design-direction/scripts/layout-diff.mjs +118 -0
  34. package/skills/design-direction/scripts/measure.mjs +1728 -0
  35. package/skills/design-direction/scripts/moodboard.mjs +123 -32
  36. package/skills/design-direction/scripts/picture-cast.mjs +270 -0
  37. package/skills/design-direction/scripts/pictures.mjs +197 -0
  38. package/skills/design-direction/scripts/screen-contrast.mjs +428 -0
  39. package/skills/design-direction/scripts/sheet.mjs +67 -0
  40. package/skills/design-direction/scripts/subject-colours.mjs +410 -0
  41. package/skills/design-families/SKILL.md +138 -0
  42. package/skills/design-families/scripts/contact-sheet.mjs +259 -0
  43. package/skills/design-families/scripts/families.mjs +606 -0
  44. package/skills/design-families/scripts/measure.mjs +1728 -0
  45. package/skills/design-families/scripts/moodboard.mjs +467 -0
  46. package/skills/design-families/scripts/tag.mjs +289 -0
  47. package/skills/design-figma/SKILL.md +69 -0
  48. package/skills/design-figma/references/graphic.md +26 -0
  49. package/skills/design-identity/SKILL.md +134 -0
  50. package/skills/design-identity/references/graphic.md +8 -0
  51. package/skills/design-identity/references/identity-board.html +140 -0
  52. package/skills/{design → design-identity}/scripts/capture.mjs +121 -37
  53. package/skills/design-identity/scripts/colours.mjs +213 -0
  54. package/skills/design-identity/scripts/contrast.mjs +41 -0
  55. package/skills/design-identity/scripts/fonts.mjs +276 -0
  56. package/skills/design-identity/scripts/measure.mjs +1728 -0
  57. package/skills/design-identity/scripts/sheet.mjs +67 -0
  58. package/skills/design-identity/scripts/subject-colours.mjs +410 -0
  59. package/skills/design-moodboard/SKILL.md +184 -0
  60. package/skills/design-moodboard/references/graphic.md +25 -0
  61. package/skills/{design-direction → design-moodboard}/references/sources.md +21 -11
  62. package/skills/design-moodboard/scripts/capture.mjs +893 -0
  63. package/skills/design-moodboard/scripts/contact-sheet.mjs +259 -0
  64. package/skills/design-moodboard/scripts/crops.mjs +256 -0
  65. package/skills/design-moodboard/scripts/dribbble-cards.mjs +418 -0
  66. package/skills/design-moodboard/scripts/families.mjs +606 -0
  67. package/skills/design-moodboard/scripts/group.mjs +221 -0
  68. package/skills/design-moodboard/scripts/measure.mjs +1728 -0
  69. package/skills/design-moodboard/scripts/moodboard.mjs +467 -0
  70. package/skills/{design-direction → design-moodboard}/scripts/picker.mjs +121 -20
  71. package/skills/design-moodboard/scripts/pictures.mjs +197 -0
  72. package/skills/design-moodboard/scripts/tag.mjs +289 -0
  73. package/skills/design-prototype/SKILL.md +149 -0
  74. package/skills/design-prototype/references/design-md-template.md +82 -0
  75. package/skills/design-prototype/references/design-rules.md +203 -0
  76. package/skills/design-prototype/references/five-second.md +47 -0
  77. package/skills/design-prototype/references/graphic.md +27 -0
  78. package/skills/design-prototype/scripts/capture.mjs +893 -0
  79. package/skills/design-prototype/scripts/contrast.mjs +41 -0
  80. package/skills/design-prototype/scripts/links.mjs +308 -0
  81. package/skills/design-prototype/scripts/pictures.mjs +197 -0
  82. package/skills/design-prototype/scripts/rules.mjs +613 -0
  83. package/skills/design-prototype/scripts/screen-contrast.mjs +428 -0
  84. package/skills/design-prototype/scripts/sheet.mjs +67 -0
  85. package/skills/design-prototype/scripts/tokens.mjs +346 -0
  86. package/skills/design-wordmark/SKILL.md +65 -0
  87. package/skills/design-wordmark/scripts/capture.mjs +893 -0
  88. package/skills/design-wordmark/scripts/sheet.mjs +67 -0
  89. package/skills/framework-skills/SKILL.md +71 -0
  90. package/skills/idea/SKILL.md +13 -7
  91. package/skills/idea/references/graphic.md +64 -0
  92. package/skills/design/references/design-md-template.md +0 -58
  93. package/skills/design/scripts/contrast.mjs +0 -27
  94. package/skills/design-direction/scripts/dribbble-cards.mjs +0 -356
@@ -0,0 +1,1728 @@
1
+ #!/usr/bin/env node
2
+ // Read a reference's real numbers, so the library records what is there and
3
+ // nothing is judged by eye. Prints JSON. Node 22+, an installed Chrome.
4
+ //
5
+ // An image: its most common colours and its loud ones, each with its share of
6
+ // the picture, and its traits: how light the ground is, how much of the
7
+ // picture is that ground (empty), and how much is loud colour. A screen shown
8
+ // on a plain grey or black surround (a presentation frame) is read inside the
9
+ // frame, and "frame" names the surround and the box that was read.
10
+ // node measure.mjs .longbeard/design/moodboard/refs/name.jpg
11
+ //
12
+ // A live page: its ground colour, the fonts it loaded, and every piece of text
13
+ // on the first screen with its face, size, weight, style, tracking, case,
14
+ // colour and box, plus the boxes of its pictures and panels, the gradients it
15
+ // uses as written, and its traits: the type scale (largest text over the most
16
+ // common size), how much of the first screen is pictures and how much is
17
+ // gradient, where the largest text sits (centre, left, right), the left
18
+ // margin, and the corner radius in use. Animations that end are read at their end. A page that
19
+ // is not the real site (an error status, a maintenance or bot-check page, nothing on it) is
20
+ // flagged with the reason, in "flag": families.mjs leaves its numbers out.
21
+ //
22
+ // A live page also lists its motion and its finish, read from what the page states. "motion" is
23
+ // read before any animation is ended: each transition and animation (property, ms, delay, easing,
24
+ // once or loop, what it is on, how many times it is used), the twelve most used, with its trigger:
25
+ // load, scroll (animation-timeline), hover (a :hover rule that changes the property), or state
26
+ // when no readable rule says. "finish" is what shows on the first screen, each value with the
27
+ // share of the screen its elements cover: shadow, textShadow, filter, backdrop, blend and
28
+ // texture (an feTurbulence filter, or a small picture tiled over a quarter of the screen or
29
+ // more), six of each at most, with "finishMore" saying how many it left out. "motionMore" does the
30
+ // same for the motion. Motion a script makes is listed too, as kind "script": a Web Animation (its
31
+ // keyframed properties, time and easing as the page set them), and a value a script writes frame
32
+ // by frame, seen by watching for about 1.2 s: it has no time and no easing ("not seen", frames
33
+ // give no curve). The watch has two parts, at load and while the page is scrolled one screen in
34
+ // three steps (the scroll position is put back); a sticky or fixed thing is listed only when it
35
+ // changes its transform, opacity, clip-path or filter. A canvas or a video that is playing is
36
+ // listed with its cover of the first screen and nothing else. "unread" counts the stylesheets the
37
+ // page does not allow reading (another origin) and the canvases whose pixels it does not allow
38
+ // reading: nothing is guessed from them, so a hover rule in one reads as "state". Not read: a
39
+ // hover that is set up in script, a script that moves things only after a click, motion that has
40
+ // ended before the page was read, and texture inside a picture file. Neither is in --tsv; both
41
+ // are in the profile's page.
42
+ //
43
+ // Traits are what families are sorted by and what a family shares, so every
44
+ // keep is measured the same way before anyone judges it by eye.
45
+ // node measure.mjs https://example.com
46
+ // node measure.mjs https://example.com --wait 9000 --width 390
47
+ //
48
+ // Many at once, in one browser: images are read one after another in one
49
+ // page, live pages in up to --jobs tabs at a time. A folder means every image
50
+ // in it. --tsv prints one row of numbers per reference, with a header, which
51
+ // is what families.mjs reads and costs far fewer tokens than the JSON.
52
+ // node measure.mjs .longbeard/design/moodboard/refs --tsv > .longbeard/design/<step>/traits.tsv
53
+ // node measure.mjs refs/a.jpg refs/b.png https://example.com --jobs 4 --tsv
54
+ //
55
+ // --swatches: images only. The colours a picture is made of, for a palette
56
+ // drawn from the product's own subject (subject-colours.mjs reads it). Each
57
+ // picture is read at 240 px on its long side, the centre counting more than
58
+ // the corners (the subject is usually in the middle), and its pixels are
59
+ // grouped into ten colours in OKLab, the same way every time. Each colour has
60
+ // its hex, OKLCH lightness (0 to 1), chroma and hue, its share of the
61
+ // picture in %, heaviest first, and its edge: how much of it lies in the outer
62
+ // fifth of the picture on any side (0 to 1). A colour that is mostly edge is
63
+ // a backdrop, a cloth or a wall, not the subject. Prints [{ target, swatches }]
64
+ // as JSON.
65
+ // node measure.mjs .longbeard/design/subject --swatches
66
+ import { spawn } from "node:child_process";
67
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
68
+ import { tmpdir } from "node:os";
69
+ import { basename, dirname, extname, join, resolve } from "node:path";
70
+
71
+ const args = process.argv.slice(2);
72
+ const flag = (name, def) => {
73
+ const i = args.indexOf(`--${name}`);
74
+ if (i === -1) return def;
75
+ return args.splice(i, 2)[1];
76
+ };
77
+ const has = (name) => {
78
+ const i = args.indexOf(`--${name}`);
79
+ if (i === -1) return false;
80
+ args.splice(i, 1);
81
+ return true;
82
+ };
83
+ const width = Math.round(Number(flag("width", "1440")));
84
+ const waitArg = flag("wait", "");
85
+ const jobs = Math.round(Number(flag("jobs", "4")));
86
+ const tsv = has("tsv");
87
+ const swatches = has("swatches");
88
+ const allLines = has("lines");
89
+ const linksArg = flag("links", "");
90
+ const profilesArg = flag("profiles", "");
91
+ const mime = { ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".webp": "image/webp", ".gif": "image/gif", ".avif": "image/avif" };
92
+ const isUrl = (t) => /^(https?|file):\/\//.test(t);
93
+ const usage = "usage: node measure.mjs <https://url | image | folder> … [--tsv | --links links.tsv --profiles profiles.json] [--jobs 4] [--wait ms] [--width 1440]";
94
+ if (!args.length) {
95
+ console.error(usage);
96
+ process.exit(2);
97
+ }
98
+ const targets = [];
99
+ // A frame stands for its folder: its profile is named after the folder, not the frame.
100
+ const names = new Map();
101
+ for (const arg of args) {
102
+ if (isUrl(arg)) targets.push(arg);
103
+ else if (existsSync(arg) && statSync(arg).isDirectory()) {
104
+ for (const f of readdirSync(arg).sort()) {
105
+ const path = join(arg, f);
106
+ if (mime[extname(f).toLowerCase()]) targets.push(path);
107
+ // A keep that only moves is a folder of frames (capture.mjs --frames): its middle frame stands for it.
108
+ else if (statSync(path).isDirectory()) {
109
+ const frames = readdirSync(path).filter((x) => mime[extname(x).toLowerCase()]).sort();
110
+ if (!frames.length) continue;
111
+ const shot = join(path, frames[Math.floor(frames.length / 2)]);
112
+ names.set(shot, f);
113
+ targets.push(shot);
114
+ }
115
+ }
116
+ } else if (mime[extname(arg).toLowerCase()]) {
117
+ if (!existsSync(arg)) {
118
+ console.error(`measure: no file at ${arg}`);
119
+ process.exit(1);
120
+ }
121
+ targets.push(arg);
122
+ } else {
123
+ console.error(usage);
124
+ process.exit(2);
125
+ }
126
+ }
127
+ // Profiles: each picture, its live page (from --links, name<TAB>link), into one JSON per exploration.
128
+ const nameOf = (path) => names.get(path) || basename(path, extname(path));
129
+ const links = new Map();
130
+ if (linksArg) {
131
+ if (!existsSync(linksArg)) {
132
+ console.error(`measure: no links at ${linksArg}`);
133
+ process.exit(1);
134
+ }
135
+ for (const l of readFileSync(linksArg, "utf8").split(/\r?\n/)) {
136
+ const [name, link] = l.split("\t").map((x) => (x || "").trim());
137
+ // A name may hold a dot (acme.com): only an image's own extension is taken off.
138
+ if (name && /^https?:\/\//.test(link || "")) links.set(mime[extname(name).toLowerCase()] ? nameOf(name) : name, link);
139
+ }
140
+ for (const t of [...targets]) if (!isUrl(t) && links.has(nameOf(t)) && !targets.includes(links.get(nameOf(t)))) targets.push(links.get(nameOf(t)));
141
+ }
142
+ if (profilesArg && tsv) {
143
+ console.error("measure: --profiles and --tsv are two outputs: pick one");
144
+ process.exit(2);
145
+ }
146
+ if (swatches && (tsv || profilesArg || targets.some(isUrl))) {
147
+ console.error("measure: --swatches reads images only, and prints JSON: no links, --tsv or --profiles");
148
+ process.exit(2);
149
+ }
150
+ if (!targets.length) {
151
+ console.error("measure: no images or links to measure");
152
+ process.exit(1);
153
+ }
154
+ const wait = waitArg === "" ? 6000 : Number(waitArg);
155
+ if (!Number.isFinite(wait) || wait < 0 || wait > 120000 || !Number.isFinite(width) || width < 200 || width > 3840 || !(jobs >= 1 && jobs <= 8)) {
156
+ console.error("wait must be ms from 0 to 120000, width from 200 to 3840, jobs from 1 to 8");
157
+ process.exit(2);
158
+ }
159
+ const height = width < 768 ? 844 : 900;
160
+
161
+ function findChrome() {
162
+ const env = process.env.CHROME_PATH;
163
+ // CHROME_PATH=none: run as if no browser were installed (a quick test run).
164
+ if (env === "none") return null;
165
+ if (env && existsSync(env)) return env;
166
+ const home = process.env.HOME || process.env.USERPROFILE || "";
167
+ const local = process.env.LOCALAPPDATA || "";
168
+ const pf = process.env.PROGRAMFILES || "C:\\Program Files";
169
+ const pf86 = process.env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)";
170
+ const candidates = [
171
+ join(pf, "Google/Chrome/Application/chrome.exe"),
172
+ join(pf86, "Google/Chrome/Application/chrome.exe"),
173
+ join(local, "Google/Chrome/Application/chrome.exe"),
174
+ join(pf, "Microsoft/Edge/Application/msedge.exe"),
175
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
176
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
177
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
178
+ join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
179
+ "/usr/bin/google-chrome",
180
+ "/usr/bin/google-chrome-stable",
181
+ "/usr/bin/chromium",
182
+ "/usr/bin/chromium-browser",
183
+ ];
184
+ return candidates.find((path) => path && existsSync(path)) || null;
185
+ }
186
+
187
+ const exe = findChrome();
188
+ if (!exe) {
189
+ console.error("No Chrome/Edge/Chromium found. Install one or set CHROME_PATH.");
190
+ process.exit(1);
191
+ }
192
+ if (typeof WebSocket === "undefined") {
193
+ console.error("Node 22+ is required.");
194
+ process.exit(1);
195
+ }
196
+
197
+ const dir = mkdtempSync(join(tmpdir(), "measure-chrome-"));
198
+ let proc;
199
+ const drop = () => {
200
+ try {
201
+ if (proc?.pid) process.kill(proc.pid, "SIGKILL");
202
+ } catch {}
203
+ try {
204
+ rmSync(dir, { recursive: true, force: true });
205
+ } catch {}
206
+ };
207
+ process.once("exit", drop);
208
+ // An interrupt or a harness timeout must not leave Chrome or its profile behind.
209
+ for (const [sig, code] of [["SIGINT", 130], ["SIGTERM", 143]]) {
210
+ process.once(sig, () => {
211
+ drop();
212
+ process.exit(code);
213
+ });
214
+ }
215
+
216
+ // One browser for every reference. Each tab is a session on one socket.
217
+ // Several tabs work at once, so no tab may be slowed for not being in front: a picture decoding in a
218
+ // tab behind another would otherwise wait for ever.
219
+ proc = spawn(
220
+ exe,
221
+ ["--headless=new", "--remote-debugging-port=0", `--user-data-dir=${dir}`, "--no-first-run", "--hide-scrollbars", "--mute-audio", "--force-color-profile=srgb", "--disable-renderer-backgrounding", "--disable-background-timer-throttling", "--disable-backgrounding-occluded-windows", `--window-size=${width},${height}`, "about:blank"],
222
+ { stdio: ["ignore", "ignore", "pipe"] },
223
+ );
224
+ proc.on("error", (e) => {
225
+ console.error(`measure: could not start ${exe}: ${e.message}`);
226
+ process.exit(1);
227
+ });
228
+ let buf = "";
229
+ const wsUrl = await new Promise((done, fail) => {
230
+ const t = setTimeout(() => fail(new Error("Chrome did not start")), 20000);
231
+ proc.stderr.on("data", (d) => {
232
+ buf += d.toString();
233
+ const m = buf.match(/DevTools listening on (ws:\/\/[^\s]+)/);
234
+ if (m) {
235
+ clearTimeout(t);
236
+ done(m[1]);
237
+ }
238
+ });
239
+ proc.on("exit", (code) => {
240
+ clearTimeout(t);
241
+ fail(new Error(`Chrome exited ${code}`));
242
+ });
243
+ });
244
+ const ws = new WebSocket(wsUrl);
245
+ await new Promise((done, fail) => {
246
+ const t = setTimeout(() => fail(new Error("CDP socket did not open")), 10000);
247
+ ws.onopen = () => {
248
+ clearTimeout(t);
249
+ done();
250
+ };
251
+ ws.onerror = () => {
252
+ clearTimeout(t);
253
+ fail(new Error("CDP socket failed"));
254
+ };
255
+ });
256
+ let nextId = 0;
257
+ const pending = new Map();
258
+ ws.onmessage = (ev) => {
259
+ const msg = JSON.parse(typeof ev.data === "string" ? ev.data : Buffer.from(ev.data).toString());
260
+ // An alert, confirm or beforeunload prompt holds the page until it is answered.
261
+ if (msg.method === "Page.javascriptDialogOpening") send("Page.handleJavaScriptDialog", { accept: false }, msg.sessionId).catch(() => {});
262
+ if (msg.id && pending.has(msg.id)) {
263
+ pending.get(msg.id)(msg);
264
+ pending.delete(msg.id);
265
+ }
266
+ };
267
+ // If Chrome goes away, every call waiting on it fails now, not at its time limit.
268
+ ws.onclose = () => {
269
+ for (const done of [...pending.values()]) done({ error: { message: "Chrome closed the connection" } });
270
+ pending.clear();
271
+ };
272
+ // Every call has a time limit: a page that hangs fails its own reference, not the run.
273
+ const send = (method, params = {}, sessionId, timeoutMs = 30000) =>
274
+ new Promise((done, fail) => {
275
+ const id = ++nextId;
276
+ const timer = setTimeout(() => {
277
+ pending.delete(id);
278
+ fail(new Error(`Chrome did not answer ${method} in ${timeoutMs / 1000} s`));
279
+ }, timeoutMs);
280
+ pending.set(id, (msg) => {
281
+ clearTimeout(timer);
282
+ done(msg);
283
+ });
284
+ try {
285
+ ws.send(JSON.stringify(sessionId ? { id, method, params, sessionId } : { id, method, params }));
286
+ } catch (e) {
287
+ clearTimeout(timer);
288
+ pending.delete(id);
289
+ fail(e);
290
+ }
291
+ });
292
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
293
+
294
+ async function openTab() {
295
+ const { result } = await send("Target.createTarget", { url: "about:blank" });
296
+ const { result: attached } = await send("Target.attachToTarget", { targetId: result.targetId, flatten: true });
297
+ const sid = attached.sessionId;
298
+ const call = (method, params, timeoutMs) => send(method, params, sid, timeoutMs);
299
+ const evaluate = async (expression) => {
300
+ const reply = await call("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true }, 60000);
301
+ if (reply.error) throw new Error(reply.error.message);
302
+ if (reply.result?.exceptionDetails) throw new Error(reply.result.exceptionDetails.exception?.description || "the page threw");
303
+ return reply.result.result.value;
304
+ };
305
+ await call("Emulation.setDeviceMetricsOverride", { width, height, deviceScaleFactor: 1, mobile: width < 768 });
306
+ await call("Page.enable");
307
+ // A tab behind another is hidden and draws no frames, so a page's own frame loop would stand
308
+ // still while it is watched: every tab is made to count as shown and focused.
309
+ await call("Emulation.setFocusEmulationEnabled", { enabled: true });
310
+ return { call, evaluate };
311
+ }
312
+
313
+ // Colours are binned sixteen steps a channel. "Loud" is saturated and at least 0.4% of the picture.
314
+ // The type in a picture, read from its pixels, for a reference that is only an image. Letters are
315
+ // marks on the ground that are two-tone (ink, ground and the blend between), not too full of their
316
+ // box, and set in lines. Photographs are many-toned or fill their box, so they are left out; text
317
+ // set on a photograph is lost with it. Each line gives its size against the screen, its stroke (the
318
+ // weight), its stroke contrast, its width, its x-height and its case, and its ink. Runs in the page.
319
+ // d: RGBA pixels, w × h, ground: [r, g, b]. Sizes are px of this read; the caller scales them.
320
+ // With an ink instead (a colour set over a photograph, where there is no ground to blend with),
321
+ // the letters are the marks of that colour.
322
+ function readType(d, w, h, ground, inkOnly) {
323
+ const n = w * h, far = new Float32Array(n), label = new Int32Array(n).fill(-1);
324
+ const base = inkOnly || ground;
325
+ for (let i = 0; i < n; i++) {
326
+ const dist = Math.max(Math.abs(d[4 * i] - base[0]), Math.abs(d[4 * i + 1] - base[1]), Math.abs(d[4 * i + 2] - base[2]));
327
+ // Ink mode: near the ink is a mark (far is high); ground mode: far from the ground is.
328
+ far[i] = inkOnly ? (dist < 40 ? 255 - dist : 0) : dist;
329
+ }
330
+ // Marks: 8-connected runs of pixels well off the ground.
331
+ const comps = [], stack = new Int32Array(n);
332
+ for (let s = 0; s < n; s++) {
333
+ if (label[s] >= 0 || far[s] <= 40) continue;
334
+ const id = comps.length;
335
+ let top = 0, x0 = w, y0 = h, x1 = 0, y1 = 0, count = 0;
336
+ stack[top++] = s;
337
+ label[s] = id;
338
+ while (top) {
339
+ const p = stack[--top], x = p % w, y = (p - x) / w;
340
+ count++;
341
+ if (x < x0) x0 = x;
342
+ if (x > x1) x1 = x;
343
+ if (y < y0) y0 = y;
344
+ if (y > y1) y1 = y;
345
+ for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
346
+ const X = x + dx, Y = y + dy;
347
+ if (X < 0 || Y < 0 || X >= w || Y >= h) continue;
348
+ const q = Y * w + X;
349
+ if (label[q] < 0 && far[q] > 40) (label[q] = id), (stack[top++] = q);
350
+ }
351
+ }
352
+ comps.push({ id, x0, y0, x1, y1, count });
353
+ }
354
+ // Pictures: big marks that fill their box. On a ground, nothing inside one is a letter (light
355
+ // spots in a photograph make letter-sized shapes); an ink set over one is read in ink mode.
356
+ const pictures = inkOnly ? [] : comps.filter((c) => (c.x1 - c.x0 + 1) * (c.y1 - c.y0 + 1) > 0.02 * n && c.count > 0.5 * (c.x1 - c.x0 + 1) * (c.y1 - c.y0 + 1));
357
+ // And photographs that break into many marks: cells of 12 px that are nearly all off the ground
358
+ // and hold many colours. Type is two-tone: its cells are part ground, or one flat colour inside a stroke.
359
+ const S = 12, cw = Math.ceil(w / S), ch = Math.ceil(h / S), photo = new Uint8Array(cw * ch), pictured = new Uint8Array(cw * ch);
360
+ if (!inkOnly) for (let cy = 0; cy < ch; cy++) for (let cx = 0; cx < cw; cx++) {
361
+ let off = 0, all = 0;
362
+ const bins = new Set();
363
+ for (let y = cy * S; y < Math.min(h, cy * S + S); y++) for (let x = cx * S; x < Math.min(w, cx * S + S); x++) {
364
+ const i = y * w + x;
365
+ all++;
366
+ if (far[i] > 40) off++, bins.add(((d[4 * i] >> 5) << 6) | ((d[4 * i + 1] >> 5) << 3) | (d[4 * i + 2] >> 5));
367
+ }
368
+ photo[cy * cw + cx] = off > 0.9 * all && bins.size >= 6 ? 1 : 0;
369
+ // For the share, a looser cut: a flat-toned stretch of photograph (a sweater, a sky) still counts.
370
+ pictured[cy * cw + cx] = off > 0.9 * all && bins.size >= 3 ? 1 : 0;
371
+ }
372
+ const onPhoto = (c) => {
373
+ let on = 0, all = 0;
374
+ for (let cy = Math.floor(c.y0 / S); cy <= Math.floor(c.y1 / S); cy++) for (let cx = Math.floor(c.x0 / S); cx <= Math.floor(c.x1 / S); cx++) all++, (on += photo[cy * cw + cx]);
375
+ return on > 0.3 * all;
376
+ };
377
+ const pictureIds = new Set(pictures.map((p) => p.id));
378
+ // Inside a picture: most of the ring just outside the mark's box is that picture's pixels.
379
+ const inPicture = (c) => {
380
+ if (!inkOnly && onPhoto(c)) return true;
381
+ // A letter on a ground has ground around it: most of the ring just outside its box.
382
+ if (!inkOnly) {
383
+ let bare = 0, all = 0;
384
+ const X0 = Math.max(0, c.x0 - 2), X1 = Math.min(w - 1, c.x1 + 2), Y0 = Math.max(0, c.y0 - 2), Y1 = Math.min(h - 1, c.y1 + 2);
385
+ for (let x = X0; x <= X1; x++) for (const y of [Y0, Y1]) all++, (bare += far[y * w + x] <= 40);
386
+ for (let y = Y0; y <= Y1; y++) for (const x of [X0, X1]) all++, (bare += far[y * w + x] <= 40);
387
+ if (bare < 0.6 * all) return true;
388
+ }
389
+ if (!pictureIds.size || pictureIds.has(c.id)) return false;
390
+ let on = 0, all = 0;
391
+ const X0 = Math.max(0, c.x0 - 2), X1 = Math.min(w - 1, c.x1 + 2), Y0 = Math.max(0, c.y0 - 2), Y1 = Math.min(h - 1, c.y1 + 2);
392
+ for (let x = X0; x <= X1; x++) for (const y of [Y0, Y1]) all++, (on += pictureIds.has(label[y * w + x]));
393
+ for (let y = Y0; y <= Y1; y++) for (const x of [X0, X1]) all++, (on += pictureIds.has(label[y * w + x]));
394
+ return on > 0.5 * all;
395
+ };
396
+ // A letter: two-tone, not a solid block, a sensible shape. Its core colour is its ink.
397
+ const letters = [];
398
+ for (const c of comps) {
399
+ const bw = c.x1 - c.x0 + 1, bh = c.y1 - c.y0 + 1, fill = c.count / (bw * bh);
400
+ if (bh < 5 || bh > 0.45 * h || c.count < 8 || fill > 0.8 || bw / bh > 6 || bh / bw > 12 || inPicture(c)) continue;
401
+ const px = [];
402
+ for (let y = c.y0; y <= c.y1; y++) for (let x = c.x0; x <= c.x1; x++) if (label[y * w + x] === c.id) px.push(y * w + x);
403
+ let ink, tOf;
404
+ if (inkOnly) {
405
+ ink = inkOnly;
406
+ tOf = () => 1;
407
+ } else {
408
+ px.sort((a, b) => far[b] - far[a]);
409
+ const core = px.slice(0, Math.max(1, Math.ceil(px.length * 0.3)));
410
+ ink = [0, 1, 2].map((j) => core.reduce((t, p) => t + d[4 * p + j], 0) / core.length);
411
+ const seg = ink.map((v, j) => v - ground[j]), len2 = seg.reduce((t, v) => t + v * v, 0) || 1;
412
+ let onSeg = 0;
413
+ tOf = (p) => Math.max(0, Math.min(1, [0, 1, 2].reduce((t, j) => t + (d[4 * p + j] - ground[j]) * seg[j], 0) / len2));
414
+ for (const p of px) {
415
+ const t = tOf(p);
416
+ const off = Math.max(...[0, 1, 2].map((j) => Math.abs(d[4 * p + j] - (ground[j] + t * seg[j]))));
417
+ if (off < 34) onSeg++;
418
+ }
419
+ if (onSeg / px.length < 0.8) continue;
420
+ }
421
+ // Strokes: runs of ink (past half way from ground to ink) across and down the letter.
422
+ const across = [], down = [];
423
+ const inked = (x, y) => label[y * w + x] === c.id && tOf(y * w + x) >= 0.5;
424
+ for (let y = c.y0; y <= c.y1; y++) for (let x = c.x0, run = 0; x <= c.x1 + 1; x++) {
425
+ if (x <= c.x1 && inked(x, y)) run++;
426
+ else if (run) across.push(run), (run = 0);
427
+ }
428
+ for (let x = c.x0; x <= c.x1; x++) for (let y = c.y0, run = 0; y <= c.y1 + 1; y++) {
429
+ if (y <= c.y1 && inked(x, y)) run++;
430
+ else if (run) down.push(run), (run = 0);
431
+ }
432
+ // In ink mode, a letter has strokes of one steady width: hair, fur and texture do not.
433
+ if (inkOnly) {
434
+ const q = (xs, f) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length * f)] || 0;
435
+ if (q(across, 0.5) < Math.max(3, 0.03 * bh)) continue;
436
+ }
437
+ let area = 0;
438
+ for (const p of px) area += tOf(p);
439
+ letters.push({ ...c, bw, bh, ink, across, down, area });
440
+ }
441
+ // Lines: letters side by side that share most of their height.
442
+ letters.sort((a, b) => a.x0 - b.x0);
443
+ const parent = letters.map((_, i) => i);
444
+ const root = (i) => (parent[i] === i ? i : (parent[i] = root(parent[i])));
445
+ for (let i = 0; i < letters.length; i++) for (let j = i + 1; j < letters.length; j++) {
446
+ const a = letters[i], b = letters[j], big = Math.max(a.bh, b.bh);
447
+ if (b.x0 - a.x1 > 1.4 * big) continue;
448
+ const overlap = Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0);
449
+ // Short letters (x, o) sit inside a tall one's height; a line holds both.
450
+ if (overlap < 0.45 * Math.min(a.bh, b.bh) || Math.min(a.bh, b.bh) < 0.3 * big) continue;
451
+ if (Math.abs(a.y1 - b.y1) > 0.35 * big && Math.abs(a.y0 - b.y0) > 0.35 * big) continue;
452
+ parent[root(j)] = root(i);
453
+ }
454
+ const groups = new Map();
455
+ letters.forEach((l, i) => groups.set(root(i), [...(groups.get(root(i)) || []), l]));
456
+ const median = (xs) => { const s = [...xs].sort((a, b) => a - b); return s.length ? s[Math.floor(s.length / 2)] : 0; };
457
+ const quart = (xs, q) => { const s = [...xs].sort((a, b) => a - b); return s.length ? s[Math.floor(s.length * q)] : 0; };
458
+ const hex = (v) => "#" + v.map((x) => Math.round(x).toString(16).padStart(2, "0")).join("");
459
+ const lines = [];
460
+ for (const ls of groups.values()) {
461
+ // Two letters make a line only when they are big and of one height (SO over LA); three always.
462
+ if (ls.length < 2 || (ls.length === 2 && (Math.min(ls[0].bh, ls[1].bh) < 0.85 * Math.max(ls[0].bh, ls[1].bh) || ls[0].bh < 0.1 * h))) continue;
463
+ const hs = ls.map((l) => l.bh);
464
+ const cap = quart(hs, 0.8);
465
+ const shortOnes = hs.filter((x) => x < 0.82 * cap);
466
+ const caps = shortOnes.length < 0.25 * ls.length;
467
+ const xh = caps ? cap : median(shortOnes);
468
+ // The em: caps are about 0.7 of it; with lowercase, the x-height about 0.5 and the caps 0.7.
469
+ const em = cap / 0.7;
470
+ const x0 = Math.min(...ls.map((l) => l.x0)), x1 = Math.max(...ls.map((l) => l.x1));
471
+ const y0 = Math.min(...ls.map((l) => l.y0)), y1 = Math.max(...ls.map((l) => l.y1));
472
+ const stem = median(ls.flatMap((l) => l.across));
473
+ const thin = quart(ls.flatMap((l) => l.down), 0.25);
474
+ // Words: gaps between letters wider than a third of the em.
475
+ let words = 1;
476
+ for (let i = 1; i < ls.length; i++) if (ls[i].x0 - Math.max(...ls.slice(0, i).map((l) => l.x1)) > 0.22 * em) words++;
477
+ const ink = [0, 1, 2].map((j) => median(ls.map((l) => l.ink[j])));
478
+ // Text stands off its ground; marks under 2.5:1 on it are a photograph's greys, not type.
479
+ if (!inkOnly) {
480
+ const lin = (v) => ((v /= 255) <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);
481
+ const L = (c) => 0.2126 * lin(c[0]) + 0.7152 * lin(c[1]) + 0.0722 * lin(c[2]);
482
+ const [hi, lo] = [L(ink), L(ground)].sort((a, b) => b - a);
483
+ if ((hi + 0.05) / (lo + 0.05) < 2.5) continue;
484
+ }
485
+ lines.push({
486
+ box: [x0, y0, x1 - x0 + 1, y1 - y0 + 1], letters: ls.length, words, cap, em,
487
+ stroke: stem / em, contrast: thin ? stem / thin : null, width: (x1 - x0 + 1) / ls.length / em,
488
+ xheight: caps ? null : xh / em, case: caps ? "uppercase" : "mixed",
489
+ dark: ls.reduce((t, l) => t + l.area, 0) / ((x1 - x0 + 1) * em), ink: hex(ink), pass: inkOnly ? "ink" : "ground",
490
+ });
491
+ }
492
+ // How much of the picture is photograph, read on the main ground: its share of cells.
493
+ lines.photo = inkOnly ? null : Math.round((1000 * pictured.reduce((t, v) => t + v, 0)) / pictured.length) / 10;
494
+ return lines;
495
+ }
496
+
497
+ // The type reading, said against the screen: the largest line (the display) and the size most of
498
+ // the small text is set in (the body), each as a share of the screen's height and as px at 1440
499
+ // wide; the weight, from the stroke; how many text blocks there are, and how many words and lines
500
+ // the headline holds, which is how much text the composition is made to carry.
501
+ // passes: the lines read on each ground and each ink; a line two passes found is kept once.
502
+ function typeOf(passes, w, h) {
503
+ const median = (xs) => { const s = [...xs].sort((a, b) => a - b); return s.length ? s[Math.floor(s.length / 2)] : 0; };
504
+ const lines = [];
505
+ const overlap = (a, b) => Math.max(0, Math.min(a[0] + a[2], b[0] + b[2]) - Math.max(a[0], b[0])) * Math.max(0, Math.min(a[1] + a[3], b[1] + b[3]) - Math.max(a[1], b[1]));
506
+ for (const l of passes.flat().sort((a, b) => b.letters - a.letters)) {
507
+ if (!lines.some((m) => overlap(l.box, m.box) > 0.5 * Math.min(l.box[2] * l.box[3], m.box[2] * m.box[3]))) lines.push(l);
508
+ }
509
+ // Blocks: lines of one size stacked close, the way a paragraph or a two-line headline is set.
510
+ lines.sort((a, b) => a.box[1] - b.box[1]);
511
+ const blocks = [];
512
+ for (const l of lines) {
513
+ const b = blocks.find((k) => {
514
+ const last = k.lines.at(-1);
515
+ const gap = l.box[1] - (last.box[1] + last.box[3]);
516
+ // A line of x-height letters reads smaller than one with capitals: 0.4 keeps a paragraph whole.
517
+ const same = Math.abs(Math.log(l.em / last.em)) < 0.4;
518
+ const beside = Math.min(l.box[0] + l.box[2], last.box[0] + last.box[2]) - Math.max(l.box[0], last.box[0]) > -0.5 * l.em;
519
+ return same && beside && gap < 1.2 * l.em && gap > -0.2 * l.em;
520
+ });
521
+ if (b) b.lines.push(l);
522
+ else blocks.push({ lines: [l] });
523
+ }
524
+ const blockList = blocks.map((b) => ({ lines: b.lines.length, em: median(b.lines.map((l) => l.em)), words: b.lines.reduce((t, l) => t + l.words, 0), box: [Math.min(...b.lines.map((l) => l.box[0])), b.lines[0].box[1], Math.max(...b.lines.map((l) => l.box[0] + l.box[2])) - Math.min(...b.lines.map((l) => l.box[0])), b.lines.at(-1).box[1] + b.lines.at(-1).box[3] - b.lines[0].box[1]] }));
525
+ return summary(lines, blockList, w, h);
526
+ }
527
+ function summary(lines, blocks, w, h) {
528
+ if (!lines.length) return { lines: 0, blocks: 0, note: "no lines of type found: text set on a photograph, rotated or in a script face is not read" };
529
+ // Stroke over em to a CSS weight, fitted on faces set at known weights: a 300 reads 0.05 to 0.07,
530
+ // a 400 0.08 to 0.095, a 700 0.13 to 0.15, a 900 0.19 and up. Lines under 40 px of this read have
531
+ // strokes of two or three pixels, thickened by antialiasing, so their weight is not given.
532
+ const weightOf = (l) => (l.em < 40 ? null : [[0.045, 100], [0.052, 200], [0.075, 300], [0.1, 400], [0.118, 500], [0.132, 600], [0.165, 700], [0.185, 800], [9, 900]].find(([s]) => l.stroke < s)[1]);
533
+ const r = (v, k = 100) => (v == null ? null : Math.round(v * k) / k);
534
+ const show = (l) => ({ size: r(l.em / h, 1000), px1440: Math.round((l.em * 1440) / w), weight: weightOf(l), stroke: r(l.stroke, 1000), contrast: r(l.contrast), width: r(l.width), xheight: r(l.xheight), case: l.case, dark: r(l.dark), ink: l.ink, box: l.box.map((v, i) => Math.round((1000 * v) / (i % 2 ? h : w)) / 1000), letters: l.letters, pass: l.pass });
535
+ const display = lines.reduce((a, b) => (b.em > a.em ? b : a));
536
+ // The body: of the lines under 0.6 of the display, the size that holds the most letters.
537
+ const small = lines.filter((l) => l.em < 0.6 * display.em);
538
+ let body = null, most = 0;
539
+ for (const l of small) {
540
+ const near = small.filter((m) => Math.abs(Math.log(m.em / l.em)) < 0.15).reduce((t, m) => t + m.letters, 0);
541
+ if (near > most) (most = near), (body = l);
542
+ }
543
+ const inks = {};
544
+ // Big letters give the truest colour: small ones never reach their ink for antialiasing.
545
+ for (const l of lines) inks[l.ink] = (inks[l.ink] || 0) + l.letters * l.em * l.em;
546
+ const head = blocks.find((b) => b.em >= 0.9 * display.em) || blocks[0];
547
+ return {
548
+ lines: ALL_LINES ? lines.map(show) : lines.length,
549
+ display: show(display),
550
+ body: body ? show(body) : null,
551
+ scale: body ? r(display.em / body.em, 10) : null,
552
+ ink: Object.entries(inks).sort((a, b) => b[1] - a[1])[0][0],
553
+ headline: { words: head.words, lines: head.lines },
554
+ blocks: blocks.length,
555
+ small: blocks.filter((b) => b.em < 0.6 * display.em).length,
556
+ };
557
+ }
558
+ const readImage = (src) => `(async () => {
559
+ const ALL_LINES = ${allLines};
560
+ // The load event, not decode(): decode() waits on the tab's rendering, which stops for a tab behind
561
+ // another, so a picture read while a page is measured in a second tab never answered.
562
+ const img = new Image();
563
+ await new Promise((done, fail) => {
564
+ img.onload = done;
565
+ img.onerror = () => fail(new Error("The source image cannot be decoded."));
566
+ img.src = ${JSON.stringify(src)};
567
+ });
568
+ // Transparent pixels are read as on white, the ground a cut-out sits on, never as black.
569
+ const paint = (ctx, cw, ch) => { ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, cw, ch); };
570
+ // Only the first screen: a tall desktop capture (a full page) is cut to the 1440 by 900 it opens on.
571
+ // A desktop capture is 1300 px wide or more; from 1000 to 1300 only a near-landscape shot is one.
572
+ // A retina phone (1170 by 2532) or a portrait poster (1080 by 1350) is read whole. A framed
573
+ // presentation shot is found on the whole picture first, so a cut never takes its bottom margin.
574
+ let sw = img.naturalWidth, sh = img.naturalHeight;
575
+ const fullPage = sh > sw * 0.75 && (sw >= 1300 || (sw >= 1000 && sh <= sw * 1.2));
576
+ // A presentation shot: the screen on a plain grey or black surround (a Dribbble frame, a device
577
+ // on a backdrop). Its ground, tone and empty would describe the surround, so the screen inside
578
+ // is what is read. A surround is one low-colour tone on all four sides, and the screen inside is
579
+ // a solid rectangle: its edge rows differ from the surround almost everywhere. A centred logo on
580
+ // an empty page has sparse edges and is never taken for a frame.
581
+ let sx = 0, sy = 0, frame = null;
582
+ {
583
+ const fk = Math.min(1, 300 / Math.max(sw, sh));
584
+ const fw = Math.max(1, Math.round(sw * fk)), fh = Math.max(1, Math.round(sh * fk));
585
+ const fc = Object.assign(document.createElement("canvas"), { width: fw, height: fh }).getContext("2d");
586
+ paint(fc, fw, fh);
587
+ fc.drawImage(img, 0, 0, sw, sh, 0, 0, fw, fh);
588
+ const p = fc.getImageData(0, 0, fw, fh).data, at = (x, y) => (y * fw + x) * 4;
589
+ const ref = [p[0], p[1], p[2]];
590
+ const same = (i) => Math.abs(p[i] - ref[0]) <= 12 && Math.abs(p[i + 1] - ref[1]) <= 12 && Math.abs(p[i + 2] - ref[2]) <= 12;
591
+ const corners = [at(fw - 1, 0), at(0, fh - 1), at(fw - 1, fh - 1)].every(same);
592
+ const lowColour = Math.max(...ref) - Math.min(...ref) <= 24;
593
+ const rowSame = (y) => { let n = 0; for (let x = 0; x < fw; x++) n += same(at(x, y)); return n / fw; };
594
+ const colSame = (x) => { let n = 0; for (let y = 0; y < fh; y++) n += same(at(x, y)); return n / fh; };
595
+ if (corners && lowColour) {
596
+ let t = 0, b = fh - 1, l = 0, r = fw - 1;
597
+ while (t < fh / 2 && rowSame(t) > 0.98) t++;
598
+ while (b > fh / 2 && rowSame(b) > 0.98) b--;
599
+ while (l < fw / 2 && colSame(l) > 0.98) l++;
600
+ while (r > fw / 2 && colSame(r) > 0.98) r--;
601
+ const iw = r - l + 1, ih = b - t + 1;
602
+ const edge = (xs, ys) => { let n = 0, m = 0; for (const y of ys) for (const x of xs) { m++; n += !same(at(x, y)); } return m ? n / m : 0; };
603
+ const span = (a, z) => Array.from({ length: Math.max(0, z - a + 1) }, (_, i) => a + i);
604
+ const solid = Math.min(edge(span(l, r), [t]), edge(span(l, r), [b]), edge([l], span(t, b)), edge([r], span(t, b)));
605
+ const margins = [t / fh, (fh - 1 - b) / fh, l / fw, (fw - 1 - r) / fw];
606
+ if (margins.every((m) => m >= 0.03) && iw * ih >= 0.25 * fw * fh && iw * ih <= 0.95 * fw * fh && solid >= 0.85) {
607
+ sx = Math.round(l / fk); sy = Math.round(t / fk); sw = Math.round(iw / fk); sh = Math.round(ih / fk);
608
+ frame = { colour: "#" + ref.map((v) => v.toString(16).padStart(2, "0")).join(""), box: [sx, sy, sw, sh] };
609
+ }
610
+ }
611
+ }
612
+ if (!frame && fullPage) sh = Math.round((sw * 900) / 1440);
613
+ const k = Math.min(1, 200 / Math.max(sw, sh));
614
+ const w = Math.max(1, Math.round(sw * k)), h = Math.max(1, Math.round(sh * k));
615
+ const c = Object.assign(document.createElement("canvas"), { width: w, height: h }).getContext("2d");
616
+ paint(c, w, h);
617
+ c.drawImage(img, sx, sy, sw, sh, 0, 0, w, h);
618
+ const d = c.getImageData(0, 0, w, h).data, bins = new Map();
619
+ for (let i = 0; i < d.length; i += 4) {
620
+ const key = (d[i] >> 4) << 8 | (d[i + 1] >> 4) << 4 | (d[i + 2] >> 4);
621
+ const b = bins.get(key) || [0, 0, 0, 0];
622
+ b[0]++; b[1] += d[i]; b[2] += d[i + 1]; b[3] += d[i + 2];
623
+ bins.set(key, b);
624
+ }
625
+ const n = d.length / 4;
626
+ const hex = (b) => "#" + [1, 2, 3].map((j) => Math.round(b[j] / b[0]).toString(16).padStart(2, "0")).join("");
627
+ const sat = (b) => { const v = [1, 2, 3].map((j) => b[j] / b[0]); return (Math.max(...v) - Math.min(...v)) / 255; };
628
+ const row = (b) => ({ colour: hex(b), share: Math.round((1000 * b[0]) / n) / 10 });
629
+ const all = [...bins.values()].sort((a, b) => b[0] - a[0]);
630
+ const avg = (b) => [1, 2, 3].map((j) => b[j] / b[0]);
631
+ const lum = (v) => { const c = v.map((x) => x / 255).map((x) => (x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4)); return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; };
632
+ const top = avg(all[0]);
633
+ const near = (b) => avg(b).every((x, j) => Math.abs(x - top[j]) <= 24);
634
+ const pct = (count) => Math.round((1000 * count) / n) / 10;
635
+ const l = lum(top);
636
+ // Busy: how much changes from one pixel to the next, on the small copy. Flat
637
+ // grounds and big shapes are low; small type, texture and photographs are high.
638
+ let edges = 0;
639
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
640
+ const i = (y * w + x) * 4, g = 0.3 * d[i] + 0.59 * d[i + 1] + 0.11 * d[i + 2];
641
+ const r = x + 1 < w ? i + 4 : i, b = y + 1 < h ? i + 4 * w : i;
642
+ edges += Math.abs(g - (0.3 * d[r] + 0.59 * d[r + 1] + 0.11 * d[r + 2])) + Math.abs(g - (0.3 * d[b] + 0.59 * d[b + 1] + 0.11 * d[b + 2]));
643
+ }
644
+ // The figure: everything that is not the ground, read again at 400 px so texture survives.
645
+ // What the picture is shows here: a photograph has many colours and fine texture, a flat
646
+ // illustration few colours and hard edges, a 3D render many colours and soft surfaces,
647
+ // chrome mostly grey with sharp highlights, lettering two colours and long hard edges.
648
+ const k2 = Math.min(1, 400 / Math.max(sw, sh));
649
+ const w2 = Math.max(1, Math.round(sw * k2)), h2 = Math.max(1, Math.round(sh * k2));
650
+ const c2 = Object.assign(document.createElement("canvas"), { width: w2, height: h2 }).getContext("2d");
651
+ paint(c2, w2, h2);
652
+ c2.drawImage(img, sx, sy, sw, sh, 0, 0, w2, h2);
653
+ const e = c2.getImageData(0, 0, w2, h2).data;
654
+ const isFig = (i) => Math.max(Math.abs(e[i] - top[0]), Math.abs(e[i + 1] - top[1]), Math.abs(e[i + 2] - top[2])) > 24;
655
+ const lumOf = (i) => 0.3 * e[i] + 0.59 * e[i + 1] + 0.11 * e[i + 2];
656
+ const COLS = 6, ROWS = 4, grid = new Array(COLS * ROWS).fill(0), cell = new Array(COLS * ROWS).fill(0);
657
+ const fbins = new Map();
658
+ let F = 0, grey = 0, flat = 0, soft = 0, sharp = 0, tex = 0, srg = 0, syb = 0, srg2 = 0, syb2 = 0;
659
+ for (let y = 0; y < h2; y++) for (let x = 0; x < w2; x++) {
660
+ const i = (y * w2 + x) * 4, g = Math.min(COLS - 1, Math.floor((x * COLS) / w2)) + COLS * Math.min(ROWS - 1, Math.floor((y * ROWS) / h2));
661
+ cell[g]++;
662
+ if (!isFig(i)) continue;
663
+ F++; grid[g]++;
664
+ const key = (e[i] >> 4) << 8 | (e[i + 1] >> 4) << 4 | (e[i + 2] >> 4);
665
+ fbins.set(key, (fbins.get(key) || 0) + 1);
666
+ const mx = Math.max(e[i], e[i + 1], e[i + 2]), mn = Math.min(e[i], e[i + 1], e[i + 2]);
667
+ if (mx - mn < 0.12 * 255) grey++;
668
+ const rg = e[i] - e[i + 1], yb = 0.5 * (e[i] + e[i + 1]) - e[i + 2];
669
+ srg += rg; syb += yb; srg2 += rg * rg; syb2 += yb * yb;
670
+ const r = x + 1 < w2 ? i + 4 : i, b = y + 1 < h2 ? i + 4 * w2 : i;
671
+ const diff = Math.max(Math.abs(lumOf(i) - lumOf(r)), Math.abs(lumOf(i) - lumOf(b)));
672
+ tex += diff;
673
+ if (diff <= 2) flat++; else if (diff <= 10) soft++; else sharp++;
674
+ }
675
+ const share = (v) => (F ? Math.round((1000 * v) / F) / 10 : 0);
676
+ const fsorted = [...fbins.entries()].sort((a, b) => b[1] - a[1]);
677
+ let covered = 0, colours = 0;
678
+ for (const [, count] of fsorted) { if (covered >= 0.9 * F) break; covered += count; colours++; }
679
+ const mrg = F ? srg / F : 0, myb = F ? syb / F : 0;
680
+ const colourful = F ? Math.sqrt(Math.max(0, srg2 / F - mrg * mrg) + Math.max(0, syb2 / F - myb * myb)) + 0.3 * Math.sqrt(mrg * mrg + myb * myb) : 0;
681
+ const binHex = (key) => "#" + [(key >> 8) & 15, (key >> 4) & 15, key & 15].map((v) => (v * 17).toString(16).padStart(2, "0")).join("");
682
+ const figure = {
683
+ share: Math.round((1000 * F) / (w2 * h2)) / 10,
684
+ colours,
685
+ colourful: Math.round(colourful),
686
+ grey: share(grey),
687
+ flat: share(flat),
688
+ soft: share(soft),
689
+ sharp: share(sharp),
690
+ texture: F ? Math.round((10 * tex) / F) / 10 : 0,
691
+ palette: fsorted.slice(0, 5).map(([key, count]) => ({ colour: binHex(key), share: share(count) })),
692
+ grid: grid.map((v, g) => Math.round((100 * v) / Math.max(1, cell[g]))),
693
+ };
694
+ const traits = {
695
+ ground: hex(all[0]),
696
+ tone: l > 0.6 ? "light" : l < 0.12 ? "dark" : "mid",
697
+ empty: pct(all.filter(near).reduce((t, b) => t + b[0], 0)),
698
+ loud: pct(all.filter((b) => sat(b) > 0.5).reduce((t, b) => t + b[0], 0)),
699
+ busy: Math.round((10 * edges) / (2 * n * 2.55)) / 10,
700
+ lum: Math.round(l * 1000) / 1000,
701
+ };
702
+ // The type, read at up to 2000 px on the long side so a body line keeps strokes to measure.
703
+ const k3 = Math.min(1, 2000 / Math.max(sw, sh));
704
+ const w3 = Math.max(1, Math.round(sw * k3)), h3 = Math.max(1, Math.round(sh * k3));
705
+ const c3 = Object.assign(document.createElement("canvas"), { width: w3, height: h3 }).getContext("2d", { willReadFrequently: true });
706
+ paint(c3, w3, h3);
707
+ c3.drawImage(img, sx, sy, sw, sh, 0, 0, w3, h3);
708
+ // Read against each main colour (the ground, a card, a panel) and each loud colour as an ink.
709
+ const px3 = c3.getImageData(0, 0, w3, h3).data;
710
+ const readType = ${readType.toString()};
711
+ const differ = (a, b) => Math.max(...a.map((v, j) => Math.abs(v - b[j]))) > 40;
712
+ const grounds = [];
713
+ // A card or a panel is flat: its pixels' neighbours are its colour too. A colour common in a
714
+ // photograph (a sweater, a sky) is not, and is never read as a ground.
715
+ const flatGround = (g) => {
716
+ const near = (i) => Math.max(Math.abs(d[i] - g[0]), Math.abs(d[i + 1] - g[1]), Math.abs(d[i + 2] - g[2])) <= 12;
717
+ let on = 0, same = 0;
718
+ for (let y = 0; y + 1 < h; y++) for (let x = 0; x + 1 < w; x++) {
719
+ const i = (y * w + x) * 4;
720
+ if (!near(i)) continue;
721
+ on++;
722
+ same += near(i + 4) && near(i + 4 * w);
723
+ }
724
+ return on && same / on >= 0.85;
725
+ };
726
+ for (const b of all) if (b[0] / n >= 0.06 && grounds.length < 3 && grounds.every((g) => differ(g, avg(b))) && (!grounds.length || flatGround(avg(b)))) grounds.push(avg(b).map(Math.round));
727
+ // A loud ground can be an ink too: lime panels and lime letters over a photograph.
728
+ const inks = [];
729
+ for (const b of all) if (sat(b) > 0.4 && b[0] / n > 0.004 && inks.length < 2 && inks.every((k) => differ(k, avg(b)))) inks.push(avg(b).map(Math.round));
730
+ const onGrounds = grounds.map((g) => readType(px3, w3, h3, g));
731
+ const type = typeOf([...onGrounds, ...inks.map((k) => readType(px3, w3, h3, null, k))], w3, h3);
732
+ if (type.ink) traits.ink = type.ink;
733
+ if (onGrounds[0]) traits.pictures = onGrounds[0].photo;
734
+ return { width: img.naturalWidth, height: img.naturalHeight, firstScreen: !frame && sh < img.naturalHeight, ...(frame ? { frame } : {}), traits, type, figure, common: all.slice(0, 6).map(row), loud: all.filter((b) => sat(b) > 0.5 && b[0] / n > 0.004).slice(0, 4).map(row) };
735
+ ${typeOf.toString()}
736
+ ${summary.toString()}
737
+ })()`;
738
+
739
+ // Swatches: the whole picture at 240 px on its long side, its pixels handed back as base64 RGBA.
740
+ const readPixels = (src) => `(async () => {
741
+ // The load event, not decode(): decode() waits on the tab's rendering, which stops for a tab behind
742
+ // another, so a picture read while a page is measured in a second tab never answered.
743
+ const img = new Image();
744
+ await new Promise((done, fail) => {
745
+ img.onload = done;
746
+ img.onerror = () => fail(new Error("The source image cannot be decoded."));
747
+ img.src = ${JSON.stringify(src)};
748
+ });
749
+ const k = Math.min(1, 240 / Math.max(img.naturalWidth, img.naturalHeight));
750
+ const w = Math.max(1, Math.round(img.naturalWidth * k)), h = Math.max(1, Math.round(img.naturalHeight * k));
751
+ const c = Object.assign(document.createElement("canvas"), { width: w, height: h }).getContext("2d");
752
+ c.drawImage(img, 0, 0, w, h);
753
+ const d = c.getImageData(0, 0, w, h).data;
754
+ let s = "";
755
+ for (let i = 0; i < d.length; i += 0x8000) s += String.fromCharCode.apply(null, d.subarray(i, i + 0x8000));
756
+ return { width: img.naturalWidth, height: img.naturalHeight, w, h, data: btoa(s) };
757
+ })()`;
758
+
759
+ // sRGB to OKLab and back, for the swatches.
760
+ const toLin = (c) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
761
+ const toGam = (c) => (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055);
762
+ function labOf(r8, g8, b8) {
763
+ const [r, g, b] = [r8, g8, b8].map((v) => toLin(v / 255));
764
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
765
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
766
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
767
+ return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s];
768
+ }
769
+ function hexOfLab([L, a, b]) {
770
+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;
771
+ const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;
772
+ const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;
773
+ const rgb = [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s];
774
+ return `#${rgb.map((c) => Math.round(Math.min(1, Math.max(0, toGam(Math.min(1, Math.max(0, c))))) * 255).toString(16).padStart(2, "0")).join("")}`;
775
+ }
776
+ // Ten colours by k-means in OKLab. Pixels are first pooled into 32 steps a channel. The first
777
+ // centre is the heaviest pool; each next one the pool farthest from every centre so far, among
778
+ // pools of at least 0.05% of the weight, so a stray pixel never takes a centre. Twelve rounds.
779
+ async function measureSwatches(tab, path) {
780
+ const src = `data:${mime[extname(path).toLowerCase()]};base64,${readFileSync(resolve(path)).toString("base64")}`;
781
+ const { width: W, height: H, w, h, data } = await tab.evaluate(readPixels(src));
782
+ const d = Buffer.from(data, "base64");
783
+ const pools = new Map();
784
+ const cx = (w - 1) / 2, cy = (h - 1) / 2;
785
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
786
+ const i = (y * w + x) * 4;
787
+ if (d[i + 3] < 128) continue;
788
+ // 1 at the centre, 0.3 at the corners.
789
+ const r = Math.hypot((x - cx) / Math.max(1, cx), (y - cy) / Math.max(1, cy)) / Math.SQRT2;
790
+ const weight = 1 - 0.7 * r;
791
+ const key = (d[i] >> 3) << 10 | (d[i + 1] >> 3) << 5 | (d[i + 2] >> 3);
792
+ const p = pools.get(key) || { w: 0, r: 0, g: 0, b: 0, e: 0 };
793
+ p.w += weight; p.r += weight * d[i]; p.g += weight * d[i + 1]; p.b += weight * d[i + 2];
794
+ if (x < 0.2 * w || x >= 0.8 * w || y < 0.2 * h || y >= 0.8 * h) p.e += weight;
795
+ pools.set(key, p);
796
+ }
797
+ const points = [...pools.entries()].sort((a, b) => a[0] - b[0]).map(([, p]) => ({ w: p.w, e: p.e, lab: labOf(p.r / p.w, p.g / p.w, p.b / p.w) }));
798
+ if (!points.length) return { width: W, height: H, swatches: [] };
799
+ const total = points.reduce((t, p) => t + p.w, 0);
800
+ const dist = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;
801
+ let heaviest = points[0];
802
+ for (const p of points) if (p.w > heaviest.w) heaviest = p;
803
+ const centres = [heaviest.lab];
804
+ const seeds = points.filter((p) => p.w >= 0.0005 * total);
805
+ const near = seeds.map((p) => dist(p.lab, heaviest.lab));
806
+ while (centres.length < Math.min(10, seeds.length)) {
807
+ let best = -1;
808
+ for (let i = 0; i < seeds.length; i++) if (best === -1 || near[i] > near[best]) best = i;
809
+ if (near[best] <= 0) break;
810
+ centres.push(seeds[best].lab);
811
+ for (let i = 0; i < seeds.length; i++) near[i] = Math.min(near[i], dist(seeds[i].lab, seeds[best].lab));
812
+ }
813
+ let groups = [];
814
+ for (let round = 0; round < 12; round++) {
815
+ groups = centres.map(() => ({ w: 0, L: 0, a: 0, b: 0, e: 0 }));
816
+ for (const p of points) {
817
+ let best = 0;
818
+ for (let c = 1; c < centres.length; c++) if (dist(p.lab, centres[c]) < dist(p.lab, centres[best])) best = c;
819
+ const g = groups[best];
820
+ g.w += p.w; g.e += p.e; g.L += p.w * p.lab[0]; g.a += p.w * p.lab[1]; g.b += p.w * p.lab[2];
821
+ }
822
+ for (let c = 0; c < centres.length; c++) if (groups[c].w) centres[c] = [groups[c].L / groups[c].w, groups[c].a / groups[c].w, groups[c].b / groups[c].w];
823
+ }
824
+ const round = (v, n) => Math.round(v * 10 ** n) / 10 ** n;
825
+ const out = centres.map((lab, c) => ({ lab, w: groups[c].w, e: groups[c].e })).filter((g) => g.w > 0).sort((a, b) => b.w - a.w);
826
+ return {
827
+ width: W,
828
+ height: H,
829
+ swatches: out.map(({ lab: [L, a, b], w: weight, e }) => ({ hex: hexOfLab([L, a, b]), L: round(L, 3), C: round(Math.hypot(a, b), 3), h: round(((Math.atan2(b, a) * 180) / Math.PI + 360) % 360, 1), share: round((100 * weight) / total, 1), edge: round(e / weight, 2) })),
830
+ };
831
+ }
832
+
833
+ const readPage = `(() => {
834
+ const W = innerWidth, H = innerHeight, box = (r) => [Math.round(r.left), Math.round(r.top), Math.round(r.width), Math.round(r.height)];
835
+ const out = { screen: [W, H], ground: getComputedStyle(document.body).backgroundColor, root: getComputedStyle(document.documentElement).backgroundColor, text: [], boxes: [], icons: 0, solids: [] };
836
+ const seen = new Set();
837
+ for (const el of document.querySelectorAll("body *")) {
838
+ let r = el.getBoundingClientRect();
839
+ const cs = getComputedStyle(el);
840
+ // An element with no box of its own (display: contents, a headline split into word spans) is
841
+ // still read by its words: their own box stands for it, and its parent says whether it shows.
842
+ const boxless = r.width < 2 || r.height < 2;
843
+ const ownText = boxless ? [...el.childNodes].filter((n) => n.nodeType === 3 && n.textContent.trim()) : [];
844
+ if (ownText.length) {
845
+ const range = document.createRange();
846
+ range.setStartBefore(ownText[0]);
847
+ range.setEndAfter(ownText.at(-1));
848
+ r = range.getBoundingClientRect();
849
+ }
850
+ if (r.width < 2 || r.height < 2 || r.top > H || r.bottom < 0 || r.left > W || r.right < 0) continue;
851
+ if (cs.visibility === "hidden" || cs.display === "none" || Number(cs.opacity) === 0) continue;
852
+ // Hidden by an ancestor (an opacity of 0 on a wrapper, mid-reveal) is hidden too.
853
+ const shown = boxless ? el.parentElement : el;
854
+ if (shown?.checkVisibility && !shown.checkVisibility({ opacityProperty: true, visibilityProperty: true })) continue;
855
+ const own = [...el.childNodes].filter((n) => n.nodeType === 3).map((n) => n.textContent.trim()).join(" ").trim();
856
+ if (own && !seen.has(own.slice(0, 24) + cs.fontSize)) {
857
+ seen.add(own.slice(0, 24) + cs.fontSize);
858
+ // The text's own box, from a range over its words: a heading's block runs the full width even when
859
+ // its words sit left, and its box would read as centred.
860
+ const words = [...el.childNodes].filter((n) => n.nodeType === 3 && n.textContent.trim());
861
+ const range = document.createRange();
862
+ range.setStartBefore(words[0]);
863
+ range.setEndAfter(words.at(-1));
864
+ const tr = range.getBoundingClientRect();
865
+ out.text.push({ text: own.slice(0, 40), face: cs.fontFamily.split(",")[0].replace(/["']/g, "").trim(), size: cs.fontSize, weight: cs.fontWeight, style: cs.fontStyle, tracking: cs.letterSpacing, leading: cs.lineHeight, case: cs.textTransform, colour: cs.color, box: box(tr.width ? tr : r) });
866
+ }
867
+ // Icons: small pictures and drawings, a logo row, emoji, pictograms.
868
+ const tag = el.tagName.toLowerCase();
869
+ const small = r.width >= 12 && r.height >= 12 && r.width <= 72 && r.height <= 72;
870
+ const mask = cs.maskImage || cs.webkitMaskImage || "none";
871
+ const before = getComputedStyle(el, "::before").content;
872
+ const glyph = (own.length > 0 && own.length <= 2 && !/[A-Za-z0-9]/.test(own)) || (before && before !== "none" && before !== "normal" && before.replace(/["']/g, "").length > 0 && before.replace(/["']/g, "").length <= 2);
873
+ if (small && (tag === "img" || (tag === "svg" && !el.parentElement.closest("svg")) || /url\\(/.test(cs.backgroundImage) || mask !== "none" || glyph)) out.icons++;
874
+ // Solid blocks: an opaque fill of its own colour, at least a fortieth of the screen. A band, a card, a shape.
875
+ const alpha = (cs.backgroundColor.match(/rgba?[(]([^)]*)[)]/) || [, ""])[1].split(",").map(Number)[3];
876
+ if (cs.backgroundColor !== "rgba(0, 0, 0, 0)" && !(alpha < 0.9) && r.width * r.height >= (W * H) / 40) out.solids.push({ fill: cs.backgroundColor, box: box(r), radius: cs.borderRadius });
877
+ const filled = cs.backgroundColor !== "rgba(0, 0, 0, 0)" && r.width < W - 40;
878
+ if ((/^(IMG|VIDEO|CANVAS|svg)$/.test(el.tagName) || cs.backgroundImage !== "none" || filled) && r.width > 30 && r.height > 2)
879
+ out.boxes.push({ kind: el.tagName.toLowerCase(), fill: cs.backgroundColor, radius: cs.borderRadius, box: box(r), picture: /^(IMG|VIDEO|CANVAS)$/.test(el.tagName) || /url\\(/.test(cs.backgroundImage), gradient: /gradient\\(/.test(cs.backgroundImage) ? cs.backgroundImage.slice(0, 240) : "", size: cs.backgroundSize, repeat: cs.backgroundRepeat });
880
+ }
881
+ // Whether this is the real site: the answer's status, and how much it says. A maintenance page,
882
+ // a bot check or an error page is not a reference, however it looks.
883
+ out.status = performance.getEntriesByType("navigation")[0]?.responseStatus || 0;
884
+ const said = (document.body.innerText || "").replace(/\\s+/g, " ").trim();
885
+ out.words = said ? said.split(" ").length : 0;
886
+ out.said = said.slice(0, 3000);
887
+ out.fonts = [...new Set([...document.fonts].filter((f) => f.status === "loaded").map((f) => f.family.replace(/["']/g, "") + " " + f.weight + " " + f.style))];
888
+ // Traits. The body size is the size most text is set in, by characters: a title split into one
889
+ // element per letter is still a few characters, and a paragraph is many.
890
+ const sizes = out.text.map((t) => parseFloat(t.size)).filter((x) => x > 0);
891
+ const tally = new Map();
892
+ for (const t of out.text) {
893
+ const x = parseFloat(t.size);
894
+ if (x > 0) tally.set(x, (tally.get(x) || 0) + t.text.length);
895
+ }
896
+ // One size alone (a hero whose only text is its headline) has no body to compare it with.
897
+ const body = tally.size > 1 ? [...tally].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0]?.[0] || 0 : 0;
898
+ // Lettering drawn as an SVG or an image (a wordmark, a title set as a picture) is display type too:
899
+ // a box at least a quarter of the screen wide and at least three times as wide as it is tall.
900
+ // Its height stands for its size: a cap height is about 0.7 of the size it was set at.
901
+ const words = [];
902
+ for (const el of document.querySelectorAll("svg, img")) {
903
+ const r = el.getBoundingClientRect();
904
+ // A line of lettering: a quarter of the screen wide or more, three times as wide as tall, and no
905
+ // taller than about a third of the screen (the largest wordmarks seen were under 320 px of 900).
906
+ if (r.bottom < 0 || r.top > H || r.width < W / 4 || r.height < 24 || r.height > H * 0.36 || r.width / r.height < 3) continue;
907
+ if (el.closest("svg") !== el && el.tagName.toLowerCase() !== "img") continue;
908
+ // Lettering is drawn: an SVG, or an image whose file is one. A wide photograph is a banner, not a word.
909
+ if (el.tagName.toLowerCase() === "img" && !/\\.svg([?#]|$)|^data:image\\/svg/i.test(el.currentSrc || el.src || "")) continue;
910
+ words.push(Math.round(r.height / 0.7));
911
+ }
912
+ const largestText = sizes.length ? Math.max(...sizes) : 0;
913
+ const largestWord = words.length ? Math.max(...words) : 0;
914
+ const largest = Math.max(largestText, largestWord);
915
+ // Picture cover is counted on a coarse grid, so overlapping pictures count once.
916
+ // Only real pictures: an image, a video, a canvas or a url() background, never a gradient or a panel.
917
+ const cells = new Set();
918
+ for (const b of out.boxes) {
919
+ if (!b.picture) continue;
920
+ const [x, y, w, h] = b.box;
921
+ for (let gx = Math.max(0, Math.floor(x / 20)); gx < Math.min(W / 20, Math.ceil((x + w) / 20)); gx++)
922
+ for (let gy = Math.max(0, Math.floor(y / 20)); gy < Math.min(H / 20, Math.ceil((y + h) / 20)); gy++) cells.add(gx + "," + gy);
923
+ }
924
+ // Gradients are recorded, never judged: how much of the first screen they cover, and the largest
925
+ // ones as written, so a family that relies on one keeps it. Counted on the same grid as pictures.
926
+ // A gradient counts only when it can be seen: its colours differ, and they are not all see-through.
927
+ // Colours of any kind (rgb, hsl, oklch, lab, hex, transparent) are read the same way: painted on
928
+ // one pixel and read back, so a modern colour function is never missed.
929
+ const px = Object.assign(document.createElement("canvas"), { width: 1, height: 1 }).getContext("2d", { willReadFrequently: true });
930
+ const rgba = (token) => {
931
+ px.clearRect(0, 0, 1, 1);
932
+ px.fillStyle = "rgba(0, 0, 0, 0)";
933
+ px.fillStyle = token;
934
+ px.fillRect(0, 0, 1, 1);
935
+ const d = px.getImageData(0, 0, 1, 1).data;
936
+ return [d[0], d[1], d[2], d[3] / 255];
937
+ };
938
+ const visible = (css) => {
939
+ const stops = [...css.matchAll(/(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\\([^()]*\\)|#[0-9a-fA-F]{3,8}\\b|\\btransparent\\b/g)].map((m) => rgba(m[0]));
940
+ const solid = stops.filter((c) => c[3] >= 0.15);
941
+ if (solid.length < 1 || stops.length < 2) return false;
942
+ if (solid.length < stops.length) return true;
943
+ return stops.some((c) => stops.some((d) => Math.max(...[0, 1, 2].map((k) => Math.abs(c[k] - d[k]))) > 24));
944
+ };
945
+ // A pattern repeats: a repeating gradient, or a gradient tiled at a small size (a dot grid, fine
946
+ // lines). A gradient with px stops that runs across its box once is a fade, not a pattern.
947
+ const isPattern = (css, size = "", repeat = "") => /repeating-/.test(css) || (!/no-repeat/.test(repeat) && /\\d/.test(size) && size.split(/[ ,]+/).filter((v) => /px$/.test(v)).length > 0 && size.split(/[ ,]+/).filter((v) => /px$/.test(v)).every((v) => parseFloat(v) <= 64));
948
+ for (const b of out.boxes) if (b.gradient && !visible(b.gradient)) b.gradient = "";
949
+ for (const b of out.boxes) if (b.gradient && isPattern(b.gradient, b.size, b.repeat)) [b.pattern, b.gradient] = [b.gradient, ""];
950
+ const pcells = new Set();
951
+ for (const b of out.boxes) {
952
+ if (!b.pattern) continue;
953
+ const [x, y, w, h] = b.box;
954
+ for (let gx = Math.max(0, Math.floor(x / 20)); gx < Math.min(W / 20, Math.ceil((x + w) / 20)); gx++)
955
+ for (let gy = Math.max(0, Math.floor(y / 20)); gy < Math.min(H / 20, Math.ceil((y + h) / 20)); gy++) pcells.add(gx + "," + gy);
956
+ }
957
+ const gcells = new Set();
958
+ for (const b of out.boxes) {
959
+ if (!b.gradient) continue;
960
+ const [x, y, w, h] = b.box;
961
+ for (let gx = Math.max(0, Math.floor(x / 20)); gx < Math.min(W / 20, Math.ceil((x + w) / 20)); gx++)
962
+ for (let gy = Math.max(0, Math.floor(y / 20)); gy < Math.min(H / 20, Math.ceil((y + h) / 20)); gy++) gcells.add(gx + "," + gy);
963
+ }
964
+ for (const layer of [document.documentElement, document.body]) {
965
+ const bg = getComputedStyle(layer).backgroundImage;
966
+ if (/gradient\\(/.test(bg) && visible(bg)) {
967
+ const pattern = isPattern(bg, getComputedStyle(layer).backgroundSize, getComputedStyle(layer).backgroundRepeat);
968
+ for (let gx = 0; gx < W / 20; gx++) for (let gy = 0; gy < H / 20; gy++) (pattern ? pcells : gcells).add(gx + "," + gy);
969
+ out.boxes.push({ kind: layer.tagName.toLowerCase(), box: [0, 0, W, H], gradient: pattern ? "" : bg.slice(0, 240), pattern: pattern ? bg.slice(0, 240) : "" });
970
+ }
971
+ }
972
+ out.patterns = out.boxes.filter((b) => b.pattern).slice(0, 3).map((b) => ({ css: b.pattern, box: b.box }));
973
+ out.gradients = out.boxes.filter((b) => b.gradient).sort((a, b) => b.box[2] * b.box[3] - a.box[2] * a.box[3]).slice(0, 3).map((b) => ({ css: b.gradient, box: b.box }));
974
+ // Where the largest text sits across the screen: centred, left or right.
975
+ const big = out.text.reduce((m, t) => (parseFloat(t.size) > parseFloat(m?.size || 0) ? t : m), null);
976
+ const cx = big ? big.box[0] + big.box[2] / 2 : W / 2;
977
+ const align = !big ? "" : Math.abs(cx - W / 2) < W * 0.08 ? "centre" : cx < W / 2 ? "left" : "right";
978
+ // What the first screen is made of: how much is photographs and images, video, canvas (most
979
+ // often WebGL: 3D and generative work) and SVG drawing. A picture's kind is half of what it looks like.
980
+ const media = { image: new Set(), video: new Set(), canvas: new Set(), svg: new Set() };
981
+ for (const b of out.boxes) {
982
+ const kind = b.kind === "video" ? "video" : b.kind === "canvas" ? "canvas" : b.kind === "svg" ? "svg" : b.picture ? "image" : "";
983
+ if (!kind) continue;
984
+ const [x, y, w, h] = b.box;
985
+ for (let gx = Math.max(0, Math.floor(x / 20)); gx < Math.min(W / 20, Math.ceil((x + w) / 20)); gx++)
986
+ for (let gy = Math.max(0, Math.floor(y / 20)); gy < Math.min(H / 20, Math.ceil((y + h) / 20)); gy++) media[kind].add(gx + "," + gy);
987
+ }
988
+ // Blocks: how much of the screen is solid colour other than the ground.
989
+ // A fill over most of the screen is the ground, whatever element carries it (a wrapper, a main).
990
+ // With no ground set on body or html, the page's ground is the browser's white. And the fill that
991
+ // covers the most of the screen, when it covers at least two fifths, is the ground in sections.
992
+ const bare = (c) => c === "rgba(0, 0, 0, 0)" || c === "transparent";
993
+ const grounds = new Set([out.ground, out.root, ...out.solids.filter((b) => b.box[2] * b.box[3] >= 0.85 * W * H).map((b) => b.fill)]);
994
+ if (bare(out.ground) && bare(out.root)) grounds.add("rgb(255, 255, 255)");
995
+ const byFill = new Map();
996
+ for (const b of out.solids) {
997
+ const cellsOf = byFill.get(b.fill) || new Set();
998
+ const [x, y, w, h] = b.box;
999
+ for (let gx = Math.max(0, Math.floor(x / 20)); gx < Math.min(W / 20, Math.ceil((x + w) / 20)); gx++)
1000
+ for (let gy = Math.max(0, Math.floor(y / 20)); gy < Math.min(H / 20, Math.ceil((y + h) / 20)); gy++) cellsOf.add(gx + "," + gy);
1001
+ byFill.set(b.fill, cellsOf);
1002
+ }
1003
+ const [topFill] = [...byFill].sort((a, b) => b[1].size - a[1].size);
1004
+ if (topFill && topFill[1].size >= 0.4 * Math.ceil(W / 20) * Math.ceil(H / 20)) grounds.add(topFill[0]);
1005
+ const bcells = new Set();
1006
+ for (const b of out.solids) {
1007
+ if (grounds.has(b.fill)) continue;
1008
+ const [x, y, w, h] = b.box;
1009
+ for (let gx = Math.max(0, Math.floor(x / 20)); gx < Math.min(W / 20, Math.ceil((x + w) / 20)); gx++)
1010
+ for (let gy = Math.max(0, Math.floor(y / 20)); gy < Math.min(H / 20, Math.ceil((y + h) / 20)); gy++) bcells.add(gx + "," + gy);
1011
+ }
1012
+ out.blocks = Math.round((1000 * bcells.size) / (Math.ceil(W / 20) * Math.ceil(H / 20))) / 10;
1013
+ delete out.solids;
1014
+ out.media = Object.fromEntries(Object.entries(media).map(([k, v]) => [k, Math.round((1000 * v.size) / (Math.ceil(W / 20) * Math.ceil(H / 20))) / 10]));
1015
+ const radii = out.boxes.map((b) => b.radius).filter((r) => r && r !== "0px");
1016
+ const radius = radii.length ? [...radii.reduce((m, r) => m.set(r, (m.get(r) || 0) + 1), new Map())].sort((a, b) => b[1] - a[1])[0][0] : "0px";
1017
+ const lefts = out.text.map((t) => t.box[0]).filter((x) => x >= 0);
1018
+ out.traits = {
1019
+ display: largest + "px",
1020
+ body: body ? body + "px" : null,
1021
+ scale: body ? Math.round((10 * largest) / body) / 10 : null,
1022
+ pictures: Math.round((1000 * cells.size) / (Math.ceil(W / 20) * Math.ceil(H / 20))) / 10,
1023
+ margin: lefts.length ? Math.round((1000 * Math.min(...lefts)) / W) / 10 : null,
1024
+ radius: parseFloat(radius) > 999 ? "pill" : radius,
1025
+ lettering: largestWord > largestText ? "picture" : "text",
1026
+ gradient: Math.round((1000 * gcells.size) / (Math.ceil(W / 20) * Math.ceil(H / 20))) / 10,
1027
+ pattern: Math.round((1000 * pcells.size) / (Math.ceil(W / 20) * Math.ceil(H / 20))) / 10,
1028
+ icons: out.icons,
1029
+ blocks: out.blocks,
1030
+ align,
1031
+ };
1032
+ return out;
1033
+ })()`;
1034
+
1035
+ // Motion: each transition and animation a page declares on an element that has a box, read from
1036
+ // computed style, so one that has already ended (a fill-mode fade) is still seen. It is read before
1037
+ // animations are ended, so a running one gives its keyframes' properties. Then what a script does
1038
+ // (watchFrames, below). Runs in the page (it is sent as text, so it holds nothing from this file).
1039
+ // Stylesheets the page does not allow reading are counted in "unread" and never guessed at: a hover
1040
+ // is named only from rules that were read.
1041
+ async function readMotion() {
1042
+ const W = innerWidth, LIMIT = 6000, CAP = 12;
1043
+ // A list of CSS values, split at the commas that are not inside brackets or quotes.
1044
+ const split = (v) => {
1045
+ const parts = [];
1046
+ let depth = 0, quote = "", at = 0;
1047
+ for (let i = 0; i < v.length; i++) {
1048
+ const c = v[i];
1049
+ if (quote) {
1050
+ if (c === "\\") i++;
1051
+ else if (c === quote) quote = "";
1052
+ } else if (c === '"' || c === "'") quote = c;
1053
+ else if (c === "(" || c === "[") depth++;
1054
+ else if (c === ")" || c === "]") depth--;
1055
+ else if (c === "," && depth === 0) (parts.push(v.slice(at, i).trim()), (at = i + 1));
1056
+ }
1057
+ parts.push(v.slice(at).trim());
1058
+ return parts.filter(Boolean);
1059
+ };
1060
+ const ms = (v) => {
1061
+ const n = parseFloat(v);
1062
+ return Number.isFinite(n) ? Math.round(/ms$/.test(v) ? n : n * 1000) : null;
1063
+ };
1064
+ // What the stylesheets say: hover rules (by the selector of what they change) and keyframes.
1065
+ let unread = 0;
1066
+ const hovers = [], keyframes = new Map(), seen = new Set();
1067
+ const walk = (rules, parent) => {
1068
+ for (const r of rules) {
1069
+ if (typeof CSSImportRule !== "undefined" && r instanceof CSSImportRule) {
1070
+ if (r.styleSheet) readSheet(r.styleSheet);
1071
+ else unread++;
1072
+ } else if (typeof CSSKeyframesRule !== "undefined" && r instanceof CSSKeyframesRule) {
1073
+ const props = keyframes.get(r.name) || new Set();
1074
+ for (const k of r.cssRules) for (let i = 0; i < (k.style?.length || 0); i++) if (!/^animation-/.test(k.style[i])) props.add(k.style[i]);
1075
+ keyframes.set(r.name, props);
1076
+ } else if (typeof CSSMediaRule !== "undefined" && r instanceof CSSMediaRule) {
1077
+ if (matchMedia(r.media.mediaText).matches) walk(r.cssRules, parent);
1078
+ } else if (typeof CSSStyleRule !== "undefined" && r instanceof CSSStyleRule) {
1079
+ let sel = r.selectorText;
1080
+ if (parent) sel = sel.includes("&") ? sel.replace(/&/g, ":is(" + parent + ")") : ":is(" + parent + ") " + sel;
1081
+ if (sel.includes(":hover") && hovers.length < 4000) {
1082
+ const props = new Set();
1083
+ for (let i = 0; i < r.style.length; i++) if (!/^(transition|animation)/.test(r.style[i])) props.add(r.style[i]);
1084
+ for (const s of split(sel)) {
1085
+ if (!s.includes(":hover") || /:not\([^)]*:hover/.test(s)) continue;
1086
+ // The selector of what is hovered, without the hover: ".card:hover .title" is read as ".card .title".
1087
+ hovers.push({ sel: s.replace(/(^|[\s>+~(])(:hover)/g, "$1*").replace(/:hover/g, ""), props });
1088
+ }
1089
+ }
1090
+ if (r.cssRules?.length) walk(r.cssRules, sel);
1091
+ } else if (r.cssRules) walk(r.cssRules, parent);
1092
+ }
1093
+ };
1094
+ const readSheet = (sheet) => {
1095
+ if (seen.has(sheet) || sheet.disabled) return;
1096
+ seen.add(sheet);
1097
+ if (sheet.media?.mediaText && !matchMedia(sheet.media.mediaText).matches) return;
1098
+ let rules = null;
1099
+ try {
1100
+ rules = sheet.cssRules;
1101
+ } catch {}
1102
+ if (!rules) return void unread++;
1103
+ walk(rules, "");
1104
+ };
1105
+ for (const sheet of [...document.styleSheets, ...(document.adoptedStyleSheets || [])]) readSheet(sheet);
1106
+ // What is running now: a keyframes' properties are read from the animation itself, which works
1107
+ // even when its stylesheet could not be read.
1108
+ const running = new Map(), scripted = [];
1109
+ const keysOf = (a) => {
1110
+ const props = new Set();
1111
+ try {
1112
+ for (const k of a.effect.getKeyframes()) for (const p of Object.keys(k)) if (!["offset", "computedOffset", "easing", "composite"].includes(p)) props.add(p);
1113
+ } catch {}
1114
+ return props;
1115
+ };
1116
+ const isTransition = (a) => typeof CSSTransition !== "undefined" && a instanceof CSSTransition;
1117
+ const isCss = (a) => isTransition(a) || (typeof CSSAnimation !== "undefined" && a instanceof CSSAnimation);
1118
+ for (const a of document.getAnimations()) {
1119
+ const target = a.effect?.target;
1120
+ if (!target) continue;
1121
+ // One a script made (element.animate) is in no style sheet: it is listed from its own timing, below.
1122
+ if (!isCss(a)) {
1123
+ if (a.playState !== "idle") scripted.push(a);
1124
+ continue;
1125
+ }
1126
+ if (a.effect.pseudoElement) continue;
1127
+ const here = running.get(target) || { names: new Map(), moves: new Set() };
1128
+ running.set(target, here);
1129
+ if (isTransition(a)) here.moves.add(a.transitionProperty);
1130
+ else here.names.set(a.animationName, keysOf(a));
1131
+ }
1132
+ const dash = (p) => p.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase());
1133
+ const words = (t) => {
1134
+ const w = (t || "").trim().replace(/\s+/g, " ").split(" ").slice(0, 3).join(" ");
1135
+ return w.length > 24 ? w.slice(0, 24) : w;
1136
+ };
1137
+ // What a thing is, in a few words and no class names: its tag or role, and for a button or a link a few of its words.
1138
+ const describe = (el) => {
1139
+ const tag = el.tagName.toLowerCase(), role = el.getAttribute("role");
1140
+ const say = (t) => (words(t) ? ` "${words(t)}"` : "");
1141
+ if (tag === "h1") return "the headline";
1142
+ if (/^h[2-6]$/.test(tag)) return "a heading";
1143
+ if (tag === "button" || role === "button") return "a button" + say(el.textContent);
1144
+ if (tag === "a") return (el.closest("nav") ? "a nav link" : "a link") + say(el.textContent);
1145
+ if (tag === "img" || tag === "picture") return "a picture";
1146
+ if (tag === "video" || tag === "canvas") return "a " + tag;
1147
+ if (/^(svg|path|circle|rect)$/.test(tag)) return el.closest("a, button") || el.getBoundingClientRect().width <= 72 ? "an icon" : "a drawing";
1148
+ if (/^(input|select|textarea)$/.test(tag)) return "a field";
1149
+ if (/^(nav|header|footer|main)$/.test(tag)) return "the " + (tag === "nav" ? "navigation" : tag);
1150
+ if (tag === "body" || tag === "html") return "the page";
1151
+ if (tag === "li") return "a list item";
1152
+ if (tag === "p") return "a paragraph";
1153
+ if (/^(span|em|strong)$/.test(tag)) return "a run of text";
1154
+ const r = el.getBoundingClientRect(), cs = getComputedStyle(el);
1155
+ const looks = cs.boxShadow !== "none" || cs.borderTopWidth !== "0px" || cs.backgroundColor !== "rgba(0, 0, 0, 0)";
1156
+ const kin = [...(el.parentElement?.children || [])].filter((s) => s.tagName === el.tagName && Math.abs(s.getBoundingClientRect().width - r.width) < 0.2 * r.width).length;
1157
+ if (looks && kin >= 2 && r.width >= 100 && r.width <= 0.6 * W) return "a card";
1158
+ return r.width >= 0.5 * W && r.height >= 200 ? "a section" : "a block";
1159
+ };
1160
+ // What a hover changes on this element: the properties of every readable hover rule that reaches it.
1161
+ const hoverProps = (el) => {
1162
+ const props = new Set();
1163
+ for (const h of hovers) {
1164
+ try {
1165
+ if (el.matches(h.sel)) for (const p of h.props) props.add(p);
1166
+ } catch {}
1167
+ }
1168
+ return props;
1169
+ };
1170
+ const found = new Map();
1171
+ const note = (item, on) => {
1172
+ const sig = [item.kind, item.name || "", item.property, item.ms, item.delay, item.easing, item.iteration, item.trigger].join("|");
1173
+ const old = found.get(sig);
1174
+ if (old) old.uses++;
1175
+ else found.set(sig, { ...item, on, uses: 1 });
1176
+ };
1177
+ const cycle = (list, i) => list[i % list.length];
1178
+ const read = (el, pseudo) => {
1179
+ const cs = pseudo ? getComputedStyle(el, pseudo) : getComputedStyle(el);
1180
+ if (pseudo && (cs.display === "none" || cs.content === "none" || cs.content === "normal")) return;
1181
+ const tp = split(cs.transitionProperty), ad = split(cs.animationName);
1182
+ const moves = tp.length && !(tp.length === 1 && tp[0] === "none") && split(cs.transitionDuration).some((d) => ms(d) > 0);
1183
+ const animates = ad.length && !(ad.length === 1 && ad[0] === "none");
1184
+ if (!moves && !animates) return;
1185
+ // A thing that cannot be seen is left out. A fade-in starts at no opacity, so an animation keeps its element.
1186
+ if (!el.checkVisibility || !el.checkVisibility({ visibilityProperty: true })) return;
1187
+ const box = el.getBoundingClientRect();
1188
+ if (!pseudo && box.width < 2 && box.height < 2) return;
1189
+ const on = describe(el) + (pseudo ? " (" + pseudo + ")" : "");
1190
+ if (moves && (pseudo || (Number(cs.opacity) > 0 && el.checkVisibility({ opacityProperty: true, visibilityProperty: true })))) {
1191
+ const durs = split(cs.transitionDuration), delays = split(cs.transitionDelay), eases = split(cs.transitionTimingFunction);
1192
+ let hover = null;
1193
+ tp.forEach((property, i) => {
1194
+ const ends = ms(cycle(durs, i));
1195
+ if (property === "none" || !(ends > 0)) return;
1196
+ const now = running.get(el)?.moves;
1197
+ let trigger = "state";
1198
+ if (!pseudo && now && (now.has(property) || property === "all")) trigger = "load";
1199
+ else if (!pseudo) {
1200
+ hover ||= hoverProps(el);
1201
+ if ([...hover].some((p) => property === "all" || p === property || p.startsWith(property + "-"))) trigger = "hover";
1202
+ }
1203
+ note({ kind: "transition", property, ms: ends, delay: ms(cycle(delays, i)), easing: cycle(eases, i), iteration: "once", trigger }, on);
1204
+ });
1205
+ }
1206
+ if (animates) {
1207
+ const durs = split(cs.animationDuration), delays = split(cs.animationDelay), eases = split(cs.animationTimingFunction), counts = split(cs.animationIterationCount), lines = split(cs.animationTimeline || "auto");
1208
+ ad.forEach((name, i) => {
1209
+ const line = cycle(lines, i), ends = ms(cycle(durs, i));
1210
+ if (name === "none" || line === "none") return;
1211
+ const scroll = line !== "auto";
1212
+ if (!scroll && !(ends > 0)) return;
1213
+ const count = cycle(counts, i);
1214
+ const props = running.get(el)?.names.get(name) || keyframes.get(name);
1215
+ note(
1216
+ { kind: "animation", name, property: props?.size ? [...props].map(dash).join(", ") : null, ms: scroll ? null : ends, delay: ms(cycle(delays, i)), easing: cycle(eases, i), iteration: count === "infinite" ? "loop" : count === "1" ? "once" : count + " times", trigger: scroll ? "scroll" : "load" },
1217
+ on,
1218
+ );
1219
+ });
1220
+ }
1221
+ };
1222
+ let n = 0;
1223
+ for (const el of [document.body, ...document.body.querySelectorAll("*")]) {
1224
+ if (++n > LIMIT) break;
1225
+ read(el, "");
1226
+ read(el, "::before");
1227
+ read(el, "::after");
1228
+ }
1229
+ // Animations a script made with element.animate: the properties its keyframes set, and its timing as set.
1230
+ for (const a of scripted.slice(0, LIMIT)) {
1231
+ const el = a.effect.target, pseudo = a.effect.pseudoElement || "";
1232
+ if (!el.checkVisibility || !el.checkVisibility({ visibilityProperty: true })) continue;
1233
+ let t;
1234
+ try {
1235
+ t = a.effect.getTiming();
1236
+ } catch {
1237
+ continue;
1238
+ }
1239
+ const line = typeof ScrollTimeline !== "undefined" && a.timeline instanceof ScrollTimeline;
1240
+ const props = keysOf(a);
1241
+ note(
1242
+ {
1243
+ kind: "script",
1244
+ property: props.size ? [...props].map(dash).join(", ") : null,
1245
+ ms: !line && typeof t.duration === "number" ? Math.round(t.duration) : null,
1246
+ delay: Math.round(t.delay) || 0,
1247
+ easing: t.easing,
1248
+ iteration: t.iterations === Infinity ? "loop" : t.iterations === 1 ? "once" : t.iterations + " times",
1249
+ trigger: line ? "scroll" : "load",
1250
+ },
1251
+ describe(el) + (pseudo ? " (" + pseudo + ")" : ""),
1252
+ );
1253
+ }
1254
+
1255
+ // Motion a script makes by writing values frame by frame (a loop on the page's own frames, a
1256
+ // library, a scroll listener) leaves nothing to read, so it is watched: a bounded set of the
1257
+ // visible elements is sampled four times over 600 ms, then again as the page is scrolled one
1258
+ // screen in three steps, and an element whose value changes between samples with no transition
1259
+ // or animation running on that property is listed. Frames give no curve, so its time and easing
1260
+ // are null ("not seen"). Reduced motion is not emulated: the page behaves as it does for anyone.
1261
+ // The watch is held to about two seconds, and the scroll position is put back.
1262
+ const watchFrames = async () => {
1263
+ const T0 = performance.now(), BUDGET = 1900, H = innerHeight;
1264
+ const late = () => performance.now() - T0 > BUDGET;
1265
+ // The next frame, or 120 ms on, whichever comes first, so a tab that draws no frames still moves on.
1266
+ const frame = () =>
1267
+ new Promise((done) => {
1268
+ const timer = setTimeout(done, 120);
1269
+ requestAnimationFrame(() => (clearTimeout(timer), done()));
1270
+ });
1271
+ const pause = (ms) => new Promise((r) => setTimeout(r, ms));
1272
+ const until = async (at) => {
1273
+ const left = T0 + at - performance.now();
1274
+ if (left > 0) await pause(left);
1275
+ await frame();
1276
+ };
1277
+ const tracked = [], pinned = [];
1278
+ let scanned = 0;
1279
+ for (const el of [document.body, ...document.body.querySelectorAll("*")]) {
1280
+ if (++scanned > LIMIT) break;
1281
+ if (!el.checkVisibility || !el.checkVisibility({ visibilityProperty: true })) continue;
1282
+ const b = el.getBoundingClientRect();
1283
+ if (b.width < 2 && b.height < 2) continue;
1284
+ tracked.push(el);
1285
+ pinned.push(/^(fixed|sticky)$/.test(getComputedStyle(el).position));
1286
+ }
1287
+ // What a rule or a Web Animation already moves is not the script's: its properties, per element.
1288
+ const LAYOUT = /^(width|height|inline-size|block-size|top|left|right|bottom|inset|margin|padding|border|font|flex|grid|gap|line-height|letter-spacing|min-|max-)/;
1289
+ const covered = new Map();
1290
+ let layoutMoves = false;
1291
+ const coverOf = (el) => covered.get(el) || covered.set(el, new Set()).get(el);
1292
+ const addProp = (el, p) => {
1293
+ coverOf(el).add(p);
1294
+ if (LAYOUT.test(p)) layoutMoves = true;
1295
+ };
1296
+ const addAnimation = (a) => {
1297
+ const el = a.effect?.target;
1298
+ if (!el || a.effect.pseudoElement) return;
1299
+ for (const p of isTransition(a) ? [a.transitionProperty] : [...keysOf(a)].map(dash)) addProp(el, p);
1300
+ };
1301
+ // A transition or animation that starts and ends between two samples is still seen as it starts.
1302
+ const onRun = (e) => {
1303
+ try {
1304
+ if (e.pseudoElement) return;
1305
+ for (const a of e.target.getAnimations()) addAnimation(a);
1306
+ if (e.propertyName) addProp(e.target, e.propertyName);
1307
+ } catch {}
1308
+ };
1309
+ document.addEventListener("transitionrun", onRun, true);
1310
+ document.addEventListener("animationstart", onRun, true);
1311
+ // A picture loads into its box, which is not motion: the box of one is left out.
1312
+ const boxOf = (el) => {
1313
+ if (/^(IMG|VIDEO|IFRAME|CANVAS|PICTURE|OBJECT|EMBED)$/.test(el.tagName)) return "";
1314
+ if (el instanceof HTMLElement) return el.offsetWidth + "," + el.offsetHeight + "," + el.offsetLeft + "," + el.offsetTop;
1315
+ try {
1316
+ const b = el.getBBox();
1317
+ return [b.width, b.height, b.x, b.y].map(Math.round).join(",");
1318
+ } catch {
1319
+ return "";
1320
+ }
1321
+ };
1322
+ // A drawing's transform as it is animated, which also shows what an animateTransform does (it is no style).
1323
+ const svgMatrix = (el) => {
1324
+ if (typeof SVGGraphicsElement === "undefined" || !(el instanceof SVGGraphicsElement) || !el.transform) return "";
1325
+ try {
1326
+ const m = el.transform.animVal.consolidate()?.matrix;
1327
+ return m ? " " + [m.a, m.b, m.c, m.d, m.e, m.f].join() : "";
1328
+ } catch {
1329
+ return "";
1330
+ }
1331
+ };
1332
+ const KEYS = ["transform","opacity", "translate", "rotate", "scale", "clip-path", "filter", "top", "left", "box"];
1333
+ const take = () => {
1334
+ for (const a of document.getAnimations()) addAnimation(a);
1335
+ return tracked.map((el) => {
1336
+ if (!el.isConnected) return null;
1337
+ const cs = getComputedStyle(el), placed = cs.position !== "static";
1338
+ return [cs.transform + svgMatrix(el),cs.opacity, cs.translate, cs.rotate, cs.scale, cs.clipPath, cs.filter, placed ? cs.top : "", placed ? cs.left : "", boxOf(el)];
1339
+ });
1340
+ };
1341
+ const isCovered = (el, key) => {
1342
+ const set = covered.get(el);
1343
+ if (!set) return false;
1344
+ return key === "box" ? [...set].some((p) => LAYOUT.test(p)) : set.has(key);
1345
+ };
1346
+ // How much of the first screen a box covers, in tenths of a percent.
1347
+ const coverOfScreen = (el) => {
1348
+ const b = el.getBoundingClientRect();
1349
+ const share = (Math.max(0, Math.min(b.right, W) - Math.max(b.left, 0)) * Math.max(0, Math.min(b.bottom, H) - Math.max(b.top, 0))) / (W * H);
1350
+ return Math.round(1000 * share) / 10;
1351
+ };
1352
+ // A canvas is read small: its pixels, drawn into a 32 px square.
1353
+ const canvases = [...document.querySelectorAll("canvas")].filter((c) => c.width > 0 && c.height > 0 && c.checkVisibility?.({ visibilityProperty: true })).slice(0, 8);
1354
+ const grab = (c) => {
1355
+ try {
1356
+ // A fresh square each time: one that has drawn an unreadable canvas stays unreadable.
1357
+ const scratch = document.createElement("canvas");
1358
+ scratch.width = scratch.height = 32;
1359
+ const sctx = scratch.getContext("2d", { willReadFrequently: true });
1360
+ sctx.drawImage(c, 0, 0, 32, 32);
1361
+ return sctx.getImageData(0, 0, 32, 32).data.join();
1362
+ } catch {
1363
+ return null;
1364
+ }
1365
+ };
1366
+ // What is found is grouped by what it is, so a hundred things one loop moves are one line.
1367
+ const groups = new Map();
1368
+ const emit = (item, el) => {
1369
+ const sig = JSON.stringify(item);
1370
+ const old = groups.get(sig);
1371
+ if (old) old.uses++;
1372
+ else groups.set(sig, { item, el, uses: 1 });
1373
+ };
1374
+ const script = (property, iteration, trigger) => ({ kind: "script", property, ms: null, delay: null, easing: null, iteration, trigger });
1375
+ const startX = scrollX, startY = scrollY;
1376
+ try {
1377
+ const load = [], pixels = [];
1378
+ const covers = canvases.map(coverOfScreen);
1379
+ for (const at of [0, 200, 400, 600]) {
1380
+ await until(at);
1381
+ load.push(take());
1382
+ pixels.push(canvases.map(grab));
1383
+ }
1384
+ // Something that moved and then held for the last step has either ended or the tab drew no frame
1385
+ // in that step (a slow machine). One more look, a little later, tells the two apart.
1386
+ const held = tracked.some((el, i) => {
1387
+ const rows = load.map((s) => s[i]);
1388
+ return !rows.some((r) => !r) && KEYS.some((key, k) => !rows.every((r) => r[k] === rows[0][k]) && rows[3][k] === rows[2][k]);
1389
+ });
1390
+ if (held && !late()) {
1391
+ await pause(250);
1392
+ await frame();
1393
+ load.push(take());
1394
+ }
1395
+ const looping = new Set();
1396
+ tracked.forEach((el, i) => {
1397
+ const rows = load.map((s) => s[i]);
1398
+ if (rows.some((r) => !r)) return;
1399
+ KEYS.forEach((key, k) => {
1400
+ if (rows.every((r) => r[k] === rows[0][k]) || isCovered(el, key)) return;
1401
+ if (key === "box" && layoutMoves) return;
1402
+ const loop = rows[3][k] !== rows[2][k] || (rows[4] !== undefined && rows[4][k] !== rows[3][k]);
1403
+ if (loop) looping.add(i + ":" + k);
1404
+ emit(script(key, loop ? "loop" : "once", "load"), el);
1405
+ });
1406
+ });
1407
+ // A canvas whose pixels differ between samples is playing; one the page does not let be read is counted, not guessed.
1408
+ canvases.forEach((c, j) => {
1409
+ const seen = pixels.map((p) => p[j]);
1410
+ if (seen.some((p) => p === null)) return void unread++;
1411
+ if (seen.some((p) => p !== seen[0])) emit({ kind: "canvas", cover: covers[j] }, c);
1412
+ });
1413
+ for (const v of document.querySelectorAll("video")) {
1414
+ if (v.paused || v.ended || v.readyState < 2 || !v.checkVisibility?.({ visibilityProperty: true })) continue;
1415
+ const b = v.getBoundingClientRect();
1416
+ if (b.width >= 2 && b.height >= 2) emit({ kind: "video", cover: coverOfScreen(v) }, v);
1417
+ }
1418
+ // Scrolled one screen in three steps. A sample taken before the first step, apart from the last
1419
+ // one of the load, shows what changes with time alone, which is not the scroll's.
1420
+ const run = Math.min(H, document.documentElement.scrollHeight - H - startY);
1421
+ if (!late() && run >= 40) {
1422
+ await pause(150);
1423
+ await frame();
1424
+ const still = take(), steps = [];
1425
+ for (const part of [1 / 3, 2 / 3, 1]) {
1426
+ if (late()) break;
1427
+ scrollTo({ left: startX, top: startY + run * part, behavior: "instant" });
1428
+ await pause(100);
1429
+ await frame();
1430
+ steps.push(take());
1431
+ }
1432
+ // A thing fixed or sticky changes its place by design: only what it does besides counts.
1433
+ const OWN = ["transform", "opacity", "translate", "rotate", "scale", "clip-path", "filter"];
1434
+ tracked.forEach((el, i) => {
1435
+ const was = load[load.length - 1][i], base = still[i];
1436
+ if (!was || !base) return;
1437
+ KEYS.forEach((key, k) => {
1438
+ if (was[k] !== base[k] || looping.has(i + ":" + k) || isCovered(el, key)) return;
1439
+ if ((pinned[i] && !OWN.includes(key)) || (key === "box" && layoutMoves)) return;
1440
+ if (steps.some((s) => s[i] && s[i][k] !== base[k])) emit(script(key, "once", "scroll"), el);
1441
+ });
1442
+ });
1443
+ }
1444
+ } finally {
1445
+ scrollTo({ left: startX, top: startY, behavior: "instant" });
1446
+ document.removeEventListener("transitionrun", onRun, true);
1447
+ document.removeEventListener("animationstart", onRun, true);
1448
+ }
1449
+ for (const { item, el, uses } of groups.values()) found.set("w|" + JSON.stringify(item), { ...item, on: describe(el), uses });
1450
+ };
1451
+ // A watch that fails leaves what was read from the style sheets as it is.
1452
+ try {
1453
+ await watchFrames();
1454
+ } catch {}
1455
+ const all = [...found.values()].sort((a, b) => b.uses - a.uses);
1456
+ return { items: all.slice(0, CAP), more: Math.max(0, all.length - CAP), unread };
1457
+ }
1458
+
1459
+ // Finish: shadows, filters, blend modes and textures of what shows on the first screen, each with
1460
+ // the share of the screen its elements cover (counted on the same 20 px grid as the pictures, so
1461
+ // overlaps count once). A pseudo-element is read only where its box can be worked out (positioned
1462
+ // absolutely or fixed). A noise or a tiled picture is a texture: an SVG filter made of feTurbulence,
1463
+ // or a small picture repeated over a quarter of the screen or more. Runs in the page.
1464
+ async function readFinish() {
1465
+ const W = innerWidth, H = innerHeight, LIMIT = 6000, CAP = 6;
1466
+ const CW = Math.ceil(W / 20), CH = Math.ceil(H / 20);
1467
+ const split = (v) => {
1468
+ const parts = [];
1469
+ let depth = 0, quote = "", at = 0;
1470
+ for (let i = 0; i < v.length; i++) {
1471
+ const c = v[i];
1472
+ if (quote) {
1473
+ if (c === "\\") i++;
1474
+ else if (c === quote) quote = "";
1475
+ } else if (c === '"' || c === "'") quote = c;
1476
+ else if (c === "(" || c === "[") depth++;
1477
+ else if (c === ")" || c === "]") depth--;
1478
+ else if (c === "," && depth === 0) (parts.push(v.slice(at, i).trim()), (at = i + 1));
1479
+ }
1480
+ parts.push(v.slice(at).trim());
1481
+ return parts.filter(Boolean);
1482
+ };
1483
+ const kinds = { shadow: new Map(), textShadow: new Map(), filter: new Map(), backdrop: new Map(), blend: new Map(), texture: new Map() };
1484
+ const mark = (kind, css, box, extra = {}) => {
1485
+ const g = kinds[kind].get(css) || { css, ...extra, cells: new Set(), uses: 0 };
1486
+ const [x, y, w, h] = box;
1487
+ for (let gx = Math.max(0, Math.floor(x / 20)); gx < Math.min(CW, Math.ceil((x + w) / 20)); gx++)
1488
+ for (let gy = Math.max(0, Math.floor(y / 20)); gy < Math.min(CH, Math.ceil((y + h) / 20)); gy++) g.cells.add(gx + "," + gy);
1489
+ g.uses++;
1490
+ kinds[kind].set(css, g);
1491
+ };
1492
+ const turbulent = (text) => /feTurbulence/i.test(text);
1493
+ const unpack = (data) => {
1494
+ try {
1495
+ return /;base64,/.test(data) ? atob(data.slice(data.indexOf(",") + 1)) : decodeURIComponent(data.slice(data.indexOf(",") + 1));
1496
+ } catch {
1497
+ return "";
1498
+ }
1499
+ };
1500
+ // A picture's address, short, and with no page words in it.
1501
+ const plain = (url) => (url.startsWith("data:") ? "url(data:" + url.slice(5, url.search(/[;,]/)) + ", " + url.length + " characters)" : "url(" + url.split(/[?#]/)[0].split("/").pop() + ")");
1502
+ const tiles = [];
1503
+ // What a box carries on its own: shadow, filter, backdrop filter, blend modes.
1504
+ const finish = (cs, box) => {
1505
+ if (cs.boxShadow !== "none") mark("shadow", cs.boxShadow, box);
1506
+ if (cs.filter !== "none") {
1507
+ const id = cs.filter.match(/url\(["']?[^"')]*#([^"')]+)/)?.[1];
1508
+ const shape = id && document.getElementById(id);
1509
+ if (shape && turbulent(shape.outerHTML)) mark("texture", "filter: url(#" + id + ")", box, { kind: "feTurbulence" });
1510
+ else mark("filter", cs.filter, box);
1511
+ }
1512
+ if (cs.backdropFilter && cs.backdropFilter !== "none") mark("backdrop", cs.backdropFilter, box);
1513
+ if (cs.mixBlendMode !== "normal") mark("blend", "mix-blend-mode: " + cs.mixBlendMode, box);
1514
+ if (cs.backgroundImage !== "none" && split(cs.backgroundBlendMode).some((m) => m !== "normal")) mark("blend", "background-blend-mode: " + cs.backgroundBlendMode, box);
1515
+ };
1516
+ // What its background pictures make: noise drawn as an SVG, or a small tile repeated over a wide box.
1517
+ const layers = (cs, box) => {
1518
+ const repeats = split(cs.backgroundRepeat), sizes = split(cs.backgroundSize);
1519
+ split(cs.backgroundImage).forEach((layer, i) => {
1520
+ const url = layer.match(/^url\((["']?)([\s\S]*)\1\)$/)?.[2];
1521
+ if (!url) return;
1522
+ const src = url.replace(/\\(.)/g, "$1");
1523
+ if (src.startsWith("data:") && turbulent(unpack(src))) return mark("texture", "background-image: " + plain(src), box, { kind: "feTurbulence" });
1524
+ if (/^no-repeat( no-repeat)?$/.test(repeats[i % repeats.length]) || box[2] * box[3] < 0.25 * W * H) return;
1525
+ tiles.push({ src, box, size: sizes[i % sizes.length], css: "background-image: " + plain(src) });
1526
+ });
1527
+ };
1528
+ // The first screen only, as the rest of the page is read: a box that is in it, that shows.
1529
+ const onScreen = (r) => r.width >= 2 && r.height >= 2 && r.top < H && r.bottom > 0 && r.left < W && r.right > 0;
1530
+ const shows = (el, cs) => cs.visibility !== "hidden" && cs.display !== "none" && Number(cs.opacity) > 0 && (!el.checkVisibility || el.checkVisibility({ opacityProperty: true, visibilityProperty: true }));
1531
+ const bare = (cs) => cs.backgroundImage === "none" && cs.backgroundColor === "rgba(0, 0, 0, 0)";
1532
+ const root = getComputedStyle(document.documentElement);
1533
+ let n = 0;
1534
+ for (const el of [document.body, ...document.body.querySelectorAll("*")]) {
1535
+ if (++n > LIMIT) break;
1536
+ const r = el.getBoundingClientRect(), cs = getComputedStyle(el);
1537
+ if (onScreen(r) && shows(el, cs)) {
1538
+ const box = [r.left, r.top, r.width, r.height];
1539
+ finish(cs, box);
1540
+ // The body's own background paints the whole canvas when the root has none.
1541
+ if (el !== document.body) layers(cs, box);
1542
+ else layers(cs, bare(root) ? [0, 0, W, H] : box);
1543
+ if (cs.textShadow !== "none") {
1544
+ const own = [...el.childNodes].filter((c) => c.nodeType === 3 && c.textContent.trim());
1545
+ if (own.length) {
1546
+ const range = document.createRange();
1547
+ range.setStartBefore(own[0]);
1548
+ range.setEndAfter(own.at(-1));
1549
+ const t = range.getBoundingClientRect();
1550
+ if (t.width >= 2) mark("textShadow", cs.textShadow, [t.left, t.top, t.width, t.height]);
1551
+ }
1552
+ }
1553
+ }
1554
+ // A pseudo-element has no box to ask for: where it is placed, its computed offsets and size are its box.
1555
+ for (const pseudo of ["::before", "::after"]) {
1556
+ const ps = getComputedStyle(el, pseudo);
1557
+ if (ps.display === "none" || ps.content === "none" || ps.content === "normal" || !/^(absolute|fixed)$/.test(ps.position) || Number(ps.opacity) === 0 || ps.visibility === "hidden") continue;
1558
+ const [left, top, w, h] = [ps.left, ps.top, ps.width, ps.height].map(parseFloat);
1559
+ if (![left, top, w, h].every(Number.isFinite) || !shows(el, cs)) continue;
1560
+ let ox = 0, oy = 0;
1561
+ if (ps.position === "absolute") {
1562
+ const home = cs.position !== "static" ? el : el.offsetParent;
1563
+ if (home && getComputedStyle(home).position !== "static") {
1564
+ const hr = home.getBoundingClientRect();
1565
+ [ox, oy] = [hr.left + home.clientLeft, hr.top + home.clientTop];
1566
+ }
1567
+ }
1568
+ const box = [ox + left, oy + top, w, h];
1569
+ if (!onScreen({ left: box[0], right: box[0] + w, top: box[1], bottom: box[1] + h, width: w, height: h })) continue;
1570
+ finish(ps, box);
1571
+ layers(ps, box);
1572
+ }
1573
+ }
1574
+ // The canvas takes the background of the root, or of the body when the root has none: a tile there covers the screen.
1575
+ layers(root, [0, 0, W, H]);
1576
+ // A tile is small if its size is given in px, or its picture is: asked of the page, with a time limit.
1577
+ const natural = new Map();
1578
+ await Promise.all(
1579
+ [...new Set(tiles.map((t) => t.src))].slice(0, 8).map(
1580
+ (src) =>
1581
+ new Promise((done) => {
1582
+ const img = new Image();
1583
+ const timer = setTimeout(done, 1200);
1584
+ img.onload = img.onerror = () => (clearTimeout(timer), natural.set(src, [img.naturalWidth, img.naturalHeight]), done());
1585
+ img.src = src;
1586
+ }),
1587
+ ),
1588
+ );
1589
+ for (const t of tiles) {
1590
+ const px = t.size.split(/\s+/).filter((v) => /px$/.test(v)).map(parseFloat);
1591
+ const [nw, nh] = natural.get(t.src) || [0, 0];
1592
+ const wide = px.length ? Math.max(...px) : Math.max(nw, nh);
1593
+ if (!(wide > 0 && wide <= 256)) continue;
1594
+ mark("texture", t.css, t.box, { kind: "tile", size: px.length ? t.size : nw + "x" + nh });
1595
+ }
1596
+ const out = {};
1597
+ let more = 0;
1598
+ for (const [kind, map] of Object.entries(kinds)) {
1599
+ more += Math.max(0, map.size - CAP);
1600
+ out[kind] = [...map.values()]
1601
+ .map(({ css, kind: how, size, cells, uses }) => ({ css, ...(how ? { kind: how } : {}), ...(size ? { size } : {}), cover: Math.round((1000 * cells.size) / (CW * CH)) / 10, uses }))
1602
+ .sort((a, b) => b.cover - a.cover || b.uses - a.uses)
1603
+ .slice(0, CAP);
1604
+ }
1605
+ return { kinds: out, more };
1606
+ }
1607
+ // A reading that fails (a page that blocks it) leaves its key null, never fails the page's other numbers.
1608
+ async function readOr(tab, fn) {
1609
+ try {
1610
+ return await tab.evaluate(`(${fn})()`);
1611
+ } catch {
1612
+ return null;
1613
+ }
1614
+ }
1615
+
1616
+ // An image is read in the tab as a data URL, so its pixels can be read back. No navigation per image.
1617
+ async function measureImage(tab, path) {
1618
+ const src = `data:${mime[extname(path).toLowerCase()]};base64,${readFileSync(resolve(path)).toString("base64")}`;
1619
+ return tab.evaluate(readImage(src));
1620
+ }
1621
+ // A page that is not the real site: an error status, a maintenance or bot-check page, or one that
1622
+ // says nothing and shows nothing. It is flagged, never dropped here: the eye confirms it.
1623
+ const NOT_THE_SITE = /\b(under maintenance|down for maintenance|scheduled maintenance|access denied|just a moment|checking your browser|verify you are (a )?human|are you a robot|attention required|enable javascript( and cookies)? to continue|page not found|404 not found|site (is )?(temporarily )?unavailable|domain (is )?for sale|this site can.t be reached)\b/i;
1624
+ // Words a real page can say too (a product that is coming soon): they count only on a page that says little else.
1625
+ const NOT_THE_SITE_IF_BARE = /\b(coming soon|launching soon|forbidden|under construction)\b/i;
1626
+ function notTheSite({ status = 0, words = 0, said = "", pictures = 0 }) {
1627
+ if (status >= 400) return `HTTP ${status}`;
1628
+ const m = String(said).slice(0, 600).match(NOT_THE_SITE) || (words < 30 && String(said).match(NOT_THE_SITE_IF_BARE));
1629
+ if (m && words < 400) return `says "${m[0].toLowerCase()}"`;
1630
+ if (!words && !(pictures > 5)) return "no text and no pictures, even after a second wait";
1631
+ return "";
1632
+ }
1633
+
1634
+ async function measurePage(tab, url) {
1635
+ await tab.call("Page.navigate", { url }, 40000);
1636
+ for (let i = 0; i < 100 && (await tab.evaluate("document.readyState")) !== "complete"; i++) await sleep(200);
1637
+ await sleep(wait);
1638
+ // The motion is read first, while its animations still run: what ends is ended just below.
1639
+ let motion = await readOr(tab, readMotion);
1640
+ // Animations that end (a headline that fades or slides in) are read as they end, never mid-way.
1641
+ // Ones that loop, and ones a script drives, are read as they are after the wait.
1642
+ await tab.evaluate(`(() => { for (const a of document.getAnimations()) { try { if (a.effect?.getComputedTiming().endTime !== Infinity) a.finish(); } catch {} } })()`);
1643
+ await sleep(300);
1644
+ let out = await tab.evaluate(readPage);
1645
+ // Nothing on it yet is often a loader: one more wait before it is called empty.
1646
+ if (!out.words && !(out.traits.pictures > 5)) {
1647
+ await sleep(Math.max(3000, wait / 2));
1648
+ out = await tab.evaluate(readPage);
1649
+ motion = (await readOr(tab, readMotion)) || motion;
1650
+ }
1651
+ out.motion = motion ? motion.items : null;
1652
+ out.motionMore = motion ? motion.more : null;
1653
+ out.unread = motion ? motion.unread : null;
1654
+ const finish = await readOr(tab, readFinish);
1655
+ out.finish = finish ? finish.kinds : null;
1656
+ out.finishMore = finish ? finish.more : null;
1657
+ out.flag = notTheSite({ status: out.status, words: out.words, said: out.said, pictures: out.traits.pictures });
1658
+ delete out.said;
1659
+ return out;
1660
+ }
1661
+
1662
+ const results = new Array(targets.length);
1663
+ const images = targets.map((t, i) => [t, i]).filter(([t]) => !isUrl(t));
1664
+ const pages = targets.map((t, i) => [t, i]).filter(([t]) => isUrl(t));
1665
+ const run = async (queue, measure) => {
1666
+ let tab;
1667
+ try {
1668
+ tab = await openTab();
1669
+ } catch (error) {
1670
+ for (let item = queue.shift(); item; item = queue.shift()) results[item[1]] = { target: item[0], error: error.message };
1671
+ return;
1672
+ }
1673
+ for (let item = queue.shift(); item; item = queue.shift()) {
1674
+ const [target, i] = item;
1675
+ try {
1676
+ results[i] = { target, ...(await measure(tab, target)) };
1677
+ } catch (error) {
1678
+ results[i] = { target, error: error.message };
1679
+ }
1680
+ }
1681
+ };
1682
+ const workers = [];
1683
+ if (images.length) workers.push(run(images, swatches ? measureSwatches : measureImage));
1684
+ for (let k = 0; k < Math.min(jobs, pages.length); k++) workers.push(run(pages, measurePage));
1685
+ await Promise.all(workers);
1686
+ ws.close();
1687
+
1688
+ const failed = results.filter((r) => r.error);
1689
+ for (const r of failed) console.error(`measure: ${r.target}: ${r.error}`);
1690
+ if (swatches) {
1691
+ console.log(JSON.stringify(results.map((r) => (r.error ? { target: r.target, error: r.error } : { target: r.target, swatches: r.swatches })), null, 1));
1692
+ } else if (profilesArg) {
1693
+ // Measurements are replaced, everything else a profile holds (the agent's tags, notes) is kept.
1694
+ const store = existsSync(profilesArg) ? JSON.parse(readFileSync(profilesArg, "utf8")) : { refs: {} };
1695
+ store.refs ||= {};
1696
+ const byTarget = new Map(results.filter((r) => !r.error).map((r) => [r.target, r]));
1697
+ const pageOf = (r) => {
1698
+ const texts = [...r.text].sort((a, b) => parseFloat(b.size) - parseFloat(a.size)).slice(0, 8);
1699
+ return { url: r.target, flag: r.flag || "", status: r.status, traits: r.traits, media: r.media, fonts: r.fonts, gradients: r.gradients, patterns: r.patterns, ground: r.ground, texts, motion: r.motion, motionMore: r.motionMore, finish: r.finish, finishMore: r.finishMore, unread: r.unread };
1700
+ };
1701
+ for (const t of targets.filter((x) => !isUrl(x))) {
1702
+ const r = byTarget.get(t);
1703
+ if (!r) continue;
1704
+ const name = nameOf(t);
1705
+ const link = links.get(name);
1706
+ const page = link && byTarget.get(link);
1707
+ const old = store.refs[name] || {};
1708
+ store.refs[name] = { ...old, shot: t, link: link || old.link || null, image: { traits: r.traits, figure: r.figure, common: r.common, loud: r.loud, ...(r.frame ? { frame: r.frame } : {}) }, page: page ? pageOf(page) : old.page || null };
1709
+ }
1710
+ mkdirSync(dirname(resolve(profilesArg)), { recursive: true });
1711
+ writeFileSync(profilesArg, `${JSON.stringify(store, null, 1)}\n`);
1712
+ const n = Object.keys(store.refs).length;
1713
+ const withPage = Object.values(store.refs).filter((p) => p.page).length;
1714
+ const tagged = Object.values(store.refs).filter((p) => p.tags).length;
1715
+ console.log(`profiles: ${profilesArg}, ${n} references, ${withPage} with their page, ${tagged} tagged`);
1716
+ } else if (tsv) {
1717
+ const cols = ["tone", "lum", "empty", "loud", "busy", "ground", "display", "body", "scale", "pictures", "margin", "radius", "lettering", "gradient", "pattern", "icons", "blocks", "align", "flag"];
1718
+ // name: the reference's name, which for a folder of frames is the folder, not the frame in ref.
1719
+ const lines = [["ref", ...cols, "name"].join("\t")];
1720
+ for (const r of results) if (!r.error) lines.push([r.target, ...cols.map((c) => (c === "flag" ? r.flag : r.traits?.[c]) ?? ""), isUrl(r.target) ? "" : nameOf(r.target)].join("\t"));
1721
+ console.log(lines.join("\n"));
1722
+ } else if (targets.length === 1) {
1723
+ if (failed.length) process.exit(1);
1724
+ const { target, ...one } = results[0];
1725
+ console.log(JSON.stringify(one, null, 1));
1726
+ } else console.log(JSON.stringify(results, null, 1));
1727
+ // What was measured is printed or written above; a non-zero exit says some input was not.
1728
+ process.exit(failed.length ? 1 : 0);