@reqvire-org/ads 0.3.49 → 0.3.51

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/README.md +36 -6
  2. package/dist/active-clock.mjs +34 -0
  3. package/dist/assets.mjs +20 -2
  4. package/dist/boundaries.mjs +2 -0
  5. package/dist/browser-audit/first-render.mjs +18 -0
  6. package/dist/browser-audit/layout-overflow.mjs +98 -0
  7. package/dist/browser-audit/layout-shift.mjs +32 -0
  8. package/dist/browser-audit/non-text-contrast.mjs +87 -0
  9. package/dist/browser-audit/worker.mjs +52 -15
  10. package/dist/browser-audit.mjs +239 -22
  11. package/dist/capture/worker.mjs +2 -5
  12. package/dist/check.mjs +16 -1
  13. package/dist/cli.mjs +9 -5
  14. package/dist/component-contrast.mjs +138 -0
  15. package/dist/config.mjs +12 -6
  16. package/dist/finding-rules.mjs +16 -1
  17. package/dist/fonts-generated.mjs +85 -0
  18. package/dist/image-attributes.mjs +110 -0
  19. package/dist/init.mjs +2 -0
  20. package/dist/layout-widths.mjs +228 -0
  21. package/dist/mcp/context.mjs +1 -1
  22. package/dist/mcp/mutations.mjs +7 -5
  23. package/dist/mcp/preview-watch.mjs +9 -8
  24. package/dist/mcp/server.mjs +6 -4
  25. package/dist/preview-files.mjs +3 -0
  26. package/dist/project-boundary.mjs +23 -0
  27. package/dist/project-documents.mjs +2 -1
  28. package/dist/scenarios-compiler.mjs +23 -3
  29. package/dist/showcase/client.bundle.js +11 -11
  30. package/dist/showcase/icons.js +5 -5
  31. package/dist/showcase/style.css +1 -1
  32. package/dist/skills/ads-break-ui/SKILL.md +9 -0
  33. package/dist/skills/ads-break-ui/references/atomic-styles.md +2 -0
  34. package/dist/skills/ads-break-ui/references/design-data.md +52 -0
  35. package/dist/skills/ads-break-ui/references/drafts.md +1 -1
  36. package/dist/skills/ads-break-ui/references/guarded-editing.md +1 -1
  37. package/dist/skills/ads-break-ui/references/validation.md +9 -5
  38. package/dist/skills/ads-designer/SKILL.md +26 -4
  39. package/dist/skills/ads-designer/references/accessibility.md +30 -13
  40. package/dist/skills/ads-designer/references/atomic-styles.md +2 -0
  41. package/dist/skills/ads-designer/references/branding.md +10 -5
  42. package/dist/skills/ads-designer/references/cli.md +2 -1
  43. package/dist/skills/ads-designer/references/design-data.md +52 -0
  44. package/dist/skills/ads-designer/references/drafts.md +1 -1
  45. package/dist/skills/ads-designer/references/guarded-editing.md +1 -1
  46. package/dist/skills/ads-designer/references/mobile.md +3 -0
  47. package/dist/skills/ads-designer/references/performance.md +89 -0
  48. package/dist/skills/ads-designer/references/validation.md +9 -5
  49. package/dist/skills/ads-import/references/atomic-styles.md +2 -0
  50. package/dist/skills/ads-import/references/cli.md +2 -1
  51. package/dist/skills/ads-import/references/design-data.md +52 -0
  52. package/dist/skills/ads-import/references/drafts.md +1 -1
  53. package/dist/skills/ads-import/references/guarded-editing.md +1 -1
  54. package/dist/skills/ads-import/references/validation.md +9 -5
  55. package/dist/skills/ads-motion/references/atomic-styles.md +2 -0
  56. package/dist/skills/ads-motion/references/design-data.md +52 -0
  57. package/dist/skills/ads-motion/references/drafts.md +1 -1
  58. package/dist/skills/ads-motion/references/guarded-editing.md +1 -1
  59. package/dist/skills/ads-motion/references/validation.md +9 -5
  60. package/dist/skills/ads-port/references/atomic-styles.md +2 -0
  61. package/dist/skills/ads-port/references/cli.md +2 -1
  62. package/dist/skills/ads-port/references/design-data.md +52 -0
  63. package/dist/skills/ads-port/references/drafts.md +1 -1
  64. package/dist/skills/ads-port/references/guarded-editing.md +1 -1
  65. package/dist/skills/ads-port/references/validation.md +9 -5
  66. package/dist/starters/preact/package.json +1 -0
  67. package/dist/starters/react/ADS.md +1 -1
  68. package/dist/starters/react/README.md +16 -2
  69. package/dist/starters/react/design-system/components/Actions/Button/Button.tsx +1 -1
  70. package/dist/starters/react/design-system/components/Content/Image/Image.ads.fixture.ts +2 -0
  71. package/dist/starters/react/design-system/components/Content/Image/Image.ads.scenario.tsx +13 -0
  72. package/dist/starters/react/design-system/components/Content/Image/Image.tsx +51 -0
  73. package/dist/starters/react/design-system/components/Content/Image/README.md +20 -0
  74. package/dist/starters/react/design-system/components/Content/Logo/Logo.tsx +2 -2
  75. package/dist/starters/react/design-system/index.ts +1 -0
  76. package/dist/starters/react/design-system/tokens/Layout.ads.fixture.ts +16 -0
  77. package/dist/starters/react/design-system/tokens/spacing.css +18 -0
  78. package/dist/starters/react/package-lock.json +47 -0
  79. package/dist/starters/react/package.json +2 -1
  80. package/dist/test-boundaries.mjs +30 -1
  81. package/dist/themes-generated.mjs +15 -4
  82. package/dist/token-quality.mjs +27 -17
  83. package/dist/units.mjs +2 -1
  84. package/dist/validation-checks.mjs +5 -4
  85. package/dist/validation.mjs +1 -1
  86. package/dist/verification/browser.mjs +28 -2
  87. package/dist/verification.mjs +5 -4
  88. package/docs/ADS.md +4 -1
  89. package/docs/ARCHITECTURE.md +16 -3
  90. package/docs/CHANGELOG.md +127 -12
  91. package/docs/GUIDE.md +238 -14
  92. package/docs/MCP.md +14 -10
  93. package/package.json +1 -1
@@ -9,19 +9,40 @@ import { executeDevelopmentCommand } from "./verification.mjs";
9
9
  import { findingSeverity, routeFindings } from "./finding-rules.mjs";
10
10
  import { inspectScenarios } from "./scenarios.mjs";
11
11
  import { inspectUnits } from "./units.mjs";
12
+ import { globMatcher, smallPartLimitPx } from "./layout-widths.mjs";
12
13
  import { affectedScenarios } from "./verification.mjs";
13
14
 
14
15
  // Browser accessibility audit: axe-core (Deque, MPL-2.0, an unmodified ADS dependency
15
16
  // injected at run time, never bundled) runs inside each rendered scenario document, once per
16
- // declared brand and theme. Only the scenario's #root is audited; the preview status chrome is excluded.
17
- // Findings are errors: they fail `ads audit` and any validation/acceptance policy with
18
- // browserAudit. Automated rules catch a subset of WCAG failures; passing proves nothing more.
17
+ // declared brand and theme, followed by ADS's own non-text contrast check (WCAG 1.4.11),
18
+ // which axe does not cover, and its layout-overflow check, which resizes the same page. Only the scenario's #root is audited; the preview status chrome is excluded.
19
+ // Findings are errors: they fail `ads audit` and the validation and acceptance policies,
20
+ // which audit by default (browserAudit: false turns a policy's audit off). Automated rules catch a subset of WCAG failures; passing proves nothing more.
19
21
 
