@mizchi/vlmkit-core 0.6.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/src/index.ts ADDED
@@ -0,0 +1,108 @@
1
+ /**
2
+ * @mizchi/vlmkit-core — VRT diff engine + shared types
3
+ *
4
+ * This barrel is the curated public API. Anything not re-exported here
5
+ * is internal — either a browser-context helper (designed to run inside
6
+ * `page.evaluate(...)`), a CLI helper, or a low-level parser. Those
7
+ * remain accessible via deep import (`@mizchi/vlmkit-core/<module>.ts`)
8
+ * but aren't part of the stable surface.
9
+ *
10
+ * Naming groups (informal):
11
+ *
12
+ * - `compareScreenshots`, `runPngDiff`, `generateDiffReport`
13
+ * → top-level diff entry points.
14
+ * - `find{HeatmapRegions,ShiftOrigins,GridSuggestions}`,
15
+ * `detect{BandShifts,Whiteout,EmptyContent}`
16
+ * → detectors that return structured findings.
17
+ * - `diff{A11yTrees,ComputedStyles,DomPositionStyles}`,
18
+ * `classify{Region,VisualDiff}`, `evaluateDomEquivalence`
19
+ * → structural comparisons.
20
+ * - `extractTextRows*`, `matchTextRows`, `compareRowTypography`
21
+ * → typography / text-row primitives.
22
+ * - `{decode,encode,crop,resize}Png*`, `getImageDimensions`
23
+ * → image-IO helpers.
24
+ * - `INTERACTIVE_ROLES`, `LANDMARK_ROLES`, `RESOLUTION_PRESETS`,
25
+ * `TRACKED_PROPERTIES` → public config constants.
26
+ * - `runQualityChecks`
27
+ * → end-to-end quality gate.
28
+ *
29
+ * Modules NOT in the barrel (deep import only):
30
+ * - terminal-colors, cli-args, cli-error — CLI helpers
31
+ * - element-compare, mask — require Playwright at module load
32
+ * - a11y-contrast, a11y-touch, a11y-focus-order — CLI entries
33
+ * - browser-script string constants & `*InDom` helpers
34
+ */
35
+
36
+ // ---- Types (open re-export — types don't pollute the value namespace) ----
37
+ export * from "./types.ts";
38
+
39
+ // ---- Image diff ----
40
+ export {
41
+ compareScreenshots,
42
+ detectBandShifts,
43
+ generateDiffReport,
44
+ detectWhiteout,
45
+ detectEmptyContent,
46
+ } from "./heatmap.ts";
47
+ export { runPngDiff } from "./png-diff.ts";
48
+ export { findHeatmapRegionsFromFile, findHeatmapRegionsFromRgba } from "./heatmap-regions.ts";
49
+ export {
50
+ createScopedVrtDiff,
51
+ normalizeVrtDiffRegions,
52
+ normalizeVrtDiffRegionPixels,
53
+ } from "./diff-regions.ts";
54
+ export { classifyRegion } from "./region-classify.ts";
55
+ export { findShiftOrigins } from "./shift-origin.ts";
56
+
57
+ // ---- Layout / typography ----
58
+ export {
59
+ extractTextRowsFromFile,
60
+ extractTextRowsFromRgba,
61
+ matchTextRows,
62
+ compareRowTypography,
63
+ computeRowGapDeltas,
64
+ } from "./text-rows.ts";
65
+ export { findGridSuggestions } from "./grid-ratio.ts";
66
+
67
+ // ---- PNG IO ----
68
+ export {
69
+ cropImage,
70
+ decodePng,
71
+ encodePng,
72
+ } from "./png-utils.ts";
73
+ export {
74
+ resizePngBuffer,
75
+ resolveResolutionForViewport,
76
+ getImageDimensions,
77
+ } from "./image-resize.ts";
78
+
79
+ // ---- DOM diff ----
80
+ export {
81
+ verifyDomEquivalence,
82
+ /** @deprecated since 0.5.0 — use `verifyDomEquivalence`. */
83
+ evaluateDomEquivalence,
84
+ } from "./dom-equivalence.ts";
85
+ export {
86
+ diffDomPositionStyles,
87
+ diffPositionStylesAcrossViewports,
88
+ } from "./dom-position-styles.ts";
89
+ export { diffComputedStyles } from "./computed-style-diff.ts";
90
+
91
+ // ---- A11y diff ----
92
+ export {
93
+ diffA11yTrees,
94
+ parsePlaywrightA11ySnapshot,
95
+ verifyA11yTree,
96
+ /** @deprecated since 0.5.0 — use `verifyA11yTree`. */
97
+ checkA11yTree,
98
+ INTERACTIVE_ROLES,
99
+ LANDMARK_ROLES,
100
+ } from "./a11y-semantic.ts";
101
+
102
+ // ---- Semantic / quality ----
103
+ export { classifyVisualDiff } from "./visual-semantic.ts";
104
+ export { runQualityChecks } from "./quality.ts";
105
+
106
+ // ---- Public config constants ----
107
+ export { RESOLUTION_PRESETS } from "./image-resize.ts";
108
+ export { TRACKED_PROPERTIES } from "./computed-style-capture.ts";
package/src/mask.ts ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * VRT Mask -- hide specific selectors before screenshotting.
3
+ *
4
+ * Uses visibility: hidden to preserve layout while hiding rendering.
5
+ * Prevents false positives from dynamic content (counters, animations, ads).
6
+ */
7
+ import type { Page } from "playwright";
8
+
9
+ /**
10
+ * Inject mask styles into the page.
11
+ * Sets visibility: hidden on target selectors including descendants.
12
+ */
13
+ export async function applyMask(page: Page, selectors: string[]): Promise<void> {
14
+ if (selectors.length === 0) return;
15
+
16
+ const css = selectors
17
+ .map((s) => `${s} { visibility: hidden !important; }`)
18
+ .join("\n");
19
+
20
+ await page.addStyleTag({ content: css });
21
+ }
22
+
23
+ /**
24
+ * Parse selector array from CLI --mask flags.
25
+ * Supports comma-separated or multiple --mask flags.
26
+ *
27
+ * --mask ".stars,.carousel"
28
+ * --mask ".stars" --mask ".carousel"
29
+ */
30
+ export function parseMaskSelectors(args: string[]): string[] {
31
+ const selectors: string[] = [];
32
+ for (let i = 0; i < args.length; i++) {
33
+ if (args[i] === "--mask" && args[i + 1]) {
34
+ for (const s of args[i + 1].split(",")) {
35
+ const trimmed = s.trim();
36
+ if (trimmed) selectors.push(trimmed);
37
+ }
38
+ }
39
+ }
40
+ return selectors;
41
+ }
@@ -0,0 +1,165 @@
1
+ import { mkdir } from "node:fs/promises";
2
+ import { basename, join } from "node:path";
3
+ import { compareScreenshots } from "./heatmap.ts";
4
+ import { classifyVisualDiff } from "./visual-semantic.ts";
5
+ import type { VrtSnapshot } from "./types.ts";
6
+
7
+ export interface PngDiffCliOptions {
8
+ baselinePath: string;
9
+ currentPath: string;
10
+ outputDir: string;
11
+ threshold: number;
12
+ skipHeatmap: boolean;
13
+ json: boolean;
14
+ }
15
+
16
+ class PngDiffCliError extends Error {
17
+ readonly exitCode: number;
18
+
19
+ constructor(message: string, exitCode: number) {
20
+ super(message);
21
+ this.exitCode = exitCode;
22
+ }
23
+ }
24
+
25
+ export function formatPngDiffUsage(): string {
26
+ return `vrt png-diff <baseline.png> <current.png>
27
+
28
+ Compare two existing PNG screenshots without launching Playwright.
29
+
30
+ Options:
31
+ --output-dir <path> Directory for generated heatmaps (default: test-results/png-diff)
32
+ --threshold <0-1> pixelmatch threshold (default: 0.1)
33
+ --no-heatmap Skip heatmap generation
34
+ --json Print JSON instead of a human-readable summary`;
35
+ }
36
+
37
+ export function parsePngDiffArgs(args: string[]): PngDiffCliOptions {
38
+ const positional: string[] = [];
39
+ let outputDir = join(process.cwd(), "test-results", "png-diff");
40
+ let threshold = 0.1;
41
+ let skipHeatmap = false;
42
+ let json = false;
43
+
44
+ for (let i = 0; i < args.length; i++) {
45
+ const arg = args[i]!;
46
+ switch (arg) {
47
+ case "--help":
48
+ case "-h":
49
+ throw new PngDiffCliError(formatPngDiffUsage(), 0);
50
+ case "--output":
51
+ case "--output-dir": {
52
+ const value = args[++i];
53
+ if (!value) throw new PngDiffCliError(`Missing value for ${arg}\n\n${formatPngDiffUsage()}`, 1);
54
+ outputDir = value;
55
+ break;
56
+ }
57
+ case "--threshold": {
58
+ const value = args[++i];
59
+ const parsed = value ? Number(value) : Number.NaN;
60
+ if (!value || !Number.isFinite(parsed) || parsed < 0 || parsed > 1) {
61
+ throw new PngDiffCliError(`Invalid --threshold value: ${value ?? ""}\n\n${formatPngDiffUsage()}`, 1);
62
+ }
63
+ threshold = parsed;
64
+ break;
65
+ }
66
+ case "--no-heatmap":
67
+ skipHeatmap = true;
68
+ break;
69
+ case "--json":
70
+ json = true;
71
+ break;
72
+ default:
73
+ if (arg.startsWith("--")) {
74
+ throw new PngDiffCliError(`Unknown option: ${arg}\n\n${formatPngDiffUsage()}`, 1);
75
+ }
76
+ positional.push(arg);
77
+ break;
78
+ }
79
+ }
80
+
81
+ if (positional.length !== 2) {
82
+ throw new PngDiffCliError(formatPngDiffUsage(), 1);
83
+ }
84
+
85
+ const [baselinePath, currentPath] = positional;
86
+ return { baselinePath, currentPath, outputDir, threshold, skipHeatmap, json };
87
+ }
88
+
89
+ export async function runPngDiff(options: PngDiffCliOptions) {
90
+ if (!options.skipHeatmap) {
91
+ await mkdir(options.outputDir, { recursive: true });
92
+ }
93
+
94
+ const snapshot: VrtSnapshot = {
95
+ testId: basename(options.currentPath, ".png") || "png-diff",
96
+ testTitle: basename(options.currentPath),
97
+ projectName: "vrt",
98
+ screenshotPath: options.currentPath,
99
+ baselinePath: options.baselinePath,
100
+ status: "changed",
101
+ };
102
+
103
+ const diff = await compareScreenshots(snapshot, {
104
+ outputDir: options.skipHeatmap ? undefined : options.outputDir,
105
+ skipHeatmap: options.skipHeatmap,
106
+ threshold: options.threshold,
107
+ });
108
+ if (!diff) {
109
+ throw new Error("PNG diff requires both baseline and current screenshot paths");
110
+ }
111
+
112
+ const semantic = classifyVisualDiff(diff);
113
+ return { diff, semantic };
114
+ }
115
+
116
+ export async function runPngDiffCli(cliArgs = process.argv.slice(2)) {
117
+ try {
118
+ const options = parsePngDiffArgs(cliArgs);
119
+ const result = await runPngDiff(options);
120
+ const output = {
121
+ status: result.diff.diffPixels === 0 ? "pass" : "changed",
122
+ baselinePath: options.baselinePath,
123
+ currentPath: options.currentPath,
124
+ diffPixels: result.diff.diffPixels,
125
+ totalPixels: result.diff.totalPixels,
126
+ diffRatio: result.diff.diffRatio,
127
+ regions: result.diff.regions,
128
+ heatmapPath: result.diff.heatmapPath,
129
+ summary: result.semantic.summary,
130
+ changes: result.semantic.changes,
131
+ };
132
+
133
+ if (options.json) {
134
+ console.log(JSON.stringify(output, null, 2));
135
+ return;
136
+ }
137
+
138
+ console.log("PNG Diff");
139
+ console.log(` baseline: ${output.baselinePath}`);
140
+ console.log(` current: ${output.currentPath}`);
141
+ console.log(` diff: ${(output.diffRatio * 100).toFixed(2)}% (${output.diffPixels} / ${output.totalPixels} px)`);
142
+ console.log(` regions: ${output.regions.length}`);
143
+ console.log(` summary: ${output.summary}`);
144
+ if (output.heatmapPath) {
145
+ console.log(` heatmap: ${output.heatmapPath}`);
146
+ }
147
+ } catch (error) {
148
+ if (error instanceof PngDiffCliError) {
149
+ if (error.exitCode === 0) {
150
+ console.log(error.message);
151
+ } else {
152
+ console.error(error.message);
153
+ }
154
+ process.exit(error.exitCode);
155
+ }
156
+ throw error;
157
+ }
158
+ }
159
+
160
+ if (process.env.__VRT_DISPATCHER_LEAF__ === "png-diff" || process.argv[1]?.endsWith("png-diff.ts")) {
161
+ runPngDiffCli().catch((error) => {
162
+ console.error(error);
163
+ process.exit(1);
164
+ });
165
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * PNG I/O utilities
3
+ *
4
+ * Low-level PNG decode/encode using pngjs.
5
+ * Used by heatmap.ts and other modules that need raw pixel data.
6
+ */
7
+ import { readFile, writeFile } from "node:fs/promises";
8
+
9
+ export interface PngData {
10
+ width: number;
11
+ height: number;
12
+ data: Uint8Array;
13
+ }
14
+
15
+ /**
16
+ * Crop or pad an image to the target dimensions.
17
+ * Only handles the common region; overflow is zero-filled.
18
+ */
19
+ export function cropImage(img: PngData, w: number, h: number): PngData {
20
+ if (img.width === w && img.height === h) return img;
21
+ const data = new Uint8Array(w * h * 4);
22
+ for (let y = 0; y < h; y++) {
23
+ const srcOffset = y * img.width * 4;
24
+ const dstOffset = y * w * 4;
25
+ data.set(img.data.subarray(srcOffset, srcOffset + w * 4), dstOffset);
26
+ }
27
+ return { width: w, height: h, data };
28
+ }
29
+
30
+ /**
31
+ * Read a PNG file and return RGBA pixel data.
32
+ */
33
+ export async function decodePng(path: string): Promise<PngData> {
34
+ const { PNG } = await import("pngjs");
35
+ const buffer = await readFile(path);
36
+ const png = PNG.sync.read(buffer);
37
+ return {
38
+ width: png.width,
39
+ height: png.height,
40
+ data: new Uint8Array(png.data.buffer, png.data.byteOffset, png.data.byteLength),
41
+ };
42
+ }
43
+
44
+ /**
45
+ * Write RGBA pixel data to a PNG file.
46
+ */
47
+ export async function encodePng(
48
+ path: string,
49
+ data: PngData
50
+ ): Promise<void> {
51
+ const { PNG } = await import("pngjs");
52
+ const png = new PNG({ width: data.width, height: data.height });
53
+ Buffer.from(data.data.buffer, data.data.byteOffset, data.data.byteLength).copy(png.data);
54
+ const buffer = PNG.sync.write(png);
55
+ await writeFile(path, buffer);
56
+ }
package/src/quality.ts ADDED
@@ -0,0 +1,209 @@
1
+ import type {
2
+ QualityCheckResult,
3
+ VrtSnapshot,
4
+ VrtDiff,
5
+ DepGraph,
6
+ AffectedComponent,
7
+ } from "./types.ts";
8
+ import { detectWhiteout, detectEmptyContent } from "./heatmap.ts";
9
+ import { decodePng } from "./png-utils.ts";
10
+
11
+ /**
12
+ * Run all quality checks.
13
+ */
14
+ export async function runQualityChecks(
15
+ snapshots: VrtSnapshot[],
16
+ diffs: VrtDiff[],
17
+ graph?: DepGraph,
18
+ affected?: AffectedComponent[]
19
+ ): Promise<QualityCheckResult[]> {
20
+ const results: QualityCheckResult[] = [];
21
+
22
+ // Per-snapshot checks
23
+ for (const snapshot of snapshots) {
24
+ const snapshotChecks = await checkSnapshot(snapshot);
25
+ results.push(...snapshotChecks);
26
+ }
27
+
28
+ // Coverage check
29
+ if (graph && affected) {
30
+ results.push(checkCoverage(snapshots, affected));
31
+ }
32
+
33
+ // Error state check (when diff exists)
34
+ for (const diff of diffs) {
35
+ if (diff.diffRatio > 0.5) {
36
+ results.push({
37
+ check: "layout-shift",
38
+ passed: false,
39
+ details: `Large visual change detected in "${diff.snapshot.testTitle}": ${(diff.diffRatio * 100).toFixed(1)}% of pixels changed. ${diff.regions.length} region(s) affected.`,
40
+ severity: "warning",
41
+ });
42
+ }
43
+ }
44
+
45
+ return results;
46
+ }
47
+
48
+ /**
49
+ * Per-snapshot quality checks.
50
+ */
51
+ async function checkSnapshot(
52
+ snapshot: VrtSnapshot
53
+ ): Promise<QualityCheckResult[]> {
54
+ const results: QualityCheckResult[] = [];
55
+
56
+ try {
57
+ const png = await decodePng(snapshot.screenshotPath);
58
+
59
+ // Whiteout detection
60
+ const whiteout = detectWhiteout(png);
61
+ results.push({
62
+ check: "whiteout",
63
+ passed: !whiteout.isWhiteout,
64
+ details: whiteout.isWhiteout
65
+ ? `Whiteout detected in "${snapshot.testTitle}": ${(whiteout.whiteRatio * 100).toFixed(1)}% white pixels`
66
+ : `OK: ${(whiteout.whiteRatio * 100).toFixed(1)}% white pixels`,
67
+ severity: whiteout.isWhiteout ? "error" : "info",
68
+ });
69
+
70
+ // Empty content detection
71
+ const empty = detectEmptyContent(png);
72
+ results.push({
73
+ check: "empty-content",
74
+ passed: !empty.isEmpty,
75
+ details: empty.isEmpty
76
+ ? `Empty content detected in "${snapshot.testTitle}": only ${empty.uniqueColors} unique colors`
77
+ : `OK: ${empty.uniqueColors} unique colors`,
78
+ severity: empty.isEmpty ? "error" : "info",
79
+ });
80
+
81
+ // Error state detection (red pixel ratio)
82
+ const errorState = detectErrorIndicators(png);
83
+ results.push({
84
+ check: "error-state",
85
+ passed: !errorState.hasError,
86
+ details: errorState.hasError
87
+ ? `Possible error state in "${snapshot.testTitle}": ${errorState.reason}`
88
+ : "OK: no error indicators detected",
89
+ severity: errorState.hasError ? "warning" : "info",
90
+ });
91
+ } catch (err) {
92
+ results.push({
93
+ check: "whiteout",
94
+ passed: false,
95
+ details: `Failed to analyze screenshot "${snapshot.testTitle}": ${err}`,
96
+ severity: "error",
97
+ });
98
+ }
99
+
100
+ return results;
101
+ }
102
+
103
+ /**
104
+ * Detect visual indicators of error states.
105
+ * - High red pixel ratio (error messages, validation errors)
106
+ * - Yellow/orange warning colors
107
+ */
108
+ function detectErrorIndicators(data: {
109
+ width: number;
110
+ height: number;
111
+ data: Uint8Array;
112
+ }): { hasError: boolean; reason: string } {
113
+ const { width, height, data: pixels } = data;
114
+ const total = width * height;
115
+ let redCount = 0;
116
+ let yellowCount = 0;
117
+
118
+ const stride = Math.max(1, Math.floor(total / 20000));
119
+ let sampled = 0;
120
+
121
+ for (let i = 0; i < total; i += stride) {
122
+ const offset = i * 4;
123
+ const r = pixels[offset];
124
+ const g = pixels[offset + 1];
125
+ const b = pixels[offset + 2];
126
+ sampled++;
127
+
128
+ // Red (error): high R, low G, low B
129
+ if (r > 180 && g < 80 && b < 80) {
130
+ redCount++;
131
+ }
132
+ // Yellow/orange (warning): high R, mid-high G, low B
133
+ if (r > 200 && g > 120 && g < 220 && b < 60) {
134
+ yellowCount++;
135
+ }
136
+ }
137
+
138
+ const redRatio = redCount / sampled;
139
+ const yellowRatio = yellowCount / sampled;
140
+
141
+ if (redRatio > 0.05) {
142
+ return {
143
+ hasError: true,
144
+ reason: `${(redRatio * 100).toFixed(1)}% red pixels (possible error state)`,
145
+ };
146
+ }
147
+ if (yellowRatio > 0.1) {
148
+ return {
149
+ hasError: true,
150
+ reason: `${(yellowRatio * 100).toFixed(1)}% yellow/orange pixels (possible warning state)`,
151
+ };
152
+ }
153
+
154
+ return { hasError: false, reason: "" };
155
+ }
156
+
157
+ /**
158
+ * VRT coverage: ratio of affected components that have VRT snapshots.
159
+ */
160
+ function checkCoverage(
161
+ snapshots: VrtSnapshot[],
162
+ affected: AffectedComponent[]
163
+ ): QualityCheckResult {
164
+ if (affected.length === 0) {
165
+ return {
166
+ check: "coverage",
167
+ passed: true,
168
+ details: "No affected components to cover",
169
+ severity: "info",
170
+ };
171
+ }
172
+
173
+ // Check if snapshot testTitle/testId contains the component name
174
+ const snapshotNames = new Set(
175
+ snapshots.flatMap((s) => [s.testTitle.toLowerCase(), s.testId.toLowerCase()])
176
+ );
177
+
178
+ const covered: string[] = [];
179
+ const uncovered: string[] = [];
180
+
181
+ for (const comp of affected) {
182
+ // Match by component filename (without extension)
183
+ const name = comp.node.id
184
+ .replace(/\.[^.]+$/, "")
185
+ .split("/")
186
+ .pop()!
187
+ .toLowerCase();
188
+
189
+ const isCovered = [...snapshotNames].some(
190
+ (sn) => sn.includes(name) || name.includes(sn)
191
+ );
192
+
193
+ if (isCovered) {
194
+ covered.push(comp.node.id);
195
+ } else {
196
+ uncovered.push(comp.node.id);
197
+ }
198
+ }
199
+
200
+ const ratio = covered.length / affected.length;
201
+ const passed = ratio >= 0.8; // 80% coverage threshold
202
+
203
+ return {
204
+ check: "coverage",
205
+ passed,
206
+ details: `VRT coverage: ${covered.length}/${affected.length} (${(ratio * 100).toFixed(0)}%) affected components covered.${uncovered.length > 0 ? ` Uncovered: ${uncovered.join(", ")}` : ""}`,
207
+ severity: passed ? "info" : "warning",
208
+ };
209
+ }