@zero2webmaster/starter-kit 0.23.0 → 0.25.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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # z2w-starter-kit
2
2
 
3
- **Version:** 0.23.0 | **Framework:** 2.19.0
3
+ **Version:** 0.25.0 | **Framework:** 2.19.0
4
4
 
5
5
  > Node CLI to scaffold new Z2W projects from canonical Templates + AGENTS.md.
6
6
 
@@ -83,7 +83,9 @@ The Claude Code skill at `~/.claude/skills/instantiate-z2w-project/SKILL.md` and
83
83
 
84
84
  ## Status
85
85
 
86
- - **v0.23.0 (current)** makes every scaffolded web app defend its own head. `audit-engine` measured 26 reachable Z2W surfaces on 2026-08-20: **22 carried none of the five baseline security headers**, while `leaderboard` carried five of five — so this was a lift from a passing in-house implementation rather than a design exercise. Every `nextjs` scaffold now emits `lib/security-headers.mjs`, applied to every route by a new `async headers()` in **both** `next.config.mjs` variants, and `cf-pages` goes from two of five to five of five. **The CSP is assembled from the origins the scaffold actually loads**, each gated on the input that ships the feature: Fathom unconditionally, Turnstile in `script-src` *and* `frame-src` when the project takes cards (the widget is an iframe, so allowing only the script leaves an uncompletable card path), Sentry in `connect-src` alone when observability is on. **It ships enforcing rather than Report-Only** — a considered deviation from the retrofit-oriented rule, reasoned in the emitted comments, because a scaffold has no live traffic to break and a header that blocks nothing is just a note asking someone to finish later. Alongside it, `lib/json-ld.ts` closes the `JSON.stringify`-into-a-`<script>` sink: not because the scaffold's own JSON-LD was exploitable (it holds a brand name and an env URL) but because the Pro-SEO extension's *documented example* fed a post title — database content — straight into it, which is the exact stored XSS found live in `z2w-social`. **A scaffold's examples are copied more often than its code is read.** Verified on the artifact: real `next build`, all six headers `curl`-confirmed on a home page, a child page and an API route, and headless Chrome reporting zero CSP violations — with a positive control proving the detector fires.
86
+ - **v0.25.0 (current)** adds `scripts/reconcile-production-url.mjs`, which reconciles the Project Registry's `production_url` column against the Vercel API — and **measuring the real API showed the 2026-08-17 design sketch was wrong in three separate ways.** The sketch said "read `domains[]`, filter out `*.vercel.app`, never take `domains[0]`." Measured across all 23 Zero2Webmaster Vercel projects: **position carries no information at all** (`z2w-social`'s correct domain is the first survivor, `org-hq`'s is the second), so no positional rule can exist; **filtering the aliases out blanks five Live rows** whose only public surface *is* a `.vercel.app` alias, so aliases are a lower-priority tier rather than noise; and **multiple custom domains are the common case, not an edge** — 6 of 19 resolvable projects have more than one, `file-server` has four. The reconciler therefore returns a *verdict object* rather than a URL, so "there is one" and "I picked one of four" cannot print the same way, and it writes only into a NULL — a recorded value that disagrees is reported as drift and never overwritten, because it may be a human's deliberate choice. **It found a real one on its first live run:** the registry's `z2w-social` URL 308-redirects to `frogspace.savethefrogs.com`. Live redirect evidence is used only to *eliminate* a candidate that points at another candidate — both `leaderboard` domains 307 to `/bansuri`, a tenant path, so "follow redirects and take the final URL" would have written a tenant-scoped URL as a project's production URL. A coverage ledger accounts for every row asserting a public surface, and a completeness check makes an unexplained row loud instead of absent. Also re-syncs the canonical Agent Coordination block to **v0.1.27**, which brings the previously-red conformance test back to green — **1199 of 1199 passing.**
87
+ - **v0.24.0** makes contrast a measured property of a PAIR rather than a taste call about a swatch. Every `nextjs` scaffold now emits `lib/a11y/contrast.ts` and `test/contrast.test.ts`, a table of **SURFACE x TEXT-ROLE x THRESHOLD** rows measured against the stylesheet the project actually ships — thirteen pairs across six surfaces, with `--brand-ink` measured four separate times because it is painted on four different backgrounds. The candidate came from `static-sites` and its lesson is one line: *contrast is per-surface, not per-palette* — a validator that checks each swatch against white passes cleanly while shipping unreadable text, because the swatch is rendered on the tint panel three components down. **Writing that check found two real defects in this scaffold's own CSS, both invisible to every brand preset.** The keyboard focus ring was painted in `--brand-primary`, which measures 2.03:1 on white in Z2W green and 1.40:1 in Z2W gold — so focusing a field made its boundary *less* visible than at rest, in Zero2Webmaster's and Save The Frogs' own colors. And `readableInkOn()` picked the better of near-black and white without checking that the winner cleared anything, which put a 4.41:1 glyph on any mid-tone brand fill. Fixed with a derived `--brand-focus` (same hue, darkened only as far as 3:1 requires) and an escalation to pure black, which provably clears 4.5:1 on every possible background. **Verified by running the scaffold's own vitest, plus four canaries that each reproduce a defect on demand** — including the one that matters most: an ink that stays green on white and fails at 4.06:1 on the code tint.
88
+ - **v0.23.0** makes every scaffolded web app defend its own head. `audit-engine` measured 26 reachable Z2W surfaces on 2026-08-20: **22 carried none of the five baseline security headers**, while `leaderboard` carried five of five — so this was a lift from a passing in-house implementation rather than a design exercise. Every `nextjs` scaffold now emits `lib/security-headers.mjs`, applied to every route by a new `async headers()` in **both** `next.config.mjs` variants, and `cf-pages` goes from two of five to five of five. **The CSP is assembled from the origins the scaffold actually loads**, each gated on the input that ships the feature: Fathom unconditionally, Turnstile in `script-src` *and* `frame-src` when the project takes cards (the widget is an iframe, so allowing only the script leaves an uncompletable card path), Sentry in `connect-src` alone when observability is on. **It ships enforcing rather than Report-Only** — a considered deviation from the retrofit-oriented rule, reasoned in the emitted comments, because a scaffold has no live traffic to break and a header that blocks nothing is just a note asking someone to finish later. Alongside it, `lib/json-ld.ts` closes the `JSON.stringify`-into-a-`<script>` sink: not because the scaffold's own JSON-LD was exploitable (it holds a brand name and an env URL) but because the Pro-SEO extension's *documented example* fed a post title — database content — straight into it, which is the exact stored XSS found live in `z2w-social`. **A scaffold's examples are copied more often than its code is read.** Verified on the artifact: real `next build`, all six headers `curl`-confirmed on a home page, a child page and an API route, and headless Chrome reporting zero CSP violations — with a positive control proving the detector fires.
87
89
  - **v0.22.0** reshapes every emitted `.env.example` / `.env.local` so the line you came to fill in is the one you see. Kerry, 2026-08-16: the `# ── Database (Neon Postgres) ─────…` ruler *"is usually too long and therefore doesn't look like anything useful"*, and eighteen lines of explanation sat between the header and `DATABASE_URL=`. Headers are now a plain `# Database (Neon Postgres)`, and each block leads with its assignments and carries its prose directly underneath. **Per block rather than per file, which was Kerry's call between two readings of his own note** — collecting every variable at the top of the file would put the pooled-connection warning a screen away from the person about to paste the wrong connection string, and that warning only works where it is read. **Not a trim: every explanatory sentence survives, reworded and moved**, and there is a control test that unwraps the comment prose and asserts the load-bearing warnings are all still present, because a layout change is exactly where a paragraph goes missing unnoticed. Verified by loading the emitted file with Node's real dotenv parser — all 13 variables read back — not by grepping the template.
