@jonandev/longbeard 0.5.0 → 0.5.2

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,12 @@
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
+ import { spawn, execSync } from "node:child_process";
7
9
  import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
8
10
  import { tmpdir } from "node:os";
9
- import { dirname, join, resolve } from "node:path";
11
+ import { dirname, isAbsolute, join, resolve } from "node:path";
10
12
 
11
13
  const args = process.argv.slice(2);
12
14
  const flag = (name, def) => {
@@ -17,12 +19,50 @@ const flag = (name, def) => {
17
19
  return v;
18
20
  };
19
21
  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");
22
+ const outArg = flag("out", "") || "";
23
+ const reviewArg = flag("review", "") || "";
24
+ const clipArg = flag("clip", "") || "";
25
+ if (!url || !/^https?:\/\//.test(url) || !outArg) {
26
+ console.error(
27
+ "usage: node capture.mjs <https://url> --out .design/refs/name.jpg [--review /tmp/name-review.jpg] [--clip x,y,w,h]",
28
+ );
23
29
  process.exit(2);
24
30
  }
25
31
 
32
+ function projectRoot() {
33
+ try {
34
+ return execSync("git rev-parse --show-toplevel", { encoding: "utf8" }).trim();
35
+ } catch {
36
+ return process.cwd();
37
+ }
38
+ }
39
+
40
+ function resolveOut(path) {
41
+ if (!path) return "";
42
+ if (isAbsolute(path)) return path;
43
+ return resolve(projectRoot(), path);
44
+ }
45
+
46
+ const out = resolveOut(outArg);
47
+ const reviewOut = resolveOut(reviewArg);
48
+
49
+ function parseClip(s) {
50
+ if (!s) return null;
51
+ const parts = s.split(",").map((n) => Number(n.trim()));
52
+ if (parts.length !== 4 || parts.some((n) => !Number.isFinite(n) || n < 0)) {
53
+ console.error("clip must be x,y,w,h (non-negative numbers)");
54
+ process.exit(2);
55
+ }
56
+ const [x, y, w, h] = parts;
57
+ if (w < 1 || h < 1) {
58
+ console.error("clip width and height must be >= 1");
59
+ process.exit(2);
60
+ }
61
+ return { x, y, width: w, height: h, scale: 1 };
62
+ }
63
+
64
+ const clip = parseClip(clipArg);
65
+
26
66
  function findChrome() {
27
67
  const env = process.env.CHROME_PATH;
28
68
  if (env && existsSync(env)) return env;
@@ -156,19 +196,48 @@ await page("Emulation.setDeviceMetricsOverride", {
156
196
  await page("Page.navigate", { url }, 40000);
157
197
  await sleep(2500);
158
198
 
199
+ const beforeHref = (
200
+ await page("Runtime.evaluate", {
201
+ expression: "location.href",
202
+ returnByValue: true,
203
+ })
204
+ ).result.value;
205
+
159
206
  await page("Runtime.evaluate", {
160
207
  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();
208
+ const labels = /^(accept( all)?( cookies)?|agree|ok|okay|got it|allow( all)?|i understand|acepto|aceptar)$/i;
209
+ const clickable = document.querySelectorAll("button, [role=button]");
210
+ for (const el of clickable) {
211
+ const t = (el.innerText || el.textContent || "").trim().replace(/\\s+/g, " ");
164
212
  if (t.length < 40 && labels.test(t)) { el.click(); break; }
165
213
  }
214
+ // Strip short privacy/cookie dialogs (e.g. Google Fonts "×" banner).
215
+ const privacy = /uses cookies|privacy and google fonts|cookie settings/i;
216
+ for (const el of [...document.querySelectorAll("div, section, aside, dialog")]) {
217
+ const t = (el.innerText || el.textContent || "").trim();
218
+ if (t.length > 0 && t.length < 300 && privacy.test(t) && el.children.length < 12) {
219
+ el.remove();
220
+ }
221
+ }
166
222
  })()`,
167
223
  awaitPromise: true,
168
224
  returnByValue: true,
169
225
  });
170
226
  await sleep(800);
171
227
 
228
+ const afterHref = (
229
+ await page("Runtime.evaluate", {
230
+ expression: "location.href",
231
+ returnByValue: true,
232
+ })
233
+ ).result.value;
234
+
235
+ if (afterHref !== beforeHref) {
236
+ console.error(`navigated away: ${afterHref}`);
237
+ drop();
238
+ process.exit(1);
239
+ }
240
+
172
241
  await page(
173
242
  "Runtime.evaluate",
174
243
  {
@@ -228,15 +297,25 @@ await sleep(400);
228
297
 
229
298
  const metrics = await page("Page.getLayoutMetrics");
230
299
  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));
300
+ const fullWidth = Math.max(1, Math.ceil(size.width || 1440));
301
+ const fullHeight = Math.max(1, Math.min(Math.ceil(size.height || 900), 14000));
302
+ const shotClip = clip
303
+ ? {
304
+ x: Math.min(clip.x, fullWidth - 1),
305
+ y: Math.min(clip.y, fullHeight - 1),
306
+ width: Math.min(clip.width, fullWidth - Math.min(clip.x, fullWidth - 1)),
307
+ height: Math.min(clip.height, fullHeight - Math.min(clip.y, fullHeight - 1)),
308
+ scale: 1,
309
+ }
310
+ : { x: 0, y: 0, width: fullWidth, height: fullHeight, scale: 1 };
311
+
233
312
  const { data } = await page(
234
313
  "Page.captureScreenshot",
235
314
  {
236
315
  format: "jpeg",
237
316
  quality: 70,
238
317
  captureBeyondViewport: true,
239
- clip: { x: 0, y: 0, width, height, scale: 1 },
318
+ clip: shotClip,
240
319
  },
241
320
  60000,
242
321
  );
@@ -244,5 +323,66 @@ const { data } = await page(
244
323
  mkdirSync(dirname(out), { recursive: true });
245
324
  writeFileSync(out, Buffer.from(data, "base64"));
246
325
  console.log(out);
326
+
327
+ if (reviewOut) {
328
+ // Side-by-side columns ~2800 px tall so a tall capture stays readable.
329
+ // Real capture stays the single tall file; review is scratch only.
330
+ const reviewHtml = `<!doctype html><meta charset=utf-8>
331
+ <canvas id=c></canvas>
332
+ <script>
333
+ const src = "data:image/jpeg;base64,${data}";
334
+ const img = new Image();
335
+ img.onload = () => {
336
+ const colH = 2800;
337
+ const gap = 20;
338
+ const cols = Math.max(1, Math.ceil(img.height / colH));
339
+ const c = document.getElementById("c");
340
+ c.width = cols * img.width + (cols - 1) * gap;
341
+ c.height = Math.min(colH, img.height);
342
+ const ctx = c.getContext("2d");
343
+ ctx.fillStyle = "#111";
344
+ ctx.fillRect(0, 0, c.width, c.height);
345
+ for (let i = 0; i < cols; i++) {
346
+ const sy = i * colH;
347
+ const sh = Math.min(colH, img.height - sy);
348
+ ctx.drawImage(img, 0, sy, img.width, sh, i * (img.width + gap), 0, img.width, sh);
349
+ }
350
+ document.title = "ready";
351
+ };
352
+ img.src = src;
353
+ </script>`;
354
+ const reviewPage = join(dir, "review.html");
355
+ writeFileSync(reviewPage, reviewHtml);
356
+ await page("Page.navigate", { url: `file://${reviewPage}` }, 20000);
357
+ await sleep(400);
358
+ for (let i = 0; i < 40; i++) {
359
+ const title = (
360
+ await page("Runtime.evaluate", { expression: "document.title", returnByValue: true })
361
+ ).result.value;
362
+ if (title === "ready") break;
363
+ await sleep(100);
364
+ }
365
+ const { result: sizeResult } = await page("Runtime.evaluate", {
366
+ expression: `(() => {
367
+ const c = document.getElementById("c");
368
+ return { w: c.width, h: c.height };
369
+ })()`,
370
+ returnByValue: true,
371
+ });
372
+ const { data: reviewData } = await page(
373
+ "Page.captureScreenshot",
374
+ {
375
+ format: "jpeg",
376
+ quality: 75,
377
+ clip: { x: 0, y: 0, width: sizeResult.value.w, height: sizeResult.value.h, scale: 1 },
378
+ captureBeyondViewport: true,
379
+ },
380
+ 60000,
381
+ );
382
+ mkdirSync(dirname(reviewOut), { recursive: true });
383
+ writeFileSync(reviewOut, Buffer.from(reviewData, "base64"));
384
+ console.log(reviewOut);
385
+ }
386
+
247
387
  drop();
248
388
  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);
@@ -0,0 +1,204 @@
1
+ #!/usr/bin/env node
2
+ // List Dribbble search/popular cards from a listing URL.
3
+ // Headless Chrome; prints TSV: id-slug\tviews\timageURL\ttitle
4
+ //
5
+ // node dribbble-cards.mjs "https://dribbble.com/search/shots/popular/product-design?q=writing+app&timeframe=year" --scrolls 4
6
+ import { spawn } from "node:child_process";
7
+ import { existsSync, mkdtempSync, rmSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+
11
+ const args = process.argv.slice(2);
12
+ const flag = (name, def) => {
13
+ const i = args.indexOf(`--${name}`);
14
+ if (i === -1) return def;
15
+ const v = args[i + 1];
16
+ args.splice(i, 2);
17
+ return v;
18
+ };
19
+ const url = args[0];
20
+ const scrolls = Math.max(0, Number(flag("scrolls", "3")) || 3);
21
+ if (!url || !/^https?:\/\/(www\.)?dribbble\.com\//i.test(url)) {
22
+ console.error(
23
+ 'usage: node dribbble-cards.mjs "https://dribbble.com/search/..." [--scrolls 4]',
24
+ );
25
+ process.exit(2);
26
+ }
27
+
28
+ function findChrome() {
29
+ const env = process.env.CHROME_PATH;
30
+ if (env && existsSync(env)) return env;
31
+ const home = process.env.HOME || process.env.USERPROFILE || "";
32
+ const local = process.env.LOCALAPPDATA || "";
33
+ const pf = process.env.PROGRAMFILES || "C:\\Program Files";
34
+ const pf86 = process.env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)";
35
+ const candidates = [
36
+ join(pf, "Google/Chrome/Application/chrome.exe"),
37
+ join(pf86, "Google/Chrome/Application/chrome.exe"),
38
+ join(local, "Google/Chrome/Application/chrome.exe"),
39
+ join(pf, "Microsoft/Edge/Application/msedge.exe"),
40
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
41
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
42
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
43
+ join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
44
+ "/usr/bin/google-chrome",
45
+ "/usr/bin/google-chrome-stable",
46
+ "/usr/bin/chromium",
47
+ "/usr/bin/chromium-browser",
48
+ ];
49
+ return candidates.find((path) => path && existsSync(path)) || null;
50
+ }
51
+
52
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
53
+ const exe = findChrome();
54
+ if (!exe) {
55
+ console.error("No Chrome/Edge/Chromium found. Install one or set CHROME_PATH.");
56
+ process.exit(1);
57
+ }
58
+ if (typeof WebSocket === "undefined") {
59
+ console.error("Node 22+ is required.");
60
+ process.exit(1);
61
+ }
62
+
63
+ const dir = mkdtempSync(join(tmpdir(), "hunt-dribbble-"));
64
+ let proc;
65
+ const drop = () => {
66
+ try {
67
+ if (proc?.pid) process.kill(proc.pid, "SIGKILL");
68
+ } catch {}
69
+ try {
70
+ rmSync(dir, { recursive: true, force: true });
71
+ } catch {}
72
+ };
73
+ process.once("exit", drop);
74
+
75
+ proc = spawn(
76
+ exe,
77
+ [
78
+ "--headless=new",
79
+ "--remote-debugging-port=0",
80
+ `--user-data-dir=${dir}`,
81
+ "--no-first-run",
82
+ "--hide-scrollbars",
83
+ "--mute-audio",
84
+ "--force-color-profile=srgb",
85
+ "--window-size=1440,900",
86
+ "about:blank",
87
+ ],
88
+ { stdio: ["ignore", "ignore", "pipe"] },
89
+ );
90
+
91
+ let buf = "";
92
+ const wsUrl = await new Promise((resolveWs, reject) => {
93
+ const t = setTimeout(() => reject(new Error("Chrome did not start")), 20000);
94
+ proc.stderr.on("data", (d) => {
95
+ buf += d.toString();
96
+ const m = buf.match(/DevTools listening on (ws:\/\/[^\s]+)/);
97
+ if (m) {
98
+ clearTimeout(t);
99
+ resolveWs(m[1]);
100
+ }
101
+ });
102
+ proc.on("exit", (code) => {
103
+ clearTimeout(t);
104
+ reject(new Error(`Chrome exited ${code}`));
105
+ });
106
+ });
107
+
108
+ const ws = new WebSocket(wsUrl);
109
+ await new Promise((res, rej) => {
110
+ ws.onopen = res;
111
+ ws.onerror = () => rej(new Error("CDP socket failed"));
112
+ });
113
+ let nextId = 1;
114
+ const pending = new Map();
115
+ ws.onmessage = (ev) => {
116
+ const msg = JSON.parse(typeof ev.data === "string" ? ev.data : Buffer.from(ev.data).toString());
117
+ if (msg.id && pending.has(msg.id)) {
118
+ const { resolve: ok, reject: bad } = pending.get(msg.id);
119
+ pending.delete(msg.id);
120
+ if (msg.error) bad(new Error(msg.error.message));
121
+ else ok(msg.result);
122
+ }
123
+ };
124
+ const send = (method, params = {}, sessionId, timeoutMs = 30000) => {
125
+ const id = nextId++;
126
+ return new Promise((resolveSend, reject) => {
127
+ const timer = setTimeout(() => {
128
+ pending.delete(id);
129
+ reject(new Error(`CDP timeout: ${method}`));
130
+ }, timeoutMs);
131
+ pending.set(id, {
132
+ resolve: (v) => {
133
+ clearTimeout(timer);
134
+ resolveSend(v);
135
+ },
136
+ reject: (e) => {
137
+ clearTimeout(timer);
138
+ reject(e);
139
+ },
140
+ });
141
+ ws.send(JSON.stringify(sessionId ? { id, method, params, sessionId } : { id, method, params }));
142
+ });
143
+ };
144
+
145
+ const { targetId } = await send("Target.createTarget", { url: "about:blank" });
146
+ const { sessionId } = await send("Target.attachToTarget", { targetId, flatten: true });
147
+ const page = (method, params, timeoutMs) => send(method, params, sessionId, timeoutMs);
148
+
149
+ await page("Page.enable");
150
+ await page("Runtime.enable");
151
+ await page("Emulation.setDeviceMetricsOverride", {
152
+ width: 1440,
153
+ height: 900,
154
+ deviceScaleFactor: 1,
155
+ mobile: false,
156
+ });
157
+ await page("Page.navigate", { url }, 40000);
158
+ await sleep(3000);
159
+
160
+ for (let i = 0; i < scrolls; i++) {
161
+ await page("Runtime.evaluate", {
162
+ expression: "window.scrollBy(0, Math.round(window.innerHeight * 0.9))",
163
+ returnByValue: true,
164
+ });
165
+ await sleep(900);
166
+ }
167
+
168
+ const { result } = await page("Runtime.evaluate", {
169
+ expression: `(() => {
170
+ const rows = [];
171
+ const seen = new Set();
172
+ for (const li of document.querySelectorAll("li")) {
173
+ const a = li.querySelector('a[href*="/shots/"]');
174
+ if (!a) continue;
175
+ const m = (a.getAttribute("href") || "").match(/\\/shots\\/([^/?#]+)/);
176
+ if (!m) continue;
177
+ const idSlug = m[1];
178
+ if (seen.has(idSlug)) continue;
179
+ const img = li.querySelector("img");
180
+ if (!img) continue;
181
+ const raw = img.getAttribute("data-src") || img.currentSrc || img.src || "";
182
+ const imageURL = raw.replace(/\\?.*$/, "");
183
+ if (!imageURL) continue;
184
+ seen.add(idSlug);
185
+ const text = (li.innerText || "").replace(/\\s+/g, " ");
186
+ const vm = text.match(/([\\d.]+\\s*[kKmM]?)\\s*views?/i) || text.match(/([\\d.]+\\s*[kKmM]?)/);
187
+ const views = vm ? vm[1].replace(/\\s+/g, "") : "";
188
+ const title = (img.getAttribute("alt") || a.getAttribute("title") || idSlug).replace(/\\t/g, " ").trim();
189
+ rows.push([idSlug, views, imageURL, title].join("\\t"));
190
+ }
191
+ return rows.join("\\n");
192
+ })()`,
193
+ returnByValue: true,
194
+ });
195
+
196
+ const tsv = result?.value || "";
197
+ if (!tsv.trim()) {
198
+ console.error("0 cards (empty listing or rate limit — retry once after a pause)");
199
+ drop();
200
+ process.exit(1);
201
+ }
202
+ console.log(tsv);
203
+ drop();
204
+ process.exit(0);