20
22
  export const AUDIT_RULE = "a11y-axe";
23
+ /** What axe could not decide on its own, such as contrast over a gradient: to check by hand. */
24
+ export const INCOMPLETE_RULE = "a11y-incomplete";
25
+ /** ADS's own rendered check: WCAG 1.4.11 non-text contrast of control boundaries and icons (axe does not check it). */
26
+ export const NON_TEXT_RULE = "a11y-non-text-contrast";
27
+ /** ADS's own rendered layout check: horizontal overflow at each of overflowWidths. */
28
+ export const OVERFLOW_RULE = "layout-overflow";
29
+ export const NARROW_RULE = "layout-overflow-narrow";
30
+ /** ADS's own rendered check: a scenario's layout shift above the Core Web Vitals 0.1 threshold. */
31
+ export const SHIFT_RULE = "layout-shift";
32
+ const shiftLimit = 0.1;
21
33
  /** WCAG A/AA rule tags. Best-practice and page-level rules (landmarks, one h1) don't fit isolated scenarios. */
22
34
  export const auditTags = Object.freeze(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"]);
23
35
  const viewport = { width: 1280, height: 800 };
36
+ /** Viewport widths layout-overflow renders every scenario at: phone, tablet and desktop. */
37
+ export const overflowWidths = Object.freeze([390, 768, 1280]);
24
38
  export const auditedKinds = Object.freeze(["components", "patterns", "composition"]);
39
+ /** The width layout-overflow also renders scenarios of these kinds at, inside the widest viewport
40
+ * and in the first theme, since layout does not follow color: a narrow side pane. A composition is
41
+ * a whole screen, and is never hosted in one. */
42
+ export const containerWidth = 240;
43
+ export const containerKinds = Object.freeze(["components", "patterns"]);
44
+ /** Attempts for one render, against a dropped preview connection or a slow preview. */
45
+ export const auditAttempts = 3;
25
46
  const limits = { scenarios: 500, nodes: 5, findings: 2000, reportBytes: 8 * 1024 * 1024, pages: 4 };
26
47
 
27
48
  /** WCAG success criteria named by axe tags such as wcag143 or wcag1412. */
@@ -52,6 +73,107 @@ export function auditFindings(runs, scenarios) {
52
73
  });
53
74
  }
54
75
 
