@mizchi/vlmkit-core 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/a11y-semantic.d.mts +34 -0
- package/dist/a11y-semantic.mjs +261 -0
- package/dist/arg-reader.d.mts +52 -0
- package/dist/arg-reader.mjs +129 -0
- package/dist/auth-state.d.mts +30 -0
- package/dist/auth-state.mjs +82 -0
- package/dist/authored-style-capture.d.mts +42 -0
- package/dist/authored-style-capture.mjs +117 -0
- package/dist/authored-style-diff.d.mts +15 -0
- package/dist/authored-style-diff.mjs +16 -0
- package/dist/cli-args.d.mts +35 -0
- package/dist/cli-args.mjs +63 -0
- package/dist/cli-error.d.mts +12 -0
- package/dist/cli-error.mjs +71 -0
- package/dist/computed-style-capture.d.mts +41 -0
- package/dist/computed-style-capture.mjs +589 -0
- package/dist/computed-style-diff.d.mts +83 -0
- package/dist/computed-style-diff.mjs +123 -0
- package/dist/diff-regions.d.mts +8 -0
- package/dist/diff-regions.mjs +52 -0
- package/dist/dom-equivalence.d.mts +51 -0
- package/dist/dom-equivalence.mjs +91 -0
- package/dist/dom-position-styles.d.mts +166 -0
- package/dist/dom-position-styles.mjs +296 -0
- package/dist/element-compare.d.mts +71 -0
- package/dist/element-compare.mjs +269 -0
- package/dist/gate-config.d.mts +116 -0
- package/dist/gate-config.mjs +169 -0
- package/dist/gate-exit.d.mts +45 -0
- package/dist/gate-exit.mjs +25 -0
- package/dist/heatmap-regions.d.mts +57 -0
- package/dist/heatmap-regions.mjs +158 -0
- package/dist/heatmap.d.mts +86 -0
- package/dist/heatmap.mjs +510 -0
- package/dist/image-resize.d.mts +34 -0
- package/dist/image-resize.mjs +92 -0
- package/dist/index.d.mts +15 -0
- package/dist/index.mjs +14 -0
- package/dist/legacy-names.d.mts +48 -0
- package/dist/legacy-names.mjs +134 -0
- package/dist/mask.d.mts +18 -0
- package/dist/mask.mjs +27 -0
- package/dist/navigation-redirect.d.mts +28 -0
- package/dist/navigation-redirect.mjs +47 -0
- package/dist/page-open.d.mts +102 -0
- package/dist/page-open.mjs +133 -0
- package/dist/png-utils.d.mts +30 -0
- package/dist/png-utils.mjs +80 -0
- package/dist/region-shift.d.mts +20 -0
- package/dist/region-shift.mjs +128 -0
- package/dist/run-ledger.d.mts +14 -0
- package/dist/run-ledger.mjs +31 -0
- package/dist/terminal-colors.d.mts +12 -0
- package/dist/terminal-colors.mjs +14 -0
- package/dist/text-rows.d.mts +121 -0
- package/dist/text-rows.mjs +246 -0
- package/{src/types.ts → dist/types.d.mts} +88 -206
- package/dist/types.mjs +1 -0
- package/package.json +17 -5
- package/src/a11y-semantic.ts +0 -384
- package/src/authored-style-capture.ts +0 -185
- package/src/authored-style-diff.ts +0 -32
- package/src/cli-args.ts +0 -29
- package/src/cli-error.ts +0 -85
- package/src/computed-style-capture.ts +0 -717
- package/src/computed-style-diff.ts +0 -192
- package/src/diff-regions.ts +0 -70
- package/src/dom-equivalence.ts +0 -158
- package/src/dom-position-styles.ts +0 -457
- package/src/element-compare.ts +0 -354
- package/src/heatmap-regions.ts +0 -245
- package/src/heatmap.ts +0 -670
- package/src/image-resize.ts +0 -112
- package/src/index.ts +0 -105
- package/src/mask.ts +0 -41
- package/src/png-utils.ts +0 -86
- package/src/region-shift.ts +0 -173
- package/src/run-ledger.ts +0 -39
- package/src/terminal-colors.ts +0 -13
- package/src/text-rows.ts +0 -412
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
import { TRACKED_PROPERTIES } from "./computed-style-capture.mjs";
|
|
2
|
+
//#region src/dom-position-styles.ts
|
|
3
|
+
/**
|
|
4
|
+
* DOM-position-based selector alignment for migration diffs.
|
|
5
|
+
*
|
|
6
|
+
* Addresses the killer finding from `docs/reports/2026-05-12-subagent-eval.md`:
|
|
7
|
+
* the migration-VRT scenario is class renames (`.card` → `.luna-panel`),
|
|
8
|
+
* but `diffComputedStyles` matches selectors by literal string and so
|
|
9
|
+
* produces zero verified entries for the entire rename. The subagent
|
|
10
|
+
* eval showed this blind spot lets a fresh agent plateau at 10–24%
|
|
11
|
+
* diff because it has to guess values from PNGs.
|
|
12
|
+
*
|
|
13
|
+
* This module captures `{ path, tag, classes, styles }` per
|
|
14
|
+
* "interesting" element on each page, then matches across baseline and
|
|
15
|
+
* variant by the position `path` (e.g. `main[0]>section[1]>article[0]>div[0]`),
|
|
16
|
+
* which is invariant under class renames. Diff output names both
|
|
17
|
+
* class strings + the property delta so the agent can rewrite the
|
|
18
|
+
* variant's CSS class against the baseline's rendered values.
|
|
19
|
+
*
|
|
20
|
+
* Pure module. The browser-side capture script ships as a string fed
|
|
21
|
+
* to `page.evaluate()`.
|
|
22
|
+
*/
|
|
23
|
+
/** Properties for which em-normalization is informative. */
|
|
24
|
+
const EM_RELATIVE = new Set([
|
|
25
|
+
"letter-spacing",
|
|
26
|
+
"word-spacing",
|
|
27
|
+
"line-height"
|
|
28
|
+
]);
|
|
29
|
+
/** Parent `display` values that coerce inline children to block-ish layouts. */
|
|
30
|
+
const FLEX_OR_GRID_DISPLAYS = new Set([
|
|
31
|
+
"flex",
|
|
32
|
+
"inline-flex",
|
|
33
|
+
"grid",
|
|
34
|
+
"inline-grid"
|
|
35
|
+
]);
|
|
36
|
+
function emEquivalent(value, fontSizePx) {
|
|
37
|
+
if (!value || value === "normal" || value === "auto" || fontSizePx <= 0) return void 0;
|
|
38
|
+
const emMatch = value.match(/^(-?\d+(?:\.\d+)?)em$/);
|
|
39
|
+
if (emMatch) return Number(emMatch[1]);
|
|
40
|
+
const pxMatch = value.match(/^(-?\d+(?:\.\d+)?)px$/);
|
|
41
|
+
if (!pxMatch) return void 0;
|
|
42
|
+
return Number(pxMatch[1]) / fontSizePx;
|
|
43
|
+
}
|
|
44
|
+
function parseFontSizePx(value) {
|
|
45
|
+
if (!value) return 0;
|
|
46
|
+
const m = value.match(/^(\d+(?:\.\d+)?)px$/);
|
|
47
|
+
return m ? Number(m[1]) : 0;
|
|
48
|
+
}
|
|
49
|
+
const EMPTY = {
|
|
50
|
+
entries: [],
|
|
51
|
+
totalDiffs: 0,
|
|
52
|
+
pathsOnlyInBaseline: [],
|
|
53
|
+
pathsOnlyInVariant: [],
|
|
54
|
+
byProperty: [],
|
|
55
|
+
byPath: []
|
|
56
|
+
};
|
|
57
|
+
function diffDomPositionStyles(baseline, variant) {
|
|
58
|
+
if (!baseline?.length || !variant?.length) return EMPTY;
|
|
59
|
+
const baselineMap = /* @__PURE__ */ new Map();
|
|
60
|
+
const variantMap = /* @__PURE__ */ new Map();
|
|
61
|
+
for (const el of baseline) baselineMap.set(el.path, el);
|
|
62
|
+
for (const el of variant) variantMap.set(el.path, el);
|
|
63
|
+
const entries = [];
|
|
64
|
+
const byProperty = /* @__PURE__ */ new Map();
|
|
65
|
+
const byPath = /* @__PURE__ */ new Map();
|
|
66
|
+
const sharedPaths = [];
|
|
67
|
+
for (const path of baselineMap.keys()) if (variantMap.has(path)) sharedPaths.push(path);
|
|
68
|
+
for (const path of sharedPaths) {
|
|
69
|
+
const b = baselineMap.get(path);
|
|
70
|
+
const v = variantMap.get(path);
|
|
71
|
+
if (b.tag !== v.tag) continue;
|
|
72
|
+
const props = new Set([...Object.keys(b.styles), ...Object.keys(v.styles)]);
|
|
73
|
+
const bFontSize = parseFontSizePx(b.styles["font-size"]);
|
|
74
|
+
const vFontSize = parseFontSizePx(v.styles["font-size"]);
|
|
75
|
+
for (const property of props) {
|
|
76
|
+
const bv = b.styles[property] ?? "";
|
|
77
|
+
const vv = v.styles[property] ?? "";
|
|
78
|
+
if (bv === vv) continue;
|
|
79
|
+
const diffEntry = {
|
|
80
|
+
path,
|
|
81
|
+
tag: b.tag,
|
|
82
|
+
baselineClasses: b.classes,
|
|
83
|
+
variantClasses: v.classes,
|
|
84
|
+
property,
|
|
85
|
+
baseline: bv,
|
|
86
|
+
variant: vv
|
|
87
|
+
};
|
|
88
|
+
if (EM_RELATIVE.has(property)) {
|
|
89
|
+
const baselineEm = emEquivalent(bv, bFontSize);
|
|
90
|
+
const variantEm = emEquivalent(vv, vFontSize);
|
|
91
|
+
if (baselineEm !== void 0) diffEntry.baselineEm = Math.round(baselineEm * 1e4) / 1e4;
|
|
92
|
+
if (variantEm !== void 0) diffEntry.variantEm = Math.round(variantEm * 1e4) / 1e4;
|
|
93
|
+
}
|
|
94
|
+
if (property === "display") {
|
|
95
|
+
const bp = b.parentDisplay ?? "";
|
|
96
|
+
const vp = v.parentDisplay ?? "";
|
|
97
|
+
if (bp || vp) diffEntry.parentDisplayContext = {
|
|
98
|
+
baselineParent: bp,
|
|
99
|
+
variantParent: vp,
|
|
100
|
+
isFlexOrGridItem: FLEX_OR_GRID_DISPLAYS.has(bp) || FLEX_OR_GRID_DISPLAYS.has(vp)
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
entries.push(diffEntry);
|
|
104
|
+
byProperty.set(property, (byProperty.get(property) ?? 0) + 1);
|
|
105
|
+
const entry = byPath.get(path) ?? {
|
|
106
|
+
baselineClasses: b.classes,
|
|
107
|
+
variantClasses: v.classes,
|
|
108
|
+
count: 0
|
|
109
|
+
};
|
|
110
|
+
entry.count += 1;
|
|
111
|
+
byPath.set(path, entry);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
const pathsOnlyInBaseline = [...baselineMap.keys()].filter((p) => !variantMap.has(p));
|
|
115
|
+
const pathsOnlyInVariant = [...variantMap.keys()].filter((p) => !baselineMap.has(p));
|
|
116
|
+
const sortedByProperty = [...byProperty.entries()].map(([property, count]) => ({
|
|
117
|
+
property,
|
|
118
|
+
count
|
|
119
|
+
})).sort((a, b) => b.count - a.count || a.property.localeCompare(b.property));
|
|
120
|
+
const sortedByPath = [...byPath.entries()].map(([path, v]) => ({
|
|
121
|
+
path,
|
|
122
|
+
baselineClasses: v.baselineClasses,
|
|
123
|
+
variantClasses: v.variantClasses,
|
|
124
|
+
count: v.count
|
|
125
|
+
})).sort((a, b) => b.count - a.count || a.path.localeCompare(b.path));
|
|
126
|
+
return {
|
|
127
|
+
entries,
|
|
128
|
+
totalDiffs: entries.length,
|
|
129
|
+
pathsOnlyInBaseline,
|
|
130
|
+
pathsOnlyInVariant,
|
|
131
|
+
byProperty: sortedByProperty,
|
|
132
|
+
byPath: sortedByPath
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Browser-side capture script: walks the DOM from `<body>`, emits
|
|
137
|
+
* `{path, tag, classes, styles}` for every element that has a class
|
|
138
|
+
* attribute or is one of the semantic / interactive tags listed below.
|
|
139
|
+
* `path` uses 0-based child indices among ALL children, so it's stable
|
|
140
|
+
* across class renames as long as the tree shape is the same.
|
|
141
|
+
*/
|
|
142
|
+
const DOM_POSITION_STYLES_BROWSER_SCRIPT = `JSON.stringify((function(){
|
|
143
|
+
var TRACKED = ${JSON.stringify(TRACKED_PROPERTIES)};
|
|
144
|
+
var SEMANTIC = new Set([
|
|
145
|
+
"main","header","nav","footer","aside","article","section",
|
|
146
|
+
"h1","h2","h3","h4","h5","h6","p","a","button","input","select","textarea",
|
|
147
|
+
"label","blockquote","pre","code","table","thead","tbody","tr","th","td",
|
|
148
|
+
"ul","ol","li","img","span"
|
|
149
|
+
]);
|
|
150
|
+
var out = [];
|
|
151
|
+
function walk(el, parentPath, indexAmongChildren) {
|
|
152
|
+
var tag = el.tagName.toLowerCase();
|
|
153
|
+
var path = parentPath === "" ? tag + "[0]" : parentPath + ">" + tag + "[" + indexAmongChildren + "]";
|
|
154
|
+
var hasClass = el.hasAttribute && el.hasAttribute("class");
|
|
155
|
+
var interesting = hasClass || SEMANTIC.has(tag);
|
|
156
|
+
if (interesting) {
|
|
157
|
+
var cs = getComputedStyle(el);
|
|
158
|
+
var styles = {};
|
|
159
|
+
for (var i = 0; i < TRACKED.length; i++) {
|
|
160
|
+
var p = TRACKED[i];
|
|
161
|
+
styles[p] = cs.getPropertyValue(p);
|
|
162
|
+
}
|
|
163
|
+
// Capture parent display so the diff layer can flag flex/grid-item coercion.
|
|
164
|
+
var parentDisplay = "";
|
|
165
|
+
if (el.parentElement) {
|
|
166
|
+
try { parentDisplay = getComputedStyle(el.parentElement).getPropertyValue("display"); } catch (e) { parentDisplay = ""; }
|
|
167
|
+
}
|
|
168
|
+
out.push({
|
|
169
|
+
path: path,
|
|
170
|
+
tag: tag,
|
|
171
|
+
classes: (el.getAttribute("class") || "").trim(),
|
|
172
|
+
styles: styles,
|
|
173
|
+
parentDisplay: parentDisplay
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
var children = el.children;
|
|
177
|
+
for (var j = 0; j < children.length; j++) {
|
|
178
|
+
walk(children[j], path, j);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (document.body) walk(document.body, "", 0);
|
|
182
|
+
return out;
|
|
183
|
+
})())`;
|
|
184
|
+
function parseDomPositionStyles(value) {
|
|
185
|
+
if (Array.isArray(value)) return value;
|
|
186
|
+
if (typeof value !== "string") return [];
|
|
187
|
+
try {
|
|
188
|
+
const parsed = JSON.parse(value);
|
|
189
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
190
|
+
} catch {
|
|
191
|
+
return [];
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
const EMPTY_PV = {
|
|
195
|
+
entries: [],
|
|
196
|
+
totalDiffs: 0,
|
|
197
|
+
verifiedPairs: [],
|
|
198
|
+
byPathProperty: [],
|
|
199
|
+
byViewport: [],
|
|
200
|
+
byProperty: [],
|
|
201
|
+
byPath: []
|
|
202
|
+
};
|
|
203
|
+
/**
|
|
204
|
+
* Diff DOM-position style captures across N viewports.
|
|
205
|
+
*
|
|
206
|
+
* Inputs are maps of viewport-label → captured element list. Each viewport
|
|
207
|
+
* is diffed independently (same `diffDomPositionStyles` per-viewport
|
|
208
|
+
* semantics), then results are merged with a viewport label per tuple and
|
|
209
|
+
* a (path, property) cross-viewport aggregate so the agent can spot
|
|
210
|
+
* "this delta appears at every viewport" vs "this delta only appears at
|
|
211
|
+
* mobile" (the latter usually means a missing or wrong media query).
|
|
212
|
+
*/
|
|
213
|
+
function diffPositionStylesAcrossViewports(baselineByVp, variantByVp) {
|
|
214
|
+
const baselineMap = baselineByVp instanceof Map ? baselineByVp : new Map(Object.entries(baselineByVp));
|
|
215
|
+
const variantMap = variantByVp instanceof Map ? variantByVp : new Map(Object.entries(variantByVp));
|
|
216
|
+
if (baselineMap.size === 0 || variantMap.size === 0) return EMPTY_PV;
|
|
217
|
+
const entries = [];
|
|
218
|
+
const byViewport = /* @__PURE__ */ new Map();
|
|
219
|
+
for (const [viewport, baselineList] of baselineMap) {
|
|
220
|
+
const variantList = variantMap.get(viewport);
|
|
221
|
+
if (!variantList) continue;
|
|
222
|
+
const perVp = diffDomPositionStyles(baselineList, variantList);
|
|
223
|
+
for (const e of perVp.entries) entries.push({
|
|
224
|
+
...e,
|
|
225
|
+
viewport
|
|
226
|
+
});
|
|
227
|
+
byViewport.set(viewport, (byViewport.get(viewport) ?? 0) + perVp.entries.length);
|
|
228
|
+
}
|
|
229
|
+
const ppKey = (path, property) => `${path} ${property}`;
|
|
230
|
+
const aggregated = /* @__PURE__ */ new Map();
|
|
231
|
+
for (const e of entries) {
|
|
232
|
+
const k = ppKey(e.path, e.property);
|
|
233
|
+
const sample = {
|
|
234
|
+
viewport: e.viewport,
|
|
235
|
+
baseline: e.baseline,
|
|
236
|
+
variant: e.variant
|
|
237
|
+
};
|
|
238
|
+
if (e.baselineEm !== void 0) sample.baselineEm = e.baselineEm;
|
|
239
|
+
if (e.variantEm !== void 0) sample.variantEm = e.variantEm;
|
|
240
|
+
const existing = aggregated.get(k);
|
|
241
|
+
if (existing) {
|
|
242
|
+
existing.viewports.push(e.viewport);
|
|
243
|
+
if (!existing.samples.some((s) => s.baseline === e.baseline && s.variant === e.variant)) existing.samples.push(sample);
|
|
244
|
+
} else aggregated.set(k, {
|
|
245
|
+
path: e.path,
|
|
246
|
+
property: e.property,
|
|
247
|
+
baselineClasses: e.baselineClasses,
|
|
248
|
+
variantClasses: e.variantClasses,
|
|
249
|
+
viewports: [e.viewport],
|
|
250
|
+
samples: [sample],
|
|
251
|
+
parentDisplayContext: e.parentDisplayContext
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
const byPathProperty = [...aggregated.values()].sort((a, b) => b.viewports.length - a.viewports.length || a.path.localeCompare(b.path) || a.property.localeCompare(b.property));
|
|
255
|
+
const byProperty = /* @__PURE__ */ new Map();
|
|
256
|
+
for (const e of entries) byProperty.set(e.property, (byProperty.get(e.property) ?? 0) + 1);
|
|
257
|
+
const byPath = /* @__PURE__ */ new Map();
|
|
258
|
+
for (const e of entries) {
|
|
259
|
+
const cur = byPath.get(e.path) ?? {
|
|
260
|
+
baselineClasses: e.baselineClasses,
|
|
261
|
+
variantClasses: e.variantClasses,
|
|
262
|
+
count: 0
|
|
263
|
+
};
|
|
264
|
+
cur.count += 1;
|
|
265
|
+
byPath.set(e.path, cur);
|
|
266
|
+
}
|
|
267
|
+
const verifiedPairsSet = /* @__PURE__ */ new Set();
|
|
268
|
+
for (const e of entries) {
|
|
269
|
+
const tokens = e.variantClasses.split(/\s+/).filter(Boolean);
|
|
270
|
+
for (const cls of tokens) verifiedPairsSet.add(`.${cls}::${e.property}`);
|
|
271
|
+
verifiedPairsSet.add(`::${e.property}`);
|
|
272
|
+
}
|
|
273
|
+
const verifiedPairs = [...verifiedPairsSet].sort();
|
|
274
|
+
return {
|
|
275
|
+
entries,
|
|
276
|
+
totalDiffs: entries.length,
|
|
277
|
+
verifiedPairs,
|
|
278
|
+
byPathProperty,
|
|
279
|
+
byViewport: [...byViewport.entries()].map(([viewport, count]) => ({
|
|
280
|
+
viewport,
|
|
281
|
+
count
|
|
282
|
+
})).sort((a, b) => b.count - a.count || a.viewport.localeCompare(b.viewport)),
|
|
283
|
+
byProperty: [...byProperty.entries()].map(([property, count]) => ({
|
|
284
|
+
property,
|
|
285
|
+
count
|
|
286
|
+
})).sort((a, b) => b.count - a.count || a.property.localeCompare(b.property)),
|
|
287
|
+
byPath: [...byPath.entries()].map(([path, v]) => ({
|
|
288
|
+
path,
|
|
289
|
+
baselineClasses: v.baselineClasses,
|
|
290
|
+
variantClasses: v.variantClasses,
|
|
291
|
+
count: v.count
|
|
292
|
+
})).sort((a, b) => b.count - a.count || a.path.localeCompare(b.path))
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
//#endregion
|
|
296
|
+
export { DOM_POSITION_STYLES_BROWSER_SCRIPT, diffDomPositionStyles, diffPositionStylesAcrossViewports, parseDomPositionStyles };
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
//#region src/element-compare.d.ts
|
|
2
|
+
interface ElementCompareOptions {
|
|
3
|
+
/** CSS selectors for elements to compare */
|
|
4
|
+
selectors: string[];
|
|
5
|
+
/** Baseline HTML file path */
|
|
6
|
+
baselineFile?: string;
|
|
7
|
+
/** Current HTML file path */
|
|
8
|
+
currentFile?: string;
|
|
9
|
+
/** Baseline URL */
|
|
10
|
+
baselineUrl?: string;
|
|
11
|
+
/** Current URL */
|
|
12
|
+
currentUrl?: string;
|
|
13
|
+
/** Viewport width/height */
|
|
14
|
+
viewport?: {
|
|
15
|
+
width: number;
|
|
16
|
+
height: number;
|
|
17
|
+
};
|
|
18
|
+
/** Output directory */
|
|
19
|
+
outputDir: string;
|
|
20
|
+
/** Selectors to mask before screenshot */
|
|
21
|
+
maskSelectors?: string[];
|
|
22
|
+
/** pixelmatch threshold */
|
|
23
|
+
threshold?: number;
|
|
24
|
+
}
|
|
25
|
+
interface ElementDiffResult {
|
|
26
|
+
selector: string;
|
|
27
|
+
found: {
|
|
28
|
+
baseline: boolean;
|
|
29
|
+
current: boolean;
|
|
30
|
+
};
|
|
31
|
+
/** Bounding box of the element in baseline */
|
|
32
|
+
baselineBBox?: {
|
|
33
|
+
x: number;
|
|
34
|
+
y: number;
|
|
35
|
+
width: number;
|
|
36
|
+
height: number;
|
|
37
|
+
};
|
|
38
|
+
/** Bounding box of the element in current */
|
|
39
|
+
currentBBox?: {
|
|
40
|
+
x: number;
|
|
41
|
+
y: number;
|
|
42
|
+
width: number;
|
|
43
|
+
height: number;
|
|
44
|
+
};
|
|
45
|
+
diffPixels: number;
|
|
46
|
+
totalPixels: number;
|
|
47
|
+
diffRatio: number;
|
|
48
|
+
heatmapPath?: string;
|
|
49
|
+
baselinePath?: string;
|
|
50
|
+
currentPath?: string;
|
|
51
|
+
}
|
|
52
|
+
interface ElementCompareReport {
|
|
53
|
+
baselineSource: string;
|
|
54
|
+
currentSource: string;
|
|
55
|
+
viewport: {
|
|
56
|
+
width: number;
|
|
57
|
+
height: number;
|
|
58
|
+
};
|
|
59
|
+
elements: ElementDiffResult[];
|
|
60
|
+
summary: {
|
|
61
|
+
total: number;
|
|
62
|
+
matched: number;
|
|
63
|
+
changed: number;
|
|
64
|
+
missing: number; /** Full-page diff ratio (for comparison) */
|
|
65
|
+
fullPageDiffRatio?: number; /** Sum of element-level diff pixels (isolates actual changes from cascading shifts) */
|
|
66
|
+
elementDiffRatio: number;
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
declare function runElementCompare(options: ElementCompareOptions): Promise<ElementCompareReport>;
|
|
70
|
+
//#endregion
|
|
71
|
+
export { ElementCompareOptions, ElementCompareReport, ElementDiffResult, runElementCompare };
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { compareScreenshots } from "./heatmap.mjs";
|
|
3
|
+
import { applyMask, parseMaskSelectors } from "./mask.mjs";
|
|
4
|
+
import { BOLD, CYAN, DIM, GREEN, RED, RESET, YELLOW, hr } from "./terminal-colors.mjs";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
7
|
+
import { chromium } from "playwright";
|
|
8
|
+
//#region src/element-compare.ts
|
|
9
|
+
/**
|
|
10
|
+
* Element-level VRT comparison
|
|
11
|
+
*
|
|
12
|
+
* Instead of full-page pixel diff (which cascades when a header shifts),
|
|
13
|
+
* compares individual DOM elements independently via locator.screenshot().
|
|
14
|
+
*
|
|
15
|
+
* Usage:
|
|
16
|
+
* vlmkit diff elements --url http://localhost:3000/ --current-url http://localhost:8080/ \
|
|
17
|
+
* --selectors "header,main,footer"
|
|
18
|
+
* vlmkit diff elements before.html after.html --selectors "header,.content,.sidebar"
|
|
19
|
+
*/
|
|
20
|
+
async function captureElementScreenshot(page, selector, outputPath) {
|
|
21
|
+
const locator = page.locator(selector).first();
|
|
22
|
+
try {
|
|
23
|
+
await locator.waitFor({
|
|
24
|
+
state: "visible",
|
|
25
|
+
timeout: 3e3
|
|
26
|
+
});
|
|
27
|
+
const bbox = await locator.boundingBox();
|
|
28
|
+
if (!bbox) return { found: false };
|
|
29
|
+
await locator.screenshot({ path: outputPath });
|
|
30
|
+
return {
|
|
31
|
+
found: true,
|
|
32
|
+
bbox: {
|
|
33
|
+
x: Math.round(bbox.x),
|
|
34
|
+
y: Math.round(bbox.y),
|
|
35
|
+
width: Math.round(bbox.width),
|
|
36
|
+
height: Math.round(bbox.height)
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
} catch {
|
|
40
|
+
return { found: false };
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
async function runElementCompare(options) {
|
|
44
|
+
const { selectors, viewport = {
|
|
45
|
+
width: 1280,
|
|
46
|
+
height: 900
|
|
47
|
+
}, outputDir, maskSelectors = [], threshold = .1 } = options;
|
|
48
|
+
await mkdir(outputDir, { recursive: true });
|
|
49
|
+
const browser = await chromium.launch();
|
|
50
|
+
const results = [];
|
|
51
|
+
let fullPageDiffRatio;
|
|
52
|
+
try {
|
|
53
|
+
const baselinePage = await browser.newPage({ viewport });
|
|
54
|
+
if (options.baselineUrl) await baselinePage.goto(options.baselineUrl, {
|
|
55
|
+
waitUntil: "networkidle",
|
|
56
|
+
timeout: 3e4
|
|
57
|
+
});
|
|
58
|
+
else if (options.baselineFile) {
|
|
59
|
+
const html = await readFile(resolve(options.baselineFile), "utf-8");
|
|
60
|
+
await baselinePage.setContent(html, { waitUntil: "networkidle" });
|
|
61
|
+
}
|
|
62
|
+
await applyMask(baselinePage, maskSelectors);
|
|
63
|
+
const currentPage = await browser.newPage({ viewport });
|
|
64
|
+
if (options.currentUrl) await currentPage.goto(options.currentUrl, {
|
|
65
|
+
waitUntil: "networkidle",
|
|
66
|
+
timeout: 3e4
|
|
67
|
+
});
|
|
68
|
+
else if (options.currentFile) {
|
|
69
|
+
const html = await readFile(resolve(options.currentFile), "utf-8");
|
|
70
|
+
await currentPage.setContent(html, { waitUntil: "networkidle" });
|
|
71
|
+
}
|
|
72
|
+
await applyMask(currentPage, maskSelectors);
|
|
73
|
+
const fullBaselinePath = join(outputDir, "fullpage-baseline.png");
|
|
74
|
+
const fullCurrentPath = join(outputDir, "fullpage-current.png");
|
|
75
|
+
await baselinePage.screenshot({
|
|
76
|
+
path: fullBaselinePath,
|
|
77
|
+
fullPage: true
|
|
78
|
+
});
|
|
79
|
+
await currentPage.screenshot({
|
|
80
|
+
path: fullCurrentPath,
|
|
81
|
+
fullPage: true
|
|
82
|
+
});
|
|
83
|
+
fullPageDiffRatio = (await compareScreenshots({
|
|
84
|
+
testId: "fullpage",
|
|
85
|
+
testTitle: "Full Page",
|
|
86
|
+
projectName: "element-compare",
|
|
87
|
+
screenshotPath: fullCurrentPath,
|
|
88
|
+
baselinePath: fullBaselinePath,
|
|
89
|
+
status: "changed"
|
|
90
|
+
}, {
|
|
91
|
+
outputDir,
|
|
92
|
+
threshold
|
|
93
|
+
}))?.diffRatio ?? 0;
|
|
94
|
+
for (const selector of selectors) {
|
|
95
|
+
const safeSelector = selector.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
96
|
+
const baselinePath = join(outputDir, `el-${safeSelector}-baseline.png`);
|
|
97
|
+
const currentPath = join(outputDir, `el-${safeSelector}-current.png`);
|
|
98
|
+
const baselineResult = await captureElementScreenshot(baselinePage, selector, baselinePath);
|
|
99
|
+
const currentResult = await captureElementScreenshot(currentPage, selector, currentPath);
|
|
100
|
+
if (!baselineResult.found || !currentResult.found) {
|
|
101
|
+
results.push({
|
|
102
|
+
selector,
|
|
103
|
+
found: {
|
|
104
|
+
baseline: baselineResult.found,
|
|
105
|
+
current: currentResult.found
|
|
106
|
+
},
|
|
107
|
+
diffPixels: 0,
|
|
108
|
+
totalPixels: 0,
|
|
109
|
+
diffRatio: baselineResult.found !== currentResult.found ? 1 : 0
|
|
110
|
+
});
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const diff = await compareScreenshots({
|
|
114
|
+
testId: `el-${safeSelector}`,
|
|
115
|
+
testTitle: `Element: ${selector}`,
|
|
116
|
+
projectName: "element-compare",
|
|
117
|
+
screenshotPath: currentPath,
|
|
118
|
+
baselinePath,
|
|
119
|
+
status: "changed"
|
|
120
|
+
}, {
|
|
121
|
+
outputDir,
|
|
122
|
+
threshold
|
|
123
|
+
});
|
|
124
|
+
results.push({
|
|
125
|
+
selector,
|
|
126
|
+
found: {
|
|
127
|
+
baseline: true,
|
|
128
|
+
current: true
|
|
129
|
+
},
|
|
130
|
+
baselineBBox: baselineResult.bbox,
|
|
131
|
+
currentBBox: currentResult.bbox,
|
|
132
|
+
diffPixels: diff?.diffPixels ?? 0,
|
|
133
|
+
totalPixels: diff?.totalPixels ?? 0,
|
|
134
|
+
diffRatio: diff?.diffRatio ?? 0,
|
|
135
|
+
heatmapPath: diff?.heatmapPath,
|
|
136
|
+
baselinePath,
|
|
137
|
+
currentPath
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
await baselinePage.close();
|
|
141
|
+
await currentPage.close();
|
|
142
|
+
} finally {
|
|
143
|
+
await browser.close();
|
|
144
|
+
}
|
|
145
|
+
const matched = results.filter((r) => r.found.baseline && r.found.current);
|
|
146
|
+
const changed = matched.filter((r) => r.diffRatio > 0);
|
|
147
|
+
const missing = results.filter((r) => !r.found.baseline || !r.found.current);
|
|
148
|
+
const totalElementPixels = matched.reduce((s, r) => s + r.totalPixels, 0);
|
|
149
|
+
const totalElementDiffPixels = matched.reduce((s, r) => s + r.diffPixels, 0);
|
|
150
|
+
return {
|
|
151
|
+
baselineSource: options.baselineUrl ?? options.baselineFile ?? "",
|
|
152
|
+
currentSource: options.currentUrl ?? options.currentFile ?? "",
|
|
153
|
+
viewport,
|
|
154
|
+
elements: results,
|
|
155
|
+
summary: {
|
|
156
|
+
total: selectors.length,
|
|
157
|
+
matched: matched.length,
|
|
158
|
+
changed: changed.length,
|
|
159
|
+
missing: missing.length,
|
|
160
|
+
fullPageDiffRatio,
|
|
161
|
+
elementDiffRatio: totalElementPixels > 0 ? totalElementDiffPixels / totalElementPixels : 0
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
function parseArgs(args) {
|
|
166
|
+
function getArg(name, fallback = "") {
|
|
167
|
+
const idx = args.indexOf(`--${name}`);
|
|
168
|
+
return idx >= 0 && args[idx + 1] ? args[idx + 1] : fallback;
|
|
169
|
+
}
|
|
170
|
+
const selectorsRaw = getArg("selectors");
|
|
171
|
+
if (!selectorsRaw) throw new Error("--selectors is required (comma-separated CSS selectors)");
|
|
172
|
+
const selectors = selectorsRaw.split(",").map((s) => s.trim()).filter(Boolean);
|
|
173
|
+
const baselineUrl = getArg("url") || void 0;
|
|
174
|
+
const currentUrl = getArg("current-url") || void 0;
|
|
175
|
+
const positional = args.filter((a) => !a.startsWith("--") && !args.some((b, i) => b.startsWith("--") && args[i + 1] === a));
|
|
176
|
+
const baselineFile = !baselineUrl ? positional[0] : void 0;
|
|
177
|
+
const currentFile = !currentUrl ? positional[1] : void 0;
|
|
178
|
+
const [w, h] = getArg("viewport", "1280x900").split("x").map(Number);
|
|
179
|
+
return {
|
|
180
|
+
selectors,
|
|
181
|
+
baselineFile,
|
|
182
|
+
currentFile,
|
|
183
|
+
baselineUrl,
|
|
184
|
+
currentUrl,
|
|
185
|
+
viewport: {
|
|
186
|
+
width: w || 1280,
|
|
187
|
+
height: h || 900
|
|
188
|
+
},
|
|
189
|
+
outputDir: resolve(getArg("output", join(process.cwd(), "test-results", "element-compare"))),
|
|
190
|
+
maskSelectors: parseMaskSelectors(args),
|
|
191
|
+
threshold: parseFloat(getArg("threshold", "0.1"))
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
function formatUsage() {
|
|
195
|
+
return [
|
|
196
|
+
"Usage:",
|
|
197
|
+
" vlmkit diff component --url <baseline> --current-url <current> --selectors \"header,main,footer\"",
|
|
198
|
+
" vlmkit diff component before.html after.html --selectors \"header,.content\"",
|
|
199
|
+
"",
|
|
200
|
+
"Aliases:",
|
|
201
|
+
" vlmkit diff elements",
|
|
202
|
+
" vlmkit diff elements",
|
|
203
|
+
"",
|
|
204
|
+
"Options:",
|
|
205
|
+
" --selectors <sel1,sel2,...> CSS selectors to compare (required)",
|
|
206
|
+
" --viewport <WxH> Viewport size (default: 1280x900)",
|
|
207
|
+
" --output <dir> Output directory",
|
|
208
|
+
" --mask <selectors> Mask dynamic content",
|
|
209
|
+
" --threshold <0-1> pixelmatch threshold (default: 0.1)"
|
|
210
|
+
].join("\n");
|
|
211
|
+
}
|
|
212
|
+
async function main() {
|
|
213
|
+
const cliArgs = process.argv.slice(2);
|
|
214
|
+
if (cliArgs.includes("--help") || cliArgs.includes("-h") || cliArgs.includes("help")) {
|
|
215
|
+
console.log(formatUsage());
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const options = parseArgs(cliArgs);
|
|
219
|
+
if (!options.baselineUrl && !options.baselineFile) {
|
|
220
|
+
console.log(formatUsage());
|
|
221
|
+
process.exit(1);
|
|
222
|
+
}
|
|
223
|
+
console.log();
|
|
224
|
+
console.log(`${BOLD}${CYAN}╔════════════════════════════════════════════════════════════════════════╗${RESET}`);
|
|
225
|
+
console.log(`${BOLD}${CYAN}║ Element-level VRT Compare ║${RESET}`);
|
|
226
|
+
console.log(`${BOLD}${CYAN}╚════════════════════════════════════════════════════════════════════════╝${RESET}`);
|
|
227
|
+
console.log(` ${DIM}Selectors: ${options.selectors.join(", ")}${RESET}`);
|
|
228
|
+
console.log(` ${DIM}Viewport: ${options.viewport?.width}x${options.viewport?.height}${RESET}`);
|
|
229
|
+
console.log();
|
|
230
|
+
const report = await runElementCompare(options);
|
|
231
|
+
for (const el of report.elements) if (!el.found.baseline && !el.found.current) console.log(` ${DIM}${el.selector.padEnd(30)}${RESET} ${YELLOW}not found${RESET}`);
|
|
232
|
+
else if (!el.found.baseline || !el.found.current) {
|
|
233
|
+
const side = el.found.baseline ? "current" : "baseline";
|
|
234
|
+
console.log(` ${DIM}${el.selector.padEnd(30)}${RESET} ${RED}missing in ${side}${RESET}`);
|
|
235
|
+
} else if (el.diffRatio === 0) console.log(` ${el.selector.padEnd(30)} ${GREEN}0.0%${RESET}`);
|
|
236
|
+
else {
|
|
237
|
+
const color = el.diffRatio < .01 ? YELLOW : RED;
|
|
238
|
+
const pct = (el.diffRatio * 100).toFixed(2);
|
|
239
|
+
const bbox = el.currentBBox;
|
|
240
|
+
const bboxStr = bbox ? ` ${DIM}(${bbox.width}x${bbox.height} @${bbox.x},${bbox.y})${RESET}` : "";
|
|
241
|
+
console.log(` ${el.selector.padEnd(30)} ${color}${pct}%${RESET}${bboxStr}`);
|
|
242
|
+
}
|
|
243
|
+
console.log();
|
|
244
|
+
hr();
|
|
245
|
+
console.log();
|
|
246
|
+
const { summary } = report;
|
|
247
|
+
if (summary.fullPageDiffRatio !== void 0) {
|
|
248
|
+
const fpColor = summary.fullPageDiffRatio === 0 ? GREEN : summary.fullPageDiffRatio < .01 ? YELLOW : RED;
|
|
249
|
+
console.log(` Full-page diff: ${fpColor}${(summary.fullPageDiffRatio * 100).toFixed(2)}%${RESET}`);
|
|
250
|
+
}
|
|
251
|
+
const elColor = summary.elementDiffRatio === 0 ? GREEN : summary.elementDiffRatio < .01 ? YELLOW : RED;
|
|
252
|
+
console.log(` Element diff: ${elColor}${(summary.elementDiffRatio * 100).toFixed(2)}%${RESET}`);
|
|
253
|
+
console.log(` ${DIM}Elements: ${summary.total} total, ${summary.matched} matched, ${summary.changed} changed, ${summary.missing} missing${RESET}`);
|
|
254
|
+
if (summary.fullPageDiffRatio !== void 0 && summary.fullPageDiffRatio > 0 && summary.elementDiffRatio < summary.fullPageDiffRatio) {
|
|
255
|
+
const reduction = ((1 - summary.elementDiffRatio / summary.fullPageDiffRatio) * 100).toFixed(0);
|
|
256
|
+
console.log(` ${GREEN}Element-level reduces noise by ${reduction}%${RESET}`);
|
|
257
|
+
}
|
|
258
|
+
console.log();
|
|
259
|
+
const reportPath = join(options.outputDir, "element-compare-report.json");
|
|
260
|
+
await writeFile(reportPath, JSON.stringify(report, null, 2));
|
|
261
|
+
console.log(` ${DIM}Report: ${reportPath}${RESET}`);
|
|
262
|
+
console.log();
|
|
263
|
+
}
|
|
264
|
+
if (process.env.__VRT_DISPATCHER_LEAF__ === "element-compare" || process.argv[1]?.endsWith("element-compare.ts")) main().catch((e) => {
|
|
265
|
+
console.error(e);
|
|
266
|
+
process.exit(1);
|
|
267
|
+
});
|
|
268
|
+
//#endregion
|
|
269
|
+
export { runElementCompare };
|