@jonandev/longbeard 0.11.2 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/AGENTS.md +4 -5
  2. package/CHANGELOG.md +72 -0
  3. package/README.md +64 -43
  4. package/beard.json +124 -28
  5. package/bin/long-beard.js +171 -36
  6. package/package.json +1 -1
  7. package/skills/design/SKILL.md +51 -126
  8. package/skills/design-brief/SKILL.md +146 -0
  9. package/skills/design-brief/references/graphic.md +59 -0
  10. package/skills/design-check/SKILL.md +27 -11
  11. package/skills/design-check/references/design-rules.md +21 -7
  12. package/skills/design-check/scripts/capture.mjs +121 -37
  13. package/skills/design-check/scripts/contrast.mjs +23 -9
  14. package/skills/design-check/scripts/rules.mjs +613 -0
  15. package/skills/design-check/scripts/screen-contrast.mjs +428 -0
  16. package/skills/design-check/scripts/tokens.mjs +346 -0
  17. package/skills/design-content/SKILL.md +118 -0
  18. package/skills/design-content/scripts/contact-sheet.mjs +259 -0
  19. package/skills/design-content/scripts/pictures.mjs +197 -0
  20. package/skills/design-direction/SKILL.md +115 -200
  21. package/skills/design-direction/references/controls.md +58 -0
  22. package/skills/{design → design-direction}/references/design-rules.md +21 -7
  23. package/skills/design-direction/references/five-second.md +47 -0
  24. package/skills/design-direction/references/full-build.md +19 -0
  25. package/skills/design-direction/references/graphic.md +35 -0
  26. package/skills/design-direction/references/grid.md +114 -0
  27. package/skills/design-direction/references/library.md +75 -0
  28. package/skills/design-direction/references/screen-template.html +233 -0
  29. package/skills/design-direction/references/subject.md +33 -0
  30. package/skills/design-direction/scripts/capture.mjs +121 -37
  31. package/skills/design-direction/scripts/contact-sheet.mjs +18 -7
  32. package/skills/design-direction/scripts/fonts.mjs +276 -0
  33. package/skills/design-direction/scripts/layout-diff.mjs +118 -0
  34. package/skills/design-direction/scripts/measure.mjs +1728 -0
  35. package/skills/design-direction/scripts/moodboard.mjs +123 -32
  36. package/skills/design-direction/scripts/picture-cast.mjs +270 -0
  37. package/skills/design-direction/scripts/pictures.mjs +197 -0
  38. package/skills/design-direction/scripts/screen-contrast.mjs +428 -0
  39. package/skills/design-direction/scripts/sheet.mjs +67 -0
  40. package/skills/design-direction/scripts/subject-colours.mjs +410 -0
  41. package/skills/design-families/SKILL.md +138 -0
  42. package/skills/design-families/scripts/contact-sheet.mjs +259 -0
  43. package/skills/design-families/scripts/families.mjs +606 -0
  44. package/skills/design-families/scripts/measure.mjs +1728 -0
  45. package/skills/design-families/scripts/moodboard.mjs +467 -0
  46. package/skills/design-families/scripts/tag.mjs +289 -0
  47. package/skills/design-figma/SKILL.md +69 -0
  48. package/skills/design-figma/references/graphic.md +26 -0
  49. package/skills/design-identity/SKILL.md +134 -0
  50. package/skills/design-identity/references/graphic.md +8 -0
  51. package/skills/design-identity/references/identity-board.html +140 -0
  52. package/skills/{design → design-identity}/scripts/capture.mjs +121 -37
  53. package/skills/design-identity/scripts/colours.mjs +213 -0
  54. package/skills/design-identity/scripts/contrast.mjs +41 -0
  55. package/skills/design-identity/scripts/fonts.mjs +276 -0
  56. package/skills/design-identity/scripts/measure.mjs +1728 -0
  57. package/skills/design-identity/scripts/sheet.mjs +67 -0
  58. package/skills/design-identity/scripts/subject-colours.mjs +410 -0
  59. package/skills/design-moodboard/SKILL.md +184 -0
  60. package/skills/design-moodboard/references/graphic.md +25 -0
  61. package/skills/{design-direction → design-moodboard}/references/sources.md +21 -11
  62. package/skills/design-moodboard/scripts/capture.mjs +893 -0
  63. package/skills/design-moodboard/scripts/contact-sheet.mjs +259 -0
  64. package/skills/design-moodboard/scripts/crops.mjs +256 -0
  65. package/skills/design-moodboard/scripts/dribbble-cards.mjs +418 -0
  66. package/skills/design-moodboard/scripts/families.mjs +606 -0
  67. package/skills/design-moodboard/scripts/group.mjs +221 -0
  68. package/skills/design-moodboard/scripts/measure.mjs +1728 -0
  69. package/skills/design-moodboard/scripts/moodboard.mjs +467 -0
  70. package/skills/{design-direction → design-moodboard}/scripts/picker.mjs +121 -20
  71. package/skills/design-moodboard/scripts/pictures.mjs +197 -0
  72. package/skills/design-moodboard/scripts/tag.mjs +289 -0
  73. package/skills/design-prototype/SKILL.md +149 -0
  74. package/skills/design-prototype/references/design-md-template.md +82 -0
  75. package/skills/design-prototype/references/design-rules.md +203 -0
  76. package/skills/design-prototype/references/five-second.md +47 -0
  77. package/skills/design-prototype/references/graphic.md +27 -0
  78. package/skills/design-prototype/scripts/capture.mjs +893 -0
  79. package/skills/design-prototype/scripts/contrast.mjs +41 -0
  80. package/skills/design-prototype/scripts/links.mjs +308 -0
  81. package/skills/design-prototype/scripts/pictures.mjs +197 -0
  82. package/skills/design-prototype/scripts/rules.mjs +613 -0
  83. package/skills/design-prototype/scripts/screen-contrast.mjs +428 -0
  84. package/skills/design-prototype/scripts/sheet.mjs +67 -0
  85. package/skills/design-prototype/scripts/tokens.mjs +346 -0
  86. package/skills/design-wordmark/SKILL.md +65 -0
  87. package/skills/design-wordmark/scripts/capture.mjs +893 -0
  88. package/skills/design-wordmark/scripts/sheet.mjs +67 -0
  89. package/skills/framework-skills/SKILL.md +71 -0
  90. package/skills/idea/SKILL.md +13 -7
  91. package/skills/idea/references/graphic.md +64 -0
  92. package/skills/design/references/design-md-template.md +0 -58
  93. package/skills/design/scripts/contrast.mjs +0 -27
  94. package/skills/design-direction/scripts/dribbble-cards.mjs +0 -356
