@mizchi/vlmkit-capture 0.8.0 → 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.
Files changed (40) hide show
  1. package/README.md +1 -1
  2. package/dist/batch-prescan.d.mts +51 -0
  3. package/dist/batch-prescan.mjs +66 -0
  4. package/dist/capture-config.d.mts +50 -0
  5. package/dist/capture-config.mjs +164 -0
  6. package/dist/capturer.d.mts +45 -0
  7. package/dist/capturer.mjs +94 -0
  8. package/dist/cloudflare-quick-actions.d.mts +114 -0
  9. package/dist/cloudflare-quick-actions.mjs +142 -0
  10. package/dist/crater-client.d.mts +159 -0
  11. package/dist/crater-client.mjs +362 -0
  12. package/dist/crater-smoke.d.mts +98 -0
  13. package/dist/crater-smoke.mjs +269 -0
  14. package/dist/crater-wasm.d.mts +65 -0
  15. package/dist/crater-wasm.mjs +132 -0
  16. package/{src/detection-types.ts → dist/detection-types.d.mts} +4 -2
  17. package/dist/detection-types.mjs +1 -0
  18. package/dist/index.d.mts +12 -0
  19. package/dist/index.mjs +11 -0
  20. package/dist/playwright-analyzer.d.mts +38 -0
  21. package/dist/playwright-analyzer.mjs +117 -0
  22. package/dist/playwright-launch-error.d.mts +7 -0
  23. package/dist/playwright-launch-error.mjs +25 -0
  24. package/dist/prescanner.d.mts +39 -0
  25. package/dist/prescanner.mjs +61 -0
  26. package/dist/viewport-discovery.d.mts +114 -0
  27. package/dist/viewport-discovery.mjs +294 -0
  28. package/package.json +18 -6
  29. package/src/batch-prescan.ts +0 -115
  30. package/src/capture-config.ts +0 -219
  31. package/src/capturer.ts +0 -138
  32. package/src/cloudflare-quick-actions.ts +0 -304
  33. package/src/crater-client.ts +0 -537
  34. package/src/crater-smoke.ts +0 -336
  35. package/src/crater-wasm.ts +0 -260
  36. package/src/index.ts +0 -157
  37. package/src/playwright-analyzer.ts +0 -180
  38. package/src/playwright-launch-error.ts +0 -41
  39. package/src/prescanner.ts +0 -123
  40. package/src/viewport-discovery.ts +0 -455