76
+ /** One info item per scenario, axe rule and element set, across brands and themes. */
77
+ export function incompleteFindings(runs, scenarios) {
78
+ const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), groups = new Map();
79
+ const add = (list, value) => { if (value !== undefined && !list.includes(value)) list.push(value); };
80
+ for (const run of runs) for (const item of run.incomplete ?? []) {
81
+ const key = JSON.stringify([run.scenario, item.id, item.nodes.map(node => node.selector).sort()]);
82
+ const group = groups.get(key) ?? { scenario: run.scenario, themes: [], brands: [], item };
83
+ groups.set(key, group); add(group.themes, run.theme); add(group.brands, run.brand);
84
+ }
85
+ return [...groups.values()].slice(0, limits.findings).map(({ scenario, themes, brands, item }) => {
86
+ const where = item.nodes.slice(0, 3).map(node => `${node.selector}${node.reason ? ` (${node.reason})` : ""}`).join(", ") + (item.nodeCount > 3 ? ` and ${item.nodeCount - 3} more` : "");
87
+ return {
88
+ rule: INCOMPLETE_RULE, severity: findingSeverity(INCOMPLETE_RULE), file: files.get(scenario) ?? scenario, line: 1, column: 1, source: "axe-core", axeRule: item.id, impact: item.impact ?? null, scenario, themes, ...(brands.length ? { brands } : {}),
89
+ nodes: item.nodes, nodeCount: item.nodeCount, helpUrl: item.helpUrl, guidanceUri: "ads://guides/accessibility",
90
+ message: `axe could not decide ${item.id} in ${scenario} [${themes.join(", ")}${brands.length ? `; ${brands.join(", ")}` : ""}]: check it by hand. ${item.help}. ${item.nodeCount} element${item.nodeCount === 1 ? "" : "s"}: ${where}. ${item.helpUrl}`,
91
+ };
92
+ });
93
+ }
94
+
95
+ const nonTextKinds = {
96
+ border: { what: count => count === 1 ? "control's border is its only boundary and has" : "controls' borders are their only boundary and have", against: "the background around it", fix: "Give the boundary a border token with 3:1 against the surface it sits on, such as --border-strong, or a background with 3:1 against it." },
97
+ icon: { what: count => count === 1 ? "icon-only control's icon has" : "icon-only controls' icons have", against: "its control's background", fix: "Paint the icon with a text or foreground token that has 3:1 against the control's background." },
98
+ };
99
+
100
+ /** Collapse per-brand, per-theme non-text contrast issues into ADS errors: one per scenario, kind
101
+ * and failing element set, keeping each element's lowest ratio. */
102
+ export function nonTextContrastFindings(runs, scenarios) {
103
+ const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), groups = new Map();
104
+ const add = (list, value) => { if (value !== undefined && !list.includes(value)) list.push(value); };
105
+ for (const run of runs) for (const kind of Object.keys(nonTextKinds)) {
106
+ const issues = (run.nonText?.issues ?? []).filter(issue => issue.kind === kind);
107
+ if (!issues.length) continue;
108
+ const key = JSON.stringify([run.scenario, kind, issues.map(issue => issue.selector).sort()]);
109
+ const group = groups.get(key) ?? { scenario: run.scenario, kind, themes: [], brands: [], nodes: new Map(), nodeCount: 0 };
110
+ groups.set(key, group); add(group.themes, run.theme); add(group.brands, run.brand);
111
+ group.nodeCount = Math.max(group.nodeCount, run.nonText.counts?.[kind] ?? issues.length);
112
+ for (const issue of issues) {
113
+ const previous = group.nodes.get(issue.selector);
114
+ if (!previous || issue.ratio < previous.ratio) group.nodes.set(issue.selector, { ...issue, theme: run.theme, ...(run.brand ? { brand: run.brand } : {}) });
115
+ }
116
+ }
117
+ return [...groups.values()].slice(0, limits.findings).map(({ scenario, kind, themes, brands, nodes, nodeCount }) => {
118
+ const list = [...nodes.values()], ratio = Math.min(...list.map(node => node.ratio));
119
+ const where = list.slice(0, 3).map(node => `${node.selector} (${node.ratio.toFixed(2)}:1, ${node.foreground} on ${node.background})`).join(", ") + (nodeCount > 3 ? ` and ${nodeCount - 3} more` : "");
120
+ return {
121
+ rule: NON_TEXT_RULE, severity: findingSeverity(NON_TEXT_RULE), file: files.get(scenario) ?? scenario, line: 1, column: 1, source: "ads", kind, wcag: ["1.4.11"], scenario, themes, ...(brands.length ? { brands } : {}),
122
+ ratio, nodes: list, nodeCount, guidanceUri: "ads://guides/accessibility",
123
+ message: `Non-text contrast (WCAG 1.4.11) in ${scenario} [${themes.join(", ")}${brands.length ? `; ${brands.join(", ")}` : ""}]: ${nodeCount} ${nonTextKinds[kind].what(nodeCount)} less than 3:1 against ${nonTextKinds[kind].against}: ${where}. ${nonTextKinds[kind].fix}`,
124
+ };
125
+ });
126
+ }
127
+
128
+ const overflowKinds = {
129
+ document: { what: "the page scrolls horizontally", fix: "Find the element wider than its container; use fluid widths, min-width: 0 on flex and grid children, and let long text wrap." },
130
+ viewport: { what: "content reaches past the viewport", fix: "Make the element fluid (%, fr, a --grid-span-N token in a container query), wrap it, or put it in an overflow-x: auto scroller." },
131
+ container: { what: "content reaches past its container", fix: "Make the element fluid (%, fr, min(100%, ...)), wrap it, or put it in an overflow-x: auto scroller. A width that truly stays this wide only fits an overlay: list its owner in layout.fixedWidthUnits." },
132
+ clipped: { what: "content is cut off by overflow hidden or clip", fix: "Make the content fit, truncate it with text-overflow: ellipsis, or use overflow-x: auto if it should scroll." },
133
+ };
134
+
135
+ /** Collapse overflow issues into ADS errors: one per scenario, kind and failing element set, with
136
+ * the widths, themes and brands it fails in. */
137
+ export function layoutOverflowFindings(runs, scenarios) {
138
+ const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), groups = new Map();
139
+ const add = (list, value) => { if (value !== undefined && !list.includes(value)) list.push(value); };
140
+ for (const run of runs) for (const { width, container = false, issues = [], counts = {} } of run.layout ?? []) for (const kind of Object.keys(overflowKinds)) {
141
+ const found = issues.filter(issue => issue.kind === kind);
142
+ if (!found.length) continue;
143
+ const key = JSON.stringify([run.scenario, kind, container, found.map(issue => issue.selector).sort()]);
144
+ const group = groups.get(key) ?? { scenario: run.scenario, kind, container, widths: [], themes: [], brands: [], nodes: new Map(), nodeCount: 0 };
145
+ groups.set(key, group); add(group.widths, width); add(group.themes, run.theme); add(group.brands, run.brand);
146
+ group.nodeCount = Math.max(group.nodeCount, counts[kind] ?? found.length);
147
+ for (const issue of found) if (!(group.nodes.get(issue.selector)?.overflow >= issue.overflow)) group.nodes.set(issue.selector, { ...issue, width });
148
+ }
149
+ return [...groups.values()].slice(0, limits.findings).map(({ scenario, kind, container, widths, themes, brands, nodes, nodeCount }) => {
150
+ const list = [...nodes.values()], sorted = [...widths].sort((a, b) => a - b);
151
+ const where = list.slice(0, 3).map(node => `${node.selector} (${node.overflow}px at ${node.width}px)`).join(", ") + (nodeCount > 3 ? ` and ${nodeCount - 3} more` : "");
152
+ return {
153
+ rule: container ? NARROW_RULE : OVERFLOW_RULE, severity: findingSeverity(container ? NARROW_RULE : OVERFLOW_RULE), file: files.get(scenario) ?? scenario, line: 1, column: 1, source: "ads", kind, ...(container ? { container: sorted[0] } : { widths: sorted }), scenario, themes, ...(brands.length ? { brands } : {}),
154
+ nodes: list, nodeCount, guidanceUri: "ads://guides/tokens",
155
+ message: `Layout overflow in ${scenario} ${container ? `in a ${sorted[0]} px container` : `at ${sorted.join(", ")} px wide`} [${themes.join(", ")}${brands.length ? `; ${brands.join(", ")}` : ""}]: ${overflowKinds[kind].what}: ${where}. ${overflowKinds[kind].fix}`,
156
+ };
157
+ });
158
+ }
159
+
160
+ /** One error per scenario above the threshold, with its worst score, themes, brands and elements. */
161
+ export function layoutShiftFindings(runs, scenarios) {
162
+ const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), groups = new Map();
163
+ const add = (list, value) => { if (value !== undefined && !list.includes(value)) list.push(value); };
164
+ for (const run of runs) {
165
+ if (!(run.layoutShift?.value > shiftLimit)) continue;
166
+ const group = groups.get(run.scenario) ?? { scenario: run.scenario, themes: [], brands: [], value: 0, nodes: [] };
167
+ groups.set(run.scenario, group); add(group.themes, run.theme); add(group.brands, run.brand);
168
+ group.value = Math.max(group.value, run.layoutShift.value);
169
+ for (const node of run.layoutShift.nodes) add(group.nodes, node);
170
+ }
171
+ return [...groups.values()].slice(0, limits.findings).map(({ scenario, themes, brands, value, nodes }) => ({
172
+ rule: SHIFT_RULE, severity: findingSeverity(SHIFT_RULE), file: files.get(scenario) ?? scenario, line: 1, column: 1, source: "ads", scenario, value, themes, ...(brands.length ? { brands } : {}), nodes: nodes.slice(0, limits.nodes).map(selector => ({ selector })), guidanceUri: "ads://guides/performance",
173
+ message: `Layout shift ${value} in ${scenario} [${themes.join(", ")}${brands.length ? `; ${brands.join(", ")}` : ""}], above ${shiftLimit}${nodes.length ? `: ${nodes.slice(0, 3).join(", ")}` : ""}. Give images and media width and height, reserve space for late content, and load the fonts the first text uses early.`,
174
+ }));
175
+ }
176
+
55
177
  /**
56
178
  * UI scenarios a candidate change can affect, for acceptance audits. Changes to configuration,
57
179
  * foundation, tokens, assets or files outside every unit affect all rendering and select every UI
@@ -76,7 +198,7 @@ export function auditScenarioSelection(options, changedFiles) {
76
198
  export function auditCheck(audit, extra = {}) {
77
199
  const routed = routeFindings([], audit.findings);
78
200
  return { routed, check: { name: "browser-accessibility-audit", passed: !routed.diagnostics.length, engine: audit.engine, scenarios: audit.scenarios, themes: audit.themes, ...(audit.brands ? { brands: audit.brands } : {}),
79
- renders: audit.runs, errors: routed.diagnostics.length, reviews: routed.advisories.length, elapsedMs: audit.elapsedMs, ...extra } };
201
+ renders: audit.runs, ...(audit.retries ? { retries: audit.retries } : {}), errors: routed.diagnostics.length, reviews: routed.advisories.filter(item => item.severity === "review").length, infos: routed.advisories.filter(item => item.severity === "info").length, elapsedMs: audit.elapsedMs, ...extra } };
80
202
  }
81
203
 
82
204
  function projectPlaywright(root) {
@@ -85,19 +207,90 @@ function projectPlaywright(root) {
85
207
  return null;
86
208
  }
87
209
 
210
+ const installHint = "`npm install -D @playwright/test` and `npx playwright install chromium` (Bun: `bun add -d @playwright/test` and `bunx playwright install chromium`)";
211
+
88
212
  /** Whether the project can run the audit: project-local Playwright, as for captures. */
89
213
  export const browserAuditAvailable = root => !!projectPlaywright(path.resolve(root));
90
214
 
