@mizchi/vlmkit-capture 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/batch-prescan.d.mts +51 -0
  2. package/dist/batch-prescan.mjs +66 -0
  3. package/dist/capture-config.d.mts +50 -0
  4. package/dist/capture-config.mjs +164 -0
  5. package/dist/capturer.d.mts +45 -0
  6. package/dist/capturer.mjs +94 -0
  7. package/dist/cloudflare-quick-actions.d.mts +114 -0
  8. package/dist/cloudflare-quick-actions.mjs +142 -0
  9. package/dist/crater-client.d.mts +159 -0
  10. package/dist/crater-client.mjs +362 -0
  11. package/dist/crater-smoke.d.mts +98 -0
  12. package/dist/crater-smoke.mjs +269 -0
  13. package/dist/crater-wasm.d.mts +65 -0
  14. package/dist/crater-wasm.mjs +132 -0
  15. package/{src/detection-types.ts → dist/detection-types.d.mts} +4 -2
  16. package/dist/detection-types.mjs +1 -0
  17. package/dist/index.d.mts +12 -0
  18. package/dist/index.mjs +11 -0
  19. package/dist/playwright-analyzer.d.mts +38 -0
  20. package/dist/playwright-analyzer.mjs +117 -0
  21. package/dist/playwright-launch-error.d.mts +7 -0
  22. package/dist/playwright-launch-error.mjs +25 -0
  23. package/dist/prescanner.d.mts +39 -0
  24. package/dist/prescanner.mjs +61 -0
  25. package/dist/viewport-discovery.d.mts +114 -0
  26. package/dist/viewport-discovery.mjs +294 -0
  27. package/package.json +18 -6
  28. package/src/batch-prescan.ts +0 -115
  29. package/src/capture-config.ts +0 -219
  30. package/src/capturer.ts +0 -138
  31. package/src/cloudflare-quick-actions.ts +0 -304
  32. package/src/crater-client.ts +0 -537
  33. package/src/crater-smoke.ts +0 -336
  34. package/src/crater-wasm.ts +0 -260
  35. package/src/index.ts +0 -157
  36. package/src/playwright-analyzer.ts +0 -180
  37. package/src/playwright-launch-error.ts +0 -41
  38. package/src/prescanner.ts +0 -123
  39. package/src/viewport-discovery.ts +0 -455
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mizchi/vlmkit-capture",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "description": "Playwright + Crater capture infrastructure for VRT — viewport discovery, multi-route capture, prescanner.",
5
5
  "license": "MIT",
6
6
  "author": "mizchi",
@@ -14,23 +14,35 @@
14
14
  "url": "https://github.com/mizchi/vlmkit/issues"
15
15
  },
16
16
  "type": "module",
17
+ "engines": {
18
+ "node": ">=24"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
17
23
  "files": [
18
- "src/**/*.ts",
19
- "!src/**/*.test.ts",
24
+ "dist/**",
20
25
  "README.md",
21
26
  "LICENSE"
22
27
  ],
23
28
  "exports": {
24
- ".": "./src/index.ts",
25
- "./*.ts": "./src/*.ts"
29
+ ".": {
30
+ "types": "./dist/index.d.mts",
31
+ "import": "./dist/index.mjs"
32
+ },
33
+ "./*.ts": {
34
+ "types": "./dist/*.d.mts",
35
+ "import": "./dist/*.mjs"
36
+ }
26
37
  },
27
38
  "dependencies": {
28
39
  "playwright": "^1.61.1",
29
40
  "pngjs": "^7.0.0",
30
41
  "ws": "^8.20.0",
31
- "@mizchi/vlmkit-core": "0.8.0"
42
+ "@mizchi/vlmkit-core": "0.8.1"
32
43
  },
33
44
  "scripts": {
45
+ "build": "pnpm --dir ../.. exec tsdown --config tsdown.packages.config.ts --filter @mizchi/vlmkit-capture",
34
46
  "test": "node --test 'src/**/*.test.ts'"
35
47
  }
36
48
  }
