@mizchi/vlmkit-core 0.8.0 → 0.8.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.
Files changed (66) hide show
  1. package/dist/a11y-semantic.d.mts +34 -0
  2. package/dist/a11y-semantic.mjs +261 -0
  3. package/dist/authored-style-capture.d.mts +42 -0
  4. package/dist/authored-style-capture.mjs +117 -0
  5. package/dist/authored-style-diff.d.mts +15 -0
  6. package/dist/authored-style-diff.mjs +16 -0
  7. package/dist/cli-args.d.mts +11 -0
  8. package/dist/cli-args.mjs +21 -0
  9. package/dist/cli-error.d.mts +4 -0
  10. package/dist/cli-error.mjs +59 -0
  11. package/dist/computed-style-capture.d.mts +41 -0
  12. package/dist/computed-style-capture.mjs +589 -0
  13. package/dist/computed-style-diff.d.mts +83 -0
  14. package/dist/computed-style-diff.mjs +123 -0
  15. package/dist/diff-regions.d.mts +8 -0
  16. package/dist/diff-regions.mjs +52 -0
  17. package/dist/dom-equivalence.d.mts +51 -0
  18. package/dist/dom-equivalence.mjs +91 -0
  19. package/dist/dom-position-styles.d.mts +166 -0
  20. package/dist/dom-position-styles.mjs +296 -0
  21. package/dist/element-compare.d.mts +71 -0
  22. package/dist/element-compare.mjs +269 -0
  23. package/dist/heatmap-regions.d.mts +57 -0
  24. package/dist/heatmap-regions.mjs +158 -0
  25. package/dist/heatmap.d.mts +86 -0
  26. package/dist/heatmap.mjs +510 -0
  27. package/dist/image-resize.d.mts +34 -0
  28. package/dist/image-resize.mjs +92 -0
  29. package/dist/index.d.mts +15 -0
  30. package/dist/index.mjs +14 -0
  31. package/dist/mask.d.mts +18 -0
  32. package/dist/mask.mjs +27 -0
  33. package/dist/png-utils.d.mts +30 -0
  34. package/dist/png-utils.mjs +80 -0
  35. package/dist/region-shift.d.mts +20 -0
  36. package/dist/region-shift.mjs +128 -0
  37. package/dist/run-ledger.d.mts +14 -0
  38. package/dist/run-ledger.mjs +31 -0
  39. package/dist/terminal-colors.d.mts +12 -0
  40. package/dist/terminal-colors.mjs +14 -0
  41. package/dist/text-rows.d.mts +121 -0
  42. package/dist/text-rows.mjs +246 -0
  43. package/{src/types.ts → dist/types.d.mts} +88 -206
  44. package/dist/types.mjs +1 -0
  45. package/package.json +17 -5
  46. package/src/a11y-semantic.ts +0 -384
  47. package/src/authored-style-capture.ts +0 -185
  48. package/src/authored-style-diff.ts +0 -32
  49. package/src/cli-args.ts +0 -29
  50. package/src/cli-error.ts +0 -85
  51. package/src/computed-style-capture.ts +0 -717
  52. package/src/computed-style-diff.ts +0 -192
  53. package/src/diff-regions.ts +0 -70
  54. package/src/dom-equivalence.ts +0 -158
  55. package/src/dom-position-styles.ts +0 -457
  56. package/src/element-compare.ts +0 -354
  57. package/src/heatmap-regions.ts +0 -245
  58. package/src/heatmap.ts +0 -670
  59. package/src/image-resize.ts +0 -112
  60. package/src/index.ts +0 -105
  61. package/src/mask.ts +0 -41
  62. package/src/png-utils.ts +0 -86
  63. package/src/region-shift.ts +0 -173
  64. package/src/run-ledger.ts +0 -39
  65. package/src/terminal-colors.ts +0 -13
  66. package/src/text-rows.ts +0 -412
