@reqvire-org/ads 0.3.49 → 0.3.50
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 +36 -6
- package/dist/active-clock.mjs +34 -0
- package/dist/assets.mjs +20 -2
- package/dist/boundaries.mjs +2 -0
- package/dist/browser-audit/layout-overflow.mjs +57 -0
- package/dist/browser-audit/layout-shift.mjs +32 -0
- package/dist/browser-audit/non-text-contrast.mjs +87 -0
- package/dist/browser-audit/worker.mjs +36 -7
- package/dist/browser-audit.mjs +198 -22
- package/dist/check.mjs +14 -1
- package/dist/cli.mjs +7 -4
- package/dist/component-contrast.mjs +138 -0
- package/dist/config.mjs +12 -6
- package/dist/finding-rules.mjs +11 -1
- package/dist/fonts-generated.mjs +85 -0
- package/dist/image-attributes.mjs +110 -0
- package/dist/init.mjs +2 -0
- package/dist/layout-widths.mjs +184 -0
- package/dist/mcp/context.mjs +1 -1
- package/dist/mcp/mutations.mjs +7 -5
- package/dist/mcp/preview-watch.mjs +9 -8
- package/dist/mcp/server.mjs +6 -4
- package/dist/preview-files.mjs +3 -0
- package/dist/project-boundary.mjs +23 -0
- package/dist/project-documents.mjs +2 -1
- package/dist/scenarios-compiler.mjs +23 -3
- package/dist/showcase/client.bundle.js +11 -11
- package/dist/showcase/icons.js +5 -5
- package/dist/showcase/style.css +1 -1
- package/dist/skills/ads-break-ui/SKILL.md +8 -0
- package/dist/skills/ads-break-ui/references/atomic-styles.md +2 -0
- package/dist/skills/ads-break-ui/references/design-data.md +39 -0
- package/dist/skills/ads-break-ui/references/drafts.md +1 -1
- package/dist/skills/ads-break-ui/references/guarded-editing.md +1 -1
- package/dist/skills/ads-break-ui/references/validation.md +9 -5
- package/dist/skills/ads-designer/SKILL.md +24 -4
- package/dist/skills/ads-designer/references/accessibility.md +30 -13
- package/dist/skills/ads-designer/references/atomic-styles.md +2 -0
- package/dist/skills/ads-designer/references/branding.md +10 -5
- package/dist/skills/ads-designer/references/cli.md +2 -1
- package/dist/skills/ads-designer/references/design-data.md +39 -0
- package/dist/skills/ads-designer/references/drafts.md +1 -1
- package/dist/skills/ads-designer/references/guarded-editing.md +1 -1
- package/dist/skills/ads-designer/references/mobile.md +3 -0
- package/dist/skills/ads-designer/references/performance.md +89 -0
- package/dist/skills/ads-designer/references/validation.md +9 -5
- package/dist/skills/ads-import/references/atomic-styles.md +2 -0
- package/dist/skills/ads-import/references/cli.md +2 -1
- package/dist/skills/ads-import/references/design-data.md +39 -0
- package/dist/skills/ads-import/references/drafts.md +1 -1
- package/dist/skills/ads-import/references/guarded-editing.md +1 -1
- package/dist/skills/ads-import/references/validation.md +9 -5
- package/dist/skills/ads-motion/references/atomic-styles.md +2 -0
- package/dist/skills/ads-motion/references/design-data.md +39 -0
- package/dist/skills/ads-motion/references/drafts.md +1 -1
- package/dist/skills/ads-motion/references/guarded-editing.md +1 -1
- package/dist/skills/ads-motion/references/validation.md +9 -5
- package/dist/skills/ads-port/references/atomic-styles.md +2 -0
- package/dist/skills/ads-port/references/cli.md +2 -1
- package/dist/skills/ads-port/references/design-data.md +39 -0
- package/dist/skills/ads-port/references/drafts.md +1 -1
- package/dist/skills/ads-port/references/guarded-editing.md +1 -1
- package/dist/skills/ads-port/references/validation.md +9 -5
- package/dist/starters/preact/ds.config.json +1 -0
- package/dist/starters/preact/package.json +1 -0
- package/dist/starters/react/ADS.md +1 -1
- package/dist/starters/react/README.md +14 -2
- package/dist/starters/react/design-system/components/Actions/Button/Button.tsx +1 -1
- package/dist/starters/react/design-system/components/Content/Image/Image.ads.fixture.ts +2 -0
- package/dist/starters/react/design-system/components/Content/Image/Image.ads.scenario.tsx +13 -0
- package/dist/starters/react/design-system/components/Content/Image/Image.tsx +48 -0
- package/dist/starters/react/design-system/components/Content/Image/README.md +20 -0
- package/dist/starters/react/design-system/components/Content/Logo/Logo.tsx +2 -2
- package/dist/starters/react/design-system/index.ts +1 -0
- package/dist/starters/react/design-system/tokens/Layout.ads.fixture.ts +16 -0
- package/dist/starters/react/design-system/tokens/spacing.css +18 -0
- package/dist/starters/react/ds.config.json +1 -0
- package/dist/starters/react/package-lock.json +47 -0
- package/dist/starters/react/package.json +2 -1
- package/dist/test-boundaries.mjs +30 -1
- package/dist/themes-generated.mjs +15 -4
- package/dist/token-quality.mjs +27 -17
- package/dist/units.mjs +2 -1
- package/dist/validation-checks.mjs +5 -4
- package/dist/validation.mjs +1 -1
- package/dist/verification/browser.mjs +28 -2
- package/dist/verification.mjs +5 -4
- package/docs/ADS.md +4 -1
- package/docs/ARCHITECTURE.md +13 -3
- package/docs/CHANGELOG.md +92 -12
- package/docs/GUIDE.md +208 -14
- package/docs/MCP.md +14 -10
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -9,6 +9,9 @@ inside your project.
|
|
|
9
9
|
behavior, tokens and styles across both.
|
|
10
10
|
- **Real UI. Guarded changes.** Humans and agents review the actual implementation;
|
|
11
11
|
agent patches pass architecture and configured project checks before they land.
|
|
12
|
+
- **Accessibility as a gate, checked in the browser.** Contrast, labels, focus and
|
|
13
|
+
target size are errors, not advice. `ads audit` runs axe-core in every UI scenario,
|
|
14
|
+
theme and brand, and blocks validation and acceptance by default.
|
|
12
15
|
- **Colocated code, clearer ownership.** Related implementation, styles, scenarios
|
|
13
16
|
and checks stay near their owner, reducing the search for change context.
|
|
14
17
|
- **Compiled styles, efficient delivery.** Linaria extracts CSS ahead of time.
|
|
@@ -35,7 +38,7 @@ uses Preact. See [implementation support](docs/GUIDE.md#implementation-support).
|
|
|
35
38
|
- **Preview** real UI through MCP Apps and the local showcase, using the same
|
|
36
39
|
project-owned scenarios and fixtures.
|
|
37
40
|
- **Edit directly or through MCP**: use your editor with MCP preview/checks, or
|
|
38
|
-
choose MCP-only tracked proposals and acceptance. See [editing
|
|
41
|
+
choose MCP-only tracked proposals and acceptance. See [editing access](docs/MCP.md#editing-access-and-compiler-ownership).
|
|
39
42
|
- **Edit with guards** using owner patches, coupled transactions and isolated
|
|
40
43
|
dry runs that validate architecture, lint and registered project checks.
|
|
41
44
|
- **Compare visual changes** with on-demand screenshots of current source and
|
|
@@ -44,7 +47,7 @@ uses Preact. See [implementation support](docs/GUIDE.md#implementation-support).
|
|
|
44
47
|
edit. Commit proposals for PR review, compare Accepted/Draft in Explorer, and
|
|
45
48
|
let the agent accept an exact reviewed revision after required checks pass.
|
|
46
49
|
- **Bound command memory** with project process-tree budgets and reported kernel
|
|
47
|
-
or watchdog enforcement. See [
|
|
50
|
+
or watchdog enforcement. See [command memory budgets](docs/MCP.md#command-memory-budgets-ads-0338).
|
|
48
51
|
- **Verify behavior** through project-owned guarantees and registered tests,
|
|
49
52
|
with progress, timings and evidence tied to current source.
|
|
50
53
|
- **Keep contracts explicit** for typed paint inputs, scoped data bindings and
|
|
@@ -58,12 +61,35 @@ See [using ADS through MCP](docs/GUIDE.md#use-ads-through-mcp) for the workflow
|
|
|
58
61
|
[visual captures](docs/MCP.md#screenshots-and-candidate-comparison) for screenshot
|
|
59
62
|
setup and comparison.
|
|
60
63
|
|
|
61
|
-
For iterative work, use
|
|
64
|
+
For iterative work, use [auto-mode tracked drafts](docs/MCP.md#auto-mode-tracked-drafts).
|
|
62
65
|
Drafts can cover token groups, components, patterns and complete views. Pattern
|
|
63
66
|
and composition previews can use dependency drafts through normal `@ds` imports;
|
|
64
67
|
accepting a dependency automatically switches dependent drafts to accepted source.
|
|
65
68
|
Drafts survive restart and Git clone, but cannot enter production imports.
|
|
66
69
|
|
|
70
|
+
## Checks and guards
|
|
71
|
+
|
|
72
|
+
Every finding is an **error** (blocks `ads check`, validation and acceptance), a
|
|
73
|
+
**review** item (shown; needs human judgement) or **info** (an analysis limit).
|
|
74
|
+
There is no warning level.
|
|
75
|
+
|
|
76
|
+
| Area | What ADS enforces |
|
|
77
|
+
|---|---|
|
|
78
|
+
| **Rendered accessibility** | `ads audit` runs axe-core (WCAG 2.2 AA rules) in every rendered UI scenario, once per theme and brand, plus ADS's own non-text contrast check (WCAG 1.4.11, which axe does not cover): a field or other control without its own text or icon, whose border is its only boundary, needs that border at 3:1 against the background around it, and an icon-only control needs its icon at 3:1 against its background. The audit gates `ads validate` by default, and MCP draft acceptance and guarded patches audit the candidate's affected scenarios (all of them after configuration, foundation, token or asset changes); `browserAudit: false` in a policy turns it off. It needs the project's Playwright and browser (`npx playwright install chromium`); without them the policy fails and names what to install. |
|
|
79
|
+
| **Static accessibility** | Focus styles, icon-only labels, image alt text, reduced motion, target size, text resize and text spacing are checked from source and tokens, without a browser. |
|
|
80
|
+
| **Contrast** | `token-contrast` checks the role pairs that meet on screen (text on surfaces, fills with their foreground, status text on tints, focus indicators and control borders) in every theme and brand. `component-contrast` checks the pairs components and patterns make themselves: a style block (including a nested state such as `&:hover` or `&[aria-selected="true"]`) that sets both `color` and `background` to tokens, such as a status color as text on its own tint. Both resolve every CSS color syntax, including `oklch()` and `color-mix()`, and composite translucent fills over the canvas. Text needs 4.5:1; focus indicators and control borders need 3:1; disabled states are exempt. |
|
|
81
|
+
| **Layout** | Widths are fluid on the grid. `layout-fixed-width` fails a width, `max-width`, `flex-basis` or grid track fixed above 48 px, whether raw, from a token or by arithmetic on spacing tokens; `%`, `fr`, `ch` measures and declared `layout.widthTokens` pass. `layout-overflow` renders every UI scenario at 390, 768 and 1280 px and fails on horizontal page overflow and clipped content; scrollers and ellipsis are exempt. |
|
|
82
|
+
| **Web performance** | `img-attributes` fails a raw `<img>` without dimensions or a `loading` choice, and a `srcset` with width descriptors and no `sizes`; `asset-image-budget` fails oversized images in `assets/` (SVG 100 KB, WebP and AVIF 300 KB, JPEG 400 KB, PNG and GIF 500 KB, or `assets.imageBudgetKb`); `layout-shift` fails a rendered scenario above 0.1. `ads assets` generates preloads for the fonts the first text uses, on the URLs the stylesheet requests. Page metadata, sitemaps, hosting and Lighthouse stay with the application. |
|
|
83
|
+
| **Themes and brands** | One mechanism: per-theme halves (`--x-light`, `--x-dark`) and brands on `[data-brand]`. `ads assets` generates `themes.generated.css` and `.ts`; missing or conflicting halves, empty themes, stale generated files, `light-dark()` and ancestor theme selectors are errors. |
|
|
84
|
+
| **Tokens** | Ownership, naming, rhythm, missing and scenario references; equal values in different roles are flagged for review. |
|
|
85
|
+
| **Architecture** | Data, UX and Skin ownership, project structure, unit and paint contracts, binding and variable ownership; Linaria atomic composition risks are flagged for review. |
|
|
86
|
+
| **Brand assets and glyphs** | Brand coverage, licenses, READMEs and previews; glyph viewBox, color and alias rules. |
|
|
87
|
+
| **Behavior** | Registered guarantees need current passing execution evidence; `ads verify` runs them against current source. |
|
|
88
|
+
| **Acceptance policy** | `ads validate --policy acceptance` applies the project's acceptance policy (core gates, its configured `acceptance.checks` scripts, affected behavior checks when enabled and the browser audit) to direct edits, the same bar MCP acceptance uses. |
|
|
89
|
+
|
|
90
|
+
See [checks and guards](docs/GUIDE.md#checks-and-guards) for the gates, thresholds and
|
|
91
|
+
how to turn the browser audit off.
|
|
92
|
+
|
|
67
93
|
## Create a new design system
|
|
68
94
|
|
|
69
95
|
`create` copies the starter shipped in this ADS version into a new folder and sets
|
|
@@ -73,12 +99,14 @@ it up, so the project always matches the tool that checks it:
|
|
|
73
99
|
npx @reqvire-org/ads create my-design-system --framework react # or preact
|
|
74
100
|
cd my-design-system
|
|
75
101
|
npm install
|
|
102
|
+
npx playwright install chromium # browser for the accessibility audit
|
|
76
103
|
npm run build
|
|
77
104
|
npm run dev:showcase
|
|
78
105
|
```
|
|
79
106
|
|
|
80
107
|
With Bun: `bunx @reqvire-org/ads create my-design-system --framework preact
|
|
81
|
-
--package-manager bun`, then `bun install
|
|
108
|
+
--package-manager bun`, then `bun install`, `bunx playwright install chromium` and
|
|
109
|
+
`bun --bun run build`. `--name` sets
|
|
82
110
|
the package name (default: the folder name).
|
|
83
111
|
|
|
84
112
|
## Set up an existing project
|
|
@@ -89,6 +117,7 @@ ADS tooling and previews. Your application can continue using Node/npm or Bun.
|
|
|
89
117
|
```sh
|
|
90
118
|
npx @reqvire-org/ads init --framework react
|
|
91
119
|
npm install
|
|
120
|
+
npx playwright install chromium
|
|
92
121
|
npm run build
|
|
93
122
|
```
|
|
94
123
|
|
|
@@ -100,11 +129,12 @@ For a Bun project, Node is unnecessary:
|
|
|
100
129
|
```sh
|
|
101
130
|
bunx @reqvire-org/ads init --framework react
|
|
102
131
|
bun install
|
|
132
|
+
bunx playwright install chromium
|
|
103
133
|
bun --bun run build
|
|
104
134
|
```
|
|
105
135
|
|
|
106
136
|
`--bun` keeps package executables on Bun even when they have a Node shebang.
|
|
107
|
-
`init` detects npm or Bun from your project. It adds ADS
|
|
137
|
+
`init` detects npm or Bun from your project. It adds ADS (and `@playwright/test`, unless Playwright is already a dependency) as development dependencies, sets up an empty local ADS if needed, and adds ADS checks before your
|
|
108
138
|
existing build. The default layout is root `design-system/`, alongside `src/`.
|
|
109
139
|
It keeps your app, token values, scripts, and lockfile. Each build runs native ADS gates for tokens, styles, imports, renderer
|
|
110
140
|
boundaries and asset ownership, then runs `ads assets` (configured brand icons, the
|
|
@@ -278,7 +308,7 @@ Committed native and export icons (`assets.targets`: SVG, PNG, ICO, ICNS) and UI
|
|
|
278
308
|
icon sets (`assets.glyphs`) are generated by `ads assets` and checked for freshness.
|
|
279
309
|
Other products' logos are not brand artwork or glyphs: keep them, in their own
|
|
280
310
|
colors and under their owners' trademark and usage terms, in `assets/logos/` and
|
|
281
|
-
show them as images
|
|
311
|
+
show them as images, never muted, tinted or recolored; ADS generates
|
|
282
312
|
and checks nothing there.
|
|
283
313
|
To generate web icons, add this to `ds.config.json`:
|
|
284
314
|
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** Time limits count time the machine is awake. On Linux performance.now() and the timers in Node
|
|
2
|
+
* and Bun read CLOCK_MONOTONIC, which stops during suspend, so nothing more is needed. Elsewhere a
|
|
3
|
+
* clock may count suspend, so a heartbeat treats a gap longer than jumpMs as suspended time. A sync
|
|
4
|
+
* block that long counts as suspended too, on those platforms only. */
|
|
5
|
+
const realNow = () => performance.now();
|
|
6
|
+
|
|
7
|
+
export function createActiveClock({ now = realNow, countsSuspend = process.platform !== "linux", beatMs = 1000, jumpMs = 30000 } = {}) {
|
|
8
|
+
let last, suspended = 0, heartbeat;
|
|
9
|
+
const tick = () => {
|
|
10
|
+
const time = now();
|
|
11
|
+
if (last !== undefined && time - last > jumpMs) suspended += time - last - beatMs;
|
|
12
|
+
last = time;
|
|
13
|
+
};
|
|
14
|
+
return {
|
|
15
|
+
now() {
|
|
16
|
+
if (!countsSuspend) return now();
|
|
17
|
+
if (!heartbeat) { heartbeat = setInterval(tick, beatMs); heartbeat.unref?.(); }
|
|
18
|
+
tick();
|
|
19
|
+
return now() - suspended;
|
|
20
|
+
},
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const activeClock = createActiveClock();
|
|
25
|
+
export const activeNow = () => activeClock.now();
|
|
26
|
+
|
|
27
|
+
/** setTimeout for a budget: a timer that wakes early after suspend waits for the rest. */
|
|
28
|
+
export function setActiveTimeout(callback, ms, { clock = activeClock, schedule = setTimeout, cancel = clearTimeout } = {}) {
|
|
29
|
+
const end = clock.now() + ms;
|
|
30
|
+
let timer;
|
|
31
|
+
const arm = delay => { timer = schedule(() => { const left = end - clock.now(); if (left > 0) arm(left); else callback(); }, delay); };
|
|
32
|
+
arm(ms);
|
|
33
|
+
return { clear: () => cancel(timer) };
|
|
34
|
+
}
|
package/dist/assets.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { existsSync, lstatSync, readFileSync, readdirSync } from "node:fs";
|
|
2
2
|
import { spawnSync } from "node:child_process";
|
|
3
3
|
import path from "node:path";
|
|
4
|
+
import { hasProjectConfig } from "./project-boundary.mjs";
|
|
4
5
|
import { brandFormats, isInside } from "./config.mjs";
|
|
5
6
|
import { brandFiles, brandSourceDiagnostic, glyphAliases, staleBrandOutputs } from "./brand-assets.mjs";
|
|
6
7
|
import { findingSeverity } from "./finding-rules.mjs";
|
|
@@ -28,7 +29,7 @@ function sourceTexts(directories, skipped) {
|
|
|
28
29
|
if (!stat || stat.isSymbolicLink() || !stat.isDirectory() || skipped.some(skip => directory === skip || isInside(skip, directory))) return;
|
|
29
30
|
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
|
30
31
|
const file = path.join(directory, entry.name);
|
|
31
|
-
if (entry.isDirectory()) { if (!["node_modules", ".git"].includes(entry.name)) visit(file); }
|
|
32
|
+
if (entry.isDirectory()) { if (!["node_modules", ".git"].includes(entry.name) && !hasProjectConfig(file)) visit(file); }
|
|
32
33
|
else if (entry.isFile() && sourceExtensions.test(entry.name)) texts.push({ file, text: readFileSync(file, "utf8") });
|
|
33
34
|
}
|
|
34
35
|
};
|
|
@@ -64,6 +65,23 @@ export function inspectGlyphs({ root, dsRoot, config }) {
|
|
|
64
65
|
return findings;
|
|
65
66
|
}
|
|
66
67
|
|
|
68
|
+
/** Image limits in KB. WebP or AVIF holds a full-width 1920 px photo in 300; JPEG needs about 400;
|
|
69
|
+
* PNG and GIF are for flat art and icons, where a 1024 px master fits in 500; an SVG over 100 is
|
|
70
|
+
* usually an embedded bitmap or unoptimized paths. assets.imageBudgetKb replaces them all. */
|
|
71
|
+
export const imageBudgets = Object.freeze({ ".svg": 100, ".webp": 300, ".avif": 300, ".jpg": 400, ".jpeg": 400, ".png": 500, ".gif": 500 });
|
|
72
|
+
function inspectImageBudget({ root, dsRoot, config }) {
|
|
73
|
+
const directory = path.join(dsRoot, "assets"), findings = [];
|
|
74
|
+
for (const relative of assetFiles(directory)) {
|
|
75
|
+
const budget = imageBudgets[path.extname(relative).toLowerCase()];
|
|
76
|
+
if (budget === undefined) continue;
|
|
77
|
+
const limit = config.assets.imageBudgetKb ?? budget, file = path.join(directory, relative), kb = Math.ceil(lstatSync(file).size / 1024);
|
|
78
|
+
if (kb <= limit) continue;
|
|
79
|
+
findings.push({ rule: "asset-image-budget", severity: findingSeverity("asset-image-budget"), file: path.relative(root, file).replaceAll("\\", "/"), line: 1, column: 1, guidanceUri: "ads://guides/performance",
|
|
80
|
+
message: `${path.basename(file)} is ${kb} KB; images of this format stay within ${limit} KB. Resize it to twice its displayed size and use WebP or AVIF for photos, or optimize the SVG. assets.imageBudgetKb in ds.config.json changes the limit for every image.` });
|
|
81
|
+
}
|
|
82
|
+
return findings;
|
|
83
|
+
}
|
|
84
|
+
|
|
67
85
|
/** Brand artwork is documented, licensed, previewed and used. Generated outputs match their masters. */
|
|
68
86
|
function inspectBrand({ root, dsRoot, config }) {
|
|
69
87
|
const diagnostics = [];
|
|
@@ -95,7 +113,7 @@ export function inspectAssets({ root, dsRoot, config, trackingRoot = root }) {
|
|
|
95
113
|
const diagnostics = [];
|
|
96
114
|
const sourceDiagnostic = brandSourceDiagnostic({ root, dsRoot, config });
|
|
97
115
|
if (sourceDiagnostic) diagnostics.push(sourceDiagnostic);
|
|
98
|
-
diagnostics.push(...inspectBrand({ root, dsRoot, config }), ...inspectGlyphs({ root, dsRoot, config }));
|
|
116
|
+
diagnostics.push(...inspectBrand({ root, dsRoot, config }), ...inspectGlyphs({ root, dsRoot, config }), ...inspectImageBudget({ root, dsRoot, config }));
|
|
99
117
|
function report(rule, file, message) { diagnostics.push({ rule, file: path.relative(root, file).replaceAll("\\", "/") || ".", line: 1, column: 1, message }); }
|
|
100
118
|
const assetRoot = path.join(dsRoot, "assets");
|
|
101
119
|
// Every mount is compared with the canonical ADS assets. Public mounts are
|
package/dist/boundaries.mjs
CHANGED
|
@@ -55,6 +55,8 @@ export function showcaseImportViolation(specifier, filename, options, resolve =
|
|
|
55
55
|
if (draftImportViolation(specifier, filename, resolve)) return true;
|
|
56
56
|
if (isTestFile(filename)) return false;
|
|
57
57
|
if (isDevelopmentFile(filename, options)) return false;
|
|
58
|
+
// A declaration file only describes types; it never runs and imports nothing at run time.
|
|
59
|
+
if (/\.d\.[cm]?ts$/.test(filename)) return false;
|
|
58
60
|
return resolve(specifier, filename).some((file) => isDevelopmentFile(file, options) || isTestFile(file));
|
|
59
61
|
}
|
|
60
62
|
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ADS's rendered layout check, run in the scenario document once per audited viewport width.
|
|
3
|
+
* It must stay self-contained: Playwright serializes the function into the page.
|
|
4
|
+
*
|
|
5
|
+
* - "document": the scenario document scrolls horizontally (scrollWidth > clientWidth).
|
|
6
|
+
* - "viewport": an element in #root reaches past the viewport's inline edges while its parent
|
|
7
|
+
* does not, the element that pushes content out.
|
|
8
|
+
* - "clipped": an element with overflow-x hidden or clip whose content is more than 4 px wider
|
|
9
|
+
* than its box, so content is cut off (a small negative margin cuts nothing).
|
|
10
|
+
* Intended scrollers (overflow-x auto or scroll) and their content, text-overflow: ellipsis,
|
|
11
|
+
* carousels (aria-roledescription="carousel"),
|
|
12
|
+
* native text fields, visually hidden content (a box of 1 px or less, clip or clip-path) and
|
|
13
|
+
* fixed-position layers are exempt.
|
|
14
|
+
*/
|
|
15
|
+
export async function layoutOverflow({ nodeLimit, width: expected }) {
|
|
16
|
+
// The resized frame lays out on its next frames.
|
|
17
|
+
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
|
18
|
+
if (window.innerWidth !== expected) throw new Error(`The scenario document is ${window.innerWidth} px wide, not the audited ${expected} px.`);
|
|
19
|
+
const root = document.querySelector("#root");
|
|
20
|
+
if (!root) return { issues: [], counts: {} };
|
|
21
|
+
const width = document.documentElement.clientWidth, issues = [], counts = { document: 0, viewport: 0, clipped: 0 };
|
|
22
|
+
const selector = element => {
|
|
23
|
+
const parts = [];
|
|
24
|
+
for (let node = element; node && node !== root; node = node.parentElement) {
|
|
25
|
+
const siblings = [...node.parentElement.children].filter(child => child.localName === node.localName);
|
|
26
|
+
parts.unshift(`${node.localName}${siblings.length > 1 ? `:nth-of-type(${siblings.indexOf(node) + 1})` : ""}`);
|
|
27
|
+
}
|
|
28
|
+
return ["#root", ...parts].join(" > ");
|
|
29
|
+
};
|
|
30
|
+
const report = (kind, element, detail) => { if (counts[kind]++ < nodeLimit) issues.push({ kind, selector: element === document.documentElement ? "html" : selector(element).slice(0, 300), html: element === document.documentElement ? "" : element.outerHTML.replace(/\s+/g, " ").slice(0, 200), ...detail }); };
|
|
31
|
+
if (document.documentElement.scrollWidth > width + 1) report("document", document.documentElement, { overflow: document.documentElement.scrollWidth - width });
|
|
32
|
+
const exempt = new Map();
|
|
33
|
+
/** Whether an element is inside an intended scroller, a fixed layer or hidden content. */
|
|
34
|
+
function excluded(element) {
|
|
35
|
+
if (!element || element === root) return false;
|
|
36
|
+
if (exempt.has(element)) return exempt.get(element);
|
|
37
|
+
const style = getComputedStyle(element), box = element.getBoundingClientRect();
|
|
38
|
+
const value = /^(?:auto|scroll)$/.test(style.overflowX) || style.position === "fixed" || style.clip !== "auto" && style.position === "absolute" || style.clipPath !== "none"
|
|
39
|
+
|| (box.width <= 1 || box.height <= 1) && style.overflow !== "visible" || excluded(element.parentElement);
|
|
40
|
+
exempt.set(element, value); return value;
|
|
41
|
+
}
|
|
42
|
+
for (const element of root.querySelectorAll("*")) {
|
|
43
|
+
if (element.closest("#ads-preview-status") || element.closest("svg") && element.localName !== "svg") continue;
|
|
44
|
+
if (excluded(element.parentElement)) continue;
|
|
45
|
+
const style = getComputedStyle(element);
|
|
46
|
+
if (style.position === "fixed" || !element.checkVisibility({ visibilityProperty: true })) continue;
|
|
47
|
+
const box = element.getBoundingClientRect();
|
|
48
|
+
if (box.width <= 1 || box.height <= 1) continue;
|
|
49
|
+
// A clipping ancestor already reports the content it cuts off, and nothing paints past it.
|
|
50
|
+
const contained = () => { for (let node = element.parentElement; node && node !== root; node = node.parentElement) if (/^(?:hidden|clip)$/.test(getComputedStyle(node).overflowX)) return true; return false; };
|
|
51
|
+
const parent = element.parentElement === root ? { left: 0, right: width } : element.parentElement.getBoundingClientRect();
|
|
52
|
+
if ((box.right > width + 1 || box.left < -1) && !(parent.right > width + 1 || parent.left < -1) && !contained()) report("viewport", element, { overflow: Math.round(Math.max(box.right - width, -box.left)) });
|
|
53
|
+
if (/^(?:hidden|clip)$/.test(style.overflowX) && element.scrollWidth > element.clientWidth + 4 && style.textOverflow !== "ellipsis" && !element.closest('[aria-roledescription="carousel"]') && !/^(?:input|textarea|select)$/.test(element.localName) && style.clip === "auto" && style.clipPath === "none")
|
|
54
|
+
report("clipped", element, { overflow: element.scrollWidth - element.clientWidth });
|
|
55
|
+
}
|
|
56
|
+
return { issues, counts };
|
|
57
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Layout shift of the rendered scenario, read once from the browser's buffered layout-shift entries
|
|
3
|
+
* and scored as Core Web Vitals scores CLS: the largest session window (shifts under 1 s apart, 5 s
|
|
4
|
+
* at most), ignoring shifts after input. Self-contained: Playwright serializes it into the page.
|
|
5
|
+
* Null where the browser does not report layout shift (Firefox, WebKit).
|
|
6
|
+
*/
|
|
7
|
+
export async function layoutShift({ nodeLimit }) {
|
|
8
|
+
if (!PerformanceObserver.supportedEntryTypes?.includes("layout-shift")) return null;
|
|
9
|
+
const entries = [];
|
|
10
|
+
const observer = new PerformanceObserver(list => { entries.push(...list.getEntries()); });
|
|
11
|
+
observer.observe({ type: "layout-shift", buffered: true });
|
|
12
|
+
await new Promise(resolve => setTimeout(resolve, 0));
|
|
13
|
+
entries.push(...observer.takeRecords());
|
|
14
|
+
observer.disconnect();
|
|
15
|
+
const root = document.querySelector("#root");
|
|
16
|
+
const selector = element => {
|
|
17
|
+
const parts = [];
|
|
18
|
+
for (let node = element; node && node !== root && node.parentElement; node = node.parentElement) {
|
|
19
|
+
const siblings = [...node.parentElement.children].filter(child => child.localName === node.localName);
|
|
20
|
+
parts.unshift(`${node.localName}${siblings.length > 1 ? `:nth-of-type(${siblings.indexOf(node) + 1})` : ""}`);
|
|
21
|
+
}
|
|
22
|
+
return ["#root", ...parts].join(" > ").slice(0, 300);
|
|
23
|
+
};
|
|
24
|
+
let best = { value: 0, nodes: new Set() }, window = { value: 0, nodes: new Set(), start: 0, last: 0 };
|
|
25
|
+
for (const entry of entries.filter(item => !item.hadRecentInput).sort((a, b) => a.startTime - b.startTime)) {
|
|
26
|
+
if (!window.value || entry.startTime - window.last >= 1000 || entry.startTime - window.start >= 5000) window = { value: 0, nodes: new Set(), start: entry.startTime, last: entry.startTime };
|
|
27
|
+
window.value += entry.value; window.last = entry.startTime;
|
|
28
|
+
for (const source of entry.sources ?? []) if (source.node?.nodeType === 1 && root?.contains(source.node)) window.nodes.add(selector(source.node));
|
|
29
|
+
if (window.value > best.value) best = window;
|
|
30
|
+
}
|
|
31
|
+
return { value: Math.round(best.value * 10000) / 10000, nodes: [...best.nodes].slice(0, nodeLimit) };
|
|
32
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ADS's own WCAG 1.4.11 (non-text contrast) check, run in the rendered scenario document with one
|
|
3
|
+
* page.evaluate per render; axe-core does not check it. It must stay self-contained: Playwright
|
|
4
|
+
* serializes the function into the page.
|
|
5
|
+
*
|
|
6
|
+
* For each visible, enabled interactive control in #root (button, input, select, textarea, a[href]
|
|
7
|
+
* and the switch, checkbox, radio, slider and tab roles) whose own background has less than 3:1
|
|
8
|
+
* against the background around it, a visible border (width > 0, a style that paints, a
|
|
9
|
+
* non-transparent color) is its boundary, so the best-contrasting side needs 3:1 against the
|
|
10
|
+
* surrounding background ("border"). A button, link or tab with text or an icon is exempt: WCAG
|
|
11
|
+
* 1.4.11 needs no boundary when that content identifies the control.
|
|
12
|
+
* An icon-only control (an svg and no text) needs its icon's paint at 3:1 against the control's
|
|
13
|
+
* effective background ("icon").
|
|
14
|
+
* A control whose background contrasts 3:1 with its surroundings is identified by its background;
|
|
15
|
+
* an icon-only one is still checked against that background. Disabled controls are exempt.
|
|
16
|
+
* Browser-drawn native checkboxes, radios and ranges and backgrounds under an image or gradient
|
|
17
|
+
* are skipped. Colors are read through a 1×1 canvas, so every CSS color syntax resolves to sRGB.
|
|
18
|
+
*/
|
|
19
|
+
export function nonTextContrast({ nodeLimit }) {
|
|
20
|
+
const root = document.querySelector("#root");
|
|
21
|
+
if (!root) return { issues: [], counts: {} };
|
|
22
|
+
const canvas = document.createElement("canvas"); canvas.width = canvas.height = 1;
|
|
23
|
+
const context = canvas.getContext("2d", { willReadFrequently: true }), cache = new Map();
|
|
24
|
+
const rgba = value => {
|
|
25
|
+
if (cache.has(value)) return cache.get(value);
|
|
26
|
+
context.clearRect(0, 0, 1, 1); context.fillStyle = "#000"; context.fillStyle = value; context.fillRect(0, 0, 1, 1);
|
|
27
|
+
const [r, g, b, a] = context.getImageData(0, 0, 1, 1).data, color = [r, g, b, a / 255];
|
|
28
|
+
cache.set(value, color); return color;
|
|
29
|
+
};
|
|
30
|
+
const over = (top, bottom) => [0, 1, 2].map(index => top[index] * top[3] + bottom[index] * (1 - top[3])).concat(1);
|
|
31
|
+
const luminance = ([r, g, b]) => { const channel = value => { value /= 255; return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4; }; return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b); };
|
|
32
|
+
const ratio = (front, back) => { const [a, b] = [luminance(over(front, back)), luminance(back)]; return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05); };
|
|
33
|
+
const hex = color => `#${color.slice(0, 3).map(value => Math.round(value).toString(16).padStart(2, "0")).join("")}`;
|
|
34
|
+
const backgrounds = new Map();
|
|
35
|
+
/** The opaque background painted behind an element's content, or null under an image. */
|
|
36
|
+
function background(element) {
|
|
37
|
+
if (!element) return [255, 255, 255, 1];
|
|
38
|
+
if (backgrounds.has(element)) return backgrounds.get(element);
|
|
39
|
+
const style = getComputedStyle(element), below = background(element.parentElement);
|
|
40
|
+
const value = !below || style.backgroundImage !== "none" ? null : over(rgba(style.backgroundColor), below);
|
|
41
|
+
backgrounds.set(element, value); return value;
|
|
42
|
+
}
|
|
43
|
+
const opacity = (element, stop) => { let value = 1; for (let node = element; node && node !== stop.parentElement; node = node.parentElement) value *= Number(getComputedStyle(node).opacity); return value; };
|
|
44
|
+
const text = element => { const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT); for (let node = walker.nextNode(); node; node = walker.nextNode()) if (node.data.trim() && !node.parentElement.closest("svg")) return true; return false; };
|
|
45
|
+
const selector = element => {
|
|
46
|
+
const parts = [];
|
|
47
|
+
for (let node = element; node && node !== root; node = node.parentElement) {
|
|
48
|
+
const siblings = [...node.parentElement.children].filter(child => child.localName === node.localName);
|
|
49
|
+
parts.unshift(`${node.localName}${siblings.length > 1 ? `:nth-of-type(${siblings.indexOf(node) + 1})` : ""}`);
|
|
50
|
+
}
|
|
51
|
+
return ["#root", ...parts].join(" > ");
|
|
52
|
+
};
|
|
53
|
+
const native = /^(?:checkbox|radio|range|color|file|hidden)$/;
|
|
54
|
+
const issues = [], counts = { border: 0, icon: 0 };
|
|
55
|
+
for (const element of root.querySelectorAll('button, input, select, textarea, a[href], [role="switch"], [role="checkbox"], [role="radio"], [role="slider"], [role="tab"]')) {
|
|
56
|
+
if (element.closest("#ads-preview-status") || element.matches(":disabled") || element.closest('[aria-disabled="true"], [inert]')) continue;
|
|
57
|
+
if (!element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true })) continue;
|
|
58
|
+
const box = element.getBoundingClientRect();
|
|
59
|
+
if (box.width < 1 || box.height < 1) continue;
|
|
60
|
+
const style = getComputedStyle(element);
|
|
61
|
+
if (element.localName === "input" && native.test(element.type) && style.appearance !== "none") continue;
|
|
62
|
+
const around = background(element.parentElement), own = background(element);
|
|
63
|
+
if (!around || !own) continue;
|
|
64
|
+
const identified = ratio(own, around) >= 3;
|
|
65
|
+
const report = (kind, value, foreground, back) => { if (counts[kind]++ < nodeLimit) issues.push({ kind, selector: selector(element).slice(0, 300), html: element.outerHTML.replace(/\s+/g, " ").slice(0, 200), ratio: Math.round(value * 100) / 100, foreground: hex(foreground), background: hex(back) }); };
|
|
66
|
+
const labelled = element.matches('button, a[href], [role="tab"]') && (text(element) || element.querySelector("svg"));
|
|
67
|
+
if (!identified && !labelled) {
|
|
68
|
+
const sides = ["top", "right", "bottom", "left"].filter(side => parseFloat(style.getPropertyValue(`border-${side}-width`)) > 0 && !/^(?:none|hidden)$/.test(style.getPropertyValue(`border-${side}-style`)))
|
|
69
|
+
.map(side => rgba(style.getPropertyValue(`border-${side}-color`))).filter(color => color[3] > 0);
|
|
70
|
+
if (sides.length) {
|
|
71
|
+
const best = sides.map(color => [ratio(color, around), color]).sort((a, b) => b[0] - a[0])[0];
|
|
72
|
+
if (best[0] + 1e-9 < 3) report("border", best[0], over(best[1], around), around);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const icon = !text(element) && [...element.querySelectorAll("svg")].find(svg => svg.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }));
|
|
76
|
+
if (icon) {
|
|
77
|
+
const shape = [...icon.querySelectorAll("path, circle, rect, ellipse, line, polyline, polygon, use, text")].find(node => { const paint = getComputedStyle(node); return paint.stroke !== "none" && rgba(paint.stroke)[3] > 0 || paint.fill !== "none" && !paint.fill.startsWith("url(") && rgba(paint.fill)[3] > 0; });
|
|
78
|
+
if (shape) {
|
|
79
|
+
const paint = getComputedStyle(shape), value = paint.stroke !== "none" && rgba(paint.stroke)[3] > 0 ? paint.stroke : paint.fill, color = rgba(value).slice();
|
|
80
|
+
color[3] *= opacity(shape, element) / Number(style.opacity);
|
|
81
|
+
const back = background(shape.parentElement) ?? own, measured = ratio(color, back);
|
|
82
|
+
if (measured + 1e-9 < 3) report("icon", measured, over(color, back), back);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return { issues, counts };
|
|
87
|
+
}
|
|
@@ -1,16 +1,26 @@
|
|
|
1
|
-
import { readFileSync, writeFileSync } from "node:fs";
|
|
1
|
+
import { readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { openPreviewScenario } from "../verification/browser.mjs";
|
|
5
|
+
import { nonTextContrast } from "./non-text-contrast.mjs";
|
|
6
|
+
import { layoutOverflow } from "./layout-overflow.mjs";
|
|
7
|
+
import { layoutShift } from "./layout-shift.mjs";
|
|
5
8
|
|
|
6
9
|
// Runs only as an owned child, using the receiving project's browser dependency.
|
|
7
10
|
const request = JSON.parse(readFileSync(process.argv[2], "utf8"));
|
|
8
11
|
const playwright = createRequire(import.meta.url)(request.playwright);
|
|
9
12
|
const axe = readFileSync(request.axe, "utf8");
|
|
13
|
+
const runs = [];
|
|
14
|
+
/** Atomic, so a worker that dies leaves the renders it finished readable. */
|
|
15
|
+
function publish() {
|
|
16
|
+
const file = path.join(request.output, "report.json"), temporary = `${file}.tmp`;
|
|
17
|
+
writeFileSync(temporary, JSON.stringify({ schemaVersion: 1, runId: request.runId, runs }));
|
|
18
|
+
renameSync(temporary, file);
|
|
19
|
+
}
|
|
10
20
|
let browser;
|
|
11
21
|
try {
|
|
12
22
|
browser = await playwright[request.settings.browser].launch({ headless: true, ...(request.settings.channel ? { channel: request.settings.channel } : {}) });
|
|
13
|
-
const
|
|
23
|
+
const timeout = request.settings.timeoutMs;
|
|
14
24
|
for (const theme of new Set(request.apps.map(app => app.theme))) {
|
|
15
25
|
const apps = request.apps.filter(app => app.theme === theme);
|
|
16
26
|
// The audit injects its own script; bypassCSP keeps project CSP from blocking it.
|
|
@@ -19,10 +29,18 @@ try {
|
|
|
19
29
|
// A bounded number of pages render at once; results keep request order.
|
|
20
30
|
const results = [];
|
|
21
31
|
let next = 0;
|
|
22
|
-
async function lane() { while (next < apps.length) { const index = next++; results[index] = await
|
|
32
|
+
async function lane() { while (next < apps.length) { const index = next++; results[index] = await attempt(apps[index]); runs.push(results[index]); publish(); } }
|
|
23
33
|
await Promise.all(Array.from({ length: Math.min(apps.length, request.concurrency ?? 1) }, lane));
|
|
24
|
-
|
|
25
|
-
async function
|
|
34
|
+
// One render failing is that render's result; what it found before failing is kept.
|
|
35
|
+
async function attempt(app) {
|
|
36
|
+
const partial = {};
|
|
37
|
+
try { return await audit(app, partial); }
|
|
38
|
+
catch (error) {
|
|
39
|
+
const code = error.failure?.code;
|
|
40
|
+
return { scenario: app.scenario, theme: app.theme, ...(app.brand ? { brand: app.brand } : {}), failed: true, cause: `${String(error.message).replace(/\s+/g, " ").trim().slice(0, 460)}${code ? ` (${code})` : ""}`, ...partial };
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
async function audit(app, partial) {
|
|
26
44
|
const page = await context.newPage();
|
|
27
45
|
try {
|
|
28
46
|
const frame = await openPreviewScenario(page, app.url, app.scenario, { timeout });
|
|
@@ -33,6 +51,8 @@ try {
|
|
|
33
51
|
await Promise.all([...document.images].map(image => image.decode().catch(() => {})));
|
|
34
52
|
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
|
35
53
|
});
|
|
54
|
+
// Before the audit touches the page: resizing below would shift it.
|
|
55
|
+
partial.layoutShift = await frame.evaluate(layoutShift, { nodeLimit: request.nodeLimit });
|
|
36
56
|
if (!await frame.evaluate(() => !!window.axe)) await frame.addScriptTag({ content: axe });
|
|
37
57
|
const result = await frame.evaluate(async ({ tags, nodeLimit }) => {
|
|
38
58
|
// Scenario content only: the preview status aside and document-level chrome are ADS-owned.
|
|
@@ -41,11 +61,20 @@ try {
|
|
|
41
61
|
return { violations: outcome.violations.map(violation => ({ id: violation.id, impact: violation.impact, tags: violation.tags, help: clip(violation.help, 300), helpUrl: clip(violation.helpUrl, 300), nodeCount: violation.nodes.length,
|
|
42
62
|
nodes: violation.nodes.slice(0, nodeLimit).map(node => ({ selector: clip(node.target.flat().join(" "), 300), html: clip(node.html, 200), summary: clip(node.failureSummary, 500) })) })), incomplete: outcome.incomplete.length };
|
|
43
63
|
}, { tags: request.tags, nodeLimit: request.nodeLimit });
|
|
64
|
+
result.layoutShift = partial.layoutShift;
|
|
65
|
+
Object.assign(partial, result);
|
|
66
|
+
result.nonText = await frame.evaluate(nonTextContrast, { nodeLimit: request.nodeLimit });
|
|
67
|
+
// The same page is resized: one evaluate per width, no new render.
|
|
68
|
+
result.layout = [];
|
|
69
|
+
for (const width of request.overflowWidths) {
|
|
70
|
+
await page.setViewportSize({ width, height: request.viewport.height });
|
|
71
|
+
result.layout.push({ width, ...await frame.evaluate(layoutOverflow, { nodeLimit: request.nodeLimit, width }) });
|
|
72
|
+
}
|
|
44
73
|
if (await frame.locator("html").getAttribute("data-ads-preview-state") !== "ready") throw new Error(`Scenario ${app.scenario} stopped being ready during the audit.`);
|
|
45
74
|
return { scenario: app.scenario, theme: app.theme, ...(app.brand ? { brand: app.brand } : {}), ...result };
|
|
46
|
-
} finally { await page.close(); }
|
|
75
|
+
} finally { await page.close().catch(() => {}); }
|
|
47
76
|
}
|
|
48
77
|
} finally { await context.close(); }
|
|
49
78
|
}
|
|
50
|
-
|
|
79
|
+
publish();
|
|
51
80
|
} finally { await browser?.close(); }
|