88
90
  - **v0.21.0** makes the external audience gate say what actually went wrong. Its refusal named exactly one cause — *"a heading was probably renamed upstream"* — for a state that has two, and `project-creator`, the only consumer that resolves Templates from a version-**pinned** package rather than from Kerry's disk, hits the other one every time: at AGENTS v2.15.0 the `## Keeping This Framework Current` section simply did not exist yet, so every outside-brand scaffold refused in their production while they hunted a rename that never happened. Each gated section now declares the Templates version that first shipped it, the gate derives a minimum from those declarations, and the error distinguishes **version skew** (upgrade Templates) from **unexplained** (fix the section list). The throw is deliberately not softened. Same release: the standards decision log is now gate-aware — a standard whose whole section the gate removed reports `removed-by-audience-gate` instead of `inserted-inline`, because the old log let a preview UI tell an outside customer it had "Skill Vault awareness" in a file that no longer mentioned it; and a new `privateReferences` finding separates a surviving line that *instructs* the reader into the private Skill Vault from one that merely points at a missing section — one hit at Templates v2.18.0 and zero at v2.19.0, which removed that sentence upstream during the same session, demoting the finding into the milder dangling-reference class rather than making the check inert. No emitted file changes by a byte.
89
91
  - **v0.20.0** emits `lib/csv-export.ts` and an enforcing `test/csv-export.test.ts` into **every** Next.js scaffold, with no capability flag. A CSV cell beginning `=`, `+`, `-` or `@` is evaluated as a formula by Excel and Google Sheets, so an unguarded export is code execution on the machine of whoever opens it — arriving through a file the app itself told them to download. A survey of 53 Z2W repos found 1 pass and 12 fail, and all 12 grew their export months after the project was scaffolded, which is why this one ships unconditionally rather than behind a flag: "this app will export CSV" is not knowable at scaffold time the way "this app takes cards" is. The emitted test greps for any file serving `text/csv` that skips the helper, so the guard survives the next person who adds an export. Same release: `scripts/rollup-integrations.mjs` now reads markdown tables and `**We CONSUME:**` headings, recovering 18 real dependency edges the ecosystem map had been missing, with none lost.
@@ -131,4 +133,4 @@ Inquiries: kerry@zero2webmaster.com.
131
133
  ---
132
134
 
133
135
  *Scaffolded 2026-05-28 via the [[instantiate-z2w-project]] Claude Code skill v1; reconciled against the consolidated skill v1.1.0 (brief-first + Agent Coordination block) on 2026-05-29.*
134
- *Version: 0.23.0 | Last Updated: 2026-08-20*
136
+ *Version: 0.25.0 | Last Updated: 2026-08-20*
@@ -33,7 +33,34 @@ export declare const INK_LIGHT = "#ffffff";
33
33
  * Deciding it at scaffold time from the actual hex is deterministic, testable,
34
34
  * and costs the emitted project nothing at runtime.
35
35
  */
36
- export declare function readableInkOn(background: string): string;
36
+ export declare function readableInkOn(background: string, minRatio?: number): string;
37
+ /** Pure black. Only reached when the softened {@link INK_DARK} falls short. */
38
+ export declare const PURE_BLACK = "#000000";
39
+ /** Expand `#rgb` to a lowercase `#rrggbb`, so emitted CSS is comparable. */
40
+ export declare function normalizeHex(hex: string): string;
41
+ /**
42
+ * The nearest shade or tint of `color` that clears `minRatio` against
43
+ * `surface`, or `color` itself when it already does.
44
+ *
45
+ * WHY THIS EXISTS, and it is a real defect this repo shipped rather than a
46
+ * hypothetical. The emitted `globals.css` painted the input FOCUS RING in
47
+ * `var(--brand-primary)`, on a white page. Measured against white: Z2W green
48
+ * `#82C92B` is 2.03:1, STF green `#72af43` is 2.65:1, Z2W gold `#FFD700` is
49
+ * 1.40:1 — all below the 3:1 that WCAG 2.1 SC 1.4.11 requires of the visual
50
+ * information that identifies a component's STATE. So every scaffold built in
51
+ * Zero2Webmaster's or Save The Frogs' own brand shipped a focus ring the
52
+ * keyboard user can barely find, and focusing a field made its boundary LESS
53
+ * visible than at rest (the resting `--field-border` is a measured 3.40:1).
54
+ *
55
+ * A brand color is the author's to choose, so the fix is not to override it —
56
+ * it is to derive a same-hue variant for the one role that has a threshold, and
57
+ * to leave `--brand-primary` alone for decorative fills.
58
+ *
59
+ * Steps in 1/200ths and takes whichever direction reaches the bar first, so the
60
+ * result is the smallest visible departure from the author's color. Ties go to
61
+ * the shade, which keeps more chroma than a tint does.
62
+ */
63
+ export declare function accessibleOn(color: string, surface: string, minRatio: number): string;
37
64
  export declare function buildClaudeMd(inputs: ScaffoldInputs, opts: ScaffolderOptions | undefined, spec: BrandPresetSpec, perTypeNarrative: string): ScaffoldFile;
38
65
  export declare function commonReadme(inputs: ScaffoldInputs, opts: ScaffolderOptions | undefined, spec: BrandPresetSpec): ScaffoldFile;
39
66
  export declare function commonRoadmap(inputs: ScaffoldInputs, opts: ScaffolderOptions | undefined, spec: BrandPresetSpec): ScaffoldFile;
@@ -64,10 +64,97 @@ export const INK_LIGHT = "#ffffff";
64
64
  * Deciding it at scaffold time from the actual hex is deterministic, testable,
65
65
  * and costs the emitted project nothing at runtime.
66
66
  */
