@mizchi/vlmkit-core 0.9.1 → 0.11.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.
Files changed (57) hide show
  1. package/dist/apng.d.mts +42 -0
  2. package/dist/apng.mjs +199 -0
  3. package/dist/auth-state.d.mts +14 -3
  4. package/dist/auth-state.mjs +30 -6
  5. package/dist/bitmap-font.d.mts +48 -0
  6. package/dist/bitmap-font.mjs +945 -0
  7. package/dist/browser-launch.d.mts +65 -0
  8. package/dist/browser-launch.mjs +194 -0
  9. package/dist/cli-error.d.mts +73 -1
  10. package/dist/cli-error.mjs +164 -32
  11. package/dist/element-compare.mjs +8 -11
  12. package/dist/filmstrip.d.mts +121 -0
  13. package/dist/filmstrip.mjs +181 -0
  14. package/dist/gate-config.d.mts +107 -22
  15. package/dist/gate-config.mjs +138 -9
  16. package/dist/heatmap.d.mts +48 -4
  17. package/dist/heatmap.mjs +157 -12
  18. package/dist/index.d.mts +6 -4
  19. package/dist/index.mjs +4 -2
  20. package/dist/mask.d.mts +66 -2
  21. package/dist/mask.mjs +91 -4
  22. package/dist/page-load.d.mts +83 -0
  23. package/dist/page-load.mjs +116 -0
  24. package/dist/page-open.d.mts +123 -2
  25. package/dist/page-open.mjs +176 -6
  26. package/dist/plugin/args.d.mts +86 -0
  27. package/dist/plugin/args.mjs +162 -0
  28. package/dist/plugin/browser.d.mts +6 -0
  29. package/dist/plugin/browser.mjs +6 -0
  30. package/dist/plugin/cli-entry.d.mts +11 -0
  31. package/dist/plugin/cli-entry.mjs +69 -0
  32. package/dist/plugin/contract.d.mts +270 -0
  33. package/dist/plugin/contract.mjs +51 -0
  34. package/dist/plugin/index.d.mts +82 -0
  35. package/dist/plugin/index.mjs +81 -0
  36. package/dist/plugin/load.d.mts +36 -0
  37. package/dist/plugin/load.mjs +98 -0
  38. package/dist/plugin/registry.d.mts +60 -0
  39. package/dist/plugin/registry.mjs +160 -0
  40. package/dist/plugin/rule-tier.d.mts +65 -0
  41. package/dist/plugin/rule-tier.mjs +77 -0
  42. package/dist/plugin/rules.d.mts +112 -0
  43. package/dist/plugin/rules.mjs +188 -0
  44. package/dist/plugin/runner.d.mts +198 -0
  45. package/dist/plugin/runner.mjs +440 -0
  46. package/dist/png-utils.d.mts +31 -1
  47. package/dist/png-utils.mjs +24 -1
  48. package/dist/rect-overlap.d.mts +41 -0
  49. package/dist/rect-overlap.mjs +28 -0
  50. package/dist/run-ledger.d.mts +56 -2
  51. package/dist/run-ledger.mjs +102 -11
  52. package/dist/types.d.mts +60 -1
  53. package/dist/version.d.mts +20 -0
  54. package/dist/version.mjs +20 -0
  55. package/dist/webp.d.mts +31 -0
  56. package/dist/webp.mjs +105 -0
  57. package/package.json +17 -3
@@ -1,8 +1,30 @@
1
+ import { UsageError } from "./cli-error.mjs";
2
+ import { parseAnnotatedRuleSettings } from "./plugin/rules.mjs";
1
3
  //#region src/gate-config.ts
4
+ /**
5
+ * `vlmkit.gates.json` — one reviewed file that says which gates run on which
6
+ * pages, and holds every suppression with a reason attached.
7
+ *
8
+ * Why this exists: the documented convention was npm scripts, one line per
9
+ * page. Three separate reviewers landed on the same complaint — the scripts
10
+ * stop scaling around twenty pages, and once a `--allow-invisible` or an
11
+ * integrity exemption is inlined in a script, the only way to audit what has
12
+ * been silenced repo-wide is `grep`. A suppression nobody can enumerate is a
13
+ * suppression nobody revisits.
14
+ *
15
+ * Two decisions make the file worth reviewing rather than just worth having:
16
+ *
17
+ * 1. **A suppression must carry a reason.** Parsing fails without one. The
18
+ * flag alone records what was silenced but not why, which is exactly the
19
+ * state that makes a reviewer approve it again a year later.
20
+ * 2. **An expired suppression is dropped, not applied.** It is reported
21
+ * loudly and the gate goes back to failing. An expiry date that keeps
22
+ * working after it passes is a comment, not a deadline.
23
+ */
2
24
  const DAY_MS = 864e5;
3
25
  const GATE_CONFIG_FILENAMES = ["vlmkit.gates.json", ".vlmkit/gates.json"];
4
26
  function fail(path, message) {
5
- throw new Error(`${path}: ${message}`);
27
+ throw new UsageError(`${path}: ${message}`);
6
28
  }
