@mizchi/vlmkit-core 0.9.1 → 0.11.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.
- package/dist/apng.d.mts +42 -0
- package/dist/apng.mjs +199 -0
- package/dist/auth-state.d.mts +14 -3
- package/dist/auth-state.mjs +30 -6
- package/dist/bitmap-font.d.mts +48 -0
- package/dist/bitmap-font.mjs +945 -0
- package/dist/browser-launch.d.mts +65 -0
- package/dist/browser-launch.mjs +194 -0
- package/dist/cli-error.d.mts +73 -1
- package/dist/cli-error.mjs +164 -32
- package/dist/element-compare.mjs +8 -11
- package/dist/filmstrip.d.mts +121 -0
- package/dist/filmstrip.mjs +181 -0
- package/dist/gate-config.d.mts +107 -22
- package/dist/gate-config.mjs +138 -9
- package/dist/heatmap.d.mts +48 -4
- package/dist/heatmap.mjs +157 -12
- package/dist/index.d.mts +6 -4
- package/dist/index.mjs +4 -2
- package/dist/mask.d.mts +66 -2
- package/dist/mask.mjs +91 -4
- package/dist/page-load.d.mts +83 -0
- package/dist/page-load.mjs +116 -0
- package/dist/page-open.d.mts +123 -2
- package/dist/page-open.mjs +176 -6
- package/dist/plugin/args.d.mts +86 -0
- package/dist/plugin/args.mjs +162 -0
- package/dist/plugin/browser.d.mts +6 -0
- package/dist/plugin/browser.mjs +6 -0
- package/dist/plugin/cli-entry.d.mts +11 -0
- package/dist/plugin/cli-entry.mjs +69 -0
- package/dist/plugin/contract.d.mts +270 -0
- package/dist/plugin/contract.mjs +51 -0
- package/dist/plugin/index.d.mts +82 -0
- package/dist/plugin/index.mjs +81 -0
- package/dist/plugin/load.d.mts +36 -0
- package/dist/plugin/load.mjs +98 -0
- package/dist/plugin/registry.d.mts +60 -0
- package/dist/plugin/registry.mjs +160 -0
- package/dist/plugin/rule-tier.d.mts +65 -0
- package/dist/plugin/rule-tier.mjs +77 -0
- package/dist/plugin/rules.d.mts +112 -0
- package/dist/plugin/rules.mjs +188 -0
- package/dist/plugin/runner.d.mts +198 -0
- package/dist/plugin/runner.mjs +440 -0
- package/dist/png-utils.d.mts +31 -1
- package/dist/png-utils.mjs +24 -1
- package/dist/rect-overlap.d.mts +41 -0
- package/dist/rect-overlap.mjs +28 -0
- package/dist/run-ledger.d.mts +56 -2
- package/dist/run-ledger.mjs +102 -11
- package/dist/types.d.mts +60 -1
- package/dist/version.d.mts +20 -0
- package/dist/version.mjs +20 -0
- package/dist/webp.d.mts +31 -0
- package/dist/webp.mjs +105 -0
- package/package.json +17 -3
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { Browser, BrowserType, LaunchOptions } from "playwright";
|
|
2
|
+
|
|
3
|
+
//#region src/browser-launch.d.ts
|
|
4
|
+
type BrowserEngine = "chromium" | "firefox" | "webkit";
|
|
5
|
+
/**
|
|
6
|
+
* Engine name → Playwright browser type.
|
|
7
|
+
*
|
|
8
|
+
* Only `stress/cross-browser.ts` needs more than Chromium (it had its own
|
|
9
|
+
* `ENGINE_BY_NAME` table); the other 64 sites are Chromium-only, which is why
|
|
10
|
+
* `engine` defaults to `"chromium"` rather than being required.
|
|
11
|
+
*/
|
|
12
|
+
declare const BROWSER_ENGINES: Record<BrowserEngine, BrowserType>;
|
|
13
|
+
declare const ALL_BROWSER_ENGINES: readonly BrowserEngine[];
|
|
14
|
+
/**
|
|
15
|
+
* A launch that failed for a reason we can explain.
|
|
16
|
+
*
|
|
17
|
+
* `message` is the *finished* operator-facing text, "error: " prefix and all —
|
|
18
|
+
* `handleCliError` writes it verbatim so the CLI output is byte-identical to
|
|
19
|
+
* what it printed when the same diagnosis lived only in the error handler.
|
|
20
|
+
* `cause` keeps the original Playwright error for anyone who wants the stack.
|
|
21
|
+
*/
|
|
22
|
+
declare class BrowserLaunchError extends Error {
|
|
23
|
+
readonly name = "BrowserLaunchError";
|
|
24
|
+
constructor(message: string, options?: {
|
|
25
|
+
cause?: unknown;
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
interface LaunchBrowserOptions {
|
|
29
|
+
/** Defaults to `"chromium"`. */
|
|
30
|
+
engine?: BrowserEngine;
|
|
31
|
+
/**
|
|
32
|
+
* Passed to `browserType.launch()` verbatim. The 4 sites that pass `args`
|
|
33
|
+
* (font-hinting determinism, headless GPU) depend on this being untouched —
|
|
34
|
+
* dropping an arg silently changes what gets rendered.
|
|
35
|
+
*/
|
|
36
|
+
launch?: LaunchOptions;
|
|
37
|
+
/**
|
|
38
|
+
* Extra diagnosis tried *before* the built-in missing-browser one, for the
|
|
39
|
+
* failure modes a single package cannot know about. The css-challenge and
|
|
40
|
+
* migration entry points pass the Codex/macOS sandbox detector that lives in
|
|
41
|
+
* `@mizchi/vlmkit-capture` — core cannot import it (capture depends on core),
|
|
42
|
+
* so it arrives as a hook instead of a second copy.
|
|
43
|
+
*
|
|
44
|
+
* Return the finished message, or `null` to decline.
|
|
45
|
+
*/
|
|
46
|
+
diagnose?: (error: unknown) => string | null;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Launch a browser and hand it to the caller, who owns closing it.
|
|
50
|
+
*
|
|
51
|
+
* Prefer `withBrowser` — this exists for the handful of sites that cannot have
|
|
52
|
+
* a scope (a factory that returns a Browser, a browser owned by a session).
|
|
53
|
+
*/
|
|
54
|
+
declare function launchBrowser(options?: LaunchBrowserOptions): Promise<Browser>;
|
|
55
|
+
/**
|
|
56
|
+
* Launch a browser, run `fn`, and close the browser whether `fn` throws or not.
|
|
57
|
+
*
|
|
58
|
+
* The `finally` is deliberately not `.catch(() => {})`-guarded: the 51 sites
|
|
59
|
+
* this replaces all wrote `finally { await browser.close(); }`, so a close
|
|
60
|
+
* failure masking a body failure is pre-existing behaviour, not something this
|
|
61
|
+
* refactor gets to change.
|
|
62
|
+
*/
|
|
63
|
+
declare function withBrowser<T>(fn: (browser: Browser) => Promise<T>, options?: LaunchBrowserOptions): Promise<T>;
|
|
64
|
+
//#endregion
|
|
65
|
+
export { ALL_BROWSER_ENGINES, BROWSER_ENGINES, BrowserEngine, BrowserLaunchError, LaunchBrowserOptions, launchBrowser, withBrowser };
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { formatMissingPlaywrightBrowserError } from "./cli-error.mjs";
|
|
2
|
+
import { chromium, firefox, webkit } from "playwright";
|
|
3
|
+
//#region src/browser-launch.ts
|
|
4
|
+
/**
|
|
5
|
+
* The one place a browser is launched.
|
|
6
|
+
*
|
|
7
|
+
* Measured before this module existed (2026-08-10, repo-wide grep for
|
|
8
|
+
* `.launch(`): **65 call sites, no shared helper.** Grouped by what they pass
|
|
9
|
+
* and what they do around it:
|
|
10
|
+
*
|
|
11
|
+
* 60 bare `launch()` — no options at all
|
|
12
|
+
* 4 `launch({ args })` — font-hinting / GPU flags (probes + design-runs)
|
|
13
|
+
* 1 `launch({ headless })`
|
|
14
|
+
*
|
|
15
|
+
* 51 close in a `finally`
|
|
16
|
+
* 9 close on the straight line after the body (leaks on any throw)
|
|
17
|
+
* 4 never close in that scope (browser handed to a caller)
|
|
18
|
+
* 1 `return chromium.launch()` (the `CaptureBackend` factory)
|
|
19
|
+
*
|
|
20
|
+
* Three separate changes had to work around the absence of a choke point:
|
|
21
|
+
*
|
|
22
|
+
* 1. Missing-browser diagnosis got bolted onto `handleCliError` instead of
|
|
23
|
+
* onto the launch, so only the CLI ever gets it — a library caller of
|
|
24
|
+
* `runIntegrityCheck` sees a raw Playwright stack.
|
|
25
|
+
* 2. `--timeout` / `--wait-until` / `--har` were threaded through 20 gates and
|
|
26
|
+
* got a shared *navigation* helper (`page-open.ts`); the launch did not.
|
|
27
|
+
* 3. Every site repeats its own `try { … } finally { await browser.close() }`,
|
|
28
|
+
* and the 9 that forgot the `finally` leak a Chromium process whenever the
|
|
29
|
+
* measurement throws.
|
|
30
|
+
*
|
|
31
|
+
* Two entry points, because the sites genuinely come in two shapes:
|
|
32
|
+
*
|
|
33
|
+
* - `withBrowser(fn)` for the 51 scoped sites — close is guaranteed, and a
|
|
34
|
+
* thrown callback can no longer leak.
|
|
35
|
+
* - `launchBrowser()` for the 5 sites that hand the browser to someone else
|
|
36
|
+
* (`CaptureBackend.launch`, `createBrowser()` in css-challenge-core, the
|
|
37
|
+
* nullable `fileSources ? null : launch()` in diff-pr). They get the
|
|
38
|
+
* diagnosis; they keep owning the close, because there is no scope to close
|
|
39
|
+
* at.
|
|
40
|
+
*
|
|
41
|
+
* Deliberately NOT in the `@mizchi/vlmkit-core` barrel: this module imports
|
|
42
|
+
* Playwright at module load, same as `element-compare.ts` and `mask.ts`. Deep
|
|
43
|
+
* import it (`@mizchi/vlmkit-core/browser-launch.ts`).
|
|
44
|
+
*/
|
|
45
|
+
/**
|
|
46
|
+
* Engine name → Playwright browser type.
|
|
47
|
+
*
|
|
48
|
+
* Only `stress/cross-browser.ts` needs more than Chromium (it had its own
|
|
49
|
+
* `ENGINE_BY_NAME` table); the other 64 sites are Chromium-only, which is why
|
|
50
|
+
* `engine` defaults to `"chromium"` rather than being required.
|
|
51
|
+
*/
|
|
52
|
+
const BROWSER_ENGINES = {
|
|
53
|
+
chromium,
|
|
54
|
+
firefox,
|
|
55
|
+
webkit
|
|
56
|
+
};
|
|
57
|
+
const ALL_BROWSER_ENGINES = [
|
|
58
|
+
"chromium",
|
|
59
|
+
"firefox",
|
|
60
|
+
"webkit"
|
|
61
|
+
];
|
|
62
|
+
/**
|
|
63
|
+
* A launch that failed for a reason we can explain.
|
|
64
|
+
*
|
|
65
|
+
* `message` is the *finished* operator-facing text, "error: " prefix and all —
|
|
66
|
+
* `handleCliError` writes it verbatim so the CLI output is byte-identical to
|
|
67
|
+
* what it printed when the same diagnosis lived only in the error handler.
|
|
68
|
+
* `cause` keeps the original Playwright error for anyone who wants the stack.
|
|
69
|
+
*/
|
|
70
|
+
var BrowserLaunchError = class extends Error {
|
|
71
|
+
name = "BrowserLaunchError";
|
|
72
|
+
constructor(message, options) {
|
|
73
|
+
super(message, options);
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Turn a launch failure into something an operator can act on, or leave it
|
|
78
|
+
* exactly as it was.
|
|
79
|
+
*
|
|
80
|
+
* Rethrowing the original untouched when nothing recognizes it is the point:
|
|
81
|
+
* `handleCliError` still has branches for navigation failures, timeouts and the
|
|
82
|
+
* raw missing-browser shape, and wrapping every error would have routed them
|
|
83
|
+
* all into the generic `console.error(e)` fallthrough.
|
|
84
|
+
*/
|
|
85
|
+
function diagnoseLaunchFailure(error, options) {
|
|
86
|
+
const extra = options.diagnose?.(error);
|
|
87
|
+
if (extra) return new BrowserLaunchError(extra, { cause: error });
|
|
88
|
+
const missing = formatMissingPlaywrightBrowserError(error);
|
|
89
|
+
if (missing) return new BrowserLaunchError(missing, { cause: error });
|
|
90
|
+
return error;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Launch a browser and hand it to the caller, who owns closing it.
|
|
94
|
+
*
|
|
95
|
+
* Prefer `withBrowser` — this exists for the handful of sites that cannot have
|
|
96
|
+
* a scope (a factory that returns a Browser, a browser owned by a session).
|
|
97
|
+
*/
|
|
98
|
+
async function launchBrowser(options = {}) {
|
|
99
|
+
const engine = BROWSER_ENGINES[options.engine ?? "chromium"];
|
|
100
|
+
try {
|
|
101
|
+
return instrumentNavigation(await engine.launch(options.launch));
|
|
102
|
+
} catch (error) {
|
|
103
|
+
throw diagnoseLaunchFailure(error, options);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** How many still-pending requests to name in a timeout. Enough to see a pattern, not a log dump. */
|
|
107
|
+
const NAMED_PENDING_REQUESTS = 3;
|
|
108
|
+
/**
|
|
109
|
+
* Make every page this browser opens explain its own navigation timeouts.
|
|
110
|
+
*
|
|
111
|
+
* Done at the launch rather than at the navigation because there are **42
|
|
112
|
+
* `.goto(` call sites across 20 files**, three of which hand-roll the same
|
|
113
|
+
* `{ waitUntil: options.waitUntil ?? "networkidle", timeout: options.timeout ?? 30000 }`
|
|
114
|
+
* — so a fix applied to `navigatePage` reaches one of them and looks finished.
|
|
115
|
+
* Wrapping `newPage` here is the only edit that covers all 42.
|
|
116
|
+
*
|
|
117
|
+
* The whole failure used to be one line — `error: page load timed out (Timeout
|
|
118
|
+
* 30000ms exceeded)` — and two dogfood agents working on separate tasks
|
|
119
|
+
* independently called it the worst thing they hit:
|
|
120
|
+
*
|
|
121
|
+
* "It doesn't say the default wait state is `networkidle`, doesn't say
|
|
122
|
+
* `--wait-until` exists, doesn't say a request is still open, doesn't name it.
|
|
123
|
+
* The tool *knows* the milestone it was waiting on and that `/api/live` is in
|
|
124
|
+
* flight."
|
|
125
|
+
*
|
|
126
|
+
* "Dead end as guidance, useful as evidence. Reproduced the reported symptom;
|
|
127
|
+
* told me nothing about how to proceed."
|
|
128
|
+
*
|
|
129
|
+
* It is #112's item 1 restated: "the timeout error reads like the tool can't
|
|
130
|
+
* handle the page rather than like a hint to change approach". Everything needed
|
|
131
|
+
* is present at the moment of failure; it just was not said.
|
|
132
|
+
*/
|
|
133
|
+
function instrumentNavigation(browser) {
|
|
134
|
+
if (typeof browser?.newPage !== "function") return browser;
|
|
135
|
+
const originalNewPage = browser.newPage.bind(browser);
|
|
136
|
+
browser.newPage = async (...args) => {
|
|
137
|
+
const page = await originalNewPage(...args);
|
|
138
|
+
const inflight = /* @__PURE__ */ new Map();
|
|
139
|
+
page.on("request", (r) => inflight.set(r.url(), Date.now()));
|
|
140
|
+
page.on("requestfinished", (r) => inflight.delete(r.url()));
|
|
141
|
+
page.on("requestfailed", (r) => inflight.delete(r.url()));
|
|
142
|
+
const originalGoto = page.goto.bind(page);
|
|
143
|
+
page.goto = async (url, gotoOptions) => {
|
|
144
|
+
try {
|
|
145
|
+
return await originalGoto(url, gotoOptions);
|
|
146
|
+
} catch (error) {
|
|
147
|
+
throw explainNavigationTimeout(error, gotoOptions, inflight);
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
return page;
|
|
151
|
+
};
|
|
152
|
+
return browser;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Restate a navigation timeout as the three things the caller needs: which
|
|
156
|
+
* milestone was waited on, what was still open, and which flag ends the wait.
|
|
157
|
+
*
|
|
158
|
+
* Any other error passes through untouched — `cli-error.ts` already has branches
|
|
159
|
+
* for a refused connection, an unresolvable host and a blocked port, and this
|
|
160
|
+
* must not shadow them.
|
|
161
|
+
*/
|
|
162
|
+
function explainNavigationTimeout(error, gotoOptions, inflight) {
|
|
163
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
164
|
+
if (!/Timeout \d+ms exceeded/i.test(message)) return error;
|
|
165
|
+
const waitUntil = gotoOptions?.waitUntil ?? "load";
|
|
166
|
+
const timeout = gotoOptions?.timeout ?? Number(message.match(/Timeout (\d+)ms/i)?.[1] ?? 3e4);
|
|
167
|
+
const now = Date.now();
|
|
168
|
+
const pending = [...inflight.entries()].sort((a, b) => a[1] - b[1]).map(([requestUrl, at]) => `${requestUrl} (open ${((now - at) / 1e3).toFixed(1)}s)`);
|
|
169
|
+
const lines = [`page load timed out after ${timeout}ms waiting for \`${waitUntil}\``];
|
|
170
|
+
if (pending.length > 0) lines.push(` ${pending.length} request(s) still open:`, ...pending.slice(0, NAMED_PENDING_REQUESTS).map((p) => ` ${p}`), ...pending.length > NAMED_PENDING_REQUESTS ? [` and ${pending.length - NAMED_PENDING_REQUESTS} more`] : []);
|
|
171
|
+
if (waitUntil === "networkidle") lines.push(" The page may have rendered long before this — `networkidle` needs every connection to close,", " which a stream or a poll never does. Try `--wait-until load` (or `domcontentloaded`),", " or pin the network with `--har <file>`. Raising `--timeout` will not help an endpoint that never closes.");
|
|
172
|
+
else lines.push(" Raise `--timeout <ms>`, or relax `--wait-until` further.");
|
|
173
|
+
const explained = new Error(lines.join("\n"));
|
|
174
|
+
explained.cause = error;
|
|
175
|
+
return explained;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Launch a browser, run `fn`, and close the browser whether `fn` throws or not.
|
|
179
|
+
*
|
|
180
|
+
* The `finally` is deliberately not `.catch(() => {})`-guarded: the 51 sites
|
|
181
|
+
* this replaces all wrote `finally { await browser.close(); }`, so a close
|
|
182
|
+
* failure masking a body failure is pre-existing behaviour, not something this
|
|
183
|
+
* refactor gets to change.
|
|
184
|
+
*/
|
|
185
|
+
async function withBrowser(fn, options = {}) {
|
|
186
|
+
const browser = await launchBrowser(options);
|
|
187
|
+
try {
|
|
188
|
+
return await fn(browser);
|
|
189
|
+
} finally {
|
|
190
|
+
await browser.close();
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
//#endregion
|
|
194
|
+
export { ALL_BROWSER_ENGINES, BROWSER_ENGINES, BrowserLaunchError, launchBrowser, withBrowser };
|
package/dist/cli-error.d.mts
CHANGED
|
@@ -7,12 +7,84 @@
|
|
|
7
7
|
declare class UsageError extends Error {
|
|
8
8
|
readonly name = "UsageError";
|
|
9
9
|
}
|
|
10
|
+
/**
|
|
11
|
+
* The `playwright` peer range. Duplicated from this package's own
|
|
12
|
+
* `peerDependencies` because the shipped bundle has no reliable path back to
|
|
13
|
+
* its manifest (tsdown flattens `dist/`, and the root CLI bundle inlines this
|
|
14
|
+
* module into a hashed chunk). `tests/playwright-peer-contract.test.mjs` reads
|
|
15
|
+
* the manifest and fails if the two drift, so the duplication cannot rot
|
|
16
|
+
* silently.
|
|
17
|
+
*/
|
|
18
|
+
declare const PLAYWRIGHT_PEER_RANGE = ">=1.61 <2";
|
|
19
|
+
/** Playwright install target: which `playwright` *this* process resolved. */
|
|
10
20
|
interface PlaywrightInstallTarget {
|
|
11
21
|
version: string;
|
|
22
|
+
/** Directory of the resolved `playwright` package — the identity the reporter of #112 could not see. */
|
|
23
|
+
packageDir: string;
|
|
12
24
|
cliPath: string;
|
|
13
25
|
nodePath: string;
|
|
14
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* Resolve the `playwright` that vlmkit itself imports, not the one a package
|
|
29
|
+
* manager would pick for `pnpm exec`.
|
|
30
|
+
*
|
|
31
|
+
* Issue #112 (item 2): with two Playwright versions in the tree, the launch
|
|
32
|
+
* failure told the user to run `pnpm exec playwright install`, which resolves
|
|
33
|
+
* from the *project* root and downloads that Playwright's browser build. In the
|
|
34
|
+
* report that was build 1228 while vlmkit's own Playwright wanted 1234, so the
|
|
35
|
+
* advice never fixed anything. `createRequire(import.meta.url)` resolves from
|
|
36
|
+
* this module's location, i.e. from inside vlmkit's own package — the same
|
|
37
|
+
* lookup the `import { chromium } from "playwright"` at the 51 launch sites
|
|
38
|
+
* performs — so the command we print targets the installation that failed.
|
|
39
|
+
*/
|
|
40
|
+
declare function resolvePlaywrightInstallTarget(): PlaywrightInstallTarget | null;
|
|
41
|
+
/**
|
|
42
|
+
* Which engine to reinstall, read off the executable path Playwright printed.
|
|
43
|
+
*
|
|
44
|
+
* Hardcoding `chromium` was wrong for `stress cross-browser`, which launches
|
|
45
|
+
* firefox and webkit too. Playwright names the download directory after the
|
|
46
|
+
* engine (`firefox-1490/`, `webkit-2247/`, `chromium_headless_shell-1228/`), so
|
|
47
|
+
* the missing path is itself the answer. Both chromium flavours map to
|
|
48
|
+
* `chromium`: `playwright install chromium` fetches the headless shell as well
|
|
49
|
+
* (verified against the 1.61.1 CLI, which lists both under that one name).
|
|
50
|
+
*/
|
|
51
|
+
declare function playwrightEngineFromLaunchError(message: string): "chromium" | "firefox" | "webkit";
|
|
52
|
+
/** `node <resolved playwright>/cli.js install <engine>` — quoted for a shell. */
|
|
53
|
+
declare function playwrightInstallCommand(target: PlaywrightInstallTarget, engine?: "chromium" | "firefox" | "webkit"): string;
|
|
15
54
|
declare function formatMissingPlaywrightBrowserError(error: unknown, target?: PlaywrightInstallTarget | null): string | null;
|
|
55
|
+
/**
|
|
56
|
+
* `playwright` absent entirely, rather than present-but-browserless.
|
|
57
|
+
*
|
|
58
|
+
* It is a **required** peer, deliberately — the argument and its measurement
|
|
59
|
+
* live in `tests/playwright-peer-contract.test.mjs`, because a JSON manifest
|
|
60
|
+
* cannot hold a comment. Short version: the gate registry statically imports
|
|
61
|
+
* `perf.gate`, which statically imports `playwright`, so even the pixel-only
|
|
62
|
+
* commands fault at module load without it. Measured 2026-08-10: in a tree with
|
|
63
|
+
* the package removed, `vlmkit diff png --help` dies with ERR_MODULE_NOT_FOUND
|
|
64
|
+
* before printing usage. That raw stack is what this turns into one sentence.
|
|
65
|
+
*/
|
|
66
|
+
declare function formatMissingPlaywrightModuleError(error: unknown): string | null;
|
|
67
|
+
/**
|
|
68
|
+
* Best-effort sanity check used by tests: does the resolved playwright actually
|
|
69
|
+
* have a `cli.js` to invoke? Kept exported so the happy-path test can assert the
|
|
70
|
+
* command we print is runnable rather than merely well-formed.
|
|
71
|
+
*/
|
|
72
|
+
declare function resolvedPlaywrightHasCli(): boolean;
|
|
73
|
+
/**
|
|
74
|
+
* The one-line diagnosis for an error, or `null` when there isn't one.
|
|
75
|
+
*
|
|
76
|
+
* Split out of `handleCliError` so the branches are testable. They were not:
|
|
77
|
+
* the only entry point ended in `process.exit`, so covering a branch meant
|
|
78
|
+
* spawning a child process, and in practice nothing covered any of them. That
|
|
79
|
+
* is how the `ERR_FILE_NOT_FOUND` gap below reached a release — the ENOENT
|
|
80
|
+
* branch it duplicates has printed the right line since 2026-05-15, and no test
|
|
81
|
+
* noticed when ten gates stopped reaching it.
|
|
82
|
+
*
|
|
83
|
+
* `null` rather than a generic string on purpose: an unrecognized error should
|
|
84
|
+
* reach the developer whole, stack and all. A prettifier that invents a summary
|
|
85
|
+
* for everything is worse than one that admits it has nothing to add.
|
|
86
|
+
*/
|
|
87
|
+
declare function formatCliError(e: unknown): string | null;
|
|
16
88
|
declare function handleCliError(e: unknown): never;
|
|
17
89
|
//#endregion
|
|
18
|
-
export { PlaywrightInstallTarget, UsageError, formatMissingPlaywrightBrowserError, handleCliError };
|
|
90
|
+
export { PLAYWRIGHT_PEER_RANGE, PlaywrightInstallTarget, UsageError, formatCliError, formatMissingPlaywrightBrowserError, formatMissingPlaywrightModuleError, handleCliError, playwrightEngineFromLaunchError, playwrightInstallCommand, resolvePlaywrightInstallTarget, resolvedPlaywrightHasCli };
|
package/dist/cli-error.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
|
-
import { readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
4
5
|
//#region src/cli-error.ts
|
|
5
6
|
/**
|
|
6
7
|
* Shared CLI error-prettifier. Recognizes common error shapes that
|
|
@@ -10,6 +11,12 @@ import { dirname, join } from "node:path";
|
|
|
10
11
|
*
|
|
11
12
|
* Use:
|
|
12
13
|
* main().catch(handleCliError);
|
|
14
|
+
*
|
|
15
|
+
* Every CLI entry must go through it, *including* `scripts/vlmkit-bundled.mjs`
|
|
16
|
+
* — that is the one `tsdown.config.ts` builds into the published `bin`. It used
|
|
17
|
+
* to `console.error(error)` instead, which made everything below dead code in
|
|
18
|
+
* the shipped CLI while it kept working in the workspace (issue #112, item 2).
|
|
19
|
+
* `tests/playwright-peer-contract.test.mjs` guards that.
|
|
13
20
|
*/
|
|
14
21
|
/**
|
|
15
22
|
* A bad flag or missing argument — the caller's typo, not a defect. Thrown by
|
|
@@ -19,76 +26,201 @@ import { dirname, join } from "node:path";
|
|
|
19
26
|
var UsageError = class extends Error {
|
|
20
27
|
name = "UsageError";
|
|
21
28
|
};
|
|
29
|
+
/**
|
|
30
|
+
* The `playwright` peer range. Duplicated from this package's own
|
|
31
|
+
* `peerDependencies` because the shipped bundle has no reliable path back to
|
|
32
|
+
* its manifest (tsdown flattens `dist/`, and the root CLI bundle inlines this
|
|
33
|
+
* module into a hashed chunk). `tests/playwright-peer-contract.test.mjs` reads
|
|
34
|
+
* the manifest and fails if the two drift, so the duplication cannot rot
|
|
35
|
+
* silently.
|
|
36
|
+
*/
|
|
37
|
+
const PLAYWRIGHT_PEER_RANGE = ">=1.61 <2";
|
|
22
38
|
function shellArg(value) {
|
|
23
39
|
return /^[A-Za-z0-9_./:@+-]+$/.test(value) ? value : JSON.stringify(value);
|
|
24
40
|
}
|
|
41
|
+
/**
|
|
42
|
+
* Resolve the `playwright` that vlmkit itself imports, not the one a package
|
|
43
|
+
* manager would pick for `pnpm exec`.
|
|
44
|
+
*
|
|
45
|
+
* Issue #112 (item 2): with two Playwright versions in the tree, the launch
|
|
46
|
+
* failure told the user to run `pnpm exec playwright install`, which resolves
|
|
47
|
+
* from the *project* root and downloads that Playwright's browser build. In the
|
|
48
|
+
* report that was build 1228 while vlmkit's own Playwright wanted 1234, so the
|
|
49
|
+
* advice never fixed anything. `createRequire(import.meta.url)` resolves from
|
|
50
|
+
* this module's location, i.e. from inside vlmkit's own package — the same
|
|
51
|
+
* lookup the `import { chromium } from "playwright"` at the 51 launch sites
|
|
52
|
+
* performs — so the command we print targets the installation that failed.
|
|
53
|
+
*/
|
|
25
54
|
function resolvePlaywrightInstallTarget() {
|
|
26
55
|
try {
|
|
27
56
|
const manifestPath = createRequire(import.meta.url).resolve("playwright/package.json");
|
|
28
57
|
const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
|
|
29
58
|
if (!manifest.version) return null;
|
|
59
|
+
const packageDir = dirname(manifestPath);
|
|
30
60
|
return {
|
|
31
61
|
version: manifest.version,
|
|
32
|
-
|
|
62
|
+
packageDir,
|
|
63
|
+
cliPath: join(packageDir, "cli.js"),
|
|
33
64
|
nodePath: process.execPath
|
|
34
65
|
};
|
|
35
66
|
} catch {
|
|
36
67
|
return null;
|
|
37
68
|
}
|
|
38
69
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
70
|
+
/**
|
|
71
|
+
* Which engine to reinstall, read off the executable path Playwright printed.
|
|
72
|
+
*
|
|
73
|
+
* Hardcoding `chromium` was wrong for `stress cross-browser`, which launches
|
|
74
|
+
* firefox and webkit too. Playwright names the download directory after the
|
|
75
|
+
* engine (`firefox-1490/`, `webkit-2247/`, `chromium_headless_shell-1228/`), so
|
|
76
|
+
* the missing path is itself the answer. Both chromium flavours map to
|
|
77
|
+
* `chromium`: `playwright install chromium` fetches the headless shell as well
|
|
78
|
+
* (verified against the 1.61.1 CLI, which lists both under that one name).
|
|
79
|
+
*/
|
|
80
|
+
function playwrightEngineFromLaunchError(message) {
|
|
81
|
+
if (/\bwebkit[-_]/i.test(message)) return "webkit";
|
|
82
|
+
if (/\bfirefox[-_]/i.test(message)) return "firefox";
|
|
83
|
+
return "chromium";
|
|
84
|
+
}
|
|
85
|
+
/** `node <resolved playwright>/cli.js install <engine>` — quoted for a shell. */
|
|
86
|
+
function playwrightInstallCommand(target, engine = "chromium") {
|
|
87
|
+
return [
|
|
44
88
|
target.nodePath,
|
|
45
89
|
target.cliPath,
|
|
46
90
|
"install",
|
|
47
|
-
|
|
91
|
+
engine
|
|
48
92
|
].map(shellArg).join(" ");
|
|
49
|
-
return `error: Playwright ${target.version} browser executable is not installed.\n run: ${command}`;
|
|
50
93
|
}
|
|
51
|
-
function
|
|
94
|
+
function missingExecutablePath(message) {
|
|
95
|
+
return message.match(/Executable doesn't exist at\s+(\S+)/i)?.[1] ?? null;
|
|
96
|
+
}
|
|
97
|
+
function formatMissingPlaywrightBrowserError(error, target = resolvePlaywrightInstallTarget()) {
|
|
98
|
+
const message = String(error?.message ?? error);
|
|
99
|
+
if (!/browserType\.launch:[\s\S]*Executable doesn't exist at/i.test(message)) return null;
|
|
100
|
+
const engine = playwrightEngineFromLaunchError(message);
|
|
101
|
+
if (!target) return `error: Playwright has no ${engine} browser executable installed, and vlmkit could not resolve its own playwright package to name the install command.`;
|
|
102
|
+
const missing = missingExecutablePath(message);
|
|
103
|
+
return [
|
|
104
|
+
`error: Playwright ${target.version} has no ${engine} browser executable installed.`,
|
|
105
|
+
...missing ? [` missing: ${missing}`] : [],
|
|
106
|
+
` resolved: playwright@${target.version} at ${target.packageDir}`,
|
|
107
|
+
` run: ${playwrightInstallCommand(target, engine)}`,
|
|
108
|
+
` (\`npx/pnpm exec playwright install\` may resolve a different playwright and download a different build)`
|
|
109
|
+
].join("\n");
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* `playwright` absent entirely, rather than present-but-browserless.
|
|
113
|
+
*
|
|
114
|
+
* It is a **required** peer, deliberately — the argument and its measurement
|
|
115
|
+
* live in `tests/playwright-peer-contract.test.mjs`, because a JSON manifest
|
|
116
|
+
* cannot hold a comment. Short version: the gate registry statically imports
|
|
117
|
+
* `perf.gate`, which statically imports `playwright`, so even the pixel-only
|
|
118
|
+
* commands fault at module load without it. Measured 2026-08-10: in a tree with
|
|
119
|
+
* the package removed, `vlmkit diff png --help` dies with ERR_MODULE_NOT_FOUND
|
|
120
|
+
* before printing usage. That raw stack is what this turns into one sentence.
|
|
121
|
+
*/
|
|
122
|
+
function formatMissingPlaywrightModuleError(error) {
|
|
123
|
+
const err = error;
|
|
124
|
+
const message = String(err?.message ?? error);
|
|
125
|
+
if (!(err?.code === "ERR_MODULE_NOT_FOUND" || /ERR_MODULE_NOT_FOUND/.test(message) || /Cannot find (?:package|module)/i.test(message))) return null;
|
|
126
|
+
if (!/Cannot find (?:package|module) ['"]playwright['"]/i.test(message)) return null;
|
|
127
|
+
const importer = message.match(/imported from\s+(\S+)/i)?.[1] ?? null;
|
|
128
|
+
return [
|
|
129
|
+
`error: the \`playwright\` package is not installed.`,
|
|
130
|
+
` vlmkit declares it as a required peer dependency (${PLAYWRIGHT_PEER_RANGE}). Every`,
|
|
131
|
+
` command loads it, the pixel-only ones included, because the gate`,
|
|
132
|
+
` registry imports the browser gates eagerly.`,
|
|
133
|
+
...importer ? [` imported by: ${importer}`] : [],
|
|
134
|
+
` run: npm install --save-dev playwright (or pnpm add -D / yarn add -D)`,
|
|
135
|
+
` then install its browsers with that installation's own CLI:`,
|
|
136
|
+
` node node_modules/playwright/cli.js install chromium`
|
|
137
|
+
].join("\n");
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Best-effort sanity check used by tests: does the resolved playwright actually
|
|
141
|
+
* have a `cli.js` to invoke? Kept exported so the happy-path test can assert the
|
|
142
|
+
* command we print is runnable rather than merely well-formed.
|
|
143
|
+
*/
|
|
144
|
+
function resolvedPlaywrightHasCli() {
|
|
145
|
+
const target = resolvePlaywrightInstallTarget();
|
|
146
|
+
return target !== null && existsSync(target.cliPath);
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* The one-line diagnosis for an error, or `null` when there isn't one.
|
|
150
|
+
*
|
|
151
|
+
* Split out of `handleCliError` so the branches are testable. They were not:
|
|
152
|
+
* the only entry point ended in `process.exit`, so covering a branch meant
|
|
153
|
+
* spawning a child process, and in practice nothing covered any of them. That
|
|
154
|
+
* is how the `ERR_FILE_NOT_FOUND` gap below reached a release — the ENOENT
|
|
155
|
+
* branch it duplicates has printed the right line since 2026-05-15, and no test
|
|
156
|
+
* noticed when ten gates stopped reaching it.
|
|
157
|
+
*
|
|
158
|
+
* `null` rather than a generic string on purpose: an unrecognized error should
|
|
159
|
+
* reach the developer whole, stack and all. A prettifier that invents a summary
|
|
160
|
+
* for everything is worse than one that admits it has nothing to add.
|
|
161
|
+
*/
|
|
162
|
+
function formatCliError(e) {
|
|
52
163
|
const err = e;
|
|
53
164
|
const msg = String(err?.message ?? e);
|
|
54
|
-
if (err?.name === "UsageError") {
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
}
|
|
58
|
-
if (err?.code === "ENOENT") {
|
|
59
|
-
const path = err.path ?? msg.match(/ENOENT: no such file or directory[^']*'([^']+)'/)?.[1] ?? "?";
|
|
60
|
-
process.stderr.write(`error: file not found: ${path}\n`);
|
|
61
|
-
process.exit(1);
|
|
62
|
-
}
|
|
165
|
+
if (err?.name === "UsageError") return `error: ${msg}`;
|
|
166
|
+
if (err?.name === "BrowserLaunchError") return msg.startsWith("error: ") ? msg : `error: ${msg}`;
|
|
167
|
+
if (err?.code === "ENOENT") return `error: file not found: ${err.path ?? msg.match(/ENOENT: no such file or directory[^']*'([^']+)'/)?.[1] ?? "?"}`;
|
|
63
168
|
if (err?.code === "EISDIR") {
|
|
64
169
|
const argvDir = findDirectoryArg();
|
|
65
170
|
const path = err.path ?? msg.match(/EISDIR:[^']*'([^']+)'/)?.[1] ?? argvDir ?? "?";
|
|
66
|
-
|
|
67
|
-
process.stderr.write(`error: expected an HTML file, got a directory: ${path}\n${hint}\n`);
|
|
68
|
-
process.exit(1);
|
|
171
|
+
return `error: expected an HTML file, got a directory: ${path}\n${path === "?" ? " hint: pass the path to a specific .html file." : ` hint: pass the path to a specific .html file inside it (e.g. ${path}/page.html).`}`;
|
|
69
172
|
}
|
|
70
173
|
const missingBrowser = formatMissingPlaywrightBrowserError(e);
|
|
71
|
-
if (missingBrowser)
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
}
|
|
75
|
-
if (/net::ERR_NAME_NOT_RESOLVED/i.test(msg) || /net::ERR_CONNECTION_REFUSED/i.test(msg) || /Cannot navigate to invalid URL/i.test(msg)) {
|
|
174
|
+
if (missingBrowser) return missingBrowser;
|
|
175
|
+
const missingModule = formatMissingPlaywrightModuleError(e);
|
|
176
|
+
if (missingModule) return missingModule;
|
|
177
|
+
if (/net::ERR_FILE_NOT_FOUND/i.test(msg)) return `error: file not found: ${navigationTargetPath(msg)}`;
|
|
178
|
+
if (/net::ERR_NAME_NOT_RESOLVED/i.test(msg) || /net::ERR_CONNECTION_REFUSED/i.test(msg) || /net::ERR_UNSAFE_PORT/i.test(msg) || /Cannot navigate to invalid URL/i.test(msg)) {
|
|
76
179
|
const url = msg.match(/Navigating to ([^,]+)/i)?.[1] ?? msg.match(/(https?:\/\/[^\s"]+)/)?.[1] ?? "the URL";
|
|
77
180
|
let reason = "failed to load";
|
|
78
181
|
if (/ERR_NAME_NOT_RESOLVED/i.test(msg)) reason = "host could not be resolved (check the URL)";
|
|
79
182
|
else if (/ERR_CONNECTION_REFUSED/i.test(msg)) reason = "connection refused (is the server running?)";
|
|
183
|
+
else if (/ERR_UNSAFE_PORT/i.test(msg)) reason = "Chromium refuses to fetch this port (it is on the blocked-port list) — try another port";
|
|
80
184
|
else if (/invalid URL/i.test(msg)) reason = "not a valid URL";
|
|
81
|
-
|
|
82
|
-
process.exit(1);
|
|
185
|
+
return `error: cannot load ${url}: ${reason}`;
|
|
83
186
|
}
|
|
84
|
-
if (
|
|
85
|
-
|
|
187
|
+
if (/^page load timed out after \d+ms waiting for/.test(msg)) return `error: ${msg}`;
|
|
188
|
+
if (/^the --har recording holds nothing for /.test(msg)) return `error: ${msg}`;
|
|
189
|
+
if (/Timeout \d+ms exceeded/i.test(msg)) return `error: page load timed out (${msg.match(/Timeout \d+ms exceeded[^.]*/i)?.[0] ?? msg})`;
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
function handleCliError(e) {
|
|
193
|
+
const diagnosis = formatCliError(e);
|
|
194
|
+
if (diagnosis !== null) {
|
|
195
|
+
process.stderr.write(`${diagnosis}\n`);
|
|
86
196
|
process.exit(1);
|
|
87
197
|
}
|
|
88
198
|
console.error(e);
|
|
89
199
|
process.exit(1);
|
|
90
200
|
}
|
|
91
201
|
/**
|
|
202
|
+
* The path a failed `page.goto` was aiming at, as an ordinary filesystem path.
|
|
203
|
+
*
|
|
204
|
+
* Playwright reports `net::ERR_FILE_NOT_FOUND at file:///abs/nope.html`, and a
|
|
205
|
+
* `file://` URL is the wrong thing to echo back: the caller typed a path, and a
|
|
206
|
+
* percent-encoded URL of it is harder to compare against what they typed. This
|
|
207
|
+
* decodes it so the message matches the ENOENT branch's exactly.
|
|
208
|
+
*
|
|
209
|
+
* Falls back to the raw match, then to scanning argv, because a message shape
|
|
210
|
+
* that changes with a Playwright upgrade should degrade to a worse path rather
|
|
211
|
+
* than to no message at all.
|
|
212
|
+
*/
|
|
213
|
+
function navigationTargetPath(msg) {
|
|
214
|
+
const url = msg.match(/(file:\/\/\/[^\s"']+)/)?.[1];
|
|
215
|
+
if (url) try {
|
|
216
|
+
return fileURLToPath(url);
|
|
217
|
+
} catch {
|
|
218
|
+
return url;
|
|
219
|
+
}
|
|
220
|
+
for (const arg of process.argv.slice(2)) if (!arg.startsWith("-") && /\.html?$/i.test(arg)) return arg;
|
|
221
|
+
return "?";
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
92
224
|
* EISDIR fallback: Node's `fsPromises.readFile` doesn't attach `.path`
|
|
93
225
|
* to the error, and the message string doesn't include the path
|
|
94
226
|
* either. Scan argv for the first positional that exists as a
|
|
@@ -104,4 +236,4 @@ function findDirectoryArg() {
|
|
|
104
236
|
}
|
|
105
237
|
}
|
|
106
238
|
//#endregion
|
|
107
|
-
export { UsageError, formatMissingPlaywrightBrowserError, handleCliError };
|
|
239
|
+
export { PLAYWRIGHT_PEER_RANGE, UsageError, formatCliError, formatMissingPlaywrightBrowserError, formatMissingPlaywrightModuleError, handleCliError, playwrightEngineFromLaunchError, playwrightInstallCommand, resolvePlaywrightInstallTarget, resolvedPlaywrightHasCli };
|
package/dist/element-compare.mjs
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { UsageError, handleCliError } from "./cli-error.mjs";
|
|
3
|
+
import { withBrowser } from "./browser-launch.mjs";
|
|
4
|
+
import { isCliEntry } from "./plugin/cli-entry.mjs";
|
|
2
5
|
import { compareScreenshots } from "./heatmap.mjs";
|
|
3
6
|
import { applyMask, parseMaskSelectors } from "./mask.mjs";
|
|
4
7
|
import { BOLD, CYAN, DIM, GREEN, RED, RESET, YELLOW, hr } from "./terminal-colors.mjs";
|
|
5
8
|
import { join, resolve } from "node:path";
|
|
9
|
+
import "playwright";
|
|
6
10
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
7
|
-
import { chromium } from "playwright";
|
|
8
11
|
//#region src/element-compare.ts
|
|
9
12
|
/**
|
|
10
13
|
* Element-level VRT comparison
|
|
@@ -46,10 +49,9 @@ async function runElementCompare(options) {
|
|
|
46
49
|
height: 900
|
|
47
50
|
}, outputDir, maskSelectors = [], threshold = .1 } = options;
|
|
48
51
|
await mkdir(outputDir, { recursive: true });
|
|
49
|
-
const browser = await chromium.launch();
|
|
50
52
|
const results = [];
|
|
51
53
|
let fullPageDiffRatio;
|
|
52
|
-
|
|
54
|
+
await withBrowser(async (browser) => {
|
|
53
55
|
const baselinePage = await browser.newPage({ viewport });
|
|
54
56
|
if (options.baselineUrl) await baselinePage.goto(options.baselineUrl, {
|
|
55
57
|
waitUntil: "networkidle",
|
|
@@ -139,9 +141,7 @@ async function runElementCompare(options) {
|
|
|
139
141
|
}
|
|
140
142
|
await baselinePage.close();
|
|
141
143
|
await currentPage.close();
|
|
142
|
-
}
|
|
143
|
-
await browser.close();
|
|
144
|
-
}
|
|
144
|
+
});
|
|
145
145
|
const matched = results.filter((r) => r.found.baseline && r.found.current);
|
|
146
146
|
const changed = matched.filter((r) => r.diffRatio > 0);
|
|
147
147
|
const missing = results.filter((r) => !r.found.baseline || !r.found.current);
|
|
@@ -168,7 +168,7 @@ function parseArgs(args) {
|
|
|
168
168
|
return idx >= 0 && args[idx + 1] ? args[idx + 1] : fallback;
|
|
169
169
|
}
|
|
170
170
|
const selectorsRaw = getArg("selectors");
|
|
171
|
-
if (!selectorsRaw) throw new
|
|
171
|
+
if (!selectorsRaw) throw new UsageError("--selectors is required (comma-separated CSS selectors)");
|
|
172
172
|
const selectors = selectorsRaw.split(",").map((s) => s.trim()).filter(Boolean);
|
|
173
173
|
const baselineUrl = getArg("url") || void 0;
|
|
174
174
|
const currentUrl = getArg("current-url") || void 0;
|
|
@@ -261,9 +261,6 @@ async function main() {
|
|
|
261
261
|
console.log(` ${DIM}Report: ${reportPath}${RESET}`);
|
|
262
262
|
console.log();
|
|
263
263
|
}
|
|
264
|
-
if (
|
|
265
|
-
console.error(e);
|
|
266
|
-
process.exit(1);
|
|
267
|
-
});
|
|
264
|
+
if (isCliEntry(import.meta.url, "element-compare")) main().catch(handleCliError);
|
|
268
265
|
//#endregion
|
|
269
266
|
export { runElementCompare };
|