@jonandev/longbeard 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/AGENTS.md +3 -4
  2. package/CHANGELOG.md +72 -0
  3. package/README.md +63 -43
  4. package/beard.json +113 -26
  5. package/bin/long-beard.js +172 -36
  6. package/package.json +1 -1
  7. package/skills/design/SKILL.md +51 -122
  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 +117 -145
  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 +17 -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/idea/SKILL.md +13 -7
  90. package/skills/idea/references/graphic.md +64 -0
  91. package/skills/design/references/design-md-template.md +0 -58
  92. package/skills/design/scripts/contrast.mjs +0 -27
  93. package/skills/design-direction/scripts/dribbble-cards.mjs +0 -356
@@ -0,0 +1,197 @@
1
+ #!/usr/bin/env node
2
+ // A few clearly licensed pictures of the product's own subject, from Wikimedia Commons, to design
3
+ // with as stand-ins until the real ones come. It is not a bulk downloader: 4 by default, 12 at most.
4
+ // Only licences that hold in every country are kept: CC0, CC BY and CC BY-SA (any version), and
5
+ // public domain marked as worldwide (read from the file's templates, as the source's own licence
6
+ // name does not tell the two kinds apart). Public domain in one country only ("PD-US", "PD-Russia"),
7
+ // NC, ND, GFDL-only, fair use, unknown, and anything the source flags as restricted or non-free
8
+ // is left out. A licence that asks for credit needs an author to credit: with none, the picture
9
+ // is left out too. Node 22+, no dependencies.
10
+ //
11
+ // node pictures.mjs "sourdough bread" --out .longbeard/design/pictures
12
+ // node pictures.mjs "flour on a wooden bench" --out .longbeard/design/pictures --count 4 --min 1200 --orientation landscape
13
+ //
14
+ // Each picture is saved 1600 wide as <name>.jpg (or .png, .webp) in --out. A picture already
15
+ // credited there is skipped, so running again adds, never duplicates. Each new one gets a row in <out>/credits.tsv:
16
+ // name, file, source, author, licence, licence link, a ready credit line, share-alike (yes or no). The
17
+ // first two columns are what contact-sheet.mjs reads; a credits.tsv from before the last three columns
18
+ // stays readable, its rows just stop at the licence.
19
+ // --count 4 (1 to 12), --min 1200 (the longer side, in pixels), --orientation landscape|portrait|square,
20
+ // --timeout 30 (seconds to wait for each request), --api <url> (the Commons endpoint: for tests)
21
+ // Search the subject, not a mood: "sourdough loaf on a board", not "cosy".
22
+ import { existsSync, mkdirSync, readFileSync, appendFileSync, writeFileSync } from "node:fs";
23
+ import { extname, join } from "node:path";
24
+
25
+ const args = process.argv.slice(2);
26
+ const flag = (name, def = "") => {
27
+ const i = args.indexOf(`--${name}`);
28
+ return i === -1 ? def : (args.splice(i, 2)[1] ?? "");
29
+ };
30
+ const fail = (text) => {
31
+ console.error(`pictures: ${text}`);
32
+ process.exit(2);
33
+ };
34
+ const api = flag("api", "https://commons.wikimedia.org/w/api.php");
35
+ const outArg = flag("out");
36
+ const count = Number(flag("count", "4"));
37
+ const min = Number(flag("min", "1200"));
38
+ const orientation = flag("orientation").toLowerCase();
39
+ const timeout = Number(flag("timeout", "30"));
40
+ const query = args.join(" ").trim();
41
+ if (!query || !outArg || !Number.isInteger(count) || count < 1 || count > 12 || !(min >= 0) || !(timeout > 0) || (orientation && !["landscape", "portrait", "square"].includes(orientation))) {
42
+ console.error(`usage: node pictures.mjs "subject" --out <dir> [--count 4] [--min 1200] [--orientation landscape|portrait|square] [--timeout 30]`);
43
+ process.exit(2);
44
+ }
45
+ const headers = { "User-Agent": "longbeard-pictures (https://github.com/jonanderdev/longbeard)" };
46
+
47
+ // Public domain is not one thing. Commons gives nearly every such file the same short name, "Public
48
+ // domain", whether it is so everywhere or only in one country (a US government photograph, a work
49
+ // old enough in the US alone), so the name cannot tell them apart; the templates on the file page
50
+ // can. A public-domain file is kept only when its page carries a template that says it holds
51
+ // everywhere: the worldwide public-domain mark, or the author's own dedication. The search asks for
52
+ // just these, so a page's list is short, and a page that shows none is left out.
53
+ const WORLDWIDE_PD_TEMPLATES = ["Cc-pd-mark-footer", "PD-self", "PD-author"];
54
+ const WORLDWIDE_PD = /^(public domain|public domain mark|pdm|pd|pd-self|pd-old|pd-old-100(-expired)?|pd-author)$/i;
55
+ // The licence as { name, link, shareAlike, credit } (credit: the licence asks for one), or
56
+ // { reason } when the picture is not one we can design with freely. templates: the names of the
57
+ // worldwide public-domain templates found on the file's page.
58
+ function licence(meta = {}, templates = []) {
59
+ const val = (k) => String(meta[k]?.value ?? "").trim();
60
+ const short = val("LicenseShortName"), code = val("License"), terms = val("UsageTerms"), link = val("LicenseUrl");
61
+ const text = `${short} ${code}`;
62
+ if (!text.trim()) return { reason: "licence" };
63
+ if (val("NonFree") && !/^(false|0|no)$/i.test(val("NonFree"))) return { reason: "restricted" };
64
+ if (val("Restrictions")) return { reason: "restricted" };
65
+ if (/\bNC\b|\bND\b|-nc\b|-nd\b|non-?commercial|no-?deriv|fair use/i.test(`${text} ${terms}`)) return { reason: "licence" };
66
+ if (/\bcc0\b|cc-zero/i.test(text)) {
67
+ return { name: "CC0", link: link || "https://creativecommons.org/publicdomain/zero/1.0/", shareAlike: false, credit: false };
68
+ }
69
+ for (const s of [short, code]) {
70
+ const m = s.match(/^cc[ -]by(?:[ -](sa))?(?:[ -](\d(?:\.\d)?))?(?:[ -]([a-z]{2,3})(?![a-z]))?/i);
71
+ if (m) {
72
+ const version = m[2] ? (m[2].includes(".") ? m[2] : `${m[2]}.0`) : "";
73
+ return {
74
+ // A ported licence keeps its country: "CC BY-SA 3.0 de".
75
+ name: `CC BY${m[1] ? "-SA" : ""}${version ? ` ${version}` : ""}${version && m[3] ? ` ${m[3].toLowerCase()}` : ""}`,
76
+ link: link || (version ? `https://creativecommons.org/licenses/${m[1] ? "by-sa" : "by"}/${version}/` : ""),
77
+ shareAlike: Boolean(m[1]), credit: true,
78
+ };
79
+ }
80
+ }
81
+ if (WORLDWIDE_PD.test(short) || (!short && WORLDWIDE_PD.test(code))) {
82
+ // The terms must not narrow it to a place or a condition, and the page must say it holds everywhere.
83
+ if (/\b(only|united states|u\.?s\.?a?\b|russia|country|countries|jurisdiction|if|except|unless)\b/i.test(terms)) return { reason: "licence" };
84
+ if (!templates.length) return { reason: "licence" };
85
+ return { name: "Public domain", link: /^https?:/i.test(link) ? link : "", shareAlike: false, credit: val("AttributionRequired") === "true" };
86
+ }
87
+ return { reason: "licence" };
88
+ }
89
+ const plain = (html) => String(html ?? "").replace(/<(\w+)[^>]*display:\s*none[^>]*>.*?<\/\1>/gis, " ").replace(/<[^>]*>/g, " ").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#0?39;/g, "'").replace(/\s+/g, " ").trim();
90
+ // An author we can credit: a name, not "unknown" or an empty field.
91
+ const usable = (author) => author && !/^(unknown|anonymous|anon|not specified|not known|n\/a|none|\?+|-+)( (author|artist|photographer|creator|source))?\.?$/i.test(author);
92
+ const name = (title) => title.replace(/^File:/i, "").replace(/\.[a-z0-9]+$/i, "").replace(/_/g, " ").trim();
93
+ const slug = (title) => name(title).toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60).replace(/-+$/, "") || "picture";
94
+
95
+ const url = new URL(api);
96
+ for (const [k, v] of Object.entries({
97
+ action: "query", format: "json", generator: "search", gsrnamespace: "6", gsrsearch: `${query} filetype:bitmap`,
98
+ gsrlimit: String(Math.min(count * 6, 50)), prop: "imageinfo|templates", iiprop: "url|size|mime|extmetadata", iiurlwidth: "1600",
99
+ tlnamespace: "10", tllimit: "500", tltemplates: WORLDWIDE_PD_TEMPLATES.map((t) => `Template:${t}`).join("|"),
100
+ })) url.searchParams.set(k, v);
101
+
102
+ let data;
103
+ try {
104
+ const res = await fetch(url, { headers, signal: AbortSignal.timeout(timeout * 1000) });
105
+ if (!res.ok) fail(`Commons answered ${res.status} for the search`);
106
+ data = await res.json();
107
+ } catch (e) {
108
+ fail(e.name === "TimeoutError" ? `Commons did not answer the search within ${timeout}s` : `could not reach Commons (${e.cause?.code ?? e.message})`);
109
+ }
110
+ if (data?.error) fail(`Commons said: ${data.error.info ?? data.error.code}`);
111
+ const pages = Object.values(data?.query?.pages ?? {}).sort((a, b) => (a.index ?? 0) - (b.index ?? 0));
112
+
113
+ const left = { licence: 0, restricted: 0, "no author": 0, "too small": 0, orientation: 0, type: 0 };
114
+ const passing = [];
115
+ for (const page of pages) {
116
+ const info = page.imageinfo?.[0];
117
+ if (!info || !["image/jpeg", "image/png", "image/webp"].includes(info.mime)) { left.type++; continue; }
118
+ const { width: w = 0, height: h = 0 } = info;
119
+ if (Math.max(w, h) < min) { left["too small"]++; continue; }
120
+ const shape = w > h * 1.1 ? "landscape" : h > w * 1.1 ? "portrait" : "square";
121
+ if (orientation && shape !== orientation) { left.orientation++; continue; }
122
+ const marks = (page.templates ?? []).map((t) => String(t.title ?? "").replace(/^Template:/i, "")).filter((t) => WORLDWIDE_PD_TEMPLATES.includes(t));
123
+ const lic = licence(info.extmetadata, marks);
124
+ if (lic.reason) { left[lic.reason]++; continue; }
125
+ const author = plain(info.extmetadata?.Artist?.value).slice(0, 200).trim();
126
+ if (lic.credit && !usable(author)) {
127
+ // A licence that asks for credit cannot be met without a name to give it to.
128
+ console.log(`left out ${name(page.title)}: ${lic.name} asks for credit and no author is given`);
129
+ left["no author"]++;
130
+ continue;
131
+ }
132
+ passing.push({ title: page.title, info, licence: lic, author: usable(author) ? author : "unknown" });
133
+ }
134
+
135
+ const why = Object.entries(left).filter(([, n]) => n).map(([k, n]) => `${n} ${k}`).join(", ");
136
+ if (!passing.length) {
137
+ console.error(`pictures: none of ${pages.length} found for "${query}" could be kept${why ? ` (left out: ${why})` : ""}. Try another query: search the subject, not a mood.`);
138
+ process.exit(1);
139
+ }
140
+
141
+ mkdirSync(outArg, { recursive: true });
142
+ const credits = join(outArg, "credits.tsv");
143
+ const HEADER = "# name\tfile\tsource\tauthor\tlicence\tlicence link\tcredit line\tshare-alike\n";
144
+ const OLD_HEADER = "# name\tfile\tsource\tauthor\tlicence\n";
145
+ if (!existsSync(credits)) writeFileSync(credits, HEADER);
146
+ else {
147
+ // A file from before the licence link: the new header over the old rows, which stay as they were.
148
+ const text = readFileSync(credits, "utf8");
149
+ if (text.startsWith(OLD_HEADER)) writeFileSync(credits, HEADER + text.slice(OLD_HEADER.length));
150
+ }
151
+ // Rows already credited: which files are taken, and which Commons pictures are already here. A
152
+ // picture is known by its source page (its name when there is none), never by its file name: two
153
+ // titles can cut down to the same name.
154
+ const rows = readFileSync(credits, "utf8").split("\n").filter((l) => l && !l.startsWith("#")).map((l) => l.split("\t"));
155
+ const listed = new Set(rows.map((r) => r[1]));
156
+ const known = new Map(rows.map((r) => [r[2] || `name:${r[0]}`, r[1]]));
157
+ const clean = (s) => String(s).replace(/[\t\r\n]+/g, " ").trim();
158
+
159
+ let kept = 0, already = 0, broken = 0, shareAlike = 0;
160
+ for (const pic of passing) {
161
+ if (kept >= count) break;
162
+ const src = pic.info.thumburl || pic.info.url;
163
+ let ext = extname(new URL(src).pathname).toLowerCase();
164
+ if (ext === ".jpeg") ext = ".jpg";
165
+ if (![".jpg", ".png", ".webp"].includes(ext)) ext = ".jpg";
166
+ const key = clean(pic.info.descriptionurl ?? "") || `name:${clean(name(pic.title))}`;
167
+ if (known.has(key) && existsSync(known.get(key))) { already++; continue; }
168
+ // A name another picture (or a file of yours) already holds gets -2, -3 …
169
+ let path = join(outArg, `${slug(pic.title)}${ext}`);
170
+ for (let i = 2; existsSync(path) || listed.has(path); i++) path = join(outArg, `${slug(pic.title)}-${i}${ext}`);
171
+ let bytes;
172
+ try {
173
+ const res = await fetch(src, { headers, signal: AbortSignal.timeout(timeout * 1000) });
174
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
175
+ bytes = Buffer.from(await res.arrayBuffer());
176
+ } catch (e) {
177
+ console.error(`pictures: could not download ${pic.title} (${e.name === "TimeoutError" ? `no answer within ${timeout}s` : e.cause?.code ?? e.message}); skipped`);
178
+ broken++;
179
+ continue;
180
+ }
181
+ writeFileSync(path, bytes);
182
+ const lic = pic.licence;
183
+ const line = `"${clean(name(pic.title))}"${pic.author === "unknown" ? "" : ` by ${clean(pic.author)}`}, ${lic.name}${lic.link ? `, ${lic.link}` : ""}`;
184
+ appendFileSync(credits, [name(pic.title), path, pic.info.descriptionurl ?? "", pic.author, lic.name, lic.link, line, lic.shareAlike ? "yes" : "no"].map(clean).join("\t") + "\n");
185
+ if (lic.shareAlike) shareAlike++;
186
+ listed.add(path);
187
+ known.set(key, path);
188
+ kept++;
189
+ console.log(`kept ${path} ${lic.name} ${pic.author}`);
190
+ }
191
+ if (broken && !kept && !already) fail(`no picture could be downloaded from Commons`);
192
+ const notes = [`${kept} kept in ${outArg}`];
193
+ if (already) notes.push(`${already} already there`);
194
+ notes.push(why ? `left out: ${why}` : "none left out");
195
+ if (broken) notes.push(`${broken} failed to download`);
196
+ console.log(`${notes.join("; ")}. Credits in ${credits}.`);
197
+ if (shareAlike) console.log(`share-alike: a cropped or toned version of ${shareAlike === 1 ? "the share-alike picture" : "a share-alike picture"} must carry the same licence. The credit lines are in ${credits}.`);
@@ -0,0 +1,428 @@
1
+ #!/usr/bin/env node
2
+ // Contrast on the rendered screen, not on swatches. A colour pair can pass on
3
+ // its swatch and fail on the screen: a pale name that reads on the ground and
4
+ // runs off onto a photograph. This reads every piece of text where it sits.
5
+ // Node 22+, an installed Chrome, no dependencies.
6
+ //
7
+ // node screen-contrast.mjs "file://$PWD/.longbeard/design/direction/prototype/grid.html?n=3" --wait-title ready
8
+ //
9
+ // How: the page is opened at --size (1440x900), scrolled once from top to
10
+ // bottom so what appears on scroll is there, and measured at its full height
11
+ // (up to --max-height, 10000). Every visible text is found with its boxes, its
12
+ // colour and its size. Then all text is made transparent and the page is shot,
13
+ // so what is under each box is the real background: a ground, a gradient, a
14
+ // photograph. Every pixel under each box is compared with the text's colour.
15
+ // A text fails when its 5th-percentile contrast is under the threshold (4.5:1,
16
+ // or 3:1 for large text: 24px, or 18.66px bold; 7:1 and 4.5:1 at --level AAA),
17
+ // so one stray pixel is not the verdict. The worst pixel is reported too.
18
+ //
19
+ // A text colour can be written in any notation (rgb, hsl, oklch, lab,
20
+ // color(display-p3 ...)): the page resolves it to the sRGB it is drawn as. A
21
+ // text whose colour cannot be read, or whose fill is a picture or gradient
22
+ // clipped to the letters, is not measured. It is listed as "not read", and is
23
+ // neither a pass nor a fail.
24
+ //
25
+ // Prints one line per failing text: the text, its box, its colour, the
26
+ // background where it is worst, the contrast (5th percentile and worst), and
27
+ // the threshold. Then one "not read" line per text it could not measure. The
28
+ // last line, on stderr, counts the texts and says how far down the page it looked.
29
+ // --size 1440x900, --wait-title ready (wait for the page to set its title),
30
+ // --level AA|AAA, --min 4.5, --large 3 (these two win over --level),
31
+ // --max-height 10000 (the most of the page, in px, to look at),
32
+ // --timeout 60 (seconds each browser call may take), --json
33
+ //
34
+ // Exit 0 when no text fails, 1 when a text fails, 2 for a bad command line,
35
+ // 3 when it could not run (no Chrome, the page would not open, a browser call
36
+ // timed out). Chrome is closed and its profile removed on every exit, and on
37
+ // SIGINT and SIGTERM.
38
+ import { spawn } from "node:child_process";
39
+ import { existsSync, mkdtempSync, rmSync } from "node:fs";
40
+ import { tmpdir } from "node:os";
41
+ import { join } from "node:path";
42
+ if (typeof WebSocket === "undefined") { console.error("Node 22+ is required."); process.exit(1); }
43
+
44
+ const FAILED = 1, USAGE = 2, COULD_NOT_RUN = 3;
45
+ const args = process.argv.slice(2);
46
+ const flag = (name, def = "") => {
47
+ const i = args.indexOf(`--${name}`);
48
+ return i === -1 ? def : (args.splice(i, 2)[1] ?? "");
49
+ };
50
+ const has = (name) => {
51
+ const i = args.indexOf(`--${name}`);
52
+ return i === -1 ? false : (args.splice(i, 1), true);
53
+ };
54
+ const sizeArg = flag("size", "1440x900");
55
+ const waitTitle = flag("wait-title");
56
+ const level = flag("level", "AA").toUpperCase();
57
+ const min = Number(flag("min", level === "AAA" ? "7" : "4.5"));
58
+ const large = Number(flag("large", level === "AAA" ? "4.5" : "3"));
59
+ const maxHeight = Number(flag("max-height", "10000"));
60
+ const limit = Number(flag("timeout", "60"));
61
+ const json = has("json");
62
+ const [url] = args;
63
+ const [W, H] = sizeArg.split("x").map(Number);
64
+ if (!url || args.length !== 1 || !/^(https?|file):/.test(url) || !(W > 0 && H > 0) || !(min > 1) || !(large > 1) || !(level === "AA" || level === "AAA") || !(maxHeight >= H) || !(limit > 0)) {
65
+ console.error('usage: node screen-contrast.mjs "<file:// or https:// url>" [--size 1440x900] [--wait-title ready] [--level AA|AAA] [--min 4.5] [--large 3] [--max-height 10000] [--timeout 60] [--json]');
66
+ process.exit(USAGE);
67
+ }
68
+
69
+ const fail = (text, code = COULD_NOT_RUN) => {
70
+ console.error(`screen-contrast: ${text}`);
71
+ process.exit(code);
72
+ };
73
+ function findChrome() {
74
+ const env = process.env.CHROME_PATH;
75
+ // CHROME_PATH=none: run as if no browser were installed (a quick test run).
76
+ if (env === "none") return null;
77
+ if (env && existsSync(env)) return env;
78
+ const home = process.env.HOME || process.env.USERPROFILE || "";
79
+ const pf = process.env.PROGRAMFILES || "C:\\Program Files";
80
+ return [
81
+ join(pf, "Google/Chrome/Application/chrome.exe"),
82
+ join(process.env.LOCALAPPDATA || "", "Google/Chrome/Application/chrome.exe"),
83
+ join(pf, "Microsoft/Edge/Application/msedge.exe"),
84
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
85
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
86
+ join(home, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
87
+ "/usr/bin/google-chrome",
88
+ "/usr/bin/google-chrome-stable",
89
+ "/usr/bin/chromium",
90
+ "/usr/bin/chromium-browser",
91
+ ].find((path) => path && existsSync(path));
92
+ }
93
+ const exe = findChrome();
94
+ if (!exe) fail("No Chrome/Edge/Chromium found. Install one or set CHROME_PATH.");
95
+
96
+ // Whatever ends the run, Chrome goes with it and so does its profile folder.
97
+ const dir = mkdtempSync(join(tmpdir(), "screen-contrast-"));
98
+ let proc = null;
99
+ let finished = false;
100
+ process.once("exit", () => {
101
+ try {
102
+ proc?.kill("SIGKILL");
103
+ } catch {}
104
+ // Chrome's helpers can still be writing as it goes: remove again until the folder is gone.
105
+ // Each try walks the folder afresh (rmSync's own retries only retry the last rmdir, and wait 21 s for nothing).
106
+ for (let end = Date.now() + 5000; ; Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50)) {
107
+ try {
108
+ rmSync(dir, { recursive: true, force: true });
109
+ break;
110
+ } catch {
111
+ if (Date.now() > end) break;
112
+ }
113
+ }
114
+ });
115
+ for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => fail(`stopped by ${signal}`));
116
+ process.on("unhandledRejection", (e) => fail(e?.message || String(e)));
117
+
118
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
119
+ // Run a step until it says yes or the time is up; the page may be slow, never stuck.
120
+ const until = async (ms, step) => {
121
+ for (const end = Date.now() + ms; Date.now() < end; await sleep(200)) if (await step().catch(() => false)) return true;
122
+ return false;
123
+ };
124
+
125
+ async function main() {
126
+ proc = spawn(exe, ["--headless=new", "--remote-debugging-port=0", `--user-data-dir=${dir}`, "--no-first-run", "--force-color-profile=srgb", "--hide-scrollbars", "--allow-file-access-from-files", "about:blank"], { stdio: ["ignore", "ignore", "pipe"] });
127
+ proc.on("exit", () => finished || fail("Chrome exited before the check was done"));
128
+ let buf = "";
129
+ const wsUrl = await new Promise((done, no) => {
130
+ const t = setTimeout(() => no(new Error("Chrome did not start")), 20000);
131
+ proc.stderr.on("data", (d) => {
132
+ const m = (buf += d).match(/DevTools listening on (ws:\/\/\S+)/);
133
+ if (m) done(m[1], clearTimeout(t));
134
+ });
135
+ });
136
+ const ws = new WebSocket(wsUrl);
137
+ await new Promise((done, no) => {
138
+ const t = setTimeout(() => no(new Error("Chrome did not accept the connection")), 20000);
139
+ ws.onopen = () => done(clearTimeout(t));
140
+ ws.onerror = () => no(new Error("Chrome did not accept the connection"));
141
+ });
142
+ ws.onclose = () => finished || fail("Chrome closed the connection");
143
+ let nextId = 0;
144
+ const pending = new Map();
145
+ ws.onmessage = (ev) => {
146
+ const msg = JSON.parse(String(ev.data));
147
+ if (pending.has(msg.id)) pending.get(msg.id)(msg), pending.delete(msg.id);
148
+ };
149
+ // Every call has a time limit: a page that hangs ends the run, it does not hang it.
150
+ const send = (method, params = {}, sessionId) =>
151
+ new Promise((done, no) => {
152
+ const id = ++nextId;
153
+ const timer = setTimeout(() => (pending.delete(id), no(new Error(`${method} did not answer within ${limit} s`))), limit * 1000);
154
+ pending.set(id, (msg) => done((clearTimeout(timer), msg)));
155
+ ws.send(JSON.stringify({ id, method, params, sessionId }));
156
+ });
157
+ const { result: target } = await send("Target.createTarget", { url: "about:blank" });
158
+ const { result: att } = await send("Target.attachToTarget", { targetId: target.targetId, flatten: true });
159
+ const call = (method, params) => send(method, params, att.sessionId);
160
+ const evaluate = async (expression) => {
161
+ const r = await call("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
162
+ if (r.result?.exceptionDetails) throw new Error(r.result.exceptionDetails.exception?.description || "the page threw");
163
+ return r.result?.result?.value;
164
+ };
165
+
166
+ await call("Emulation.setDeviceMetricsOverride", { width: W, height: H, deviceScaleFactor: 1, mobile: W < 768 });
167
+ const nav = await call("Page.navigate", { url });
168
+ if (nav.result?.errorText) fail(`could not open ${url}: ${nav.result.errorText}`);
169
+ if (waitTitle) {
170
+ if (!(await until(20000, async () => (await evaluate("document.title")) === waitTitle))) fail(`the page did not set its title to "${waitTitle}" within 20 s`);
171
+ } else {
172
+ await until(20000, async () => (await evaluate("document.readyState")) === "complete");
173
+ await sleep(500);
174
+ }
175
+ await evaluate("document.fonts ? document.fonts.ready.then(() => true) : true").catch(() => true);
176
+
177
+ // Scroll down the page once, so what shows itself on scroll is showing, then back to the top.
178
+ const total = await evaluate("Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0)");
179
+ const looked = Math.min(total, maxHeight);
180
+ for (let y = H; y < looked; y += H) {
181
+ await evaluate(`window.scrollTo(0, ${y})`);
182
+ await sleep(120);
183
+ }
184
+ await evaluate("window.scrollTo(0, 0)");
185
+ await sleep(300);
186
+
187
+ // Every visible text: its element, its boxes down the page, its colour and size.
188
+ const texts = await evaluate(`(() => {
189
+ const W = ${W}, H = ${looked};
190
+ // Any notation Chrome knows, as the sRGB it is drawn as: [r, g, b, alpha], or null when it cannot be read.
191
+ // A colour the canvas will not take leaves its fill as it was, so two different starts tell the two apart.
192
+ const cv = Object.assign(document.createElement("canvas"), { width: 1, height: 1 });
193
+ const cx = cv.getContext("2d", { willReadFrequently: true });
194
+ const over = (css, ground) => {
195
+ cx.clearRect(0, 0, 1, 1);
196
+ cx.fillStyle = ground;
197
+ cx.fillRect(0, 0, 1, 1);
198
+ cx.fillStyle = css;
199
+ cx.fillRect(0, 0, 1, 1);
200
+ return cx.getImageData(0, 0, 1, 1).data;
201
+ };
202
+ const parse = (css) => {
203
+ if (!css) return null;
204
+ cx.fillStyle = "#010203";
205
+ cx.fillStyle = css;
206
+ const a = cx.fillStyle;
207
+ cx.fillStyle = "#fdfcfb";
208
+ cx.fillStyle = css;
209
+ if (a !== cx.fillStyle) return null;
210
+ const dark = over(css, "#000000"), light = over(css, "#ffffff");
211
+ const alpha = 1 - (light[0] - dark[0] + light[1] - dark[1] + light[2] - dark[2]) / 765;
212
+ if (alpha < 0.004) return [0, 0, 0, 0];
213
+ return [0, 1, 2].map((i) => Math.min(255, Math.round(dark[i] / alpha))).concat(Math.min(1, Math.round(alpha * 255) / 255));
214
+ };
215
+ const seen = (el) => {
216
+ for (let up = el; up && up.nodeType === 1; up = up.parentElement) {
217
+ const s = getComputedStyle(up);
218
+ if (s.display === "none" || s.visibility === "hidden" || Number(s.opacity) === 0) return false;
219
+ }
220
+ return true;
221
+ };
222
+ // A picture or gradient clipped to the letters is the text's fill; its pixels are not read here.
223
+ const clipped = (el) => {
224
+ for (let up = el; up && up.nodeType === 1; up = up.parentElement) {
225
+ const s = getComputedStyle(up);
226
+ if ((s.webkitBackgroundClip === "text" || s.backgroundClip === "text") && s.backgroundImage !== "none") return true;
227
+ }
228
+ return false;
229
+ };
230
+ // Is the text cut by a clip-path, a clip or an overflow on it or above it? Then only part of it shows.
231
+ const cut = (el, boxes) => {
232
+ for (let up = el; up && up.nodeType === 1; up = up.parentElement) {
233
+ const s = getComputedStyle(up);
234
+ if (s.clipPath && s.clipPath !== "none") return true;
235
+ if (s.clip && s.clip !== "auto" && /absolute|fixed/.test(s.position)) return true;
236
+ if (s.overflowX !== "visible" || s.overflowY !== "visible") {
237
+ const r = up.getBoundingClientRect();
238
+ const x = r.left + scrollX, y = r.top + scrollY;
239
+ if (boxes.some((b) => b.x < x - 0.5 || b.y < y - 0.5 || b.r > x + r.width + 0.5 || b.b > y + r.height + 0.5)) return true;
240
+ }
241
+ }
242
+ return false;
243
+ };
244
+ const byEl = new Map();
245
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
246
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
247
+ if (!n.textContent.trim()) continue;
248
+ const el = n.parentElement;
249
+ if (!el || /^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE)$/.test(el.tagName) || !seen(el)) continue;
250
+ const range = document.createRange();
251
+ range.selectNodeContents(n);
252
+ const boxes = [...range.getClientRects()]
253
+ .map((r) => ({ x: Math.max(0, Math.floor(r.left + scrollX)), y: Math.max(0, Math.floor(r.top + scrollY)), r: Math.min(W, Math.ceil(r.right + scrollX)), b: Math.min(H, Math.ceil(r.bottom + scrollY)) }))
254
+ .filter((b) => b.r - b.x >= 1 && b.b - b.y >= 1);
255
+ if (!boxes.length) continue;
256
+ if (!byEl.has(el)) {
257
+ const s = getComputedStyle(el);
258
+ const size = parseFloat(s.fontSize), weight = parseInt(s.fontWeight, 10) || 400;
259
+ const own = parse(s.color), fill = parse(s.webkitTextFillColor || s.color), edge = parse(s.webkitTextStrokeColor);
260
+ const stroke = parseFloat(s.webkitTextStrokeWidth) || 0;
261
+ let colour = own, outline = false, unread = null;
262
+ if (!own || !fill) unread = "its colour is written in a way Chrome did not resolve: " + (!own ? s.color : s.webkitTextFillColor);
263
+ else {
264
+ // Text drawn only as an outline (a stroke, the fill clear): its stroke is what is read.
265
+ outline = stroke > 0 && fill[3] < 0.1;
266
+ if (outline) {
267
+ colour = edge;
268
+ if (!edge) unread = "its outline colour is written in a way Chrome did not resolve: " + s.webkitTextStrokeColor;
269
+ } else if (fill[3] < own[3]) colour = fill;
270
+ if (!unread && !outline && colour[3] < 0.1 && clipped(el)) unread = "its fill is a picture or gradient clipped to the letters";
271
+ }
272
+ // A faded container fades its text too: every opacity from the element up multiplies in.
273
+ if (colour) for (let up = el; up && up.nodeType === 1; up = up.parentElement) colour[3] *= Number(getComputedStyle(up).opacity);
274
+ byEl.set(el, { el: byEl.size, text: "", boxes: [], colour, unread, size, weight, outline, large: size >= 24 || (size >= 18.66 && weight >= 700) });
275
+ }
276
+ const t = byEl.get(el);
277
+ t.text += (t.text ? " " : "") + n.textContent.trim().replace(/\\s+/g, " ");
278
+ t.boxes.push(...boxes);
279
+ }
280
+ for (const [el, t] of byEl) t.cut = cut(el, t.boxes);
281
+ // Kept for the mask shots below, which show one element at a time.
282
+ window.__screenContrastEls = [...byEl.keys()];
283
+ return [...byEl.values()];
284
+ })()`);
285
+
286
+ // Hide every text, so the shot is what lies under it.
287
+ await evaluate(`(() => {
288
+ const s = document.createElement("style");
289
+ s.textContent = "* { color: transparent !important; text-shadow: none !important; -webkit-text-stroke: 0 !important; -webkit-text-fill-color: transparent !important; caret-color: transparent !important; text-decoration-color: transparent !important; }";
290
+ document.head.appendChild(s);
291
+ return new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(() => done(true))));
292
+ })()`);
293
+ const shot = await call("Page.captureScreenshot", { format: "png", captureBeyondViewport: looked > H, clip: { x: 0, y: 0, width: W, height: looked, scale: 1 } });
294
+ if (!shot.result?.data) fail(`could not take the screenshot${shot.error ? `: ${shot.error.message}` : ""}`);
295
+
296
+ const boxOf = (t) => {
297
+ const x = Math.min(...t.boxes.map((b) => b.x)), y = Math.min(...t.boxes.map((b) => b.y));
298
+ return [x, y, Math.max(...t.boxes.map((b) => b.r)) - x, Math.max(...t.boxes.map((b) => b.b)) - y];
299
+ };
300
+ // Where each text actually shows. A text cut by a clip-path, a clip or an overflow shows only
301
+ // inside its cut; and a copy of the same text in the same box drawn after it (a knockout label:
302
+ // the copy in another colour, clipped to a disc behind) hides it wherever that copy shows. For
303
+ // these texts one more shot is taken per element: everything hidden but that element, painted
304
+ // white on black, with its own and its ancestors' clips still applied. That shot is its mask.
305
+ const measured = texts.filter((t) => !t.unread);
306
+ const keyOf = (t) => t.text + "|" + boxOf(t).join(",");
307
+ for (const [i, t] of measured.entries()) {
308
+ const over = measured.slice(i + 1).filter((u) => keyOf(u) === keyOf(t));
309
+ t.covers = over.map((u) => u.el);
310
+ for (const u of over) u.cut = t.cut = true;
311
+ }
312
+ const masks = {};
313
+ const toMask = measured.filter((t) => t.cut);
314
+ if (toMask.length) {
315
+ await call("Emulation.setDefaultBackgroundColorOverride", { color: { r: 0, g: 0, b: 0, a: 1 } });
316
+ await evaluate(`(() => {
317
+ const s = document.createElement("style");
318
+ s.textContent = "html, body { background: none !important; } * { visibility: hidden !important; } [data-screen-contrast-mask] { visibility: visible !important; background: #fff !important; border-color: transparent !important; box-shadow: none !important; outline: none !important; filter: none !important; mix-blend-mode: normal !important; } [data-screen-contrast-mask] * { visibility: hidden !important; }";
319
+ document.head.appendChild(s);
320
+ return true;
321
+ })()`);
322
+ for (const t of toMask) {
323
+ const [x, y, w, h] = boxOf(t);
324
+ await evaluate(`(() => {
325
+ for (const e of document.querySelectorAll("[data-screen-contrast-mask]")) e.removeAttribute("data-screen-contrast-mask");
326
+ window.__screenContrastEls[${t.el}].setAttribute("data-screen-contrast-mask", "");
327
+ return new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(() => done(true))));
328
+ })()`);
329
+ const m = await call("Page.captureScreenshot", { format: "png", captureBeyondViewport: looked > H, clip: { x, y, width: w, height: h, scale: 1 } });
330
+ if (!m.result?.data) fail(`could not take a mask shot${m.error ? `: ${m.error.message}` : ""}`);
331
+ masks[t.el] = { x, y, w, h, data: m.result.data };
332
+ }
333
+ }
334
+
335
+ // Read the shot's pixels in a blank page, and measure each text against what is under it.
336
+ await call("Page.navigate", { url: "about:blank" });
337
+ await sleep(200);
338
+ const results = await evaluate(`(async () => {
339
+ const texts = ${JSON.stringify(measured)};
340
+ const img = new Image();
341
+ img.src = "data:image/png;base64,${shot.result.data}";
342
+ await img.decode();
343
+ const c = Object.assign(document.createElement("canvas"), { width: img.width, height: img.height });
344
+ const g = c.getContext("2d", { willReadFrequently: true });
345
+ g.drawImage(img, 0, 0);
346
+ const d = g.getImageData(0, 0, img.width, img.height).data;
347
+ const lin = (v) => ((v /= 255) <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);
348
+ const lum = (r, gg, b) => 0.2126 * lin(r) + 0.7152 * lin(gg) + 0.0722 * lin(b);
349
+ // Each mask as a test: does its element show at (x, y)? Shown means at least half its brightest
350
+ // pixel, so a faded ancestor still shows and a clip's soft edge counts on one side only.
351
+ const masks = ${JSON.stringify(masks)};
352
+ const shows = {};
353
+ for (const [el, m] of Object.entries(masks)) {
354
+ const mi = new Image();
355
+ mi.src = "data:image/png;base64," + m.data;
356
+ await mi.decode();
357
+ const mc = Object.assign(document.createElement("canvas"), { width: mi.width, height: mi.height });
358
+ const mg = mc.getContext("2d", { willReadFrequently: true });
359
+ mg.drawImage(mi, 0, 0);
360
+ const md = mg.getImageData(0, 0, mi.width, mi.height).data;
361
+ let peak = 0;
362
+ for (let i = 0; i < md.length; i += 4) peak = Math.max(peak, md[i], md[i + 1], md[i + 2]);
363
+ shows[el] = (x, y) => {
364
+ const mx = x - m.x, my = y - m.y;
365
+ if (peak < 8 || mx < 0 || my < 0 || mx >= mi.width || my >= mi.height) return false;
366
+ const i = (my * mi.width + mx) * 4;
367
+ return Math.max(md[i], md[i + 1], md[i + 2]) * 2 >= peak;
368
+ };
369
+ }
370
+ return texts.map((t) => {
371
+ const [tr, tg, tb, ta] = t.colour;
372
+ const area = t.boxes.reduce((s, b) => s + (b.r - b.x) * (b.b - b.y), 0);
373
+ const stride = Math.max(1, Math.floor(Math.sqrt(area / 20000)));
374
+ const ks = [];
375
+ let worst = Infinity, worstBg = null;
376
+ const own = shows[t.el], covers = (t.covers || []).map((c) => shows[c]);
377
+ for (const b of t.boxes) for (let y = b.y; y < b.b; y += stride) for (let x = b.x; x < b.r; x += stride) {
378
+ // Only where the text shows: inside its own cut, and not under a copy of it drawn on top.
379
+ if (own && !own(x, y)) continue;
380
+ if (covers.some((c) => c(x, y))) continue;
381
+ const i = (y * img.width + x) * 4;
382
+ const br = d[i], bg = d[i + 1], bb = d[i + 2];
383
+ // The text's alpha over the pixel under it.
384
+ const fr = tr * ta + br * (1 - ta), fg = tg * ta + bg * (1 - ta), fb = tb * ta + bb * (1 - ta);
385
+ const l1 = lum(fr, fg, fb), l2 = lum(br, bg, bb);
386
+ const k = (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
387
+ ks.push(k);
388
+ if (k < worst) (worst = k), (worstBg = [br, bg, bb]);
389
+ }
390
+ ks.sort((a, b) => a - b);
391
+ const p5 = ks.length ? ks[Math.floor(ks.length * 0.05)] : null;
392
+ return { ...t, p5, worst: ks.length ? worst : null, worstBg };
393
+ });
394
+ })()`);
395
+ finished = true;
396
+ ws.close();
397
+
398
+ const hex = (rgb) => `#${rgb.slice(0, 3).map((v) => Math.round(v).toString(16).padStart(2, "0")).join("")}`;
399
+ // Rounded down, so a ratio just under its threshold never prints as the threshold.
400
+ const r2 = (v) => (v == null ? null : Math.floor(v * 100) / 100);
401
+ const said = (t) => (t.text.length > 40 ? `${t.text.slice(0, 39)}…` : t.text);
402
+ const rows = results.map((t) => {
403
+ const need = t.large ? large : min;
404
+ return {
405
+ text: said(t),
406
+ box: boxOf(t),
407
+ colour: hex(t.colour) + (t.colour[3] < 1 ? ` at ${Math.round(t.colour[3] * 100)}%` : "") + (t.outline ? " (outline)" : ""),
408
+ size: t.size,
409
+ large: t.large,
410
+ background: t.worstBg ? hex(t.worstBg) : null,
411
+ p5: r2(t.p5),
412
+ worst: r2(t.worst),
413
+ need,
414
+ pass: t.p5 == null || t.p5 >= need,
415
+ };
416
+ });
417
+ const unread = texts.filter((t) => t.unread).map((t) => ({ text: said(t), box: boxOf(t), reason: t.unread }));
418
+ const failing = rows.filter((r) => !r.pass);
419
+ const reach = looked >= total ? `all ${total} px of the page` : `the top ${looked} of ${total} px; the rest is not checked (--max-height)`;
420
+ if (json) console.log(JSON.stringify({ texts: rows, failing: failing.length, unread, page: { height: total, looked, whole: looked >= total } }, null, 1));
421
+ else {
422
+ for (const r of failing) console.log([`"${r.text}"`, `box ${r.box.join(",")}`, `text ${r.colour}`, `worst on ${r.background}`, `${r.p5}:1 (worst ${r.worst}:1)`, `needs ${r.need}:1${r.large ? " (large)" : ""}`].join("\t"));
423
+ for (const u of unread) console.log([`not read: "${u.text}"`, `box ${u.box.join(",")}`, u.reason].join("\t"));
424
+ }
425
+ console.error(`screen-contrast: ${rows.length} texts, ${failing.length} under, ${unread.length} not read; looked at ${reach}`);
426
+ process.exit(failing.length ? FAILED : 0);
427
+ }
428
+ main().catch((e) => fail(e.message));