@@ -1,115 +0,0 @@
1
- /**
2
- * Crater v0.18.0 `batchRender` driver for prescanner detection.
3
- *
4
- * Renders baseline + multiple broken variants in one BiDi call and returns
5
- * the paint-tree diff per variant. This is the fast path for prescanner
6
- * mode: instead of doing N × (setContent + capturePaintTree) for N trials
7
- * at a single viewport, do one `batchRender` and diff the returned trees.
8
- *
9
- * Computed-style and forced-state signals still require the per-viewport
10
- * capture flow — `batchRender` only returns paint trees. Use this driver
11
- * alongside the existing capture loop, not as a wholesale replacement.
12
- */
13
- import type {
14
- CraterClient,
15
- CraterCssMutation,
16
- PaintNode,
17
- PaintTreeChange,
18
- } from "./crater-client.ts";
19
- import { diffPaintTrees } from "./crater-client.ts";
20
-
21
- export interface BatchPrescanRequest {
22
- /** Stable id (echoed back in the result). */
23
- id: string;
24
- /** CSS mutations describing how this variant diverges from the baseline. */
25
- mutations: CraterCssMutation[];
26
- }
27
-
28
- export interface BatchPrescanResult {
29
- id: string;
30
- /** Paint-tree changes vs. the baseline tree. Empty when the variant looks identical. */
31
- changes: PaintTreeChange[];
32
- /** The variant's paint tree, when Crater returned one (kept for downstream inspection). */
33
- paintTree?: PaintNode | null;
34
- /** True when Crater silently dropped the variant (no `paintTree` in the response). */
35
- missing: boolean;
36
- }
37
-
38
- export interface BatchPrescanOptions {
39
- /** Skip variants whose `mutations` array is empty — Crater would no-op them anyway. */
40
- skipEmptyMutations?: boolean;
41
- }
42
-
43
- /**
44
- * Drive `batchRender` and return per-variant paint-tree diffs against a
45
- * caller-supplied baseline tree. The baseline tree must come from a render
46
- * of the unmodified `baseHtml` at the same viewport.
47
- *
48
- * The caller is responsible for collecting `baselinePaintTree` (e.g. via
49
- * the existing `capturePageStateCrater` flow at the same viewport).
50
- */
51
- export async function runBatchPrescan(
52
- client: Pick<CraterClient, "batchRender">,
53
- baseHtml: string,
54
- viewport: { width: number; height: number },
55
- baselinePaintTree: PaintNode,
56
- requests: BatchPrescanRequest[],
57
- options: BatchPrescanOptions = {},
58
- ): Promise<BatchPrescanResult[]> {
59
- const skipEmpty = options.skipEmptyMutations ?? true;
60
- const callable = skipEmpty
61
- ? requests.filter((req) => req.mutations.length > 0)
62
- : requests;
63
-
64
- if (callable.length === 0) return [];
65
-
66
- const batch = await client.batchRender(
67
- baseHtml,
68
- viewport,
69
- callable.map((req) => ({ id: req.id, mutations: req.mutations })),
70
- );
71
-
72
- const byId = new Map<string, PaintNode | null | undefined>();
73
- for (const entry of batch.results ?? []) {
74
- byId.set(entry.id, entry.paintTree ?? null);
75
- }
76
-
77
- return callable.map((req) => {
78
- const tree = byId.get(req.id);
79
- if (tree === undefined || tree === null) {
80
- return { id: req.id, changes: [], missing: true };
81
- }
82
- const changes = diffPaintTrees(baselinePaintTree, tree);
83
- return { id: req.id, changes, paintTree: tree, missing: false };
84
- });
85
- }
86
-
87
- /**
88
- * Build a Crater `mutations` payload for "remove a single CSS declaration"
89
- * — the css-challenge property-mode trial shape.
90
- */
91
- export function mutationsForPropertyRemoval(
92
- selector: string,
93
- property: string,
94
- ): CraterCssMutation[] {
95
- return [{ selector, property, action: "remove" }];
96
- }
97
-
98
- /**
99
- * Build a Crater `mutations` payload for "remove every declaration in a
100
- * selector block" — the css-challenge selector-mode trial shape.
101
- */
102
- export function mutationsForSelectorBlockRemoval(
103
- selector: string,
104
- properties: string[],
105
- ): CraterCssMutation[] {
106
- return properties.map((property) => ({ selector, property, action: "remove" }));
107
- }
108
-
109
- /**
110
- * True when at least one of the batch-prescan results found a paint-tree
111
- * signal. Used to short-circuit follow-up per-viewport captures.
112
- */
113
- export function hasAnyBatchPrescanSignal(results: BatchPrescanResult[]): boolean {
114
- return results.some((result) => !result.missing && result.changes.length > 0);
115
- }
@@ -1,219 +0,0 @@
1
- /**
2
- * Capture configuration loader for `vrt workflow init|capture`.
3
- *
4
- * Allows external projects to drive `e2e/vrt-capture.spec.ts` without
5
- * editing the spec by sourcing routes from `vrt.config.json` (or any
6
- * file pointed at by `--config` / `VRT_CONFIG_PATH`).
7
- */
8
- import { existsSync, readFileSync } from "node:fs";
9
- import { dirname, isAbsolute, resolve } from "node:path";
10
-
11
- export interface CaptureRoute {
12
- name: string;
13
- path: string;
14
- waitFor?: string;
15
- }
16
-
17
- export interface CaptureConfig {
18
- baseUrl?: string;
19
- routes?: CaptureRoute[];
20
- }
21
-
22
- export interface CaptureRouteSet {
23
- baseUrl: string;
24
- routes: CaptureRoute[];
25
- source: "env" | "config" | "default";
26
- configPath?: string;
27
- }
28
-
29
- export const DEFAULT_CAPTURE_BASE_URL = "http://127.0.0.1:4174";
30
-
31
- /**
32
- * Built-in fallback used when no config or env override is provided.
33
- * Kept for vrt's own development workflow; external projects should
34
- * supply their own routes via `vrt.config.json`.
35
- */
36
- export const DEFAULT_CAPTURE_ROUTES: CaptureRoute[] = [
37
- { name: "home", path: "/", waitFor: "main" },
38
- { name: "readme", path: "/readme", waitFor: "article" },
39
- { name: "files", path: "/files", waitFor: "main" },
40
- { name: "issues", path: "/issues", waitFor: "main" },
41
- { name: "pulls", path: "/pulls", waitFor: "main" },
42
- ];
43
-
44
- export const DEFAULT_CAPTURE_CONFIG_FILE = "vrt.config.json";
45
-
46
- export function parseCaptureConfig(raw: string): CaptureConfig {
47
- let parsed: unknown;
48
- try {
49
- parsed = JSON.parse(raw);
50
- } catch (error) {
51
- throw new Error(`Invalid capture config JSON: ${String(error)}`);
52
- }
53
-
54
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
55
- throw new Error("Capture config must be an object");
56
- }
57
-
58
- const record = parsed as Record<string, unknown>;
59
- const baseUrl = record.baseUrl == null
60
- ? undefined
61
- : parseNonEmptyString(record.baseUrl, "capture config baseUrl must be a non-empty string");
62
-
63
- // `capture.routes` is preferred so it coexists cleanly with snapshot `routes`.
64
- const captureSection = record.capture;
65
- const routesSource = pickRoutesSource(captureSection, record.routes);
66
- const routes = routesSource === undefined ? undefined : parseCaptureRoutes(routesSource);
67
-
68
- return { baseUrl, routes };
69
- }
70
-
71
- function pickRoutesSource(captureSection: unknown, topLevelRoutes: unknown): unknown {
72
- if (captureSection !== undefined && captureSection !== null) {
73
- if (typeof captureSection !== "object" || Array.isArray(captureSection)) {
74
- throw new Error("capture config `capture` must be an object");
75
- }
76
- const inner = (captureSection as Record<string, unknown>).routes;
77
- if (inner !== undefined) return inner;
78
- }
79
- return topLevelRoutes;
80
- }
81
-
82
- function parseCaptureRoutes(value: unknown): CaptureRoute[] {
83
- if (!Array.isArray(value)) {
84
- throw new Error("capture config routes must be an array");
85
- }
86
-
87
- return value.map((entry, index) => parseCaptureRoute(entry, index));
88
- }
89
-
90
- function parseCaptureRoute(entry: unknown, index: number): CaptureRoute {
91
- if (typeof entry === "string") {
92
- const path = entry.trim();
93
- if (!path) {
94
- throw new Error(`capture config route at index ${index} must be a non-empty string`);
95
- }
96
- return { name: routeNameFromPath(path), path };
97
- }
98
-
99
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
100
- throw new Error(`capture config route at index ${index} must be a string or object`);
101
- }
102
-
103
- const record = entry as Record<string, unknown>;
104
- const pathValue = record.path ?? record.url;
105
- const path = parseNonEmptyString(pathValue, `capture config route at index ${index} must have a path`);
106
-
107
- const nameRaw = record.name ?? record.label;
108
- const name = nameRaw === undefined
109
- ? routeNameFromPath(path)
110
- : parseNonEmptyString(nameRaw, `capture config route at index ${index} has an invalid name`);
111
-
112
- const waitForRaw = record.waitFor ?? record.wait_for;
113
- const route: CaptureRoute = { name, path };
114
- if (waitForRaw !== undefined) {
115
- route.waitFor = parseNonEmptyString(
116
- waitForRaw,
117
- `capture config route at index ${index} has an invalid waitFor`,
118
- );
119
- }
120
- return route;
121
- }
122
-
123
- export function routeNameFromPath(path: string): string {
124
- const trimmed = path.split("?")[0]!.split("#")[0]!;
125
- const cleaned = trimmed.replace(/^\/+|\/+$/g, "");
126
- if (!cleaned) return "home";
127
- const safe = cleaned.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
128
- return safe || "home";
129
- }
130
-
131
- export interface LoadCaptureConfigOptions {
132
- configPath?: string;
133
- cwd?: string;
134
- envRoutes?: string;
135
- envBaseUrl?: string;
136
- envConfigPath?: string;
137
- }
138
-
139
- /**
140
- * Resolve the route set to use for a capture run.
141
- *
142
- * Precedence (highest first):
143
- * 1. `VRT_CAPTURE_ROUTES` env var (JSON-encoded array)
144
- * 2. Explicit config path (CLI / `VRT_CONFIG_PATH`)
145
- * 3. `vrt.config.json` discovered in `cwd`
146
- * 4. Built-in defaults
147
- */
148
- export function resolveCaptureRoutes(options: LoadCaptureConfigOptions = {}): CaptureRouteSet {
149
- const cwd = options.cwd ?? process.cwd();
150
- const envBaseUrl = options.envBaseUrl?.trim();
151
-
152
- const envRoutes = options.envRoutes;
153
- if (envRoutes && envRoutes.trim().length > 0) {
154
- const routes = parseCaptureRoutes(JSON.parse(envRoutes));
155
- return {
156
- baseUrl: envBaseUrl || DEFAULT_CAPTURE_BASE_URL,
157
- routes,
158
- source: "env",
159
- };
160
- }
161
-
162
- const configPath = resolveConfigPath(options.configPath, options.envConfigPath, cwd);
163
- if (configPath) {
164
- const raw = readFileSync(configPath, "utf-8");
165
- const config = parseCaptureConfig(raw);
166
- const routes = config.routes ?? DEFAULT_CAPTURE_ROUTES;
167
- return {
168
- baseUrl: envBaseUrl || config.baseUrl || DEFAULT_CAPTURE_BASE_URL,
169
- routes,
170
- source: "config",
171
- configPath,
172
- };
173
- }
174
-
175
- return {
176
- baseUrl: envBaseUrl || DEFAULT_CAPTURE_BASE_URL,
177
- routes: DEFAULT_CAPTURE_ROUTES,
178
- source: "default",
179
- };
180
- }
181
-
182
- function resolveConfigPath(
183
- explicit: string | undefined,
184
- fromEnv: string | undefined,
185
- cwd: string,
186
- ): string | undefined {
187
- const candidate = explicit ?? fromEnv;
188
- if (candidate && candidate.trim().length > 0) {
189
- const absolute = isAbsolute(candidate) ? candidate : resolve(cwd, candidate);
190
- if (!existsSync(absolute)) {
191
- throw new Error(`Capture config not found: ${absolute}`);
192
- }
193
- return absolute;
194
- }
195
-
196
- const defaultPath = resolve(cwd, DEFAULT_CAPTURE_CONFIG_FILE);
197
- return existsSync(defaultPath) ? defaultPath : undefined;
198
- }
199
-
200
- function parseNonEmptyString(value: unknown, message: string): string {
201
- if (typeof value !== "string" || value.trim() === "") {
202
- throw new Error(message);
203
- }
204
- return value;
205
- }
206
-
207
- /**
208
- * Helper for unit tests / non-Playwright callers: read & normalize a file.
209
- */
210
- export function loadCaptureConfigFromFile(configPath: string): CaptureConfig {
211
- if (!existsSync(configPath)) {
212
- throw new Error(`Capture config not found: ${configPath}`);
213
- }
214
- return parseCaptureConfig(readFileSync(configPath, "utf-8"));
215
- }
216
-
217
- export function captureConfigDir(configPath: string): string {
218
- return dirname(configPath);
219
- }
package/src/capturer.ts DELETED
@@ -1,138 +0,0 @@
1
- /**
2
- * Browser launch abstraction.
3
- *
4
- * Lets every consumer pick between launching Chromium locally and connecting
5
- * to a remote Chrome DevTools Protocol endpoint such as Cloudflare's
6
- * Browser Run service (https://api.cloudflare.com/client/v4/accounts/<id>/browser-rendering/devtools/browser).
7
- *
8
- * The factory only knows how to *open* a Browser. Page/context creation is
9
- * left to the caller so existing capture code can keep its current
10
- * `browser.newPage({viewport})` style.
11
- */
12
- import { chromium, type Browser } from "playwright";
13
-
14
- export type CaptureBackendKind = "local" | "cloudflare-cdp";
15
-
16
- export interface CaptureBackend {
17
- readonly kind: CaptureBackendKind;
18
- /** Human-readable label used in logs. */
19
- readonly label: string;
20
- launch(): Promise<Browser>;
21
- close(browser: Browser): Promise<void>;
22
- }
23
-
24
- export interface CloudflareCdpOptions {
25
- accountId: string;
26
- apiToken: string;
27
- /** Override the default CF CDP URL (useful for tests / private deployments). */
28
- endpoint?: string;
29
- }
30
-
31
- export function buildCloudflareCdpUrl(opts: { accountId: string; endpoint?: string }): string {
32
- if (opts.endpoint && opts.endpoint.length > 0) return opts.endpoint;
33
- const account = opts.accountId.trim();
34
- if (account.length === 0) {
35
- throw new Error("Cloudflare account id is required to build the CDP URL");
36
- }
37
- return `wss://api.cloudflare.com/client/v4/accounts/${account}/browser-rendering/devtools/browser`;
38
- }
39
-
40
- export function createLocalCapturer(): CaptureBackend {
41
- return {
42
- kind: "local",
43
- label: "local chromium",
44
- async launch() {
45
- return chromium.launch();
46
- },
47
- async close(browser) {
48
- await browser.close();
49
- },
50
- };
51
- }
52
-
53
- export function createCloudflareCdpCapturer(opts: CloudflareCdpOptions): CaptureBackend {
54
- if (!opts.apiToken || opts.apiToken.trim().length === 0) {
55
- throw new Error("Cloudflare API token is required for the cloudflare-cdp backend");
56
- }
57
- const wsEndpoint = buildCloudflareCdpUrl(opts);
58
- const headers = { Authorization: `Bearer ${opts.apiToken}` };
59
-
60
- return {
61
- kind: "cloudflare-cdp",
62
- label: `cloudflare browser run (${maskAccount(opts.accountId)})`,
63
- async launch() {
64
- return chromium.connectOverCDP(wsEndpoint, { headers });
65
- },
66
- async close(browser) {
67
- // For remote browsers, close() releases the WebSocket but does not
68
- // terminate the CF session — that's managed server-side.
69
- await browser.close();
70
- },
71
- };
72
- }
73
-
74
- function maskAccount(id: string): string {
75
- if (id.length <= 8) return id;
76
- return `${id.slice(0, 4)}…${id.slice(-4)}`;
77
- }
78
-
79
- export interface ResolveCaptureBackendOptions {
80
- /** Value from `--backend` CLI flag (e.g. "local", "cloudflare"). */
81
- backendFlag?: string;
82
- env?: NodeJS.ProcessEnv;
83
- }
84
-
85
- export interface ResolvedCaptureBackend {
86
- backend: CaptureBackend;
87
- source: "flag" | "env" | "default";
88
- }
89
-
90
- /**
91
- * Resolution order:
92
- * 1. Explicit `--backend` flag
93
- * 2. `VRT_CAPTURE_BACKEND` env var
94
- * 3. Default local
95
- *
96
- * For the Cloudflare backend, credentials come from env (`CLOUDFLARE_ACCOUNT_ID`
97
- * + `CLOUDFLARE_API_TOKEN`) regardless of how the backend was selected, so
98
- * CI configs can stay declarative.
99
- */
100
- export function resolveCaptureBackend(
101
- options: ResolveCaptureBackendOptions = {},
102
- ): ResolvedCaptureBackend {
103
- const env = options.env ?? process.env;
104
- const explicit = options.backendFlag?.trim().toLowerCase();
105
- const envChoice = env.VRT_CAPTURE_BACKEND?.trim().toLowerCase();
106
-
107
- const choice = explicit || envChoice || "local";
108
- const source: ResolvedCaptureBackend["source"] = explicit
109
- ? "flag"
110
- : envChoice
111
- ? "env"
112
- : "default";
113
-
114
- switch (choice) {
115
- case "local":
116
- case "chromium":
117
- return { backend: createLocalCapturer(), source };
118
- case "cloudflare":
119
- case "cloudflare-cdp":
120
- case "browser-run": {
121
- const accountId = env.CLOUDFLARE_ACCOUNT_ID?.trim();
122
- const apiToken = env.CLOUDFLARE_API_TOKEN?.trim();
123
- const endpoint = env.CLOUDFLARE_BROWSER_RUN_ENDPOINT?.trim();
124
- if (!accountId) {
125
- throw new Error("CLOUDFLARE_ACCOUNT_ID is required when --backend cloudflare is selected");
126
- }
127
- if (!apiToken) {
128
- throw new Error("CLOUDFLARE_API_TOKEN is required when --backend cloudflare is selected");
129
- }
130
- return {
131
- backend: createCloudflareCdpCapturer({ accountId, apiToken, endpoint }),
132
- source,
133
- };
134
- }
135
- default:
136
- throw new Error(`Unknown capture backend: ${choice}`);
137
- }
138
- }