@mizchi/vlmkit-capture 0.6.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,443 @@
1
+ /**
2
+ * Crater BiDi client
3
+ *
4
+ * Lightweight client connecting to mizchi/crater WebDriver BiDi server
5
+ * for HTML rendering + screenshot capture.
6
+ *
7
+ * Start crater server:
8
+ * cd ~/ghq/github.com/mizchi/crater
9
+ * just build-bidi && just start-bidi-with-font
10
+ */
11
+ import WebSocket from "ws";
12
+ import { PNG } from "pngjs";
13
+ import {
14
+ buildComputedStyleCaptureJsonExpression,
15
+ computedStyleSnapshotToMap,
16
+ hasMeaningfulComputedStyleSnapshot,
17
+ parseComputedStyleSnapshot,
18
+ } from "@mizchi/vlmkit-core/computed-style-capture.ts";
19
+
20
+ export const DEFAULT_BIDI_URL = "ws://127.0.0.1:9222";
21
+
22
+ export interface CraterResponsiveBreakpoint {
23
+ axis: "width";
24
+ op: "ge" | "gt" | "le" | "lt";
25
+ valuePx: number;
26
+ raw: string;
27
+ normalized: string;
28
+ guards: string[];
29
+ ruleCount: number;
30
+ }
31
+
32
+ export interface CraterBreakpointDiscoveryDiagnostics {
33
+ stylesheetCount: number;
34
+ ruleCount: number;
35
+ externalStylesheetLinks: string[];
36
+ ignoredQueries: string[];
37
+ unsupportedQueries: string[];
38
+ }
39
+
40
+ export interface CraterRuleViewportMapEntry {
41
+ selector: string;
42
+ properties: string[];
43
+ mediaCondition: string;
44
+ activeAtWidths: number[];
45
+ inactiveAtWidths: number[];
46
+ }
47
+
48
+ export interface CraterRuleViewportMap {
49
+ rules: CraterRuleViewportMapEntry[];
50
+ }
51
+
52
+ export interface CraterComputedStyleWithState {
53
+ normal: Record<string, string>;
54
+ forced: Record<string, string>;
55
+ diff: Array<{ property: string; normal: string; forced: string }>;
56
+ }
57
+
58
+ export interface CraterBatchRenderResult {
59
+ results: Array<{
60
+ id: string;
61
+ paintData?: string;
62
+ width?: number;
63
+ height?: number;
64
+ }>;
65
+ }
66
+
67
+ export interface CraterBreakpointDiscoveryResult {
68
+ breakpoints: CraterResponsiveBreakpoint[];
69
+ diagnostics?: CraterBreakpointDiscoveryDiagnostics;
70
+ }
71
+
72
+ interface BidiResponse {
73
+ id: number;
74
+ type: "success" | "error";
75
+ result?: unknown;
76
+ error?: string;
77
+ message?: string;
78
+ }
79
+
80
+ type PendingCommand = {
81
+ resolve: (value: BidiResponse) => void;
82
+ reject: (error: Error) => void;
83
+ };
84
+
85
+ export class CraterClient {
86
+ private ws: WebSocket | null = null;
87
+ private commandId = 0;
88
+ private pendingCommands = new Map<number, PendingCommand>();
89
+ private contextId: string | null = null;
90
+ private url: string;
91
+
92
+ constructor(url = DEFAULT_BIDI_URL) {
93
+ this.url = url;
94
+ }
95
+
96
+ async connect(): Promise<void> {
97
+ await new Promise<void>((resolve, reject) => {
98
+ this.ws = new WebSocket(this.url);
99
+ this.ws.on("open", async () => {
100
+ try {
101
+ const resp = await this.sendBidi("browsingContext.create", { type: "tab" });
102
+ this.contextId = (resp.result as { context: string }).context;
103
+ resolve();
104
+ } catch (error) {
105
+ reject(error);
106
+ }
107
+ });
108
+ this.ws.on("error", (error) => reject(error));
109
+ this.ws.on("message", (data) => this.handleMessage(data.toString()));
110
+ });
111
+ }
112
+
113
+ async close(): Promise<void> {
114
+ if (this.contextId) {
115
+ try {
116
+ await this.sendBidi("browsingContext.close", { context: this.contextId });
117
+ } catch (e) { console.warn("[crater] close context failed:", e instanceof Error ? e.message : e); }
118
+ }
119
+ this.contextId = null;
120
+ this.ws?.close();
121
+ this.ws = null;
122
+ }
123
+
124
+ async setViewport(width: number, height: number): Promise<void> {
125
+ await this.sendBidi("browsingContext.setViewport", {
126
+ context: this.requireContextId(),
127
+ viewport: { width, height },
128
+ });
129
+ }
130
+
131
+ async setContent(html: string): Promise<void> {
132
+ const dataUrl = `data:text/html;base64,${Buffer.from(html).toString("base64")}`;
133
+ await this.sendBidi("browsingContext.navigate", {
134
+ context: this.requireContextId(),
135
+ url: dataUrl,
136
+ wait: "complete",
137
+ });
138
+ await this.evaluate(`__loadHTML(${JSON.stringify(html)})`);
139
+ await this.evaluate(`(async () => await __executeScripts())()`, true);
140
+ }
141
+
142
+ async evaluate<T>(expression: string, awaitPromise = false): Promise<T> {
143
+ const resp = await this.sendBidi("script.evaluate", {
144
+ expression,
145
+ target: { context: this.requireContextId() },
146
+ awaitPromise: awaitPromise || expression.includes("await ") || expression.includes("new Promise"),
147
+ });
148
+ if (resp.type === "error") {
149
+ throw new Error(resp.message || resp.error || "script.evaluate failed");
150
+ }
151
+ const result = resp.result as { result?: { value?: T }; exceptionDetails?: unknown };
152
+ if (result.exceptionDetails) {
153
+ throw new Error(JSON.stringify(result.exceptionDetails));
154
+ }
155
+ return result.result?.value as T;
156
+ }
157
+
158
+ /** PNG screenshot (Buffer) */
159
+ async captureScreenshot(): Promise<Buffer> {
160
+ const resp = await this.sendBidi("browsingContext.captureScreenshotData", {
161
+ context: this.requireContextId(),
162
+ origin: "viewport",
163
+ });
164
+ if (resp.type === "error") {
165
+ throw new Error(resp.message || resp.error || "captureScreenshotData failed");
166
+ }
167
+ return Buffer.from(String(resp.result || ""), "base64");
168
+ }
169
+
170
+ /** Raw RGBA data (pixelmatch compatible) */
171
+ async capturePaintData(): Promise<{ width: number; height: number; data: Uint8Array }> {
172
+ const resp = await this.sendBidi("browsingContext.capturePaintData", {
173
+ context: this.requireContextId(),
174
+ origin: "viewport",
175
+ }, 120_000);
176
+ if (resp.type === "error") {
177
+ throw new Error(resp.message || resp.error || "capturePaintData failed");
178
+ }
179
+ const result = resp.result as { width?: number; height?: number; data?: string };
180
+ return {
181
+ width: Number(result.width ?? 0),
182
+ height: Number(result.height ?? 0),
183
+ data: Uint8Array.from(Buffer.from(String(result.data || ""), "base64")),
184
+ };
185
+ }
186
+
187
+ /** Raw RGBA -> PNG Buffer conversion */
188
+ async capturePng(): Promise<{ png: Buffer; width: number; height: number }> {
189
+ const { width, height, data } = await this.capturePaintData();
190
+ const png = new PNG({ width, height });
191
+ png.data = Buffer.from(data);
192
+ const pngBuffer = PNG.sync.write(png);
193
+ return { png: pngBuffer, width, height };
194
+ }
195
+
196
+ async captureComputedStyles(
197
+ properties: string[],
198
+ ): Promise<Map<string, Record<string, string>>> {
199
+ const rawSnapshot = await this.evaluate<unknown>(
200
+ buildComputedStyleCaptureJsonExpression(properties),
201
+ );
202
+ const snapshot = parseComputedStyleSnapshot(rawSnapshot);
203
+ if (!hasMeaningfulComputedStyleSnapshot(snapshot)) {
204
+ return new Map();
205
+ }
206
+ return computedStyleSnapshotToMap(snapshot);
207
+ }
208
+
209
+ async getResponsiveBreakpoints(
210
+ options: {
211
+ mode?: "live-inline" | "html-inline";
212
+ axis?: "width";
213
+ includeDiagnostics?: boolean;
214
+ } = {},
215
+ ): Promise<CraterBreakpointDiscoveryResult> {
216
+ const resp = await this.sendBidi("browsingContext.getResponsiveBreakpoints", {
217
+ context: this.requireContextId(),
218
+ mode: options.mode ?? "live-inline",
219
+ axis: options.axis ?? "width",
220
+ includeDiagnostics: options.includeDiagnostics ?? true,
221
+ }, 30_000);
222
+ if (resp.type === "error") {
223
+ throw new Error(resp.message || resp.error || "getResponsiveBreakpoints failed");
224
+ }
225
+ const result = resp.result as CraterBreakpointDiscoveryResult | undefined;
226
+ return {
227
+ breakpoints: result?.breakpoints ?? [],
228
+ diagnostics: result?.diagnostics,
229
+ };
230
+ }
231
+
232
+ /** CSS rule → viewport mapping (#33) */
233
+ async getCssRuleViewportMap(viewportWidths?: number[]): Promise<CraterRuleViewportMap> {
234
+ const resp = await this.sendBidi("browsingContext.getCssRuleViewportMap", {
235
+ context: this.requireContextId(),
236
+ ...(viewportWidths ? { viewportWidths } : {}),
237
+ }, 30_000);
238
+ if (resp.type === "error") throw new Error(resp.message || resp.error || "getCssRuleViewportMap failed");
239
+ return (resp.result as CraterRuleViewportMap) ?? { rules: [] };
240
+ }
241
+
242
+ /** Required test viewports (#33) */
243
+ async getRequiredTestViewports(): Promise<{ viewports: Array<{ width: number; reason: string }> }> {
244
+ const resp = await this.sendBidi("browsingContext.getRequiredTestViewports", {
245
+ context: this.requireContextId(),
246
+ }, 30_000);
247
+ if (resp.type === "error") throw new Error(resp.message || resp.error || "getRequiredTestViewports failed");
248
+ return (resp.result as { viewports: Array<{ width: number; reason: string }> }) ?? { viewports: [] };
249
+ }
250
+
251
+ /** Computed styles with forced pseudo-class state (#34) */
252
+ async getComputedStylesWithState(
253
+ selector: string,
254
+ forcedStates: string[],
255
+ properties: string[],
256
+ ): Promise<CraterComputedStyleWithState> {
257
+ const resp = await this.sendBidi("browsingContext.getComputedStylesWithState", {
258
+ context: this.requireContextId(),
259
+ selector,
260
+ forcedStates,
261
+ properties,
262
+ }, 30_000);
263
+ if (resp.type === "error") throw new Error(resp.message || resp.error || "getComputedStylesWithState failed");
264
+ return (resp.result as CraterComputedStyleWithState) ?? { normal: {}, forced: {}, diff: [] };
265
+ }
266
+
267
+ /** Batch variant rendering (#28) */
268
+ async batchRender(
269
+ baseHtml: string,
270
+ viewport: { width: number; height: number },
271
+ variants: Array<{ id: string; cssRemove?: { selector: string; property?: string }; replaceCss?: { original: string; replacement: string } }>,
272
+ ): Promise<CraterBatchRenderResult> {
273
+ const resp = await this.sendBidi("browsingContext.batchRender", {
274
+ context: this.requireContextId(),
275
+ baseHtml,
276
+ viewport,
277
+ variants,
278
+ }, 120_000);
279
+ if (resp.type === "error") throw new Error(resp.message || resp.error || "batchRender failed");
280
+ return (resp.result as CraterBatchRenderResult) ?? { results: [] };
281
+ }
282
+
283
+ // ---- Private ----
284
+
285
+ private requireContextId(): string {
286
+ if (!this.contextId) throw new Error("Not connected. Call connect() first.");
287
+ return this.contextId;
288
+ }
289
+
290
+ private handleMessage(data: string): void {
291
+ let msg: BidiResponse;
292
+ try {
293
+ msg = JSON.parse(data) as BidiResponse;
294
+ } catch {
295
+ console.warn("[crater] invalid JSON from BiDi:", data.slice(0, 200));
296
+ return;
297
+ }
298
+ if (typeof msg.id !== "number") return;
299
+ const pending = this.pendingCommands.get(msg.id);
300
+ if (pending) {
301
+ this.pendingCommands.delete(msg.id);
302
+ pending.resolve(msg);
303
+ }
304
+ }
305
+
306
+ private sendBidi(method: string, params: Record<string, unknown>, timeoutMs = 10_000): Promise<BidiResponse> {
307
+ return new Promise((resolve, reject) => {
308
+ const id = ++this.commandId;
309
+ const timer = setTimeout(() => {
310
+ this.pendingCommands.delete(id);
311
+ reject(new Error(`BiDi command ${method} timed out after ${timeoutMs}ms`));
312
+ }, timeoutMs);
313
+
314
+ this.pendingCommands.set(id, {
315
+ resolve: (resp) => { clearTimeout(timer); resolve(resp); },
316
+ reject: (err) => { clearTimeout(timer); reject(err); },
317
+ });
318
+
319
+ this.ws?.send(JSON.stringify({ id, method, params }));
320
+ });
321
+ }
322
+
323
+ /** Paint tree (render tree JSON) */
324
+ async capturePaintTree(): Promise<PaintNode> {
325
+ const resp = await this.sendBidi("browsingContext.capturePaintTree", {
326
+ context: this.requireContextId(),
327
+ }, 120_000);
328
+ if (resp.type === "error") {
329
+ throw new Error(resp.message || resp.error || "capturePaintTree failed");
330
+ }
331
+ const result = resp.result as { paintTree?: string };
332
+ return JSON.parse(result.paintTree || "{}");
333
+ }
334
+ }
335
+
336
+ // ---- Paint tree types & diff ----
337
+
338
+ export interface PaintNode {
339
+ id?: string;
340
+ tag?: string;
341
+ x: number;
342
+ y: number;
343
+ w: number;
344
+ h: number;
345
+ ox?: string;
346
+ oy?: string;
347
+ p?: PaintProps;
348
+ text?: string;
349
+ ch?: PaintNode[];
350
+ }
351
+
352
+ export interface PaintProps {
353
+ op?: number; // opacity
354
+ c?: number[]; // color [r,g,b,a]
355
+ bg?: number[]; // background [r,g,b,a]
356
+ fs?: number; // font-size
357
+ ib?: boolean; // is-bold
358
+ vis?: string; // visibility
359
+ br?: number[]; // border-radius
360
+ }
361
+
362
+ export interface PaintTreeChange {
363
+ path: string; // e.g. "body > div > div[0]"
364
+ type: "geometry" | "paint" | "text" | "added" | "removed";
365
+ property?: string;
366
+ before?: string;
367
+ after?: string;
368
+ }
369
+
370
+ /** Compare two paint trees and return the diff */
371
+ export function diffPaintTrees(baseline: PaintNode, current: PaintNode, path = "root"): PaintTreeChange[] {
372
+ const changes: PaintTreeChange[] = [];
373
+
374
+ // Geometry diff
375
+ if (baseline.x !== current.x || baseline.y !== current.y ||
376
+ baseline.w !== current.w || baseline.h !== current.h) {
377
+ changes.push({
378
+ path, type: "geometry",
379
+ property: "bounds",
380
+ before: `${baseline.x},${baseline.y} ${baseline.w}x${baseline.h}`,
381
+ after: `${current.x},${current.y} ${current.w}x${current.h}`,
382
+ });
383
+ }
384
+
385
+ // Paint properties diff
386
+ if (baseline.p && current.p) {
387
+ const bp = baseline.p;
388
+ const cp = current.p;
389
+ if (bp.op !== cp.op) {
390
+ changes.push({ path, type: "paint", property: "opacity", before: String(bp.op), after: String(cp.op) });
391
+ }
392
+ if (JSON.stringify(bp.c) !== JSON.stringify(cp.c)) {
393
+ changes.push({ path, type: "paint", property: "color", before: JSON.stringify(bp.c), after: JSON.stringify(cp.c) });
394
+ }
395
+ if (JSON.stringify(bp.bg) !== JSON.stringify(cp.bg)) {
396
+ changes.push({ path, type: "paint", property: "background", before: JSON.stringify(bp.bg), after: JSON.stringify(cp.bg) });
397
+ }
398
+ if (bp.fs !== cp.fs) {
399
+ changes.push({ path, type: "paint", property: "font-size", before: String(bp.fs), after: String(cp.fs) });
400
+ }
401
+ if (bp.ib !== cp.ib) {
402
+ changes.push({ path, type: "paint", property: "font-weight", before: String(bp.ib), after: String(cp.ib) });
403
+ }
404
+ if (JSON.stringify(bp.br) !== JSON.stringify(cp.br)) {
405
+ changes.push({ path, type: "paint", property: "border-radius", before: JSON.stringify(bp.br), after: JSON.stringify(cp.br) });
406
+ }
407
+ }
408
+
409
+ // Text diff
410
+ if (baseline.text !== current.text) {
411
+ changes.push({ path, type: "text", before: baseline.text, after: current.text });
412
+ }
413
+
414
+ // Children diff
415
+ const bch = baseline.ch ?? [];
416
+ const cch = current.ch ?? [];
417
+ const maxLen = Math.max(bch.length, cch.length);
418
+ for (let i = 0; i < maxLen; i++) {
419
+ const childPath = `${path} > ${(cch[i] ?? bch[i])?.tag ?? "?"}[${i}]`;
420
+ if (i >= bch.length) {
421
+ changes.push({ path: childPath, type: "added" });
422
+ } else if (i >= cch.length) {
423
+ changes.push({ path: childPath, type: "removed" });
424
+ } else {
425
+ changes.push(...diffPaintTrees(bch[i], cch[i], childPath));
426
+ }
427
+ }
428
+
429
+ return changes;
430
+ }
431
+
432
+ // ---- Utility ----
433
+
434
+ /** Check if crater server is running */
435
+ export async function isCraterAvailable(url = DEFAULT_BIDI_URL): Promise<boolean> {
436
+ try {
437
+ const httpUrl = url.replace("ws://", "http://");
438
+ const resp = await fetch(httpUrl, { signal: AbortSignal.timeout(2000) });
439
+ return resp.ok || resp.status === 426; // 426 = upgrade required (WebSocket)
440
+ } catch {
441
+ return false;
442
+ }
443
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Capture-level detection result shared across capture backends
3
+ * (Playwright, Crater BiDi) and downstream detection classifiers.
4
+ */
5
+
6
+ export interface ViewportDetectionResult {
7
+ width: number;
8
+ height: number;
9
+ visualDiffDetected: boolean;
10
+ visualDiffRatio: number;
11
+ a11yDiffDetected: boolean;
12
+ a11yChangeCount: number;
13
+ computedStyleDiffCount: number;
14
+ hoverDiffDetected: boolean;
15
+ paintTreeDiffCount: number;
16
+ }
package/src/index.ts ADDED
@@ -0,0 +1,86 @@
1
+ /**
2
+ * @mizchi/vlmkit-capture — Playwright + Crater capture infrastructure
3
+ *
4
+ * The barrel re-exports the lightweight modules. `capturer.ts`
5
+ * (Playwright bootstrap) imports Playwright at module top-level and is
6
+ * intentionally NOT in the barrel — deep-import when you need it.
7
+ */
8
+
9
+ // ---- Capture config (vrt.config.json + route resolution) ----
10
+ export {
11
+ parseCaptureConfig,
12
+ resolveCaptureRoutes,
13
+ loadCaptureConfigFromFile,
14
+ captureConfigDir,
15
+ routeNameFromPath,
16
+ DEFAULT_CAPTURE_BASE_URL,
17
+ DEFAULT_CAPTURE_ROUTES,
18
+ DEFAULT_CAPTURE_CONFIG_FILE,
19
+ type CaptureRoute,
20
+ type CaptureConfig,
21
+ type CaptureRouteSet,
22
+ type LoadCaptureConfigOptions,
23
+ } from "./capture-config.ts";
24
+
25
+ // ---- Viewport / breakpoint discovery ----
26
+ export {
27
+ discoverViewports,
28
+ generateViewports,
29
+ extractBreakpoints,
30
+ extractBreakpointsFromHtml,
31
+ extractResponsiveBreakpointsFromHtml,
32
+ toResponsiveBreakpoints,
33
+ mergeResponsiveBreakpoints,
34
+ type Breakpoint,
35
+ type ResponsiveBreakpoint,
36
+ type ViewportSpec,
37
+ type ViewportOptions,
38
+ type DiscoveryResult,
39
+ } from "./viewport-discovery.ts";
40
+
41
+ // ---- Playwright launch diagnostics ----
42
+ export {
43
+ isPlaywrightSandboxRestrictionError,
44
+ formatPlaywrightLaunchError,
45
+ } from "./playwright-launch-error.ts";
46
+
47
+ // ---- Playwright report analyzer ----
48
+ export {
49
+ analyzeReport,
50
+ collectScreenshots,
51
+ formatStats,
52
+ type AnalyzedReport,
53
+ type FailedTest,
54
+ type ReportStats,
55
+ } from "./playwright-analyzer.ts";
56
+
57
+ // ---- Prescanner (signal aggregator) ----
58
+ export {
59
+ hasAnyDetectionSignal,
60
+ hasCraterPrescanSignal,
61
+ resolvePrescannerTrial,
62
+ summarizePrescannerTrials,
63
+ type PrescannerResolvedBy,
64
+ type PrescannerTrialResolution,
65
+ type PrescannerTrialSummary,
66
+ } from "./prescanner.ts";
67
+
68
+ // ---- Crater client (Bidi protocol) ----
69
+ export {
70
+ CraterClient,
71
+ DEFAULT_BIDI_URL,
72
+ type CraterResponsiveBreakpoint,
73
+ type CraterBreakpointDiscoveryDiagnostics,
74
+ type CraterRuleViewportMapEntry,
75
+ type CraterRuleViewportMap,
76
+ type CraterComputedStyleWithState,
77
+ type CraterBatchRenderResult,
78
+ type CraterBreakpointDiscoveryResult,
79
+ type PaintNode,
80
+ type PaintProps,
81
+ } from "./crater-client.ts";
82
+ export { isCraterAvailable } from "./crater-client.ts";
83
+
84
+ // ---- Detection / paint-tree types ----
85
+ export * from "./detection-types.ts";
86
+ export { diffPaintTrees } from "./crater-client.ts";