@@ -0,0 +1,510 @@
1
+ import { cropImage, decodePng, encodePng } from "./png-utils.mjs";
2
+ import { estimateRegionShift } from "./region-shift.mjs";
3
+ //#region src/heatmap.ts
4
+ async function runPixelDiff(baselinePath, screenshotPath, testId, opts) {
5
+ const pixelmatch = (await import("pixelmatch")).default;
6
+ const baseline = await decodePng(baselinePath);
7
+ const current = await decodePng(screenshotPath);
8
+ let resizedBaseline = baseline;
9
+ let resizedCurrent = current;
10
+ let overflowPixels = 0;
11
+ if (baseline.width !== current.width || baseline.height !== current.height) {
12
+ const commonW = Math.min(baseline.width, current.width);
13
+ const commonH = Math.min(baseline.height, current.height);
14
+ overflowPixels = Math.max(baseline.width, current.width) * Math.max(baseline.height, current.height) - commonW * commonH;
15
+ resizedBaseline = cropImage(baseline, commonW, commonH);
16
+ resizedCurrent = cropImage(current, commonW, commonH);
17
+ }
18
+ const width = resizedBaseline.width;
19
+ const height = resizedBaseline.height;
20
+ const totalPixels = width * height + overflowPixels;
21
+ const diffOutput = new Uint8Array(width * height * 4);
22
+ const threshold = opts.threshold ?? .1;
23
+ const diffPixels = overflowPixels + pixelmatch(resizedBaseline.data, resizedCurrent.data, diffOutput, width, height, { threshold });
24
+ let heatmapPath;
25
+ if (opts.outputDir && diffPixels > 0 && !opts.skipHeatmap) {
26
+ const safeName = testId.replace(/[/\\:]/g, "_");
27
+ heatmapPath = `${opts.outputDir}/${safeName}_heatmap.png`;
28
+ await encodePng(heatmapPath, {
29
+ width,
30
+ height,
31
+ data: diffOutput
32
+ });
33
+ }
34
+ return {
35
+ diffOutput,
36
+ width,
37
+ height,
38
+ diffPixels,
39
+ totalPixels,
40
+ threshold,
41
+ resizedBaseline,
42
+ resizedCurrent,
43
+ heatmapPath
44
+ };
45
+ }
46
+ /**
47
+ * Compare two screenshots pixel-by-pixel and generate a diff heatmap.
48
+ */
49
+ async function compareScreenshots(snapshot, opts = {}) {
50
+ if (!snapshot.baselinePath) return null;
51
+ const r = await runPixelDiff(snapshot.baselinePath, snapshot.screenshotPath, snapshot.testId, opts);
52
+ const regions = detectDiffRegions(r.diffOutput, r.width, r.height);
53
+ attachRegionColorSamples(regions, r.resizedBaseline, r.resizedCurrent);
54
+ attachRegionShiftEstimates(regions, r.resizedBaseline, r.resizedCurrent);
55
+ return {
56
+ snapshot,
57
+ diffPixels: r.diffPixels,
58
+ totalPixels: r.totalPixels,
59
+ diffRatio: r.diffPixels / r.totalPixels,
60
+ heatmapPath: r.heatmapPath,
61
+ regions
62
+ };
63
+ }
64
+ /**
65
+ * Grid-based diff region detection.
66
+ * Splits image into cells and clusters cells exceeding the diff threshold.
67
+ */
68
+ function detectDiffRegions(diffData, width, height, cellSize = 32) {
69
+ const cols = Math.ceil(width / cellSize);
70
+ const rows = Math.ceil(height / cellSize);
71
+ const grid = new Uint32Array(cols * rows);
72
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) if (diffData[(y * width + x) * 4 + 1] < 128) {
73
+ const col = Math.floor(x / cellSize);
74
+ const row = Math.floor(y / cellSize);
75
+ grid[row * cols + col]++;
76
+ }
77
+ const visited = new Uint8Array(cols * rows);
78
+ const regions = [];
79
+ const minPixels = 4;
80
+ for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) {
81
+ const i = r * cols + c;
82
+ if (visited[i] || grid[i] < minPixels) continue;
83
+ let minC = c, maxC = c, minR = r, maxR = r;
84
+ let totalDiff = 0;
85
+ const queue = [i];
86
+ visited[i] = 1;
87
+ while (queue.length > 0) {
88
+ const ci = queue.shift();
89
+ const cr = Math.floor(ci / cols);
90
+ const cc = ci % cols;
91
+ totalDiff += grid[ci];
92
+ minC = Math.min(minC, cc);
93
+ maxC = Math.max(maxC, cc);
94
+ minR = Math.min(minR, cr);
95
+ maxR = Math.max(maxR, cr);
96
+ for (const [dr, dc] of [
97
+ [-1, 0],
98
+ [1, 0],
99
+ [0, -1],
100
+ [0, 1]
101
+ ]) {
102
+ const nr = cr + dr;
103
+ const nc = cc + dc;
104
+ if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
105
+ const ni = nr * cols + nc;
106
+ if (!visited[ni] && grid[ni] >= minPixels) {
107
+ visited[ni] = 1;
108
+ queue.push(ni);
109
+ }
110
+ }
111
+ }
112
+ const regionWidth = (maxC - minC + 1) * cellSize;
113
+ const regionHeight = (maxR - minR + 1) * cellSize;
114
+ regions.push({
115
+ x: minC * cellSize,
116
+ y: minR * cellSize,
117
+ width: regionWidth,
118
+ height: regionHeight,
119
+ diffPixelCount: totalDiff,
120
+ regionType: classifyRegion(regionWidth, regionHeight, width)
121
+ });
122
+ }
123
+ return regions;
124
+ }
125
+ function attachRegionColorSamples(regions, baseline, current) {
126
+ for (const region of regions) {
127
+ const sample = sampleRegionColorSample(baseline, current, region);
128
+ if (sample) region.colorSample = sample;
129
+ }
130
+ }
131
+ function attachRegionShiftEstimates(regions, baseline, current) {
132
+ for (const region of regions) {
133
+ if (region.regionType === "edge") continue;
134
+ const shift = estimateRegionShift(baseline, current, region);
135
+ if (shift) region.shift = shift;
136
+ }
137
+ }
138
+ /** Fraction of a region's opaque pixels below which the change counts as
139
+ * "sparse" (thin glyphs, a minority recolor) and a peak pixel is worth
140
+ * surfacing alongside the mean. */
141
+ const SPARSE_CHANGE_RATIO = .5;
142
+ /** Per-channel mean delta above which a pixel counts as actually changed,
143
+ * matching `diff region`'s sampleBboxColorPair gate. */
144
+ const CHANGED_PIXEL_DELTA = 1;
145
+ function makeColorAccumulator() {
146
+ return {
147
+ br: 0,
148
+ bg: 0,
149
+ bb: 0,
150
+ cr: 0,
151
+ cg: 0,
152
+ cb: 0,
153
+ n: 0
154
+ };
155
+ }
156
+ function meanPair(acc) {
157
+ const baseline = roundColor(acc.br / acc.n, acc.bg / acc.n, acc.bb / acc.n);
158
+ const current = roundColor(acc.cr / acc.n, acc.cg / acc.n, acc.cb / acc.n);
159
+ return {
160
+ baseline,
161
+ current,
162
+ distance: Math.round(rgbDistance(baseline, current))
163
+ };
164
+ }
165
+ function roundColor(r, g, b) {
166
+ const ri = Math.round(r);
167
+ const gi = Math.round(g);
168
+ const bi = Math.round(b);
169
+ return {
170
+ r: ri,
171
+ g: gi,
172
+ b: bi,
173
+ hex: toHex(ri, gi, bi)
174
+ };
175
+ }
176
+ /**
177
+ * Sample a region's color pair from the pixels that actually differ.
178
+ *
179
+ * A region-wide median (the old behaviour) reflects the unchanged majority
180
+ * and reads as "no change" on exactly the regions that changed in a minority
181
+ * of their pixels — e.g. a dark background recolor hidden behind dominant
182
+ * white form inputs (A/B v3 draft 10). We accumulate only pixels whose
183
+ * baseline↔current per-channel delta clears CHANGED_PIXEL_DELTA, falling back
184
+ * to every opaque pixel when nothing clears the gate.
185
+ *
186
+ * When the changed pixels are sparse, the mean is still dominated by
187
+ * antialiasing blends, so we additionally surface the single highest-delta
188
+ * pixel pair as `peak` (draft 11).
189
+ */
190
+ function sampleRegionColorSample(baseline, current, region) {
191
+ const left = Math.max(0, region.x);
192
+ const top = Math.max(0, region.y);
193
+ const right = Math.min(baseline.width, current.width, region.x + region.width);
194
+ const bottom = Math.min(baseline.height, current.height, region.y + region.height);
195
+ if (right <= left || bottom <= top) return void 0;
196
+ const all = makeColorAccumulator();
197
+ const changed = makeColorAccumulator();
198
+ let peakDelta = -1;
199
+ let peakBaseline;
200
+ let peakCurrent;
201
+ for (let y = top; y < bottom; y++) for (let x = left; x < right; x++) {
202
+ const bi = (y * baseline.width + x) * 4;
203
+ const ci = (y * current.width + x) * 4;
204
+ if (baseline.data[bi + 3] === 0 || current.data[ci + 3] === 0) continue;
205
+ const br = baseline.data[bi];
206
+ const bg = baseline.data[bi + 1];
207
+ const bb = baseline.data[bi + 2];
208
+ const cr = current.data[ci];
209
+ const cg = current.data[ci + 1];
210
+ const cb = current.data[ci + 2];
211
+ all.br += br;
212
+ all.bg += bg;
213
+ all.bb += bb;
214
+ all.cr += cr;
215
+ all.cg += cg;
216
+ all.cb += cb;
217
+ all.n++;
218
+ const delta = (Math.abs(br - cr) + Math.abs(bg - cg) + Math.abs(bb - cb)) / 3;
219
+ if (delta > CHANGED_PIXEL_DELTA) {
220
+ changed.br += br;
221
+ changed.bg += bg;
222
+ changed.bb += bb;
223
+ changed.cr += cr;
224
+ changed.cg += cg;
225
+ changed.cb += cb;
226
+ changed.n++;
227
+ if (delta > peakDelta) {
228
+ peakDelta = delta;
229
+ peakBaseline = {
230
+ r: br,
231
+ g: bg,
232
+ b: bb,
233
+ hex: toHex(br, bg, bb)
234
+ };
235
+ peakCurrent = {
236
+ r: cr,
237
+ g: cg,
238
+ b: cb,
239
+ hex: toHex(cr, cg, cb)
240
+ };
241
+ }
242
+ }
243
+ }
244
+ if (all.n === 0) return void 0;
245
+ const sample = meanPair(changed.n > 0 ? changed : all);
246
+ if (changed.n > 0 && peakBaseline && peakCurrent && changed.n < all.n * SPARSE_CHANGE_RATIO && (peakBaseline.hex !== sample.baseline.hex || peakCurrent.hex !== sample.current.hex)) sample.peak = {
247
+ baseline: peakBaseline,
248
+ current: peakCurrent,
249
+ distance: Math.round(rgbDistance(peakBaseline, peakCurrent))
250
+ };
251
+ return sample;
252
+ }
253
+ function toHex(r, g, b) {
254
+ const hex = (value) => value.toString(16).padStart(2, "0");
255
+ return `#${hex(r)}${hex(g)}${hex(b)}`;
256
+ }
257
+ function rgbDistance(a, b) {
258
+ return Math.sqrt((a.r - b.r) ** 2 + (a.g - b.g) ** 2 + (a.b - b.b) ** 2);
259
+ }
260
+ /**
261
+ * Classify a diff region based on its shape relative to the image width.
262
+ * - "edge": thin lines (height <= 2 or width <= 2)
263
+ * - "shift": wide horizontal bands (width/height > 3 and width > 80% image width)
264
+ * - "content": localized changes
265
+ */
266
+ function classifyRegion(regionWidth, regionHeight, imageWidth) {
267
+ if (regionHeight <= 2 || regionWidth <= 2) return "edge";
268
+ if (regionWidth / regionHeight > 3 && regionWidth > imageWidth * .8) return "shift";
269
+ return "content";
270
+ }
271
+ /**
272
+ * Compute luminance profile (average brightness per row).
273
+ */
274
+ function luminanceProfile(data, width, height) {
275
+ const profile = new Float64Array(height);
276
+ for (let y = 0; y < height; y++) {
277
+ let sum = 0;
278
+ for (let x = 0; x < width; x++) {
279
+ const idx = (y * width + x) * 4;
280
+ sum += .299 * data[idx] + .587 * data[idx + 1] + .114 * data[idx + 2];
281
+ }
282
+ profile[y] = sum / width;
283
+ }
284
+ return profile;
285
+ }
286
+ /**
287
+ * Detect global vertical shift between two images using cross-correlation.
288
+ * Returns the offset in pixels (positive = img2 shifted down).
289
+ */
290
+ function detectGlobalShift(baseline, current, maxShift) {
291
+ const height = Math.min(baseline.height, current.height);
292
+ const width = Math.min(baseline.width, current.width);
293
+ const limit = maxShift ?? Math.min(Math.floor(height / 4), 500);
294
+ const profile1 = luminanceProfile(baseline.data, width, height);
295
+ const profile2 = luminanceProfile(current.data, width, height);
296
+ let bestOffset = 0;
297
+ let bestCorr = -Infinity;
298
+ for (let offset = -limit; offset <= limit; offset++) {
299
+ let sum = 0;
300
+ let count = 0;
301
+ for (let y = 0; y < height; y++) {
302
+ const y2 = y + offset;
303
+ if (y2 >= 0 && y2 < height) {
304
+ sum += profile1[y] * profile2[y2];
305
+ count++;
306
+ }
307
+ }
308
+ const corr = count > 0 ? sum / count : 0;
309
+ if (corr > bestCorr) {
310
+ bestCorr = corr;
311
+ bestOffset = offset;
312
+ }
313
+ }
314
+ return bestOffset;
315
+ }
316
+ /**
317
+ * Per-band shift detection — split the image into horizontal bands and run
318
+ * the same cross-correlation per band. Lets us report "section A shifted
319
+ * +8px, section B shifted +20px" instead of a single global average that
320
+ * loses localization.
321
+ *
322
+ * Bands with low luminance variance (e.g. a flat white footer) are dropped
323
+ * because cross-correlation can't lock onto them and the result is noise.
324
+ *
325
+ * Exported for unit testing.
326
+ */
327
+ function detectBandShifts(baseline, current, options = {}) {
328
+ const height = Math.min(baseline.height, current.height);
329
+ const width = Math.min(baseline.width, current.width);
330
+ const bandHeight = Math.max(50, options.bandHeight ?? 240);
331
+ const minConfidence = options.minConfidence ?? .02;
332
+ const limit = options.maxShift ?? Math.min(Math.floor(bandHeight / 2), 400);
333
+ if (height < bandHeight * 2) return [];
334
+ const profile1 = luminanceProfile(baseline.data, width, height);
335
+ const profile2 = luminanceProfile(current.data, width, height);
336
+ const regions = [];
337
+ const bandCount = Math.floor(height / bandHeight);
338
+ for (let b = 0; b < bandCount; b++) {
339
+ const yStart = b * bandHeight;
340
+ const yEnd = b === bandCount - 1 ? height : yStart + bandHeight;
341
+ let mean = 0;
342
+ for (let y = yStart; y < yEnd; y++) mean += profile1[y];
343
+ mean /= yEnd - yStart;
344
+ let variance = 0;
345
+ for (let y = yStart; y < yEnd; y++) {
346
+ const d = profile1[y] - mean;
347
+ variance += d * d;
348
+ }
349
+ variance /= yEnd - yStart;
350
+ if (variance < 5) continue;
351
+ let mean2 = 0;
352
+ for (let y = yStart; y < yEnd; y++) mean2 += profile2[y];
353
+ mean2 /= yEnd - yStart;
354
+ let bestOffset = 0;
355
+ let bestCorr = -Infinity;
356
+ let secondBestCorr = -Infinity;
357
+ let zeroOffsetCorr = 0;
358
+ for (let offset = -limit; offset <= limit; offset++) {
359
+ let sum = 0;
360
+ let count = 0;
361
+ for (let y = yStart; y < yEnd; y++) {
362
+ const y2 = y + offset;
363
+ if (y2 >= 0 && y2 < height) {
364
+ sum += (profile1[y] - mean) * (profile2[y2] - mean2);
365
+ count++;
366
+ }
367
+ }
368
+ const corr = count > 0 ? sum / count : 0;
369
+ if (offset === 0) zeroOffsetCorr = corr;
370
+ if (corr > bestCorr) {
371
+ secondBestCorr = bestCorr;
372
+ bestCorr = corr;
373
+ bestOffset = offset;
374
+ } else if (corr > secondBestCorr) secondBestCorr = corr;
375
+ }
376
+ const confidence = bestCorr > 0 && secondBestCorr > 0 ? Math.min(1, Math.max(0, (bestCorr - secondBestCorr) / bestCorr)) : 0;
377
+ if (bestOffset !== 0 && bestCorr > zeroOffsetCorr && confidence >= minConfidence) regions.push({
378
+ yStart,
379
+ yEnd,
380
+ shift: bestOffset,
381
+ confidence: Number(confidence.toFixed(3))
382
+ });
383
+ }
384
+ return regions;
385
+ }
386
+ /**
387
+ * Count diff pixels after compensating for vertical shift.
388
+ */
389
+ function compensatedDiffCount(baselineData, currentData, width, height, shift, threshold) {
390
+ let count = 0;
391
+ for (let y = 0; y < height; y++) {
392
+ const y2 = y + shift;
393
+ if (y2 < 0 || y2 >= height) {
394
+ count += width;
395
+ continue;
396
+ }
397
+ for (let x = 0; x < width; x++) {
398
+ const idx1 = (y * width + x) * 4;
399
+ const idx2 = (y2 * width + x) * 4;
400
+ const dr = Math.abs(baselineData[idx1] - currentData[idx2]);
401
+ const dg = Math.abs(baselineData[idx1 + 1] - currentData[idx2 + 1]);
402
+ const db = Math.abs(baselineData[idx1 + 2] - currentData[idx2 + 2]);
403
+ if ((dr + dg + db) / 3 > threshold * 255) count++;
404
+ }
405
+ }
406
+ return count;
407
+ }
408
+ /**
409
+ * Generate a compact 10x10 ASCII heatmap of diff distribution.
410
+ */
411
+ function generateCompact(diffData, width, height, diffPixels, totalPixels, regions) {
412
+ const gridSize = 10;
413
+ const cellW = Math.ceil(width / gridSize);
414
+ const cellH = Math.ceil(height / gridSize);
415
+ const grid = Array.from({ length: gridSize }, () => new Array(gridSize).fill(0));
416
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) if (diffData[(y * width + x) * 4 + 1] < 128) {
417
+ const gx = Math.min(Math.floor(x / cellW), gridSize - 1);
418
+ const gy = Math.min(Math.floor(y / cellH), gridSize - 1);
419
+ grid[gy][gx]++;
420
+ }
421
+ const lines = [`diff:${diffPixels}/${totalPixels}(${((1 - diffPixels / totalPixels) * 100).toFixed(0)}%match)`];
422
+ const cellTotal = cellW * cellH;
423
+ for (let gy = 0; gy < gridSize; gy++) lines.push(grid[gy].map((v) => v > cellTotal * .05 ? "X" : ".").join(""));
424
+ if (regions.length > 0) {
425
+ const regionStrs = regions.map((r) => `${r.regionType || "content"}:${r.x},${r.y},${r.width}x${r.height}`);
426
+ lines.push(`regions:${regionStrs.join(";")}`);
427
+ }
428
+ return lines.join("\n");
429
+ }
430
+ /**
431
+ * Generate a comprehensive diff report including clustering, shift detection,
432
+ * and region classification. Compatible with mizchi/pixelmatch 0.5.0 DiffReport format.
433
+ */
434
+ async function generateDiffReport(snapshot, opts = {}) {
435
+ if (!snapshot.baselinePath) return null;
436
+ const r = await runPixelDiff(snapshot.baselinePath, snapshot.screenshotPath, snapshot.testId, opts);
437
+ const regions = detectDiffRegions(r.diffOutput, r.width, r.height);
438
+ let globalShift = 0;
439
+ let shiftRegions = [];
440
+ let compensated = r.diffPixels;
441
+ if (opts.detectShift !== false && r.height > 4) {
442
+ globalShift = detectGlobalShift(r.resizedBaseline, r.resizedCurrent);
443
+ if (globalShift !== 0) {
444
+ compensated = compensatedDiffCount(r.resizedBaseline.data, r.resizedCurrent.data, r.width, r.height, globalShift, r.threshold);
445
+ const bands = detectBandShifts(r.resizedBaseline, r.resizedCurrent);
446
+ shiftRegions = bands.length > 0 ? bands : [{
447
+ yStart: 0,
448
+ yEnd: r.height,
449
+ shift: globalShift
450
+ }];
451
+ }
452
+ }
453
+ const shiftOnly = regions.length > 0 && regions.every((rg) => rg.regionType === "shift" || rg.regionType === "edge");
454
+ const contentChangeCount = regions.filter((rg) => rg.regionType === "content").length;
455
+ const compact = generateCompact(r.diffOutput, r.width, r.height, r.diffPixels, r.totalPixels, regions);
456
+ return {
457
+ diffPixels: r.diffPixels,
458
+ totalPixels: r.totalPixels,
459
+ diffRatio: r.diffPixels / r.totalPixels,
460
+ regions,
461
+ shiftOnly,
462
+ contentChangeCount,
463
+ globalShift,
464
+ shiftRegions,
465
+ compensatedDiffCount: compensated,
466
+ compact
467
+ };
468
+ }
469
+ /**
470
+ * Whiteout detection: checks if most of the image is white (or a single color).
471
+ */
472
+ function detectWhiteout(data, opts = {}) {
473
+ const threshold = opts.threshold ?? .95;
474
+ const { width, height, data: pixels } = data;
475
+ const total = width * height;
476
+ let whiteCount = 0;
477
+ for (let i = 0; i < total; i++) {
478
+ const offset = i * 4;
479
+ const r = pixels[offset];
480
+ const g = pixels[offset + 1];
481
+ const b = pixels[offset + 2];
482
+ if (r >= 250 && g >= 250 && b >= 250) whiteCount++;
483
+ }
484
+ const whiteRatio = whiteCount / total;
485
+ return {
486
+ isWhiteout: whiteRatio >= threshold,
487
+ whiteRatio
488
+ };
489
+ }
490
+ /**
491
+ * Empty content detection: checks if the image has low entropy.
492
+ */
493
+ function detectEmptyContent(data, opts = {}) {
494
+ const threshold = opts.threshold ?? 8;
495
+ const colorSet = /* @__PURE__ */ new Set();
496
+ const { width, height, data: pixels } = data;
497
+ const total = width * height;
498
+ const stride = Math.max(1, Math.floor(total / 1e4));
499
+ for (let i = 0; i < total; i += stride) {
500
+ const offset = i * 4;
501
+ const color = pixels[offset] << 16 | pixels[offset + 1] << 8 | pixels[offset + 2];
502
+ colorSet.add(color);
503
+ }
504
+ return {
505
+ isEmpty: colorSet.size <= threshold,
506
+ uniqueColors: colorSet.size
507
+ };
508
+ }
509
+ //#endregion
510
+ export { compareScreenshots, detectBandShifts, detectEmptyContent, detectWhiteout, generateDiffReport, sampleRegionColorSample };
@@ -0,0 +1,34 @@
1
+ //#region src/image-resize.d.ts
2
+ type ResolutionPreset = "low" | "medium" | "high" | "full";
3
+ declare const RESOLUTION_PRESETS: Record<ResolutionPreset, {
4
+ maxWidth: number;
5
+ maxHeight: number;
6
+ }>;
7
+ /**
8
+ * Select the optimal resolution preset for a given viewport width.
9
+ * Returns the smallest preset with at least half the viewport width.
10
+ */
11
+ declare function resolveResolutionForViewport(viewportWidth: number, maxPreset?: ResolutionPreset): ResolutionPreset;
12
+ interface ResizeOptions {
13
+ /** Preset or custom size */
14
+ resolution?: ResolutionPreset | {
15
+ maxWidth: number;
16
+ maxHeight: number;
17
+ };
18
+ }
19
+ /** Resize PNG buffer to fit within the given size. Preserves aspect ratio. */
20
+ declare function resizePngBuffer(pngBuffer: Buffer, options?: ResizeOptions): Buffer;
21
+ /** Read dimensions from PNG IHDR chunk (no full decode needed) */
22
+ declare function readPngDimensions(buf: Buffer): {
23
+ width: number;
24
+ height: number;
25
+ };
26
+ /** Resize a base64 PNG to the specified resolution. Returns base64. */
27
+ declare function resizeBase64Png(base64: string, options?: ResizeOptions): string;
28
+ /** Get image dimensions */
29
+ declare function getImageDimensions(base64: string): {
30
+ width: number;
31
+ height: number;
32
+ };
33
+ //#endregion
34
+ export { RESOLUTION_PRESETS, ResizeOptions, ResolutionPreset, getImageDimensions, readPngDimensions, resizeBase64Png, resizePngBuffer, resolveResolutionForViewport };
@@ -0,0 +1,92 @@
1
+ import { PNG } from "pngjs";
2
+ //#region src/image-resize.ts
3
+ /**
4
+ * Image resize + VLM optimization
5
+ *
6
+ * Downscale images before sending to VLM to reduce token cost.
7
+ * Supports auto-escalation when resolution is insufficient.
8
+ */
9
+ const RESOLUTION_PRESETS = {
10
+ low: {
11
+ maxWidth: 375,
12
+ maxHeight: 320
13
+ },
14
+ medium: {
15
+ maxWidth: 640,
16
+ maxHeight: 480
17
+ },
18
+ high: {
19
+ maxWidth: 1280,
20
+ maxHeight: 900
21
+ },
22
+ full: {
23
+ maxWidth: 4096,
24
+ maxHeight: 4096
25
+ }
26
+ };
27
+ /**
28
+ * Select the optimal resolution preset for a given viewport width.
29
+ * Returns the smallest preset with at least half the viewport width.
30
+ */
31
+ function resolveResolutionForViewport(viewportWidth, maxPreset = "high") {
32
+ const order = [
33
+ "low",
34
+ "medium",
35
+ "high",
36
+ "full"
37
+ ];
38
+ const maxIdx = order.indexOf(maxPreset);
39
+ for (let i = 0; i <= maxIdx; i++) if (RESOLUTION_PRESETS[order[i]].maxWidth >= viewportWidth / 2) return order[i];
40
+ return maxPreset;
41
+ }
42
+ /** Resize PNG buffer to fit within the given size. Preserves aspect ratio. */
43
+ function resizePngBuffer(pngBuffer, options = {}) {
44
+ const preset = typeof options.resolution === "string" ? RESOLUTION_PRESETS[options.resolution] : options.resolution ?? RESOLUTION_PRESETS.medium;
45
+ const src = PNG.sync.read(pngBuffer);
46
+ if (src.width <= preset.maxWidth && src.height <= preset.maxHeight) return pngBuffer;
47
+ const scale = Math.min(preset.maxWidth / src.width, preset.maxHeight / src.height);
48
+ const targetW = Math.round(src.width * scale);
49
+ const targetH = Math.round(src.height * scale);
50
+ const dst = new PNG({
51
+ width: targetW,
52
+ height: targetH
53
+ });
54
+ const xRatio = src.width / targetW;
55
+ const yRatio = src.height / targetH;
56
+ for (let y = 0; y < targetH; y++) for (let x = 0; x < targetW; x++) {
57
+ const srcX = Math.min(Math.floor(x * xRatio), src.width - 1);
58
+ const si = (Math.min(Math.floor(y * yRatio), src.height - 1) * src.width + srcX) * 4;
59
+ const di = (y * targetW + x) * 4;
60
+ dst.data[di] = src.data[si];
61
+ dst.data[di + 1] = src.data[si + 1];
62
+ dst.data[di + 2] = src.data[si + 2];
63
+ dst.data[di + 3] = src.data[si + 3];
64
+ }
65
+ return Buffer.from(PNG.sync.write(dst));
66
+ }
67
+ /** Read dimensions from PNG IHDR chunk (no full decode needed) */
68
+ function readPngDimensions(buf) {
69
+ if (buf.length >= 24 && buf[0] === 137 && buf[1] === 80) return {
70
+ width: buf.readUInt32BE(16),
71
+ height: buf.readUInt32BE(20)
72
+ };
73
+ const png = PNG.sync.read(buf);
74
+ return {
75
+ width: png.width,
76
+ height: png.height
77
+ };
78
+ }
79
+ /** Resize a base64 PNG to the specified resolution. Returns base64. */
80
+ function resizeBase64Png(base64, options = {}) {
81
+ const preset = typeof options.resolution === "string" ? RESOLUTION_PRESETS[options.resolution] : options.resolution ?? RESOLUTION_PRESETS.medium;
82
+ const buf = Buffer.from(base64, "base64");
83
+ const { width, height } = readPngDimensions(buf);
84
+ if (width <= preset.maxWidth && height <= preset.maxHeight) return base64;
85
+ return resizePngBuffer(buf, options).toString("base64");
86
+ }
87
+ /** Get image dimensions */
88
+ function getImageDimensions(base64) {
89
+ return readPngDimensions(Buffer.from(base64, "base64"));
90
+ }
91
+ //#endregion
92
+ export { RESOLUTION_PRESETS, getImageDimensions, readPngDimensions, resizeBase64Png, resizePngBuffer, resolveResolutionForViewport };
@@ -0,0 +1,15 @@
1
+ import { A11yChange, A11yChangeType, A11yDiff, A11yExpectation, A11yNode, A11ySnapshot, AffectedComponent, AgentContext, Attachment, ChangeIntent, CrossValidationResult, DepEdge, DepGraph, DepNode, DiffHunk, DiffRegion, DiffRegionColor, DiffRegionColorPair, DiffRegionColorSample, DiffRegionSelectorCandidate, DiffRegionShift, DiffRegionType, DiffReport, DiffSemantics, ExpectedA11yChange, FileChange, HtmlSource, IntrospectResult, Language, LoopScore, NlAssertion, PageExpectation, PageIntrospection, PageSpec, PlaywrightReport, ProjectConfig, QualityCheckResult, QualityCheckType, ScoreDetail, ShiftRegion, SpecCheckType, SpecInvariant, TestAttempt, TestError, TestResult, TestSpec, TestSuite, UiSpec, UnifiedAgentContext, VisualChangeType, VisualExpectation, VisualSemanticChange, VisualSemanticDiff, VrtDiff, VrtExpectation, VrtSnapshot, VrtVerdict } from "./types.mjs";
2
+ import { INTERACTIVE_ROLES, LANDMARK_ROLES, checkA11yTree, diffA11yTrees, parsePlaywrightA11ySnapshot, verifyA11yTree } from "./a11y-semantic.mjs";
3
+ import { AUTHORED_PROPERTIES } from "./authored-style-capture.mjs";
4
+ import { TRACKED_PROPERTIES } from "./computed-style-capture.mjs";
5
+ import { diffComputedStyles } from "./computed-style-diff.mjs";
6
+ import { aggregateAuthoredStyleByViewport, diffAuthoredStyles } from "./authored-style-diff.mjs";
7
+ import { createScopedVrtDiff, normalizeVrtDiffRegionPixels, normalizeVrtDiffRegions } from "./diff-regions.mjs";
8
+ import { evaluateDomEquivalence, verifyDomEquivalence } from "./dom-equivalence.mjs";
9
+ import { diffDomPositionStyles, diffPositionStylesAcrossViewports } from "./dom-position-styles.mjs";
10
+ import { findHeatmapRegionsFromFile, findHeatmapRegionsFromRgba } from "./heatmap-regions.mjs";
11
+ import { cropImage, decodePng, encodePng } from "./png-utils.mjs";
12
+ import { compareScreenshots, detectBandShifts, detectEmptyContent, detectWhiteout, generateDiffReport } from "./heatmap.mjs";
13
+ import { RESOLUTION_PRESETS, getImageDimensions, resizePngBuffer, resolveResolutionForViewport } from "./image-resize.mjs";
14
+ import { compareRowTypography, computeRowGapDeltas, extractTextRowsFromFile, extractTextRowsFromRgba, matchTextRows } from "./text-rows.mjs";
15
+ export { A11yChange, A11yChangeType, A11yDiff, A11yExpectation, A11yNode, A11ySnapshot, AUTHORED_PROPERTIES, AffectedComponent, AgentContext, Attachment, ChangeIntent, CrossValidationResult, DepEdge, DepGraph, DepNode, DiffHunk, DiffRegion, DiffRegionColor, DiffRegionColorPair, DiffRegionColorSample, DiffRegionSelectorCandidate, DiffRegionShift, DiffRegionType, DiffReport, DiffSemantics, ExpectedA11yChange, FileChange, HtmlSource, INTERACTIVE_ROLES, IntrospectResult, LANDMARK_ROLES, Language, LoopScore, NlAssertion, PageExpectation, PageIntrospection, PageSpec, PlaywrightReport, ProjectConfig, QualityCheckResult, QualityCheckType, RESOLUTION_PRESETS, ScoreDetail, ShiftRegion, SpecCheckType, SpecInvariant, TRACKED_PROPERTIES, TestAttempt, TestError, TestResult, TestSpec, TestSuite, UiSpec, UnifiedAgentContext, VisualChangeType, VisualExpectation, VisualSemanticChange, VisualSemanticDiff, VrtDiff, VrtExpectation, VrtSnapshot, VrtVerdict, aggregateAuthoredStyleByViewport, checkA11yTree, compareRowTypography, compareScreenshots, computeRowGapDeltas, createScopedVrtDiff, cropImage, decodePng, detectBandShifts, detectEmptyContent, detectWhiteout, diffA11yTrees, diffAuthoredStyles, diffComputedStyles, diffDomPositionStyles, diffPositionStylesAcrossViewports, encodePng, evaluateDomEquivalence, extractTextRowsFromFile, extractTextRowsFromRgba, findHeatmapRegionsFromFile, findHeatmapRegionsFromRgba, generateDiffReport, getImageDimensions, matchTextRows, normalizeVrtDiffRegionPixels, normalizeVrtDiffRegions, parsePlaywrightA11ySnapshot, resizePngBuffer, resolveResolutionForViewport, verifyA11yTree, verifyDomEquivalence };
package/dist/index.mjs ADDED
@@ -0,0 +1,14 @@
1
+ import { INTERACTIVE_ROLES, LANDMARK_ROLES, checkA11yTree, diffA11yTrees, parsePlaywrightA11ySnapshot, verifyA11yTree } from "./a11y-semantic.mjs";
2
+ import { AUTHORED_PROPERTIES } from "./authored-style-capture.mjs";
3
+ import { diffComputedStyles } from "./computed-style-diff.mjs";
4
+ import { aggregateAuthoredStyleByViewport, diffAuthoredStyles } from "./authored-style-diff.mjs";
5
+ import { TRACKED_PROPERTIES } from "./computed-style-capture.mjs";
6
+ import { createScopedVrtDiff, normalizeVrtDiffRegionPixels, normalizeVrtDiffRegions } from "./diff-regions.mjs";
7
+ import { evaluateDomEquivalence, verifyDomEquivalence } from "./dom-equivalence.mjs";
8
+ import { diffDomPositionStyles, diffPositionStylesAcrossViewports } from "./dom-position-styles.mjs";
9
+ import { cropImage, decodePng, encodePng } from "./png-utils.mjs";
10
+ import { compareScreenshots, detectBandShifts, detectEmptyContent, detectWhiteout, generateDiffReport } from "./heatmap.mjs";
11
+ import { findHeatmapRegionsFromFile, findHeatmapRegionsFromRgba } from "./heatmap-regions.mjs";
12
+ import { RESOLUTION_PRESETS, getImageDimensions, resizePngBuffer, resolveResolutionForViewport } from "./image-resize.mjs";
13
+ import { compareRowTypography, computeRowGapDeltas, extractTextRowsFromFile, extractTextRowsFromRgba, matchTextRows } from "./text-rows.mjs";
14
+ export { AUTHORED_PROPERTIES, INTERACTIVE_ROLES, LANDMARK_ROLES, RESOLUTION_PRESETS, TRACKED_PROPERTIES, aggregateAuthoredStyleByViewport, checkA11yTree, compareRowTypography, compareScreenshots, computeRowGapDeltas, createScopedVrtDiff, cropImage, decodePng, detectBandShifts, detectEmptyContent, detectWhiteout, diffA11yTrees, diffAuthoredStyles, diffComputedStyles, diffDomPositionStyles, diffPositionStylesAcrossViewports, encodePng, evaluateDomEquivalence, extractTextRowsFromFile, extractTextRowsFromRgba, findHeatmapRegionsFromFile, findHeatmapRegionsFromRgba, generateDiffReport, getImageDimensions, matchTextRows, normalizeVrtDiffRegionPixels, normalizeVrtDiffRegions, parsePlaywrightA11ySnapshot, resizePngBuffer, resolveResolutionForViewport, verifyA11yTree, verifyDomEquivalence };
@@ -0,0 +1,18 @@
1
+ import { Page } from "playwright";
2
+
3
+ //#region src/mask.d.ts
4
+ /**
5
+ * Inject mask styles into the page.
6
+ * Sets visibility: hidden on target selectors including descendants.
7
+ */
8
+ declare function applyMask(page: Page, selectors: string[]): Promise<void>;
9
+ /**
10
+ * Parse selector array from CLI --mask flags.
11
+ * Supports comma-separated or multiple --mask flags.
12
+ *
13
+ * --mask ".stars,.carousel"
14
+ * --mask ".stars" --mask ".carousel"
15
+ */
16
+ declare function parseMaskSelectors(args: string[]): string[];
17
+ //#endregion
18
+ export { applyMask, parseMaskSelectors };