215
+ /** Scenarios of an owner in layout.fixedWidthUnits float above the layout, and have no container to fit. */
216
+ function floatingScenarios(options, scenarios) {
217
+ const globs = options.config.layout.fixedWidthUnits, floating = globMatcher(globs);
218
+ if (!globs.length) return new Set();
219
+ const inventory = inspectUnits(options);
220
+ return new Set(scenarios.filter(scenario => {
221
+ const owner = inventory.owner(inventory.relative(scenario.file));
222
+ return owner && (floating(owner) || inventory.units.find(unit => unit.id === owner)?.files.some(floating));
223
+ }).map(scenario => scenario.id));
224
+ }
225
+
226
+ const renderKey = ({ scenario, theme, brand }) => JSON.stringify([scenario, theme, brand ?? null]);
227
+ const clipCause = text => String(text).replace(/\s+/g, " ").trim().slice(0, 500);
228
+
229
+ /** Warm scenarios, separating those that cannot build. A project that fails validation fails
230
+ * every scenario the same way, so it stops the audit as it always has; anything else is one
231
+ * scenario's trouble (a slow or dropped build) and comes back as its cause. */
232
+ async function warmScenariosApart(host, ids, signal) {
233
+ const unbuilt = new Map();
234
+ const projectWide = error => signal.aborted || error.build?.failure?.scope === "project" || error.build?.failure?.phase === "validation";
235
+ try { await host.warmScenarios?.(ids, signal); return unbuilt; }
236
+ catch (error) { if (projectWide(error)) throw error; }
237
+ for (const id of ids) {
238
+ try { await host.warmScenarios?.([id], signal); }
239
+ catch (error) { if (projectWide(error)) throw error; unbuilt.set(id, clipCause(error.message)); }
240
+ }
241
+ return unbuilt;
242
+ }
243
+
244
+ /** One browser process over the given renders. Its report grows as they finish, so a worker that
245
+ * dies keeps what it finished. A browser that is not installed stops the audit. */
246
+ async function runAuditWorker({ root, temporary, playwright, settings, apps, signal }) {
247
+ const request = path.join(temporary, "request.json"), report = path.join(temporary, "report.json"), runId = randomUUID();
248
+ rmSync(report, { force: true });
249
+ writeFileSync(request, JSON.stringify({ schemaVersion: 1, runId, playwright, axe: requireTool.resolve("axe-core/axe.min.js"), settings, viewport, overflowWidths, smallPart: smallPartLimitPx, tags: auditTags, nodeLimit: limits.nodes, concurrency: limits.pages, apps, output: temporary }));
250
+ const timeoutMs = Math.min(30 * 60 * 1000, settings.timeoutMs + apps.length * Math.min(settings.timeoutMs, 15000));
251
+ let cause;
252
+ try {
253
+ const run = await executeDevelopmentCommand({ command: "runtime", timeoutMs, label: "Accessibility audit" }, [fileURLToPath(new URL("./browser-audit/worker.mjs", import.meta.url)), request], root, {}, signal);
254
+ if (run.code !== 0 && /Executable doesn't exist|playwright install/i.test(run.output)) throw Object.assign(new Error(`The browser accessibility audit needs Playwright's ${settings.browser} browser. Install it with \`npx playwright install ${settings.browser}\` (Bun: \`bunx playwright install ${settings.browser}\`), or select an installed Chrome with mcp.capture.channel "chrome".`), { code: "ADS_AUDIT_UNAVAILABLE" });
255
+ if (run.code !== 0) cause = `Accessibility audit browser failed (${run.code}): ${clipCause(run.output.slice(-400))}`;
256
+ } catch (error) {
257
+ if (signal.aborted || error.code === "ADS_AUDIT_UNAVAILABLE") throw error;
258
+ cause = clipCause(error.message);
259
+ }
260
+ if (!existsSync(report) || realpathSync(report) !== report || lstatSync(report).size > limits.reportBytes) return { runs: [], cause: cause ?? "Accessibility audit produced no bounded report." };
261
+ const value = JSON.parse(readFileSync(report, "utf8"));
262
+ if (value.schemaVersion !== 1 || value.runId !== runId || !Array.isArray(value.runs)) return { runs: [], cause: cause ?? "Accessibility audit returned the wrong run identity." };
263
+ return { runs: value.runs, cause };
264
+ }
265
+
266
+ /** A scenario that could not be audited is an error naming it and its last cause, never a pass. */
267
+ function unauditedFindings(renders, scenarios) {
268
+ const files = new Map(scenarios.map(scenario => [scenario.id, scenario.file])), groups = new Map();
269
+ for (const { app, attempts, causes } of renders) {
270
+ const group = groups.get(app.scenario) ?? { scenario: app.scenario, themes: [], brands: [], attempts, cause: "" };
271
+ groups.set(app.scenario, group);
272
+ if (!group.themes.includes(app.theme)) group.themes.push(app.theme);
273
+ if (app.brand && !group.brands.includes(app.brand)) group.brands.push(app.brand);
274
+ group.cause = causes.at(-1) ?? group.cause;
275
+ }
276
+ return [...groups.values()].map(({ scenario, themes, brands, attempts, cause }) => ({
277
+ rule: "browser-audit", severity: findingSeverity("browser-audit"), file: files.get(scenario) ?? scenario, line: 1, column: 1, source: "ads", scenario, themes, ...(brands.length ? { brands } : {}), attempts, cause, guidanceUri: "ads://guides/accessibility",
278
+ message: `Could not audit ${scenario} [${themes.join(", ")}${brands.length ? `; ${brands.join(", ")}` : ""}] in ${attempts} attempt${attempts === 1 ? "" : "s"}: ${cause}`,
279
+ }));
280
+ }
281
+
91
282
  /**
92
283
  * Render every selected scenario in every declared brand and theme and run axe-core on it.
93
284
  * Without declared brands it renders the single default brand.
94
285
  * Reuses a showcase-serving preview host when given one; otherwise starts and closes its own.
286
+ * A render that fails is retried on its own, up to auditAttempts, and the rest keep their results.
287
+ * Findings never cause a retry; a retried pass is listed in retries.
95
288
  */