7
29
  function parseSuppression(raw, path) {
8
30
  if (typeof raw !== "object" || raw === null) fail(path, "must be an object");
@@ -39,7 +61,7 @@ function parseGateConfig(raw) {
39
61
  try {
40
62
  data = JSON.parse(raw);
41
63
  } catch (e) {
42
- throw new Error(`gate config is not valid JSON: ${e instanceof Error ? e.message : e}`);
64
+ throw new UsageError(`gate config is not valid JSON: ${e instanceof Error ? e.message : e}`);
43
65
  }
44
66
  if (typeof data !== "object" || data === null) fail("config", "must be a JSON object");
45
67
  const root = data;
@@ -52,6 +74,11 @@ function parseGateConfig(raw) {
52
74
  if (!Array.isArray(d.suppressions)) fail("defaults.suppressions", "must be an array");
53
75
  defaults.suppressions = d.suppressions.map((s, i) => parseSuppression(s, `defaults.suppressions[${i}]`));
54
76
  }
77
+ if (d.rules !== void 0) {
78
+ const parsed = parseAnnotatedRuleSettings(d.rules, "defaults.rules");
79
+ defaults.rules = parsed.settings;
80
+ if (Object.keys(parsed.annotations).length > 0) defaults.ruleAnnotations = parsed.annotations;
81
+ }
55
82
  }
56
83
  if (!Array.isArray(root.pages)) fail("pages", "must be an array");
57
84
  if (root.pages.length === 0) fail("pages", "is empty — nothing would run");
@@ -74,29 +101,111 @@ function parseGateConfig(raw) {
74
101
  if (!Array.isArray(p.suppressions)) fail(`${at}.suppressions`, "must be an array");
75
102
  page.suppressions = p.suppressions.map((s, j) => parseSuppression(s, `${at}.suppressions[${j}]`));
76
103
  }
104
+ if (p.rules !== void 0) {
105
+ const parsed = parseAnnotatedRuleSettings(p.rules, `${at}.rules`);
106
+ page.rules = parsed.settings;
107
+ if (Object.keys(parsed.annotations).length > 0) page.ruleAnnotations = parsed.annotations;
108
+ }
77
109
  if (!page.gates && !page.extraGates && !defaults.gates) fail(at, `no gates: set ${at}.gates or defaults.gates`);
78
110
  return page;
79
111
  });
80
112
  return {
113
+ ...root.webServer !== void 0 ? { webServer: parseWebServer(root.webServer) } : {},
81
114
  ...Object.keys(defaults).length > 0 ? { defaults } : {},
82
115
  pages
83
116
  };
84
117
  }
118
+ function parseWebServer(raw) {
119
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) fail("webServer", "must be an object");
120
+ const w = raw;
121
+ if (typeof w.command !== "string" || !w.command.trim()) fail("webServer", "command is required");
122
+ if (typeof w.url !== "string" || !/^https?:\/\//.test(w.url)) fail("webServer", `url is required and must be http(s), got ${JSON.stringify(w.url)}`);
123
+ const server = {
124
+ command: w.command.trim(),
125
+ url: w.url.trim()
126
+ };
127
+ if (w.timeout !== void 0) {
128
+ if (typeof w.timeout !== "number" || !Number.isFinite(w.timeout) || w.timeout <= 0) fail("webServer", `timeout must be a positive number of ms, got ${JSON.stringify(w.timeout)}`);
129
+ server.timeout = w.timeout;
130
+ }
131
+ if (w.reuseExistingServer !== void 0) {
132
+ if (typeof w.reuseExistingServer !== "boolean") fail("webServer", "reuseExistingServer must be a boolean");
133
+ server.reuseExistingServer = w.reuseExistingServer;
134
+ }
135
+ if (w.cwd !== void 0) {
136
+ if (typeof w.cwd !== "string" || !w.cwd.trim()) fail("webServer", "cwd must be a non-empty string");
137
+ server.cwd = w.cwd.trim();
138
+ }
139
+ if (w.env !== void 0) {
140
+ if (typeof w.env !== "object" || w.env === null || Array.isArray(w.env)) fail("webServer.env", "must be an object");
141
+ const env = {};
142
+ for (const [key, value] of Object.entries(w.env)) {
143
+ if (typeof value !== "string") fail(`webServer.env["${key}"]`, `must be a string, got ${JSON.stringify(value)}`);
144
+ env[key] = value;
145
+ }
146
+ server.env = env;
147
+ }
148
+ return server;
149
+ }
150
+ /**
151
+ * Whether to reuse a server already listening. Playwright's default, and for
152
+ * Playwright's reason: locally the listening port is your own `npm run dev`; in
153
+ * CI it is usually a leaked process from an earlier job, and reusing it gates a
154
+ * build nobody asked about.
155
+ */
156
+ function shouldReuseExistingServer(server, env = process.env) {
157
+ return server.reuseExistingServer ?? !env.CI;
158
+ }
85
159
  /** UTC midnight, so "expires today" behaves the same in every timezone. */
86
160
  function utcDay(date) {
87
161
  return Math.floor(date.getTime() / DAY_MS);
88
162
  }
