@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,41 @@
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. --level AAA (the design brief's
5
+ // accessibility line) asks 7:1 for text and 4.5:1 for large text; a mark stays 3:1. Short hex (#abc) is read as #aabbcc.
6
+ // An argument it cannot read is an error: it exits 1 rather than pass unchecked.
7
+ // The ratio is cut, not rounded, to two places: 4.496 prints as 4.49 and fails, never as 4.50 FAIL.
8
+ const hex6 = (h) => (h.length === 4 ? `#${[...h.slice(1)].map((c) => c + c).join("")}` : h).toLowerCase();
9
+ const lum = (hex) => {
10
+ const [r, g, b] = [1, 3, 5]
11
+ .map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)
12
+ .map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
13
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
14
+ };
15
+ const args = process.argv.slice(2);
16
+ const at = args.indexOf("--level");
17
+ const level = at === -1 ? "AA" : String(args.splice(at, 2)[1] || "").toUpperCase();
18
+ if (level !== "AA" && level !== "AAA") {
19
+ console.error("contrast: --level is AA or AAA");
20
+ process.exit(2);
21
+ }
22
+ let failed = false;
23
+ for (const arg of args) {
24
+ const m = arg.trim().match(/^(#[0-9a-f]{3}(?:[0-9a-f]{3})?)\s+on\s+(#[0-9a-f]{3}(?:[0-9a-f]{3})?)(?::(large|mark))?$/i);
25
+ if (!m) {
26
+ console.error(`cannot read: ${arg} (write "#rrggbb on #rrggbb", optionally :large or :mark)`);
27
+ failed = true;
28
+ continue;
29
+ }
30
+ m[1] = hex6(m[1]);
31
+ m[2] = hex6(m[2]);
32
+ const [a, b] = [lum(m[1]), lum(m[2])];
33
+ const ratio = (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
34
+ const kind = (m[3] || "").toLowerCase();
35
+ const need = kind === "mark" ? 3 : kind === "large" ? (level === "AAA" ? 4.5 : 3) : level === "AAA" ? 7 : 4.5;
36
+ const best = kind === "mark" ? "" : ratio >= (kind ? 4.5 : 7) ? "AAA" : "";
37
+ const verdict = ratio < need ? "FAIL" : best || "AA";
38
+ if (verdict === "FAIL") failed = true;
39
+ console.log(`${m[1]} on ${m[2]} ${(Math.floor(ratio * 100) / 100).toFixed(2)}:1 ${verdict}${kind || level === "AAA" ? ` (${[kind, `needs ${need}:1`].filter(Boolean).join(", ")})` : ""}`);
40
+ }
41
+ process.exit(failed ? 1 : 0);
@@ -0,0 +1,276 @@
1
+ #!/usr/bin/env node
2
+ // The face options of design-identity, from Google Fonts' own list, not the agent's memory: faces of
3
+ // the same kind as the one the chosen screen has, nearest in shape first. The kind is the list's
4
+ // (serif or sans, display or text, the weight in use, Latin); the shape is measured in one Chrome,
5
+ // each face set at the weight in use: how wide it runs, its x-height, how dark it sets, and its
6
+ // stroke contrast (thick over thin, from an "o"). A face from elsewhere is still measured, given
7
+ // its kind with --kind, and --kind also overrides the list's kind for a face Google files wrongly. Node 22+, an installed Chrome, no dependencies.
8
+ //
9
+ // node fonts.mjs "Newsreader" --weight 300
10
+ // node fonts.mjs "Inter" --body the body row: text faces with 400 and 700
11
+ // node fonts.mjs "Their Face" --kind serif --css https://…/their-face.css
12
+ // a face not in Google's list, from its stylesheet
13
+ // node fonts.mjs "Italiana" --kind serif the list calls it a sans: say what it is
14
+ // node fonts.mjs --shape width=0.53,xheight=0.54,contrast=1.3 --kind sans --weight 700
15
+ // a reference that is only a picture: no face to
16
+ // name, so the shape measure.mjs read from its
17
+ // pixels (type.display) stands in for it
18
+ //
19
+ // Prints one row a face, nearest first: face, kind, width, x-height, dark, contrast (each the
20
+ // face's own, the chosen one's first), weights, axes, how widely it is used (its rank in Google's
21
+ // list, 1 the most used). The order is nearness, never taste: which to show, and why each is
22
+ // of the same kind, is still the agent's to say, and which to keep is theirs.
23
+ // --css <url> (the chosen face's own stylesheet), --count 8 (rows), --json, --metadata <file> (Google's list, saved), --local (installed faces
24
+ // only, no stylesheets: for tests)
25
+ import { spawn } from "node:child_process";
26
+ import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
27
+ import { tmpdir } from "node:os";
28
+ import { join } from "node:path";
29
+ if (typeof WebSocket === "undefined") { console.error("Node 22+ is required."); process.exit(1); }
30
+
31
+ const args = process.argv.slice(2);
32
+ const flag = (name, def = "") => {
33
+ const i = args.indexOf(`--${name}`);
34
+ return i === -1 ? def : (args.splice(i, 2)[1] ?? "");
35
+ };
36
+ const has = (name) => {
37
+ const i = args.indexOf(`--${name}`);
38
+ return i === -1 ? false : (args.splice(i, 1), true);
39
+ };
40
+ const weight = Number(flag("weight", "400"));
41
+ const count = Number(flag("count", "8"));
42
+ const kindArg = flag("kind").toLowerCase();
43
+ const metadataArg = flag("metadata");
44
+ const cssArg = flag("css");
45
+ const json = has("json");
46
+ const body = has("body");
47
+ const italic = has("italic");
48
+ const local = has("local");
49
+ const shapeArg = flag("shape");
50
+ // --shape: the shape read from a picture (measure.mjs, type.display), as width, xheight, dark and
51
+ // contrast; any left out are not compared. Its kind must be said: there is no face to look up.
52
+ const given = Object.fromEntries(shapeArg.split(",").filter(Boolean).map((kv) => kv.split("=")).map(([k, v]) => [k.trim(), Number(v)]));
53
+ const shapeBad = shapeArg && (!kindArg || !Object.keys(given).length || Object.entries(given).some(([k, v]) => !["width", "xheight", "dark", "contrast"].includes(k) || !(v > 0)));
54
+ const face = shapeArg ? "the picture's type" : args.join(" ").trim();
55
+ const KINDS = { serif: ["Serif", "Serif"], slab: ["Serif", "Slab Serif"], sans: ["Sans Serif", "Sans Serif"], display: ["Display", null], handwriting: ["Handwriting", null], mono: ["Monospace", null] };
56
+ if (!face || shapeBad || (shapeArg && args.length) || !(weight >= 100 && weight <= 1000) || !(count >= 1 && count <= 40) || (kindArg && !KINDS[kindArg])) {
57
+ console.error(`usage: node fonts.mjs "Face" [--weight 400] [--italic] [--body] [--kind ${Object.keys(KINDS).join("|")}] [--count 8] [--json]\n node fonts.mjs --shape width=0.53,xheight=0.54,dark=0.2,contrast=1.3 --kind ${Object.keys(KINDS).join("|")} [--weight 400] [--count 8] [--json]`);
58
+ process.exit(2);
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 pf = process.env.PROGRAMFILES || "C:\\Program Files";
68
+ return [
69
+ join(pf, "Google/Chrome/Application/chrome.exe"),
70
+ join(process.env.LOCALAPPDATA || "", "Google/Chrome/Application/chrome.exe"),
71
+ join(pf, "Microsoft/Edge/Application/msedge.exe"),
72
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
73
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
74
+ join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
75
+ "/usr/bin/google-chrome",
76
+ "/usr/bin/google-chrome-stable",
77
+ "/usr/bin/chromium",
78
+ "/usr/bin/chromium-browser",
79
+ ].find((path) => path && existsSync(path));
80
+ }
81
+ const exe = findChrome();
82
+ if (!exe) {
83
+ console.error("No Chrome/Edge/Chromium found. Install one or set CHROME_PATH.");
84
+ process.exit(1);
85
+ }
86
+ const dir = mkdtempSync(join(tmpdir(), "fonts-chrome-"));
87
+ 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"] });
88
+ process.once("exit", () => {
89
+ try {
90
+ proc.kill("SIGKILL");
91
+ } catch {}
92
+ try {
93
+ rmSync(dir, { recursive: true, force: true });
94
+ } catch {}
95
+ });
96
+ const fail = (text) => {
97
+ console.error(`fonts: ${text}`);
98
+ process.exit(1);
99
+ };
100
+ let buf = "";
101
+ const wsUrl = await new Promise((done, no) => {
102
+ const t = setTimeout(() => no(new Error("Chrome did not start")), 20000);
103
+ proc.stderr.on("data", (d) => {
104
+ const m = (buf += d).match(/DevTools listening on (ws:\/\/\S+)/);
105
+ if (m) done(m[1], clearTimeout(t));
106
+ });
107
+ }).catch((e) => fail(e.message));
108
+ const ws = new WebSocket(wsUrl);
109
+ await new Promise((done) => (ws.onopen = done));
110
+ let nextId = 0;
111
+ const pending = new Map();
112
+ ws.onmessage = (ev) => {
113
+ const msg = JSON.parse(String(ev.data));
114
+ if (pending.has(msg.id)) pending.get(msg.id)(msg), pending.delete(msg.id);
115
+ };
116
+ const send = (method, params = {}, sessionId) => new Promise((done) => (pending.set(++nextId, done), ws.send(JSON.stringify({ id: nextId, method, params, sessionId }))));
117
+ const { result: target } = await send("Target.createTarget", { url: "about:blank" });
118
+ const { result: att } = await send("Target.attachToTarget", { targetId: target.targetId, flatten: true });
119
+ const call = (method, params) => send(method, params, att.sessionId);
120
+ const evaluate = async (expression) => {
121
+ const r = await call("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
122
+ if (r.result?.exceptionDetails) throw new Error(r.result.exceptionDetails.exception?.description || "the page threw");
123
+ return r.result.result.value;
124
+ };
125
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
126
+ const go = async (url) => {
127
+ await call("Page.navigate", { url });
128
+ for (let i = 0; i < 150 && (await evaluate("document.readyState").catch(() => "")) !== "complete"; i++) await sleep(200);
129
+ };
130
+
131
+ // Google's list, saved for a week. Read through the browser, which uses the network the way a page does.
132
+ const saved = metadataArg || join(tmpdir(), "longbeard-google-fonts.json");
133
+ let list;
134
+ if (existsSync(saved) && (metadataArg || Date.now() - statSync(saved).mtimeMs < 7 * 864e5)) list = readFileSync(saved, "utf8");
135
+ else {
136
+ await go("https://fonts.google.com/metadata/fonts");
137
+ list = await evaluate("document.body.innerText");
138
+ if (!/familyMetadataList/.test(list || "")) fail("could not read Google Fonts' list (fonts.google.com/metadata/fonts): check the network");
139
+ writeFileSync(saved, list);
140
+ }
141
+ const families = JSON.parse(list.replace(/^\)\]\}'\s*/, "")).familyMetadataList || [];
142
+
143
+ // The kind: the list's category and stroke, display or not, in Latin, with the weight in use.
144
+ const offers = (f, w, it) => (it ? `${w}i` : `${w}`) in f.fonts || (f.axes || []).some((a) => a.tag === "wght" && a.min <= w && a.max >= w && (!it || Object.keys(f.fonts).some((k) => k.endsWith("i"))));
145
+ const isDisplay = (f) => (f.classifications || []).includes("Display");
146
+ const chosen = shapeArg ? null : families.find((f) => f.family.toLowerCase() === face.toLowerCase());
147
+ if (!chosen && !kindArg) fail(`${face} is not in Google Fonts' list: say its kind with --kind ${Object.keys(KINDS).join("|")}`);
148
+ // --kind wins over the list: Google files some faces under the wrong kind (Italiana is listed as a
149
+ // sans), and a row of the wrong kind is no row at all.
150
+ const [category, stroke] = kindArg ? KINDS[kindArg] : [chosen.category, chosen.stroke];
151
+ const display = kindArg ? kindArg === "display" : isDisplay(chosen);
152
+ const pool = families
153
+ // A shape read from a picture has no list to say display or text: both are in reach, and the shape decides.
154
+ .filter((f) => f !== chosen && f.category === category && (!stroke || !f.stroke || f.stroke === stroke) && (shapeArg ? true : isDisplay(f) === display))
155
+ // A small-caps twin is the same face; a slab in a serif's row is another kind. A slab is one Google
156
+ // lists as a slab, or, where it lists no stroke, one named so.
157
+ .filter((f) => !/ SC$/.test(f.family) && (f.stroke === "Slab Serif" || /slab/i.test(f.family)) === (stroke === "Slab Serif"))
158
+ .filter((f) => (f.subsets || []).includes("latin") && !f.isNoto && !(f.classifications || []).includes("Symbols"))
159
+ // A weight read from a picture is an estimate: a face within 100 of it is in reach, set at its nearest.
160
+ .filter((f) => (body ? offers(f, 400, false) && offers(f, 700, false) : shapeArg ? [weight, weight - 100, weight + 100].some((w) => offers(f, w, italic)) : offers(f, weight, italic)))
161
+ .sort((a, b) => a.popularity - b.popularity);
162
+ if (!pool.length) fail(`no faces of ${face}'s kind (${category}${stroke ? `, ${stroke}` : ""}${display ? ", display" : ""}) offer weight ${body ? "400 and 700" : weight}`);
163
+ // Every face of the kind is measured (a stylesheet of the sample letters only is small), so the
164
+ // less known are in reach as much as the most used. Past 800 faces, the most used 800.
165
+ const candidates = pool.slice(0, 800);
166
+ const weightOf = Object.fromEntries(candidates.map((f) => [f.family, shapeArg ? [weight, weight - 100, weight + 100].find((w) => offers(f, w, italic)) : weight]));
167
+ const rank = new Map([...families].sort((a, b) => a.popularity - b.popularity).map((f, i) => [f.family, i + 1]));
168
+
169
+ // The shape of each face, set at the weight in use. A face is only measured once it is really
170
+ // there: set with two different fallbacks, it must measure the same in both.
171
+ await go("about:blank");
172
+ const shapes = await evaluate(`(async () => {
173
+ const W = ${weight}, IT = ${italic}, LOCAL = ${local}, CSS = ${JSON.stringify(cssArg)}, SAMPLE = "Hamburgefonstivxo";
174
+ const faces = ${JSON.stringify([...(shapeArg ? [] : [face]), ...candidates.map((f) => f.family)])};
175
+ const WEIGHTS = ${JSON.stringify(weightOf)};
176
+ const c = Object.assign(document.createElement("canvas"), { width: 2400, height: 420 }).getContext("2d", { willReadFrequently: true });
177
+ const font = (name, fb, size = 120) => (IT ? "italic " : "") + (WEIGHTS[name] || W) + " " + size + "px \\"" + name + "\\", " + fb;
178
+ const load = (name) => new Promise((done) => {
179
+ if (LOCAL && !(name === faces[0] && CSS)) return done();
180
+ const fam = encodeURIComponent(name).replace(/%20/g, "+");
181
+ const link = Object.assign(document.createElement("link"), { rel: "stylesheet", href: name === faces[0] && CSS ? CSS : "https://fonts.googleapis.com/css2?family=" + fam + ":" + (IT ? "ital,wght@1," : "wght@") + (WEIGHTS[name] || W) + "&text=" + SAMPLE + "&display=block" });
182
+ const t = setTimeout(done, 8000);
183
+ link.onload = link.onerror = () => (clearTimeout(t), done());
184
+ document.head.appendChild(link);
185
+ });
186
+ // In batches, and once more for any face not in yet: two hundred stylesheets at once time out by the half.
187
+ const arrived = (n) => document.fonts.check(font(n, "serif"), SAMPLE);
188
+ for (let pass = 0; pass < 2; pass++) {
189
+ const todo = faces.filter((n) => !pass || !arrived(n));
190
+ if (pass) for (const l of [...document.querySelectorAll("link[rel=stylesheet]")]) if (todo.some((n) => l.href.includes(encodeURIComponent(n).replace(/%20/g, "+")))) l.remove();
191
+ for (let i = 0; i < todo.length; i += 25) {
192
+ const batch = todo.slice(i, i + 25);
193
+ await Promise.all(batch.map(load));
194
+ await Promise.all(batch.map((n) => document.fonts.load(font(n, "serif"), SAMPLE).catch(() => [])));
195
+ }
196
+ }
197
+ const ink = (n) => {
198
+ c.clearRect(0, 0, 2400, 420);
199
+ c.font = font(n, "serif");
200
+ c.fillText(SAMPLE, 10, 200);
201
+ const d = c.getImageData(0, 0, 2400, 420).data;
202
+ let dark = 0;
203
+ for (let i = 3; i < d.length; i += 4) dark += d[i] / 255;
204
+ return dark;
205
+ };
206
+ // Contrast: an "o" at 300 px, its side stroke (across the middle row) over its top (down the middle).
207
+ const contrast = (n) => {
208
+ c.clearRect(0, 0, 2400, 420);
209
+ c.font = font(n, "serif", 300);
210
+ const m = c.measureText("o");
211
+ c.fillText("o", 10, 380);
212
+ const d = c.getImageData(0, 0, 2400, 420).data, a = (x, y) => d[(y * 2400 + x) * 4 + 3] > 127;
213
+ const midY = Math.round(380 - m.actualBoundingBoxAscent / 2), midX = Math.round(10 + (m.actualBoundingBoxRight - m.actualBoundingBoxLeft) / 2 - m.actualBoundingBoxLeft);
214
+ const run = (get, from, to) => { let s = -1; for (let i = from; i < to; i++) { if (get(i) && s < 0) s = i; if (!get(i) && s >= 0) return i - s; } return 0; };
215
+ const side = run((x) => a(x, midY), 0, 2400), top = run((y) => a(midX, y), 0, 420);
216
+ return side && top ? side / top : null;
217
+ };
218
+ const out = {};
219
+ for (const n of faces) {
220
+ c.font = font(n, "monospace");
221
+ const mono = c.measureText(SAMPLE).width;
222
+ c.font = font(n, "serif");
223
+ const m = c.measureText(SAMPLE);
224
+ if (Math.abs(mono - m.width) > 0.5) continue;
225
+ const x = (c.font = font(n, "serif"), c.measureText("x").actualBoundingBoxAscent);
226
+ out[n] = { width: m.width / 120 / SAMPLE.length, xheight: x / 120, dark: ink(n) / (m.width * 120), contrast: contrast(n) };
227
+ }
228
+ return out;
229
+ })()`);
230
+ ws.close();
231
+
232
+ // A picture's stroke contrast reads higher than a face's "o" does once hairlines are a pixel or two
233
+ // thick; past 5 it is clamped, so a didone read at 10 still finds the didones.
234
+ if (shapeArg && given.contrast > 5) given.contrast = 5;
235
+ const mine = shapeArg ? given : shapes[face];
236
+ if (!mine) fail(`${face} did not load${local ? " (--local: it must be installed)" : chosen ? "" : " (a face not in Google's list needs --css, its stylesheet)"}: check the name and the weight (${weight})`);
237
+ const ln = (a, b) => Math.abs(Math.log(a / b));
238
+ // Only what is known counts: a shape read from a picture may lack a measure, and then it is left out.
239
+ const far = (s) => (mine.width ? ln(s.width, mine.width) / 0.12 : 0) + (mine.xheight ? Math.abs(s.xheight - mine.xheight) / 0.05 : 0) + (mine.dark ? ln(s.dark, mine.dark) / 0.2 : 0) + (mine.contrast ? (s.contrast ? ln(s.contrast, mine.contrast) / 0.3 : 1) : 0);
240
+ const meta = new Map(families.map((f) => [f.family, f]));
241
+ const r2 = (v) => (v == null ? null : Math.round(v * 100) / 100);
242
+ const row = (name, s) => {
243
+ const f = meta.get(name);
244
+ const ws = f ? Object.keys(f.fonts).filter((k) => !k.endsWith("i")).map(Number).sort((a, b) => a - b) : [];
245
+ return {
246
+ face: name,
247
+ kind: [category, stroke !== category && stroke, display && "display"].filter(Boolean).join(", "),
248
+ width: r2(s.width),
249
+ xheight: r2(s.xheight),
250
+ dark: r2(s.dark),
251
+ contrast: r2(s.contrast),
252
+ weights: ws.length ? (ws.length > 2 ? `${ws[0]}–${ws.at(-1)}` : ws.join(",")) : "",
253
+ italic: f ? Object.keys(f.fonts).some((k) => k.endsWith("i")) : null,
254
+ axes: f ? (f.axes || []).map((a) => a.tag).join(" ") : "",
255
+ used: rank.get(name) || null,
256
+ far: r2(far(s)),
257
+ };
258
+ };
259
+ const rows = Object.entries(shapes)
260
+ .filter(([n]) => n !== face)
261
+ .map(([n, s]) => row(n, s))
262
+ .sort((a, b) => a.far - b.far)
263
+ .slice(0, count);
264
+ const missed = candidates.length - Object.keys(shapes).filter((n) => n !== face).length;
265
+ // Nothing close: say so, so the face is shown as a stand-in and others are looked at, never taken quietly.
266
+ const close = rows.length && rows[0].far <= 2;
267
+ if (shapeArg && !close) console.error(`fonts: nothing close to the picture's type (nearest is ${rows[0]?.far ?? "none"} far): render the top three with the reference's words beside it and take the one of its kind, or try --kind display, and call it a stand-in`);
268
+ const top = shapeArg ? { face, kind: row(face, { width: 1, xheight: 0, dark: 1 }).kind, ...given, far: 0 } : row(face, mine);
269
+ if (json) console.log(JSON.stringify({ chosen: top, close, rows, measured: candidates.length - missed, missed }, null, 1));
270
+ else {
271
+ const cols = ["face", "kind", "width", "xheight", "dark", "contrast", "weights", "italic", "axes", "used", "far"];
272
+ console.log(cols.join("\t"));
273
+ for (const r of [top, ...rows]) console.log(cols.map((k) => r[k] ?? "").join("\t"));
274
+ console.error(`fonts: ${candidates.length - missed} of ${pool.length} faces of this kind measured${missed ? `, ${missed} did not load` : ""}; nearest first, the chosen face on top`);
275
+ }
276
+ process.exit(0);