96
289
  export async function runBrowserAudit(root, { scenarios: selected, themes: selectedThemes, brands: selectedBrands, previewHost, signal = new AbortController().signal, onProgress } = {}) {
97
290
  root = path.resolve(root);
98
291
  const startedAt = Date.now(), options = loadConfig(root);
99
292
  const playwright = projectPlaywright(root);
100
- if (!playwright) throw Object.assign(new Error("The browser accessibility audit requires project-local @playwright/test or playwright and its installed browser. ADS installs neither; mcp.capture selects browser/channel/timeoutMs."), { code: "ADS_AUDIT_UNAVAILABLE" });
293
+ if (!playwright) throw Object.assign(new Error(`The browser accessibility audit needs Playwright in the project. Install it with ${installHint}, or set browserAudit to false in the acceptance and validation policies of ds.config.json.`), { code: "ADS_AUDIT_UNAVAILABLE" });
101
294
  const registry = discoverScenarioRegistry(options);
102
295
  if (registry.diagnostics.length) throw new Error(`Scenario registration failed: ${registry.diagnostics[0].message}`);
103
296
  const unknown = (selected ?? []).filter(id => !registry.scenarios.some(scenario => scenario.id === id));
@@ -120,24 +313,48 @@ export async function runBrowserAudit(root, { scenarios: selected, themes: selec
120
313
  let host = previewHost;
121
314
  try {
122
315
  onProgress?.({ stage: "browser-audit", message: `Accessibility audit: building ${scenarios.length} scenario previews.`, elapsedMs: Date.now() - startedAt });
123
- if (!host?.url) { const { startAdsMcp } = await import("./mcp/server.mjs"); host = await startAdsMcp(root, { stdio: false, showcase: true }); }
124
- await host.warmScenarios?.(scenarios.map(scenario => scenario.id), signal);
125
- const apps = themes.flatMap(theme => (brands.length ? brands : [undefined]).flatMap(brand => scenarios.map(scenario => {
126
- const url = new URL(host.url); url.searchParams.set("scenario", scenario.id); url.searchParams.set("capture", "1"); url.searchParams.set("theme", theme.name);
127
- if (brand) url.searchParams.set("brand", brand.name);
128
- return { scenario: scenario.id, theme: theme.name, ...(brand ? { brand: brand.name } : {}), scheme: theme.scheme, url: url.href };
129
- })));
316
+ const startHost = async () => { const { startAdsMcp } = await import("./mcp/server.mjs"); return startAdsMcp(root, { stdio: false, showcase: true }); };
317
+ if (!host?.url) host = await startHost();
130
318
  const settings = { browser: "chromium", timeoutMs: 60000, ...options.config.mcp.capture };
131
- const request = path.join(temporary, "request.json"), report = path.join(temporary, "report.json"), runId = randomUUID();
132
- writeFileSync(request, JSON.stringify({ schemaVersion: 1, runId, playwright, axe: requireTool.resolve("axe-core/axe.min.js"), settings, viewport, tags: auditTags, nodeLimit: limits.nodes, concurrency: limits.pages, apps, output: temporary }));
133
- onProgress?.({ stage: "browser-audit", message: `Accessibility audit: ${apps.length} renders (${scenarios.length} scenarios × ${themes.length} themes${brands.length ? ` × ${brands.length} brands` : ""}).`, elapsedMs: Date.now() - startedAt });
134
- const timeoutMs = Math.min(30 * 60 * 1000, settings.timeoutMs + apps.length * Math.min(settings.timeoutMs, 15000));
135
- const run = await executeDevelopmentCommand({ command: "runtime", timeoutMs, label: "Accessibility audit" }, [fileURLToPath(new URL("./browser-audit/worker.mjs", import.meta.url)), request], root, {}, signal);
136
- if (run.code !== 0) throw new Error(`Accessibility audit browser failed (${run.code}): ${run.output.slice(-3000)}`);
137
- if (!existsSync(report) || realpathSync(report) !== report || lstatSync(report).size > limits.reportBytes) throw new Error("Accessibility audit produced no bounded report.");
138
- const value = JSON.parse(readFileSync(report, "utf8"));
139
- if (value.schemaVersion !== 1 || value.runId !== runId || !Array.isArray(value.runs) || value.runs.length !== apps.length) throw new Error("Accessibility audit returned the wrong run identity or render count.");
140
- return { ...summary, runs: value.runs.length, incomplete: value.runs.reduce((sum, item) => sum + item.incomplete, 0), findings: auditFindings(value.runs, scenarios), elapsedMs: Date.now() - startedAt };
319
+ const floating = floatingScenarios(options, scenarios);
320
+ const wanted = themes.flatMap(theme => (brands.length ? brands : [undefined]).flatMap(brand => scenarios.map(scenario => ({ scenario: scenario.id, theme: theme.name, ...(brand ? { brand: brand.name } : {}), scheme: theme.scheme, ...(theme === themes[0] && containerKinds.includes(scenario.kind) && !floating.has(scenario.id) ? { container: containerWidth } : {}) }))));
321
+ const renders = new Map(wanted.map(app => [renderKey(app), { app, attempts: 0, causes: [] }]));
322
+ onProgress?.({ stage: "browser-audit", message: `Accessibility audit: ${wanted.length} renders (${scenarios.length} scenarios × ${themes.length} themes${brands.length ? ` × ${brands.length} brands` : ""}).`, elapsedMs: Date.now() - startedAt });
323
+ for (let attempt = 1; attempt <= auditAttempts; attempt++) {
324
+ const pending = [...renders.values()].filter(render => !render.result);
325
+ if (!pending.length) break;
326
+ signal.throwIfAborted();
327
+ for (const render of pending) render.attempts = attempt;
328
+ if (!host) {
329
+ try { host = await startHost(); }
330
+ catch (error) { if (signal.aborted) throw error; for (const render of pending) render.causes.push(clipCause(error.message)); continue; }
331
+ }
332
+ const unbuilt = await warmScenariosApart(host, [...new Set(pending.map(render => render.app.scenario))], signal);
333
+ for (const render of pending) if (unbuilt.has(render.app.scenario)) render.causes.push(unbuilt.get(render.app.scenario));
334
+ const apps = pending.filter(render => !unbuilt.has(render.app.scenario)).map(({ app }) => {
335
+ const url = new URL(host.url); url.searchParams.set("scenario", app.scenario); url.searchParams.set("capture", "1"); url.searchParams.set("theme", app.theme);
336
+ if (app.brand) url.searchParams.set("brand", app.brand);
337
+ return { ...app, url: url.href };
338
+ });
339
+ const reached = apps.length ? await runAuditWorker({ root, temporary, playwright, settings, apps, signal }) : { runs: [] };
340
+ for (const run of reached.runs) {
341
+ const render = renders.get(renderKey(run));
342
+ if (!render) continue;
343
+ if (run.failed) { render.causes.push(run.cause); if (run.violations) render.partial = run; }
344
+ else render.result = run;
345
+ }
346
+ for (const { app } of pending.filter(render => !render.result && apps.some(app => renderKey(app) === renderKey(render.app)) && !reached.runs.some(run => renderKey(run) === renderKey(render.app)))) renders.get(renderKey(app)).causes.push(reached.cause ?? "The audit browser stopped before this render.");
347
+ // The next attempt gets a new browser and, when this audit owns it, a new preview host.
348
+ if (attempt < auditAttempts && host !== previewHost && [...renders.values()].some(render => !render.result)) {
349
+ const previous = host; host = undefined;
350
+ await previous.close().catch(() => {});
351
+ }
352
+ }
353
+ const all = [...renders.values()], runs = all.map(render => render.result ?? render.partial).filter(Boolean);
354
+ const retries = all.filter(render => render.result && render.attempts > 1).map(({ app, attempts, causes }) => ({ scenario: app.scenario, theme: app.theme, ...(app.brand ? { brand: app.brand } : {}), attempts, causes }));
355
+ const findings = [...auditFindings(runs, scenarios), ...nonTextContrastFindings(runs, scenarios), ...layoutOverflowFindings(runs, scenarios), ...layoutShiftFindings(runs, scenarios), ...unauditedFindings(all.filter(render => !render.result), scenarios), ...incompleteFindings(runs, scenarios)];
356
+ const shifts = runs.filter(run => run.layoutShift).sort((a, b) => b.layoutShift.value - a.layoutShift.value);
357
+ return { ...summary, ...(shifts.length ? { worstLayoutShift: { value: shifts[0].layoutShift.value, scenario: shifts[0].scenario } } : {}), runs: all.filter(render => render.result).length, incomplete: findings.filter(finding => finding.rule === INCOMPLETE_RULE).length, findings, ...(retries.length ? { retries } : {}), elapsedMs: Date.now() - startedAt };
141
358
  } finally {
142
359
  try { if (host !== previewHost) await host?.close(); } finally { rmSync(temporary, { recursive: true, force: true }); }
143
360
  }
@@ -1,6 +1,7 @@
1
1
  import { readFileSync, writeFileSync } from "node:fs";
2
2
  import { createRequire } from "node:module";
3
3
  import path from "node:path";
4
+ import { firstRender } from "../browser-audit/first-render.mjs";
4
5
  import { openPreviewScenario } from "../verification/browser.mjs";
5
6
 
6
7
  // Runs only as an owned child, using the receiving project's browser dependency.
@@ -18,11 +19,7 @@ try {
18
19
  await frame.locator("html").waitFor({ state: "visible", timeout });
19
20
  await frame.waitForFunction(theme => document.documentElement.dataset.theme === theme, app.theme, { timeout });
20
21
  if (app.brand) await frame.waitForFunction(brand => document.documentElement.dataset.brand === brand, app.brand, { timeout });
21
- await frame.evaluate(async () => {
22
- await document.fonts.ready;
23
- await Promise.all([...document.images].map(image => image.decode().catch(() => {})));
24
- await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
25
- });
22
+ await frame.evaluate(firstRender);
26
23
  const actualViewport = await frame.evaluate(() => ({ width: innerWidth, height: innerHeight }));
27
24
  if (actualViewport.width !== app.viewport.width || actualViewport.height !== app.viewport.height) throw new Error(`App viewport differs from requested capture settings: ${JSON.stringify(actualViewport)}`);
28
25
  const target = frame.locator(app.selector);
package/dist/check.mjs CHANGED
@@ -39,6 +39,9 @@ import { inspectTestBoundaries } from "./test-boundaries.mjs";
39
39
  import { inspectBehaviorLibraries } from "./behavior-libraries.mjs";
40
40
  import { inspectUsage } from "./usage.mjs";
41
41
  import { controlPaddingAdvisories } from "./control-padding.mjs";
42
+ import { createComponentContrast } from "./component-contrast.mjs";
43
+ import { createLayoutWidths, globMatcher } from "./layout-widths.mjs";
44
+ import { imageAttributeFindings } from "./image-attributes.mjs";
42
45
  import { findingSeverity, routeFindings } from "./finding-rules.mjs";
43
46
 
44
47
  const scenarioLayoutGuidance = "Put demo-only sizing and framing in the development-only review/ layer, imported through the separate review entry. Patterns are production UI. Keep required behavior in the runtime owner; add component props for deliberate product API needs.";
@@ -105,6 +108,11 @@ export function checkProject(directory, { trackingRoot } = {}) {
105
108
  // The foundation remains a fixed import-only entry, not an extra styling layer.
106
109
  const foundationEntry = path.join(dsRoot, config.stylesEntry);
107
110
  const registeredProperties=new Map(), controlPaddingSeen=new Set();
111
+ const componentContrast = createComponentContrast(tokenInventory.tokens, config.themes, config.brands);
112
+ const layoutWidths = createLayoutWidths(tokenInventory.tokens, config), fixedWidthOwner = globMatcher(config.layout.fixedWidthUnits);
113
+ for (const glob of config.layout.widthTokens) if (!tokenInventory.tokens.some(token => globMatcher([glob])(token.name))) diagnostics.push({ rule: "layout-config", file: "ds.config.json", line: 1, column: 1, message: `layout.widthTokens entry ${glob} matches no declared token. Remove it or declare the token.` });
114
+ for (const glob of config.layout.fixedWidthUnits) if (!units.units.some(unit => globMatcher([glob])(unit.id) || unit.files.some(file => globMatcher([glob])(file)))) diagnostics.push({ rule: "layout-config", file: "ds.config.json", line: 1, column: 1, message: `layout.fixedWidthUnits entry ${glob} matches no unit or owned file. Remove it or correct the path.` });
115
+ const ownerFixedWidths = [];
108
116
  function checkRegistrations(file,css,offset={line:1}){
109
117
  css.walkAtRules(/^property$/i,rule=>{
110
118
  const line=offset.line+(rule.source?.start.line??1)-1;
@@ -141,6 +149,13 @@ export function checkProject(directory, { trackingRoot } = {}) {
141
149
  layers.collectComponentStyles(file, css);
142
150
  layerStyles.push({ file, css, offset });
143
151
  checkRegistrations(file,css,offset);
152
+ if (!foundation && !isDevelopmentFile(file, options) && ["components", "patterns"].some(layer => isInside(path.join(dsRoot, layer), file))) componentContrast.collect(path.relative(root, file).replaceAll("\\", "/"), css, offset);
153
+ if (!foundation && (isInside(path.join(dsRoot, "composition"), file) || !isDevelopmentFile(file, options) && ["components", "patterns"].some(layer => isInside(path.join(dsRoot, layer), file)))) {
154
+ const relative = path.relative(root, file).replaceAll("\\", "/"), owner = units.owner(units.relative(path.relative(root, file)));
155
+ const widths = layoutWidths.inspect(css, relative, offset);
156
+ if (!fixedWidthOwner(relative) && !(owner && fixedWidthOwner(owner))) advisories.push(...widths);
157
+ else ownerFixedWidths.push(...widths.filter(finding => finding.rule === "layout-fixed-width"));
158
+ }
144
159
  // Linaria templates are checked once per resolved interpolation variant.
145
160
  if (!foundation) for (const finding of controlPaddingAdvisories(css, { tokens: declaredTokens, file: path.relative(root, file).replaceAll("\\", "/"), offset })) {
146
161
  const key = JSON.stringify([finding.file, finding.line, finding.column, finding.message]);
@@ -368,7 +383,7 @@ export function checkProject(directory, { trackingRoot } = {}) {
368
383
  }
369
384
  inspectDesignAliases(layerStyles,options,report);
370
385
  for (const { file, css, offset } of layerStyles) layers.inspectStyles(file, css, offset);
371
- advisories.push(...(tokenInventory.advisories??[]), ...assetAdvisories, ...a11ySourceAdvisories(options));
386
+ advisories.push(...(tokenInventory.advisories??[]), ...assetAdvisories, ...a11ySourceAdvisories(options), ...imageAttributeFindings(options), ...componentContrast.findings(), ...layoutWidths.declaredWidths(ownerFixedWidths));
372
387
  // Errors block by class; bounded clients see review items before informational limits.
373
388
  const routed=routeFindings(diagnostics,advisories);
374
389
  const uniqueDiagnostics=[...new Map(routed.diagnostics.map(diagnostic=>[JSON.stringify([diagnostic.file,diagnostic.rule,diagnostic.line,diagnostic.column,diagnostic.message]),diagnostic])).values()];
package/dist/cli.mjs CHANGED
@@ -18,9 +18,11 @@ Usage: ads create <directory> --framework react|preact New design-system proje
18
18
  compile [directory] Build ADS previews with Bun (--watch for incremental previews)
19
19
  validate [dir] Audit ADS gates and the chosen project policy
20
20
  --policy acceptance|validation (default validation)
21
+ both run the browser audit unless its browserAudit is false
21
22
  behaviors [dir] Inspect behavior contracts and current verification evidence
22
23
  verify [directory] Run registered behavior checks (--unit and --check select)
23
- audit [directory] Run axe-core in each rendered scenario, once per brand and theme
24
+ audit [directory] Run axe-core, non-text contrast, layout shift and overflow checks in each rendered
25
+ scenario, once per brand and theme
24
26
  (--scenario, --theme and --brand select; findings are errors)
25
27
  tokens [directory] Inspect local token values and theme definitions
26
28
  --format dtcg prints them as W3C Design Tokens JSON;
@@ -179,21 +181,23 @@ async function main(args) {
179
181
  }
180
182
  else if (command === "tokens" && format === "dtcg") { const { exportTokensDtcg } = await import("./token-export.mjs"); console.log(JSON.stringify(exportTokensDtcg(target, { theme, brand }), null, 2)); return; }
181
183
  else if (command === "tokens") result = inspectTokens(target);
182
- else if (command === "assets") { const { refreshThemesCss } = await import("./themes-watch.mjs"); const themes = refreshThemesCss(target); result = { ...await generateBrandAssets(target), themes: { file: themes.file, written: themes.files[0]?.written ?? false, ...(themes.skipped ? { skipped: themes.skipped } : {}) }, ...(themes.files[1] ? { palette: { file: themes.files[1].file, written: themes.files[1].written } } : {}) }; }
184
+ else if (command === "assets") { const { refreshThemesCss } = await import("./themes-watch.mjs"); const themes = refreshThemesCss(target); result = { ...await generateBrandAssets(target), themes: { file: themes.file, written: themes.files[0]?.written ?? false, ...(themes.skipped ? { skipped: themes.skipped } : {}) }, ...(themes.files[1] ? { palette: { file: themes.files[1].file, written: themes.files[1].written }, ...(themes.files[2] ? { fontPreloads: { file: themes.files[2].file, written: themes.files[2].written } } : {}) } : {}) }; }
183
185
  else if (command === "lint-config") result = generateLintConfig(target);
184
186
  else throw new Error(`Unknown command: ${command}. Run ads --help.`);
185
- if (json) console.log(JSON.stringify(result, null, 2));
186
- else if (command === "create") console.log(`Created ${result.name} in ${target}\nFramework: ${result.framework}\nNext: cd ${((folder) => /[\s'"$`\\]/.test(folder) ? JSON.stringify(folder) : folder)(path.relative(process.cwd(), target) || ".")} && ${result.packageManager} install && ${result.packageManager} run build && ${result.packageManager} run dev:showcase`);
187
+ // Bun ends a piped stdout at its buffer unless the write is awaited.
188
+ if (json) await new Promise(resolve => process.stdout.write(`${JSON.stringify(result, null, 2)}\n`, resolve));
189
+ else if (command === "create") console.log(`Created ${result.name} in ${target}\nFramework: ${result.framework}\nNext: cd ${((folder) => /[\s'"$`\\]/.test(folder) ? JSON.stringify(folder) : folder)(path.relative(process.cwd(), target) || ".")} && ${result.packageManager} install && ${result.packageManager === "bun" ? "bunx" : "npx"} playwright install chromium && ${result.packageManager} run build && ${result.packageManager} run dev:showcase`);
187
190
  else if (command === "init") console.log(`Initialized ${target}\nFramework: ${result.framework}\nAdded ${result.toolDependency.name} (${result.toolDependency.spec}) as a development dependency.\nRun ${result.packageManager} install and ${result.packageManager} run build; the build runs ADS checks and generates configured brand assets automatically.`);
188
191
  else if (command === "assets") {
189
192
  console.log(result.skipped ? "No assets.iconSource configured; brand generation skipped." : `Generated ${result.files.length} brand assets in ${result.directory}.`);
190
193
  const themesFile = path.relative(process.cwd(), result.themes.file) || result.themes.file;
191
194
  console.log(result.themes.skipped ? `Skipped ${themesFile}: the token sheets still use the old theme form.` : `${result.themes.written ? "Wrote" : "Unchanged"} ${themesFile}.`);
192
195
  if (result.palette) console.log(`${result.palette.written ? "Wrote" : "Unchanged"} ${path.relative(process.cwd(), result.palette.file) || result.palette.file}.`);
196
+ if (result.fontPreloads) console.log(`${result.fontPreloads.written ? "Wrote" : "Unchanged"} ${path.relative(process.cwd(), result.fontPreloads.file) || result.fontPreloads.file}.`);
193
197
  }
194
198
  else if (command === "lint-config") console.log(`Generated ${result.file}\nUse this optional configuration only in the project linter you choose to run.`);
195
199
  else if (command === "behaviors") console.log(JSON.stringify(result, null, 2));
196
- else if (command === "audit") { const { findingCounts } = await import("./finding-rules.mjs"); console.log(`ADS accessibility audit (${result.engine}): ${findingCounts(result.diagnostics.length, result.findings.length)} across ${result.scenarios} scenarios × ${result.themes.length} themes (${result.themes.join(", ")})${result.brands ? ` × ${result.brands.length} brands (${result.brands.join(", ")})` : ""}.`); for (const finding of result.findings) console.error(`${finding.file}:${finding.line}:${finding.column} [${finding.severity}:${finding.rule}] ${finding.message}`); }
200
+ else if (command === "audit") { const { findingCounts } = await import("./finding-rules.mjs"); console.log(`ADS accessibility audit (${result.engine}): ${findingCounts(result.diagnostics.length, result.findings.filter(finding => finding.severity === "review").length)}, ${result.incomplete ?? 0} that axe could not decide across ${result.scenarios} scenarios × ${result.themes.length} themes (${result.themes.join(", ")})${result.brands ? ` × ${result.brands.length} brands (${result.brands.join(", ")})` : ""}.`); if (result.retries) console.log(`Retried ${result.retries.length} render${result.retries.length === 1 ? "" : "s"} that then passed: ${result.retries.map(retry => `${retry.scenario} [${[retry.theme, retry.brand].filter(Boolean).join(", ")}] in ${retry.attempts} attempts`).join("; ")}.`); for (const finding of result.findings) console.error(`${finding.file}:${finding.line}:${finding.column} [${finding.severity}:${finding.rule}] ${finding.message}`); }
197
201
  else if (command === "verify") { for (const item of result.results) console.log(`${item.unit}#${item.check}: ${item.status} (${item.profile})`); }
198
202
  else if (command === "validate") {console.log(`ADS ${result.policy} ${result.ok?"passed":"failed"}: ${result.scope}${result.fallback?` (${result.fallback})`:""}`);for(const check of result.checks)console.log(`${check.name}: ${check.skipped?"skipped":check.passed?"passed":"failed"}${check.reason?` (${check.reason})`:""}`);}
199
203
  else if (command === "tokens") {
@@ -0,0 +1,138 @@
1
+ import valueParser from "postcss-value-parser";
2
+ import { contrastContexts, contrastPairs, contrastRatio } from "./token-quality.mjs";
3
+ import { findingSeverity } from "./finding-rules.mjs";
4
+
5
+ /** Text contrast of the color and background a component or pattern style block pairs itself.
6
+ * token-contrast checks the role pairs the token contract names; components can pair any two
7
+ * tokens, such as a status color as text on its own tint. Where one block (the template's top
8
+ * level, a nested selector such as &:hover or &[aria-selected="true"], or an at-rule) declares
9
+ * both `color: var(--a)` and `background(-color): var(--b)`, the pair needs 4.5:1 (WCAG 1.4.3)
10
+ * in every theme and brand, resolved and composited as token-contrast resolves them. Local
11
+ * custom properties declared in the block or an enclosing block resolve one level, and an
12
+ * undeclared one reads its var() fallback, the default it renders with. Disabled states are
13
+ * exempt (WCAG exempts inactive components). A block that sets one token on both sides, or that
14
+ * styles a <progress>, <meter> or range through its pseudo-elements, paints no text with them.
15
+ * Keywords (currentColor, inherit, transparent) and fully transparent backgrounds paint the
16
+ * surroundings, so the pair is skipped. A side that names no declared color token is a
17
+ * component-contrast-unresolved info item; so is text matching the canvas (under 1.25:1) over a
18
+ * translucent background, which says the block sits on another backdrop (media, an inverted surface). Pairs
19
+ * token-contrast already checks are not repeated. */
20
+
21
+ const guidance = "ads://guides/accessibility";
22
+ const disabled = /:disabled\b|\[\s*(?:aria-disabled\s*=\s*["']?true["']?|disabled|data-disabled)[^\]]*\]/i;
23
+ const nativeParts = /::-(?:webkit|moz|ms)-(?:progress|meter|slider|range)/i;
24
+ const keyword = /^(?:currentcolor|inherit|initial|unset|revert(?:-layer)?|transparent|none)$/i;
25
+
26
+ /** The variable a value reads when it is exactly var(--name[, fallback]); a keyword; or null. */
27
+ function single(value) {
28
+ const nodes = valueParser(value.trim()).nodes.filter(node => node.type !== "space" && node.type !== "comment");
29
+ if (nodes.length !== 1) return null;
30
+ const [node] = nodes;
31
+ if (node.type === "word" && keyword.test(node.value)) return { keyword: node.value };
32
+ if (node.type !== "function" || node.value.toLowerCase() !== "var") return null;
33
+ const name = node.nodes.find(child => child.type === "word")?.value;
34
+ if (!name?.startsWith("--")) return null;
35
+ const comma = node.nodes.findIndex(child => child.type === "div" && child.value === ",");
36
+ return { name, ...(comma < 0 ? {} : { fallback: valueParser.stringify(node.nodes.slice(comma + 1)) }) };
37
+ }
38
+
39
+ /** Declarations directly in a container, the last per property winning. */
40
+ function own(container) {
41
+ const values = new Map();
42
+ for (const node of container.nodes ?? []) if (node.type === "decl") values.set(node.prop.toLowerCase(), node);
43
+ return values;
44
+ }
45
+
46
+ function selectorChain(container) {
47
+ const parts = [];
48
+ for (let node = container; node && node.type !== "root"; node = node.parent) parts.unshift(node.type === "rule" ? node.selector : `@${node.name} ${node.params}`);
49
+ return parts;
50
+ }
51
+
52
+ /** A role-contract suggestion for a pair: --x-text on --x-bg, --x-fg on --x. */
53
+ function suggestion(background, names) {
54
+ const tint = background.match(/^--(.+)-bg$/);
55
+ if (tint && names.has(`--${tint[1]}-text`)) return `Pair the role contract instead: --${tint[1]}-text on ${background}.`;
56
+ if (names.has(`${background}-fg`)) return `Pair the role contract instead: ${background}-fg on ${background}.`;
57
+ return "Pair role tokens the contract defines together: --x-text on --x-bg, --x-fg on --x.";
58
+ }
59
+
60
+ export function createComponentContrast(tokens, themes, brands) {
61
+ const names = new Set(tokens.map(token => token.name));
62
+ const checked = new Set(contrastPairs(names).filter(([, , minimum]) => minimum === 4.5).map(([foreground, background]) => `${foreground} ${background}`));
63
+ let contexts;
64
+ const findings = new Map(), unresolved = new Map();
65
+
66
+ /** The token a declaration paints with, following one level of local custom properties. */
67
+ function paint(decl, container) {
68
+ const value = single(decl.value);
69
+ if (!value?.name || names.has(value.name)) return value;
70
+ for (let node = container; node; node = node.parent) {
71
+ const local = own(node).get(value.name);
72
+ if (local) { const target = single(local.value); return target?.name && names.has(target.name) ? target : target?.keyword ? target : { unresolved: value.name }; }
73
+ }
74
+ return value.fallback ? fallbackPaint(value) : { unresolved: value.name };
75
+ }
76
+ function fallbackPaint({ name, fallback }) {
77
+ const value = single(fallback);
78
+ if (value?.keyword || value?.name && names.has(value.name)) return value;
79
+ return value?.fallback ? fallbackPaint(value) : { unresolved: name };
80
+ }
81
+
82
+ function block(container, file, offset) {
83
+ const declarations = own(container), text = declarations.get("color");
84
+ const fill = [declarations.get("background-color"), declarations.get("background")].filter(Boolean).sort((a, b) => b.source.start.offset - a.source.start.offset)[0];
85
+ if (!text || !fill) return;
86
+ // :not(:disabled) is the enabled state; only a positive disabled condition is exempt.
87
+ if (selectorChain(container).some(part => disabled.test(part.replace(/:not\((?:[^()]|\([^()]*\))*\)/g, "")))) return;
88
+ const front = paint(text, container), back = paint(fill, container);
89
+ if (!front || !back || front.keyword || back.keyword || front.name && front.name === back.name) return;
90
+ if (container.nodes?.some(node => node.type === "rule" && nativeParts.test(node.selector))) return;
91
+ const line = offset.line + text.source.start.line - 1, column = text.source.start.column + (text.source.start.line === 1 ? offset.column - 1 : 0);
92
+ if (front.unresolved || back.unresolved) {
93
+ const key = JSON.stringify([file, line]);
94
+ if (!unresolved.has(key)) unresolved.set(key, { rule: "component-contrast-unresolved", severity: findingSeverity("component-contrast-unresolved"), file, line, column, guidanceUri: guidance,
95
+ message: `${file}:${line} pairs color: ${text.value} with ${fill.prop}: ${fill.value}; ${[front.unresolved, back.unresolved].filter(Boolean).join(" and ")} is not a declared color token here, so ADS cannot check the pair's contrast statically. Check the rendered component with ads audit.` });
96
+ return;
97
+ }
98
+ const [foreground, background] = [front.name, back.name];
99
+ if (checked.has(`${foreground} ${background}`)) return;
100
+ contexts ??= contrastContexts(tokens, themes, brands);
101
+ const failing = [];
102
+ for (const context of contexts) {
103
+ if (!context.changed(foreground) && !context.changed(background)) continue;
104
+ const a = context.color(foreground), b = context.color(background);
105
+ if (!a?.color || !b?.color) {
106
+ const key = JSON.stringify([file, line]);
107
+ if (!unresolved.has(key)) unresolved.set(key, { rule: "component-contrast-unresolved", severity: findingSeverity("component-contrast-unresolved"), file, line, column, tokens: [foreground, background], guidanceUri: guidance,
108
+ message: `${file}:${line} pairs ${foreground} on ${background}, but ${!a?.color ? foreground : background} does not resolve to a color statically in ${context.label}, so the pair's contrast is not checked. Check the rendered component with ads audit.` });
109
+ continue;
110
+ }
111
+ if (b.color[3] === 0) continue;
112
+ if (b.color[3] < 1 && contrastRatio(a.color, context.canvas) < 1.25) {
113
+ const key = JSON.stringify([file, line]);
114
+ if (!unresolved.has(key)) unresolved.set(key, { rule: "component-contrast-unresolved", severity: findingSeverity("component-contrast-unresolved"), file, line, column, tokens: [foreground, background], guidanceUri: guidance,
115
+ message: `${file}:${line} pairs ${foreground} on the translucent ${background}, and ${foreground} matches the canvas in ${context.label}, so the block sits on another backdrop and the pair's contrast is not checked. Check the rendered component with ads audit.` });
116
+ continue;
117
+ }
118
+ const ratio = contrastRatio(a.color, context.opaque(b, background));
119
+ if (ratio + 1e-9 < 4.5) failing.push({ ratio, label: context.label, theme: context.context.theme.name, ...(context.context.brand === undefined ? {} : { brand: context.context.brand }) });
120
+ }
121
+ if (!failing.length) return;
122
+ const key = JSON.stringify([file, line, foreground, background]);
123
+ if (findings.has(key)) return;
124
+ const worst = Math.min(...failing.map(item => item.ratio));
125
+ findings.set(key, { rule: "component-contrast", severity: findingSeverity("component-contrast"), file, line, column, tokens: [foreground, background], ratio: Number(worst.toFixed(2)),
126
+ contexts: failing.map(({ theme, brand, ratio }) => ({ theme, ...(brand === undefined ? {} : { brand }), ratio: Number(ratio.toFixed(2)) })), selector: selectorChain(container).join(" ") || "&", guidanceUri: guidance,
127
+ message: `${file}:${line} sets color: var(${foreground}) on ${fill.prop}: var(${background}), ${failing.map(item => `${item.ratio.toFixed(2)}:1 in ${item.label}`).join(", ")}; text needs 4.5:1 (WCAG 1.4.3). ${suggestion(background, names)}` });
128
+ }
129
+
130
+ return {
131
+ /** Check one parsed component or pattern style sheet or Linaria template. */
132
+ collect(file, css, offset = { line: 1, column: 1 }) {
133
+ block(css, file, offset);
134
+ css.walk(node => { if (node.type === "rule" || node.type === "atrule" && node.nodes) block(node, file, offset); });
135
+ },
136
+ findings: () => [...findings.values(), ...unresolved.values()],
137
+ };
138
+ }