@jonandev/longbeard 0.5.1 → 0.6.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.
@@ -3,10 +3,14 @@
3
3
  // repeat the same fold. Node 22+. Uses an installed Chrome/Edge/Chromium.
4
4
  //
5
5
  // node capture.mjs <url> --out .design/refs/name.jpg
6
- import { spawn } from "node:child_process";
6
+ // node capture.mjs <url> --out .design/refs/name.jpg --review /tmp/name-review.jpg
7
+ // node capture.mjs <url> --out .design/refs/name.jpg --clip x,y,w,h
8
+ // node capture.mjs <url> --out .design/refs/name.jpg --clip-selector "main"
9
+ // node capture.mjs file:///abs/path/moodboard.html --out /tmp/moodboard.jpg
10
+ import { spawn, execSync } from "node:child_process";
7
11
  import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
8
12
  import { tmpdir } from "node:os";
9
- import { dirname, join, resolve } from "node:path";
13
+ import { dirname, isAbsolute, join, resolve } from "node:path";
10
14
 
11
15
  const args = process.argv.slice(2);
12
16
  const flag = (name, def) => {
@@ -17,11 +21,54 @@ const flag = (name, def) => {
17
21
  return v;
18
22
  };
19
23
  const url = args[0];
20
- const out = resolve(flag("out", "") || "");
21
- if (!url || !/^https?:\/\//.test(url) || !out) {
22
- console.error("usage: node capture.mjs <https://url> --out .design/refs/name.jpg");
24
+ const outArg = flag("out", "") || "";
25
+ const reviewArg = flag("review", "") || "";
26
+ const clipArg = flag("clip", "") || "";
27
+ const clipSelector = flag("clip-selector", "") || "";
28
+ if (!url || !/^(https?|file):\/\//.test(url) || !outArg) {
29
+ console.error(
30
+ 'usage: node capture.mjs <https://url | file:///path> --out .design/refs/name.jpg [--review /tmp/name-review.jpg] [--clip x,y,w,h | --clip-selector "css"]',
31
+ );
23
32
  process.exit(2);
24
33
  }
34
+ if (clipArg && clipSelector) {
35
+ console.error("pass --clip or --clip-selector, not both");
36
+ process.exit(2);
37
+ }
38
+
39
+ function projectRoot() {
40
+ try {
41
+ return execSync("git rev-parse --show-toplevel", { encoding: "utf8" }).trim();
42
+ } catch {
43
+ return process.cwd();
44
+ }
45
+ }
46
+
47
+ function resolveOut(path) {
48
+ if (!path) return "";
49
+ if (isAbsolute(path)) return path;
50
+ return resolve(projectRoot(), path);
51
+ }
52
+
53
+ const out = resolveOut(outArg);
54
+ const reviewOut = resolveOut(reviewArg);
55
+
56
+ function parseClip(s) {
57
+ if (!s) return null;
58
+ const parts = s.split(",").map((n) => Number(n.trim()));
59
+ if (parts.length !== 4 || parts.some((n) => !Number.isFinite(n) || n < 0)) {
60
+ console.error("clip must be x,y,w,h (non-negative numbers)");
61
+ process.exit(2);
62
+ }
63
+ const [x, y, w, h] = parts;
64
+ if (w < 1 || h < 1) {
65
+ console.error("clip width and height must be >= 1");
66
+ process.exit(2);
67
+ }
68
+ return { x, y, width: w, height: h, scale: 1 };
69
+ }
70
+
71
+ const clip = parseClip(clipArg);
25
72
 
26
73
  function findChrome() {
27
74
  const env = process.env.CHROME_PATH;
@@ -156,19 +203,48 @@ await page("Emulation.setDeviceMetricsOverride", {
156
203
  await page("Page.navigate", { url }, 40000);
157
204
  await sleep(2500);
158
205
 
206
+ const beforeHref = (
207
+ await page("Runtime.evaluate", {
208
+ expression: "location.href",
209
+ returnByValue: true,
210
+ })
211
+ ).result.value;
212
+
159
213
  await page("Runtime.evaluate", {
160
214
  expression: `(() => {
161
- const labels = /accept|agree|ok|got it|allow|i understand|acepto|aceptar/i;
162
- for (const el of document.querySelectorAll("button, [role=button], a")) {
163
- const t = (el.innerText || el.textContent || "").trim();
215
+ const labels = /^(accept( all)?( cookies)?|agree|ok|okay|got it|allow( all)?|i understand|acepto|aceptar)$/i;
216
+ const clickable = document.querySelectorAll("button, [role=button]");
217
+ for (const el of clickable) {
218
+ const t = (el.innerText || el.textContent || "").trim().replace(/\\s+/g, " ");
164
219
  if (t.length < 40 && labels.test(t)) { el.click(); break; }
165
220
  }
221
+ // Strip short privacy/cookie dialogs (e.g. Google Fonts "×" banner).
222
+ const privacy = /uses cookies|privacy and google fonts|cookie settings/i;
223
+ for (const el of [...document.querySelectorAll("div, section, aside, dialog")]) {
224
+ const t = (el.innerText || el.textContent || "").trim();
225
+ if (t.length > 0 && t.length < 300 && privacy.test(t) && el.children.length < 12) {
226
+ el.remove();
227
+ }
228
+ }
166
229
  })()`,
167
230
  awaitPromise: true,
168
231
  returnByValue: true,
169
232
  });
170
233
  await sleep(800);
171
234
 
235
+ const afterHref = (
236
+ await page("Runtime.evaluate", {
237
+ expression: "location.href",
238
+ returnByValue: true,
239
+ })
240
+ ).result.value;
241
+
242
+ if (afterHref !== beforeHref) {
243
+ console.error(`navigated away: ${afterHref}`);
244
+ drop();
245
+ process.exit(1);
246
+ }
247
+
172
248
  await page(
173
249
  "Runtime.evaluate",
174
250
  {
@@ -226,17 +302,59 @@ await page("Runtime.evaluate", {
226
302
  });
227
303
  await sleep(400);
228
304
 
305
+ // --clip-selector takes the element's box in document coordinates, measured
306
+ // after the unstick pass so the numbers match what the capture sees.
307
+ let selected = null;
308
+ if (clipSelector) {
309
+ const { result } = await page("Runtime.evaluate", {
310
+ expression: `(() => {
311
+ const el = document.querySelector(${JSON.stringify(clipSelector)});
312
+ if (!el) return null;
313
+ const r = el.getBoundingClientRect();
314
+ return {
315
+ x: Math.max(0, Math.round(r.left + window.scrollX)),
316
+ y: Math.max(0, Math.round(r.top + window.scrollY)),
317
+ width: Math.round(r.width),
318
+ height: Math.round(r.height),
319
+ };
320
+ })()`,
321
+ returnByValue: true,
322
+ });
323
+ selected = result?.value || null;
324
+ if (!selected) {
325
+ console.error(`no element matches ${clipSelector}`);
326
+ drop();
327
+ process.exit(1);
328
+ }
329
+ if (selected.width < 1 || selected.height < 1) {
330
+ console.error(`${clipSelector} has no box (width ${selected.width}, height ${selected.height})`);
331
+ drop();
332
+ process.exit(1);
333
+ }
334
+ }
335
+
229
336
  const metrics = await page("Page.getLayoutMetrics");
230
337
  const size = metrics.cssContentSize || metrics.contentSize;
231
- const width = Math.max(1, Math.ceil(size.width || 1440));
232
- const height = Math.max(1, Math.min(Math.ceil(size.height || 900), 14000));
338
+ const fullWidth = Math.max(1, Math.ceil(size.width || 1440));
339
+ const fullHeight = Math.max(1, Math.min(Math.ceil(size.height || 900), 14000));
340
+ const clipBox = clip || (selected ? { ...selected, scale: 1 } : null);
341
+ const shotClip = clipBox
342
+ ? {
343
+ x: Math.min(clipBox.x, fullWidth - 1),
344
+ y: Math.min(clipBox.y, fullHeight - 1),
345
+ width: Math.min(clipBox.width, fullWidth - Math.min(clipBox.x, fullWidth - 1)),
346
+ height: Math.min(clipBox.height, fullHeight - Math.min(clipBox.y, fullHeight - 1)),
347
+ scale: 1,
348
+ }
349
+ : { x: 0, y: 0, width: fullWidth, height: fullHeight, scale: 1 };
350
+
233
351
  const { data } = await page(
234
352
  "Page.captureScreenshot",
235
353
  {
236
354
  format: "jpeg",
237
355
  quality: 70,
238
356
  captureBeyondViewport: true,
239
- clip: { x: 0, y: 0, width, height, scale: 1 },
357
+ clip: shotClip,
240
358
  },
241
359
  60000,
242
360
  );
@@ -244,5 +362,66 @@ const { data } = await page(
244
362
  mkdirSync(dirname(out), { recursive: true });
245
363
  writeFileSync(out, Buffer.from(data, "base64"));
246
364
  console.log(out);
365
+
366
+ if (reviewOut) {
367
+ // Side-by-side columns ~2800 px tall so a tall capture stays readable.
368
+ // Real capture stays the single tall file; review is scratch only.
369
+ const reviewHtml = `<!doctype html><meta charset=utf-8>
370
+ <canvas id=c></canvas>
371
+ <script>
372
+ const src = "data:image/jpeg;base64,${data}";
373
+ const img = new Image();
374
+ img.onload = () => {
375
+ const colH = 2800;
376
+ const gap = 20;
377
+ const cols = Math.max(1, Math.ceil(img.height / colH));
378
+ const c = document.getElementById("c");
379
+ c.width = cols * img.width + (cols - 1) * gap;
380
+ c.height = Math.min(colH, img.height);
381
+ const ctx = c.getContext("2d");
382
+ ctx.fillStyle = "#111";
383
+ ctx.fillRect(0, 0, c.width, c.height);
384
+ for (let i = 0; i < cols; i++) {
385
+ const sy = i * colH;
386
+ const sh = Math.min(colH, img.height - sy);
387
+ ctx.drawImage(img, 0, sy, img.width, sh, i * (img.width + gap), 0, img.width, sh);
388
+ }
389
+ document.title = "ready";
390
+ };
391
+ img.src = src;
392
+ </script>`;
393
+ const reviewPage = join(dir, "review.html");
394
+ writeFileSync(reviewPage, reviewHtml);
395
+ await page("Page.navigate", { url: `file://${reviewPage}` }, 20000);
396
+ await sleep(400);
397
+ for (let i = 0; i < 40; i++) {
398
+ const title = (
399
+ await page("Runtime.evaluate", { expression: "document.title", returnByValue: true })
400
+ ).result.value;
401
+ if (title === "ready") break;
402
+ await sleep(100);
403
+ }
404
+ const { result: sizeResult } = await page("Runtime.evaluate", {
405
+ expression: `(() => {
406
+ const c = document.getElementById("c");
407
+ return { w: c.width, h: c.height };
408
+ })()`,
409
+ returnByValue: true,
410
+ });
411
+ const { data: reviewData } = await page(
412
+ "Page.captureScreenshot",
413
+ {
414
+ format: "jpeg",
415
+ quality: 75,
416
+ clip: { x: 0, y: 0, width: sizeResult.value.w, height: sizeResult.value.h, scale: 1 },
417
+ captureBeyondViewport: true,
418
+ },
419
+ 60000,
420
+ );
421
+ mkdirSync(dirname(reviewOut), { recursive: true });
422
+ writeFileSync(reviewOut, Buffer.from(reviewData, "base64"));
423
+ console.log(reviewOut);
424
+ }
425
+
247
426
  drop();
248
427
  process.exit(0);
@@ -0,0 +1,247 @@
1
+ #!/usr/bin/env node
2
+ // Build labelled contact sheets from a TSV of label\timageURL.
3
+ // Writes JPEG grids (~36 per sheet) into an output directory (scratch, not .design/).
4
+ // Viewing listing thumbnails is allowed; this is not a capture.
5
+ //
6
+ // node contact-sheet.mjs candidates.tsv --out /tmp/hunt-sheets
7
+ import { spawn } from "node:child_process";
8
+ import {
9
+ existsSync,
10
+ mkdirSync,
11
+ mkdtempSync,
12
+ readFileSync,
13
+ rmSync,
14
+ writeFileSync,
15
+ } from "node:fs";
16
+ import { tmpdir } from "node:os";
17
+ import { join, resolve } from "node:path";
18
+
19
+ const args = process.argv.slice(2);
20
+ const flag = (name, def) => {
21
+ const i = args.indexOf(`--${name}`);
22
+ if (i === -1) return def;
23
+ const v = args[i + 1];
24
+ args.splice(i, 2);
25
+ return v;
26
+ };
27
+ const tsvPath = args[0];
28
+ const outDir = resolve(flag("out", "") || "");
29
+ const perSheet = Math.max(1, Number(flag("per", "36")) || 36);
30
+ if (!tsvPath || !outDir) {
31
+ console.error("usage: node contact-sheet.mjs candidates.tsv --out /tmp/hunt-sheets [--per 36]");
32
+ process.exit(2);
33
+ }
34
+
35
+ const lines = readFileSync(tsvPath, "utf8")
36
+ .split(/\r?\n/)
37
+ .map((l) => l.trim())
38
+ .filter(Boolean)
39
+ .map((l) => {
40
+ const tab = l.indexOf("\t");
41
+ if (tab === -1) return { label: l, url: l };
42
+ return { label: l.slice(0, tab).trim(), url: l.slice(tab + 1).trim() };
43
+ })
44
+ .filter((r) => /^https?:\/\//i.test(r.url));
45
+
46
+ if (!lines.length) {
47
+ console.error("no label\timageURL rows found");
48
+ process.exit(1);
49
+ }
50
+
51
+ function findChrome() {
52
+ const env = process.env.CHROME_PATH;
53
+ if (env && existsSync(env)) return env;
54
+ const home = process.env.HOME || process.env.USERPROFILE || "";
55
+ const local = process.env.LOCALAPPDATA || "";
56
+ const pf = process.env.PROGRAMFILES || "C:\\Program Files";
57
+ const pf86 = process.env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)";
58
+ const candidates = [
59
+ join(pf, "Google/Chrome/Application/chrome.exe"),
60
+ join(pf86, "Google/Chrome/Application/chrome.exe"),
61
+ join(local, "Google/Chrome/Application/chrome.exe"),
62
+ join(pf, "Microsoft/Edge/Application/msedge.exe"),
63
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
64
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
65
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
66
+ join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
67
+ "/usr/bin/google-chrome",
68
+ "/usr/bin/google-chrome-stable",
69
+ "/usr/bin/chromium",
70
+ "/usr/bin/chromium-browser",
71
+ ];
72
+ return candidates.find((path) => path && existsSync(path)) || null;
73
+ }
74
+
75
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
76
+ const exe = findChrome();
77
+ if (!exe) {
78
+ console.error("No Chrome/Edge/Chromium found. Install one or set CHROME_PATH.");
79
+ process.exit(1);
80
+ }
81
+ if (typeof WebSocket === "undefined") {
82
+ console.error("Node 22+ is required.");
83
+ process.exit(1);
84
+ }
85
+
86
+ const dir = mkdtempSync(join(tmpdir(), "hunt-sheet-"));
87
+ let proc;
88
+ const drop = () => {
89
+ try {
90
+ if (proc?.pid) process.kill(proc.pid, "SIGKILL");
91
+ } catch {}
92
+ try {
93
+ rmSync(dir, { recursive: true, force: true });
94
+ } catch {}
95
+ };
96
+ process.once("exit", drop);
97
+
98
+ proc = spawn(
99
+ exe,
100
+ [
101
+ "--headless=new",
102
+ "--remote-debugging-port=0",
103
+ `--user-data-dir=${dir}`,
104
+ "--no-first-run",
105
+ "--hide-scrollbars",
106
+ "--mute-audio",
107
+ "--force-color-profile=srgb",
108
+ "--window-size=1600,1200",
109
+ "about:blank",
110
+ ],
111
+ { stdio: ["ignore", "ignore", "pipe"] },
112
+ );
113
+
114
+ let buf = "";
115
+ const wsUrl = await new Promise((resolveWs, reject) => {
116
+ const t = setTimeout(() => reject(new Error("Chrome did not start")), 20000);
117
+ proc.stderr.on("data", (d) => {
118
+ buf += d.toString();
119
+ const m = buf.match(/DevTools listening on (ws:\/\/[^\s]+)/);
120
+ if (m) {
121
+ clearTimeout(t);
122
+ resolveWs(m[1]);
123
+ }
124
+ });
125
+ proc.on("exit", (code) => {
126
+ clearTimeout(t);
127
+ reject(new Error(`Chrome exited ${code}`));
128
+ });
129
+ });
130
+
131
+ const ws = new WebSocket(wsUrl);
132
+ await new Promise((res, rej) => {
133
+ ws.onopen = res;
134
+ ws.onerror = () => rej(new Error("CDP socket failed"));
135
+ });
136
+ let nextId = 1;
137
+ const pending = new Map();
138
+ ws.onmessage = (ev) => {
139
+ const msg = JSON.parse(typeof ev.data === "string" ? ev.data : Buffer.from(ev.data).toString());
140
+ if (msg.id && pending.has(msg.id)) {
141
+ const { resolve: ok, reject: bad } = pending.get(msg.id);
142
+ pending.delete(msg.id);
143
+ if (msg.error) bad(new Error(msg.error.message));
144
+ else ok(msg.result);
145
+ }
146
+ };
147
+ const send = (method, params = {}, sessionId, timeoutMs = 30000) => {
148
+ const id = nextId++;
149
+ return new Promise((resolveSend, reject) => {
150
+ const timer = setTimeout(() => {
151
+ pending.delete(id);
152
+ reject(new Error(`CDP timeout: ${method}`));
153
+ }, timeoutMs);
154
+ pending.set(id, {
155
+ resolve: (v) => {
156
+ clearTimeout(timer);
157
+ resolveSend(v);
158
+ },
159
+ reject: (e) => {
160
+ clearTimeout(timer);
161
+ reject(e);
162
+ },
163
+ });
164
+ ws.send(JSON.stringify(sessionId ? { id, method, params, sessionId } : { id, method, params }));
165
+ });
166
+ };
167
+
168
+ const { targetId } = await send("Target.createTarget", { url: "about:blank" });
169
+ const { sessionId } = await send("Target.attachToTarget", { targetId, flatten: true });
170
+ const page = (method, params, timeoutMs) => send(method, params, sessionId, timeoutMs);
171
+
172
+ await page("Page.enable");
173
+ await page("Runtime.enable");
174
+ await page("Emulation.setDeviceMetricsOverride", {
175
+ width: 1600,
176
+ height: 1200,
177
+ deviceScaleFactor: 1,
178
+ mobile: false,
179
+ });
180
+
181
+ mkdirSync(outDir, { recursive: true });
182
+ const sheets = [];
183
+ for (let i = 0; i < lines.length; i += perSheet) {
184
+ sheets.push(lines.slice(i, i + perSheet));
185
+ }
186
+
187
+ const esc = (s) =>
188
+ String(s)
189
+ .replace(/&/g, "&amp;")
190
+ .replace(/</g, "&lt;")
191
+ .replace(/>/g, "&gt;")
192
+ .replace(/"/g, "&quot;");
193
+
194
+ for (let s = 0; s < sheets.length; s++) {
195
+ const cells = sheets[s]
196
+ .map(
197
+ (r) =>
198
+ `<figure><img src="${esc(r.url)}" loading="eager"><figcaption>${esc(r.label)}</figcaption></figure>`,
199
+ )
200
+ .join("\n");
201
+ const html = `<!doctype html><meta charset=utf-8>
202
+ <style>
203
+ body { margin: 16px; background: #1a1a1a; color: #eee; font: 11px/1.2 system-ui, sans-serif; }
204
+ .grid { display: grid; grid-template-columns: repeat(6, 1fr); gap: 10px; }
205
+ figure { margin: 0; background: #2a2a2a; border-radius: 4px; overflow: hidden; }
206
+ img { display: block; width: 100%; height: 140px; object-fit: cover; background: #111; }
207
+ figcaption { padding: 6px 8px; word-break: break-word; max-height: 2.4em; overflow: hidden; }
208
+ </style>
209
+ <div class="grid">${cells}</div>
210
+ <script>
211
+ Promise.all([...document.images].map((img) => img.decode().catch(() => {}))).then(() => {
212
+ document.title = "ready";
213
+ });
214
+ </script>`;
215
+ const htmlPath = join(dir, `sheet-${s + 1}.html`);
216
+ writeFileSync(htmlPath, html);
217
+ await page("Page.navigate", { url: `file://${htmlPath}` }, 30000);
218
+ await sleep(500);
219
+ for (let i = 0; i < 60; i++) {
220
+ const title = (
221
+ await page("Runtime.evaluate", { expression: "document.title", returnByValue: true })
222
+ ).result.value;
223
+ if (title === "ready") break;
224
+ await sleep(150);
225
+ }
226
+ await sleep(400);
227
+ const metrics = await page("Page.getLayoutMetrics");
228
+ const size = metrics.cssContentSize || metrics.contentSize;
229
+ const width = Math.max(1, Math.ceil(size.width || 1600));
230
+ const height = Math.max(1, Math.min(Math.ceil(size.height || 1200), 8000));
231
+ const { data } = await page(
232
+ "Page.captureScreenshot",
233
+ {
234
+ format: "jpeg",
235
+ quality: 80,
236
+ captureBeyondViewport: true,
237
+ clip: { x: 0, y: 0, width, height, scale: 1 },
238
+ },
239
+ 60000,
240
+ );
241
+ const outPath = join(outDir, `sheet-${String(s + 1).padStart(2, "0")}.jpg`);
242
+ writeFileSync(outPath, Buffer.from(data, "base64"));
243
+ console.log(outPath);
244
+ }
245
+
246
+ drop();
247
+ process.exit(0);
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env node
2
+ // WCAG 2.x contrast for colour pairs.
3
+ // node contrast.mjs "#2c2824 on #f6f1e7" "#b0563a on #f6f1e7:mark"
4
+ // Suffix :large or :mark checks against 3:1 instead of 4.5:1.
5
+ const lum = (hex) => {
6
+ const [r, g, b] = [1, 3, 5]
7
+ .map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)
8
+ .map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
9
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
10
+ };
11
+ let failed = false;
12
+ for (const arg of process.argv.slice(2)) {
13
+ const m = arg.match(/^(#[0-9a-f]{6})\s+on\s+(#[0-9a-f]{6})(?::(large|mark))?$/i);
14
+ if (!m) {
15
+ console.error(`skip: ${arg}`);
16
+ continue;
17
+ }
18
+ const [a, b] = [lum(m[1]), lum(m[2])];
19
+ const ratio = (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
20
+ const need = m[3] ? 3 : 4.5;
21
+ const verdict = ratio >= 7 && !m[3] ? "AAA" : ratio >= need ? "AA" : "FAIL";
22
+ if (verdict === "FAIL") failed = true;
23
+ console.log(
24
+ `${m[1]} on ${m[2]} ${ratio.toFixed(2)}:1 ${verdict}${m[3] ? ` (${m[3]}, needs 3:1)` : ""}`,
25
+ );
26
+ }
27
+ process.exit(failed ? 1 : 0);