@specimo/check 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +35 -2
- package/bin/specimo-check.js +87 -0
- package/package.json +51 -4
- package/src/collect.js +153 -0
- package/src/compare.js +231 -0
- package/src/index.js +3 -0
- package/src/pixel.js +112 -0
- package/src/report.js +36 -0
- package/src/run.js +301 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Murvatoff Solutions
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,36 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @specimo/check
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Is what you shipped what was approved? `specimo check` renders the approved design from [Specimo](https://specimo.design)
|
|
4
|
+
and your running app **in the same Chromium**, with the same viewport, scale, locale, timezone and reduced motion, and
|
|
5
|
+
reports what differs, element by element: size, spacing, colour, type, radius, shadow, missing or hidden elements, each
|
|
6
|
+
named with the design token it should use. A pixel diff is attached as evidence. No AI model runs during the check.
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npm i -D @specimo/check playwright-core && npx playwright install chromium
|
|
10
|
+
SPECIMO_TOKEN=adp_… npx specimo-check --base-url http://localhost:3000
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
- **Screens:** every approved screen with a route, or `--screen <key>` (repeatable).
|
|
14
|
+
- **Scenarios:** `--viewport desktop|tablet|mobile`, `--theme light|dark` (repeatable).
|
|
15
|
+
- **Exit codes:** `0` no blocking findings · `1` blocking findings · `2` the check could not run (never a pass).
|
|
16
|
+
- **Warn by default:** findings are warnings until you set `"severity": "error"` for a check.
|
|
17
|
+
- **Results** go to Specimo (screen page → Shipped) unless `--no-upload`; a Markdown report is written to
|
|
18
|
+
`specimo-report/` and to the GitHub job summary.
|
|
19
|
+
|
|
20
|
+
`.specimo.json`:
|
|
21
|
+
|
|
22
|
+
```json
|
|
23
|
+
{
|
|
24
|
+
"api": "https://api.specimo.design",
|
|
25
|
+
"project": "Shop",
|
|
26
|
+
"check": {
|
|
27
|
+
"baseURL": "http://localhost:3000",
|
|
28
|
+
"viewports": ["desktop", "mobile"],
|
|
29
|
+
"themes": ["light", "dark"],
|
|
30
|
+
"screens": { "checkout": { "route": "/checkout", "version": 3 } },
|
|
31
|
+
"checks": { "parity": { "severity": "warning", "maxDiffRatio": 0.02 } }
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Add `data-specimo-id` attributes (Specimo's code export does) so elements match reliably.
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// specimo check (DSGN-182): is the shipped UI the approved design? Renders both in the same Chromium and compares them.
|
|
3
|
+
// Token: --token, $SPECIMO_TOKEN, ~/.config/specimo/credentials.json. API: --api, $SPECIMO_API, .specimo.json, default.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { parseArgs } from 'node:util';
|
|
8
|
+
import { runCheck } from '../src/run.js';
|
|
9
|
+
|
|
10
|
+
const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
11
|
+
const DEFAULT_API = 'https://api.specimo.design';
|
|
12
|
+
const CRED_FILE = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'specimo', 'credentials.json');
|
|
13
|
+
|
|
14
|
+
const HELP = `specimo check ${VERSION}: compare your running app with the approved designs in Specimo
|
|
15
|
+
|
|
16
|
+
Usage: specimo check [--base-url http://localhost:3000] [--screen key]... [options]
|
|
17
|
+
|
|
18
|
+
--base-url <url> Where your app runs (or check.baseURL in .specimo.json)
|
|
19
|
+
--screen <key> Check only this screen (repeatable). Default: every approved screen with a route
|
|
20
|
+
--viewport <name> desktop | tablet | mobile (repeatable; default from .specimo.json or desktop)
|
|
21
|
+
--theme <name> light | dark (repeatable; default light)
|
|
22
|
+
--version <v> approved (default) | latest — compare with drafts under review
|
|
23
|
+
--out <dir> Report folder (default specimo-report)
|
|
24
|
+
--no-upload Don't send results to Specimo
|
|
25
|
+
--json Print the report as JSON
|
|
26
|
+
--token <t> --api <url> -h, --help -v, --version
|
|
27
|
+
|
|
28
|
+
Exit codes: 0 no blocking findings · 1 blocking findings · 2 the check could not run (never a pass)
|
|
29
|
+
`;
|
|
30
|
+
|
|
31
|
+
const { values: opt } = parseArgs({
|
|
32
|
+
allowPositionals: true,
|
|
33
|
+
options: {
|
|
34
|
+
'base-url': { type: 'string' }, screen: { type: 'string', multiple: true }, viewport: { type: 'string', multiple: true }, theme: { type: 'string', multiple: true },
|
|
35
|
+
version: { type: 'string' }, out: { type: 'string' }, 'no-upload': { type: 'boolean' }, json: { type: 'boolean' }, token: { type: 'string' }, api: { type: 'string' },
|
|
36
|
+
help: { type: 'boolean', short: 'h' }, 'show-version': { type: 'boolean', short: 'v' },
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
if (opt.help) { process.stdout.write(HELP); process.exit(0); }
|
|
40
|
+
if (opt['show-version']) { process.stdout.write(`${VERSION}\n`); process.exit(0); }
|
|
41
|
+
|
|
42
|
+
const die = (msg) => { process.stderr.write(`specimo check: ${msg}\n`); process.exit(2); };
|
|
43
|
+
const readJson = (f) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return null; } };
|
|
44
|
+
const findUp = (name, dir = process.cwd()) => { for (let d = dir; ; d = path.dirname(d)) { const f = path.join(d, name); if (fs.existsSync(f)) return f; if (path.dirname(d) === d) return null; } };
|
|
45
|
+
const cfgFile = findUp('.specimo.json');
|
|
46
|
+
const cfg = (cfgFile && readJson(cfgFile)) || {};
|
|
47
|
+
const check = cfg.check ?? {};
|
|
48
|
+
const api = (opt.api || process.env.SPECIMO_API || cfg.api || DEFAULT_API).replace(/\/+$/, '');
|
|
49
|
+
const token = opt.token || process.env.SPECIMO_TOKEN || readJson(CRED_FILE)?.[api]?.token;
|
|
50
|
+
if (!token) die('no token. Set SPECIMO_TOKEN (a project token from Specimo → Project → Connect agent) or run `specimo login`.');
|
|
51
|
+
const baseURL = opt['base-url'] || process.env.SPECIMO_BASE_URL || check.baseURL;
|
|
52
|
+
if (!baseURL) die('where does your app run? Pass --base-url http://localhost:3000 or set check.baseURL in .specimo.json.');
|
|
53
|
+
|
|
54
|
+
// The token belongs to one project.
|
|
55
|
+
let who;
|
|
56
|
+
try {
|
|
57
|
+
const res = await fetch(`${api}/api/v1/whoami`, { headers: { authorization: `Bearer ${token}`, 'user-agent': `specimo-check/${VERSION}` } });
|
|
58
|
+
if (res.status === 401) die('the token was rejected (revoked or expired). Create a new one in Specimo → Project → Connect agent.');
|
|
59
|
+
if (!res.ok) die(`Specimo answered ${res.status} for the token.`);
|
|
60
|
+
who = await res.json();
|
|
61
|
+
} catch (e) {
|
|
62
|
+
die(`cannot reach ${api}: ${e.message}`);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const screenConfig = check.screens ?? {};
|
|
66
|
+
const report = await runCheck({
|
|
67
|
+
api,
|
|
68
|
+
appUrl: who.appUrl,
|
|
69
|
+
token,
|
|
70
|
+
project: who.projectId,
|
|
71
|
+
baseURL,
|
|
72
|
+
screens: opt.screen ?? (Object.keys(screenConfig).length && check.only ? Object.keys(screenConfig) : undefined),
|
|
73
|
+
viewports: opt.viewport ?? check.viewports,
|
|
74
|
+
themes: opt.theme ?? check.themes,
|
|
75
|
+
checks: check.checks,
|
|
76
|
+
screenConfig,
|
|
77
|
+
version: opt.version,
|
|
78
|
+
upload: !opt['no-upload'],
|
|
79
|
+
outDir: opt.out ?? check.out ?? 'specimo-report',
|
|
80
|
+
readyTimeoutMs: check.readyTimeoutMs,
|
|
81
|
+
runnerVersion: VERSION,
|
|
82
|
+
userAgent: `specimo-check/${VERSION}`,
|
|
83
|
+
log: opt.json ? () => undefined : (s) => process.stdout.write(`${s}\n`),
|
|
84
|
+
});
|
|
85
|
+
if (opt.json) process.stdout.write(`${JSON.stringify({ ...report, markdown: undefined }, null, 2)}\n`);
|
|
86
|
+
else process.stdout.write(`\n${report.markdown}\n`);
|
|
87
|
+
process.exit(report.exitCode);
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@specimo/check",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Specimo shipped-UI parity check: renders the approved design and your app in the same browser and reports what differs, element by element.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./src/index.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"src",
|
|
12
|
+
"bin",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=20"
|
|
18
|
+
},
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"homepage": "https://specimo.design/docs/shipped-parity",
|
|
21
|
+
"scripts": {
|
|
22
|
+
"test": "node --test --test-timeout=120000 test/*.test.js"
|
|
23
|
+
},
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"playwright-core": ">=1.45"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"playwright-core": "^1.65.1"
|
|
29
|
+
},
|
|
30
|
+
"author": "Specimo (https://specimo.design)",
|
|
31
|
+
"bin": {
|
|
32
|
+
"specimo-check": "bin/specimo-check.js"
|
|
33
|
+
},
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "git+https://github.com/specimodesign/specimo-check.git"
|
|
37
|
+
},
|
|
38
|
+
"bugs": {
|
|
39
|
+
"url": "https://github.com/specimodesign/specimo-check/issues"
|
|
40
|
+
},
|
|
41
|
+
"keywords": [
|
|
42
|
+
"specimo",
|
|
43
|
+
"design-system",
|
|
44
|
+
"visual-regression",
|
|
45
|
+
"ui-parity",
|
|
46
|
+
"playwright",
|
|
47
|
+
"ci",
|
|
48
|
+
"design-tokens"
|
|
49
|
+
],
|
|
50
|
+
"publishConfig": {
|
|
51
|
+
"access": "public"
|
|
52
|
+
}
|
|
53
|
+
}
|
package/src/collect.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs inside the page (page.evaluate). Self-contained: no imports, no closures.
|
|
3
|
+
* Returns a snapshot of the meaningful elements (ids, roles, names, boxes, computed styles) plus resolved token values.
|
|
4
|
+
* Colours are normalised to rgb()/rgba() through a canvas so oklch(), color-mix() and named colours compare equally.
|
|
5
|
+
*
|
|
6
|
+
* @param {{ tokenVars?: string[], maxElements?: number }} opts
|
|
7
|
+
*/
|
|
8
|
+
export function collectInPage(opts) {
|
|
9
|
+
const tokenVars = (opts && opts.tokenVars) || [];
|
|
10
|
+
const maxElements = (opts && opts.maxElements) || 1500;
|
|
11
|
+
const STYLE_PROPS = [
|
|
12
|
+
'display', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left', 'row-gap', 'column-gap',
|
|
13
|
+
'color', 'background-color', 'border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width', 'border-top-color', 'border-top-style',
|
|
14
|
+
'border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius',
|
|
15
|
+
'font-family', 'font-weight', 'font-size', 'line-height', 'letter-spacing', 'text-align', 'text-transform', 'box-shadow', 'opacity',
|
|
16
|
+
];
|
|
17
|
+
const COLOR_PROPS = new Set(['color', 'background-color', 'border-top-color']);
|
|
18
|
+
const LANDMARK = { header: 'banner', footer: 'contentinfo', main: 'main', nav: 'navigation', form: 'form', aside: 'complementary' };
|
|
19
|
+
const NAME_FROM_CONTENT = new Set(['button', 'link', 'heading', 'checkbox', 'radio', 'tab', 'menuitem', 'option', 'switch', 'cell', 'columnheader', 'rowheader', 'tooltip', 'treeitem']);
|
|
20
|
+
const INPUT_ROLE = { checkbox: 'checkbox', radio: 'radio', range: 'slider', button: 'button', submit: 'button', reset: 'button', image: 'button', search: 'searchbox' };
|
|
21
|
+
|
|
22
|
+
const canvas = document.createElement('canvas');
|
|
23
|
+
canvas.width = canvas.height = 1;
|
|
24
|
+
const ctx = canvas.getContext('2d', { willReadFrequently: true });
|
|
25
|
+
const colorCache = new Map();
|
|
26
|
+
const toRgb = (c) => {
|
|
27
|
+
if (!c) return c;
|
|
28
|
+
if (colorCache.has(c)) return colorCache.get(c);
|
|
29
|
+
let out = c;
|
|
30
|
+
try {
|
|
31
|
+
ctx.clearRect(0, 0, 1, 1);
|
|
32
|
+
ctx.fillStyle = '#000';
|
|
33
|
+
ctx.fillStyle = c;
|
|
34
|
+
ctx.fillRect(0, 0, 1, 1);
|
|
35
|
+
const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data;
|
|
36
|
+
out = a === 255 ? `rgb(${r}, ${g}, ${b})` : a === 0 ? 'transparent' : `rgba(${r}, ${g}, ${b}, ${Math.round((a / 255) * 100) / 100})`;
|
|
37
|
+
} catch {}
|
|
38
|
+
colorCache.set(c, out);
|
|
39
|
+
return out;
|
|
40
|
+
};
|
|
41
|
+
const clean = (s) => (s || '').replace(/\s+/g, ' ').trim();
|
|
42
|
+
const roleOf = (el) => {
|
|
43
|
+
const explicit = el.getAttribute('role');
|
|
44
|
+
if (explicit) return explicit.split(/\s+/)[0];
|
|
45
|
+
const tag = el.tagName.toLowerCase();
|
|
46
|
+
if (tag === 'button') return 'button';
|
|
47
|
+
if (tag === 'a') return el.hasAttribute('href') ? 'link' : null;
|
|
48
|
+
if (/^h[1-6]$/.test(tag)) return 'heading';
|
|
49
|
+
if (tag === 'img' || tag === 'svg') return el.getAttribute('alt') === '' || el.getAttribute('aria-hidden') === 'true' ? null : 'img';
|
|
50
|
+
if (tag === 'textarea') return 'textbox';
|
|
51
|
+
if (tag === 'select') return 'combobox';
|
|
52
|
+
if (tag === 'input') return INPUT_ROLE[(el.getAttribute('type') || 'text').toLowerCase()] || 'textbox';
|
|
53
|
+
if (tag === 'ul' || tag === 'ol') return 'list';
|
|
54
|
+
if (tag === 'li') return 'listitem';
|
|
55
|
+
return LANDMARK[tag] || null;
|
|
56
|
+
};
|
|
57
|
+
const nameOf = (el) => {
|
|
58
|
+
const aria = el.getAttribute('aria-label');
|
|
59
|
+
if (aria) return clean(aria);
|
|
60
|
+
const by = el.getAttribute('aria-labelledby');
|
|
61
|
+
if (by) return clean(by.split(/\s+/).map((id) => document.getElementById(id)?.textContent || '').join(' '));
|
|
62
|
+
if (el.id) {
|
|
63
|
+
const label = document.querySelector(`label[for="${CSS.escape(el.id)}"]`);
|
|
64
|
+
if (label) return clean(label.textContent);
|
|
65
|
+
}
|
|
66
|
+
const alt = el.getAttribute('alt');
|
|
67
|
+
if (alt) return clean(alt);
|
|
68
|
+
const tag = el.tagName.toLowerCase();
|
|
69
|
+
if (tag === 'input' || tag === 'textarea') return clean(el.getAttribute('placeholder') || el.getAttribute('value') || '');
|
|
70
|
+
// Name from content only where ARIA allows it; landmarks and lists are named by aria-label alone.
|
|
71
|
+
if (!NAME_FROM_CONTENT.has(roleOf(el) || '')) return clean(el.getAttribute('title') || '');
|
|
72
|
+
return clean(el.innerText || el.textContent || el.getAttribute('title') || '').slice(0, 80);
|
|
73
|
+
};
|
|
74
|
+
const ownText = (el) => clean(Array.from(el.childNodes).filter((n) => n.nodeType === 3).map((n) => n.textContent).join(' ')).slice(0, 120);
|
|
75
|
+
const pathOf = (el) => {
|
|
76
|
+
const parts = [];
|
|
77
|
+
for (let e = el; e && e !== document.body && e.parentElement; e = e.parentElement) {
|
|
78
|
+
const tag = e.tagName.toLowerCase();
|
|
79
|
+
const same = Array.from(e.parentElement.children).filter((c) => c.tagName === e.tagName);
|
|
80
|
+
parts.unshift(same.length > 1 ? `${tag}:${same.indexOf(e) + 1}` : tag);
|
|
81
|
+
}
|
|
82
|
+
return parts.join('>');
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const out = [];
|
|
86
|
+
const all = document.body ? document.body.querySelectorAll('*') : [];
|
|
87
|
+
for (const el of all) {
|
|
88
|
+
if (out.length >= maxElements) break;
|
|
89
|
+
if (el.closest('[data-pg-ignore], script, style, template, noscript, head')) continue;
|
|
90
|
+
const tag = el.tagName.toLowerCase();
|
|
91
|
+
const id = el.getAttribute('data-specimo-id');
|
|
92
|
+
const role = roleOf(el);
|
|
93
|
+
const text = ownText(el);
|
|
94
|
+
if (!id && !role && !text) continue;
|
|
95
|
+
const cs = getComputedStyle(el);
|
|
96
|
+
const r = el.getBoundingClientRect();
|
|
97
|
+
const visible = cs.display !== 'none' && cs.visibility !== 'hidden' && r.width > 0 && r.height > 0;
|
|
98
|
+
if (!visible && !id) continue;
|
|
99
|
+
const styles = {};
|
|
100
|
+
for (const p of STYLE_PROPS) {
|
|
101
|
+
const v = cs.getPropertyValue(p);
|
|
102
|
+
styles[p] = COLOR_PROPS.has(p) ? toRgb(v) : v;
|
|
103
|
+
}
|
|
104
|
+
const comp = el.closest('[data-ds-component]');
|
|
105
|
+
out.push({
|
|
106
|
+
id: id || null,
|
|
107
|
+
tag,
|
|
108
|
+
role,
|
|
109
|
+
name: nameOf(el),
|
|
110
|
+
text,
|
|
111
|
+
component: comp ? comp.getAttribute('data-ds-component') : null,
|
|
112
|
+
path: pathOf(el),
|
|
113
|
+
visible,
|
|
114
|
+
rect: { x: Math.round(r.left + scrollX), y: Math.round(r.top + scrollY), w: Math.round(r.width), h: Math.round(r.height) },
|
|
115
|
+
styles,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Token values as this page resolves them (per mode/scheme), via probes so colours and lengths are comparable.
|
|
120
|
+
const probe = document.createElement('div');
|
|
121
|
+
probe.setAttribute('data-pg-ignore', '');
|
|
122
|
+
probe.style.cssText = 'position:absolute;visibility:hidden;pointer-events:none;left:-9999px;top:0';
|
|
123
|
+
(document.body || document.documentElement).appendChild(probe);
|
|
124
|
+
const tokens = {};
|
|
125
|
+
const root = getComputedStyle(document.documentElement);
|
|
126
|
+
const declared = (v, depth = 0) => {
|
|
127
|
+
const raw = root.getPropertyValue(v).trim();
|
|
128
|
+
const m = raw.match(/^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/);
|
|
129
|
+
return m && depth < 10 ? declared(m[1], depth + 1) || (m[2] || '').trim() : raw;
|
|
130
|
+
};
|
|
131
|
+
for (const v of tokenVars) {
|
|
132
|
+
const raw = root.getPropertyValue(v).trim();
|
|
133
|
+
if (!raw) continue;
|
|
134
|
+
const value = declared(v);
|
|
135
|
+
let color = null, px = null;
|
|
136
|
+
if (CSS.supports('color', value)) color = toRgb(value);
|
|
137
|
+
else if (CSS.supports('width', value)) {
|
|
138
|
+
probe.style.width = value;
|
|
139
|
+
const w = getComputedStyle(probe).width;
|
|
140
|
+
px = /px$/.test(w) ? parseFloat(w) : null;
|
|
141
|
+
probe.style.width = '';
|
|
142
|
+
}
|
|
143
|
+
tokens[v] = { raw, value, color, px };
|
|
144
|
+
}
|
|
145
|
+
probe.remove();
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
url: location.href,
|
|
149
|
+
page: { width: document.documentElement.scrollWidth, height: Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0) },
|
|
150
|
+
elements: out,
|
|
151
|
+
tokens,
|
|
152
|
+
};
|
|
153
|
+
}
|
package/src/compare.js
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Element-level parity (ADR-022): match design elements to implementation elements, compare what a designer cares about
|
|
3
|
+
* (size, spacing, colour, type, radius, shadow, visibility) and name the design token for each expected value.
|
|
4
|
+
* Pure and deterministic: takes two snapshots from collectInPage().
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** @typedef {{ id: string|null, tag: string, role: string|null, name: string, text: string, component: string|null, path: string, visible: boolean, rect: {x:number,y:number,w:number,h:number}, styles: Record<string,string> }} El */
|
|
8
|
+
/** @typedef {{ elements: El[], tokens: Record<string, {raw:string,color:string|null,px:number|null}>, page: {width:number,height:number} }} Snapshot */
|
|
9
|
+
|
|
10
|
+
export const DEFAULT_TOLERANCES = { px: 1, sizePx: 2, sizeRatio: 0.01, colorDeltaE: 2.5, fontSizePx: 0.5 };
|
|
11
|
+
|
|
12
|
+
const IMPORTANT_ROLES = new Set(['button', 'link', 'textbox', 'searchbox', 'checkbox', 'radio', 'combobox', 'slider', 'heading', 'img']);
|
|
13
|
+
|
|
14
|
+
// ── colour ────────────────────────────────────────────────────────────────────
|
|
15
|
+
export function parseRgb(s) {
|
|
16
|
+
if (!s) return null;
|
|
17
|
+
if (s === 'transparent') return [0, 0, 0, 0];
|
|
18
|
+
const m = s.match(/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s/]+([\d.]+%?))?\s*\)/);
|
|
19
|
+
if (!m) return null;
|
|
20
|
+
const a = m[4] === undefined ? 1 : m[4].endsWith('%') ? parseFloat(m[4]) / 100 : parseFloat(m[4]);
|
|
21
|
+
return [+m[1], +m[2], +m[3], a];
|
|
22
|
+
}
|
|
23
|
+
const lin = (c) => ((c /= 255) <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
|
|
24
|
+
function oklab([r, g, b]) {
|
|
25
|
+
const R = lin(r), G = lin(g), B = lin(b);
|
|
26
|
+
const l = Math.cbrt(0.4122214708 * R + 0.5363325363 * G + 0.0514459929 * B);
|
|
27
|
+
const m = Math.cbrt(0.2119034982 * R + 0.6806995451 * G + 0.1073969566 * B);
|
|
28
|
+
const s = Math.cbrt(0.0883024619 * R + 0.2817188376 * G + 0.6299787005 * B);
|
|
29
|
+
return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s];
|
|
30
|
+
}
|
|
31
|
+
/** OKLab distance × 100 (≈ 1 is a just-noticeable difference). Alpha differences count fully. */
|
|
32
|
+
export function deltaE(a, b) {
|
|
33
|
+
const x = parseRgb(a), y = parseRgb(b);
|
|
34
|
+
if (!x || !y) return a === b ? 0 : Infinity;
|
|
35
|
+
if (x[3] === 0 && y[3] === 0) return 0;
|
|
36
|
+
const [l1, a1, b1] = oklab(x), [l2, a2, b2] = oklab(y);
|
|
37
|
+
return Math.hypot(l1 - l2, a1 - a2, b1 - b2) * 100 + Math.abs(x[3] - y[3]) * 100;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// ── tokens ────────────────────────────────────────────────────────────────────
|
|
41
|
+
/** cssVar → token name, built from the bundle's tokens. */
|
|
42
|
+
export function tokenIndex(bundleTokens = [], resolved = {}) {
|
|
43
|
+
const byVar = new Map(bundleTokens.map((t) => [t.cssVar, t]));
|
|
44
|
+
const colors = [], lengths = [];
|
|
45
|
+
for (const [v, r] of Object.entries(resolved)) {
|
|
46
|
+
const t = byVar.get(v);
|
|
47
|
+
if (!t) continue;
|
|
48
|
+
if (r.color && r.color !== 'transparent') colors.push({ name: t.name, color: r.color });
|
|
49
|
+
else if (r.px !== null && r.px !== undefined) lengths.push({ name: t.name, type: t.type, px: r.px });
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
color(c) {
|
|
53
|
+
let best = null;
|
|
54
|
+
for (const t of colors) {
|
|
55
|
+
const d = deltaE(c, t.color);
|
|
56
|
+
if (d < 1 && (!best || d < best.d)) best = { name: t.name, d };
|
|
57
|
+
}
|
|
58
|
+
return best?.name ?? null;
|
|
59
|
+
},
|
|
60
|
+
length(px, prefer) {
|
|
61
|
+
const hits = lengths.filter((t) => Math.abs(t.px - px) < 0.5);
|
|
62
|
+
if (!hits.length) return null;
|
|
63
|
+
return (hits.find((t) => prefer.includes(t.type)) ?? hits[0]).name;
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// ── matching ──────────────────────────────────────────────────────────────────
|
|
69
|
+
const norm = (s) => (s || '').toLowerCase().replace(/\s+/g, ' ').trim();
|
|
70
|
+
const meaningful = (e) => !!(e.id || e.role || e.text);
|
|
71
|
+
export const labelOf = (e) => {
|
|
72
|
+
const what = e.role ? `${e.role}` : `<${e.tag}>`;
|
|
73
|
+
const name = e.name || e.text;
|
|
74
|
+
return `${what}${name ? ` “${name.slice(0, 50)}”` : ''}${e.id ? ` [${e.id}]` : ''}`;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Pairs design elements with implementation elements: data-specimo-id, then role + accessible name, then tag + own text,
|
|
79
|
+
* then component + position among same-component elements. Each implementation element is used once.
|
|
80
|
+
*/
|
|
81
|
+
export function matchElements(design, impl) {
|
|
82
|
+
const used = new Set();
|
|
83
|
+
const pairs = [];
|
|
84
|
+
const missing = [];
|
|
85
|
+
const take = (d, i, how) => {
|
|
86
|
+
used.add(i);
|
|
87
|
+
pairs.push({ design: d, impl: i, how });
|
|
88
|
+
};
|
|
89
|
+
const pending = design.filter((d) => meaningful(d) && d.visible);
|
|
90
|
+
const byId = new Map(impl.filter((i) => i.id).map((i) => [i.id, i]));
|
|
91
|
+
let rest = [];
|
|
92
|
+
for (const d of pending) {
|
|
93
|
+
const i = d.id ? byId.get(d.id) : null;
|
|
94
|
+
if (i && !used.has(i)) take(d, i, 'id');
|
|
95
|
+
else rest.push(d);
|
|
96
|
+
}
|
|
97
|
+
const strategies = [
|
|
98
|
+
['role-name', (e) => (e.role && e.name ? `${e.role}|${norm(e.name)}` : null)],
|
|
99
|
+
['tag-text', (e) => (e.text ? `${e.tag}|${norm(e.text)}` : null)],
|
|
100
|
+
['role-path', (e) => (e.role ? `${e.role}|${e.path}` : null)],
|
|
101
|
+
];
|
|
102
|
+
for (const [how, keyOf] of strategies) {
|
|
103
|
+
const buckets = new Map();
|
|
104
|
+
for (const i of impl) {
|
|
105
|
+
if (used.has(i)) continue;
|
|
106
|
+
const k = keyOf(i);
|
|
107
|
+
if (k) buckets.set(k, [...(buckets.get(k) ?? []), i]);
|
|
108
|
+
}
|
|
109
|
+
const next = [];
|
|
110
|
+
for (const d of rest) {
|
|
111
|
+
const k = keyOf(d);
|
|
112
|
+
// Same key several times (e.g. three "Save" buttons): pair them in document order.
|
|
113
|
+
const i = k ? buckets.get(k)?.find((x) => !used.has(x)) : undefined;
|
|
114
|
+
if (i) take(d, i, how);
|
|
115
|
+
else next.push(d);
|
|
116
|
+
}
|
|
117
|
+
rest = next;
|
|
118
|
+
}
|
|
119
|
+
for (const d of rest) {
|
|
120
|
+
const sameComp = d.component ? impl.filter((i) => !used.has(i) && i.component === d.component && i.tag === d.tag) : [];
|
|
121
|
+
if (sameComp.length) take(d, sameComp[0], 'component');
|
|
122
|
+
else missing.push(d);
|
|
123
|
+
}
|
|
124
|
+
return { pairs, missing, extraIds: impl.filter((i) => i.id && !design.some((d) => d.id === i.id)).map((i) => i.id) };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// ── comparison ────────────────────────────────────────────────────────────────
|
|
128
|
+
const px = (v) => (/^-?[\d.]+px$/.test(v ?? '') ? parseFloat(v) : null);
|
|
129
|
+
const firstFamily = (v) => norm((v || '').split(',')[0].replace(/["']/g, ''));
|
|
130
|
+
const SIDES = ['top', 'right', 'bottom', 'left'];
|
|
131
|
+
const CORNERS = ['top-left', 'top-right', 'bottom-right', 'bottom-left'];
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Compare matched pairs. Returns findings: { id, element, property, expected, actual, token, severity, message }.
|
|
135
|
+
* @param {{ design: Snapshot, impl: Snapshot, bundleTokens?: any[], tolerances?: Partial<typeof DEFAULT_TOLERANCES>, textAgnostic?: boolean }} o
|
|
136
|
+
*/
|
|
137
|
+
export function compareSnapshots(o) {
|
|
138
|
+
const tol = { ...DEFAULT_TOLERANCES, ...(o.tolerances ?? {}) };
|
|
139
|
+
const tokens = tokenIndex(o.bundleTokens, o.design.tokens ?? {});
|
|
140
|
+
const { pairs, missing, extraIds } = matchElements(o.design.elements, o.impl.elements);
|
|
141
|
+
const findings = [];
|
|
142
|
+
const keyOf = (d) => d.id ?? `${d.role ?? d.tag}:${norm(d.name || d.text).slice(0, 40)}:${d.path}`;
|
|
143
|
+
const add = (d, property, expected, actual, extra = {}) => {
|
|
144
|
+
const label = labelOf(d);
|
|
145
|
+
findings.push({ id: `${keyOf(d)}|${property}`, element: label, property, expected: String(expected), actual: String(actual), token: extra.token ?? undefined, severity: extra.severity ?? 'warning', message: extra.message ?? `${property} ${actual}, design ${expected}${extra.token ? ` = ${extra.token}` : ''}` });
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
for (const d of missing) {
|
|
149
|
+
const important = !!d.id || IMPORTANT_ROLES.has(d.role);
|
|
150
|
+
add(d, 'presence', 'present', 'missing', { severity: important ? 'error' : 'warning', message: `${labelOf(d)} is in the design but not in the implementation` });
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
for (const { design: d, impl: i, how } of pairs) {
|
|
154
|
+
if (d.id && how !== 'id') add(d, 'specimo-id', d.id, 'none', { severity: 'info', message: `matched by ${how}; add data-specimo-id="${d.id}" so parity stays reliable` });
|
|
155
|
+
if (!i.visible) {
|
|
156
|
+
add(d, 'visibility', 'visible', 'hidden', { severity: d.id || IMPORTANT_ROLES.has(d.role) ? 'error' : 'warning', message: `${labelOf(d)} is hidden in the implementation` });
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
const ds = d.styles, is = i.styles;
|
|
160
|
+
// Size (position depends on surrounding content; size is what the design fixes).
|
|
161
|
+
for (const [prop, a, b] of [['width', d.rect.w, i.rect.w], ['height', d.rect.h, i.rect.h]]) {
|
|
162
|
+
if (Math.abs(a - b) > Math.max(tol.sizePx, a * tol.sizeRatio)) add(d, prop, `${a}px`, `${b}px`);
|
|
163
|
+
}
|
|
164
|
+
// Box: padding, border width, radius — grouped when all sides agree.
|
|
165
|
+
const group = (name, keys, prefer) => {
|
|
166
|
+
const diffs = keys.filter((k) => {
|
|
167
|
+
const a = px(ds[k]), b = px(is[k]);
|
|
168
|
+
return a !== null && b !== null ? Math.abs(a - b) > tol.px : (ds[k] ?? '') !== (is[k] ?? '');
|
|
169
|
+
});
|
|
170
|
+
if (!diffs.length) return;
|
|
171
|
+
const same = (s) => keys.every((k) => s[k] === s[keys[0]]);
|
|
172
|
+
if (diffs.length === keys.length && same(ds) && same(is)) {
|
|
173
|
+
const e = ds[keys[0]];
|
|
174
|
+
add(d, name, e, is[keys[0]], { token: px(e) !== null ? tokens.length(px(e), prefer) : null });
|
|
175
|
+
} else for (const k of diffs) add(d, k, ds[k], is[k], { token: px(ds[k]) !== null ? tokens.length(px(ds[k]), prefer) : null });
|
|
176
|
+
};
|
|
177
|
+
group('padding', SIDES.map((s) => `padding-${s}`), ['spacing', 'size']);
|
|
178
|
+
group('border-width', SIDES.map((s) => `border-${s}-width`), ['size', 'other']);
|
|
179
|
+
group('border-radius', CORNERS.map((c) => `border-${c}-radius`), ['radius']);
|
|
180
|
+
if (/flex|grid/.test(ds.display ?? '')) for (const k of ['row-gap', 'column-gap']) {
|
|
181
|
+
const a = px(ds[k]), b = px(is[k]);
|
|
182
|
+
if (a !== null && b !== null && Math.abs(a - b) > tol.px) add(d, k === 'row-gap' ? 'gap' : 'column-gap', ds[k], is[k], { token: tokens.length(a, ['spacing']) });
|
|
183
|
+
}
|
|
184
|
+
// Colour.
|
|
185
|
+
const colorProps = ['color', 'background-color', ...(px(ds['border-top-width']) ? ['border-top-color'] : [])];
|
|
186
|
+
for (const k of colorProps) {
|
|
187
|
+
if (deltaE(ds[k], is[k]) > tol.colorDeltaE) add(d, k === 'border-top-color' ? 'border-color' : k, ds[k], is[k], { token: tokens.color(ds[k]) });
|
|
188
|
+
}
|
|
189
|
+
// Typography.
|
|
190
|
+
if (d.text || d.role === 'button' || d.role === 'link' || d.role === 'heading') {
|
|
191
|
+
if (firstFamily(ds['font-family']) !== firstFamily(is['font-family'])) add(d, 'font-family', firstFamily(ds['font-family']), firstFamily(is['font-family']));
|
|
192
|
+
if (ds['font-weight'] !== is['font-weight']) add(d, 'font-weight', ds['font-weight'], is['font-weight']);
|
|
193
|
+
const fa = px(ds['font-size']), fb = px(is['font-size']);
|
|
194
|
+
if (fa !== null && fb !== null && Math.abs(fa - fb) > tol.fontSizePx) add(d, 'font-size', ds['font-size'], is['font-size'], { token: tokens.length(fa, ['typography', 'size']) });
|
|
195
|
+
const la = px(ds['line-height']), lb = px(is['line-height']);
|
|
196
|
+
if ((la === null) !== (lb === null) ? ds['line-height'] !== is['line-height'] : la !== null && Math.abs(la - lb) > tol.px) add(d, 'line-height', ds['line-height'], is['line-height']);
|
|
197
|
+
const sa = px(ds['letter-spacing']) ?? 0, sb = px(is['letter-spacing']) ?? 0;
|
|
198
|
+
if (Math.abs(sa - sb) > 0.25) add(d, 'letter-spacing', ds['letter-spacing'], is['letter-spacing']);
|
|
199
|
+
if (ds['text-transform'] !== is['text-transform']) add(d, 'text-transform', ds['text-transform'], is['text-transform']);
|
|
200
|
+
}
|
|
201
|
+
// Shadow and opacity.
|
|
202
|
+
const shadow = (v) => (v === 'none' || !v ? 'none' : v.replace(/rgba?\([^)]*\)/g, (c) => c.replace(/\s/g, '')).replace(/\s+/g, ' '));
|
|
203
|
+
if (shadow(ds['box-shadow']) !== shadow(is['box-shadow'])) add(d, 'box-shadow', ds['box-shadow'], is['box-shadow']);
|
|
204
|
+
if (Math.abs(parseFloat(ds.opacity ?? '1') - parseFloat(is.opacity ?? '1')) > 0.05) add(d, 'opacity', ds.opacity, is.opacity);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// A size change that padding, borders or type already explain is noise: keep the cause, drop the symptom.
|
|
208
|
+
const CAUSES = new Set(['padding', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left', 'border-width', 'font-size', 'font-family', 'font-weight', 'line-height', 'letter-spacing', 'gap', 'column-gap', 'text-transform']);
|
|
209
|
+
const explained = new Set(findings.filter((f) => CAUSES.has(f.property)).map((f) => f.id.slice(0, f.id.lastIndexOf('|'))));
|
|
210
|
+
const kept = findings.filter((f) => !((f.property === 'width' || f.property === 'height') && explained.has(f.id.slice(0, f.id.lastIndexOf('|')))));
|
|
211
|
+
const rank = { error: 0, warning: 1, info: 2 };
|
|
212
|
+
kept.sort((a, b) => rank[a.severity] - rank[b.severity]);
|
|
213
|
+
findings.length = 0;
|
|
214
|
+
findings.push(...kept);
|
|
215
|
+
|
|
216
|
+
const designMeaningful = o.design.elements.filter((e) => meaningful(e) && e.visible);
|
|
217
|
+
const coverage = {
|
|
218
|
+
designElements: designMeaningful.length,
|
|
219
|
+
matched: pairs.length,
|
|
220
|
+
byId: pairs.filter((p) => p.how === 'id').length,
|
|
221
|
+
designIds: designMeaningful.filter((e) => e.id).length,
|
|
222
|
+
missing: missing.length,
|
|
223
|
+
extraIds,
|
|
224
|
+
};
|
|
225
|
+
return { findings, coverage };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Worst severity of a set of findings ('info' when empty). */
|
|
229
|
+
export function worstSeverity(findings) {
|
|
230
|
+
return findings.some((f) => f.severity === 'error') ? 'error' : findings.some((f) => f.severity === 'warning') ? 'warning' : 'info';
|
|
231
|
+
}
|
package/src/index.js
ADDED
package/src/pixel.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pixel layer (evidence, not the main signal — ADR-022). Same algorithm as Visual QA (DSGN-51): per-channel
|
|
3
|
+
* tolerance, 24 px cells with ≥ 8 % mismatching pixels merged into regions, a faded diff image. Different page heights
|
|
4
|
+
* are padded with white and reported, never thrown. Runs in a blank browser page (canvas), so no native image deps.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** Runs inside the browser. Inputs are PNG base64 of the same width. */
|
|
8
|
+
async function pixelDiffInPage({ design, impl, tolerance, maxHeight }) {
|
|
9
|
+
const load = (b64) =>
|
|
10
|
+
new Promise((resolve, reject) => {
|
|
11
|
+
const img = new Image();
|
|
12
|
+
img.onload = () => resolve(img);
|
|
13
|
+
img.onerror = () => reject(new Error('Unreadable image'));
|
|
14
|
+
img.src = `data:image/png;base64,${b64}`;
|
|
15
|
+
});
|
|
16
|
+
const [d, i] = await Promise.all([load(design), load(impl)]);
|
|
17
|
+
const width = d.naturalWidth;
|
|
18
|
+
const designH = Math.min(d.naturalHeight, maxHeight);
|
|
19
|
+
const implH = Math.min(Math.round(i.naturalHeight * (width / i.naturalWidth)), maxHeight);
|
|
20
|
+
const H = Math.max(designH, implH);
|
|
21
|
+
const canvas = (h) => Object.assign(document.createElement('canvas'), { width, height: h });
|
|
22
|
+
const paint = (img, w, h) => {
|
|
23
|
+
const c = canvas(H);
|
|
24
|
+
const x = c.getContext('2d');
|
|
25
|
+
x.fillStyle = '#fff';
|
|
26
|
+
x.fillRect(0, 0, width, H);
|
|
27
|
+
x.drawImage(img, 0, 0, w, h);
|
|
28
|
+
return x.getImageData(0, 0, width, H).data;
|
|
29
|
+
};
|
|
30
|
+
const a = paint(d, width, d.naturalHeight);
|
|
31
|
+
const b = paint(i, width, Math.round(i.naturalHeight * (width / i.naturalWidth)));
|
|
32
|
+
const out = new ImageData(width, H);
|
|
33
|
+
const o = out.data;
|
|
34
|
+
const limit = Math.round((tolerance / 100) * 255);
|
|
35
|
+
const CELL = 24;
|
|
36
|
+
const cols = Math.ceil(width / CELL), rows = Math.ceil(H / CELL);
|
|
37
|
+
const cellBad = new Uint32Array(cols * rows);
|
|
38
|
+
let bad = 0;
|
|
39
|
+
for (let y = 0; y < H; y++) {
|
|
40
|
+
for (let x = 0; x < width; x++) {
|
|
41
|
+
const p = (y * width + x) * 4;
|
|
42
|
+
const diff = Math.max(Math.abs(a[p] - b[p]), Math.abs(a[p + 1] - b[p + 1]), Math.abs(a[p + 2] - b[p + 2]));
|
|
43
|
+
if (diff > limit) {
|
|
44
|
+
bad++;
|
|
45
|
+
cellBad[Math.floor(y / CELL) * cols + Math.floor(x / CELL)]++;
|
|
46
|
+
o[p] = 230; o[p + 1] = 0; o[p + 2] = 64; o[p + 3] = 255;
|
|
47
|
+
} else {
|
|
48
|
+
const g = 255 - Math.round((255 - (b[p] * 0.3 + b[p + 1] * 0.59 + b[p + 2] * 0.11)) * 0.25);
|
|
49
|
+
o[p] = g; o[p + 1] = g; o[p + 2] = g; o[p + 3] = 255;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const oc = canvas(H);
|
|
54
|
+
oc.getContext('2d').putImageData(out, 0, 0);
|
|
55
|
+
const diff = oc.toDataURL('image/png').split(',')[1];
|
|
56
|
+
const hot = new Uint8Array(cols * rows);
|
|
57
|
+
for (let k = 0; k < hot.length; k++) hot[k] = cellBad[k] >= CELL * CELL * 0.08 ? 1 : 0;
|
|
58
|
+
const seen = new Uint8Array(cols * rows);
|
|
59
|
+
const regions = [];
|
|
60
|
+
for (let k = 0; k < hot.length; k++) {
|
|
61
|
+
if (!hot[k] || seen[k]) continue;
|
|
62
|
+
let minC = cols, minR = rows, maxC = 0, maxR = 0, pixels = 0;
|
|
63
|
+
const stack = [k];
|
|
64
|
+
seen[k] = 1;
|
|
65
|
+
while (stack.length) {
|
|
66
|
+
const c = stack.pop();
|
|
67
|
+
const cx = c % cols, cy = Math.floor(c / cols);
|
|
68
|
+
minC = Math.min(minC, cx); maxC = Math.max(maxC, cx); minR = Math.min(minR, cy); maxR = Math.max(maxR, cy);
|
|
69
|
+
pixels += cellBad[c];
|
|
70
|
+
for (const n of [cx > 0 ? c - 1 : -1, cx < cols - 1 ? c + 1 : -1, cy > 0 ? c - cols : -1, cy < rows - 1 ? c + cols : -1]) {
|
|
71
|
+
if (n >= 0 && hot[n] && !seen[n]) { seen[n] = 1; stack.push(n); }
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const x = minC * CELL, y = minR * CELL;
|
|
75
|
+
const w = Math.min((maxC + 1) * CELL, width) - x, h = Math.min((maxR + 1) * CELL, H) - y;
|
|
76
|
+
regions.push({ x, y, w, h, percent: Math.round((pixels / (w * h)) * 1000) / 10 });
|
|
77
|
+
}
|
|
78
|
+
regions.sort((p, q) => q.w * q.h * q.percent - p.w * p.h * p.percent);
|
|
79
|
+
return {
|
|
80
|
+
mismatchRatio: Math.round((bad / (width * H)) * 1e5) / 1e5,
|
|
81
|
+
width,
|
|
82
|
+
height: H,
|
|
83
|
+
regions: regions.slice(0, 20),
|
|
84
|
+
diff,
|
|
85
|
+
sizes: designH !== implH ? { design: [width, designH], impl: [i.naturalWidth, i.naturalHeight] } : null,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Compare two full-page PNGs.
|
|
91
|
+
* @param {import('playwright-core').BrowserContext} ctx
|
|
92
|
+
* @param {Buffer} design
|
|
93
|
+
* @param {Buffer} impl
|
|
94
|
+
* @param {{ tolerance?: number, maxHeight?: number }} [opts] tolerance = per-channel percent (default 10)
|
|
95
|
+
*/
|
|
96
|
+
export async function pixelCompare(ctx, design, impl, opts = {}) {
|
|
97
|
+
const page = await ctx.newPage();
|
|
98
|
+
try {
|
|
99
|
+
const r = await page.evaluate(pixelDiffInPage, { design: design.toString('base64'), impl: impl.toString('base64'), tolerance: opts.tolerance ?? 10, maxHeight: opts.maxHeight ?? 16000 });
|
|
100
|
+
return { ...r, diff: Buffer.from(r.diff, 'base64') };
|
|
101
|
+
} finally {
|
|
102
|
+
await page.close().catch(() => undefined);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Full-page screenshot at the viewport width, animations disabled. */
|
|
107
|
+
export async function fullPageShot(page, width, maxHeight = 16000) {
|
|
108
|
+
const h = await page.evaluate(() => Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0)).catch(() => 0);
|
|
109
|
+
const vh = page.viewportSize()?.height ?? 900;
|
|
110
|
+
// fullPage so content below the fold is captured; clip caps the height of endless pages.
|
|
111
|
+
return page.screenshot({ type: 'png', animations: 'disabled', fullPage: true, clip: { x: 0, y: 0, width, height: Math.min(Math.max(h, vh), maxHeight) } });
|
|
112
|
+
}
|
package/src/report.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Markdown report for CI job summaries and the local report file (DSGN-182/183). */
|
|
2
|
+
const ICON = { passed: 'Passed', warnings: 'Warnings', failed: 'Failed', error: 'Could not run' };
|
|
3
|
+
const SEV = { error: 'error', warning: 'warning', info: 'info' };
|
|
4
|
+
const esc = (s) => String(s ?? '').replace(/\|/g, '\\|').replace(/\n/g, ' ');
|
|
5
|
+
|
|
6
|
+
/** @param {{ status: string, exitCode: number, runUrl?: string|null, results: any[], repo?: string, prNumber?: number, commitSha?: string }} r */
|
|
7
|
+
export function renderMarkdown(r) {
|
|
8
|
+
const lines = [`## Specimo shipped parity: ${ICON[r.status] ?? r.status}`, ''];
|
|
9
|
+
const scope = [r.repo && r.prNumber ? `${r.repo}#${r.prNumber}` : r.repo, r.commitSha ? `commit ${String(r.commitSha).slice(0, 7)}` : null].filter(Boolean).join(' · ');
|
|
10
|
+
if (scope) lines.push(scope, '');
|
|
11
|
+
if (!r.results.length) lines.push('Nothing was checked.');
|
|
12
|
+
const byScreen = new Map();
|
|
13
|
+
for (const x of r.results) byScreen.set(x.screen, [...(byScreen.get(x.screen) ?? []), x]);
|
|
14
|
+
const rank = { error: 2, warning: 1, info: 0 };
|
|
15
|
+
const rows = [...byScreen.entries()].map(([screen, rs]) => {
|
|
16
|
+
const worst = rs.reduce((w, x) => (rank[x.severity] > rank[w] ? x.severity : w), 'info');
|
|
17
|
+
const infra = rs.some((x) => x.category === 'infra' && x.severity === 'error');
|
|
18
|
+
const findings = rs.flatMap((x) => (x.findings ?? []).filter((f) => f.severity !== 'info').map((f) => ({ ...f, where: x.scenario ? `${x.scenario.viewport}/${x.scenario.theme}` : '' })));
|
|
19
|
+
findings.sort((a, b) => rank[b.severity] - rank[a.severity]);
|
|
20
|
+
return { screen, worst, infra, findings, rs };
|
|
21
|
+
});
|
|
22
|
+
rows.sort((a, b) => Number(b.infra) - Number(a.infra) || rank[b.worst] - rank[a.worst]);
|
|
23
|
+
if (rows.length) {
|
|
24
|
+
lines.push('| Screen | Result | Top findings |', '| --- | --- | --- |');
|
|
25
|
+
for (const row of rows) {
|
|
26
|
+
const result = row.infra ? 'could not run' : row.worst === 'info' ? 'matches the design' : `${row.findings.length} ${row.worst === 'error' ? 'blocking' : 'warning'}${row.findings.length === 1 ? '' : 's'}`;
|
|
27
|
+
const top = row.findings.slice(0, 3).map((f) => `${SEV[f.severity]}: ${esc(f.element && f.element !== 'page' ? `${f.element}: ` : '')}${esc(f.message)}${f.where ? ` (${f.where})` : ''}`).join('<br>') || '';
|
|
28
|
+
const name = r.screenUrl ? `[${esc(row.screen)}](${r.screenUrl(row.screen)})` : esc(row.screen);
|
|
29
|
+
lines.push(`| ${name} | ${result} | ${top} |`);
|
|
30
|
+
}
|
|
31
|
+
lines.push('');
|
|
32
|
+
}
|
|
33
|
+
if (r.runUrl) lines.push(`Screen names link to their Shipped tab in Specimo, where designers can accept or flag each difference.`, '');
|
|
34
|
+
lines.push(r.exitCode === 2 ? 'The check could not run completely: fix the setup above, it is never counted as a pass.' : r.exitCode === 1 ? 'Blocking findings: fix them, or ask a designer to accept the deviation in Specimo.' : 'No blocking findings.');
|
|
35
|
+
return lines.join('\n');
|
|
36
|
+
}
|
package/src/run.js
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `specimo check` runner (DSGN-182, Tier 1). For each selected screen × viewport × theme: render the approved design
|
|
3
|
+
* (signed reference URL from the bundle) and the app (baseURL + route) in the same Chromium with the same viewport,
|
|
4
|
+
* scale, locale, timezone and reduced motion; compare elements and pixels; apply the policy; report and upload.
|
|
5
|
+
* Never a silent pass: an unreachable app or a broken page is an infra error (exit 2).
|
|
6
|
+
*/
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { execFileSync } from 'node:child_process';
|
|
10
|
+
import { collectInPage } from './collect.js';
|
|
11
|
+
import { compareSnapshots, worstSeverity } from './compare.js';
|
|
12
|
+
import { pixelCompare, fullPageShot } from './pixel.js';
|
|
13
|
+
import { renderMarkdown } from './report.js';
|
|
14
|
+
|
|
15
|
+
export const VIEWPORTS = { desktop: { width: 1440, height: 900 }, tablet: { width: 768, height: 1024 }, mobile: { width: 390, height: 844 } };
|
|
16
|
+
export const DEFAULT_CHECKS = {
|
|
17
|
+
parity: { severity: 'warning', maxDiffRatio: 0.02, pixelTolerance: 10 },
|
|
18
|
+
coverage: { severity: 'warning' },
|
|
19
|
+
};
|
|
20
|
+
const SEVERITY_RANK = { info: 0, warning: 1, error: 2 };
|
|
21
|
+
const FREEZE_CSS = '*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important;scroll-behavior:auto!important}';
|
|
22
|
+
|
|
23
|
+
/** Same key as the API (parity.service fingerprintOf): one finding of one scenario on one design version. */
|
|
24
|
+
export const fingerprintOf = (version, scenario, category, findingId) => `v${version ?? 0}|${[scenario.state, scenario.fixture ?? '', scenario.theme, scenario.viewport].join('|')}|${category}|${findingId}`;
|
|
25
|
+
|
|
26
|
+
/** Findings a designer accepted in Specimo stay visible but count as info. */
|
|
27
|
+
export function applyWaivers(findings, waivers, screen, version, scenario, category) {
|
|
28
|
+
const keys = new Set((waivers ?? []).filter((w) => w.screen === screen).map((w) => w.fingerprint));
|
|
29
|
+
if (!keys.size) return findings;
|
|
30
|
+
const whole = keys.has(fingerprintOf(version, scenario, category, '*'));
|
|
31
|
+
return findings.map((f) => (whole || (f.id && keys.has(fingerprintOf(version, scenario, category, f.id))) ? { ...f, severity: 'info', accepted: true } : f));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Apply a check's policy severity to a finding: off drops it, warning caps errors at warning, error keeps them. */
|
|
35
|
+
export function applyPolicy(findings, severity) {
|
|
36
|
+
if (severity === 'off') return [];
|
|
37
|
+
return findings.map((f) => (severity === 'warning' && f.severity === 'error' ? { ...f, severity: 'warning' } : f));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function mergeChecks(checks = {}) {
|
|
41
|
+
const out = {};
|
|
42
|
+
for (const k of new Set([...Object.keys(DEFAULT_CHECKS), ...Object.keys(checks)])) out[k] = { ...(DEFAULT_CHECKS[k] ?? {}), ...(checks[k] ?? {}) };
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 0 = nothing blocking, 1 = blocking findings, 2 = infrastructure / setup failure. */
|
|
47
|
+
export function exitCodeFor(results) {
|
|
48
|
+
if (results.some((r) => r.category === 'infra' && r.severity === 'error')) return 2;
|
|
49
|
+
if (results.some((r) => r.severity === 'error')) return 1;
|
|
50
|
+
return 0;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Repository context from CI env or git. */
|
|
54
|
+
export function gitContext(env = process.env, cwd = process.cwd()) {
|
|
55
|
+
const git = (...a) => {
|
|
56
|
+
try {
|
|
57
|
+
return execFileSync('git', a, { cwd, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim() || undefined;
|
|
58
|
+
} catch {
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
let prNumber;
|
|
63
|
+
const m = (env.GITHUB_REF ?? '').match(/^refs\/pull\/(\d+)\//);
|
|
64
|
+
if (m) prNumber = Number(m[1]);
|
|
65
|
+
else if (env.CI_MERGE_REQUEST_IID) prNumber = Number(env.CI_MERGE_REQUEST_IID);
|
|
66
|
+
return {
|
|
67
|
+
repo: env.GITHUB_REPOSITORY || env.CI_PROJECT_PATH || undefined,
|
|
68
|
+
prNumber,
|
|
69
|
+
commitSha: env.GITHUB_SHA || env.CI_COMMIT_SHA || git('rev-parse', 'HEAD'),
|
|
70
|
+
branch: env.GITHUB_HEAD_REF || env.CI_MERGE_REQUEST_SOURCE_BRANCH_NAME || env.CI_COMMIT_REF_NAME || git('rev-parse', '--abbrev-ref', 'HEAD'),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
class Api {
|
|
75
|
+
constructor(base, token, userAgent) {
|
|
76
|
+
this.base = base.replace(/\/+$/, '');
|
|
77
|
+
this.token = token;
|
|
78
|
+
this.ua = userAgent;
|
|
79
|
+
}
|
|
80
|
+
async req(method, p, body) {
|
|
81
|
+
let res;
|
|
82
|
+
try {
|
|
83
|
+
res = await fetch(`${this.base}${p}`, { method, headers: { authorization: `Bearer ${this.token}`, 'content-type': 'application/json', 'user-agent': this.ua }, body: body ? JSON.stringify(body) : undefined });
|
|
84
|
+
} catch (e) {
|
|
85
|
+
throw new Error(`cannot reach ${this.base}: ${e.message}`);
|
|
86
|
+
}
|
|
87
|
+
const text = await res.text();
|
|
88
|
+
let json;
|
|
89
|
+
try {
|
|
90
|
+
json = JSON.parse(text);
|
|
91
|
+
} catch {
|
|
92
|
+
json = { message: text.slice(0, 200) };
|
|
93
|
+
}
|
|
94
|
+
if (!res.ok) throw Object.assign(new Error(`${method} ${p}: ${res.status} ${json.message ?? ''}`.trim()), { status: res.status });
|
|
95
|
+
return json;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function settle(page, readyTimeout) {
|
|
100
|
+
await page.waitForLoadState('networkidle', { timeout: readyTimeout }).catch(() => undefined);
|
|
101
|
+
await page.evaluate(() => document.fonts && document.fonts.ready).catch(() => undefined);
|
|
102
|
+
if (await page.locator('[data-specimo-ready]').count().catch(() => 0)) await page.locator('[data-specimo-ready]').first().waitFor({ timeout: readyTimeout }).catch(() => undefined);
|
|
103
|
+
// Layout stable for 300 ms (max 3 s).
|
|
104
|
+
await page
|
|
105
|
+
.evaluate(
|
|
106
|
+
() =>
|
|
107
|
+
new Promise((resolve) => {
|
|
108
|
+
let last = '', stableSince = performance.now();
|
|
109
|
+
const t0 = performance.now();
|
|
110
|
+
const tick = () => {
|
|
111
|
+
const h = `${document.documentElement.scrollHeight}x${document.documentElement.scrollWidth}x${document.body ? document.body.innerHTML.length : 0}`;
|
|
112
|
+
if (h !== last) { last = h; stableSince = performance.now(); }
|
|
113
|
+
if (performance.now() - stableSince > 300 || performance.now() - t0 > 3000) resolve(undefined);
|
|
114
|
+
else requestAnimationFrame(tick);
|
|
115
|
+
};
|
|
116
|
+
tick();
|
|
117
|
+
}),
|
|
118
|
+
)
|
|
119
|
+
.catch(() => undefined);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function referenceUrl(screen, scenario, bundle) {
|
|
123
|
+
const u = new URL(screen.reference.url);
|
|
124
|
+
u.searchParams.set('state', scenario.state);
|
|
125
|
+
u.searchParams.set('motion', 'reduce');
|
|
126
|
+
if (scenario.theme === 'dark') {
|
|
127
|
+
u.searchParams.set('scheme', 'dark');
|
|
128
|
+
const themeCol = (bundle.modes ?? []).find((c) => /^(theme|color|colour|scheme|mode)s?$/i.test(c.name) && c.modes.includes('dark'));
|
|
129
|
+
if (themeCol) u.searchParams.set('modes', `${themeCol.name}:dark`);
|
|
130
|
+
}
|
|
131
|
+
return u.toString();
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* @param {{ api: string, token: string, project: string, baseURL: string, screens?: string[], all?: boolean, viewports?: string[], themes?: string[],
|
|
136
|
+
* checks?: object, screenConfig?: Record<string, { route?: string, version?: number }>, version?: string, upload?: boolean, outDir?: string,
|
|
137
|
+
* readyTimeoutMs?: number, chromium?: any, log?: (s: string) => void, env?: Record<string,string|undefined>, userAgent?: string }} o
|
|
138
|
+
*/
|
|
139
|
+
export async function runCheck(o) {
|
|
140
|
+
const log = o.log ?? ((s) => process.stdout.write(`${s}\n`));
|
|
141
|
+
const checks = mergeChecks(o.checks);
|
|
142
|
+
const api = new Api(o.api, o.token, o.userAgent ?? 'specimo-check');
|
|
143
|
+
const startedAt = new Date();
|
|
144
|
+
const results = [];
|
|
145
|
+
const images = new Map(); // result index → { expected, actual, diff }
|
|
146
|
+
const viewports = (o.viewports?.length ? o.viewports : ['desktop']).filter((v) => VIEWPORTS[v]);
|
|
147
|
+
const themes = o.themes?.length ? o.themes : ['light'];
|
|
148
|
+
const readyTimeout = o.readyTimeoutMs ?? 10000;
|
|
149
|
+
const infra = (screen, message, extra = {}) => results.push({ screen, category: 'infra', severity: 'error', scenario: extra.scenario, findings: [{ severity: 'error', message }] });
|
|
150
|
+
|
|
151
|
+
// 1. The approved design (one bundle per pinned version).
|
|
152
|
+
const cfg = o.screenConfig ?? {};
|
|
153
|
+
const pinned = new Map();
|
|
154
|
+
for (const [k, v] of Object.entries(cfg)) if (v?.version) pinned.set(k, v.version);
|
|
155
|
+
let bundle;
|
|
156
|
+
try {
|
|
157
|
+
const sel = o.screens?.length ? o.screens : null;
|
|
158
|
+
const base = await api.req('GET', `/api/v1/projects/${o.project}/parity/bundle?version=${encodeURIComponent(o.version ?? 'approved')}${sel ? `&screens=${encodeURIComponent(sel.filter((s) => !pinned.has(s)).join(','))}` : ''}`);
|
|
159
|
+
bundle = base;
|
|
160
|
+
for (const [k, v] of pinned) {
|
|
161
|
+
if (sel && !sel.includes(k)) continue;
|
|
162
|
+
const b = await api.req('GET', `/api/v1/projects/${o.project}/parity/bundle?version=${v}&screens=${encodeURIComponent(k)}`);
|
|
163
|
+
bundle.screens = [...bundle.screens.filter((s) => s.key !== k), ...b.screens];
|
|
164
|
+
bundle.missing = [...bundle.missing.filter((m) => m.key !== k), ...b.missing];
|
|
165
|
+
}
|
|
166
|
+
} catch (e) {
|
|
167
|
+
infra('*', `Couldn't load the approved design from Specimo: ${e.message}`);
|
|
168
|
+
return finish();
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// 2. Which screens: explicit list, else every screen with a route (from Specimo or .specimo.json).
|
|
172
|
+
const routeOf = (s) => cfg[s.key]?.route ?? s.route;
|
|
173
|
+
const explicit = !!o.screens?.length;
|
|
174
|
+
let targets = bundle.screens.filter((s) => (explicit ? o.screens.includes(s.key) : true));
|
|
175
|
+
for (const m of bundle.missing ?? []) {
|
|
176
|
+
if (!o.screens?.length && m.reason === 'no_approved_version') continue; // drafts are simply not checked yet
|
|
177
|
+
results.push({ screen: m.key, category: 'coverage', severity: 'warning', findings: [{ severity: 'warning', message: m.reason === 'not_found' ? `Screen "${m.key}" doesn't exist in Specimo` : m.reason === 'no_approved_version' ? `Screen "${m.key}" has no approved version to check against` : `Screen "${m.key}" has no version ${pinned.get(m.key) ?? ''}` }] });
|
|
178
|
+
}
|
|
179
|
+
for (const s of targets.filter((s) => !routeOf(s))) {
|
|
180
|
+
// Asked for explicitly → a warning; otherwise a note (modals and partials often have no route of their own).
|
|
181
|
+
const sev = explicit ? 'warning' : 'info';
|
|
182
|
+
results.push({ screen: s.key, version: s.version, category: 'coverage', severity: sev, findings: [{ severity: sev, message: `Screen "${s.key}" has no route, so it wasn't checked: set one in Specimo or in .specimo.json → check.screens.${s.key}.route` }] });
|
|
183
|
+
}
|
|
184
|
+
targets = targets.filter((s) => routeOf(s));
|
|
185
|
+
if (!targets.length && !results.length) results.push({ screen: '*', category: 'coverage', severity: 'warning', findings: [{ severity: 'warning', message: 'No screens to check: give screens a route in Specimo, or list them with --screen' }] });
|
|
186
|
+
|
|
187
|
+
// 3. Render and compare.
|
|
188
|
+
const chromium = o.chromium ?? (await import('playwright-core')).chromium;
|
|
189
|
+
let browser;
|
|
190
|
+
try {
|
|
191
|
+
browser = await chromium.launch();
|
|
192
|
+
} catch (e) {
|
|
193
|
+
infra('*', `Couldn't start Chromium: ${e.message.split('\n')[0]}. Run \`npx playwright install chromium\`.`);
|
|
194
|
+
return finish();
|
|
195
|
+
}
|
|
196
|
+
const tokenVars = (bundle.tokens ?? []).map((t) => t.cssVar);
|
|
197
|
+
try {
|
|
198
|
+
for (const s of targets) {
|
|
199
|
+
for (const vpName of viewports) {
|
|
200
|
+
for (const theme of themes) {
|
|
201
|
+
const vp = VIEWPORTS[vpName];
|
|
202
|
+
const scenario = { state: 'default', theme, viewport: vpName, width: vp.width, height: vp.height };
|
|
203
|
+
const ctx = await browser.newContext({ viewport: vp, deviceScaleFactor: 1, locale: 'en-US', timezoneId: 'UTC', reducedMotion: 'reduce', colorScheme: theme === 'dark' ? 'dark' : 'light' });
|
|
204
|
+
try {
|
|
205
|
+
const shoot = async (url, what) => {
|
|
206
|
+
const page = await ctx.newPage();
|
|
207
|
+
page.setDefaultTimeout(readyTimeout * 3);
|
|
208
|
+
const res = await page.goto(url, { waitUntil: 'load', timeout: readyTimeout * 3 });
|
|
209
|
+
if (res && res.status() >= 400) throw new Error(`${what} answered HTTP ${res.status()}`);
|
|
210
|
+
await page.addStyleTag({ content: FREEZE_CSS }).catch(() => undefined);
|
|
211
|
+
await settle(page, readyTimeout);
|
|
212
|
+
const snap = await page.evaluate(collectInPage, { tokenVars });
|
|
213
|
+
const png = await fullPageShot(page, vp.width);
|
|
214
|
+
await page.close();
|
|
215
|
+
return { snap, png };
|
|
216
|
+
};
|
|
217
|
+
let design, impl;
|
|
218
|
+
try {
|
|
219
|
+
design = await shoot(referenceUrl(s, scenario, bundle), 'The approved design');
|
|
220
|
+
} catch (e) {
|
|
221
|
+
infra(s.key, `Couldn't render the approved design: ${e.message.split('\n')[0]}`, { scenario });
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
const appUrl = new URL(routeOf(s), o.baseURL).toString();
|
|
225
|
+
try {
|
|
226
|
+
impl = await shoot(appUrl, appUrl);
|
|
227
|
+
} catch (e) {
|
|
228
|
+
infra(s.key, `Couldn't load the app at ${appUrl}: ${e.message.split('\n')[0]}`, { scenario });
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
// Text content legitimately differs until fixtures are bound (Phase 2), so text is not compared here.
|
|
232
|
+
const cmp = compareSnapshots({ design: design.snap, impl: impl.snap, bundleTokens: bundle.tokens, tolerances: checks.parity.tolerances });
|
|
233
|
+
const px = await pixelCompare(ctx, design.png, impl.png, { tolerance: checks.parity.pixelTolerance });
|
|
234
|
+
const visualFindings = cmp.findings.filter((f) => f.property !== 'specimo-id');
|
|
235
|
+
if (px.mismatchRatio > checks.parity.maxDiffRatio) visualFindings.push({ id: `${s.key}|pixels`, element: 'page', property: 'pixels', expected: `≤ ${checks.parity.maxDiffRatio * 100}%`, actual: `${Math.round(px.mismatchRatio * 1000) / 10}%`, severity: 'warning', message: `${Math.round(px.mismatchRatio * 1000) / 10}% of pixels differ (allowed ${checks.parity.maxDiffRatio * 100}%)${px.sizes ? `; page height ${px.sizes.impl[1]}px vs design ${px.sizes.design[1]}px` : ''}` });
|
|
236
|
+
const vf = applyWaivers(applyPolicy(visualFindings, checks.parity.severity), bundle.waivers, s.key, s.version, scenario, 'visual');
|
|
237
|
+
if (checks.parity.severity !== 'off') {
|
|
238
|
+
results.push({ screen: s.key, version: s.version, scenario, category: 'visual', severity: worstSeverity(vf), mismatchRatio: px.mismatchRatio, threshold: checks.parity.maxDiffRatio, findings: vf.slice(0, 200) });
|
|
239
|
+
images.set(results.length - 1, { expected: design.png, actual: impl.png, diff: px.diff });
|
|
240
|
+
}
|
|
241
|
+
const idHints = cmp.findings.filter((f) => f.property === 'specimo-id');
|
|
242
|
+
const cf = applyPolicy(idHints.map((f) => ({ ...f, severity: 'info' })), checks.coverage.severity);
|
|
243
|
+
if (cf.length) results.push({ screen: s.key, version: s.version, scenario, category: 'coverage', severity: worstSeverity(cf), findings: cf.slice(0, 200) });
|
|
244
|
+
} finally {
|
|
245
|
+
await ctx.close().catch(() => undefined);
|
|
246
|
+
}
|
|
247
|
+
log(` ${s.key} · ${vpName} · ${theme}: ${describe(results.filter((r) => r.screen === s.key && r.scenario?.viewport === vpName && r.scenario?.theme === theme))}`);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
} finally {
|
|
252
|
+
await browser.close().catch(() => undefined);
|
|
253
|
+
}
|
|
254
|
+
return finish();
|
|
255
|
+
|
|
256
|
+
async function finish() {
|
|
257
|
+
const exitCode = exitCodeFor(results);
|
|
258
|
+
const run = { source: 'ci', ...gitContext(o.env), policy: checks, runner: { name: '@specimo/check', version: o.runnerVersion ?? '0.0.0' }, startedAt, finishedAt: new Date(), results };
|
|
259
|
+
let uploaded = null;
|
|
260
|
+
if (o.upload !== false && results.length && api.token) {
|
|
261
|
+
try {
|
|
262
|
+
uploaded = await api.req('POST', `/api/v1/projects/${o.project}/parity/runs`, run);
|
|
263
|
+
for (const [i, imgs] of images) {
|
|
264
|
+
const r = results[i];
|
|
265
|
+
if (r.severity === 'info') continue; // only evidence for what needs attention
|
|
266
|
+
const id = uploaded.results[i]?.id;
|
|
267
|
+
if (!id) continue;
|
|
268
|
+
for (const [kind, buf] of Object.entries(imgs)) await api.req('PUT', `/api/v1/projects/${o.project}/parity/results/${id}/images/${kind}`, { image: buf.toString('base64') }).catch((e) => log(` (image upload failed: ${e.message})`));
|
|
269
|
+
}
|
|
270
|
+
} catch (e) {
|
|
271
|
+
log(`Couldn't upload the results to Specimo: ${e.message}`);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
const report = { status: statusOf(results), exitCode, runId: uploaded?.id ?? null, runUrl: uploaded && o.appUrl ? `${o.appUrl.replace(/\/+$/, '')}/projects/${o.project}/screens` : null, ...run };
|
|
275
|
+
const screenUrl = uploaded && o.appUrl ? (key) => `${o.appUrl.replace(/\/+$/, '')}/projects/${o.project}/screens/${encodeURIComponent(key)}?mode=shipped` : null;
|
|
276
|
+
const md = renderMarkdown({ ...report, screenUrl: screenUrl && ((k) => (k === '*' ? report.runUrl : screenUrl(k))) });
|
|
277
|
+
if (o.outDir) {
|
|
278
|
+
fs.mkdirSync(o.outDir, { recursive: true });
|
|
279
|
+
fs.writeFileSync(path.join(o.outDir, 'report.json'), JSON.stringify(report, null, 2));
|
|
280
|
+
fs.writeFileSync(path.join(o.outDir, 'report.md'), md);
|
|
281
|
+
for (const [i, imgs] of images) for (const [kind, buf] of Object.entries(imgs)) fs.writeFileSync(path.join(o.outDir, `${results[i].screen}-${results[i].scenario.viewport}-${results[i].scenario.theme}-${kind}.png`), buf);
|
|
282
|
+
}
|
|
283
|
+
const summaryFile = (o.env ?? process.env).GITHUB_STEP_SUMMARY;
|
|
284
|
+
if (summaryFile) fs.appendFileSync(summaryFile, `${md}\n`);
|
|
285
|
+
return { ...report, markdown: md };
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function statusOf(results) {
|
|
290
|
+
if (results.some((r) => r.category === 'infra' && r.severity === 'error')) return 'error';
|
|
291
|
+
if (results.some((r) => r.severity === 'error')) return 'failed';
|
|
292
|
+
if (results.some((r) => r.severity === 'warning')) return 'warnings';
|
|
293
|
+
return 'passed';
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function describe(rs) {
|
|
297
|
+
if (!rs.length) return 'nothing to report';
|
|
298
|
+
const worst = rs.reduce((w, r) => (SEVERITY_RANK[r.severity] > SEVERITY_RANK[w] ? r.severity : w), 'info');
|
|
299
|
+
const n = rs.reduce((k, r) => k + (r.findings?.filter((f) => f.severity !== 'info').length ?? 0), 0);
|
|
300
|
+
return worst === 'info' ? 'matches the design' : `${n} finding${n === 1 ? '' : 's'} (${worst})`;
|
|
301
|
+
}
|