@mizchi/vlmkit-core 0.8.1 → 0.9.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.
@@ -2,8 +2,8 @@
2
2
  import { compareScreenshots } from "./heatmap.mjs";
3
3
  import { applyMask, parseMaskSelectors } from "./mask.mjs";
4
4
  import { BOLD, CYAN, DIM, GREEN, RED, RESET, YELLOW, hr } from "./terminal-colors.mjs";
5
- import { mkdir, readFile, writeFile } from "node:fs/promises";
6
5
  import { join, resolve } from "node:path";
6
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
7
7
  import { chromium } from "playwright";
8
8
  //#region src/element-compare.ts
9
9
  /**
@@ -13,9 +13,9 @@ import { chromium } from "playwright";
13
13
  * compares individual DOM elements independently via locator.screenshot().
14
14
  *
15
15
  * Usage:
16
- * vrt elements --url http://localhost:3000/ --current-url http://localhost:8080/ \
16
+ * vlmkit diff elements --url http://localhost:3000/ --current-url http://localhost:8080/ \
17
17
  * --selectors "header,main,footer"
18
- * vrt elements before.html after.html --selectors "header,.content,.sidebar"
18
+ * vlmkit diff elements before.html after.html --selectors "header,.content,.sidebar"
19
19
  */
20
20
  async function captureElementScreenshot(page, selector, outputPath) {
21
21
  const locator = page.locator(selector).first();
@@ -194,12 +194,12 @@ function parseArgs(args) {
194
194
  function formatUsage() {
195
195
  return [
196
196
  "Usage:",
197
- " vrt diff component --url <baseline> --current-url <current> --selectors \"header,main,footer\"",
198
- " vrt diff component before.html after.html --selectors \"header,.content\"",
197
+ " vlmkit diff component --url <baseline> --current-url <current> --selectors \"header,main,footer\"",
198
+ " vlmkit diff component before.html after.html --selectors \"header,.content\"",
199
199
  "",
200
200
  "Aliases:",
201
- " vrt diff elements",
202
- " vrt elements",
201
+ " vlmkit diff elements",
202
+ " vlmkit diff elements",
203
203
  "",
204
204
  "Options:",
205
205
  " --selectors <sel1,sel2,...> CSS selectors to compare (required)",
@@ -261,7 +261,7 @@ async function main() {
261
261
  console.log(` ${DIM}Report: ${reportPath}${RESET}`);
262
262
  console.log();
263
263
  }
264
- if (process.env.__VRT_DISPATCHER_LEAF__ === "element-compare" || process.argv[1]?.endsWith("element-compare.ts")) main().catch((e) => {
264
+ if (process.env.__VLMKIT_DISPATCHER_LEAF__ === "element-compare" || process.argv[1]?.endsWith("element-compare.ts")) main().catch((e) => {
265
265
  console.error(e);
266
266
  process.exit(1);
267
267
  });
@@ -0,0 +1,116 @@
1
+ //#region src/gate-config.d.ts
2
+ /**
3
+ * `vlmkit.gates.json` — one reviewed file that says which gates run on which
4
+ * pages, and holds every suppression with a reason attached.
5
+ *
6
+ * Why this exists: the documented convention was npm scripts, one line per
7
+ * page. Three separate reviewers landed on the same complaint — the scripts
8
+ * stop scaling around twenty pages, and once a `--allow-invisible` or an
9
+ * integrity exemption is inlined in a script, the only way to audit what has
10
+ * been silenced repo-wide is `grep`. A suppression nobody can enumerate is a
11
+ * suppression nobody revisits.
12
+ *
13
+ * Two decisions make the file worth reviewing rather than just worth having:
14
+ *
15
+ * 1. **A suppression must carry a reason.** Parsing fails without one. The
16
+ * flag alone records what was silenced but not why, which is exactly the
17
+ * state that makes a reviewer approve it again a year later.
18
+ * 2. **An expired suppression is dropped, not applied.** It is reported
19
+ * loudly and the gate goes back to failing. An expiry date that keeps
20
+ * working after it passes is a comment, not a deadline.
21
+ */
22
+ interface GateSuppression {
23
+ /**
24
+ * Gate this applies to, as a prefix of the gate command: `check copy`
25
+ * matches `check copy --manifest x.txt`.
26
+ */
27
+ gate: string;
28
+ /** Flag(s) appended to that gate's invocation, e.g. `--allow-invisible visually-hidden`. */
29
+ flag: string;
30
+ /** Why this is acceptable. Required — an unexplained suppression is unauditable. */
31
+ reason: string;
32
+ /** Who signed off. Optional but reported, so an unowned entry is visible. */
33
+ owner?: string;
34
+ /** `YYYY-MM-DD`. Omitted means permanent, which the inventory counts separately. */
35
+ expires?: string;
36
+ }
37
+ interface GatePage {
38
+ /** Short stable name for `--only` and reports. Defaults to the source. */
39
+ id?: string;
40
+ /** File path, glob, or URL handed to each gate. */
41
+ source: string;
42
+ /** Gate commands for this page. Falls back to `defaults.gates`. */
43
+ gates?: string[];
44
+ /** Extra gates for this page on top of the defaults. */
45
+ extraGates?: string[];
46
+ suppressions?: GateSuppression[];
47
+ }
48
+ interface GateConfig {
49
+ defaults?: {
50
+ gates?: string[];
51
+ suppressions?: GateSuppression[];
52
+ };
53
+ pages: GatePage[];
54
+ }
55
+ interface ResolvedSuppression extends GateSuppression {
56
+ /** Page id this came from, or `defaults`. */
57
+ scope: string;
58
+ status: "active" | "expired" | "permanent";
59
+ /** Days until expiry; negative when overdue, null when permanent. */
60
+ daysLeft: number | null;
61
+ }
62
+ interface GateJob {
63
+ pageId: string;
64
+ source: string;
65
+ /** Gate command with any active suppression flags already appended. */
66
+ gate: string;
67
+ /** The gate as written in the config, before suppression flags. */
68
+ baseGate: string;
69
+ appliedSuppressions: ResolvedSuppression[];
70
+ }
71
+ interface GatePlan {
72
+ jobs: GateJob[];
73
+ /** Every suppression the config declares, resolved against `now`. */
74
+ suppressions: ResolvedSuppression[];
75
+ /**
76
+ * Suppressions past their expiry. Their flags are NOT applied — the gate
77
+ * fails again — and callers are expected to print these before running.
78
+ */
79
+ expired: ResolvedSuppression[];
80
+ }
81
+ declare const GATE_CONFIG_FILENAMES: string[];
82
+ /** Parse and validate. Every error names the JSON path so the fix is obvious. */
83
+ declare function parseGateConfig(raw: string): GateConfig;
84
+ declare function resolveSuppression(s: GateSuppression, scope: string, now: Date): ResolvedSuppression;
85
+ interface ResolveOptions {
86
+ now?: Date;
87
+ /** Page ids or sources to keep. Substring match, so `admin` selects a subtree. */
88
+ only?: string[];
89
+ }
90
+ /**
91
+ * Turn the config into the exact list of gate invocations to run.
92
+ *
93
+ * Suppression flags are appended to matching gates only when active. An
94
+ * expired one is surfaced in `plan.expired` and deliberately left off the
95
+ * command line: the gate returns to failing, which is what an expiry date is
96
+ * supposed to mean.
97
+ */
98
+ declare function resolveGatePlan(config: GateConfig, options?: ResolveOptions): GatePlan;
99
+ /**
100
+ * Token-wise prefix match: `check copy` matches `check copy --manifest x.txt`
101
+ * but not `check copyright`, and `check` matches every check gate.
102
+ */
103
+ declare function gateMatches(gate: string, pattern: string): boolean;
104
+ interface SuppressionSummary {
105
+ rows: ResolvedSuppression[];
106
+ active: number;
107
+ expired: number;
108
+ permanent: number;
109
+ /** Active entries with no owner — visible rather than tolerated silently. */
110
+ unowned: number;
111
+ /** Active entries expiring within `soonDays`. */
112
+ expiringSoon: number;
113
+ }
114
+ declare function summarizeSuppressions(suppressions: ResolvedSuppression[], soonDays?: number): SuppressionSummary;
115
+ //#endregion
116
+ export { GATE_CONFIG_FILENAMES, GateConfig, GateJob, GatePage, GatePlan, GateSuppression, ResolveOptions, ResolvedSuppression, SuppressionSummary, gateMatches, parseGateConfig, resolveGatePlan, resolveSuppression, summarizeSuppressions };
@@ -0,0 +1,169 @@
1
+ //#region src/gate-config.ts
2
+ const DAY_MS = 864e5;
3
+ const GATE_CONFIG_FILENAMES = ["vlmkit.gates.json", ".vlmkit/gates.json"];
4
+ function fail(path, message) {
5
+ throw new Error(`${path}: ${message}`);
6
+ }
7
+ function parseSuppression(raw, path) {
8
+ if (typeof raw !== "object" || raw === null) fail(path, "must be an object");
9
+ const s = raw;
10
+ for (const key of [
11
+ "gate",
12
+ "flag",
13
+ "reason"
14
+ ]) if (typeof s[key] !== "string" || !s[key].trim()) fail(path, `${key} is required and must be a non-empty string`);
15
+ if (s.owner !== void 0 && typeof s.owner !== "string") fail(path, "owner must be a string");
16
+ if (s.expires !== void 0) {
17
+ if (typeof s.expires !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(s.expires)) fail(path, `expires must be YYYY-MM-DD, got ${JSON.stringify(s.expires)}`);
18
+ if (Number.isNaN(Date.parse(`${s.expires}T00:00:00Z`))) fail(path, `expires is not a real date: ${s.expires}`);
19
+ }
20
+ return {
21
+ gate: s.gate.trim(),
22
+ flag: s.flag.trim(),
23
+ reason: s.reason.trim(),
24
+ ...s.owner ? { owner: s.owner } : {},
25
+ ...s.expires ? { expires: s.expires } : {}
26
+ };
27
+ }
28
+ function parseGateList(raw, path) {
29
+ if (!Array.isArray(raw)) fail(path, "must be an array of gate command strings");
30
+ if (raw.length === 0) fail(path, "is empty — remove the key or list at least one gate");
31
+ return raw.map((g, i) => {
32
+ if (typeof g !== "string" || !g.trim()) fail(`${path}[${i}]`, "must be a non-empty string");
33
+ return g.trim();
34
+ });
35
+ }
36
+ /** Parse and validate. Every error names the JSON path so the fix is obvious. */
37
+ function parseGateConfig(raw) {
38
+ let data;
39
+ try {
40
+ data = JSON.parse(raw);
41
+ } catch (e) {
42
+ throw new Error(`gate config is not valid JSON: ${e instanceof Error ? e.message : e}`);
43
+ }
44
+ if (typeof data !== "object" || data === null) fail("config", "must be a JSON object");
45
+ const root = data;
46
+ const defaults = {};
47
+ if (root.defaults !== void 0) {
48
+ if (typeof root.defaults !== "object" || root.defaults === null) fail("defaults", "must be an object");
49
+ const d = root.defaults;
50
+ if (d.gates !== void 0) defaults.gates = parseGateList(d.gates, "defaults.gates");
51
+ if (d.suppressions !== void 0) {
52
+ if (!Array.isArray(d.suppressions)) fail("defaults.suppressions", "must be an array");
53
+ defaults.suppressions = d.suppressions.map((s, i) => parseSuppression(s, `defaults.suppressions[${i}]`));
54
+ }
55
+ }
56
+ if (!Array.isArray(root.pages)) fail("pages", "must be an array");
57
+ if (root.pages.length === 0) fail("pages", "is empty — nothing would run");
58
+ const seen = /* @__PURE__ */ new Set();
59
+ const pages = root.pages.map((raw, i) => {
60
+ const at = `pages[${i}]`;
61
+ if (typeof raw !== "object" || raw === null) fail(at, "must be an object");
62
+ const p = raw;
63
+ if (typeof p.source !== "string" || !p.source.trim()) fail(at, "source is required (path, glob, or URL)");
64
+ const id = typeof p.id === "string" && p.id.trim() ? p.id.trim() : p.source.trim();
65
+ if (seen.has(id)) fail(at, `duplicate page id "${id}" — ids must be unique so --only is unambiguous`);
66
+ seen.add(id);
67
+ const page = {
68
+ id,
69
+ source: p.source.trim()
70
+ };
71
+ if (p.gates !== void 0) page.gates = parseGateList(p.gates, `${at}.gates`);
72
+ if (p.extraGates !== void 0) page.extraGates = parseGateList(p.extraGates, `${at}.extraGates`);
73
+ if (p.suppressions !== void 0) {
74
+ if (!Array.isArray(p.suppressions)) fail(`${at}.suppressions`, "must be an array");
75
+ page.suppressions = p.suppressions.map((s, j) => parseSuppression(s, `${at}.suppressions[${j}]`));
76
+ }
77
+ if (!page.gates && !page.extraGates && !defaults.gates) fail(at, `no gates: set ${at}.gates or defaults.gates`);
78
+ return page;
79
+ });
80
+ return {
81
+ ...Object.keys(defaults).length > 0 ? { defaults } : {},
82
+ pages
83
+ };
84
+ }
85
+ /** UTC midnight, so "expires today" behaves the same in every timezone. */
86
+ function utcDay(date) {
87
+ return Math.floor(date.getTime() / DAY_MS);
88
+ }
89
+ function resolveSuppression(s, scope, now) {
90
+ if (!s.expires) return {
91
+ ...s,
92
+ scope,
93
+ status: "permanent",
94
+ daysLeft: null
95
+ };
96
+ const daysLeft = utcDay(/* @__PURE__ */ new Date(`${s.expires}T00:00:00Z`)) - utcDay(now);
97
+ return {
98
+ ...s,
99
+ scope,
100
+ status: daysLeft < 0 ? "expired" : "active",
101
+ daysLeft
102
+ };
103
+ }
104
+ /**
105
+ * Turn the config into the exact list of gate invocations to run.
106
+ *
107
+ * Suppression flags are appended to matching gates only when active. An
108
+ * expired one is surfaced in `plan.expired` and deliberately left off the
109
+ * command line: the gate returns to failing, which is what an expiry date is
110
+ * supposed to mean.
111
+ */
112
+ function resolveGatePlan(config, options = {}) {
113
+ const now = options.now ?? /* @__PURE__ */ new Date();
114
+ const only = options.only?.filter((s) => s.trim()) ?? [];
115
+ const defaultGates = config.defaults?.gates ?? [];
116
+ const defaultSuppressions = (config.defaults?.suppressions ?? []).map((s) => resolveSuppression(s, "defaults", now));
117
+ const jobs = [];
118
+ const suppressions = [...defaultSuppressions];
119
+ for (const page of config.pages) {
120
+ const pageId = page.id ?? page.source;
121
+ const pageSuppressions = (page.suppressions ?? []).map((s) => resolveSuppression(s, pageId, now));
122
+ suppressions.push(...pageSuppressions);
123
+ if (only.length > 0 && !only.some((o) => pageId.includes(o) || page.source.includes(o))) continue;
124
+ 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.`);
126
+ const candidates = [...defaultSuppressions, ...pageSuppressions];
127
+ for (const baseGate of gates) {
128
+ const applied = candidates.filter((s) => s.status !== "expired" && gateMatches(baseGate, s.gate));
129
+ jobs.push({
130
+ pageId,
131
+ source: page.source,
132
+ baseGate,
133
+ gate: [baseGate, ...applied.map((s) => s.flag)].join(" "),
134
+ appliedSuppressions: applied
135
+ });
136
+ }
137
+ }
138
+ return {
139
+ jobs,
140
+ suppressions,
141
+ expired: suppressions.filter((s) => s.status === "expired")
142
+ };
143
+ }
144
+ /**
145
+ * Token-wise prefix match: `check copy` matches `check copy --manifest x.txt`
146
+ * but not `check copyright`, and `check` matches every check gate.
147
+ */
148
+ function gateMatches(gate, pattern) {
149
+ const g = gate.split(/\s+/).filter(Boolean);
150
+ const p = pattern.split(/\s+/).filter(Boolean);
151
+ if (p.length > g.length) return false;
152
+ return p.every((token, i) => token === g[i]);
153
+ }
154
+ function summarizeSuppressions(suppressions, soonDays = 30) {
155
+ const rows = [...suppressions].sort((a, b) => {
156
+ const rank = (s) => s.status === "expired" ? 0 : s.status === "active" ? 1 : 2;
157
+ return rank(a) - rank(b) || (a.daysLeft ?? Infinity) - (b.daysLeft ?? Infinity);
158
+ });
159
+ return {
160
+ rows,
161
+ active: rows.filter((s) => s.status === "active").length,
162
+ expired: rows.filter((s) => s.status === "expired").length,
163
+ permanent: rows.filter((s) => s.status === "permanent").length,
164
+ unowned: rows.filter((s) => s.status !== "expired" && !s.owner).length,
165
+ expiringSoon: rows.filter((s) => s.status === "active" && (s.daysLeft ?? Infinity) <= soonDays).length
166
+ };
167
+ }
168
+ //#endregion
169
+ export { GATE_CONFIG_FILENAMES, gateMatches, parseGateConfig, resolveGatePlan, resolveSuppression, summarizeSuppressions };
@@ -0,0 +1,45 @@
1
+ //#region src/gate-exit.d.ts
2
+ /**
3
+ * One exit-code contract for every gate.
4
+ *
5
+ * Measured during the 2026-08-01 round-10 audit, the behaviour was
6
+ * incoherent: verdict gates (integrity DEFECTS, layout VIOLATED, flow
7
+ * FAILED, markup NOT DONE) exited non-zero on their own, `check
8
+ * interactions` and `scan handlers` also exited non-zero on a suspect, but
9
+ * `check copy`, `check asset` and `scan scroll` exited ZERO unless you
10
+ * remembered `--fail-on-suspect`. Two commands in the same `scan` group
11
+ * disagreed. Worse, the safe-looking default was the dangerous one: a
12
+ * pre-push or CI command that printed a defect and exited 0.
13
+ *
14
+ * The contract is now: **a suspect fails the command.** A verification tool
15
+ * whose default is "found a defect, exiting 0" is a footgun; the burden
16
+ * belongs on the person who wants to ignore findings, not on the person who
17
+ * wants them enforced.
18
+ *
19
+ * `--advisory` opts back into print-and-succeed for gates being piloted
20
+ * before they gate CI — which is the rollout order the docs recommend.
21
+ * `--fail-on-suspect` is kept as an accepted no-op so existing scripts and
22
+ * the published documentation keep working.
23
+ *
24
+ * Warns never affect the exit code, under any flag.
25
+ */
26
+ interface GateExitFlags {
27
+ /** Print findings and exit 0 even when suspects exist. */
28
+ advisory: boolean;
29
+ }
30
+ /** Parse the shared exit-code flags out of an argv array. */
31
+ declare function parseGateExitFlags(argv: readonly string[]): GateExitFlags;
32
+ /**
33
+ * Decide the process exit code. `hasSuspect` should count only
34
+ * defect-severity findings; warn-level findings must not reach it.
35
+ */
36
+ declare function gateExitCode(hasSuspect: boolean, flags: GateExitFlags): 0 | 1;
37
+ /** Shared help text so every gate documents the contract identically. */
38
+ declare const GATE_EXIT_HELP = " --advisory Print findings but exit 0 (default: a suspect exits 1)";
39
+ /**
40
+ * Apply the contract. Sets `process.exitCode` rather than calling
41
+ * `process.exit` so buffered stdout is not truncated.
42
+ */
43
+ declare function applyGateExit(hasSuspect: boolean, flags: GateExitFlags): void;
44
+ //#endregion
45
+ export { GATE_EXIT_HELP, GateExitFlags, applyGateExit, gateExitCode, parseGateExitFlags };
@@ -0,0 +1,25 @@
1
+ //#region src/gate-exit.ts
2
+ /** Parse the shared exit-code flags out of an argv array. */
3
+ function parseGateExitFlags(argv) {
4
+ return { advisory: argv.includes("--advisory") };
5
+ }
6
+ /**
7
+ * Decide the process exit code. `hasSuspect` should count only
8
+ * defect-severity findings; warn-level findings must not reach it.
9
+ */
10
+ function gateExitCode(hasSuspect, flags) {
11
+ if (!hasSuspect) return 0;
12
+ return flags.advisory ? 0 : 1;
13
+ }
14
+ /** Shared help text so every gate documents the contract identically. */
15
+ const GATE_EXIT_HELP = " --advisory Print findings but exit 0 (default: a suspect exits 1)";
16
+ /**
17
+ * Apply the contract. Sets `process.exitCode` rather than calling
18
+ * `process.exit` so buffered stdout is not truncated.
19
+ */
20
+ function applyGateExit(hasSuspect, flags) {
21
+ const code = gateExitCode(hasSuspect, flags);
22
+ if (code !== 0) process.exitCode = code;
23
+ }
24
+ //#endregion
25
+ export { GATE_EXIT_HELP, applyGateExit, gateExitCode, parseGateExitFlags };
package/dist/index.d.mts CHANGED
@@ -1,15 +1,15 @@
1
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";
2
+ import { INTERACTIVE_ROLES, LANDMARK_ROLES, diffA11yTrees, parsePlaywrightA11ySnapshot, verifyA11yTree } from "./a11y-semantic.mjs";
3
3
  import { AUTHORED_PROPERTIES } from "./authored-style-capture.mjs";
4
4
  import { TRACKED_PROPERTIES } from "./computed-style-capture.mjs";
5
5
  import { diffComputedStyles } from "./computed-style-diff.mjs";
6
6
  import { aggregateAuthoredStyleByViewport, diffAuthoredStyles } from "./authored-style-diff.mjs";
7
7
  import { createScopedVrtDiff, normalizeVrtDiffRegionPixels, normalizeVrtDiffRegions } from "./diff-regions.mjs";
8
- import { evaluateDomEquivalence, verifyDomEquivalence } from "./dom-equivalence.mjs";
8
+ import { verifyDomEquivalence } from "./dom-equivalence.mjs";
9
9
  import { diffDomPositionStyles, diffPositionStylesAcrossViewports } from "./dom-position-styles.mjs";
10
10
  import { findHeatmapRegionsFromFile, findHeatmapRegionsFromRgba } from "./heatmap-regions.mjs";
11
11
  import { cropImage, decodePng, encodePng } from "./png-utils.mjs";
12
12
  import { compareScreenshots, detectBandShifts, detectEmptyContent, detectWhiteout, generateDiffReport } from "./heatmap.mjs";
13
13
  import { RESOLUTION_PRESETS, getImageDimensions, resizePngBuffer, resolveResolutionForViewport } from "./image-resize.mjs";
14
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 };
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 };
package/dist/index.mjs CHANGED
@@ -1,14 +1,14 @@
1
- import { INTERACTIVE_ROLES, LANDMARK_ROLES, checkA11yTree, diffA11yTrees, parsePlaywrightA11ySnapshot, verifyA11yTree } from "./a11y-semantic.mjs";
1
+ import { INTERACTIVE_ROLES, LANDMARK_ROLES, diffA11yTrees, parsePlaywrightA11ySnapshot, verifyA11yTree } from "./a11y-semantic.mjs";
2
2
  import { AUTHORED_PROPERTIES } from "./authored-style-capture.mjs";
3
3
  import { diffComputedStyles } from "./computed-style-diff.mjs";
4
4
  import { aggregateAuthoredStyleByViewport, diffAuthoredStyles } from "./authored-style-diff.mjs";
5
5
  import { TRACKED_PROPERTIES } from "./computed-style-capture.mjs";
6
6
  import { createScopedVrtDiff, normalizeVrtDiffRegionPixels, normalizeVrtDiffRegions } from "./diff-regions.mjs";
7
- import { evaluateDomEquivalence, verifyDomEquivalence } from "./dom-equivalence.mjs";
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
10
  import { compareScreenshots, detectBandShifts, detectEmptyContent, detectWhiteout, generateDiffReport } from "./heatmap.mjs";
11
11
  import { findHeatmapRegionsFromFile, findHeatmapRegionsFromRgba } from "./heatmap-regions.mjs";
12
12
  import { RESOLUTION_PRESETS, getImageDimensions, resizePngBuffer, resolveResolutionForViewport } from "./image-resize.mjs";
13
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 };
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 };
@@ -0,0 +1,28 @@
1
+ //#region src/navigation-redirect.d.ts
2
+ /**
3
+ * Redirect disclosure for gates that navigate.
4
+ *
5
+ * Discovered by the 2026-08-01 hard-target audit: pointing a gate at an
6
+ * auth-walled route (`/dashboard` behind a session cookie) silently
7
+ * followed the 302 to `/login` and measured THAT page. `check integrity`
8
+ * reported `verdict: CLEAN` — a green gate on a page that never rendered,
9
+ * which is worse than an error, and `check copy` reported the dashboard's
10
+ * copy as "missing" when the real problem was that it was never visited.
11
+ *
12
+ * A gate must never report on a URL it did not measure. This helper
13
+ * compares requested vs. final URL and returns a message when they differ
14
+ * in a way the caller should hear about.
15
+ *
16
+ * Deliberately quiet about cosmetic redirects — scheme upgrade, added or
17
+ * dropped trailing slash, host canonicalization (www.) — because those
18
+ * still land on the intended page and crying wolf about them would train
19
+ * users to ignore the warning.
20
+ */
21
+ /**
22
+ * Returns a human-readable warning when the final URL is a different page
23
+ * than the one requested, or `null` when the navigation landed where the
24
+ * caller intended (or when either URL is unparseable / not http(s)).
25
+ */
26
+ declare function describeRedirect(requested: string, final: string): string | null;
27
+ //#endregion
28
+ export { describeRedirect };
@@ -0,0 +1,47 @@
1
+ //#region src/navigation-redirect.ts
2
+ /**
3
+ * Redirect disclosure for gates that navigate.
4
+ *
5
+ * Discovered by the 2026-08-01 hard-target audit: pointing a gate at an
6
+ * auth-walled route (`/dashboard` behind a session cookie) silently
7
+ * followed the 302 to `/login` and measured THAT page. `check integrity`
8
+ * reported `verdict: CLEAN` — a green gate on a page that never rendered,
9
+ * which is worse than an error, and `check copy` reported the dashboard's
10
+ * copy as "missing" when the real problem was that it was never visited.
11
+ *
12
+ * A gate must never report on a URL it did not measure. This helper
13
+ * compares requested vs. final URL and returns a message when they differ
14
+ * in a way the caller should hear about.
15
+ *
16
+ * Deliberately quiet about cosmetic redirects — scheme upgrade, added or
17
+ * dropped trailing slash, host canonicalization (www.) — because those
18
+ * still land on the intended page and crying wolf about them would train
19
+ * users to ignore the warning.
20
+ */
21
+ function normalizePath(pathname) {
22
+ const p = pathname.replace(/\/+$/, "");
23
+ return p === "" ? "/" : p;
24
+ }
25
+ /**
26
+ * Returns a human-readable warning when the final URL is a different page
27
+ * than the one requested, or `null` when the navigation landed where the
28
+ * caller intended (or when either URL is unparseable / not http(s)).
29
+ */
30
+ function describeRedirect(requested, final) {
31
+ if (!requested || !final || requested === final) return null;
32
+ let a, b;
33
+ try {
34
+ a = new URL(requested);
35
+ b = new URL(final);
36
+ } catch {
37
+ return null;
38
+ }
39
+ if (a.protocol !== "http:" && a.protocol !== "https:") return null;
40
+ const hostA = a.hostname.replace(/^www\./, "");
41
+ const hostB = b.hostname.replace(/^www\./, "");
42
+ if (normalizePath(a.pathname) === normalizePath(b.pathname) && hostA === hostB) return null;
43
+ const hint = /login|signin|sign-in|auth|sso|account\/login/i.test(b.pathname) ? " This looks like a login wall: the gate measured the sign-in page, NOT the page you asked about. Pass a logged-in Playwright storage state (--storage-state <file>, or VLMKIT_STORAGE_STATE), or point the gate at a route that does not need auth." : " The gate measured the destination, not the URL you passed.";
44
+ return `redirected: requested ${a.pathname}${a.search} but measured ${b.href}.${hint}`;
45
+ }
46
+ //#endregion
47
+ export { describeRedirect };
@@ -0,0 +1,102 @@
1
+ import { Browser, Page, ViewportSize } from "playwright";
2
+
3
+ //#region src/page-open.d.ts
4
+ declare const isUrlSource: (source: string) => boolean;
5
+ /**
6
+ * Normalize a source for storage and display: an absolute path for a file, the
7
+ * URL untouched for a URL.
8
+ *
9
+ * `resolve()` alone mangles a URL into a path — `resolve("http://x/p.html")`
10
+ * yields `<cwd>/http:/x/p.html`, which then fails as "file not found" and tells
11
+ * the caller nothing about what actually went wrong.
12
+ */
13
+ declare function resolveSource(source: string): string;
14
+ /** File path or URL → a URL Playwright can navigate to. */
15
+ declare function sourceToUrl(source: string): string;
16
+ /**
17
+ * Wait for the page to stop moving: bounded network idle, then webfonts, then
18
+ * one frame. Every part is best-effort — a page with a long-poll connection
19
+ * never reaches network idle, and refusing to measure it would be worse than
20
+ * measuring it slightly early.
21
+ *
22
+ * **A gate that navigates and does not call this measures the wrong document.**
23
+ * `load` fires before a client-rendered view paints, and the failure is never
24
+ * reported as "I looked too early" — it is reported as a defect in the page:
25
+ *
26
+ * - 2026-08-01: `check interactions` said "interactive elements: 0" on a React
27
+ * page with a button, two links and a scroller. It measured the "Loading…"
28
+ * placeholder.
29
+ * - 2026-08-02: `verify flow` failed `count .card expected 2, measured 0` on a
30
+ * page where `check layout` measured 2 at the same instant, and
31
+ * `build page` screenshotted a candidate at 5.3% of its settled ink — so
32
+ * every component came back missing. Both blamed the markup.
33
+ *
34
+ * Playwright *actions* auto-wait, which is why this stayed hidden: a click on a
35
+ * late-rendered element is safe. Reads are not — `page.evaluate`,
36
+ * `page.screenshot` and `getBoundingClientRect` all sample the DOM at that
37
+ * instant.
38
+ *
39
+ * `waitUntil` is not the axis. `goto(load)` followed by this settle waits for
40
+ * network idle anyway, so the 8 `load` and 2 `domcontentloaded` call sites are
41
+ * equivalent to the 71 `networkidle` ones **provided they settle**. The
42
+ * difference that mattered was always the settle, never the load state.
43
+ */
44
+ declare function settlePage(page: Page, settleMs?: number): Promise<void>;
45
+ interface OpenPageOptions {
46
+ viewport?: ViewportSize;
47
+ deviceScaleFactor?: number;
48
+ /** `prefers-color-scheme` for the page's context (theme-parity opens both). */
49
+ colorScheme?: "light" | "dark" | "no-preference";
50
+ /** Playwright storage state for pages behind a login. */
51
+ storageState?: string;
52
+ waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit";
53
+ timeout?: number;
54
+ /** Extra quiet time after load. 0 skips it. */
55
+ settleMs?: number;
56
+ /** Skip settling entirely (a gate that measures load timing does its own). */
57
+ skipSettle?: boolean;
58
+ }
59
+ interface OpenedPage {
60
+ page: Page;
61
+ /**
62
+ * Human-readable note when a URL redirected somewhere meaningful (a login
63
+ * wall), else null. Gates surface this so an auth-walled route cannot come
64
+ * back CLEAN by measuring the login page.
65
+ */
66
+ redirect: string | null;
67
+ }
68
+ /**
69
+ * Open a file or URL by navigation, so relative assets resolve.
70
+ */
71
+ declare function openSource(browser: Browser, source: string, options?: OpenPageOptions): Promise<OpenedPage>;
72
+ interface OpenHtmlOptions extends OpenPageOptions {
73
+ /**
74
+ * The file or URL this HTML came from. The page navigates there first, so the
75
+ * document keeps that base URL and the mutated copy still resolves the
76
+ * stylesheets and images sitting next to the original.
77
+ *
78
+ * Omit only for HTML synthesized from nothing.
79
+ */
80
+ baseSource?: string;
81
+ }
82
+ /**
83
+ * Open HTML a gate has rewritten in memory (inflated text, forced theme,
84
+ * deleted rule).
85
+ *
86
+ * Prefer `openSource` when the bytes on disk are what should be measured.
87
+ *
88
+ * Navigate-then-replace, because the obvious alternative does not work.
89
+ * Measured on the same one-line fixture (external `style.css` setting
90
+ * `p { color: rgb(4,5,6) }`):
91
+ *
92
+ * setContent + injected `<base href="file:///dir/">` -> rgb(0, 0, 0)
93
+ * goto(file) then setContent -> rgb(4, 5, 6)
94
+ *
95
+ * A `<base>` cannot rescue it: the `setContent` document has an opaque origin,
96
+ * and Chromium blocks a `file://` subresource from one. Navigating first gives
97
+ * the document a real base URL, and `setContent` replaces the markup without
98
+ * discarding it.
99
+ */
100
+ declare function openHtml(browser: Browser, html: string, options?: OpenHtmlOptions): Promise<Page>;
101
+ //#endregion
102
+ export { OpenHtmlOptions, OpenPageOptions, OpenedPage, isUrlSource, openHtml, openSource, resolveSource, settlePage, sourceToUrl };