89
163
  function resolveSuppression(s, scope, now) {
90
- if (!s.expires) return {
164
+ const base = {
91
165
  ...s,
92
166
  scope,
167
+ kind: "suppression"
168
+ };
169
+ if (!s.expires) return {
170
+ ...base,
93
171
  status: "permanent",
94
172
  daysLeft: null
95
173
  };
96
174
  const daysLeft = utcDay(/* @__PURE__ */ new Date(`${s.expires}T00:00:00Z`)) - utcDay(now);
97
175
  return {
98
- ...s,
176
+ ...base,
177
+ status: daysLeft < 0 ? "expired" : "active",
178
+ daysLeft
179
+ };
180
+ }
181
+ /**
182
+ * Resolve one long-form `rules` entry onto the same shape as a suppression, so
183
+ * the inventory, the expiry notice and `--require-expiry` cover both.
184
+ *
185
+ * `gate` is the gate portion of the reference (`check.integrity/text-collision`
186
+ * -> `check.integrity`), which is what a reader scanning the inventory wants to
187
+ * see; a bare rule id has no gate to name and reports as `*`.
188
+ */
189
+ function resolveRuleSetting(ref, entry, scope, now) {
190
+ const slash = ref.indexOf("/");
191
+ const base = {
192
+ gate: slash > 0 ? ref.slice(0, slash) : ref.includes(".") ? ref : "*",
193
+ flag: `--rule ${ref}=${entry.setting}`,
194
+ reason: entry.reason,
195
+ ...entry.owner ? { owner: entry.owner } : {},
196
+ ...entry.expires ? { expires: entry.expires } : {},
99
197
  scope,
198
+ kind: "rule",
199
+ ref
200
+ };
201
+ if (!entry.expires) return {
202
+ ...base,
203
+ status: "permanent",
204
+ daysLeft: null
205
+ };
206
+ const daysLeft = utcDay(/* @__PURE__ */ new Date(`${entry.expires}T00:00:00Z`)) - utcDay(now);
207
+ return {
208
+ ...base,
100
209
  status: daysLeft < 0 ? "expired" : "active",
101
210
  daysLeft
102
211
  };
@@ -114,24 +223,40 @@ function resolveGatePlan(config, options = {}) {
114
223
  const only = options.only?.filter((s) => s.trim()) ?? [];
115
224
  const defaultGates = config.defaults?.gates ?? [];
116
225
  const defaultSuppressions = (config.defaults?.suppressions ?? []).map((s) => resolveSuppression(s, "defaults", now));
226
+ const defaultRuleSettings = Object.entries(config.defaults?.ruleAnnotations ?? {}).map(([ref, entry]) => resolveRuleSetting(ref, entry, "defaults", now));
117
227
  const jobs = [];
118
- const suppressions = [...defaultSuppressions];
228
+ const suppressions = [...defaultSuppressions, ...defaultRuleSettings];
119
229
  for (const page of config.pages) {
120
230
  const pageId = page.id ?? page.source;
121
231
  const pageSuppressions = (page.suppressions ?? []).map((s) => resolveSuppression(s, pageId, now));
122
232
  suppressions.push(...pageSuppressions);
233
+ const pageRuleSettings = Object.entries(page.ruleAnnotations ?? {}).map(([ref, entry]) => resolveRuleSetting(ref, entry, pageId, now));
234
+ suppressions.push(...pageRuleSettings);
123
235
  if (only.length > 0 && !only.some((o) => pageId.includes(o) || page.source.includes(o))) continue;
124
236
  const gates = [...page.gates ?? defaultGates, ...page.extraGates ?? []];
125
- if (gates.length === 0) throw new Error(`Page "${pageId}" resolved to zero gates — set its \`gates\` or \`defaults.gates\`. A page that silently runs nothing is worse than a config error.`);
237
+ if (gates.length === 0) throw new UsageError(`Page "${pageId}" resolved to zero gates — set its \`gates\` or \`defaults.gates\`. A page that silently runs nothing is worse than a config error.`);
126
238
  const candidates = [...defaultSuppressions, ...pageSuppressions];
239
+ const merged = {
240
+ ...config.defaults?.rules,
241
+ ...page.rules
242
+ };
243
+ const shadowed = new Set(Object.keys(page.ruleAnnotations ?? {}));
244
+ for (const resolved of defaultRuleSettings) if (resolved.status === "expired" && !shadowed.has(resolved.ref)) delete merged[resolved.ref];
245
+ for (const resolved of pageRuleSettings) if (resolved.status === "expired") delete merged[resolved.ref];
246
+ const rules = merged;
127
247
  for (const baseGate of gates) {
128
248
  const applied = candidates.filter((s) => s.status !== "expired" && gateMatches(baseGate, s.gate));
129
249
  jobs.push({
130
250
  pageId,
131
251
  source: page.source,
132
252
  baseGate,
133
- gate: [baseGate, ...applied.map((s) => s.flag)].join(" "),
134
- appliedSuppressions: applied
253
+ gate: [
254
+ baseGate,
255
+ ...applied.map((s) => s.flag),
256
+ ...ruleFlags(options.rulesForGate ? options.rulesForGate(baseGate, rules) : rules)
257
+ ].join(" "),
258
+ appliedSuppressions: applied,
259
+ rules
135
260
  });
136
261
  }
137
262
  }
@@ -141,6 +266,10 @@ function resolveGatePlan(config, options = {}) {
141
266
  expired: suppressions.filter((s) => s.status === "expired")
142
267
  };
143
268
  }
269
+ /** `{ "check.integrity/text-collision": "off" }` → `["--rule", "check.integrity/text-collision=off"]`. */
270
+ function ruleFlags(rules) {
271
+ return Object.entries(rules).flatMap(([ref, setting]) => ["--rule", `${ref}=${setting}`]);
272
+ }
144
273
  /**
145
274
  * Token-wise prefix match: `check copy` matches `check copy --manifest x.txt`
146
275
  * but not `check copyright`, and `check` matches every check gate.
@@ -166,4 +295,4 @@ function summarizeSuppressions(suppressions, soonDays = 30) {
166
295
  };
167
296
  }
168
297
  //#endregion
169
- export { GATE_CONFIG_FILENAMES, gateMatches, parseGateConfig, resolveGatePlan, resolveSuppression, summarizeSuppressions };
298
+ export { GATE_CONFIG_FILENAMES, gateMatches, parseGateConfig, resolveGatePlan, resolveRuleSetting, resolveSuppression, ruleFlags, shouldReuseExistingServer, summarizeSuppressions };
@@ -1,15 +1,57 @@
1
- import { DiffRegionColorSample, DiffReport, ShiftRegion, VrtDiff, VrtSnapshot } from "./types.mjs";
1
+ import { DiffIgnoreRegion, DiffRegionColorSample, DiffReport, ShiftRegion, VrtDiff, VrtSnapshot } from "./types.mjs";
2
2
  import { PngData } from "./png-utils.mjs";
3
3
 
4
4
  //#region src/heatmap.d.ts
5
+ /**
6
+ * Parse `"<x>,<y>,<w>x<h>"` (e.g. `"0,300,640x60"`) into an ignore rect.
7
+ *
8
+ * This spelling, rather than `baseline approve --region`'s `x=,y=,w=,h=`,
9
+ * because it is the spelling `diff png` already *prints* regions in — the
10
+ * round-trip from "the report says `(0,300) 640x60`" to "ignore that" should be
11
+ * copy-paste, not translation.
12
+ *
13
+ * Zero-area rects are rejected: `"0,0,0x0"` masks nothing, so accepting it
14
+ * would only ever mean the caller mistyped and got silence.
15
+ */
16
+ declare function parseIgnoreRegionSpec(value: string): DiffIgnoreRegion;
5
17
  /**
6
18
  * Compare two screenshots pixel-by-pixel and generate a diff heatmap.
7
19
  */
8
20
  declare function compareScreenshots(snapshot: VrtSnapshot, opts?: {
9
21
  threshold?: number;
10
22
  outputDir?: string;
11
- skipHeatmap?: boolean;
23
+ skipHeatmap?: boolean; /** Override the adaptive grid. See `adaptiveRegionCellSize`. */
24
+ regionCellSize?: number;
25
+ /**
26
+ * Rectangles that are non-deterministic by construction (particles, a
27
+ * timer readout) and should never be measured. Distinct from an approval:
28
+ * nothing is recorded, nothing expires, and there is nothing for a
29
+ * suppression stocktake to list. See `applyIgnoreRegions` and
30
+ * `DiffMaskSummary` for the effect on `diffRatio`.
31
+ */
32
+ ignoreRegions?: DiffIgnoreRegion[];
12
33
  }): Promise<VrtDiff | null>;
34
+ /**
35
+ * Cell size for region detection, scaled to the image.
36
+ *
37
+ * A fixed 32px grid is right for a page screenshot and wrong for a game frame, and the
38
+ * failure is not cosmetic — it changes which element gets blamed. Measured on a 640x360
39
+ * HUD whose only change was an HP bar's fill (`(106,16) 90x20`, vlmkit#117): the reported
40
+ * region was `(96,0) 128x64`, larger than the `200x20` element that caused it, and
41
+ * attribution then scored the full-frame ancestor at 0.391 against the real cause at
42
+ * 0.385. The ancestor won by 0.006.
43
+ *
44
+ * That near-tie is a *symptom*, not a second bug. `regionCoverage` is the dominant term
45
+ * (weight 0.7), and a region coarser than the element hands the ancestor a free 1.0 while
46
+ * starving the leaf. At a 16px grid the same case scores 0.590 for the leaf against 0.388
47
+ * for the ancestor — no change to the scoring function required.
48
+ *
49
+ * So: keep 32 wherever it has been working, and refine only the small frames where it
50
+ * cannot be right. Bucketed rather than continuous (`min/40` or similar) because a
51
+ * continuous function would shift region geometry on nearly every existing image, and
52
+ * region bboxes appear in baselines, approvals and reports.
53
+ */
54
+ declare function adaptiveRegionCellSize(width: number, height: number): number;
13
55
  /**
14
56
  * Sample a region's color pair from the pixels that actually differ.
15
57
  *
@@ -62,7 +104,9 @@ declare function generateDiffReport(snapshot: VrtSnapshot, opts?: {
62
104
  threshold?: number;
63
105
  outputDir?: string;
64
106
  skipHeatmap?: boolean;
65
- detectShift?: boolean;
107
+ detectShift?: boolean; /** Override the adaptive grid. See `adaptiveRegionCellSize`. */
108
+ regionCellSize?: number; /** See `compareScreenshots`. Shift detection is NOT masked — see below. */
109
+ ignoreRegions?: DiffIgnoreRegion[];
66
110
  }): Promise<DiffReport | null>;
