@mizchi/vlmkit-capture 0.6.0 → 0.8.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.
- package/package.json +3 -3
- package/src/batch-prescan.ts +115 -0
- package/src/cloudflare-quick-actions.ts +304 -0
- package/src/crater-client.ts +100 -6
- package/src/crater-smoke.ts +336 -0
- package/src/crater-wasm.ts +260 -0
- package/src/detection-types.ts +7 -0
- package/src/index.ts +71 -0
- package/src/prescanner.ts +56 -2
- package/src/viewport-discovery.ts +205 -17
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mizchi/vlmkit-capture",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Playwright + Crater capture infrastructure for VRT — viewport discovery, multi-route capture, prescanner.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "mizchi",
|
|
@@ -25,10 +25,10 @@
|
|
|
25
25
|
"./*.ts": "./src/*.ts"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"playwright": "^1.
|
|
28
|
+
"playwright": "^1.61.1",
|
|
29
29
|
"pngjs": "^7.0.0",
|
|
30
30
|
"ws": "^8.20.0",
|
|
31
|
-
"@mizchi/vlmkit-core": "0.
|
|
31
|
+
"@mizchi/vlmkit-core": "0.8.0"
|
|
32
32
|
},
|
|
33
33
|
"scripts": {
|
|
34
34
|
"test": "node --test 'src/**/*.test.ts'"
|
|
@@ -0,0 +1,115 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
export type CloudflareQuickAction = "screenshot" | "crawl";
|
|
2
|
+
|
|
3
|
+
export interface CloudflareQuickActionsConfig {
|
|
4
|
+
accountId: string;
|
|
5
|
+
apiToken: string;
|
|
6
|
+
apiBase?: string;
|
|
7
|
+
fetch?: typeof fetch;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface CloudflareQuickActionsEnv {
|
|
11
|
+
CLOUDFLARE_ACCOUNT_ID?: string;
|
|
12
|
+
CLOUDFLARE_API_TOKEN?: string;
|
|
13
|
+
CLOUDFLARE_BROWSER_RENDERING_API_BASE?: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface CloudflareQuickActionEndpointInput {
|
|
17
|
+
accountId: string;
|
|
18
|
+
action: CloudflareQuickAction;
|
|
19
|
+
jobId?: string;
|
|
20
|
+
apiBase?: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface CloudflareScreenshotRequest {
|
|
24
|
+
url?: string;
|
|
25
|
+
html?: string;
|
|
26
|
+
viewport?: {
|
|
27
|
+
width: number;
|
|
28
|
+
height: number;
|
|
29
|
+
deviceScaleFactor?: number;
|
|
30
|
+
};
|
|
31
|
+
screenshotOptions?: {
|
|
32
|
+
fullPage?: boolean;
|
|
33
|
+
omitBackground?: boolean;
|
|
34
|
+
type?: "png" | "jpeg" | "webp";
|
|
35
|
+
quality?: number;
|
|
36
|
+
clip?: {
|
|
37
|
+
x: number;
|
|
38
|
+
y: number;
|
|
39
|
+
width: number;
|
|
40
|
+
height: number;
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
selector?: string;
|
|
44
|
+
gotoOptions?: Record<string, unknown>;
|
|
45
|
+
authenticate?: Record<string, unknown>;
|
|
46
|
+
cookies?: unknown[];
|
|
47
|
+
setExtraHTTPHeaders?: Record<string, string>;
|
|
48
|
+
addScriptTag?: Array<Record<string, unknown>>;
|
|
49
|
+
addStyleTag?: Array<Record<string, unknown>>;
|
|
50
|
+
userAgent?: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface CloudflareScreenshotResult {
|
|
54
|
+
bytes: ArrayBuffer;
|
|
55
|
+
contentType: string;
|
|
56
|
+
browserMsUsed?: number;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface CloudflareCrawlRequest {
|
|
60
|
+
url: string;
|
|
61
|
+
limit?: number;
|
|
62
|
+
depth?: number;
|
|
63
|
+
formats?: Array<"html" | "markdown" | "json">;
|
|
64
|
+
render?: boolean;
|
|
65
|
+
maxAge?: number;
|
|
66
|
+
options?: {
|
|
67
|
+
includePatterns?: string[];
|
|
68
|
+
excludePatterns?: string[];
|
|
69
|
+
includeExternalLinks?: boolean;
|
|
70
|
+
includeSubdomains?: boolean;
|
|
71
|
+
};
|
|
72
|
+
gotoOptions?: Record<string, unknown>;
|
|
73
|
+
authenticate?: Record<string, unknown>;
|
|
74
|
+
cookies?: unknown[];
|
|
75
|
+
setExtraHTTPHeaders?: Record<string, string>;
|
|
76
|
+
rejectResourceTypes?: string[];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface CloudflareCrawlStartResult {
|
|
80
|
+
jobId: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export type CloudflareCrawlRecordStatus =
|
|
84
|
+
| "queued"
|
|
85
|
+
| "errored"
|
|
86
|
+
| "completed"
|
|
87
|
+
| "disallowed"
|
|
88
|
+
| "skipped"
|
|
89
|
+
| "cancelled";
|
|
90
|
+
|
|
91
|
+
export interface CloudflareCrawlRecord {
|
|
92
|
+
url: string;
|
|
93
|
+
status: CloudflareCrawlRecordStatus;
|
|
94
|
+
metadata?: {
|
|
95
|
+
status?: number;
|
|
96
|
+
url?: string;
|
|
97
|
+
title?: string;
|
|
98
|
+
};
|
|
99
|
+
html?: string;
|
|
100
|
+
markdown?: string;
|
|
101
|
+
json?: unknown;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export interface CloudflareCrawlResult {
|
|
105
|
+
id: string;
|
|
106
|
+
status: string;
|
|
107
|
+
browserSecondsUsed?: number;
|
|
108
|
+
total?: number;
|
|
109
|
+
finished?: number;
|
|
110
|
+
records: CloudflareCrawlRecord[];
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export interface CloudflareCrawlRoute {
|
|
114
|
+
url: string;
|
|
115
|
+
path: string;
|
|
116
|
+
title?: string;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface ExtractCloudflareCrawlRoutesOptions {
|
|
120
|
+
baseUrl?: string;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function buildCloudflareQuickActionEndpoint(input: CloudflareQuickActionEndpointInput): string {
|
|
124
|
+
const apiBase = (input.apiBase ?? "https://api.cloudflare.com/client/v4").replace(/\/$/u, "");
|
|
125
|
+
const account = encodeURIComponent(input.accountId);
|
|
126
|
+
const action = input.action;
|
|
127
|
+
const base = `${apiBase}/accounts/${account}/browser-rendering/${action}`;
|
|
128
|
+
return input.jobId ? `${base}/${encodeURIComponent(input.jobId)}` : base;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function resolveCloudflareQuickActionsConfig(
|
|
132
|
+
env: CloudflareQuickActionsEnv = process.env,
|
|
133
|
+
): CloudflareQuickActionsConfig {
|
|
134
|
+
const accountId = env.CLOUDFLARE_ACCOUNT_ID?.trim();
|
|
135
|
+
if (!accountId) {
|
|
136
|
+
throw new Error("CLOUDFLARE_ACCOUNT_ID is required for Cloudflare Quick Actions");
|
|
137
|
+
}
|
|
138
|
+
const apiToken = env.CLOUDFLARE_API_TOKEN?.trim();
|
|
139
|
+
if (!apiToken) {
|
|
140
|
+
throw new Error("CLOUDFLARE_API_TOKEN is required for Cloudflare Quick Actions");
|
|
141
|
+
}
|
|
142
|
+
return {
|
|
143
|
+
accountId,
|
|
144
|
+
apiToken,
|
|
145
|
+
apiBase: env.CLOUDFLARE_BROWSER_RENDERING_API_BASE?.trim() || undefined,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function createCloudflareQuickActionsClient(config: CloudflareQuickActionsConfig) {
|
|
150
|
+
const fetchImpl = config.fetch ?? fetch;
|
|
151
|
+
const headers = {
|
|
152
|
+
Authorization: `Bearer ${config.apiToken}`,
|
|
153
|
+
"Content-Type": "application/json",
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
async function post(action: CloudflareQuickAction, body: unknown): Promise<Response> {
|
|
157
|
+
const response = await fetchImpl(buildCloudflareQuickActionEndpoint({
|
|
158
|
+
accountId: config.accountId,
|
|
159
|
+
action,
|
|
160
|
+
apiBase: config.apiBase,
|
|
161
|
+
}), {
|
|
162
|
+
method: "POST",
|
|
163
|
+
headers,
|
|
164
|
+
body: JSON.stringify(body),
|
|
165
|
+
});
|
|
166
|
+
if (!response.ok) {
|
|
167
|
+
throw new Error(`Cloudflare ${action} failed: ${response.status} ${await response.text()}`);
|
|
168
|
+
}
|
|
169
|
+
return response;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return {
|
|
173
|
+
async screenshot(input: CloudflareScreenshotRequest): Promise<CloudflareScreenshotResult> {
|
|
174
|
+
if (!input.url && !input.html) {
|
|
175
|
+
throw new Error("Cloudflare screenshot requires url or html");
|
|
176
|
+
}
|
|
177
|
+
const response = await post("screenshot", input);
|
|
178
|
+
const browserMsHeader = response.headers.get("x-browser-ms-used");
|
|
179
|
+
return {
|
|
180
|
+
bytes: await response.arrayBuffer(),
|
|
181
|
+
contentType: response.headers.get("content-type") ?? "image/png",
|
|
182
|
+
browserMsUsed: browserMsHeader ? Number(browserMsHeader) : undefined,
|
|
183
|
+
};
|
|
184
|
+
},
|
|
185
|
+
|
|
186
|
+
async startCrawl(input: CloudflareCrawlRequest): Promise<CloudflareCrawlStartResult> {
|
|
187
|
+
const response = await post("crawl", input);
|
|
188
|
+
const parsed = await response.json() as unknown;
|
|
189
|
+
return {
|
|
190
|
+
jobId: normalizeCrawlJobId(parsed),
|
|
191
|
+
};
|
|
192
|
+
},
|
|
193
|
+
|
|
194
|
+
async getCrawlResult(jobId: string): Promise<CloudflareCrawlResult> {
|
|
195
|
+
const response = await fetchImpl(buildCloudflareQuickActionEndpoint({
|
|
196
|
+
accountId: config.accountId,
|
|
197
|
+
action: "crawl",
|
|
198
|
+
jobId,
|
|
199
|
+
apiBase: config.apiBase,
|
|
200
|
+
}), {
|
|
201
|
+
method: "GET",
|
|
202
|
+
headers: { Authorization: `Bearer ${config.apiToken}` },
|
|
203
|
+
});
|
|
204
|
+
if (!response.ok) {
|
|
205
|
+
throw new Error(`Cloudflare crawl result failed: ${response.status} ${await response.text()}`);
|
|
206
|
+
}
|
|
207
|
+
const parsed = await response.json() as unknown;
|
|
208
|
+
return normalizeCrawlResult(parsed);
|
|
209
|
+
},
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export function extractCloudflareCrawlRoutes(
|
|
214
|
+
result: CloudflareCrawlResult,
|
|
215
|
+
options: ExtractCloudflareCrawlRoutesOptions = {},
|
|
216
|
+
): CloudflareCrawlRoute[] {
|
|
217
|
+
const base = options.baseUrl ? new URL(options.baseUrl) : undefined;
|
|
218
|
+
const seen = new Set<string>();
|
|
219
|
+
const routes: CloudflareCrawlRoute[] = [];
|
|
220
|
+
for (const record of result.records) {
|
|
221
|
+
if (record.status !== "completed") continue;
|
|
222
|
+
const rawUrl = record.metadata?.url ?? record.url;
|
|
223
|
+
let parsed: URL;
|
|
224
|
+
try {
|
|
225
|
+
parsed = new URL(rawUrl);
|
|
226
|
+
} catch {
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
if (base && parsed.origin !== base.origin) continue;
|
|
230
|
+
const path = parsed.pathname + parsed.search;
|
|
231
|
+
if (seen.has(path)) continue;
|
|
232
|
+
seen.add(path);
|
|
233
|
+
const route: CloudflareCrawlRoute = {
|
|
234
|
+
url: rawUrl,
|
|
235
|
+
path,
|
|
236
|
+
};
|
|
237
|
+
if (record.metadata?.title) route.title = record.metadata.title;
|
|
238
|
+
routes.push(route);
|
|
239
|
+
}
|
|
240
|
+
return routes;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function normalizeCrawlJobId(parsed: unknown): string {
|
|
244
|
+
if (typeof parsed === "string") return parsed;
|
|
245
|
+
if (isRecord(parsed)) {
|
|
246
|
+
if (typeof parsed.result === "string") return parsed.result;
|
|
247
|
+
if (isRecord(parsed.result) && typeof parsed.result.id === "string") return parsed.result.id;
|
|
248
|
+
if (typeof parsed.id === "string") return parsed.id;
|
|
249
|
+
}
|
|
250
|
+
throw new Error("Cloudflare crawl response did not include a job id");
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function normalizeCrawlResult(parsed: unknown): CloudflareCrawlResult {
|
|
254
|
+
const value = isRecord(parsed) && isRecord(parsed.result) ? parsed.result : parsed;
|
|
255
|
+
if (!isRecord(value)) {
|
|
256
|
+
throw new Error("Cloudflare crawl result must be an object");
|
|
257
|
+
}
|
|
258
|
+
return {
|
|
259
|
+
id: readString(value, "id"),
|
|
260
|
+
status: readString(value, "status"),
|
|
261
|
+
browserSecondsUsed: readNumber(value, "browserSecondsUsed"),
|
|
262
|
+
total: readNumber(value, "total"),
|
|
263
|
+
finished: readNumber(value, "finished"),
|
|
264
|
+
records: Array.isArray(value.records)
|
|
265
|
+
? value.records.filter(isRecord).map(normalizeCrawlRecord)
|
|
266
|
+
: [],
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function normalizeCrawlRecord(value: Record<string, unknown>): CloudflareCrawlRecord {
|
|
271
|
+
return {
|
|
272
|
+
url: readString(value, "url"),
|
|
273
|
+
status: readString(value, "status") as CloudflareCrawlRecordStatus,
|
|
274
|
+
metadata: isRecord(value.metadata)
|
|
275
|
+
? {
|
|
276
|
+
status: readNumber(value.metadata, "status"),
|
|
277
|
+
url: readOptionalString(value.metadata, "url"),
|
|
278
|
+
title: readOptionalString(value.metadata, "title"),
|
|
279
|
+
}
|
|
280
|
+
: undefined,
|
|
281
|
+
html: readOptionalString(value, "html"),
|
|
282
|
+
markdown: readOptionalString(value, "markdown"),
|
|
283
|
+
json: value.json,
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
288
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function readString(record: Record<string, unknown>, key: string): string {
|
|
292
|
+
const value = record[key];
|
|
293
|
+
return typeof value === "string" ? value : "";
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function readOptionalString(record: Record<string, unknown>, key: string): string | undefined {
|
|
297
|
+
const value = record[key];
|
|
298
|
+
return typeof value === "string" ? value : undefined;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function readNumber(record: Record<string, unknown>, key: string): number | undefined {
|
|
302
|
+
const value = record[key];
|
|
303
|
+
return typeof value === "number" ? value : undefined;
|
|
304
|
+
}
|
package/src/crater-client.ts
CHANGED
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import WebSocket from "ws";
|
|
12
12
|
import { PNG } from "pngjs";
|
|
13
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
14
|
+
import { resolve } from "node:path";
|
|
13
15
|
import {
|
|
14
16
|
buildComputedStyleCaptureJsonExpression,
|
|
15
17
|
computedStyleSnapshotToMap,
|
|
@@ -18,6 +20,55 @@ import {
|
|
|
18
20
|
} from "@mizchi/vlmkit-core/computed-style-capture.ts";
|
|
19
21
|
|
|
20
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
|
+
}
|
|
21
72
|
|
|
22
73
|
export interface CraterResponsiveBreakpoint {
|
|
23
74
|
axis: "width";
|
|
@@ -55,12 +106,25 @@ export interface CraterComputedStyleWithState {
|
|
|
55
106
|
diff: Array<{ property: string; normal: string; forced: string }>;
|
|
56
107
|
}
|
|
57
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
|
+
|
|
58
124
|
export interface CraterBatchRenderResult {
|
|
59
125
|
results: Array<{
|
|
60
126
|
id: string;
|
|
61
|
-
|
|
62
|
-
width?: number;
|
|
63
|
-
height?: number;
|
|
127
|
+
paintTree?: PaintNode | null;
|
|
64
128
|
}>;
|
|
65
129
|
}
|
|
66
130
|
|
|
@@ -89,7 +153,7 @@ export class CraterClient {
|
|
|
89
153
|
private contextId: string | null = null;
|
|
90
154
|
private url: string;
|
|
91
155
|
|
|
92
|
-
constructor(url =
|
|
156
|
+
constructor(url = resolveCraterBidiUrl()) {
|
|
93
157
|
this.url = url;
|
|
94
158
|
}
|
|
95
159
|
|
|
@@ -196,6 +260,9 @@ export class CraterClient {
|
|
|
196
260
|
async captureComputedStyles(
|
|
197
261
|
properties: string[],
|
|
198
262
|
): Promise<Map<string, Record<string, string>>> {
|
|
263
|
+
const nativeSnapshot = await this.captureNativeComputedStyles(properties);
|
|
264
|
+
if (nativeSnapshot) return nativeSnapshot;
|
|
265
|
+
|
|
199
266
|
const rawSnapshot = await this.evaluate<unknown>(
|
|
200
267
|
buildComputedStyleCaptureJsonExpression(properties),
|
|
201
268
|
);
|
|
@@ -206,6 +273,33 @@ export class CraterClient {
|
|
|
206
273
|
return computedStyleSnapshotToMap(snapshot);
|
|
207
274
|
}
|
|
208
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
|
+
|
|
209
303
|
async getResponsiveBreakpoints(
|
|
210
304
|
options: {
|
|
211
305
|
mode?: "live-inline" | "html-inline";
|
|
@@ -268,7 +362,7 @@ export class CraterClient {
|
|
|
268
362
|
async batchRender(
|
|
269
363
|
baseHtml: string,
|
|
270
364
|
viewport: { width: number; height: number },
|
|
271
|
-
variants:
|
|
365
|
+
variants: CraterRenderVariant[],
|
|
272
366
|
): Promise<CraterBatchRenderResult> {
|
|
273
367
|
const resp = await this.sendBidi("browsingContext.batchRender", {
|
|
274
368
|
context: this.requireContextId(),
|
|
@@ -432,7 +526,7 @@ export function diffPaintTrees(baseline: PaintNode, current: PaintNode, path = "
|
|
|
432
526
|
// ---- Utility ----
|
|
433
527
|
|
|
434
528
|
/** Check if crater server is running */
|
|
435
|
-
export async function isCraterAvailable(url =
|
|
529
|
+
export async function isCraterAvailable(url = resolveCraterBidiUrl()): Promise<boolean> {
|
|
436
530
|
try {
|
|
437
531
|
const httpUrl = url.replace("ws://", "http://");
|
|
438
532
|
const resp = await fetch(httpUrl, { signal: AbortSignal.timeout(2000) });
|