67
- export function readableInkOn(background) {
68
- return contrastRatio(background, INK_DARK) >= contrastRatio(background, INK_LIGHT)
67
+ export function readableInkOn(background, minRatio = 4.5) {
68
+ const preferred = contrastRatio(background, INK_DARK) >= contrastRatio(background, INK_LIGHT)
69
69
  ? INK_DARK
70
70
  : INK_LIGHT;
71
+ if (contrastRatio(background, preferred) >= minRatio)
72
+ return preferred;
73
+ // Neither the soft near-black nor white clears the bar, which means the fill
74
+ // is MID-TONE — the case every current brand preset happens to avoid, so no
75
+ // test that only exercises the presets can see it. `#808080` scores 4.41:1
76
+ // against `#1a1a1a`, i.e. a 13px glyph that fails AA while looking perfectly
77
+ // deliberate. Escalate to PURE black, which buys back the ~0.9:1 that the
78
+ // softened near-black gives away for aesthetics.
79
+ //
80
+ // This always succeeds, and provably so: max(black, white) is minimised at
81
+ // the luminance where the two ratios cross, and there it is still 4.58:1. So
82
+ // the returned ink clears 4.5:1 against EVERY possible background.
83
+ return contrastRatio(background, PURE_BLACK) >= contrastRatio(background, INK_LIGHT)
84
+ ? PURE_BLACK
85
+ : INK_LIGHT;
86
+ }
87
+ /** Pure black. Only reached when the softened {@link INK_DARK} falls short. */
88
+ export const PURE_BLACK = "#000000";
89
+ /** Expand `#rgb` to a lowercase `#rrggbb`, so emitted CSS is comparable. */
90
+ export function normalizeHex(hex) {
91
+ const h = hex.trim().replace(/^#/, "").toLowerCase();
92
+ return "#" + (h.length === 3 ? h.split("").map((c) => c + c).join("") : h);
93
+ }
94
+ function channels(hex) {
95
+ const h = normalizeHex(hex).slice(1);
96
+ return [
97
+ parseInt(h.slice(0, 2), 16),
98
+ parseInt(h.slice(2, 4), 16),
99
+ parseInt(h.slice(4, 6), 16),
100
+ ];
101
+ }
102
+ /**
103
+ * Mix `hex` toward pure black (`toward = 0`) or pure white (`toward = 255`) by
104
+ * `amount` in 0..1. Both directions preserve HUE — a shade and a tint of the
105
+ * author's color, never a different color.
106
+ */
107
+ function mixToward(hex, toward, amount) {
108
+ const out = channels(hex).map((c) => Math.round(c + (toward - c) * amount));
109
+ return "#" + out.map((c) => c.toString(16).padStart(2, "0")).join("");
110
+ }
111
+ /**
112
+ * The nearest shade or tint of `color` that clears `minRatio` against
113
+ * `surface`, or `color` itself when it already does.
114
+ *
115
+ * WHY THIS EXISTS, and it is a real defect this repo shipped rather than a
116
+ * hypothetical. The emitted `globals.css` painted the input FOCUS RING in
117
+ * `var(--brand-primary)`, on a white page. Measured against white: Z2W green
118
+ * `#82C92B` is 2.03:1, STF green `#72af43` is 2.65:1, Z2W gold `#FFD700` is
119
+ * 1.40:1 — all below the 3:1 that WCAG 2.1 SC 1.4.11 requires of the visual
120
+ * information that identifies a component's STATE. So every scaffold built in
121
+ * Zero2Webmaster's or Save The Frogs' own brand shipped a focus ring the
122
+ * keyboard user can barely find, and focusing a field made its boundary LESS
123
+ * visible than at rest (the resting `--field-border` is a measured 3.40:1).
124
+ *
125
+ * A brand color is the author's to choose, so the fix is not to override it —
126
+ * it is to derive a same-hue variant for the one role that has a threshold, and
127
+ * to leave `--brand-primary` alone for decorative fills.
128
+ *
129
+ * Steps in 1/200ths and takes whichever direction reaches the bar first, so the
130
+ * result is the smallest visible departure from the author's color. Ties go to
131
+ * the shade, which keeps more chroma than a tint does.
132
+ */
133
+ export function accessibleOn(color, surface, minRatio) {
134
+ if (contrastRatio(color, surface) >= minRatio)
135
+ return normalizeHex(color);
136
+ const STEPS = 200;
137
+ let best = normalizeHex(color);
138
+ let bestRatio = contrastRatio(color, surface);
139
+ for (let i = 1; i <= STEPS; i++) {
140
+ const amount = i / STEPS;
141
+ for (const toward of [0, 255]) {
142
+ const candidate = mixToward(color, toward, amount);
143
+ const ratio = contrastRatio(candidate, surface);
144
+ if (ratio >= minRatio)
145
+ return candidate;
146
+ if (ratio > bestRatio) {
147
+ best = candidate;
148
+ bestRatio = ratio;
149
+ }
150
+ }
151
+ }
152
+ // Unreachable for any surface that is itself near-black or near-white, since
153
+ // one endpoint is then 21:1. Returning the best effort rather than throwing is
154
+ // deliberate: the emitted `test/contrast.test.ts` measures the VALUE that
155
+ // actually lands in the CSS, so a shortfall fails in the scaffolded project
156
+ // instead of being swallowed here.
157
+ return best;
71
158
  }
72
159
  const README_TEMPLATE = `# {{slug}}
73
160
 
@@ -46,7 +46,7 @@
46
46
  // allowlist stub in `.env.example`. This CLI emits no auth code, so it plants the
47
47
  // seam + the pointer at [[z2w-magic-link-auth]] §0 rule 2b rather than a check —
48
48
  // see CANONICAL_HOSTS_ENV_BLOCK for why that is the honest half.
49
- import { commonBaseFiles, EMAIL_DEPS, EMAIL_ENV_BLOCK, emailFiles, localEnvFrom, readableInkOn, resolveBrandSpec, SENTRY_DEPS, NEON_DRIVER_DEP, sub, } from "./common.js";
49
+ import { commonBaseFiles, EMAIL_DEPS, EMAIL_ENV_BLOCK, emailFiles, localEnvFrom, accessibleOn, contrastRatio, readableInkOn, resolveBrandSpec, SENTRY_DEPS, NEON_DRIVER_DEP, sub, } from "./common.js";
50
50
  const NARRATIVE = `## What this is
51
51
 
52
52
  \`{{slug}}\` is a Next.js App Router project scaffolded under the {{brand_name}} brand. The 7-item SEO baseline (per Z2W standing org requirement 2026-05-30) is wired in at instantiation.
@@ -1308,6 +1308,16 @@ export function Field({
1308
1308
  );
1309
1309
  }
1310
1310
  `;
1311
+ /**
1312
+ * The page background every emitted surface is ultimately drawn on.
1313
+ *
1314
+ * It is a NAMED CONSTANT rather than an inline `"#ffffff"` because the emitted
1315
+ * contrast test enumerates SURFACES, and the failure mode it exists to prevent
1316
+ * is exactly a check that assumes one background. If a future theme makes the
1317
+ * page a tint, changing it here changes what `--brand-focus` is measured against
1318
+ * — which is the behaviour that was missing.
1319
+ */
1320
+ const PAGE_SURFACE = "#ffffff";
1311
1321
  /**
1312
1322
  * Global stylesheet. Built by a function rather than substituted from a flat
1313
1323
  * template because ONE value has to be computed from the brand hex rather than
@@ -1321,6 +1331,11 @@ export function Field({
1321
1331
  */
1322
1332
  function globalsCss(primaryColor) {
1323
1333
  const onPrimary = readableInkOn(primaryColor);
1334
+ // The focus ring is a STATE indicator, so it has a 3:1 floor against the page
1335
+ // it is drawn on (WCAG 2.1 SC 1.4.11). Most brand primaries do not clear it on
1336
+ // white — see `accessibleOn` for the measured list, which includes Z2W's and
1337
+ // STF's own greens. Derived here, at scaffold time, from the actual hex.
1338
+ const brandFocus = accessibleOn(primaryColor, PAGE_SURFACE, 3);
1324
1339
  return `/* Global styles.
1325
1340
  *
1326
1341
  * Body typography lives here, not as an inline style on <body>, so there is ONE
@@ -1334,12 +1349,35 @@ function globalsCss(primaryColor) {
1334
1349
  scaffold time — do not hand-edit to match a sibling project, whose primary
1335
1350
  may sit on the other side of the luminance threshold. */
1336
1351
  --brand-on-primary: ${onPrimary};
1352
+ /* The brand primary, darkened or lightened just far enough to clear 3:1
1353
+ against the page — same hue, different lightness. Use it for anything whose
1354
+ visibility is REQUIRED rather than decorative: focus rings, the active edge
1355
+ of a control, a state chip's border.
1356
+
1357
+ Measured on ${PAGE_SURFACE} at scaffold time: the brand primary scores
1358
+ ${contrastRatio(primaryColor, PAGE_SURFACE).toFixed(2)}:1, this scores
1359
+ ${contrastRatio(brandFocus, PAGE_SURFACE).toFixed(2)}:1. When the two
1360
+ variables hold the SAME value, the brand primary already cleared the bar on
1361
+ its own and nothing was changed.
1362
+
1363
+ DO NOT collapse these two variables back into one. They are different
1364
+ because they answer to different rules: one is the author's brand, the other
1365
+ has a measured floor. \`test/contrast.test.ts\` fails if this one stops
1366
+ clearing it. */
1367
+ --brand-focus: ${brandFocus};
1337
1368
  --brand-ink: #3f3c36;
1338
1369
  /* Input border. #ccc on white is ~1.6:1, below the 3:1 WCAG 2.1 minimum for a
1339
1370
  UI component boundary — i.e. the edge of the box is genuinely not visible,
1340
1371
  not merely subtle. #8f8b81 clears 3:1. */
1341
1372
  --field-border: #8f8b81;
1342
1373
  --field-border-hover: #6f6b62;
1374
+ /* The page itself. Named so \`test/contrast.test.ts\` can enumerate SURFACES
1375
+ rather than assume one — the whole point of that file. */
1376
+ --page-surface: ${PAGE_SURFACE};
1377
+ }
1378
+
1379
+ body {
1380
+ background: var(--page-surface);
1343
1381
  }
1344
1382
 
1345
1383
  html {
@@ -1416,13 +1454,20 @@ body {
1416
1454
  }
1417
1455
 
1418
1456
  /* A 2px focus ring so keyboard position stays obvious against the now-darker
1419
- resting edge. */
1457
+ resting edge.
1458
+
1459
+ \`--brand-focus\`, NOT \`--brand-primary\`. The ring is drawn on the page
1460
+ surface (\`outline-offset\` puts a 1px gap of page between it and the box), so
1461
+ it is measured against the page — and most brand greens, golds and oranges sit
1462
+ around 2:1 there. Using the raw brand primary here made focusing a field
1463
+ REDUCE the visibility of its boundary, since the resting \`--field-border\` is
1464
+ a measured 3.40:1. That was a real shipped defect, not a hypothetical. */
1420
1465
  .form-field input:focus-visible,
1421
1466
  .form-field textarea:focus-visible,
1422
1467
  .form-field select:focus-visible {
1423
- outline: 2px solid var(--brand-primary);
1468
+ outline: 2px solid var(--brand-focus);
1424
1469
  outline-offset: 1px;
1425
- border-color: var(--brand-primary);
1470
+ border-color: var(--brand-focus);
1426
1471
  }
1427
1472
 
1428
1473
  .form-field input:disabled,
@@ -2736,6 +2781,562 @@ export {};
2736
2781
  * `fileURLToPath(import.meta.url)`. grantor's original used `__dirname` because
2737
2782
  * that project is CommonJS; copying it verbatim would throw at run time.
2738
2783
  */
2784
+ const CONTRAST_MODULE_TEMPLATE = `/**
2785
+ * WCAG 2.1 contrast math, and the rule for WHICH THRESHOLD a given piece of
2786
+ * text has to clear.
2787
+ *
2788
+ * Adding a color to this project should be a measurable act rather than a taste
2789
+ * call. \`test/contrast.test.ts\` is this module's first consumer; your own
2790
+ * design-system code is the intended second — call \`meetsContrast()\` when you
2791
+ * introduce a swatch, rather than eyeballing it.
2792
+ *
2793
+ * THE LESSON THIS FILE ENCODES, and it was expensive: contrast is a property of
2794
+ * a PAIR, not of a color. A palette validator that checks every swatch against
2795
+ * white reports a clean pass while shipping unreadable text, because the swatch
2796
+ * is not rendered on white — it is rendered on the tint panel three components
2797
+ * down. So the unit of measurement here is SURFACE x TEXT-ROLE x THRESHOLD, and
2798
+ * all three vary independently. One swatch can clear 3:1 and fail 4.5:1 on the
2799
+ * very same background.
2800
+ */
2801
+
2802
+ /** WCAG 2.1 relative luminance of an \`#rgb\` / \`#rrggbb\` color. */
2803
+ export function relativeLuminance(hex: string): number {
2804
+ const h = hex.trim().replace(/^#/, "");
2805
+ const full =
2806
+ h.length === 3
2807
+ ? h
2808
+ .split("")
2809
+ .map((c) => c + c)
2810
+ .join("")
2811
+ : h;
2812
+ if (!/^[0-9a-fA-F]{6}$/.test(full)) {
2813
+ // Refusing is the point. A color this module cannot parse must not quietly
2814
+ // score 0 and sail through a >= comparison as if it had been measured.
2815
+ throw new Error("relativeLuminance: not a hex color: " + hex);
2816
+ }
2817
+ const channel = (pair: string): number => {
2818
+ const srgb = parseInt(pair, 16) / 255;
2819
+ return srgb <= 0.03928 ? srgb / 12.92 : ((srgb + 0.055) / 1.055) ** 2.4;
2820
+ };
2821
+ return (
2822
+ 0.2126 * channel(full.slice(0, 2)) +
2823
+ 0.7152 * channel(full.slice(2, 4)) +
2824
+ 0.0722 * channel(full.slice(4, 6))
2825
+ );
2826
+ }
2827
+
2828
+ /** WCAG 2.1 contrast ratio between two colors. 1:1 identical, 21:1 black/white. */
2829
+ export function contrastRatio(a: string, b: string): number {
2830
+ const la = relativeLuminance(a);
2831
+ const lb = relativeLuminance(b);
2832
+ const [hi, lo] = la > lb ? [la, lb] : [lb, la];
2833
+ return (hi + 0.05) / (lo + 0.05);
2834
+ }
2835
+
2836
+ /** AA for body-sized text. */
2837
+ export const AA_TEXT = 4.5;
2838
+ /** AA for large-scale text only. */
2839
+ export const AA_LARGE_TEXT = 3;
2840
+ /** AA for non-text: UI component boundaries, state indicators, focus rings. */
2841
+ export const AA_NON_TEXT = 3;
2842
+
2843
+ /**
2844
+ * WCAG "large scale" text: 18pt, or 14pt bold. At the CSS reference 96dpi those
2845
+ * are 24px and 18.66px.
2846
+ *
2847
+ * READ THE 18px CASE CAREFULLY, because it is the one everyone gets wrong. The
2848
+ * standing {{brand_name}} readability rule sets body text at 18px or more, and
2849
+ * "18" next to "18pt" invites the conclusion that body copy qualifies for the
2850
+ * relaxed 3:1 bar. It does not: 18px is 13.5pt, so ordinary body copy needs the
2851
+ * full 4.5:1. The relaxed bar starts at 24px, or at 18.66px when bold.
2852
+ */
2853
+ export function isLargeText(fontPx: number, fontWeight: number): boolean {
2854
+ return fontPx >= 24 || (fontPx >= 18.66 && fontWeight >= 700);
2855
+ }
2856
+
2857
+ /**
2858
+ * What a pair is being used for. The third axis — a threshold is DERIVED from
2859
+ * the role, never chosen per swatch.
2860
+ */
2861
+ export type ContrastRole =
2862
+ | { kind: "text"; fontPx: number; fontWeight: number }
2863
+ | { kind: "non-text" };
2864
+
2865
+ /** The ratio \`role\` must clear. */
2866
+ export function requiredRatio(role: ContrastRole): number {
2867
+ if (role.kind === "non-text") return AA_NON_TEXT;
2868
+ return isLargeText(role.fontPx, role.fontWeight) ? AA_LARGE_TEXT : AA_TEXT;
2869
+ }
2870
+
2871
+ /** Whether \`fg\` on \`bg\` is good enough for \`role\`. */
2872
+ export function meetsContrast(fg: string, bg: string, role: ContrastRole): boolean {
2873
+ return contrastRatio(fg, bg) >= requiredRatio(role);
2874
+ }
2875
+ `;
2876
+ const CONTRAST_TEST_TEMPLATE = `/**
2877
+ * Per-SURFACE contrast, enforced on the stylesheet this project actually ships.
2878
+ *
2879
+ * WHY THIS FILE IS SHAPED THE WAY IT IS. The obvious version of this test walks
2880
+ * the palette and checks each color against white. That version passes while the
2881
+ * app ships unreadable text, because a color is not rendered on "the palette" —
2882
+ * it is rendered on a specific surface, and this stylesheet has five of them
2883
+ * (the page, the field fill, the disabled field fill, the help panel, the code
2884
+ * tint) plus a sixth that varies per brand (the brand fill itself).
2885
+ *
2886
+ * So the unit here is a PAIR: one text role, one surface, one threshold. All
2887
+ * three vary. \\\`--brand-ink\\\` is measured four times, on four different
2888
+ * backgrounds, because that is four different questions.
2889
+ *
2890
+ * Everything is READ FROM \\\`app/globals.css\\\`, never restated here. A test that
2891
+ * asserts \\\`toMatch(/--field-border:\\\\s*#8f8b81/)\\\` is checking the SPELLING of
2892
+ * a decision; this one re-derives the MEASUREMENT, so changing a hex to another
2893
+ * hex is caught if and only if it actually breaks something. Font sizes and
2894
+ * weights are read from the CSS too, which is what makes the threshold axis real
2895
+ * rather than a number someone typed next to a color.
2896
+ */
2897
+ import { describe, it, expect } from "vitest";
2898
+ import { readFileSync } from "node:fs";
2899
+ import { join, dirname } from "node:path";
2900
+ import { fileURLToPath } from "node:url";
2901
+ import {
2902
+ contrastRatio,
2903
+ isLargeText,
2904
+ meetsContrast,
2905
+ requiredRatio,
2906
+ type ContrastRole,
2907
+ } from "../lib/a11y/contrast";
2908
+
2909
+ // NOT \\\`__dirname\\\` — this package is "type": "module", where it is undefined.
2910
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
2911
+ const CSS_RAW = readFileSync(join(ROOT, "app/globals.css"), "utf8");
2912
+
2913
+ // Comments in this stylesheet quote example hexes on purpose ("#ccc on white is
2914
+ // ~1.6:1"). Those are prose, not shipped colors, and the completeness scan below
2915
+ // would spend its life reporting them. Strip comments before any scan — and do it
2916
+ // once, here, so no individual check can forget to.
2917
+ const CSS = CSS_RAW.replace(/\\/\\*[\\s\\S]*?\\*\\//g, "");
2918
+
2919
+ /** Every rule body whose selector list contains \\\`selector\\\` as a whole entry. */
2920
+ function ruleBodies(selector: string): string[] {
2921
+ const out: string[] = [];
2922
+ const re = /([^{}]+)\\{([^}]*)\\}/g;
2923
+ let m: RegExpExecArray | null;
2924
+ while ((m = re.exec(CSS)) !== null) {
2925
+ const selectors = m[1].split(",").map((s) => s.trim());
2926
+ if (selectors.includes(selector)) out.push(m[2]);
2927
+ }
2928
+ return out;
2929
+ }
2930
+
2931
+ /**
2932
+ * One declaration, from the rules for \\\`selector\\\`. Later rules win, matching the
2933
+ * cascade for equal specificity.
2934
+ *
2935
+ * THROWS when absent, and that is the design. A missing declaration means the
2936
+ * pair table has drifted from the stylesheet, and the honest report for that is
2937
+ * a failure — not a skipped row, and certainly not a default that happens to
2938
+ * pass ([[zero-is-not-a-pass]]).
2939
+ */
2940
+ function decl(selector: string, prop: string): string {
2941
+ const bodies = ruleBodies(selector);
2942
+ if (bodies.length === 0) {
2943
+ throw new Error("contrast table names a selector that is not in globals.css: " + selector);
2944
+ }
2945
+ const re = new RegExp("(?:^|;)\\\\s*" + prop + "\\\\s*:\\\\s*([^;]+)");
2946
+ let found: string | null = null;
2947
+ for (const body of bodies) {
2948
+ const m = re.exec(body);
2949
+ if (m) found = m[1].trim();
2950
+ }
2951
+ if (found === null) {
2952
+ throw new Error("no \\\`" + prop + "\\\` declared for selector: " + selector);
2953
+ }
2954
+ return found;
2955
+ }
2956
+
2957
+ function declOr(selector: string, prop: string, fallback: string): string {
2958
+ try {
2959
+ return decl(selector, prop);
2960
+ } catch {
2961
+ return fallback;
2962
+ }
2963
+ }
2964
+
2965
+ /** Expand \\\`#abc\\\` to \\\`#aabbcc\\\`, lowercase. */
2966
+ function expand(hex: string): string {
2967
+ const h = hex.replace(/^#/, "").toLowerCase();
2968
+ return "#" + (h.length === 3 ? h.split("").map((c) => c + c).join("") : h);
2969
+ }
2970
+
2971
+ /** Resolve a \\\`var(--x)\\\` reference against \\\`:root\\\`, recursively. */
2972
+ function resolveToken(token: string, seen: string[] = []): string {
2973
+ const v = token.trim();
2974
+ const varRef = /^var\\(\\s*(--[\\w-]+)\\s*\\)$/.exec(v);
2975
+ if (varRef) {
2976
+ const name = varRef[1];
2977
+ if (seen.includes(name)) throw new Error("circular custom property: " + name);
2978
+ return colorIn(decl(":root", name), [...seen, name]);
2979
+ }
2980
+ if (/^#[0-9a-fA-F]{3}$/.test(v) || /^#[0-9a-fA-F]{6}$/.test(v)) return expand(v);
2981
+ // Deliberately NOT a silent skip. \\\`rgb()\\\`, \\\`hsl()\\\`, \\\`color-mix()\\\` and named
2982
+ // colors are all perfectly good CSS and this scanner cannot measure any of
2983
+ // them — so it says so and fails, rather than reporting a pass it did not earn.
2984
+ throw new Error("not a measurable color (use a hex, or teach this test): " + token);
2985
+ }
2986
+
2987
+ /** Pull the color out of a value, shorthand included (\\\`2px solid var(--x)\\\`). */
2988
+ function colorIn(value: string, seen: string[] = []): string {
2989
+ const direct = value.trim();
2990
+ if (/^(var\\(|#)/.test(direct) && !/\\s/.test(direct)) return resolveToken(direct, seen);
2991
+ const m = /var\\(\\s*--[\\w-]+\\s*\\)|#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3}\\b/.exec(direct);
2992
+ if (!m) throw new Error("no color token in value: " + value);
2993
+ return resolveToken(m[0], seen);
2994
+ }
2995
+
2996
+ /** The color a property resolves to, for a selector. */
2997
+ const color = (selector: string, prop: string): string => colorIn(decl(selector, prop));
2998
+ const px = (v: string): number => parseFloat(v);
2999
+
3000
+ const PAGE = color(":root", "--page-surface");
3001
+
3002
+ interface Pair {
3003
+ /** Plain-English description, used as the failure message. */
3004
+ what: string;
3005
+ /** The CSS selector or custom property this row models. */
3006
+ where: string;
3007
+ fg: string;
3008
+ bg: string;
3009
+ role: ContrastRole;
3010
+ }
3011
+
3012
+ // ---------------------------------------------------------------------------
3013
+ // THE PAIRS. Surface x text-role x threshold, one row each.
3014
+ //
3015
+ // This table is hand-maintained ON PURPOSE. "Which text sits on which surface"
3016
+ // is a fact about the rendered DOM, and no amount of stylesheet parsing can
3017
+ // recover it. What the test CAN do — and does, below — is prove the table has
3018
+ // not fallen behind the stylesheet: every color in globals.css must appear in
3019
+ // this table or in the exempt table, so a new surface cannot arrive unmeasured.
3020
+ // ---------------------------------------------------------------------------
3021
+ const PAIRS: Pair[] = [
3022
+ {
3023
+ what: "body copy on the page",
3024
+ where: "body",
3025
+ fg: color("body", "color"),
3026
+ bg: PAGE,
3027
+ role: {
3028
+ kind: "text",
3029
+ fontPx: px(decl("body", "font-size")),
3030
+ fontWeight: px(declOr("body", "font-weight", "400")),
3031
+ },
3032
+ },
3033
+ {
3034
+ what: "field label on the page",
3035
+ where: ".form-field label",
3036
+ fg: color(".form-field label", "color"),
3037
+ bg: PAGE,
3038
+ role: {
3039
+ kind: "text",
3040
+ fontPx: px(decl(".form-field label", "font-size")),
3041
+ fontWeight: px(decl(".form-field label", "font-weight")),
3042
+ },
3043
+ },
3044
+ {
3045
+ what: "typed text on the field fill",
3046
+ where: ".form-field input",
3047
+ fg: color(".form-field input", "color"),
3048
+ bg: color(".form-field input", "background"),
3049
+ role: {
3050
+ kind: "text",
3051
+ fontPx: px(decl(".form-field input", "font-size")),
3052
+ fontWeight: 400,
3053
+ },
3054
+ },
3055
+ {
3056
+ // A disabled field is exempt from the NON-TEXT rule, never from the TEXT
3057
+ // rule — the value in a disabled field still has to be readable, which is
3058
+ // usually the whole reason it is on screen.
3059
+ what: "text in a DISABLED field, on the disabled fill",
3060
+ where: ".form-field input:disabled",
3061
+ fg: color(".form-field input:disabled", "color"),
3062
+ bg: color(".form-field input:disabled", "background"),
3063
+ role: {
3064
+ kind: "text",
3065
+ fontPx: px(decl(".form-field input", "font-size")),
3066
+ fontWeight: 400,
3067
+ },
3068
+ },
3069
+ {
3070
+ // Sized by the label it sits in, not by itself.
3071
+ what: "the required-marker asterisk on the page",
3072
+ where: ".req-mark",
3073
+ fg: color(".req-mark", "color"),
3074
+ bg: PAGE,
3075
+ role: {
3076
+ kind: "text",
3077
+ fontPx: px(decl(".form-field label", "font-size")),
3078
+ fontWeight: px(decl(".req-mark", "font-weight")),
3079
+ },
3080
+ },
3081
+ {
3082
+ what: "the help-hint trigger on the page",
3083
+ where: ".info-hint > summary",
3084
+ fg: color(".info-hint > summary", "color"),
3085
+ bg: PAGE,
3086
+ role: {
3087
+ kind: "text",
3088
+ fontPx: px(decl(".info-hint", "font-size")),
3089
+ fontWeight: px(decl(".info-hint > summary", "font-weight")),
3090
+ },
3091
+ },
3092
+ {
3093
+ // THE BRAND-DEPENDENT ROW. Every other pair is fixed at scaffold time; this
3094
+ // one has the author's brand hex as its BACKGROUND, so it is the row that
3095
+ // can pass for one project and fail for the next. A 13px glyph, so the full
3096
+ // 4.5:1 applies however bold it is.
3097
+ what: "the 'i' glyph on the BRAND FILL",
3098
+ where: ".info-hint-icon",
3099
+ fg: color(".info-hint-icon", "color"),
3100
+ bg: color(".info-hint-icon", "background"),
3101
+ role: {
3102
+ kind: "text",
3103
+ fontPx: px(decl(".info-hint-icon", "font-size")),
3104
+ fontWeight: px(decl(".info-hint-icon", "font-weight")),
3105
+ },
3106
+ },
3107
+ {
3108
+ what: "help-panel body text on the PANEL (not on the page)",
3109
+ where: ".info-hint-body",
3110
+ fg: color(".info-hint-body", "color"),
3111
+ bg: color(".info-hint-body", "background"),
3112
+ role: {
3113
+ kind: "text",
3114
+ fontPx: px(decl(".info-hint-body", "font-size")),
3115
+ fontWeight: 400,
3116
+ },
3117
+ },
3118
+ {
3119
+ // The same ink as the row above, on a different surface, at a smaller size.
3120
+ // This is the pair a per-palette validator structurally cannot see.
3121
+ what: "inline code on the CODE TINT inside the help panel",
3122
+ where: ".info-hint-body code",
3123
+ fg: color(".info-hint-body", "color"),
3124
+ bg: color(".info-hint-body code", "background"),
3125
+ role: {
3126
+ kind: "text",
3127
+ fontPx: px(decl(".info-hint-body code", "font-size")),
3128
+ fontWeight: 400,
3129
+ },
3130
+ },
3131
+
3132
+ // --- non-text: boundaries and state (WCAG 2.1 SC 1.4.11) -----------------
3133
+ {
3134
+ what: "the resting edge of a field, against the page",
3135
+ where: "--field-border",
3136
+ fg: color(":root", "--field-border"),
3137
+ bg: PAGE,
3138
+ role: { kind: "non-text" },
3139
+ },
3140
+ {
3141
+ what: "the hovered edge of a field, against the page",
3142
+ where: "--field-border-hover",
3143
+ fg: color(":root", "--field-border-hover"),
3144
+ bg: PAGE,
3145
+ role: { kind: "non-text" },
3146
+ },
3147
+ {
3148
+ // \\\`outline-offset\\\` puts a 1px gap of PAGE between the ring and the box, so
3149
+ // the ring is measured against the page and not against the field fill.
3150
+ // This row is why \\\`--brand-focus\\\` exists as a separate variable.
3151
+ what: "the keyboard FOCUS RING, against the page",
3152
+ where: ".form-field input:focus-visible (outline)",
3153
+ fg: color(".form-field input:focus-visible", "outline"),
3154
+ bg: PAGE,
3155
+ role: { kind: "non-text" },
3156
+ },
3157
+ {
3158
+ what: "the focused field's own border, against the page",
3159
+ where: ".form-field input:focus-visible (border-color)",
3160
+ fg: color(".form-field input:focus-visible", "border-color"),
3161
+ bg: PAGE,
3162
+ role: { kind: "non-text" },
3163
+ },
3164
+ ];
3165
+
3166
+ // ---------------------------------------------------------------------------
3167
+ // EXEMPT. Colors that are in the stylesheet and deliberately NOT held to a
3168
+ // ratio. Each needs a reason, because an exempt list is precisely where a real
3169
+ // failure hides — "we decided this one does not count" is indistinguishable
3170
+ // from "we forgot this one" unless the decision is written down.
3171
+ // ---------------------------------------------------------------------------
3172
+ const EXEMPT: Array<{ color: string; where: string; why: string }> = [
3173
+ {
3174
+ color: color(".form-field input:disabled", "border-color"),
3175
+ where: ".form-field input:disabled (border-color)",
3176
+ why:
3177
+ "WCAG 2.1 SC 1.4.11 exempts an inactive user interface component in so " +
3178
+ "many words. Forcing 3:1 here would make a disabled field look MORE " +
3179
+ "present than an enabled one.",
3180
+ },
3181
+ {
3182
+ color: colorIn(decl(".info-hint-body", "border")),
3183
+ where: ".info-hint-body (border)",
3184
+ why:
3185
+ "Decorative container edge. It carries no state, and it is not required " +
3186
+ "to identify the panel — the panel's own text does that, and the 4px " +
3187
+ "brand stripe on its left gives it its shape.",
3188
+ },
3189
+ {
3190
+ color: color(":root", "--brand-primary"),
3191
+ where: "--brand-primary as a decorative fill / accent stripe",
3192
+ why:
3193
+ "The author's brand color, used as the info-icon fill and the panel's " +
3194
+ "left stripe. Both are decorative next to a text label that carries the " +
3195
+ "meaning, so SC 1.4.11 does not apply to the SHAPES. The GLYPH painted " +
3196
+ "on this fill is a different question and is measured in PAIRS above.",
3197
+ },
3198
+ ];
3199
+
3200
+ describe("the contrast math itself", () => {
3201
+ // A broken ratio function makes every assertion below meaningless while
3202
+ // leaving them all green, so it is pinned against published values first.
3203
+ it("reproduces known WCAG ratios", () => {
3204
+ expect(contrastRatio("#000000", "#ffffff")).toBeCloseTo(21, 5);
3205
+ expect(contrastRatio("#ffffff", "#ffffff")).toBeCloseTo(1, 5);
3206
+ // #767676 is the canonical "just passes AA on white" grey.
3207
+ expect(contrastRatio("#767676", "#ffffff")).toBeGreaterThanOrEqual(4.5);
3208
+ expect(contrastRatio("#777777", "#ffffff")).toBeLessThan(4.5);
3209
+ // Order must not matter.
3210
+ expect(contrastRatio("#8a4b08", "#ffffff")).toBeCloseTo(
3211
+ contrastRatio("#ffffff", "#8a4b08"),
3212
+ 10,
3213
+ );
3214
+ });
3215
+
3216
+ it("REFUSES a color it cannot measure instead of scoring it zero", () => {
3217
+ // An unparseable color that quietly returns 0 luminance would read as
3218
+ // maximum contrast against white and pass every check in this file.
3219
+ expect(() => contrastRatio("rgb(0 0 0)", "#ffffff")).toThrow();
3220
+ expect(() => contrastRatio("tomato", "#ffffff")).toThrow();
3221
+ });
3222
+
3223
+ it("detects a failing pair (the assertions above point the right way)", () => {
3224
+ // #ccc on white is ~1.6:1. If this reads as a pass, every other assertion
3225
+ // in this file is decorative.
3226
+ expect(meetsContrast("#cccccc", "#ffffff", { kind: "non-text" })).toBe(false);
3227
+ expect(meetsContrast("#cccccc", "#ffffff", { kind: "text", fontPx: 18, fontWeight: 400 })).toBe(
3228
+ false,
3229
+ );
3230
+ expect(meetsContrast("#3f3c36", "#ffffff", { kind: "text", fontPx: 18, fontWeight: 400 })).toBe(
3231
+ true,
3232
+ );
3233
+ });
3234
+
3235
+ it("does not treat 18px body copy as WCAG large text", () => {
3236
+ // The {{brand_name}} readability rule says body 18px+, and "18" invites the
3237
+ // wrong conclusion: 18px is 13.5pt, so it needs the full 4.5:1. The relaxed
3238
+ // 3:1 bar begins at 24px, or 18.66px when bold.
3239
+ expect(isLargeText(18, 400)).toBe(false);
3240
+ expect(isLargeText(18, 700)).toBe(false);
3241
+ expect(isLargeText(19, 700)).toBe(true);
3242
+ expect(isLargeText(24, 400)).toBe(true);
3243
+ expect(requiredRatio({ kind: "text", fontPx: 18, fontWeight: 400 })).toBe(4.5);
3244
+ expect(requiredRatio({ kind: "text", fontPx: 24, fontWeight: 400 })).toBe(3);
3245
+ expect(requiredRatio({ kind: "non-text" })).toBe(3);
3246
+ });
3247
+ });
3248
+
3249
+ describe("per-surface contrast", () => {
3250
+ it("has pairs to check, on more than one surface, at more than one threshold", () => {
3251
+ // Three separate ways this file could go vacuously green: an empty table, a
3252
+ // table that only ever looks at the page background (the exact bug this
3253
+ // file exists to prevent), and a table where every row happens to want the
3254
+ // same threshold, which would hide a broken requiredRatio().
3255
+ expect(PAIRS.length).toBeGreaterThan(8);
3256
+ expect(new Set(PAIRS.map((p) => p.bg)).size).toBeGreaterThan(2);
3257
+ const thresholds = new Set(PAIRS.map((p) => requiredRatio(p.role)));
3258
+ expect(thresholds).toContain(4.5);
3259
+ expect(thresholds).toContain(3);
3260
+ });
3261
+
3262
+ it.each(PAIRS.map((p) => [p.what, p] as const))("%s clears its threshold", (_what, pair) => {
3263
+ const need = requiredRatio(pair.role);
3264
+ const got = contrastRatio(pair.fg, pair.bg);
3265
+ expect(
3266
+ got >= need,
3267
+ pair.what +
3268
+ " (" +
3269
+ pair.where +
3270
+ "): " +
3271
+ pair.fg +
3272
+ " on " +
3273
+ pair.bg +
3274
+ " is " +
3275
+ // 3 decimals, not 2: a ratio of 4.4999 renders as "4.50:1, needs 4.5:1",
3276
+ // which reads like a rounding bug in the test rather than a real miss.
3277
+ got.toFixed(3) +
3278
+ ":1, needs " +
3279
+ need +
3280
+ ":1",
3281
+ ).toBe(true);
3282
+ });
3283
+
3284
+ it("measures --brand-ink on every surface it is actually painted on", () => {
3285
+ // The headline case. One ink, four backgrounds, four questions — and a
3286
+ // palette-shaped check would have asked only the first.
3287
+ const ink = color(":root", "--brand-ink");
3288
+ const surfaces = PAIRS.filter((p) => p.fg === ink).map((p) => p.bg);
3289
+ expect(new Set(surfaces).size).toBeGreaterThanOrEqual(3);
3290
+ });
3291
+
3292
+ it("the focus ring is NOT the raw brand primary", () => {
3293
+ // The defect this variable was introduced to fix. Most brand greens, golds
3294
+ // and oranges land near 2:1 on white, so a ring painted in --brand-primary
3295
+ // made FOCUSING a field reduce the visibility of its boundary. The pair
3296
+ // assertions above would catch a regression numerically; this one names it,
3297
+ // so the failure says what went wrong instead of just which ratio slipped.
3298
+ const ring = decl(".form-field input:focus-visible", "outline");
3299
+ expect(ring).toContain("var(--brand-focus)");
3300
+ expect(ring).not.toContain("var(--brand-primary)");
3301
+ });
3302
+ });
3303
+
3304
+ describe("the pair table has not fallen behind the stylesheet", () => {
3305
+ it("every color in globals.css is either measured or explicitly exempt", () => {
3306
+ // THIS is the check that makes the rest trustworthy. Without it, adding a
3307
+ // surface to the stylesheet leaves the table silently incomplete and the
3308
+ // suite green — which is how a per-palette validator fails, one level up.
3309
+ const declared = new Set<string>();
3310
+ const re = /#[0-9a-fA-F]{6}\\b|#[0-9a-fA-F]{3}\\b/g;
3311
+ let m: RegExpExecArray | null;
3312
+ while ((m = re.exec(CSS)) !== null) declared.add(expand(m[0]));
3313
+ expect(declared.size).toBeGreaterThan(6);
3314
+
3315
+ const accounted = new Set<string>([
3316
+ ...PAIRS.flatMap((p) => [p.fg, p.bg]),
3317
+ ...EXEMPT.map((e) => e.color),
3318
+ ]);
3319
+ const unaccounted = [...declared].filter((c) => !accounted.has(c));
3320
+ expect(
3321
+ unaccounted,
3322
+ "these colors are in app/globals.css but no pair measures them. Add a row " +
3323
+ "to PAIRS naming the surface each one is painted on — or to EXEMPT with " +
3324
+ "a reason, in test/contrast.test.ts",
3325
+ ).toEqual([]);
3326
+ });
3327
+
3328
+ it("every exempt color gives a reason", () => {
3329
+ // An exempt row without a stated reason is a silent suppression.
3330
+ for (const e of EXEMPT) {
3331
+ expect(e.why.length, e.where + " is exempt without saying why").toBeGreaterThan(40);
3332
+ expect(/1\\.4\\.11|decorative|inactive/i.test(e.why), e.where + ": " + e.why).toBe(true);
3333
+ }
3334
+ // The exempt list is small on purpose. If it is growing, the stylesheet is
3335
+ // accumulating colors nobody measured.
3336
+ expect(EXEMPT.length).toBeLessThanOrEqual(5);
3337
+ });
3338
+ });
3339
+ `;
2739
3340
  const FORM_STANDARDS_TEST_TEMPLATE = `/**
2740
3341
  * {{brand_name}} form standards, enforced as tests rather than as a convention
2741
3342
  * someone has to remember:
@@ -4050,6 +4651,17 @@ export function scaffoldNextjs(inputs, opts) {
4050
4651
  { path: "test/server-only.stub.ts", content: SERVER_ONLY_STUB_TEMPLATE },
4051
4652
  { path: "app/globals.css", content: globalsCss(spec.primaryColor) },
4052
4653
  { path: "components/FormBits.tsx", content: sub(FORM_BITS_TEMPLATE, inputs, opts, spec) },
4654
+ // The contrast pair table and the math it uses. Emitted unconditionally: the
4655
+ // stylesheet it measures is emitted unconditionally, and a project whose
4656
+ // palette is unmeasured is exactly the project that needs measuring.
4657
+ {
4658
+ path: "lib/a11y/contrast.ts",
4659
+ content: sub(CONTRAST_MODULE_TEMPLATE, inputs, opts, spec),
4660
+ },
4661
+ {
4662
+ path: "test/contrast.test.ts",
4663
+ content: sub(CONTRAST_TEST_TEMPLATE, inputs, opts, spec),
4664
+ },
4053
4665
  {
4054
4666
  path: "test/form-standards.test.ts",
4055
4667
  content: sub(FORM_STANDARDS_TEST_TEMPLATE, inputs, opts, spec),
@@ -78,7 +78,7 @@ export interface StandardsResolution {
78
78
  * family — the safe default for anything else with `has_web_ui=true`.
79
79
  */
80
80
  export declare function fathomEnvVarFor(projectType: ProjectType): string;
81
- export declare const CANONICAL_COORDINATION_BLOCK_VERSION = "v0.1.26";
81
+ export declare const CANONICAL_COORDINATION_BLOCK_VERSION = "v0.1.27";
82
82
  /**
83
83
  * The canonical **Capture Learnings** block, emitted VERBATIM into every
84
84
  * scaffolded `CLAUDE.md`.
package/dist/standards.js CHANGED
@@ -447,7 +447,7 @@ const NEON_CAREFUL_BODY = `### Neon-careful (Neon Postgres)
447
447
  // Two consecutive handoffs compared this constant against the DOCUMENT version
448
448
  // and reported a "15-version gap" that did not exist — the real gap was 4. Read
449
449
  // the `<!-- ... canonical-block vX.Y.Z -->` comment, never the `**Version:**` line.
450
- export const CANONICAL_COORDINATION_BLOCK_VERSION = "v0.1.26";
450
+ export const CANONICAL_COORDINATION_BLOCK_VERSION = "v0.1.27";
451
451
  /**
452
452
  * The canonical **Capture Learnings** block, emitted VERBATIM into every
453
453
  * scaffolded `CLAUDE.md`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zero2webmaster/starter-kit",
3
- "version": "0.23.0",
3
+ "version": "0.25.0",
4
4
  "description": "Node CLI to scaffold new Z2W projects from canonical Templates + AGENTS.md.",
5
5
  "author": {
6
6
  "name": "Dr. Kerry Kriger",