@jonandev/longbeard 0.11.2 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +3 -4
- package/CHANGELOG.md +67 -0
- package/README.md +63 -43
- package/beard.json +113 -26
- package/bin/long-beard.js +172 -36
- package/package.json +1 -1
- package/skills/design/SKILL.md +51 -126
- package/skills/design-brief/SKILL.md +146 -0
- package/skills/design-brief/references/graphic.md +59 -0
- package/skills/design-check/SKILL.md +27 -11
- package/skills/design-check/references/design-rules.md +21 -7
- package/skills/design-check/scripts/capture.mjs +121 -37
- package/skills/design-check/scripts/contrast.mjs +23 -9
- package/skills/design-check/scripts/rules.mjs +613 -0
- package/skills/design-check/scripts/screen-contrast.mjs +428 -0
- package/skills/design-check/scripts/tokens.mjs +346 -0
- package/skills/design-content/SKILL.md +118 -0
- package/skills/design-content/scripts/contact-sheet.mjs +259 -0
- package/skills/design-content/scripts/pictures.mjs +197 -0
- package/skills/design-direction/SKILL.md +115 -200
- package/skills/design-direction/references/controls.md +58 -0
- package/skills/{design → design-direction}/references/design-rules.md +21 -7
- package/skills/design-direction/references/five-second.md +47 -0
- package/skills/design-direction/references/full-build.md +19 -0
- package/skills/design-direction/references/graphic.md +35 -0
- package/skills/design-direction/references/grid.md +114 -0
- package/skills/design-direction/references/library.md +75 -0
- package/skills/design-direction/references/screen-template.html +233 -0
- package/skills/design-direction/references/subject.md +33 -0
- package/skills/design-direction/scripts/capture.mjs +121 -37
- package/skills/design-direction/scripts/contact-sheet.mjs +18 -7
- package/skills/design-direction/scripts/fonts.mjs +276 -0
- package/skills/design-direction/scripts/layout-diff.mjs +118 -0
- package/skills/design-direction/scripts/measure.mjs +1728 -0
- package/skills/design-direction/scripts/moodboard.mjs +123 -32
- package/skills/design-direction/scripts/picture-cast.mjs +270 -0
- package/skills/design-direction/scripts/pictures.mjs +197 -0
- package/skills/design-direction/scripts/screen-contrast.mjs +428 -0
- package/skills/design-direction/scripts/sheet.mjs +67 -0
- package/skills/design-direction/scripts/subject-colours.mjs +410 -0
- package/skills/design-families/SKILL.md +138 -0
- package/skills/design-families/scripts/contact-sheet.mjs +259 -0
- package/skills/design-families/scripts/families.mjs +606 -0
- package/skills/design-families/scripts/measure.mjs +1728 -0
- package/skills/design-families/scripts/moodboard.mjs +467 -0
- package/skills/design-families/scripts/tag.mjs +289 -0
- package/skills/design-figma/SKILL.md +69 -0
- package/skills/design-figma/references/graphic.md +26 -0
- package/skills/design-identity/SKILL.md +134 -0
- package/skills/design-identity/references/graphic.md +8 -0
- package/skills/design-identity/references/identity-board.html +140 -0
- package/skills/{design → design-identity}/scripts/capture.mjs +121 -37
- package/skills/design-identity/scripts/colours.mjs +213 -0
- package/skills/design-identity/scripts/contrast.mjs +41 -0
- package/skills/design-identity/scripts/fonts.mjs +276 -0
- package/skills/design-identity/scripts/measure.mjs +1728 -0
- package/skills/design-identity/scripts/sheet.mjs +67 -0
- package/skills/design-identity/scripts/subject-colours.mjs +410 -0
- package/skills/design-moodboard/SKILL.md +184 -0
- package/skills/design-moodboard/references/graphic.md +25 -0
- package/skills/{design-direction → design-moodboard}/references/sources.md +17 -11
- package/skills/design-moodboard/scripts/capture.mjs +893 -0
- package/skills/design-moodboard/scripts/contact-sheet.mjs +259 -0
- package/skills/design-moodboard/scripts/crops.mjs +256 -0
- package/skills/design-moodboard/scripts/dribbble-cards.mjs +418 -0
- package/skills/design-moodboard/scripts/families.mjs +606 -0
- package/skills/design-moodboard/scripts/group.mjs +221 -0
- package/skills/design-moodboard/scripts/measure.mjs +1728 -0
- package/skills/design-moodboard/scripts/moodboard.mjs +467 -0
- package/skills/{design-direction → design-moodboard}/scripts/picker.mjs +121 -20
- package/skills/design-moodboard/scripts/pictures.mjs +197 -0
- package/skills/design-moodboard/scripts/tag.mjs +289 -0
- package/skills/design-prototype/SKILL.md +149 -0
- package/skills/design-prototype/references/design-md-template.md +82 -0
- package/skills/design-prototype/references/design-rules.md +203 -0
- package/skills/design-prototype/references/five-second.md +47 -0
- package/skills/design-prototype/references/graphic.md +27 -0
- package/skills/design-prototype/scripts/capture.mjs +893 -0
- package/skills/design-prototype/scripts/contrast.mjs +41 -0
- package/skills/design-prototype/scripts/links.mjs +308 -0
- package/skills/design-prototype/scripts/pictures.mjs +197 -0
- package/skills/design-prototype/scripts/rules.mjs +613 -0
- package/skills/design-prototype/scripts/screen-contrast.mjs +428 -0
- package/skills/design-prototype/scripts/sheet.mjs +67 -0
- package/skills/design-prototype/scripts/tokens.mjs +346 -0
- package/skills/design-wordmark/SKILL.md +65 -0
- package/skills/design-wordmark/scripts/capture.mjs +893 -0
- package/skills/design-wordmark/scripts/sheet.mjs +67 -0
- package/skills/idea/SKILL.md +13 -7
- package/skills/idea/references/graphic.md +64 -0
- package/skills/design/references/design-md-template.md +0 -58
- package/skills/design/scripts/contrast.mjs +0 -27
- package/skills/design-direction/scripts/dribbble-cards.mjs +0 -356
|
@@ -0,0 +1,893 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Full-page capture. Unsticks fixed/sticky chrome first so Chrome does not
|
|
3
|
+
// repeat the same fold. Node 22+. Uses an installed Chrome/Edge/Chromium.
|
|
4
|
+
//
|
|
5
|
+
// node capture.mjs <url> --out .longbeard/design/moodboard/refs/name.jpg
|
|
6
|
+
// node capture.mjs <url> --out .longbeard/design/moodboard/refs/name.jpg --review /tmp/name-review.jpg
|
|
7
|
+
// node capture.mjs <url> --out .longbeard/design/moodboard/refs/name.jpg --clip x,y,w,h
|
|
8
|
+
// node capture.mjs <url> --out .longbeard/design/moodboard/refs/name.jpg --clip-selector "main"
|
|
9
|
+
// node capture.mjs <url> --out /tmp/mobile.png --width 390
|
|
10
|
+
// node capture.mjs http://localhost:3000/app --out /tmp/app.png --cookie "session=abc; theme=dark" --strict
|
|
11
|
+
//
|
|
12
|
+
// A page that ends up at another address (a login, or a site's canonical
|
|
13
|
+
// www) is named on stderr. With --strict that is exit 1, so a 0 means the
|
|
14
|
+
// shot is of the page asked for.
|
|
15
|
+
// node capture.mjs file:///abs/path/moodboard.html --out /tmp/moodboard.jpg
|
|
16
|
+
// node capture.mjs file:///abs/path/shot.jpg --out .longbeard/design/moodboard/refs/name.jpg --clip x,y,w,h
|
|
17
|
+
//
|
|
18
|
+
// Before the shot it waits out loaders: until no loader covers the screen and
|
|
19
|
+
// the screen is not one flat colour and the network is quiet, for at most --wait ms (15 s on the web,
|
|
20
|
+
// 2 s for files and localhost). If a full page comes back blank at the top
|
|
21
|
+
// where the screen was not (a canvas that redraws only what is on screen),
|
|
22
|
+
// it keeps the screen it saw as the shot, the full page beside it as
|
|
23
|
+
// <name>-full.jpg, and says so.
|
|
24
|
+
//
|
|
25
|
+
// Motion: --frames N writes N screen-sized frames, --every ms apart (500), to
|
|
26
|
+
// the folder --out names: 01-00000ms.jpg, 02-00500ms.jpg… Without --scroll they
|
|
27
|
+
// start as the page opens, so the loader and the intro are in them. With
|
|
28
|
+
// --scroll they start once it has loaded, and each frame scrolls half a
|
|
29
|
+
// screen by the wheel, so scroll-driven motion plays.
|
|
30
|
+
// node capture.mjs <url> --out .longbeard/design/moodboard/refs/name-intro --frames 12
|
|
31
|
+
// node capture.mjs <url> --out .longbeard/design/moodboard/refs/name-scroll --frames 12 --every 400 --scroll
|
|
32
|
+
//
|
|
33
|
+
// --click "css" clicks that element once the page has loaded, as a person
|
|
34
|
+
// would. Alone it keeps the screen after the click (an open menu). With
|
|
35
|
+
// --frames the first frame is before the click and the rest record what the
|
|
36
|
+
// click does (a menu opening, a page transition).
|
|
37
|
+
// node capture.mjs <url> --out .longbeard/design/moodboard/refs/name-menu.jpg --click "button[aria-label*=menu i]"
|
|
38
|
+
// node capture.mjs <url> --out .longbeard/design/moodboard/refs/name-menu-open --frames 10 --every 150 --click "header button"
|
|
39
|
+
import { spawn } from "node:child_process";
|
|
40
|
+
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
41
|
+
import { tmpdir } from "node:os";
|
|
42
|
+
import { dirname, join, resolve } from "node:path";
|
|
43
|
+
import { fileURLToPath } from "node:url";
|
|
44
|
+
import { inflateSync } from "node:zlib";
|
|
45
|
+
|
|
46
|
+
const args = process.argv.slice(2);
|
|
47
|
+
const flag = (name, def) => {
|
|
48
|
+
const i = args.indexOf(`--${name}`);
|
|
49
|
+
if (i === -1) return def;
|
|
50
|
+
const v = args[i + 1];
|
|
51
|
+
// A flag that needs a value and has none is a usage error, not a plain shot.
|
|
52
|
+
if (v === undefined || /^--[a-z]/.test(v)) {
|
|
53
|
+
console.error(`--${name} needs a value`);
|
|
54
|
+
process.exit(2);
|
|
55
|
+
}
|
|
56
|
+
args.splice(i, 2);
|
|
57
|
+
return v;
|
|
58
|
+
};
|
|
59
|
+
const url = args[0];
|
|
60
|
+
const outArg = flag("out", "") || "";
|
|
61
|
+
const reviewArg = flag("review", "") || "";
|
|
62
|
+
const clipArg = flag("clip", "") || "";
|
|
63
|
+
const clipSelector = flag("clip-selector", "") || "";
|
|
64
|
+
// Sent with every request to the page's own origin, as a logged-in browser would.
|
|
65
|
+
const cookieArg = flag("cookie", "") || "";
|
|
66
|
+
const bool = (name) => {
|
|
67
|
+
const i = args.indexOf(`--${name}`);
|
|
68
|
+
if (i !== -1) args.splice(i, 1);
|
|
69
|
+
return i !== -1;
|
|
70
|
+
};
|
|
71
|
+
const strict = bool("strict");
|
|
72
|
+
const scrollFrames = bool("scroll");
|
|
73
|
+
const framesArg = flag("frames", "") || "";
|
|
74
|
+
// Clicks this element once the page has loaded: a menu button, a link, a tab.
|
|
75
|
+
const clickArg = flag("click", "") || "";
|
|
76
|
+
const everyArg = flag("every", "") || "";
|
|
77
|
+
const waitArg = flag("wait", "") || "";
|
|
78
|
+
// Below 768 the page gets a phone viewport: mobile layout, 2x pixels.
|
|
79
|
+
const width = Math.round(Number(flag("width", "1440")));
|
|
80
|
+
if (!url || !/^(https?|file):\/\//.test(url) || !outArg) {
|
|
81
|
+
console.error(
|
|
82
|
+
'usage: node capture.mjs <https://url | file:///path> --out .longbeard/design/moodboard/refs/name.jpg [--review /tmp/name-review.jpg] [--clip x,y,w,h | --clip-selector "css"] [--width 390] [--cookie "name=value; …"] [--strict] [--wait ms] [--click "css"] [--frames N [--every ms] [--scroll]]',
|
|
83
|
+
);
|
|
84
|
+
process.exit(2);
|
|
85
|
+
}
|
|
86
|
+
if (!Number.isFinite(width) || width < 200 || width > 3840) {
|
|
87
|
+
console.error("width must be a number from 200 to 3840");
|
|
88
|
+
process.exit(2);
|
|
89
|
+
}
|
|
90
|
+
const frames = framesArg ? Number(framesArg) : 0;
|
|
91
|
+
const every = everyArg ? Number(everyArg) : 500;
|
|
92
|
+
if (framesArg && (!Number.isInteger(frames) || frames < 2 || frames > 60)) {
|
|
93
|
+
console.error("frames must be a whole number from 2 to 60");
|
|
94
|
+
process.exit(2);
|
|
95
|
+
}
|
|
96
|
+
if (!Number.isInteger(every) || every < 100 || every > 10000) {
|
|
97
|
+
console.error("every must be a whole number of ms from 100 to 10000");
|
|
98
|
+
process.exit(2);
|
|
99
|
+
}
|
|
100
|
+
if ((everyArg || scrollFrames) && !frames) {
|
|
101
|
+
console.error("--every and --scroll go with --frames");
|
|
102
|
+
process.exit(2);
|
|
103
|
+
}
|
|
104
|
+
if (clickArg && scrollFrames) {
|
|
105
|
+
console.error("pass --click or --scroll, not both");
|
|
106
|
+
process.exit(2);
|
|
107
|
+
}
|
|
108
|
+
if ((frames || clickArg) && (reviewArg || clipArg || clipSelector)) {
|
|
109
|
+
console.error("--frames and --click take whole screens: drop --review, --clip and --clip-selector");
|
|
110
|
+
process.exit(2);
|
|
111
|
+
}
|
|
112
|
+
// A local page has no loader worth waiting for, so a sparse screen costs little.
|
|
113
|
+
// A full page stops at 14000 px; our own files (a picker, a moodboard) run to 30000 px a part,
|
|
114
|
+
// and a longer one is kept in parts (see below).
|
|
115
|
+
const tallest = /^file:/.test(url) ? 30000 : 14000;
|
|
116
|
+
const local = /^file:/.test(url) || /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/.test(url);
|
|
117
|
+
const maxWait = waitArg ? Number(waitArg) : local ? 2000 : 15000;
|
|
118
|
+
if (!Number.isFinite(maxWait) || maxWait < 0 || maxWait > 120000) {
|
|
119
|
+
console.error("wait must be ms from 0 to 120000");
|
|
120
|
+
process.exit(2);
|
|
121
|
+
}
|
|
122
|
+
const mobile = width < 768;
|
|
123
|
+
const height = mobile ? 844 : 900;
|
|
124
|
+
if (clipArg && clipSelector) {
|
|
125
|
+
console.error("pass --clip or --clip-selector, not both");
|
|
126
|
+
process.exit(2);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// A relative path is relative to the folder the command runs in.
|
|
130
|
+
function resolveOut(path) {
|
|
131
|
+
return path ? resolve(path) : "";
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const out = resolveOut(outArg);
|
|
135
|
+
const reviewOut = resolveOut(reviewArg);
|
|
136
|
+
|
|
137
|
+
// A page that is not there would otherwise be a black shot that looks like a result.
|
|
138
|
+
if (/^file:/.test(url)) {
|
|
139
|
+
let file = "";
|
|
140
|
+
try {
|
|
141
|
+
file = fileURLToPath(url.replace(/[?#].*$/, ""));
|
|
142
|
+
} catch {}
|
|
143
|
+
if (!file || !existsSync(file)) {
|
|
144
|
+
console.error(`no such file: ${file || url}`);
|
|
145
|
+
process.exit(1);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function parseClip(s) {
|
|
150
|
+
if (!s) return null;
|
|
151
|
+
const parts = s.split(",").map((n) => Number(n.trim()));
|
|
152
|
+
if (parts.length !== 4 || parts.some((n) => !Number.isFinite(n) || n < 0)) {
|
|
153
|
+
console.error("clip must be x,y,w,h (non-negative numbers)");
|
|
154
|
+
process.exit(2);
|
|
155
|
+
}
|
|
156
|
+
const [x, y, w, h] = parts;
|
|
157
|
+
if (w < 1 || h < 1) {
|
|
158
|
+
console.error("clip width and height must be >= 1");
|
|
159
|
+
process.exit(2);
|
|
160
|
+
}
|
|
161
|
+
return { x, y, width: w, height: h, scale: 1 };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const clip = parseClip(clipArg);
|
|
165
|
+
|
|
166
|
+
function findChrome() {
|
|
167
|
+
const env = process.env.CHROME_PATH;
|
|
168
|
+
// CHROME_PATH=none: run as if no browser were installed (a quick test run).
|
|
169
|
+
if (env === "none") return null;
|
|
170
|
+
if (env && existsSync(env)) return env;
|
|
171
|
+
const home = process.env.HOME || process.env.USERPROFILE || "";
|
|
172
|
+
const local = process.env.LOCALAPPDATA || "";
|
|
173
|
+
const pf = process.env.PROGRAMFILES || "C:\\Program Files";
|
|
174
|
+
const pf86 = process.env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)";
|
|
175
|
+
const candidates = [
|
|
176
|
+
join(pf, "Google/Chrome/Application/chrome.exe"),
|
|
177
|
+
join(pf86, "Google/Chrome/Application/chrome.exe"),
|
|
178
|
+
join(local, "Google/Chrome/Application/chrome.exe"),
|
|
179
|
+
join(pf, "Microsoft/Edge/Application/msedge.exe"),
|
|
180
|
+
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
181
|
+
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
182
|
+
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
|
183
|
+
join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
|
|
184
|
+
"/usr/bin/google-chrome",
|
|
185
|
+
"/usr/bin/google-chrome-stable",
|
|
186
|
+
"/usr/bin/chromium",
|
|
187
|
+
"/usr/bin/chromium-browser",
|
|
188
|
+
];
|
|
189
|
+
return candidates.find((path) => path && existsSync(path)) || null;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
193
|
+
|
|
194
|
+
const exe = findChrome();
|
|
195
|
+
if (!exe) {
|
|
196
|
+
console.error("No Chrome/Edge/Chromium found. Install one or set CHROME_PATH.");
|
|
197
|
+
process.exit(1);
|
|
198
|
+
}
|
|
199
|
+
if (typeof WebSocket === "undefined") {
|
|
200
|
+
console.error("Node 22+ is required.");
|
|
201
|
+
process.exit(1);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const dir = mkdtempSync(join(tmpdir(), "hunt-chrome-"));
|
|
205
|
+
let proc;
|
|
206
|
+
const drop = () => {
|
|
207
|
+
try {
|
|
208
|
+
if (proc?.pid) process.kill(proc.pid, "SIGKILL");
|
|
209
|
+
} catch {}
|
|
210
|
+
try {
|
|
211
|
+
rmSync(dir, { recursive: true, force: true });
|
|
212
|
+
} catch {}
|
|
213
|
+
};
|
|
214
|
+
process.once("exit", drop);
|
|
215
|
+
// An interrupt or a harness timeout must not leave Chrome or its profile behind.
|
|
216
|
+
for (const [sig, code] of [["SIGINT", 130], ["SIGTERM", 143]]) {
|
|
217
|
+
process.once(sig, () => {
|
|
218
|
+
drop();
|
|
219
|
+
process.exit(code);
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
proc = spawn(
|
|
224
|
+
exe,
|
|
225
|
+
[
|
|
226
|
+
"--headless=new",
|
|
227
|
+
"--remote-debugging-port=0",
|
|
228
|
+
`--user-data-dir=${dir}`,
|
|
229
|
+
"--no-first-run",
|
|
230
|
+
"--hide-scrollbars",
|
|
231
|
+
"--mute-audio",
|
|
232
|
+
"--force-color-profile=srgb",
|
|
233
|
+
// Without a GPU, Chrome no longer falls back to software WebGL on its own.
|
|
234
|
+
"--enable-unsafe-swiftshader",
|
|
235
|
+
`--window-size=${width},${height}`,
|
|
236
|
+
"about:blank",
|
|
237
|
+
],
|
|
238
|
+
{ stdio: ["ignore", "ignore", "pipe"] },
|
|
239
|
+
);
|
|
240
|
+
proc.on("error", (e) => {
|
|
241
|
+
console.error(`could not start ${exe}: ${e.message}`);
|
|
242
|
+
process.exit(1);
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
let buf = "";
|
|
246
|
+
const wsUrl = await new Promise((resolveWs, reject) => {
|
|
247
|
+
const t = setTimeout(() => reject(new Error("Chrome did not start")), 20000);
|
|
248
|
+
proc.stderr.on("data", (d) => {
|
|
249
|
+
buf += d.toString();
|
|
250
|
+
const m = buf.match(/DevTools listening on (ws:\/\/[^\s]+)/);
|
|
251
|
+
if (m) {
|
|
252
|
+
clearTimeout(t);
|
|
253
|
+
resolveWs(m[1]);
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
proc.on("exit", (code) => {
|
|
257
|
+
clearTimeout(t);
|
|
258
|
+
reject(new Error(`Chrome exited ${code}`));
|
|
259
|
+
});
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
const ws = new WebSocket(wsUrl);
|
|
263
|
+
await new Promise((res, rej) => {
|
|
264
|
+
const t = setTimeout(() => rej(new Error("CDP socket did not open")), 10000);
|
|
265
|
+
ws.onopen = () => {
|
|
266
|
+
clearTimeout(t);
|
|
267
|
+
res();
|
|
268
|
+
};
|
|
269
|
+
ws.onerror = () => {
|
|
270
|
+
clearTimeout(t);
|
|
271
|
+
rej(new Error("CDP socket failed"));
|
|
272
|
+
};
|
|
273
|
+
});
|
|
274
|
+
let nextId = 1;
|
|
275
|
+
const pending = new Map();
|
|
276
|
+
// Requests in flight, so the wait can tell a loader still fetching its assets.
|
|
277
|
+
// A request open for over 10 s is a stream or a poll, not a load.
|
|
278
|
+
const inflight = new Map();
|
|
279
|
+
let lastNetwork = Date.now();
|
|
280
|
+
ws.onmessage = (ev) => {
|
|
281
|
+
const msg = JSON.parse(typeof ev.data === "string" ? ev.data : Buffer.from(ev.data).toString());
|
|
282
|
+
// A hot-reload stream or a socket stays open by design, so it is not a load.
|
|
283
|
+
if (msg.method === "Network.requestWillBeSent" && !/^(EventSource|WebSocket)$/.test(msg.params.type || "")) {
|
|
284
|
+
inflight.set(msg.params.requestId, Date.now());
|
|
285
|
+
lastNetwork = Date.now();
|
|
286
|
+
} else if (msg.method === "Network.loadingFinished" || msg.method === "Network.loadingFailed") {
|
|
287
|
+
inflight.delete(msg.params.requestId);
|
|
288
|
+
lastNetwork = Date.now();
|
|
289
|
+
}
|
|
290
|
+
// An alert, confirm or beforeunload prompt holds the page until it is answered.
|
|
291
|
+
if (msg.method === "Page.javascriptDialogOpening") {
|
|
292
|
+
send("Page.handleJavaScriptDialog", { accept: false }, msg.sessionId).catch(() => {});
|
|
293
|
+
}
|
|
294
|
+
if (msg.id && pending.has(msg.id)) {
|
|
295
|
+
const { resolve: ok, reject: bad } = pending.get(msg.id);
|
|
296
|
+
pending.delete(msg.id);
|
|
297
|
+
if (msg.error) bad(new Error(msg.error.message));
|
|
298
|
+
else ok(msg.result);
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
// If Chrome goes away, every call waiting on it fails now, not at its time limit.
|
|
302
|
+
ws.onclose = () => {
|
|
303
|
+
for (const { reject: bad } of [...pending.values()]) bad(new Error("Chrome closed the connection"));
|
|
304
|
+
};
|
|
305
|
+
const send = (method, params = {}, sessionId, timeoutMs = 30000) => {
|
|
306
|
+
const id = nextId++;
|
|
307
|
+
return new Promise((resolveSend, reject) => {
|
|
308
|
+
const timer = setTimeout(() => {
|
|
309
|
+
pending.delete(id);
|
|
310
|
+
reject(new Error(`CDP timeout: ${method}`));
|
|
311
|
+
}, timeoutMs);
|
|
312
|
+
pending.set(id, {
|
|
313
|
+
resolve: (v) => {
|
|
314
|
+
clearTimeout(timer);
|
|
315
|
+
resolveSend(v);
|
|
316
|
+
},
|
|
317
|
+
reject: (e) => {
|
|
318
|
+
clearTimeout(timer);
|
|
319
|
+
reject(e);
|
|
320
|
+
},
|
|
321
|
+
});
|
|
322
|
+
ws.send(JSON.stringify(sessionId ? { id, method, params, sessionId } : { id, method, params }));
|
|
323
|
+
});
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
const { targetId } = await send("Target.createTarget", { url: "about:blank" });
|
|
327
|
+
const { sessionId } = await send("Target.attachToTarget", { targetId, flatten: true });
|
|
328
|
+
const page = (method, params, timeoutMs) => send(method, params, sessionId, timeoutMs);
|
|
329
|
+
|
|
330
|
+
await page("Page.enable");
|
|
331
|
+
await page("Runtime.enable");
|
|
332
|
+
await page("Network.enable");
|
|
333
|
+
await page("Emulation.setDeviceMetricsOverride", {
|
|
334
|
+
width,
|
|
335
|
+
height,
|
|
336
|
+
deviceScaleFactor: mobile ? 2 : 1,
|
|
337
|
+
mobile,
|
|
338
|
+
});
|
|
339
|
+
// Chrome centres an image file and shrinks it to the window. A page that holds
|
|
340
|
+
// it at full size from 0,0 makes --clip x,y,w,h the image's own pixels.
|
|
341
|
+
let target = url;
|
|
342
|
+
if (/^file:\/\/.*\.(png|jpe?g|webp|gif)$/i.test(url)) {
|
|
343
|
+
target = `file://${join(dir, "image.html")}`;
|
|
344
|
+
writeFileSync(join(dir, "image.html"), `<!doctype html><body style="margin:0;background:#000"><img src="${url.replace(/"/g, "%22")}" style="display:block">`);
|
|
345
|
+
}
|
|
346
|
+
if (cookieArg && /^https?:/.test(url)) {
|
|
347
|
+
const cookies = cookieArg
|
|
348
|
+
.split(";")
|
|
349
|
+
.map((pair) => pair.trim())
|
|
350
|
+
.filter(Boolean)
|
|
351
|
+
.map((pair) => {
|
|
352
|
+
const at = pair.indexOf("=");
|
|
353
|
+
return { name: pair.slice(0, at), value: pair.slice(at + 1), url: new URL(url).origin };
|
|
354
|
+
});
|
|
355
|
+
if (cookies.some((cookie) => !cookie.name)) {
|
|
356
|
+
console.error('cookie must be "name=value; name=value"');
|
|
357
|
+
drop();
|
|
358
|
+
process.exit(2);
|
|
359
|
+
}
|
|
360
|
+
await page("Network.setCookies", { cookies });
|
|
361
|
+
}
|
|
362
|
+
const evalValue = async (expression, timeoutMs) =>
|
|
363
|
+
(await page("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true }, timeoutMs)).result?.value;
|
|
364
|
+
|
|
365
|
+
// Share of a PNG's pixels in its most common colour, so 1 is one flat colour.
|
|
366
|
+
// Chrome writes 8-bit RGB or RGBA, not interlaced; anything else counts as not flat.
|
|
367
|
+
function flatShare(png) {
|
|
368
|
+
if (png.readUInt32BE(12) !== 0x49484452) return 0;
|
|
369
|
+
const w = png.readUInt32BE(16);
|
|
370
|
+
const h = png.readUInt32BE(20);
|
|
371
|
+
const depth = png[24];
|
|
372
|
+
const type = png[25];
|
|
373
|
+
const bpp = type === 6 ? 4 : type === 2 ? 3 : 0;
|
|
374
|
+
if (depth !== 8 || !bpp || png[28] !== 0) return 0;
|
|
375
|
+
const chunks = [];
|
|
376
|
+
for (let at = 8; at < png.length; ) {
|
|
377
|
+
const len = png.readUInt32BE(at);
|
|
378
|
+
const kind = png.toString("latin1", at + 4, at + 8);
|
|
379
|
+
if (kind === "IDAT") chunks.push(png.subarray(at + 8, at + 8 + len));
|
|
380
|
+
at += len + 12;
|
|
381
|
+
}
|
|
382
|
+
const raw = inflateSync(Buffer.concat(chunks));
|
|
383
|
+
const stride = w * bpp;
|
|
384
|
+
let prev = Buffer.alloc(stride);
|
|
385
|
+
const counts = new Map();
|
|
386
|
+
for (let y = 0; y < h; y++) {
|
|
387
|
+
const filter = raw[y * (stride + 1)];
|
|
388
|
+
const line = Buffer.from(raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1)));
|
|
389
|
+
for (let i = 0; i < stride; i++) {
|
|
390
|
+
const a = i >= bpp ? line[i - bpp] : 0;
|
|
391
|
+
const b = prev[i];
|
|
392
|
+
const c = i >= bpp ? prev[i - bpp] : 0;
|
|
393
|
+
let add = 0;
|
|
394
|
+
if (filter === 1) add = a;
|
|
395
|
+
else if (filter === 2) add = b;
|
|
396
|
+
else if (filter === 3) add = (a + b) >> 1;
|
|
397
|
+
else if (filter === 4) {
|
|
398
|
+
const p = a + b - c;
|
|
399
|
+
const pa = Math.abs(p - a);
|
|
400
|
+
const pb = Math.abs(p - b);
|
|
401
|
+
const pc = Math.abs(p - c);
|
|
402
|
+
add = pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
|
|
403
|
+
}
|
|
404
|
+
line[i] = (line[i] + add) & 255;
|
|
405
|
+
}
|
|
406
|
+
for (let i = 0; i < stride; i += bpp) {
|
|
407
|
+
const key = ((line[i] >> 3) << 10) | ((line[i + 1] >> 3) << 5) | (line[i + 2] >> 3);
|
|
408
|
+
counts.set(key, (counts.get(key) || 0) + 1);
|
|
409
|
+
}
|
|
410
|
+
prev = line;
|
|
411
|
+
}
|
|
412
|
+
return Math.max(...counts.values()) / (w * h);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// How flat the screen is: a small PNG of what a person sees right now, or of
|
|
416
|
+
// the top of the full page once it has been laid out for the full shot.
|
|
417
|
+
const FLAT = 0.985;
|
|
418
|
+
const screenFlat = async (beyond = false) => {
|
|
419
|
+
const { data } = await page(
|
|
420
|
+
"Page.captureScreenshot",
|
|
421
|
+
{ format: "png", clip: { x: 0, y: 0, width, height, scale: 0.25 }, captureBeyondViewport: beyond },
|
|
422
|
+
20000,
|
|
423
|
+
);
|
|
424
|
+
return flatShare(Buffer.from(data, "base64"));
|
|
425
|
+
};
|
|
426
|
+
|
|
427
|
+
// A loader is a fixed or absolute layer named like one that covers most of
|
|
428
|
+
// the screen, or a visible count to 100%. A canvas or a video is the page.
|
|
429
|
+
const loaderCheck = `(() => {
|
|
430
|
+
const vw = innerWidth, vh = innerHeight;
|
|
431
|
+
const named = /(^|[-_\\s])(pre-?)?load(er|ing)?([-_\\s]|$)|preload|intro|splash|curtain/i;
|
|
432
|
+
for (const el of document.body ? document.body.querySelectorAll("*") : []) {
|
|
433
|
+
if (el.tagName === "CANVAS" || el.tagName === "VIDEO") continue;
|
|
434
|
+
const label = ((typeof el.className === "string" ? el.className : "") + " " + el.id).trim();
|
|
435
|
+
const count = el.childElementCount === 0 && /^\\s*\\d{1,3}\\s*%\\s*$/.test(el.textContent || "");
|
|
436
|
+
if (!count && !named.test(label)) continue;
|
|
437
|
+
const s = getComputedStyle(el);
|
|
438
|
+
if (s.display === "none" || s.visibility === "hidden" || Number(s.opacity) < 0.05) continue;
|
|
439
|
+
if (!count && s.position !== "fixed" && s.position !== "absolute") continue;
|
|
440
|
+
const r = el.getBoundingClientRect();
|
|
441
|
+
const seen = Math.max(0, Math.min(r.right, vw) - Math.max(r.left, 0)) * Math.max(0, Math.min(r.bottom, vh) - Math.max(r.top, 0));
|
|
442
|
+
if (count ? seen > 0 : seen >= vw * vh * 0.6) return (label || el.tagName).slice(0, 60);
|
|
443
|
+
}
|
|
444
|
+
return "";
|
|
445
|
+
})()`;
|
|
446
|
+
|
|
447
|
+
// Waits for the load event and fonts, then until two checks in a row see no
|
|
448
|
+
// loader, a screen that is not one flat colour (or has stayed flat with the
|
|
449
|
+
// network quiet for 2.5 s), and no request for a second.
|
|
450
|
+
// Returns why it gave up.
|
|
451
|
+
async function settle() {
|
|
452
|
+
const start = Date.now();
|
|
453
|
+
const left = () => Math.max(0, maxWait - (Date.now() - start));
|
|
454
|
+
await evalValue(
|
|
455
|
+
`new Promise((done) => {
|
|
456
|
+
const t = setTimeout(done, ${Math.max(1500, Math.min(maxWait, 20000))});
|
|
457
|
+
const fonts = () => (document.fonts ? document.fonts.ready : Promise.resolve()).then(() => { clearTimeout(t); done(); });
|
|
458
|
+
if (document.readyState === "complete") fonts(); else addEventListener("load", fonts, { once: true });
|
|
459
|
+
})`,
|
|
460
|
+
25000,
|
|
461
|
+
).catch(() => {});
|
|
462
|
+
const busy = () => {
|
|
463
|
+
for (const [id, at] of inflight) if (Date.now() - at > 10000) inflight.delete(id);
|
|
464
|
+
return inflight.size > 0 || Date.now() - lastNetwork < 1000;
|
|
465
|
+
};
|
|
466
|
+
let good = 0;
|
|
467
|
+
let fetched = false;
|
|
468
|
+
let flatSince = 0;
|
|
469
|
+
for (;;) {
|
|
470
|
+
const loader = await evalValue(loaderCheck).catch(() => "");
|
|
471
|
+
const flat = loader ? 1 : await screenFlat().catch(() => 0);
|
|
472
|
+
const fetching = busy();
|
|
473
|
+
fetched ||= fetching;
|
|
474
|
+
// A flat screen with nothing left to fetch for 2.5 s is a sparse page, not a loader.
|
|
475
|
+
flatSince = flat >= FLAT && !loader && !fetching ? flatSince || Date.now() : 0;
|
|
476
|
+
const sparse = flatSince && Date.now() - flatSince >= 2500;
|
|
477
|
+
good = !loader && !fetching && (flat < FLAT || sparse) ? good + 1 : 0;
|
|
478
|
+
if (good >= 2) break;
|
|
479
|
+
if (!left()) {
|
|
480
|
+
return loader
|
|
481
|
+
? `a loader still covers the screen (${loader})`
|
|
482
|
+
: flat >= FLAT
|
|
483
|
+
? "the screen is still one flat colour"
|
|
484
|
+
: "the page is still fetching";
|
|
485
|
+
}
|
|
486
|
+
await sleep(Math.min(500, left()));
|
|
487
|
+
}
|
|
488
|
+
// A loader that waited on its assets usually plays a reveal once they land.
|
|
489
|
+
if (fetched && !local) await sleep(Math.min(1500, left()));
|
|
490
|
+
return "";
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
// Clicks a consent button, which can be any element, or else strips a short
|
|
494
|
+
// privacy notice. Rejecting comes first: a script has no use for tracking,
|
|
495
|
+
// and accepting can start scripts that redraw the page.
|
|
496
|
+
// A local page is a state someone set up on purpose, so it is left as it is, and
|
|
497
|
+
// so is a record of motion (--frames): nothing there is cleaned up.
|
|
498
|
+
const dismissConsent = () =>
|
|
499
|
+
local ? Promise.resolve(false) : evalValue(`(() => {
|
|
500
|
+
// The common consent tools first, by their own ids: reject, then accept.
|
|
501
|
+
const known = [
|
|
502
|
+
"#onetrust-reject-all-handler", "#CybotCookiebotDialogBodyButtonDecline", "#didomi-notice-disagree-button",
|
|
503
|
+
".cky-btn-reject", "#cmplz-deny, .cmplz-deny", "[data-cookiefirst-action=reject]", ".iubenda-cs-reject-btn",
|
|
504
|
+
"#onetrust-accept-btn-handler", "#CybotCookiebotDialogBodyLevelButtonLevelOptinAllowAll", "#didomi-notice-agree-button",
|
|
505
|
+
".cky-btn-accept", ".cmplz-accept", "[data-cookiefirst-action=accept]", ".iubenda-cs-accept-btn",
|
|
506
|
+
];
|
|
507
|
+
for (const sel of known) {
|
|
508
|
+
const el = document.querySelector(sel);
|
|
509
|
+
if (el && el.getClientRects().length) {
|
|
510
|
+
el.click();
|
|
511
|
+
return true;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
const accept = /^(accept( all)?( cookies)?|accept (and|&) (close|continue)|agree|i agree|ok|okay|got it|allow( all)?( cookies)?|i understand|acepto|aceptar( todas?| todo| cookies)?|aceptar y (cerrar|continuar)|onartu( guztiak)?|accepter( tout)?|tout accepter|j'accepte|alle akzeptieren|akzeptieren|accetta( tutti)?|accetto|aceitar( todos)?)$/i;
|
|
515
|
+
const reject = /^(reject( all)?( cookies)?|decline( all)?|deny|only (essential|necessary)( cookies)?|rechazar( todas?| todo| cookies)?|denegar|ukatu( guztiak)?|refuser( tout)?|tout refuser|continuer sans accepter|alle ablehnen|ablehnen|rifiuta( tutti)?|rejeitar( todos)?)$/i;
|
|
516
|
+
const clickable = [...document.querySelectorAll("button, [role=button], a, input[type=button], input[type=submit], [onclick], div, span")]
|
|
517
|
+
.filter((el) => el.childElementCount <= 2 && el.getClientRects().length);
|
|
518
|
+
// Only inside something that looks like a notice about cookies or privacy: a
|
|
519
|
+
// dialog, a layer fixed or sticky over the page, or one named like a banner.
|
|
520
|
+
// Never the page itself, so a short page that mentions privacy is not a notice.
|
|
521
|
+
const about = /cookie|consent|privacy|gdpr|datenschutz|privacidad|consentimiento|confidentialit|privacit/i;
|
|
522
|
+
const named = /cookie|consent|gdpr|privacy|banner|notice|popup|modal|dialog/i;
|
|
523
|
+
const notice = (el) => {
|
|
524
|
+
for (let up = el, i = 0; up && up !== document.body && up !== document.documentElement && i < 8; up = up.parentElement, i++) {
|
|
525
|
+
const t = up.innerText || "";
|
|
526
|
+
if (t.length >= 1500 || !about.test(t)) continue;
|
|
527
|
+
const pos = getComputedStyle(up).position;
|
|
528
|
+
const label = (typeof up.className === "string" ? up.className : "") + " " + up.id;
|
|
529
|
+
if (up.tagName === "DIALOG" || /^(dialog|alertdialog)$/.test(up.getAttribute("role") || "") ||
|
|
530
|
+
up.getAttribute("aria-modal") === "true" || pos === "fixed" || pos === "sticky" || named.test(label)) return true;
|
|
531
|
+
}
|
|
532
|
+
return false;
|
|
533
|
+
};
|
|
534
|
+
const text = (el) => (el.innerText || el.value || el.textContent || "").trim().replace(/\\s+/g, " ");
|
|
535
|
+
const pick = (re) => clickable.find((el) => text(el).length < 40 && re.test(text(el)) && notice(el));
|
|
536
|
+
const hit = pick(reject) || pick(accept);
|
|
537
|
+
if (hit) {
|
|
538
|
+
hit.click();
|
|
539
|
+
return true;
|
|
540
|
+
}
|
|
541
|
+
// No button: strip a short privacy notice that floats over the page (e.g.
|
|
542
|
+
// Google Fonts "×" banner). Only a fixed or sticky layer with no canvas or
|
|
543
|
+
// video, because a wrapper whose only text is the notice can hold the page.
|
|
544
|
+
const privacy = /uses cookies|uses essential cookies|privacy and google fonts|cookie settings/i;
|
|
545
|
+
for (const el of [...document.querySelectorAll("div, section, aside, dialog")]) {
|
|
546
|
+
const t = (el.innerText || el.textContent || "").trim();
|
|
547
|
+
const pos = getComputedStyle(el).position;
|
|
548
|
+
if (t.length > 0 && t.length < 300 && privacy.test(t) && el.children.length < 12 &&
|
|
549
|
+
(pos === "fixed" || pos === "sticky") && !el.querySelector("canvas, video")) {
|
|
550
|
+
el.remove();
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
return false;
|
|
554
|
+
})()`).catch(() => false);
|
|
555
|
+
|
|
556
|
+
// A real press and release in the middle of the element, as a person would click.
|
|
557
|
+
async function clickOn(selector) {
|
|
558
|
+
const box = await evalValue(`(() => {
|
|
559
|
+
const el = document.querySelector(${JSON.stringify(selector)});
|
|
560
|
+
if (!el) return null;
|
|
561
|
+
el.scrollIntoView({ block: "center", inline: "center" });
|
|
562
|
+
const r = el.getBoundingClientRect();
|
|
563
|
+
return r.width && r.height ? { x: r.left + r.width / 2, y: r.top + r.height / 2 } : null;
|
|
564
|
+
})()`);
|
|
565
|
+
if (!box) {
|
|
566
|
+
console.error(`no visible element matches ${selector}`);
|
|
567
|
+
drop();
|
|
568
|
+
process.exit(1);
|
|
569
|
+
}
|
|
570
|
+
const at = { x: Math.round(box.x), y: Math.round(box.y), button: "left", clickCount: 1 };
|
|
571
|
+
await page("Input.dispatchMouseEvent", { type: "mouseMoved", x: at.x, y: at.y });
|
|
572
|
+
await page("Input.dispatchMouseEvent", { type: "mousePressed", ...at });
|
|
573
|
+
await page("Input.dispatchMouseEvent", { type: "mouseReleased", ...at });
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
const navigateStarted = Date.now();
|
|
577
|
+
// A page that cannot be reached comes back as Chrome's own error page, which would be saved as if
|
|
578
|
+
// it were the site: say so and stop.
|
|
579
|
+
const nav = await page("Page.navigate", { url: target }, 40000);
|
|
580
|
+
if (nav?.errorText && nav.errorText !== "net::ERR_ABORTED") {
|
|
581
|
+
console.error(`could not reach ${target}: ${nav.errorText}`);
|
|
582
|
+
drop();
|
|
583
|
+
process.exit(1);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
if (frames) {
|
|
587
|
+
// The frames are the record of motion, so nothing is paused, unstuck or cleaned up.
|
|
588
|
+
const folder = out.replace(/\.(png|jpe?g|webp)$/i, "");
|
|
589
|
+
mkdirSync(folder, { recursive: true });
|
|
590
|
+
let t0 = navigateStarted;
|
|
591
|
+
if (scrollFrames || clickArg) {
|
|
592
|
+
const why = await settle();
|
|
593
|
+
if (why) console.error(`waited ${maxWait} ms: ${why}`);
|
|
594
|
+
await sleep(600);
|
|
595
|
+
t0 = Date.now();
|
|
596
|
+
}
|
|
597
|
+
for (let i = 0; i < frames; i++) {
|
|
598
|
+
const due = t0 + i * every;
|
|
599
|
+
if (Date.now() < due) await sleep(due - Date.now());
|
|
600
|
+
if (scrollFrames && i > 0) {
|
|
601
|
+
await page("Input.dispatchMouseEvent", { type: "mouseWheel", x: Math.round(width / 2), y: Math.round(height / 2), deltaX: 0, deltaY: Math.round(height / 2) });
|
|
602
|
+
}
|
|
603
|
+
// While the page is still swapping in, Chrome refuses a shot for a moment.
|
|
604
|
+
let data = "";
|
|
605
|
+
for (let tries = 0; !data && tries < 10; tries++) {
|
|
606
|
+
data = await page("Page.captureScreenshot", { format: "jpeg", quality: 70 }, 20000).then((r) => r.data, () => "");
|
|
607
|
+
if (!data) await sleep(150);
|
|
608
|
+
}
|
|
609
|
+
if (!data) continue;
|
|
610
|
+
const at = Date.now() - t0;
|
|
611
|
+
const file = join(folder, `${String(i + 1).padStart(2, "0")}-${String(at).padStart(5, "0")}ms.jpg`);
|
|
612
|
+
writeFileSync(file, Buffer.from(data, "base64"));
|
|
613
|
+
// The first frame is the page before the click; the rest are what it does.
|
|
614
|
+
if (clickArg && i === 0) await clickOn(clickArg);
|
|
615
|
+
}
|
|
616
|
+
console.log(folder);
|
|
617
|
+
drop();
|
|
618
|
+
process.exit(0);
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
const waited = await settle();
|
|
622
|
+
if (waited) console.error(`waited ${maxWait} ms: ${waited}`);
|
|
623
|
+
|
|
624
|
+
const beforeHref = await evalValue("location.href");
|
|
625
|
+
// A consent click can make a page redraw from black, so the wait runs again.
|
|
626
|
+
if (await dismissConsent()) {
|
|
627
|
+
await sleep(800);
|
|
628
|
+
const again = await settle();
|
|
629
|
+
if (again) console.error(`after the consent click, waited ${maxWait} ms: ${again}`);
|
|
630
|
+
} else await sleep(800);
|
|
631
|
+
const afterHref = await evalValue("location.href");
|
|
632
|
+
|
|
633
|
+
if (afterHref !== beforeHref) {
|
|
634
|
+
console.error(`navigated away: ${afterHref}`);
|
|
635
|
+
drop();
|
|
636
|
+
process.exit(1);
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// After a click the page is a new state, often an overlay: the screen is the shot.
|
|
640
|
+
if (clickArg) {
|
|
641
|
+
await clickOn(clickArg);
|
|
642
|
+
await sleep(1500);
|
|
643
|
+
const format = /\.png$/i.test(out) ? "png" : /\.webp$/i.test(out) ? "webp" : "jpeg";
|
|
644
|
+
const { data } = await page("Page.captureScreenshot", { format, ...(format === "png" ? {} : { quality: 70 }) }, 20000);
|
|
645
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
646
|
+
writeFileSync(out, Buffer.from(data, "base64"));
|
|
647
|
+
console.log(out);
|
|
648
|
+
drop();
|
|
649
|
+
process.exit(0);
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// The screen as a person first sees it, kept in case the full page loses it.
|
|
653
|
+
const firstFormat = /\.png$/i.test(out) ? "png" : /\.webp$/i.test(out) ? "webp" : "jpeg";
|
|
654
|
+
const firstScreen = (
|
|
655
|
+
await page("Page.captureScreenshot", { format: firstFormat, ...(firstFormat === "png" ? {} : { quality: 70 }) }, 20000)
|
|
656
|
+
).data;
|
|
657
|
+
const firstFlat = await screenFlat().catch(() => 1);
|
|
658
|
+
|
|
659
|
+
await page(
|
|
660
|
+
"Runtime.evaluate",
|
|
661
|
+
{
|
|
662
|
+
expression: `(() => new Promise((done) => {
|
|
663
|
+
(async () => {
|
|
664
|
+
for (const img of document.images) {
|
|
665
|
+
if (img.loading === "lazy") img.loading = "eager";
|
|
666
|
+
}
|
|
667
|
+
const dwell = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
668
|
+
const step = Math.max(480, Math.round(window.innerHeight * 0.65));
|
|
669
|
+
const limit = Math.min(
|
|
670
|
+
Math.max(document.documentElement.scrollHeight, document.body?.scrollHeight || 0),
|
|
671
|
+
${tallest}
|
|
672
|
+
);
|
|
673
|
+
let y = 0;
|
|
674
|
+
while (y < limit) {
|
|
675
|
+
y = Math.min(limit, y + step);
|
|
676
|
+
window.scrollTo(0, y);
|
|
677
|
+
await dwell(600);
|
|
678
|
+
}
|
|
679
|
+
await Promise.race([
|
|
680
|
+
Promise.all([...document.images].map((img) => img.decode().catch(() => {}))),
|
|
681
|
+
dwell(8000),
|
|
682
|
+
]);
|
|
683
|
+
window.scrollTo(0, 0);
|
|
684
|
+
await dwell(700);
|
|
685
|
+
done();
|
|
686
|
+
})().catch(() => done());
|
|
687
|
+
}))()`,
|
|
688
|
+
awaitPromise: true,
|
|
689
|
+
returnByValue: true,
|
|
690
|
+
},
|
|
691
|
+
90000,
|
|
692
|
+
);
|
|
693
|
+
|
|
694
|
+
await page("Runtime.evaluate", {
|
|
695
|
+
expression: `(() => {
|
|
696
|
+
const style = document.createElement("style");
|
|
697
|
+
style.textContent = \`
|
|
698
|
+
html, body { height: auto !important; max-height: none !important; overflow: visible !important; }
|
|
699
|
+
* { animation-play-state: paused !important; transition: none !important; scroll-behavior: auto !important; }
|
|
700
|
+
\`;
|
|
701
|
+
document.head.appendChild(style);
|
|
702
|
+
for (const el of document.querySelectorAll("*")) {
|
|
703
|
+
const pos = getComputedStyle(el).position;
|
|
704
|
+
if (pos === "fixed" || pos === "sticky") {
|
|
705
|
+
el.style.setProperty("position", "relative", "important");
|
|
706
|
+
el.style.setProperty("top", "auto", "important");
|
|
707
|
+
el.style.setProperty("bottom", "auto", "important");
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
})()`,
|
|
711
|
+
awaitPromise: true,
|
|
712
|
+
returnByValue: true,
|
|
713
|
+
});
|
|
714
|
+
await sleep(400);
|
|
715
|
+
|
|
716
|
+
// A redirect can land late (an app checks the session after it loads), so
|
|
717
|
+
// the address is checked last, right before the shot.
|
|
718
|
+
if (target === url) {
|
|
719
|
+
const landed = (await page("Runtime.evaluate", { expression: "location.href", returnByValue: true })).result.value;
|
|
720
|
+
const where = (href) => {
|
|
721
|
+
const u = new URL(href);
|
|
722
|
+
return `${u.origin}${u.pathname.replace(/\/$/, "")}`;
|
|
723
|
+
};
|
|
724
|
+
if (where(landed) !== where(url)) {
|
|
725
|
+
console.error(`landed on ${landed}, not ${url}.${/^https?:/.test(landed) ? " Behind a login? Pass --cookie." : " Check the address."}`);
|
|
726
|
+
if (strict) {
|
|
727
|
+
drop();
|
|
728
|
+
process.exit(1);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
// --clip-selector takes the element's box in document coordinates, measured
|
|
734
|
+
// after the unstick pass so the numbers match what the capture sees.
|
|
735
|
+
let selected = null;
|
|
736
|
+
if (clipSelector) {
|
|
737
|
+
const { result } = await page("Runtime.evaluate", {
|
|
738
|
+
expression: `(() => {
|
|
739
|
+
const el = document.querySelector(${JSON.stringify(clipSelector)});
|
|
740
|
+
if (!el) return null;
|
|
741
|
+
const r = el.getBoundingClientRect();
|
|
742
|
+
return {
|
|
743
|
+
x: Math.max(0, Math.round(r.left + window.scrollX)),
|
|
744
|
+
y: Math.max(0, Math.round(r.top + window.scrollY)),
|
|
745
|
+
width: Math.round(r.width),
|
|
746
|
+
height: Math.round(r.height),
|
|
747
|
+
};
|
|
748
|
+
})()`,
|
|
749
|
+
returnByValue: true,
|
|
750
|
+
});
|
|
751
|
+
selected = result?.value || null;
|
|
752
|
+
if (!selected) {
|
|
753
|
+
console.error(`no element matches ${clipSelector}`);
|
|
754
|
+
drop();
|
|
755
|
+
process.exit(1);
|
|
756
|
+
}
|
|
757
|
+
if (selected.width < 1 || selected.height < 1) {
|
|
758
|
+
console.error(`${clipSelector} has no box (width ${selected.width}, height ${selected.height})`);
|
|
759
|
+
drop();
|
|
760
|
+
process.exit(1);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
const metrics = await page("Page.getLayoutMetrics");
|
|
765
|
+
const size = metrics.cssContentSize || metrics.contentSize;
|
|
766
|
+
const fullWidth = Math.max(1, Math.ceil(size.width || width));
|
|
767
|
+
const fullHeight = Math.max(1, Math.min(Math.ceil(size.height || height), tallest));
|
|
768
|
+
const clipBox = clip || (selected ? { ...selected, scale: 1 } : null);
|
|
769
|
+
const shotClip = clipBox
|
|
770
|
+
? {
|
|
771
|
+
x: Math.min(clipBox.x, fullWidth - 1),
|
|
772
|
+
y: Math.min(clipBox.y, fullHeight - 1),
|
|
773
|
+
width: Math.min(clipBox.width, fullWidth - Math.min(clipBox.x, fullWidth - 1)),
|
|
774
|
+
height: Math.min(clipBox.height, fullHeight - Math.min(clipBox.y, fullHeight - 1)),
|
|
775
|
+
scale: 1,
|
|
776
|
+
}
|
|
777
|
+
: { x: 0, y: 0, width: fullWidth, height: fullHeight, scale: 1 };
|
|
778
|
+
|
|
779
|
+
// The file is what its name says, so a reader that trusts the extension is right.
|
|
780
|
+
const format = /\.png$/i.test(out) ? "png" : /\.webp$/i.test(out) ? "webp" : "jpeg";
|
|
781
|
+
let { data } = await page(
|
|
782
|
+
"Page.captureScreenshot",
|
|
783
|
+
{
|
|
784
|
+
format,
|
|
785
|
+
...(format === "png" ? {} : { quality: 70 }),
|
|
786
|
+
captureBeyondViewport: true,
|
|
787
|
+
clip: shotClip,
|
|
788
|
+
},
|
|
789
|
+
60000,
|
|
790
|
+
);
|
|
791
|
+
|
|
792
|
+
// A canvas that draws only what is on screen goes blank when the page is laid
|
|
793
|
+
// out full length. Then the screen seen first is the honest shot, and the
|
|
794
|
+
// full page is kept beside it for what lies below.
|
|
795
|
+
let fullOut = "";
|
|
796
|
+
if (!clipBox && firstFlat < FLAT && (await screenFlat(true).catch(() => 0)) >= FLAT) {
|
|
797
|
+
if (fullHeight > height * 1.2) {
|
|
798
|
+
fullOut = out.replace(/(\.[a-z]+)?$/i, (ext) => `-full${ext || ".jpg"}`);
|
|
799
|
+
mkdirSync(dirname(fullOut), { recursive: true });
|
|
800
|
+
writeFileSync(fullOut, Buffer.from(data, "base64"));
|
|
801
|
+
}
|
|
802
|
+
data = firstScreen;
|
|
803
|
+
console.error(
|
|
804
|
+
`the full page came back blank at the top (a canvas that draws only what is on screen): kept the first screen${fullOut ? `, and the full page as ${fullOut}` : ""}`,
|
|
805
|
+
);
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
809
|
+
writeFileSync(out, Buffer.from(data, "base64"));
|
|
810
|
+
console.log(out);
|
|
811
|
+
|
|
812
|
+
// A local page longer than one shot (a families board of hundreds) is kept whole, in parts:
|
|
813
|
+
// <out>-2, <out>-3 … each up to the same height, so nothing below the first part is lost.
|
|
814
|
+
const realHeight = Math.ceil(size.height || height);
|
|
815
|
+
if (clipBox && (shotClip.height < clipBox.height || shotClip.width < clipBox.width)) {
|
|
816
|
+
console.error(`the clip reaches past the page (${fullWidth}x${realHeight} px): kept ${shotClip.width}x${shotClip.height} px of ${clipBox.width}x${clipBox.height}`);
|
|
817
|
+
} else if (!clipBox && !/^file:/.test(url) && realHeight > fullHeight) {
|
|
818
|
+
console.error(`the page is ${realHeight} px, over the ${tallest} px limit: kept the first ${fullHeight} px`);
|
|
819
|
+
}
|
|
820
|
+
if (!clipBox && /^file:/.test(url) && realHeight > fullHeight) {
|
|
821
|
+
const parts = Math.min(10, Math.ceil(realHeight / tallest));
|
|
822
|
+
for (let i = 1; i < parts; i++) {
|
|
823
|
+
const y = i * tallest;
|
|
824
|
+
const { data: part } = await page("Page.captureScreenshot", { format, ...(format === "png" ? {} : { quality: 70 }), captureBeyondViewport: true, clip: { x: 0, y, width: fullWidth, height: Math.min(tallest, realHeight - y), scale: 1 } }, 60000);
|
|
825
|
+
const partOut = out.replace(/(\.[a-z]+)?$/i, (ext) => `-${i + 1}${ext || ".jpg"}`);
|
|
826
|
+
writeFileSync(partOut, Buffer.from(part, "base64"));
|
|
827
|
+
console.log(partOut);
|
|
828
|
+
}
|
|
829
|
+
if (realHeight > parts * tallest) console.error(`the page is ${realHeight} px: kept the first ${parts * tallest} px in ${parts} parts`);
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
if (reviewOut) {
|
|
833
|
+
// Side-by-side columns ~2800 px tall so a tall capture stays readable.
|
|
834
|
+
// Real capture stays the single tall file; review is scratch only.
|
|
835
|
+
const reviewHtml = `<!doctype html><meta charset=utf-8>
|
|
836
|
+
<canvas id=c></canvas>
|
|
837
|
+
<script>
|
|
838
|
+
const src = "data:image/${format};base64,${data}";
|
|
839
|
+
const img = new Image();
|
|
840
|
+
img.onload = () => {
|
|
841
|
+
const colH = 2800;
|
|
842
|
+
const gap = 20;
|
|
843
|
+
const cols = Math.max(1, Math.ceil(img.height / colH));
|
|
844
|
+
const c = document.getElementById("c");
|
|
845
|
+
c.width = cols * img.width + (cols - 1) * gap;
|
|
846
|
+
c.height = Math.min(colH, img.height);
|
|
847
|
+
const ctx = c.getContext("2d");
|
|
848
|
+
ctx.fillStyle = "#111";
|
|
849
|
+
ctx.fillRect(0, 0, c.width, c.height);
|
|
850
|
+
for (let i = 0; i < cols; i++) {
|
|
851
|
+
const sy = i * colH;
|
|
852
|
+
const sh = Math.min(colH, img.height - sy);
|
|
853
|
+
ctx.drawImage(img, 0, sy, img.width, sh, i * (img.width + gap), 0, img.width, sh);
|
|
854
|
+
}
|
|
855
|
+
document.title = "ready";
|
|
856
|
+
};
|
|
857
|
+
img.src = src;
|
|
858
|
+
</script>`;
|
|
859
|
+
const reviewPage = join(dir, "review.html");
|
|
860
|
+
writeFileSync(reviewPage, reviewHtml);
|
|
861
|
+
await page("Page.navigate", { url: `file://${reviewPage}` }, 20000);
|
|
862
|
+
await sleep(400);
|
|
863
|
+
for (let i = 0; i < 40; i++) {
|
|
864
|
+
const title = (
|
|
865
|
+
await page("Runtime.evaluate", { expression: "document.title", returnByValue: true })
|
|
866
|
+
).result.value;
|
|
867
|
+
if (title === "ready") break;
|
|
868
|
+
await sleep(100);
|
|
869
|
+
}
|
|
870
|
+
const { result: sizeResult } = await page("Runtime.evaluate", {
|
|
871
|
+
expression: `(() => {
|
|
872
|
+
const c = document.getElementById("c");
|
|
873
|
+
return { w: c.width, h: c.height };
|
|
874
|
+
})()`,
|
|
875
|
+
returnByValue: true,
|
|
876
|
+
});
|
|
877
|
+
const { data: reviewData } = await page(
|
|
878
|
+
"Page.captureScreenshot",
|
|
879
|
+
{
|
|
880
|
+
format: /\.png$/i.test(reviewOut) ? "png" : "jpeg",
|
|
881
|
+
quality: 75,
|
|
882
|
+
clip: { x: 0, y: 0, width: sizeResult.value.w, height: sizeResult.value.h, scale: 1 },
|
|
883
|
+
captureBeyondViewport: true,
|
|
884
|
+
},
|
|
885
|
+
60000,
|
|
886
|
+
);
|
|
887
|
+
mkdirSync(dirname(reviewOut), { recursive: true });
|
|
888
|
+
writeFileSync(reviewOut, Buffer.from(reviewData, "base64"));
|
|
889
|
+
console.log(reviewOut);
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
drop();
|
|
893
|
+
process.exit(0);
|