@mizchi/vlmkit-core 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 };
@@ -0,0 +1,48 @@
1
+ //#region src/legacy-names.d.ts
2
+ declare const STATE_DIR = ".vlmkit";
3
+ declare const LEGACY_STATE_DIR = ".vrt";
4
+ declare const CONFIG_FILE = "vlmkit.config.json";
5
+ declare const LEGACY_CONFIG_FILE = "vrt.config.json";
6
+ declare function noteLegacyName(oldName: string, newName: string, detail?: string): void;
7
+ /** Reset between tests. */
8
+ declare function resetLegacyNotices(): void;
9
+ /**
10
+ * Absolute path for a state entry, preferring `.vlmkit/<entry>` and falling back
11
+ * to an existing `.vrt/<entry>`.
12
+ *
13
+ * Writers get the new path unless the old one is already populated, so a
14
+ * project keeps appending where its history is instead of starting a second,
15
+ * half-empty baseline set beside it.
16
+ */
17
+ declare function resolveStatePath(cwd: string, entry: string): string;
18
+ /**
19
+ * Config filenames in search order: new before old, JSON before TOML (JSON wins
20
+ * when both exist, which was the pre-rename behaviour). `legacy: true` entries
21
+ * are what `findConfigPath` reports a notice for.
22
+ *
23
+ * Exported as data rather than a resolver because the caller also has to name
24
+ * every candidate in its "not found" error — listing only the new one would
25
+ * tell a project with a working `vrt.config.json` that it has no config.
26
+ */
27
+ declare const CONFIG_CANDIDATES: readonly {
28
+ name: string;
29
+ legacy: boolean;
30
+ }[];
31
+ /**
32
+ * `VLMKIT_FOO`, falling back to `VRT_FOO`.
33
+ *
34
+ * Pass the suffix, not the whole name, so a call site cannot mismatch the two
35
+ * halves — `readEnv("LLM_MODEL")` reads `VLMKIT_LLM_MODEL` then `VRT_LLM_MODEL`.
36
+ * An empty string counts as unset, matching how the previous `process.env.X ||`
37
+ * reads behaved.
38
+ */
39
+ declare function readEnv(suffix: string): string | undefined;
40
+ /**
41
+ * `DEBUG_VLMKIT`, falling back to `DEBUG_VRT`. Separate from `readEnv` because
42
+ * this one is a prefix, not a suffix — `DEBUG_VRT`, not `VRT_DEBUG`.
43
+ */
44
+ declare function debugEnabled(): boolean;
45
+ /** Every env suffix that has both spellings, so the docs and tests can enumerate. */
46
+ declare const ENV_SUFFIXES: readonly ["BASE_URL", "CAPTURE_BACKEND", "CONFIG_FILE", "CONFIG_PATH", "LLM_MODEL", "LLM_PROVIDER", "PROJECT_ROOT", "VLM_MODEL"];
47
+ //#endregion
48
+ export { CONFIG_CANDIDATES, CONFIG_FILE, ENV_SUFFIXES, LEGACY_CONFIG_FILE, LEGACY_STATE_DIR, STATE_DIR, debugEnabled, noteLegacyName, readEnv, resetLegacyNotices, resolveStatePath };
@@ -0,0 +1,134 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ //#region src/legacy-names.ts
4
+ /**
5
+ * Backward compatibility for the `vrt` → `vlmkit` rename of things that are not
6
+ * text: the state directory, the config filename, and the environment
7
+ * variables.
8
+ *
9
+ * The command-name rename was pure text — nothing on disk moved. These three
10
+ * are different: rename them without a fallback and every existing project
11
+ * silently loses its approved baselines, stops finding its config, and drops
12
+ * whatever its CI exports. So each new name is preferred, each old name still
13
+ * works, and using an old one prints one line saying so.
14
+ *
15
+ * ## Why per-subpath and not per-directory
16
+ *
17
+ * `.vlmkit/` already exists in any project that has run a gate — the run
18
+ * ledger, `gates`, `markup-loop` and `copy-review` all live there, while
19
+ * `baselines`, `runs` and `last-diff-for-agent.json` were still under `.vrt/`.
20
+ * So "if `.vlmkit/` is missing, use `.vrt/`" would resolve to the new directory
21
+ * immediately and lose the baselines anyway. The check has to be on the
22
+ * specific entry: `.vlmkit/baselines` vs `.vrt/baselines`.
23
+ *
24
+ * ## What is deliberately NOT here
25
+ *
26
+ * Values that leave this process or land in someone else's file — the
27
+ * `X-Title` header sent to OpenRouter, the Playwright `projectName` that
28
+ * appears inside snapshot paths, the plan schema's `vrt?:` field, the published
29
+ * OpenAPI title. Those are wire and data formats, not local state, and moving
30
+ * them is a separate decision.
31
+ */
32
+ const STATE_DIR = ".vlmkit";
33
+ const LEGACY_STATE_DIR = ".vrt";
34
+ const CONFIG_FILE = "vlmkit.config.json";
35
+ const LEGACY_CONFIG_FILE = "vrt.config.json";
36
+ /** One notice per distinct old name per process — a loop must not spam. */
37
+ const announced = /* @__PURE__ */ new Set();
38
+ function noteLegacyName(oldName, newName, detail = "") {
39
+ if (announced.has(oldName)) return;
40
+ announced.add(oldName);
41
+ const tag = !process.env.NO_COLOR && process.stderr.isTTY ? "\x1B[33m[vlmkit legacy]\x1B[0m" : "[vlmkit legacy]";
42
+ process.stderr.write(`${tag} using ${oldName} — rename to ${newName}; support ends in 1.0.0${detail ? `. ${detail}` : ""}\n`);
43
+ }
44
+ /** Reset between tests. */
45
+ function resetLegacyNotices() {
46
+ announced.clear();
47
+ }
48
+ /**
49
+ * Absolute path for a state entry, preferring `.vlmkit/<entry>` and falling back
50
+ * to an existing `.vrt/<entry>`.
51
+ *
52
+ * Writers get the new path unless the old one is already populated, so a
53
+ * project keeps appending where its history is instead of starting a second,
54
+ * half-empty baseline set beside it.
55
+ */
56
+ function resolveStatePath(cwd, entry) {
57
+ const next = resolve(cwd, join(STATE_DIR, entry));
58
+ if (existsSync(next)) return next;
59
+ const legacy = resolve(cwd, join(LEGACY_STATE_DIR, entry));
60
+ if (existsSync(legacy)) {
61
+ noteLegacyName(`${LEGACY_STATE_DIR}/${entry}`, `${STATE_DIR}/${entry}`, "move it to keep using one location");
62
+ return legacy;
63
+ }
64
+ return next;
65
+ }
66
+ /**
67
+ * Config filenames in search order: new before old, JSON before TOML (JSON wins
68
+ * when both exist, which was the pre-rename behaviour). `legacy: true` entries
69
+ * are what `findConfigPath` reports a notice for.
70
+ *
71
+ * Exported as data rather than a resolver because the caller also has to name
72
+ * every candidate in its "not found" error — listing only the new one would
73
+ * tell a project with a working `vrt.config.json` that it has no config.
74
+ */
75
+ const CONFIG_CANDIDATES = [
76
+ {
77
+ name: CONFIG_FILE,
78
+ legacy: false
79
+ },
80
+ {
81
+ name: "vlmkit.config.toml",
82
+ legacy: false
83
+ },
84
+ {
85
+ name: LEGACY_CONFIG_FILE,
86
+ legacy: true
87
+ },
88
+ {
89
+ name: "vrt.config.toml",
90
+ legacy: true
91
+ }
92
+ ];
93
+ /**
94
+ * `VLMKIT_FOO`, falling back to `VRT_FOO`.
95
+ *
96
+ * Pass the suffix, not the whole name, so a call site cannot mismatch the two
97
+ * halves — `readEnv("LLM_MODEL")` reads `VLMKIT_LLM_MODEL` then `VRT_LLM_MODEL`.
98
+ * An empty string counts as unset, matching how the previous `process.env.X ||`
99
+ * reads behaved.
100
+ */
101
+ function readEnv(suffix) {
102
+ const next = process.env[`VLMKIT_${suffix}`];
103
+ if (next) return next;
104
+ const legacy = process.env[`VRT_${suffix}`];
105
+ if (legacy) {
106
+ noteLegacyName(`VRT_${suffix}`, `VLMKIT_${suffix}`);
107
+ return legacy;
108
+ }
109
+ }
110
+ /**
111
+ * `DEBUG_VLMKIT`, falling back to `DEBUG_VRT`. Separate from `readEnv` because
112
+ * this one is a prefix, not a suffix — `DEBUG_VRT`, not `VRT_DEBUG`.
113
+ */
114
+ function debugEnabled() {
115
+ if (process.env.DEBUG_VLMKIT) return true;
116
+ if (process.env.DEBUG_VRT) {
117
+ noteLegacyName("DEBUG_VRT", "DEBUG_VLMKIT");
118
+ return true;
119
+ }
120
+ return false;
121
+ }
122
+ /** Every env suffix that has both spellings, so the docs and tests can enumerate. */
123
+ const ENV_SUFFIXES = [
124
+ "BASE_URL",
125
+ "CAPTURE_BACKEND",
126
+ "CONFIG_FILE",
127
+ "CONFIG_PATH",
128
+ "LLM_MODEL",
129
+ "LLM_PROVIDER",
130
+ "PROJECT_ROOT",
131
+ "VLM_MODEL"
132
+ ];
133
+ //#endregion
134
+ export { CONFIG_CANDIDATES, CONFIG_FILE, ENV_SUFFIXES, LEGACY_CONFIG_FILE, LEGACY_STATE_DIR, STATE_DIR, debugEnabled, noteLegacyName, readEnv, resetLegacyNotices, resolveStatePath };
@@ -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 };