67
111
  /**
68
112
  * Whiteout detection: checks if most of the image is white (or a single color).
@@ -83,4 +127,4 @@ declare function detectEmptyContent(data: PngData, opts?: {
83
127
  uniqueColors: number;
84
128
  };
85
129
  //#endregion
86
- export { compareScreenshots, detectBandShifts, detectEmptyContent, detectWhiteout, generateDiffReport, sampleRegionColorSample };
130
+ export { adaptiveRegionCellSize, compareScreenshots, detectBandShifts, detectEmptyContent, detectWhiteout, generateDiffReport, parseIgnoreRegionSpec, sampleRegionColorSample };
package/dist/heatmap.mjs CHANGED
@@ -1,6 +1,107 @@
1
1
  import { cropImage, decodePng, encodePng } from "./png-utils.mjs";
2
2
  import { estimateRegionShift } from "./region-shift.mjs";
3
3
  //#region src/heatmap.ts
4
+ /**
5
+ * Colour written into the heatmap over ignored pixels.
6
+ *
7
+ * Not white: white means "these pixels matched", and a reader who opens the
8
+ * heatmap to check a suspiciously clean result must be able to see the hole.
9
+ * Chosen so neither downstream hot-pixel test fires on it — `detectDiffRegions`
10
+ * and `generateCompact` want green < 128 (this is 200), and
11
+ * `findHeatmapRegionsFromRgba` wants red − max(green, blue) >= 60 (this is
12
+ * −85).
13
+ */
14
+ const IGNORED_HEATMAP_RGB = [
15
+ 170,
16
+ 200,
17
+ 255
18
+ ];
19
+ /**
20
+ * Parse `"<x>,<y>,<w>x<h>"` (e.g. `"0,300,640x60"`) into an ignore rect.
21
+ *
22
+ * This spelling, rather than `baseline approve --region`'s `x=,y=,w=,h=`,
23
+ * because it is the spelling `diff png` already *prints* regions in — the
24
+ * round-trip from "the report says `(0,300) 640x60`" to "ignore that" should be
25
+ * copy-paste, not translation.
26
+ *
27
+ * Zero-area rects are rejected: `"0,0,0x0"` masks nothing, so accepting it
28
+ * would only ever mean the caller mistyped and got silence.
29
+ */
30
+ function parseIgnoreRegionSpec(value) {
31
+ const match = /^\s*(-?\d+)\s*,\s*(-?\d+)\s*,\s*(\d+)\s*[xX*]\s*(\d+)\s*$/.exec(value);
32
+ if (!match) throw new Error(`invalid ignore region "${value}" — expected "<x>,<y>,<w>x<h>", e.g. "0,300,640x60"`);
33
+ const [x, y, width, height] = match.slice(1, 5).map(Number);
34
+ if (width <= 0 || height <= 0) throw new Error(`invalid ignore region "${value}" — width and height must be positive, got ${width}x${height}`);
35
+ return {
36
+ x,
37
+ y,
38
+ width,
39
+ height
40
+ };
41
+ }
42
+ /**
43
+ * Blank ignored pixels out of the pixelmatch output and account for what was lost.
44
+ *
45
+ * Both halves of "never measured" happen here, and deliberately in one place:
46
+ * the pixels stop counting toward `diffPixels` *and* they disappear from the
47
+ * buffer `detectDiffRegions` clusters, so a noisy strip produces neither a
48
+ * ratio contribution nor a phantom region. Doing only the first would leave a
49
+ * region whose `diffPixelCount` is 0 — worse than useless for attribution.
50
+ *
51
+ * The `covered` bitmap exists so overlapping rects are counted once. Without it
52
+ * two rects that overlap by 100px would report 100 more ignored pixels than
53
+ * exist, and `imagePixels - ignoredPixels === totalPixels` would stop holding —
54
+ * which is the one identity a reader can use to audit the number.
55
+ *
56
+ * Known limitation: region *bboxes* are cell-aligned, so a diff cell touching a
57
+ * mask edge still yields a region whose box overlaps the mask, and that box's
58
+ * `colorSample` / `shift` are sampled from the source images, not from this
59
+ * buffer. Colours for a region abutting a mask can therefore still be tinted by
60
+ * ignored pixels. The mask governs what counts as a difference, not what a
61
+ * surviving region's colours are averaged over.
62
+ */
63
+ function applyIgnoreRegions(diffOutput, width, height, regions) {
64
+ const covered = new Uint8Array(width * height);
65
+ const reported = [];
66
+ for (const region of regions) {
67
+ const left = Math.max(0, Math.trunc(region.x));
68
+ const top = Math.max(0, Math.trunc(region.y));
69
+ const right = Math.min(width, Math.trunc(region.x) + Math.trunc(region.width));
70
+ const bottom = Math.min(height, Math.trunc(region.y) + Math.trunc(region.height));
71
+ let pixels = 0;
72
+ let diffPixels = 0;
73
+ for (let y = top; y < bottom; y++) for (let x = left; x < right; x++) {
74
+ const index = y * width + x;
75
+ pixels++;
76
+ if (diffOutput[index * 4 + 1] < 128) diffPixels++;
77
+ covered[index] = 1;
78
+ }
79
+ reported.push({
80
+ ...region,
81
+ pixels,
82
+ diffPixels
83
+ });
84
+ }
85
+ let ignoredPixels = 0;
86
+ let ignoredDiffPixels = 0;
87
+ const [mr, mg, mb] = IGNORED_HEATMAP_RGB;
88
+ for (let index = 0; index < covered.length; index++) {
89
+ if (!covered[index]) continue;
90
+ ignoredPixels++;
91
+ const offset = index * 4;
92
+ if (diffOutput[offset + 1] < 128) ignoredDiffPixels++;
93
+ diffOutput[offset] = mr;
94
+ diffOutput[offset + 1] = mg;
95
+ diffOutput[offset + 2] = mb;
96
+ diffOutput[offset + 3] = 255;
97
+ }
98
+ return {
99
+ regions: reported,
100
+ ignoredPixels,
101
+ ignoredDiffPixels,
102
+ imagePixels: width * height
103
+ };
104
+ }
4
105
  async function runPixelDiff(baselinePath, screenshotPath, testId, opts) {
5
106
  const pixelmatch = (await import("pixelmatch")).default;
6
107
  const baseline = await decodePng(baselinePath);
@@ -17,12 +118,15 @@ async function runPixelDiff(baselinePath, screenshotPath, testId, opts) {
17
118
  }
18
119
  const width = resizedBaseline.width;
19
120
  const height = resizedBaseline.height;
20
- const totalPixels = width * height + overflowPixels;
21
121
  const diffOutput = new Uint8Array(width * height * 4);
22
122
  const threshold = opts.threshold ?? .1;
23
- const diffPixels = overflowPixels + pixelmatch(resizedBaseline.data, resizedCurrent.data, diffOutput, width, height, { threshold });
123
+ const rawDiffPixels = pixelmatch(resizedBaseline.data, resizedCurrent.data, diffOutput, width, height, { threshold });
124
+ const mask = opts.ignoreRegions && opts.ignoreRegions.length > 0 ? applyIgnoreRegions(diffOutput, width, height, opts.ignoreRegions) : void 0;
125
+ const ignoredPixels = mask?.ignoredPixels ?? 0;
126
+ const totalPixels = width * height - ignoredPixels + overflowPixels;
127
+ const diffPixels = overflowPixels + rawDiffPixels - (mask?.ignoredDiffPixels ?? 0);
24
128
  let heatmapPath;
25
- if (opts.outputDir && diffPixels > 0 && !opts.skipHeatmap) {
129
+ if (opts.outputDir && (diffPixels > 0 || ignoredPixels > 0) && !opts.skipHeatmap) {
26
130
  const safeName = testId.replace(/[/\\:]/g, "_");
27
131
  heatmapPath = `${opts.outputDir}/${safeName}_heatmap.png`;
28
132
  await encodePng(heatmapPath, {
@@ -40,32 +144,72 @@ async function runPixelDiff(baselinePath, screenshotPath, testId, opts) {
40
144
  threshold,
41
145
  resizedBaseline,
42
146
  resizedCurrent,
43
- heatmapPath
147
+ heatmapPath,
148
+ ...mask ? { mask } : {}
44
149
  };
45
150
  }
46
151
  /**
152
+ * `diffPixels / totalPixels`, with the degenerate case named.
153
+ *
154
+ * A mask covering the whole compared area leaves nothing measured, and 0/0 must
155
+ * not surface as `NaN` — it serialises to `null` in JSON and compares false
156
+ * against every threshold, so a gate would silently pass. 0 with a mask summary
157
+ * saying `ignoredPixels === imagePixels` is the honest reading: nothing changed
158
+ * *of what was looked at*, and nothing was looked at.
159
+ */
160
+ function safeDiffRatio(diffPixels, totalPixels) {
161
+ return totalPixels > 0 ? diffPixels / totalPixels : 0;
162
+ }
163
+ /**
47
164
  * Compare two screenshots pixel-by-pixel and generate a diff heatmap.
48
165
  */
49
166
  async function compareScreenshots(snapshot, opts = {}) {
50
167
  if (!snapshot.baselinePath) return null;
51
168
  const r = await runPixelDiff(snapshot.baselinePath, snapshot.screenshotPath, snapshot.testId, opts);
52
- const regions = detectDiffRegions(r.diffOutput, r.width, r.height);
169
+ const regions = detectDiffRegions(r.diffOutput, r.width, r.height, opts.regionCellSize);
53
170
  attachRegionColorSamples(regions, r.resizedBaseline, r.resizedCurrent);
54
171
  attachRegionShiftEstimates(regions, r.resizedBaseline, r.resizedCurrent);
55
172
  return {
56
173
  snapshot,
57
174
  diffPixels: r.diffPixels,
58
175
  totalPixels: r.totalPixels,
59
- diffRatio: r.diffPixels / r.totalPixels,
176
+ diffRatio: safeDiffRatio(r.diffPixels, r.totalPixels),
60
177
  heatmapPath: r.heatmapPath,
61
- regions
178
+ regions,
179
+ ...r.mask ? { mask: r.mask } : {}
62
180
  };
63
181
  }
64
182
  /**
183
+ * Cell size for region detection, scaled to the image.
184
+ *
185
+ * A fixed 32px grid is right for a page screenshot and wrong for a game frame, and the
186
+ * failure is not cosmetic — it changes which element gets blamed. Measured on a 640x360
187
+ * HUD whose only change was an HP bar's fill (`(106,16) 90x20`, vlmkit#117): the reported
188
+ * region was `(96,0) 128x64`, larger than the `200x20` element that caused it, and
189
+ * attribution then scored the full-frame ancestor at 0.391 against the real cause at
190
+ * 0.385. The ancestor won by 0.006.
191
+ *
192
+ * That near-tie is a *symptom*, not a second bug. `regionCoverage` is the dominant term
193
+ * (weight 0.7), and a region coarser than the element hands the ancestor a free 1.0 while
194
+ * starving the leaf. At a 16px grid the same case scores 0.590 for the leaf against 0.388
195
+ * for the ancestor — no change to the scoring function required.
196
+ *
197
+ * So: keep 32 wherever it has been working, and refine only the small frames where it
198
+ * cannot be right. Bucketed rather than continuous (`min/40` or similar) because a
199
+ * continuous function would shift region geometry on nearly every existing image, and
200
+ * region bboxes appear in baselines, approvals and reports.
201
+ */
202
+ function adaptiveRegionCellSize(width, height) {
203
+ const shortSide = Math.min(width, height);
204
+ if (shortSide >= 720) return 32;
205
+ if (shortSide >= 480) return 16;
206
+ return 8;
207
+ }
208
+ /**
65
209
  * Grid-based diff region detection.
66
210
  * Splits image into cells and clusters cells exceeding the diff threshold.
67
211
  */
68
- function detectDiffRegions(diffData, width, height, cellSize = 32) {
212
+ function detectDiffRegions(diffData, width, height, cellSize = adaptiveRegionCellSize(width, height)) {
69
213
  const cols = Math.ceil(width / cellSize);
70
214
  const rows = Math.ceil(height / cellSize);
71
215
  const grid = new Uint32Array(cols * rows);
@@ -418,7 +562,7 @@ function generateCompact(diffData, width, height, diffPixels, totalPixels, regio
418
562
  const gy = Math.min(Math.floor(y / cellH), gridSize - 1);
419
563
  grid[gy][gx]++;
420
564
  }
421
- const lines = [`diff:${diffPixels}/${totalPixels}(${((1 - diffPixels / totalPixels) * 100).toFixed(0)}%match)`];
565
+ const lines = [`diff:${diffPixels}/${totalPixels}(${((1 - safeDiffRatio(diffPixels, totalPixels)) * 100).toFixed(0)}%match)`];
422
566
  const cellTotal = cellW * cellH;
423
567
  for (let gy = 0; gy < gridSize; gy++) lines.push(grid[gy].map((v) => v > cellTotal * .05 ? "X" : ".").join(""));
424
568
  if (regions.length > 0) {
@@ -434,7 +578,7 @@ function generateCompact(diffData, width, height, diffPixels, totalPixels, regio
434
578
  async function generateDiffReport(snapshot, opts = {}) {
435
579
  if (!snapshot.baselinePath) return null;
436
580
  const r = await runPixelDiff(snapshot.baselinePath, snapshot.screenshotPath, snapshot.testId, opts);
437
- const regions = detectDiffRegions(r.diffOutput, r.width, r.height);
581
+ const regions = detectDiffRegions(r.diffOutput, r.width, r.height, opts.regionCellSize);
438
582
  let globalShift = 0;
439
583
  let shiftRegions = [];
440
584
  let compensated = r.diffPixels;
@@ -456,8 +600,9 @@ async function generateDiffReport(snapshot, opts = {}) {
456
600
  return {
457
601
  diffPixels: r.diffPixels,
458
602
  totalPixels: r.totalPixels,
459
- diffRatio: r.diffPixels / r.totalPixels,
603
+ diffRatio: safeDiffRatio(r.diffPixels, r.totalPixels),
460
604
  regions,
605
+ ...r.mask ? { mask: r.mask } : {},
461
606
  shiftOnly,
462
607
  contentChangeCount,
463
608
  globalShift,
@@ -507,4 +652,4 @@ function detectEmptyContent(data, opts = {}) {
507
652
  };
508
653
  }
509
654
  //#endregion
510
- export { compareScreenshots, detectBandShifts, detectEmptyContent, detectWhiteout, generateDiffReport, sampleRegionColorSample };
655
+ export { adaptiveRegionCellSize, compareScreenshots, detectBandShifts, detectEmptyContent, detectWhiteout, generateDiffReport, parseIgnoreRegionSpec, sampleRegionColorSample };
package/dist/index.d.mts CHANGED
@@ -1,5 +1,6 @@
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";
1
+ import { A11yChange, A11yChangeType, A11yDiff, A11yExpectation, A11yNode, A11ySnapshot, AffectedComponent, AgentContext, Attachment, ChangeIntent, CrossValidationResult, DepEdge, DepGraph, DepNode, DiffHunk, DiffIgnoreRegion, DiffIgnoredRegionReport, DiffMaskSummary, 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
2
  import { INTERACTIVE_ROLES, LANDMARK_ROLES, diffA11yTrees, parsePlaywrightA11ySnapshot, verifyA11yTree } from "./a11y-semantic.mjs";
3
+ import { cropImage, decodePng, encodePng } from "./png-utils.mjs";
3
4
  import { AUTHORED_PROPERTIES } from "./authored-style-capture.mjs";
4
5
  import { TRACKED_PROPERTIES } from "./computed-style-capture.mjs";
5
6
  import { diffComputedStyles } from "./computed-style-diff.mjs";
@@ -7,9 +8,10 @@ import { aggregateAuthoredStyleByViewport, diffAuthoredStyles } from "./authored
7
8
  import { createScopedVrtDiff, normalizeVrtDiffRegionPixels, normalizeVrtDiffRegions } from "./diff-regions.mjs";
8
9
  import { verifyDomEquivalence } from "./dom-equivalence.mjs";
9
10
  import { diffDomPositionStyles, diffPositionStylesAcrossViewports } from "./dom-position-styles.mjs";
11
+ import { FilmstripLayout, FilmstripOptions, composeFilmstrip, filmstripLayout } from "./filmstrip.mjs";
10
12
  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 { compareScreenshots, detectBandShifts, detectEmptyContent, detectWhiteout, generateDiffReport, parseIgnoreRegionSpec } from "./heatmap.mjs";
13
14
  import { RESOLUTION_PRESETS, getImageDimensions, resizePngBuffer, resolveResolutionForViewport } from "./image-resize.mjs";
15
+ import { WebpEncodeOptions, encodeWebp, imageFormatForPath, webpEncoderAvailable } from "./webp.mjs";
14
16
  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, compareRowTypography, compareScreenshots, computeRowGapDeltas, createScopedVrtDiff, cropImage, decodePng, detectBandShifts, detectEmptyContent, detectWhiteout, diffA11yTrees, diffAuthoredStyles, diffComputedStyles, diffDomPositionStyles, diffPositionStylesAcrossViewports, encodePng, extractTextRowsFromFile, extractTextRowsFromRgba, findHeatmapRegionsFromFile, findHeatmapRegionsFromRgba, generateDiffReport, getImageDimensions, matchTextRows, normalizeVrtDiffRegionPixels, normalizeVrtDiffRegions, parsePlaywrightA11ySnapshot, resizePngBuffer, resolveResolutionForViewport, verifyA11yTree, verifyDomEquivalence };
17
+ export { A11yChange, A11yChangeType, A11yDiff, A11yExpectation, A11yNode, A11ySnapshot, AUTHORED_PROPERTIES, AffectedComponent, AgentContext, Attachment, ChangeIntent, CrossValidationResult, DepEdge, DepGraph, DepNode, DiffHunk, DiffIgnoreRegion, DiffIgnoredRegionReport, DiffMaskSummary, DiffRegion, DiffRegionColor, DiffRegionColorPair, DiffRegionColorSample, DiffRegionSelectorCandidate, DiffRegionShift, DiffRegionType, DiffReport, DiffSemantics, ExpectedA11yChange, FileChange, type FilmstripLayout, type FilmstripOptions, 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, type WebpEncodeOptions, aggregateAuthoredStyleByViewport, compareRowTypography, compareScreenshots, composeFilmstrip, computeRowGapDeltas, createScopedVrtDiff, cropImage, decodePng, detectBandShifts, detectEmptyContent, detectWhiteout, diffA11yTrees, diffAuthoredStyles, diffComputedStyles, diffDomPositionStyles, diffPositionStylesAcrossViewports, encodePng, encodeWebp, extractTextRowsFromFile, extractTextRowsFromRgba, filmstripLayout, findHeatmapRegionsFromFile, findHeatmapRegionsFromRgba, generateDiffReport, getImageDimensions, imageFormatForPath, matchTextRows, normalizeVrtDiffRegionPixels, normalizeVrtDiffRegions, parseIgnoreRegionSpec, parsePlaywrightA11ySnapshot, resizePngBuffer, resolveResolutionForViewport, verifyA11yTree, verifyDomEquivalence, webpEncoderAvailable };
package/dist/index.mjs CHANGED
@@ -7,8 +7,10 @@ import { createScopedVrtDiff, normalizeVrtDiffRegionPixels, normalizeVrtDiffRegi
7
7
  import { verifyDomEquivalence } from "./dom-equivalence.mjs";
8
8
  import { diffDomPositionStyles, diffPositionStylesAcrossViewports } from "./dom-position-styles.mjs";
9
9
  import { cropImage, decodePng, encodePng } from "./png-utils.mjs";
10
- import { compareScreenshots, detectBandShifts, detectEmptyContent, detectWhiteout, generateDiffReport } from "./heatmap.mjs";
10
+ import { compareScreenshots, detectBandShifts, detectEmptyContent, detectWhiteout, generateDiffReport, parseIgnoreRegionSpec } from "./heatmap.mjs";
11
+ import { composeFilmstrip, filmstripLayout } from "./filmstrip.mjs";
11
12
  import { findHeatmapRegionsFromFile, findHeatmapRegionsFromRgba } from "./heatmap-regions.mjs";
12
13
  import { RESOLUTION_PRESETS, getImageDimensions, resizePngBuffer, resolveResolutionForViewport } from "./image-resize.mjs";
14
+ import { encodeWebp, imageFormatForPath, webpEncoderAvailable } from "./webp.mjs";
13
15
  import { compareRowTypography, computeRowGapDeltas, extractTextRowsFromFile, extractTextRowsFromRgba, matchTextRows } from "./text-rows.mjs";
14
- export { AUTHORED_PROPERTIES, INTERACTIVE_ROLES, LANDMARK_ROLES, RESOLUTION_PRESETS, TRACKED_PROPERTIES, aggregateAuthoredStyleByViewport, compareRowTypography, compareScreenshots, computeRowGapDeltas, createScopedVrtDiff, cropImage, decodePng, detectBandShifts, detectEmptyContent, detectWhiteout, diffA11yTrees, diffAuthoredStyles, diffComputedStyles, diffDomPositionStyles, diffPositionStylesAcrossViewports, encodePng, extractTextRowsFromFile, extractTextRowsFromRgba, findHeatmapRegionsFromFile, findHeatmapRegionsFromRgba, generateDiffReport, getImageDimensions, matchTextRows, normalizeVrtDiffRegionPixels, normalizeVrtDiffRegions, parsePlaywrightA11ySnapshot, resizePngBuffer, resolveResolutionForViewport, verifyA11yTree, verifyDomEquivalence };
16
+ export { AUTHORED_PROPERTIES, INTERACTIVE_ROLES, LANDMARK_ROLES, RESOLUTION_PRESETS, TRACKED_PROPERTIES, aggregateAuthoredStyleByViewport, compareRowTypography, compareScreenshots, composeFilmstrip, computeRowGapDeltas, createScopedVrtDiff, cropImage, decodePng, detectBandShifts, detectEmptyContent, detectWhiteout, diffA11yTrees, diffAuthoredStyles, diffComputedStyles, diffDomPositionStyles, diffPositionStylesAcrossViewports, encodePng, encodeWebp, extractTextRowsFromFile, extractTextRowsFromRgba, filmstripLayout, findHeatmapRegionsFromFile, findHeatmapRegionsFromRgba, generateDiffReport, getImageDimensions, imageFormatForPath, matchTextRows, normalizeVrtDiffRegionPixels, normalizeVrtDiffRegions, parseIgnoreRegionSpec, parsePlaywrightA11ySnapshot, resizePngBuffer, resolveResolutionForViewport, verifyA11yTree, verifyDomEquivalence, webpEncoderAvailable };