@@ -0,0 +1,259 @@
1
+ #!/usr/bin/env node
2
+ // Build labelled contact sheets from a TSV of label\timageURL. The image can
3
+ // be a local file too, so a family's references are sorted by eye from a few
4
+ // sheets of thumbnails, not opened one at a time.
5
+ // Writes JPEG grids (~36 per sheet) into an output directory (scratch, not .longbeard/design/).
6
+ // Viewing listing thumbnails is allowed; this is not a capture.
7
+ //
8
+ // node contact-sheet.mjs candidates.tsv --out /tmp/hunt-sheets
9
+ // node contact-sheet.mjs family-f3.tsv --out <scratch>/f3 --contain # TSV: label<TAB>refs/name.jpg
10
+ import { spawn } from "node:child_process";
11
+ import {
12
+ existsSync,
13
+ mkdirSync,
14
+ mkdtempSync,
15
+ readFileSync,
16
+ rmSync,
17
+ writeFileSync,
18
+ } from "node:fs";
19
+ import { tmpdir } from "node:os";
20
+ import { join, resolve } from "node:path";
21
+ import { pathToFileURL } from "node:url";
22
+
23
+ const args = process.argv.slice(2);
24
+ const flag = (name, def) => {
25
+ const i = args.indexOf(`--${name}`);
26
+ if (i === -1) return def;
27
+ const v = args[i + 1];
28
+ args.splice(i, 2);
29
+ return v;
30
+ };
31
+ const tsvPath = args[0];
32
+ const outDir = resolve(flag("out", "") || "");
33
+ const perSheet = Math.max(1, Number(flag("per", "36")) || 36);
34
+ const cols = Math.min(8, Math.max(1, Number(flag("cols", "6")) || 6));
35
+ const containAt = args.indexOf("--contain");
36
+ const contain = containAt !== -1;
37
+ if (contain) args.splice(containAt, 1);
38
+ if (!tsvPath || !outDir) {
39
+ console.error("usage: node contact-sheet.mjs candidates.tsv --out <scratch>/sheets [--per 36] [--cols 6] [--contain]");
40
+ process.exit(2);
41
+ }
42
+
43
+ const lines = readFileSync(tsvPath, "utf8")
44
+ .split(/\r?\n/)
45
+ .map((l) => l.trim())
46
+ .filter(Boolean)
47
+ .map((l) => {
48
+ // label\timageURL, and any columns after that (a listing URL) are ignored.
49
+ const cols = l.split("\t").map((c) => c.trim());
50
+ if (cols.length === 1) return { label: l, url: l };
51
+ return { label: cols[0], url: cols[1] };
52
+ })
53
+ .map((r) => (/^https?:\/\//i.test(r.url) || !existsSync(r.url) ? r : { ...r, url: pathToFileURL(resolve(r.url)).href }))
54
+ .filter((r) => /^(https?|file):\/\//i.test(r.url));
55
+
56
+ if (!lines.length) {
57
+ console.error("no label\timageURL rows found");
58
+ process.exit(1);
59
+ }
60
+
61
+ function findChrome() {
62
+ const env = process.env.CHROME_PATH;
63
+ // CHROME_PATH=none: run as if no browser were installed (a quick test run).
64
+ if (env === "none") return null;
65
+ if (env && existsSync(env)) return env;
66
+ const home = process.env.HOME || process.env.USERPROFILE || "";
67
+ const local = process.env.LOCALAPPDATA || "";
68
+ const pf = process.env.PROGRAMFILES || "C:\\Program Files";
69
+ const pf86 = process.env["PROGRAMFILES(X86)"] || "C:\\Program Files (x86)";
70
+ const candidates = [
71
+ join(pf, "Google/Chrome/Application/chrome.exe"),
72
+ join(pf86, "Google/Chrome/Application/chrome.exe"),
73
+ join(local, "Google/Chrome/Application/chrome.exe"),
74
+ join(pf, "Microsoft/Edge/Application/msedge.exe"),
75
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
76
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
77
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
78
+ join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
79
+ "/usr/bin/google-chrome",
80
+ "/usr/bin/google-chrome-stable",
81
+ "/usr/bin/chromium",
82
+ "/usr/bin/chromium-browser",
83
+ ];
84
+ return candidates.find((path) => path && existsSync(path)) || null;
85
+ }
86
+
87
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
88
+ const exe = findChrome();
89
+ if (!exe) {
90
+ console.error("No Chrome/Edge/Chromium found. Install one or set CHROME_PATH.");
91
+ process.exit(1);
92
+ }
93
+ if (typeof WebSocket === "undefined") {
94
+ console.error("Node 22+ is required.");
95
+ process.exit(1);
96
+ }
97
+
98
+ const dir = mkdtempSync(join(tmpdir(), "hunt-sheet-"));
99
+ let proc;
100
+ const drop = () => {
101
+ try {
102
+ if (proc?.pid) process.kill(proc.pid, "SIGKILL");
103
+ } catch {}
104
+ try {
105
+ rmSync(dir, { recursive: true, force: true });
106
+ } catch {}
107
+ };
108
+ process.once("exit", drop);
109
+
110
+ proc = spawn(
111
+ exe,
112
+ [
113
+ "--headless=new",
114
+ "--remote-debugging-port=0",
115
+ `--user-data-dir=${dir}`,
116
+ "--no-first-run",
117
+ "--hide-scrollbars",
118
+ "--mute-audio",
119
+ "--force-color-profile=srgb",
120
+ "--window-size=1600,1200",
121
+ "about:blank",
122
+ ],
123
+ { stdio: ["ignore", "ignore", "pipe"] },
124
+ );
125
+
126
+ let buf = "";
127
+ const wsUrl = await new Promise((resolveWs, reject) => {
128
+ const t = setTimeout(() => reject(new Error("Chrome did not start")), 20000);
129
+ proc.stderr.on("data", (d) => {
130
+ buf += d.toString();
131
+ const m = buf.match(/DevTools listening on (ws:\/\/[^\s]+)/);
132
+ if (m) {
133
+ clearTimeout(t);
134
+ resolveWs(m[1]);
135
+ }
136
+ });
137
+ proc.on("exit", (code) => {
138
+ clearTimeout(t);
139
+ reject(new Error(`Chrome exited ${code}`));
140
+ });
141
+ });
142
+
143
+ const ws = new WebSocket(wsUrl);
144
+ await new Promise((res, rej) => {
145
+ ws.onopen = res;
146
+ ws.onerror = () => rej(new Error("CDP socket failed"));
147
+ });
148
+ let nextId = 1;
149
+ const pending = new Map();
150
+ ws.onmessage = (ev) => {
151
+ const msg = JSON.parse(typeof ev.data === "string" ? ev.data : Buffer.from(ev.data).toString());
152
+ if (msg.id && pending.has(msg.id)) {
153
+ const { resolve: ok, reject: bad } = pending.get(msg.id);
154
+ pending.delete(msg.id);
155
+ if (msg.error) bad(new Error(msg.error.message));
156
+ else ok(msg.result);
157
+ }
158
+ };
159
+ const send = (method, params = {}, sessionId, timeoutMs = 30000) => {
160
+ const id = nextId++;
161
+ return new Promise((resolveSend, reject) => {
162
+ const timer = setTimeout(() => {
163
+ pending.delete(id);
164
+ reject(new Error(`CDP timeout: ${method}`));
165
+ }, timeoutMs);
166
+ pending.set(id, {
167
+ resolve: (v) => {
168
+ clearTimeout(timer);
169
+ resolveSend(v);
170
+ },
171
+ reject: (e) => {
172
+ clearTimeout(timer);
173
+ reject(e);
174
+ },
175
+ });
176
+ ws.send(JSON.stringify(sessionId ? { id, method, params, sessionId } : { id, method, params }));
177
+ });
178
+ };
179
+
180
+ const { targetId } = await send("Target.createTarget", { url: "about:blank" });
181
+ const { sessionId } = await send("Target.attachToTarget", { targetId, flatten: true });
182
+ const page = (method, params, timeoutMs) => send(method, params, sessionId, timeoutMs);
183
+
184
+ await page("Page.enable");
185
+ await page("Runtime.enable");
186
+ await page("Emulation.setDeviceMetricsOverride", {
187
+ width: 1600,
188
+ height: 1200,
189
+ deviceScaleFactor: 1,
190
+ mobile: false,
191
+ });
192
+
193
+ mkdirSync(outDir, { recursive: true });
194
+ const sheets = [];
195
+ for (let i = 0; i < lines.length; i += perSheet) {
196
+ sheets.push(lines.slice(i, i + perSheet));
197
+ }
198
+
199
+ const esc = (s) =>
200
+ String(s)
201
+ .replace(/&/g, "&amp;")
202
+ .replace(/</g, "&lt;")
203
+ .replace(/>/g, "&gt;")
204
+ .replace(/"/g, "&quot;");
205
+
206
+ for (let s = 0; s < sheets.length; s++) {
207
+ const cells = sheets[s]
208
+ .map(
209
+ (r) =>
210
+ `<figure><img src="${esc(r.url)}" loading="eager"><figcaption>${esc(r.label)}</figcaption></figure>`,
211
+ )
212
+ .join("\n");
213
+ const html = `<!doctype html><meta charset=utf-8>
214
+ <style>
215
+ body { margin: 16px; background: #1a1a1a; color: #eee; font: 11px/1.2 system-ui, sans-serif; }
216
+ .grid { display: grid; grid-template-columns: repeat(${cols}, 1fr); gap: 10px; }
217
+ figure { margin: 0; background: #2a2a2a; border-radius: 4px; overflow: hidden; }
218
+ img { display: block; width: 100%; height: ${contain ? Math.round(1200 / cols) : 140}px; object-fit: ${contain ? "contain" : "cover"}; background: #111; }
219
+ figcaption { padding: 6px 8px; word-break: break-word; max-height: 2.4em; overflow: hidden; }
220
+ </style>
221
+ <div class="grid">${cells}</div>
222
+ <script>
223
+ Promise.all([...document.images].map((img) => img.decode().catch(() => {}))).then(() => {
224
+ document.title = "ready";
225
+ });
226
+ </script>`;
227
+ const htmlPath = join(dir, `sheet-${s + 1}.html`);
228
+ writeFileSync(htmlPath, html);
229
+ await page("Page.navigate", { url: pathToFileURL(htmlPath).href }, 30000);
230
+ await sleep(500);
231
+ for (let i = 0; i < 60; i++) {
232
+ const title = (
233
+ await page("Runtime.evaluate", { expression: "document.title", returnByValue: true })
234
+ ).result.value;
235
+ if (title === "ready") break;
236
+ await sleep(150);
237
+ }
238
+ await sleep(400);
239
+ const metrics = await page("Page.getLayoutMetrics");
240
+ const size = metrics.cssContentSize || metrics.contentSize;
241
+ const width = Math.max(1, Math.ceil(size.width || 1600));
242
+ const height = Math.max(1, Math.min(Math.ceil(size.height || 1200), 8000));
243
+ const { data } = await page(
244
+ "Page.captureScreenshot",
245
+ {
246
+ format: "jpeg",
247
+ quality: 80,
248
+ captureBeyondViewport: true,
249
+ clip: { x: 0, y: 0, width, height, scale: 1 },
250
+ },
251
+ 60000,
252
+ );
253
+ const outPath = join(outDir, `sheet-${String(s + 1).padStart(2, "0")}.jpg`);
254
+ writeFileSync(outPath, Buffer.from(data, "base64"));
255
+ console.log(outPath);
256
+ }
257
+
258
+ drop();
259
+ process.exit(0);
@@ -0,0 +1,256 @@
1
+ #!/usr/bin/env node
2
+ // Cut a Figma board's cards out of the images they share, so each image is
3
+ // downloaded once, not once per card. Many boards crop every card from a
4
+ // larger upload: the card's fill has scaleMode CROP and an imageTransform
5
+ // [[a,0,tx],[0,d,ty]], which shows the region x from tx to tx+a and y from ty
6
+ // to ty+d of the image, as fractions. Node 22+, an installed Chrome, no
7
+ // dependencies.
8
+ //
9
+ // node crops.mjs cards.json --list
10
+ // node crops.mjs cards.json --sheets <dir> --out .longbeard/design/moodboard/refs
11
+ //
12
+ // cards.json is what use_figma read from the board, a list (or { "cards": [] }):
13
+ // [{ "name": "<card name>", "hash": "<imageHash>", "transform": [[a,0,tx],[0,d,ty]],
14
+ // "caption": "<optional>", "tags": ["<optional>"] }]
15
+ //
16
+ // --list prints each distinct image to download, one a line: hash<TAB>cards using it.
17
+ // --sheets is the folder of those downloads, each named <hash>.<png|jpg|jpeg|webp|gif>.
18
+ // Each download is checked: its SHA-1 must be its hash, or its cards are skipped and named.
19
+ // A missing sheet, or a transform that rotates or skews, skips its cards the same way.
20
+ // Each card is written at the sheet's own pixel size to <out>/<card-name>.png, and
21
+ // <out>/crops.tsv lists name, file, caption and tags (joined with +), for tag.mjs to seed
22
+ // from. Exit 1 when any card was skipped; the others are still written.
23
+ import { spawn } from "node:child_process";
24
+ import { createHash } from "node:crypto";
25
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
26
+ import { tmpdir } from "node:os";
27
+ import { extname, join, resolve } from "node:path";
28
+ if (typeof WebSocket === "undefined") { console.error("Node 22+ is required."); process.exit(1); }
29
+
30
+ const args = process.argv.slice(2);
31
+ const flag = (name) => {
32
+ const i = args.indexOf(`--${name}`);
33
+ return i === -1 ? "" : (args.splice(i, 2)[1] ?? "");
34
+ };
35
+ const has = (name) => {
36
+ const i = args.indexOf(`--${name}`);
37
+ return i === -1 ? false : (args.splice(i, 1), true);
38
+ };
39
+ const list = has("list");
40
+ const sheetsArg = flag("sheets");
41
+ const outArg = flag("out");
42
+ const [input] = args;
43
+ const usage = "usage: node crops.mjs cards.json --list | node crops.mjs cards.json --sheets <dir> --out <refs dir>";
44
+ if (!input || args.length !== 1 || (!list && (!sheetsArg || !outArg))) {
45
+ console.error(usage);
46
+ process.exit(2);
47
+ }
48
+ const fail = (text) => {
49
+ console.error(`crops: ${text}`);
50
+ process.exit(1);
51
+ };
52
+ if (!existsSync(input)) fail(`nothing at ${input}`);
53
+ let cards;
54
+ try {
55
+ const raw = JSON.parse(readFileSync(input, "utf8"));
56
+ cards = Array.isArray(raw) ? raw : raw.cards;
57
+ } catch (e) {
58
+ fail(`${input} is not JSON: ${e.message}`);
59
+ }
60
+ if (!Array.isArray(cards) || !cards.length) fail(`${input} holds no cards`);
61
+ for (const c of cards) if (!c.name || !c.hash) fail(`every card needs a name and a hash (${JSON.stringify(c).slice(0, 80)})`);
62
+
63
+ const byHash = new Map();
64
+ for (const c of cards) byHash.set(c.hash.toLowerCase(), [...(byHash.get(c.hash.toLowerCase()) || []), c]);
65
+ if (list) {
66
+ for (const [hash, cs] of byHash) console.log(`${hash}\t${cs.length}`);
67
+ console.error(`crops: ${byHash.size} images to download for ${cards.length} cards`);
68
+ process.exit(0);
69
+ }
70
+ if (!existsSync(sheetsArg)) fail(`no sheets folder at ${sheetsArg}`);
71
+
72
+ // File-safe names, the card's own, so a crop keeps its name across board versions.
73
+ const used = new Set();
74
+ const fileName = (name) => {
75
+ const base = String(name).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "card";
76
+ let n = base;
77
+ for (let i = 2; used.has(n); i++) n = `${base}-${i}`;
78
+ used.add(n);
79
+ return n;
80
+ };
81
+
82
+ const skipped = [];
83
+ const skip = (c, why) => skipped.push(`${c.name}: ${why}`);
84
+ const files = readdirSync(sheetsArg);
85
+ const MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif" };
86
+ const jobs = [];
87
+ for (const [hash, cs] of byHash) {
88
+ const file = files.find((f) => f.toLowerCase().startsWith(`${hash}.`) && MIME[extname(f).toLowerCase()]);
89
+ if (!file) {
90
+ for (const c of cs) skip(c, `no sheet ${hash} in ${sheetsArg}`);
91
+ continue;
92
+ }
93
+ const bytes = readFileSync(join(sheetsArg, file));
94
+ const sha = createHash("sha1").update(bytes).digest("hex");
95
+ if (sha !== hash) {
96
+ console.error(`crops: ${file} does not match its hash (its SHA-1 is ${sha}): its ${cs.length} cards skipped`);
97
+ for (const c of cs) skip(c, `sheet ${file} does not match its hash`);
98
+ continue;
99
+ }
100
+ const regions = [];
101
+ for (const c of cs) {
102
+ const t = c.transform || [[1, 0, 0], [0, 1, 0]];
103
+ const ok = Array.isArray(t) && t.length === 2 && t.every((r) => Array.isArray(r) && r.length === 3 && r.every(Number.isFinite));
104
+ if (!ok) {
105
+ skip(c, "transform is not [[a,0,tx],[0,d,ty]]");
106
+ continue;
107
+ }
108
+ const [[a, b, tx], [cc, d, ty]] = t;
109
+ if (Math.abs(b) > 1e-9 || Math.abs(cc) > 1e-9) {
110
+ skip(c, "transform rotates or skews");
111
+ continue;
112
+ }
113
+ if (!(a > 0 && d > 0)) {
114
+ skip(c, "transform has no area");
115
+ continue;
116
+ }
117
+ regions.push({ card: c, file: fileName(c.name), a, d, tx, ty });
118
+ }
119
+ if (regions.length) jobs.push({ hash, mime: MIME[extname(file).toLowerCase()], data: bytes.toString("base64"), regions });
120
+ }
121
+
122
+ function findChrome() {
123
+ const env = process.env.CHROME_PATH;
124
+ // CHROME_PATH=none: run as if no browser were installed (a quick test run).
125
+ if (env === "none") return null;
126
+ if (env && existsSync(env)) return env;
127
+ const home = process.env.HOME || process.env.USERPROFILE || "";
128
+ const pf = process.env.PROGRAMFILES || "C:\\Program Files";
129
+ return [
130
+ join(pf, "Google/Chrome/Application/chrome.exe"),
131
+ join(process.env.LOCALAPPDATA || "", "Google/Chrome/Application/chrome.exe"),
132
+ join(pf, "Microsoft/Edge/Application/msedge.exe"),
133
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
134
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
135
+ join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
136
+ "/usr/bin/google-chrome",
137
+ "/usr/bin/google-chrome-stable",
138
+ "/usr/bin/chromium",
139
+ "/usr/bin/chromium-browser",
140
+ ].find((path) => path && existsSync(path));
141
+ }
142
+
143
+ const out = resolve(outArg);
144
+ mkdirSync(out, { recursive: true });
145
+ const rows = [];
146
+ let written = 0;
147
+ if (jobs.length) {
148
+ const exe = findChrome();
149
+ if (!exe) fail("No Chrome/Edge/Chromium found. Install one or set CHROME_PATH.");
150
+ const dir = mkdtempSync(join(tmpdir(), "crops-chrome-"));
151
+ const proc = spawn(exe, ["--headless=new", "--remote-debugging-port=0", `--user-data-dir=${dir}`, "--no-first-run", "--force-color-profile=srgb", "about:blank"], { stdio: ["ignore", "ignore", "pipe"] });
152
+ const drop = () => {
153
+ try {
154
+ proc.kill("SIGKILL");
155
+ } catch {}
156
+ try {
157
+ rmSync(dir, { recursive: true, force: true });
158
+ } catch {}
159
+ };
160
+ process.once("exit", drop);
161
+ // An interrupt or a harness timeout must not leave Chrome or its profile behind.
162
+ for (const [sig, code] of [["SIGINT", 130], ["SIGTERM", 143]]) {
163
+ process.once(sig, () => {
164
+ drop();
165
+ process.exit(code);
166
+ });
167
+ }
168
+ proc.on("error", (e) => fail(`could not start ${exe}: ${e.message}`));
169
+ let buf = "";
170
+ const wsUrl = await new Promise((done, no) => {
171
+ const t = setTimeout(() => no(new Error("Chrome did not start")), 20000);
172
+ proc.stderr.on("data", (d) => {
173
+ const m = (buf += d).match(/DevTools listening on (ws:\/\/\S+)/);
174
+ if (m) done(m[1], clearTimeout(t));
175
+ });
176
+ proc.on("exit", (code) => no(new Error(`Chrome exited ${code}`)));
177
+ }).catch((e) => fail(e.message));
178
+ const ws = new WebSocket(wsUrl);
179
+ await new Promise((done, no) => {
180
+ const t = setTimeout(() => no(new Error("CDP socket did not open")), 10000);
181
+ ws.onopen = () => done(clearTimeout(t));
182
+ ws.onerror = () => no(new Error("CDP socket failed"));
183
+ }).catch((e) => fail(e.message));
184
+ let nextId = 0;
185
+ const pending = new Map();
186
+ ws.onmessage = (ev) => {
187
+ const msg = JSON.parse(String(ev.data));
188
+ if (pending.has(msg.id)) pending.get(msg.id)(msg), pending.delete(msg.id);
189
+ };
190
+ // If Chrome goes away, every call waiting on it fails now, not at its time limit.
191
+ ws.onclose = () => {
192
+ for (const done of [...pending.values()]) done({ error: { message: "Chrome closed the connection" } });
193
+ pending.clear();
194
+ };
195
+ // Every call has a time limit, so a sheet that hangs the page skips its own cards.
196
+ const send = (method, params = {}, sessionId, timeoutMs = 60000) =>
197
+ new Promise((done, no) => {
198
+ const id = ++nextId;
199
+ const timer = setTimeout(() => (pending.delete(id), no(new Error(`Chrome did not answer ${method} in ${timeoutMs / 1000} s`))), timeoutMs);
200
+ pending.set(id, (msg) => done((clearTimeout(timer), msg)));
201
+ try {
202
+ ws.send(JSON.stringify({ id, method, params, sessionId }));
203
+ } catch (e) {
204
+ clearTimeout(timer);
205
+ pending.delete(id);
206
+ no(e);
207
+ }
208
+ });
209
+ const { result: target } = await send("Target.createTarget", { url: "about:blank" }).catch((e) => fail(e.message));
210
+ const { result: att } = await send("Target.attachToTarget", { targetId: target.targetId, flatten: true }).catch((e) => fail(e.message));
211
+ const evaluate = async (expression) => {
212
+ const r = await send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true }, att.sessionId);
213
+ if (r.error) throw new Error(r.error.message);
214
+ if (r.result?.exceptionDetails) throw new Error(r.result.exceptionDetails.exception?.description || "the page threw");
215
+ return r.result.result.value;
216
+ };
217
+ // One sheet at a time, so a board of large sheets never holds them all in memory.
218
+ for (const job of jobs) {
219
+ const regions = job.regions.map(({ a, d, tx, ty }) => ({ a, d, tx, ty }));
220
+ let crops;
221
+ try {
222
+ crops = await evaluate(`(async () => {
223
+ const img = new Image();
224
+ img.src = "data:${job.mime};base64,${job.data}";
225
+ await img.decode();
226
+ const W = img.naturalWidth, H = img.naturalHeight;
227
+ return ${JSON.stringify(regions)}.map(({ a, d, tx, ty }) => {
228
+ // A region that starts before the sheet loses that part of its width and height too.
229
+ const x0 = Math.round(tx * W), y0 = Math.round(ty * H);
230
+ const x = Math.max(0, x0), y = Math.max(0, y0);
231
+ const w = Math.min(W, x0 + Math.round(a * W)) - x, h = Math.min(H, y0 + Math.round(d * H)) - y;
232
+ if (w < 1 || h < 1) return null;
233
+ const c = Object.assign(document.createElement("canvas"), { width: w, height: h });
234
+ c.getContext("2d").drawImage(img, x, y, w, h, 0, 0, w, h);
235
+ return c.toDataURL("image/png").split(",")[1];
236
+ });
237
+ })()`);
238
+ } catch (e) {
239
+ for (const r of job.regions) skip(r.card, `sheet ${job.hash} did not decode (${String(e.message).split("\n")[0]})`);
240
+ continue;
241
+ }
242
+ job.regions.forEach((r, i) => {
243
+ if (!crops[i]) return skip(r.card, "region falls outside its sheet");
244
+ const path = join(out, `${r.file}.png`);
245
+ writeFileSync(path, Buffer.from(crops[i], "base64"));
246
+ rows.push([r.card.name, path, (r.card.caption || "").replace(/[\t\n]+/g, " "), (r.card.tags || []).join("+")].join("\t"));
247
+ written++;
248
+ });
249
+ }
250
+ ws.close();
251
+ }
252
+
253
+ writeFileSync(join(out, "crops.tsv"), `name\tfile\tcaption\ttags\n${rows.map((r) => `${r}\n`).join("")}`);
254
+ for (const s of skipped) console.error(`crops: skipped ${s}`);
255
+ console.error(`crops: ${written} cards from ${jobs.length} sheets, ${skipped.length} skipped`);
256
+ process.exit(skipped.length ? 1 : 0);