@@ -1,537 +0,0 @@
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 { existsSync, readFileSync } from "node:fs";
14
- import { resolve } from "node:path";
15
- import {
16
- buildComputedStyleCaptureJsonExpression,
17
- computedStyleSnapshotToMap,
18
- hasMeaningfulComputedStyleSnapshot,
19
- parseComputedStyleSnapshot,
20
- } from "@mizchi/vlmkit-core/computed-style-capture.ts";
21
-
22
- export const DEFAULT_BIDI_URL = "ws://127.0.0.1:9222";
23
- export const VLMKIT_CRATER_BIDI_URL_ENV = "VLMKIT_CRATER_BIDI_URL";
24
- export const CRATER_BIDI_URL_ENV = "CRATER_BIDI_URL";
25
- export const VLMKIT_CRATER_ROOT_ENV = "VLMKIT_CRATER_ROOT";
26
- export const CRATER_ROOT_ENV = "CRATER_ROOT";
27
-
28
- export interface ResolveCraterBidiUrlOptions {
29
- env?: Partial<Record<
30
- | typeof VLMKIT_CRATER_BIDI_URL_ENV
31
- | typeof CRATER_BIDI_URL_ENV
32
- | typeof VLMKIT_CRATER_ROOT_ENV
33
- | typeof CRATER_ROOT_ENV,
34
- string | undefined
35
- >>;
36
- craterRoot?: string;
37
- urlFile?: string;
38
- }
39
-
40
- export function resolveCraterBidiUrl(
41
- options: ResolveCraterBidiUrlOptions = {},
42
- ): string {
43
- const env = options.env ?? process.env;
44
- const fromEnv = env[VLMKIT_CRATER_BIDI_URL_ENV] ?? env[CRATER_BIDI_URL_ENV];
45
- if (fromEnv?.trim()) return fromEnv.trim();
46
-
47
- const fileCandidates = [
48
- options.urlFile,
49
- resolveCraterBidiUrlFile(
50
- options.craterRoot
51
- ?? env[VLMKIT_CRATER_ROOT_ENV]
52
- ?? env[CRATER_ROOT_ENV],
53
- ),
54
- ].filter((candidate): candidate is string => Boolean(candidate));
55
-
56
- for (const candidate of fileCandidates) {
57
- try {
58
- if (!existsSync(candidate)) continue;
59
- const value = readFileSync(candidate, "utf-8").trim();
60
- if (value) return value;
61
- } catch {
62
- // Ignore stale or unreadable helper files and fall back to the root URL.
63
- }
64
- }
65
-
66
- return DEFAULT_BIDI_URL;
67
- }
68
-
69
- function resolveCraterBidiUrlFile(craterRoot: string | undefined): string | undefined {
70
- return craterRoot?.trim() ? resolve(craterRoot, ".bidi-ws-url") : undefined;
71
- }
72
-
73
- export interface CraterResponsiveBreakpoint {
74
- axis: "width";
75
- op: "ge" | "gt" | "le" | "lt";
76
- valuePx: number;
77
- raw: string;
78
- normalized: string;
79
- guards: string[];
80
- ruleCount: number;
81
- }
82
-
83
- export interface CraterBreakpointDiscoveryDiagnostics {
84
- stylesheetCount: number;
85
- ruleCount: number;
86
- externalStylesheetLinks: string[];
87
- ignoredQueries: string[];
88
- unsupportedQueries: string[];
89
- }
90
-
91
- export interface CraterRuleViewportMapEntry {
92
- selector: string;
93
- properties: string[];
94
- mediaCondition: string;
95
- activeAtWidths: number[];
96
- inactiveAtWidths: number[];
97
- }
98
-
99
- export interface CraterRuleViewportMap {
100
- rules: CraterRuleViewportMapEntry[];
101
- }
102
-
103
- export interface CraterComputedStyleWithState {
104
- normal: Record<string, string>;
105
- forced: Record<string, string>;
106
- diff: Array<{ property: string; normal: string; forced: string }>;
107
- }
108
-
109
- type ComputedStyleRecord = Record<string, Record<string, string>>;
110
-
111
- export type CraterCssMutationAction = "remove" | { override: string };
112
-
113
- export interface CraterCssMutation {
114
- selector: string;
115
- property: string;
116
- action?: CraterCssMutationAction;
117
- }
118
-
119
- export interface CraterRenderVariant {
120
- id: string;
121
- mutations: CraterCssMutation[];
122
- }
123
-
124
- export interface CraterBatchRenderResult {
125
- results: Array<{
126
- id: string;
127
- paintTree?: PaintNode | null;
128
- }>;
129
- }
130
-
131
- export interface CraterBreakpointDiscoveryResult {
132
- breakpoints: CraterResponsiveBreakpoint[];
133
- diagnostics?: CraterBreakpointDiscoveryDiagnostics;
134
- }
135
-
136
- interface BidiResponse {
137
- id: number;
138
- type: "success" | "error";
139
- result?: unknown;
140
- error?: string;
141
- message?: string;
142
- }
143
-
144
- type PendingCommand = {
145
- resolve: (value: BidiResponse) => void;
146
- reject: (error: Error) => void;
147
- };
148
-
149
- export class CraterClient {
150
- private ws: WebSocket | null = null;
151
- private commandId = 0;
152
- private pendingCommands = new Map<number, PendingCommand>();
153
- private contextId: string | null = null;
154
- private url: string;
155
-
156
- constructor(url = resolveCraterBidiUrl()) {
157
- this.url = url;
158
- }
159
-
160
- async connect(): Promise<void> {
161
- await new Promise<void>((resolve, reject) => {
162
- this.ws = new WebSocket(this.url);
163
- this.ws.on("open", async () => {
164
- try {
165
- const resp = await this.sendBidi("browsingContext.create", { type: "tab" });
166
- this.contextId = (resp.result as { context: string }).context;
167
- resolve();
168
- } catch (error) {
169
- reject(error);
170
- }
171
- });
172
- this.ws.on("error", (error) => reject(error));
173
- this.ws.on("message", (data) => this.handleMessage(data.toString()));
174
- });
175
- }
176
-
177
- async close(): Promise<void> {
178
- if (this.contextId) {
179
- try {
180
- await this.sendBidi("browsingContext.close", { context: this.contextId });
181
- } catch (e) { console.warn("[crater] close context failed:", e instanceof Error ? e.message : e); }
182
- }
183
- this.contextId = null;
184
- this.ws?.close();
185
- this.ws = null;
186
- }
187
-
188
- async setViewport(width: number, height: number): Promise<void> {
189
- await this.sendBidi("browsingContext.setViewport", {
190
- context: this.requireContextId(),
191
- viewport: { width, height },
192
- });
193
- }
194
-
195
- async setContent(html: string): Promise<void> {
196
- const dataUrl = `data:text/html;base64,${Buffer.from(html).toString("base64")}`;
197
- await this.sendBidi("browsingContext.navigate", {
198
- context: this.requireContextId(),
199
- url: dataUrl,
200
- wait: "complete",
201
- });
202
- await this.evaluate(`__loadHTML(${JSON.stringify(html)})`);
203
- await this.evaluate(`(async () => await __executeScripts())()`, true);
204
- }
205
-
206
- async evaluate<T>(expression: string, awaitPromise = false): Promise<T> {
207
- const resp = await this.sendBidi("script.evaluate", {
208
- expression,
209
- target: { context: this.requireContextId() },
210
- awaitPromise: awaitPromise || expression.includes("await ") || expression.includes("new Promise"),
211
- });
212
- if (resp.type === "error") {
213
- throw new Error(resp.message || resp.error || "script.evaluate failed");
214
- }
215
- const result = resp.result as { result?: { value?: T }; exceptionDetails?: unknown };
216
- if (result.exceptionDetails) {
217
- throw new Error(JSON.stringify(result.exceptionDetails));
218
- }
219
- return result.result?.value as T;
220
- }
221
-
222
- /** PNG screenshot (Buffer) */
223
- async captureScreenshot(): Promise<Buffer> {
224
- const resp = await this.sendBidi("browsingContext.captureScreenshotData", {
225
- context: this.requireContextId(),
226
- origin: "viewport",
227
- });
228
- if (resp.type === "error") {
229
- throw new Error(resp.message || resp.error || "captureScreenshotData failed");
230
- }
231
- return Buffer.from(String(resp.result || ""), "base64");
232
- }
233
-
234
- /** Raw RGBA data (pixelmatch compatible) */
235
- async capturePaintData(): Promise<{ width: number; height: number; data: Uint8Array }> {
236
- const resp = await this.sendBidi("browsingContext.capturePaintData", {
237
- context: this.requireContextId(),
238
- origin: "viewport",
239
- }, 120_000);
240
- if (resp.type === "error") {
241
- throw new Error(resp.message || resp.error || "capturePaintData failed");
242
- }
243
- const result = resp.result as { width?: number; height?: number; data?: string };
244
- return {
245
- width: Number(result.width ?? 0),
246
- height: Number(result.height ?? 0),
247
- data: Uint8Array.from(Buffer.from(String(result.data || ""), "base64")),
248
- };
249
- }
250
-
251
- /** Raw RGBA -> PNG Buffer conversion */
252
- async capturePng(): Promise<{ png: Buffer; width: number; height: number }> {
253
- const { width, height, data } = await this.capturePaintData();
254
- const png = new PNG({ width, height });
255
- png.data = Buffer.from(data);
256
- const pngBuffer = PNG.sync.write(png);
257
- return { png: pngBuffer, width, height };
258
- }
259
-
260
- async captureComputedStyles(
261
- properties: string[],
262
- ): Promise<Map<string, Record<string, string>>> {
263
- const nativeSnapshot = await this.captureNativeComputedStyles(properties);
264
- if (nativeSnapshot) return nativeSnapshot;
265
-
266
- const rawSnapshot = await this.evaluate<unknown>(
267
- buildComputedStyleCaptureJsonExpression(properties),
268
- );
269
- const snapshot = parseComputedStyleSnapshot(rawSnapshot);
270
- if (!hasMeaningfulComputedStyleSnapshot(snapshot)) {
271
- return new Map();
272
- }
273
- return computedStyleSnapshotToMap(snapshot);
274
- }
275
-
276
- private async captureNativeComputedStyles(
277
- properties: string[],
278
- ): Promise<Map<string, Record<string, string>> | null> {
279
- let context: string;
280
- try {
281
- context = this.requireContextId();
282
- } catch {
283
- return null;
284
- }
285
-
286
- try {
287
- const resp = await this.sendBidi("browsingContext.getAllComputedStyles", {
288
- context,
289
- properties,
290
- }, 30_000);
291
- if (resp.type === "error") return null;
292
- const result = resp.result as { styles?: ComputedStyleRecord } | undefined;
293
- const snapshot = parseComputedStyleSnapshot(result?.styles ?? {});
294
- if (!hasMeaningfulComputedStyleSnapshot(snapshot)) {
295
- return new Map();
296
- }
297
- return computedStyleSnapshotToMap(snapshot);
298
- } catch {
299
- return null;
300
- }
301
- }
302
-
303
- async getResponsiveBreakpoints(
304
- options: {
305
- mode?: "live-inline" | "html-inline";
306
- axis?: "width";
307
- includeDiagnostics?: boolean;
308
- } = {},
309
- ): Promise<CraterBreakpointDiscoveryResult> {
310
- const resp = await this.sendBidi("browsingContext.getResponsiveBreakpoints", {
311
- context: this.requireContextId(),
312
- mode: options.mode ?? "live-inline",
313
- axis: options.axis ?? "width",
314
- includeDiagnostics: options.includeDiagnostics ?? true,
315
- }, 30_000);
316
- if (resp.type === "error") {
317
- throw new Error(resp.message || resp.error || "getResponsiveBreakpoints failed");
318
- }
319
- const result = resp.result as CraterBreakpointDiscoveryResult | undefined;
320
- return {
321
- breakpoints: result?.breakpoints ?? [],
322
- diagnostics: result?.diagnostics,
323
- };
324
- }
325
-
326
- /** CSS rule → viewport mapping (#33) */
327
- async getCssRuleViewportMap(viewportWidths?: number[]): Promise<CraterRuleViewportMap> {
328
- const resp = await this.sendBidi("browsingContext.getCssRuleViewportMap", {
329
- context: this.requireContextId(),
330
- ...(viewportWidths ? { viewportWidths } : {}),
331
- }, 30_000);
332
- if (resp.type === "error") throw new Error(resp.message || resp.error || "getCssRuleViewportMap failed");
333
- return (resp.result as CraterRuleViewportMap) ?? { rules: [] };
334
- }
335
-
336
- /** Required test viewports (#33) */
337
- async getRequiredTestViewports(): Promise<{ viewports: Array<{ width: number; reason: string }> }> {
338
- const resp = await this.sendBidi("browsingContext.getRequiredTestViewports", {
339
- context: this.requireContextId(),
340
- }, 30_000);
341
- if (resp.type === "error") throw new Error(resp.message || resp.error || "getRequiredTestViewports failed");
342
- return (resp.result as { viewports: Array<{ width: number; reason: string }> }) ?? { viewports: [] };
343
- }
344
-
345
- /** Computed styles with forced pseudo-class state (#34) */
346
- async getComputedStylesWithState(
347
- selector: string,
348
- forcedStates: string[],
349
- properties: string[],
350
- ): Promise<CraterComputedStyleWithState> {
351
- const resp = await this.sendBidi("browsingContext.getComputedStylesWithState", {
352
- context: this.requireContextId(),
353
- selector,
354
- forcedStates,
355
- properties,
356
- }, 30_000);
357
- if (resp.type === "error") throw new Error(resp.message || resp.error || "getComputedStylesWithState failed");
358
- return (resp.result as CraterComputedStyleWithState) ?? { normal: {}, forced: {}, diff: [] };
359
- }
360
-
361
- /** Batch variant rendering (#28) */
362
- async batchRender(
363
- baseHtml: string,
364
- viewport: { width: number; height: number },
365
- variants: CraterRenderVariant[],
366
- ): Promise<CraterBatchRenderResult> {
367
- const resp = await this.sendBidi("browsingContext.batchRender", {
368
- context: this.requireContextId(),
369
- baseHtml,
370
- viewport,
371
- variants,
372
- }, 120_000);
373
- if (resp.type === "error") throw new Error(resp.message || resp.error || "batchRender failed");
374
- return (resp.result as CraterBatchRenderResult) ?? { results: [] };
375
- }
376
-
377
- // ---- Private ----
378
-
379
- private requireContextId(): string {
380
- if (!this.contextId) throw new Error("Not connected. Call connect() first.");
381
- return this.contextId;
382
- }
383
-
384
- private handleMessage(data: string): void {
385
- let msg: BidiResponse;
386
- try {
387
- msg = JSON.parse(data) as BidiResponse;
388
- } catch {
389
- console.warn("[crater] invalid JSON from BiDi:", data.slice(0, 200));
390
- return;
391
- }
392
- if (typeof msg.id !== "number") return;
393
- const pending = this.pendingCommands.get(msg.id);
394
- if (pending) {
395
- this.pendingCommands.delete(msg.id);
396
- pending.resolve(msg);
397
- }
398
- }
399
-
400
- private sendBidi(method: string, params: Record<string, unknown>, timeoutMs = 10_000): Promise<BidiResponse> {
401
- return new Promise((resolve, reject) => {
402
- const id = ++this.commandId;
403
- const timer = setTimeout(() => {
404
- this.pendingCommands.delete(id);
405
- reject(new Error(`BiDi command ${method} timed out after ${timeoutMs}ms`));
406
- }, timeoutMs);
407
-
408
- this.pendingCommands.set(id, {
409
- resolve: (resp) => { clearTimeout(timer); resolve(resp); },
410
- reject: (err) => { clearTimeout(timer); reject(err); },
411
- });
412
-
413
- this.ws?.send(JSON.stringify({ id, method, params }));
414
- });
415
- }
416
-
417
- /** Paint tree (render tree JSON) */
418
- async capturePaintTree(): Promise<PaintNode> {
419
- const resp = await this.sendBidi("browsingContext.capturePaintTree", {
420
- context: this.requireContextId(),
421
- }, 120_000);
422
- if (resp.type === "error") {
423
- throw new Error(resp.message || resp.error || "capturePaintTree failed");
424
- }
425
- const result = resp.result as { paintTree?: string };
426
- return JSON.parse(result.paintTree || "{}");
427
- }
428
- }
429
-
430
- // ---- Paint tree types & diff ----
431
-
432
- export interface PaintNode {
433
- id?: string;
434
- tag?: string;
435
- x: number;
436
- y: number;
437
- w: number;
438
- h: number;
439
- ox?: string;
440
- oy?: string;
441
- p?: PaintProps;
442
- text?: string;
443
- ch?: PaintNode[];
444
- }
445
-
446
- export interface PaintProps {
447
- op?: number; // opacity
448
- c?: number[]; // color [r,g,b,a]
449
- bg?: number[]; // background [r,g,b,a]
450
- fs?: number; // font-size
451
- ib?: boolean; // is-bold
452
- vis?: string; // visibility
453
- br?: number[]; // border-radius
454
- }
455
-
456
- export interface PaintTreeChange {
457
- path: string; // e.g. "body > div > div[0]"
458
- type: "geometry" | "paint" | "text" | "added" | "removed";
459
- property?: string;
460
- before?: string;
461
- after?: string;
462
- }
463
-
464
- /** Compare two paint trees and return the diff */
465
- export function diffPaintTrees(baseline: PaintNode, current: PaintNode, path = "root"): PaintTreeChange[] {
466
- const changes: PaintTreeChange[] = [];
467
-
468
- // Geometry diff
469
- if (baseline.x !== current.x || baseline.y !== current.y ||
470
- baseline.w !== current.w || baseline.h !== current.h) {
471
- changes.push({
472
- path, type: "geometry",
473
- property: "bounds",
474
- before: `${baseline.x},${baseline.y} ${baseline.w}x${baseline.h}`,
475
- after: `${current.x},${current.y} ${current.w}x${current.h}`,
476
- });
477
- }
478
-
479
- // Paint properties diff
480
- if (baseline.p && current.p) {
481
- const bp = baseline.p;
482
- const cp = current.p;
483
- if (bp.op !== cp.op) {
484
- changes.push({ path, type: "paint", property: "opacity", before: String(bp.op), after: String(cp.op) });
485
- }
486
- if (JSON.stringify(bp.c) !== JSON.stringify(cp.c)) {
487
- changes.push({ path, type: "paint", property: "color", before: JSON.stringify(bp.c), after: JSON.stringify(cp.c) });
488
- }
489
- if (JSON.stringify(bp.bg) !== JSON.stringify(cp.bg)) {
490
- changes.push({ path, type: "paint", property: "background", before: JSON.stringify(bp.bg), after: JSON.stringify(cp.bg) });
491
- }
492
- if (bp.fs !== cp.fs) {
493
- changes.push({ path, type: "paint", property: "font-size", before: String(bp.fs), after: String(cp.fs) });
494
- }
495
- if (bp.ib !== cp.ib) {
496
- changes.push({ path, type: "paint", property: "font-weight", before: String(bp.ib), after: String(cp.ib) });
497
- }
498
- if (JSON.stringify(bp.br) !== JSON.stringify(cp.br)) {
499
- changes.push({ path, type: "paint", property: "border-radius", before: JSON.stringify(bp.br), after: JSON.stringify(cp.br) });
500
- }
501
- }
502
-
503
- // Text diff
504
- if (baseline.text !== current.text) {
505
- changes.push({ path, type: "text", before: baseline.text, after: current.text });
506
- }
507
-
508
- // Children diff
509
- const bch = baseline.ch ?? [];
510
- const cch = current.ch ?? [];
511
- const maxLen = Math.max(bch.length, cch.length);
512
- for (let i = 0; i < maxLen; i++) {
513
- const childPath = `${path} > ${(cch[i] ?? bch[i])?.tag ?? "?"}[${i}]`;
514
- if (i >= bch.length) {
515
- changes.push({ path: childPath, type: "added" });
516
- } else if (i >= cch.length) {
517
- changes.push({ path: childPath, type: "removed" });
518
- } else {
519
- changes.push(...diffPaintTrees(bch[i], cch[i], childPath));
520
- }
521
- }
522
-
523
- return changes;
524
- }
525
-
526
- // ---- Utility ----
527
-
528
- /** Check if crater server is running */
529
- export async function isCraterAvailable(url = resolveCraterBidiUrl()): Promise<boolean> {
530
- try {
531
- const httpUrl = url.replace("ws://", "http://");
532
- const resp = await fetch(httpUrl, { signal: AbortSignal.timeout(2000) });
533
- return resp.ok || resp.status === 426; // 426 = upgrade required (WebSocket)
534
- } catch {
535
- return false;
536
- }
537
- }