@mizchi/vlmkit-capture 0.7.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.
- package/dist/batch-prescan.d.mts +51 -0
- package/dist/batch-prescan.mjs +66 -0
- package/dist/capture-config.d.mts +50 -0
- package/dist/capture-config.mjs +164 -0
- package/dist/capturer.d.mts +45 -0
- package/dist/capturer.mjs +94 -0
- package/dist/cloudflare-quick-actions.d.mts +114 -0
- package/dist/cloudflare-quick-actions.mjs +142 -0
- package/dist/crater-client.d.mts +159 -0
- package/dist/crater-client.mjs +362 -0
- package/dist/crater-smoke.d.mts +98 -0
- package/dist/crater-smoke.mjs +269 -0
- package/dist/crater-wasm.d.mts +65 -0
- package/dist/crater-wasm.mjs +132 -0
- package/{src/detection-types.ts → dist/detection-types.d.mts} +4 -2
- package/dist/detection-types.mjs +1 -0
- package/dist/index.d.mts +12 -0
- package/dist/index.mjs +11 -0
- package/dist/playwright-analyzer.d.mts +38 -0
- package/dist/playwright-analyzer.mjs +117 -0
- package/dist/playwright-launch-error.d.mts +7 -0
- package/dist/playwright-launch-error.mjs +25 -0
- package/dist/prescanner.d.mts +39 -0
- package/dist/prescanner.mjs +61 -0
- package/dist/viewport-discovery.d.mts +114 -0
- package/dist/viewport-discovery.mjs +294 -0
- package/package.json +18 -6
- package/src/batch-prescan.ts +0 -115
- package/src/capture-config.ts +0 -219
- package/src/capturer.ts +0 -138
- package/src/cloudflare-quick-actions.ts +0 -304
- package/src/crater-client.ts +0 -537
- package/src/crater-smoke.ts +0 -336
- package/src/crater-wasm.ts +0 -260
- package/src/index.ts +0 -157
- package/src/playwright-analyzer.ts +0 -180
- package/src/playwright-launch-error.ts +0 -41
- package/src/prescanner.ts +0 -123
- package/src/viewport-discovery.ts +0 -455
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { basename, join, relative } from "node:path";
|
|
2
|
+
import { readFile, readdir, stat } from "node:fs/promises";
|
|
3
|
+
//#region src/playwright-analyzer.ts
|
|
4
|
+
/**
|
|
5
|
+
* Playwright JSON レポートを読み込み、構造化された VRT データに変換する
|
|
6
|
+
*/
|
|
7
|
+
async function analyzeReport(reportPath) {
|
|
8
|
+
const raw = await readFile(reportPath, "utf-8");
|
|
9
|
+
const report = JSON.parse(raw);
|
|
10
|
+
const snapshots = [];
|
|
11
|
+
const failedTests = [];
|
|
12
|
+
const stats = {
|
|
13
|
+
total: 0,
|
|
14
|
+
passed: 0,
|
|
15
|
+
failed: 0,
|
|
16
|
+
skipped: 0,
|
|
17
|
+
flaky: 0,
|
|
18
|
+
duration: 0
|
|
19
|
+
};
|
|
20
|
+
function walkSuites(suites, prefix = "") {
|
|
21
|
+
for (const suite of suites) {
|
|
22
|
+
const suitePath = prefix ? `${prefix} > ${suite.title}` : suite.title;
|
|
23
|
+
for (const spec of suite.specs) processSpec(spec, suitePath);
|
|
24
|
+
if (suite.suites) walkSuites(suite.suites, suitePath);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function processSpec(spec, suitePath) {
|
|
28
|
+
for (const test of spec.tests) {
|
|
29
|
+
stats.total++;
|
|
30
|
+
stats.duration += test.duration;
|
|
31
|
+
const testId = `${suitePath} > ${spec.title}[${test.projectName}]`;
|
|
32
|
+
if (test.status === "skipped") {
|
|
33
|
+
stats.skipped++;
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
if (test.status === "flaky") stats.flaky++;
|
|
37
|
+
if (test.status === "expected") stats.passed++;
|
|
38
|
+
if (test.status === "unexpected") stats.failed++;
|
|
39
|
+
for (const attempt of test.results) {
|
|
40
|
+
const screenshots = attempt.attachments.filter((a) => a.contentType === "image/png" && a.path && !a.name.includes("trace"));
|
|
41
|
+
for (const screenshot of screenshots) snapshots.push({
|
|
42
|
+
testId,
|
|
43
|
+
testTitle: spec.title,
|
|
44
|
+
projectName: test.projectName,
|
|
45
|
+
screenshotPath: screenshot.path,
|
|
46
|
+
status: test.status === "expected" ? "unchanged" : "changed"
|
|
47
|
+
});
|
|
48
|
+
if (attempt.errors.length > 0) failedTests.push({
|
|
49
|
+
testId,
|
|
50
|
+
title: spec.title,
|
|
51
|
+
project: test.projectName,
|
|
52
|
+
errors: attempt.errors.map((e) => e.message),
|
|
53
|
+
attachments: attempt.attachments
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
walkSuites(report.suites);
|
|
59
|
+
return {
|
|
60
|
+
snapshots,
|
|
61
|
+
failedTests,
|
|
62
|
+
stats
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* test-results ディレクトリからスクリーンショットファイルを収集し、
|
|
67
|
+
* ベースラインとの対応関係を構築する
|
|
68
|
+
*/
|
|
69
|
+
async function collectScreenshots(resultsDir, baselineDir) {
|
|
70
|
+
const snapshots = [];
|
|
71
|
+
async function walk(dir) {
|
|
72
|
+
let entries;
|
|
73
|
+
try {
|
|
74
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
75
|
+
} catch {
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
for (const entry of entries) {
|
|
79
|
+
const fullPath = join(dir, entry.name);
|
|
80
|
+
if (entry.isDirectory()) await walk(fullPath);
|
|
81
|
+
else if (entry.name.endsWith(".png") && !entry.name.includes("diff")) {
|
|
82
|
+
const relPath = relative(resultsDir, fullPath);
|
|
83
|
+
const baselinePath = join(baselineDir, relPath);
|
|
84
|
+
let baselineExists = false;
|
|
85
|
+
try {
|
|
86
|
+
await stat(baselinePath);
|
|
87
|
+
baselineExists = true;
|
|
88
|
+
} catch {}
|
|
89
|
+
snapshots.push({
|
|
90
|
+
testId: relPath.replace(/\.png$/, ""),
|
|
91
|
+
testTitle: basename(relPath, ".png"),
|
|
92
|
+
projectName: relPath.split("/")[0] || "default",
|
|
93
|
+
screenshotPath: fullPath,
|
|
94
|
+
baselinePath: baselineExists ? baselinePath : void 0,
|
|
95
|
+
status: baselineExists ? "unchanged" : "new"
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
await walk(resultsDir);
|
|
101
|
+
return snapshots;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* レポートの統計サマリを人間可読な文字列にする
|
|
105
|
+
*/
|
|
106
|
+
function formatStats(stats) {
|
|
107
|
+
return [
|
|
108
|
+
`Total: ${stats.total} tests`,
|
|
109
|
+
`Passed: ${stats.passed}`,
|
|
110
|
+
`Failed: ${stats.failed}`,
|
|
111
|
+
`Skipped: ${stats.skipped}`,
|
|
112
|
+
`Flaky: ${stats.flaky}`,
|
|
113
|
+
`Duration: ${(stats.duration / 1e3).toFixed(1)}s`
|
|
114
|
+
].join("\n");
|
|
115
|
+
}
|
|
116
|
+
//#endregion
|
|
117
|
+
export { analyzeReport, collectScreenshots, formatStats };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
//#region src/playwright-launch-error.d.ts
|
|
2
|
+
declare function isPlaywrightSandboxRestrictionError(error: unknown): boolean;
|
|
3
|
+
declare function formatPlaywrightLaunchError(error: unknown, options?: {
|
|
4
|
+
commandHint?: string;
|
|
5
|
+
}): string;
|
|
6
|
+
//#endregion
|
|
7
|
+
export { formatPlaywrightLaunchError, isPlaywrightSandboxRestrictionError };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
//#region src/playwright-launch-error.ts
|
|
2
|
+
const FORMATTED_SANDBOX_MARKER = "Codex/macOS sandbox restriction";
|
|
3
|
+
const RAW_SANDBOX_SIGNAL_PATTERNS = [
|
|
4
|
+
"Operation not permitted",
|
|
5
|
+
"Permission denied",
|
|
6
|
+
"MachPortRendezvousServer",
|
|
7
|
+
"bootstrap_check_in",
|
|
8
|
+
"mach_port_rendezvous_mac.cc"
|
|
9
|
+
];
|
|
10
|
+
function normalizeErrorMessage(error) {
|
|
11
|
+
if (error instanceof Error) return error.message;
|
|
12
|
+
return String(error).replace(/^Error:\s*/, "");
|
|
13
|
+
}
|
|
14
|
+
function isPlaywrightSandboxRestrictionError(error) {
|
|
15
|
+
const message = normalizeErrorMessage(error);
|
|
16
|
+
return message.includes(FORMATTED_SANDBOX_MARKER) || message.includes("browserType.launch:") && RAW_SANDBOX_SIGNAL_PATTERNS.some((pattern) => message.includes(pattern));
|
|
17
|
+
}
|
|
18
|
+
function formatPlaywrightLaunchError(error, options = {}) {
|
|
19
|
+
const message = normalizeErrorMessage(error);
|
|
20
|
+
if (!isPlaywrightSandboxRestrictionError(error)) return message;
|
|
21
|
+
if (message.includes(FORMATTED_SANDBOX_MARKER)) return message;
|
|
22
|
+
return `Playwright browser launch is blocked by a ${FORMATTED_SANDBOX_MARKER}. Chromium itself is likely fine.${` ${!options.commandHint ? "Re-run outside the Codex sandbox or in CI" : /re-?run outside the codex sandbox/i.test(options.commandHint) ? options.commandHint : `Re-run outside the Codex sandbox or ${options.commandHint}`}.`}\nOriginal error: ${message.split("\n").find((line) => line.trim().length > 0) ?? message}`;
|
|
23
|
+
}
|
|
24
|
+
//#endregion
|
|
25
|
+
export { formatPlaywrightLaunchError, isPlaywrightSandboxRestrictionError };
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { ViewportDetectionResult } from "./detection-types.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/prescanner.d.ts
|
|
4
|
+
type PrescannerResolvedBy = "crater" | "chromium" | "none";
|
|
5
|
+
/** Which Crater metadata signal first fired for a trial resolved by crater. */
|
|
6
|
+
type PrescannerCraterSignal = "paint-tree" | "computed-style" | "forced-state" | "visual" | "none";
|
|
7
|
+
interface PrescannerTrialResolution {
|
|
8
|
+
craterDetected: boolean;
|
|
9
|
+
fallbackUsed: boolean;
|
|
10
|
+
finalDetected: boolean;
|
|
11
|
+
resolvedBy: PrescannerResolvedBy;
|
|
12
|
+
/** Whether the crater path skipped PNG capture entirely (metadata-only). */
|
|
13
|
+
metadataOnly: boolean;
|
|
14
|
+
/** First crater signal type that fired (paint-tree wins over computed-style → forced-state → visual). */
|
|
15
|
+
craterSignal: PrescannerCraterSignal;
|
|
16
|
+
}
|
|
17
|
+
interface PrescannerTrialSummary {
|
|
18
|
+
total: number;
|
|
19
|
+
detected: number;
|
|
20
|
+
craterResolved: number;
|
|
21
|
+
chromiumFallbacks: number;
|
|
22
|
+
chromiumDetected: number;
|
|
23
|
+
passedAfterFallback: number;
|
|
24
|
+
/** Trials resolved by crater that never captured a PNG (metadata-only detection). */
|
|
25
|
+
metadataOnly: number;
|
|
26
|
+
/** Per-signal breakdown of crater-resolved trials. */
|
|
27
|
+
craterBySignal: {
|
|
28
|
+
paintTree: number;
|
|
29
|
+
computedStyle: number;
|
|
30
|
+
forcedState: number;
|
|
31
|
+
visual: number;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
declare function hasCraterPrescanSignal(viewports: ViewportDetectionResult[]): boolean;
|
|
35
|
+
declare function hasAnyDetectionSignal(viewports: ViewportDetectionResult[]): boolean;
|
|
36
|
+
declare function resolvePrescannerTrial(craterViewports: ViewportDetectionResult[], chromiumViewports?: ViewportDetectionResult[]): PrescannerTrialResolution;
|
|
37
|
+
declare function summarizePrescannerTrials(resolutions: PrescannerTrialResolution[]): PrescannerTrialSummary;
|
|
38
|
+
//#endregion
|
|
39
|
+
export { PrescannerCraterSignal, PrescannerResolvedBy, PrescannerTrialResolution, PrescannerTrialSummary, hasAnyDetectionSignal, hasCraterPrescanSignal, resolvePrescannerTrial, summarizePrescannerTrials };
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
//#region src/prescanner.ts
|
|
2
|
+
function hasCraterPrescanSignal(viewports) {
|
|
3
|
+
return viewports.some((viewport) => viewport.visualDiffDetected || viewport.computedStyleDiffCount > 0 || viewport.hoverDiffDetected || viewport.paintTreeDiffCount > 0);
|
|
4
|
+
}
|
|
5
|
+
function hasAnyDetectionSignal(viewports) {
|
|
6
|
+
return viewports.some((viewport) => viewport.visualDiffDetected || viewport.a11yDiffDetected || viewport.computedStyleDiffCount > 0 || viewport.hoverDiffDetected || viewport.paintTreeDiffCount > 0);
|
|
7
|
+
}
|
|
8
|
+
/** Classify the first crater signal that fired. */
|
|
9
|
+
function classifyCraterSignal(viewports) {
|
|
10
|
+
if (viewports.some((v) => v.paintTreeDiffCount > 0)) return "paint-tree";
|
|
11
|
+
if (viewports.some((v) => v.computedStyleDiffCount > 0)) return "computed-style";
|
|
12
|
+
if (viewports.some((v) => v.hoverDiffDetected)) return "forced-state";
|
|
13
|
+
if (viewports.some((v) => v.visualDiffDetected)) return "visual";
|
|
14
|
+
return "none";
|
|
15
|
+
}
|
|
16
|
+
/** True when every viewport in the crater capture skipped its PNG. */
|
|
17
|
+
function isMetadataOnly(viewports) {
|
|
18
|
+
if (viewports.length === 0) return false;
|
|
19
|
+
return viewports.every((v) => v.visualCaptureSkipped === true);
|
|
20
|
+
}
|
|
21
|
+
function resolvePrescannerTrial(craterViewports, chromiumViewports = []) {
|
|
22
|
+
const craterDetected = hasCraterPrescanSignal(craterViewports);
|
|
23
|
+
const metadataOnly = isMetadataOnly(craterViewports);
|
|
24
|
+
if (craterDetected) return {
|
|
25
|
+
craterDetected: true,
|
|
26
|
+
fallbackUsed: false,
|
|
27
|
+
finalDetected: true,
|
|
28
|
+
resolvedBy: "crater",
|
|
29
|
+
metadataOnly,
|
|
30
|
+
craterSignal: classifyCraterSignal(craterViewports)
|
|
31
|
+
};
|
|
32
|
+
const chromiumDetected = hasAnyDetectionSignal(chromiumViewports);
|
|
33
|
+
return {
|
|
34
|
+
craterDetected: false,
|
|
35
|
+
fallbackUsed: true,
|
|
36
|
+
finalDetected: chromiumDetected,
|
|
37
|
+
resolvedBy: chromiumDetected ? "chromium" : "none",
|
|
38
|
+
metadataOnly,
|
|
39
|
+
craterSignal: "none"
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function summarizePrescannerTrials(resolutions) {
|
|
43
|
+
const craterResolved = resolutions.filter((r) => r.resolvedBy === "crater");
|
|
44
|
+
return {
|
|
45
|
+
total: resolutions.length,
|
|
46
|
+
detected: resolutions.filter((resolution) => resolution.finalDetected).length,
|
|
47
|
+
craterResolved: craterResolved.length,
|
|
48
|
+
chromiumFallbacks: resolutions.filter((resolution) => resolution.fallbackUsed).length,
|
|
49
|
+
chromiumDetected: resolutions.filter((resolution) => resolution.resolvedBy === "chromium").length,
|
|
50
|
+
passedAfterFallback: resolutions.filter((resolution) => resolution.resolvedBy === "none").length,
|
|
51
|
+
metadataOnly: craterResolved.filter((r) => r.metadataOnly).length,
|
|
52
|
+
craterBySignal: {
|
|
53
|
+
paintTree: craterResolved.filter((r) => r.craterSignal === "paint-tree").length,
|
|
54
|
+
computedStyle: craterResolved.filter((r) => r.craterSignal === "computed-style").length,
|
|
55
|
+
forcedState: craterResolved.filter((r) => r.craterSignal === "forced-state").length,
|
|
56
|
+
visual: craterResolved.filter((r) => r.craterSignal === "visual").length
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
//#endregion
|
|
61
|
+
export { hasAnyDetectionSignal, hasCraterPrescanSignal, resolvePrescannerTrial, summarizePrescannerTrials };
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
//#region src/viewport-discovery.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Viewport Discovery -- discover breakpoints from CSS and generate boundary-check viewports
|
|
4
|
+
*
|
|
5
|
+
* Extracts breakpoints from @media queries and generates viewport lists
|
|
6
|
+
* at boundary +/-1px + random samples within ranges (quickcheck-style).
|
|
7
|
+
*/
|
|
8
|
+
interface Breakpoint {
|
|
9
|
+
value: number;
|
|
10
|
+
type: "min-width" | "max-width";
|
|
11
|
+
raw: string;
|
|
12
|
+
}
|
|
13
|
+
interface ResponsiveBreakpoint {
|
|
14
|
+
axis: "width";
|
|
15
|
+
op: "ge" | "gt" | "le" | "lt";
|
|
16
|
+
valuePx: number;
|
|
17
|
+
raw: string;
|
|
18
|
+
normalized: string;
|
|
19
|
+
guards: string[];
|
|
20
|
+
ruleCount: number;
|
|
21
|
+
}
|
|
22
|
+
/** Where a viewport candidate originated. */
|
|
23
|
+
type ViewportSource = "standard" | "regex-boundary" | "regex-sample" | "crater-required" | "crater-rule-map";
|
|
24
|
+
interface ViewportSpec {
|
|
25
|
+
width: number;
|
|
26
|
+
height: number;
|
|
27
|
+
label: string;
|
|
28
|
+
reason: string;
|
|
29
|
+
/**
|
|
30
|
+
* Optional provenance for downstream reports — present when discovery
|
|
31
|
+
* went through `generateViewports` / the Crater discovery path. Older
|
|
32
|
+
* callers that build a plain spec without this field still validate.
|
|
33
|
+
*/
|
|
34
|
+
source?: ViewportSource;
|
|
35
|
+
}
|
|
36
|
+
interface DiscoveryResult {
|
|
37
|
+
breakpoints: Breakpoint[];
|
|
38
|
+
responsiveBreakpoints: ResponsiveBreakpoint[];
|
|
39
|
+
viewports: ViewportSpec[];
|
|
40
|
+
/**
|
|
41
|
+
* Which backend supplied the viewport list. `"crater"` means the
|
|
42
|
+
* BiDi v0.18.0 viewport intelligence APIs returned a usable set;
|
|
43
|
+
* `"regex"` means the inline-CSS regex discovery did. `"hybrid"`
|
|
44
|
+
* means Crater seeded the list and regex contributed additional
|
|
45
|
+
* widths (or vice versa).
|
|
46
|
+
*/
|
|
47
|
+
backend: "regex" | "crater" | "hybrid";
|
|
48
|
+
}
|
|
49
|
+
type ViewportBreakpoint = Breakpoint | ResponsiveBreakpoint;
|
|
50
|
+
/** Extract all breakpoints from CSS text */
|
|
51
|
+
declare function extractBreakpoints(css: string): Breakpoint[];
|
|
52
|
+
/** Extract breakpoints from HTML <style> */
|
|
53
|
+
declare function extractBreakpointsFromHtml(html: string): Breakpoint[];
|
|
54
|
+
declare function extractStylesheetHrefsFromHtml(html: string): string[];
|
|
55
|
+
declare function extractBreakpointsFromHtmlWithStylesheets(html: string, stylesheetTexts: string[]): Breakpoint[];
|
|
56
|
+
declare function toResponsiveBreakpoints(breakpoints: ViewportBreakpoint[]): ResponsiveBreakpoint[];
|
|
57
|
+
declare function mergeResponsiveBreakpoints(...collections: ViewportBreakpoint[][]): ResponsiveBreakpoint[];
|
|
58
|
+
declare function extractResponsiveBreakpointsFromHtml(html: string): ResponsiveBreakpoint[];
|
|
59
|
+
declare function extractResponsiveBreakpointsFromHtmlWithStylesheets(html: string, stylesheetTexts: string[]): ResponsiveBreakpoint[];
|
|
60
|
+
interface ViewportOptions {
|
|
61
|
+
height?: number;
|
|
62
|
+
maxViewports?: number;
|
|
63
|
+
randomSamples?: number;
|
|
64
|
+
seed?: number;
|
|
65
|
+
includeStandard?: boolean;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Generate viewport list from breakpoints (quickcheck-style).
|
|
69
|
+
*
|
|
70
|
+
* For each breakpoint:
|
|
71
|
+
* - boundary +1px: just after breakpoint activates
|
|
72
|
+
* - boundary -1px: just before breakpoint activates
|
|
73
|
+
* - (optional) random samples within range
|
|
74
|
+
*/
|
|
75
|
+
declare function generateViewports(breakpoints: ViewportBreakpoint[], options?: ViewportOptions): ViewportSpec[];
|
|
76
|
+
/**
|
|
77
|
+
* Discover breakpoints from HTML and generate boundary-check viewports.
|
|
78
|
+
*/
|
|
79
|
+
declare function discoverViewports(html: string, options?: ViewportOptions): DiscoveryResult;
|
|
80
|
+
interface CraterViewportSource {
|
|
81
|
+
getRequiredTestViewports(): Promise<{
|
|
82
|
+
viewports: Array<{
|
|
83
|
+
width: number;
|
|
84
|
+
reason: string;
|
|
85
|
+
}>;
|
|
86
|
+
}>;
|
|
87
|
+
getCssRuleViewportMap?(viewportWidths?: number[]): Promise<{
|
|
88
|
+
rules: Array<{
|
|
89
|
+
activeAtWidths?: number[];
|
|
90
|
+
inactiveAtWidths?: number[];
|
|
91
|
+
}>;
|
|
92
|
+
}>;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Drive Crater v0.18.0 viewport intelligence (`getRequiredTestViewports`
|
|
96
|
+
* + optional `getCssRuleViewportMap`) to seed the viewport list with
|
|
97
|
+
* breakpoints the renderer itself determined are load-bearing for the
|
|
98
|
+
* current document. Falls back gracefully when either RPC fails.
|
|
99
|
+
*/
|
|
100
|
+
declare function discoverViewportsViaCrater(client: CraterViewportSource, options?: ViewportOptions): Promise<{
|
|
101
|
+
viewports: ViewportSpec[];
|
|
102
|
+
widthsSeen: Set<number>;
|
|
103
|
+
}>;
|
|
104
|
+
/**
|
|
105
|
+
* Hybrid viewport discovery: prefer Crater v0.18.0 viewport intelligence
|
|
106
|
+
* when available, fall back to regex breakpoints for any widths Crater
|
|
107
|
+
* didn't surface, and tag each viewport with its `source`. The returned
|
|
108
|
+
* `backend` field tells downstream reports which path supplied the list.
|
|
109
|
+
*/
|
|
110
|
+
declare function discoverViewportsWithBackend(html: string, options?: ViewportOptions & {
|
|
111
|
+
craterClient?: CraterViewportSource | null;
|
|
112
|
+
}): Promise<DiscoveryResult>;
|
|
113
|
+
//#endregion
|
|
114
|
+
export { Breakpoint, CraterViewportSource, DiscoveryResult, ResponsiveBreakpoint, ViewportOptions, ViewportSource, ViewportSpec, discoverViewports, discoverViewportsViaCrater, discoverViewportsWithBackend, extractBreakpoints, extractBreakpointsFromHtml, extractBreakpointsFromHtmlWithStylesheets, extractResponsiveBreakpointsFromHtml, extractResponsiveBreakpointsFromHtmlWithStylesheets, extractStylesheetHrefsFromHtml, generateViewports, mergeResponsiveBreakpoints, toResponsiveBreakpoints };
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
//#region src/viewport-discovery.ts
|
|
2
|
+
const MEDIA_PATTERN = /@media\s+([^{]+)\{/g;
|
|
3
|
+
const WIDTH_PATTERN = /\(\s*(min|max)-width\s*:\s*([\d.]+)(px|rem|em)\s*\)/g;
|
|
4
|
+
/** Extract all breakpoints from CSS text */
|
|
5
|
+
function extractBreakpoints(css) {
|
|
6
|
+
const breakpoints = /* @__PURE__ */ new Map();
|
|
7
|
+
for (const mediaMatch of css.matchAll(MEDIA_PATTERN)) {
|
|
8
|
+
const condition = mediaMatch[1].trim();
|
|
9
|
+
for (const widthMatch of condition.matchAll(WIDTH_PATTERN)) {
|
|
10
|
+
const type = `${widthMatch[1]}-width`;
|
|
11
|
+
let value = parseFloat(widthMatch[2]);
|
|
12
|
+
const unit = widthMatch[3];
|
|
13
|
+
if (unit === "rem" || unit === "em") value *= 16;
|
|
14
|
+
value = Math.round(value);
|
|
15
|
+
const key = `${type}:${value}`;
|
|
16
|
+
if (!breakpoints.has(key)) breakpoints.set(key, {
|
|
17
|
+
value,
|
|
18
|
+
type,
|
|
19
|
+
raw: `(${type}: ${value}px)`
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return [...breakpoints.values()].sort((a, b) => a.value - b.value);
|
|
24
|
+
}
|
|
25
|
+
function extractInlineStyleCss(html) {
|
|
26
|
+
const styleMatch = html.match(/<style[^>]*>([\s\S]*?)<\/style>/g);
|
|
27
|
+
if (!styleMatch) return "";
|
|
28
|
+
return styleMatch.map((s) => s.replace(/<\/?style[^>]*>/g, "")).join("\n");
|
|
29
|
+
}
|
|
30
|
+
/** Extract breakpoints from HTML <style> */
|
|
31
|
+
function extractBreakpointsFromHtml(html) {
|
|
32
|
+
return extractBreakpoints(extractInlineStyleCss(html));
|
|
33
|
+
}
|
|
34
|
+
function readAttr(tag, name) {
|
|
35
|
+
const re = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`, "i");
|
|
36
|
+
const m = tag.match(re);
|
|
37
|
+
return m?.[1] ?? m?.[2] ?? m?.[3];
|
|
38
|
+
}
|
|
39
|
+
function isStylesheetLink(tag) {
|
|
40
|
+
if (!/^<link\b/i.test(tag)) return false;
|
|
41
|
+
const rel = readAttr(tag, "rel");
|
|
42
|
+
if (!rel) return false;
|
|
43
|
+
return rel.split(/\s+/).some((part) => part.toLowerCase() === "stylesheet");
|
|
44
|
+
}
|
|
45
|
+
function extractStylesheetHrefsFromHtml(html) {
|
|
46
|
+
return (html.match(/<link\b[^>]*>/gi) ?? []).filter(isStylesheetLink).map((tag) => readAttr(tag, "href")).filter((href) => !!href);
|
|
47
|
+
}
|
|
48
|
+
function extractBreakpointsFromHtmlWithStylesheets(html, stylesheetTexts) {
|
|
49
|
+
return extractBreakpoints([extractInlineStyleCss(html), ...stylesheetTexts].join("\n"));
|
|
50
|
+
}
|
|
51
|
+
function isResponsiveBreakpoint(breakpoint) {
|
|
52
|
+
return "axis" in breakpoint;
|
|
53
|
+
}
|
|
54
|
+
function normalizeResponsiveBreakpoint(breakpoint) {
|
|
55
|
+
if (isResponsiveBreakpoint(breakpoint)) {
|
|
56
|
+
const guards = [...new Set(breakpoint.guards)].sort((a, b) => a.localeCompare(b));
|
|
57
|
+
return {
|
|
58
|
+
axis: breakpoint.axis,
|
|
59
|
+
op: breakpoint.op,
|
|
60
|
+
valuePx: breakpoint.valuePx,
|
|
61
|
+
raw: breakpoint.raw,
|
|
62
|
+
normalized: breakpoint.normalized,
|
|
63
|
+
guards,
|
|
64
|
+
ruleCount: breakpoint.ruleCount ?? 1
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
const op = breakpoint.type === "min-width" ? "ge" : "le";
|
|
68
|
+
const operator = op === "ge" ? ">=" : "<=";
|
|
69
|
+
return {
|
|
70
|
+
axis: "width",
|
|
71
|
+
op,
|
|
72
|
+
valuePx: breakpoint.value,
|
|
73
|
+
raw: breakpoint.raw,
|
|
74
|
+
normalized: `(width ${operator} ${breakpoint.value}px)`,
|
|
75
|
+
guards: [],
|
|
76
|
+
ruleCount: 1
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function compareResponsiveBreakpoint(left, right) {
|
|
80
|
+
if (left.valuePx !== right.valuePx) return left.valuePx - right.valuePx;
|
|
81
|
+
const order = {
|
|
82
|
+
lt: 0,
|
|
83
|
+
le: 1,
|
|
84
|
+
ge: 2,
|
|
85
|
+
gt: 3
|
|
86
|
+
};
|
|
87
|
+
if (order[left.op] !== order[right.op]) return order[left.op] - order[right.op];
|
|
88
|
+
return left.guards.join("|").localeCompare(right.guards.join("|"));
|
|
89
|
+
}
|
|
90
|
+
function toResponsiveBreakpoints(breakpoints) {
|
|
91
|
+
const merged = /* @__PURE__ */ new Map();
|
|
92
|
+
for (const breakpoint of breakpoints) {
|
|
93
|
+
const normalized = normalizeResponsiveBreakpoint(breakpoint);
|
|
94
|
+
const key = [
|
|
95
|
+
normalized.axis,
|
|
96
|
+
normalized.op,
|
|
97
|
+
normalized.valuePx,
|
|
98
|
+
normalized.guards.join("&")
|
|
99
|
+
].join(":");
|
|
100
|
+
const existing = merged.get(key);
|
|
101
|
+
if (existing) {
|
|
102
|
+
existing.ruleCount += normalized.ruleCount;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
merged.set(key, { ...normalized });
|
|
106
|
+
}
|
|
107
|
+
return [...merged.values()].sort(compareResponsiveBreakpoint);
|
|
108
|
+
}
|
|
109
|
+
function mergeResponsiveBreakpoints(...collections) {
|
|
110
|
+
return toResponsiveBreakpoints(collections.flat());
|
|
111
|
+
}
|
|
112
|
+
function extractResponsiveBreakpointsFromHtml(html) {
|
|
113
|
+
return toResponsiveBreakpoints(extractBreakpointsFromHtml(html));
|
|
114
|
+
}
|
|
115
|
+
function extractResponsiveBreakpointsFromHtmlWithStylesheets(html, stylesheetTexts) {
|
|
116
|
+
return toResponsiveBreakpoints(extractBreakpointsFromHtmlWithStylesheets(html, stylesheetTexts));
|
|
117
|
+
}
|
|
118
|
+
const STANDARD_VIEWPORTS = [
|
|
119
|
+
{
|
|
120
|
+
width: 375,
|
|
121
|
+
label: "mobile"
|
|
122
|
+
},
|
|
123
|
+
{
|
|
124
|
+
width: 1280,
|
|
125
|
+
label: "desktop"
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
width: 1440,
|
|
129
|
+
label: "wide"
|
|
130
|
+
}
|
|
131
|
+
];
|
|
132
|
+
/**
|
|
133
|
+
* Generate viewport list from breakpoints (quickcheck-style).
|
|
134
|
+
*
|
|
135
|
+
* For each breakpoint:
|
|
136
|
+
* - boundary +1px: just after breakpoint activates
|
|
137
|
+
* - boundary -1px: just before breakpoint activates
|
|
138
|
+
* - (optional) random samples within range
|
|
139
|
+
*/
|
|
140
|
+
function generateViewports(breakpoints, options = {}) {
|
|
141
|
+
const responsiveBreakpoints = toResponsiveBreakpoints(breakpoints);
|
|
142
|
+
const height = options.height ?? 900;
|
|
143
|
+
const maxViewports = options.maxViewports ?? 20;
|
|
144
|
+
const randomSamples = options.randomSamples ?? 0;
|
|
145
|
+
const includeStandard = options.includeStandard ?? true;
|
|
146
|
+
const seed = options.seed ?? 42;
|
|
147
|
+
const viewportMap = /* @__PURE__ */ new Map();
|
|
148
|
+
function add(width, label, reason, source) {
|
|
149
|
+
if (width < 320 || width > 2560) return;
|
|
150
|
+
if (!viewportMap.has(width)) viewportMap.set(width, {
|
|
151
|
+
width,
|
|
152
|
+
height,
|
|
153
|
+
label,
|
|
154
|
+
reason,
|
|
155
|
+
source
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
if (includeStandard) for (const sv of STANDARD_VIEWPORTS) add(sv.width, sv.label, "standard", "standard");
|
|
159
|
+
for (const bp of responsiveBreakpoints) if (bp.op === "ge") {
|
|
160
|
+
add(bp.valuePx - 1, `below-${bp.valuePx}`, `${bp.raw} boundary-below`, "regex-boundary");
|
|
161
|
+
add(bp.valuePx, `at-${bp.valuePx}`, `${bp.raw} boundary-at`, "regex-boundary");
|
|
162
|
+
} else if (bp.op === "gt") {
|
|
163
|
+
add(bp.valuePx, `at-${bp.valuePx}`, `${bp.raw} boundary-at`, "regex-boundary");
|
|
164
|
+
add(bp.valuePx + 1, `above-${bp.valuePx}`, `${bp.raw} boundary-above`, "regex-boundary");
|
|
165
|
+
} else if (bp.op === "le") {
|
|
166
|
+
add(bp.valuePx, `at-${bp.valuePx}`, `${bp.raw} boundary-at`, "regex-boundary");
|
|
167
|
+
add(bp.valuePx + 1, `above-${bp.valuePx}`, `${bp.raw} boundary-above`, "regex-boundary");
|
|
168
|
+
} else {
|
|
169
|
+
add(bp.valuePx - 1, `below-${bp.valuePx}`, `${bp.raw} boundary-below`, "regex-boundary");
|
|
170
|
+
add(bp.valuePx, `at-${bp.valuePx}`, `${bp.raw} boundary-at`, "regex-boundary");
|
|
171
|
+
}
|
|
172
|
+
if (randomSamples > 0 && responsiveBreakpoints.length > 0) {
|
|
173
|
+
const allWidths = [...new Set(responsiveBreakpoints.map((b) => b.valuePx))].sort((a, b) => a - b);
|
|
174
|
+
const ranges = [];
|
|
175
|
+
ranges.push([320, allWidths[0] - 1]);
|
|
176
|
+
for (let i = 0; i < allWidths.length - 1; i++) ranges.push([allWidths[i], allWidths[i + 1] - 1]);
|
|
177
|
+
ranges.push([allWidths[allWidths.length - 1], 1920]);
|
|
178
|
+
let s = seed;
|
|
179
|
+
const rand = () => {
|
|
180
|
+
s = s * 1664525 + 1013904223 & 2147483647;
|
|
181
|
+
return s / 2147483647;
|
|
182
|
+
};
|
|
183
|
+
for (const [lo, hi] of ranges) {
|
|
184
|
+
if (hi - lo < 2) continue;
|
|
185
|
+
for (let j = 0; j < randomSamples; j++) {
|
|
186
|
+
const w = Math.round(lo + rand() * (hi - lo));
|
|
187
|
+
add(w, `sample-${w}`, `random sample in [${lo}, ${hi}]`, "regex-sample");
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return [...viewportMap.values()].sort((a, b) => a.width - b.width).slice(0, maxViewports);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Discover breakpoints from HTML and generate boundary-check viewports.
|
|
195
|
+
*/
|
|
196
|
+
function discoverViewports(html, options = {}) {
|
|
197
|
+
const breakpoints = extractBreakpointsFromHtml(html);
|
|
198
|
+
const responsiveBreakpoints = toResponsiveBreakpoints(breakpoints);
|
|
199
|
+
return {
|
|
200
|
+
breakpoints,
|
|
201
|
+
responsiveBreakpoints,
|
|
202
|
+
viewports: generateViewports(responsiveBreakpoints, options),
|
|
203
|
+
backend: "regex"
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
function clampViewport(width) {
|
|
207
|
+
return Number.isFinite(width) && width >= 320 && width <= 2560;
|
|
208
|
+
}
|
|
209
|
+
function buildCraterViewport(width, height, reason, source) {
|
|
210
|
+
if (!clampViewport(width)) return null;
|
|
211
|
+
return {
|
|
212
|
+
width,
|
|
213
|
+
height,
|
|
214
|
+
label: `at-${width}`,
|
|
215
|
+
reason,
|
|
216
|
+
source
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Drive Crater v0.18.0 viewport intelligence (`getRequiredTestViewports`
|
|
221
|
+
* + optional `getCssRuleViewportMap`) to seed the viewport list with
|
|
222
|
+
* breakpoints the renderer itself determined are load-bearing for the
|
|
223
|
+
* current document. Falls back gracefully when either RPC fails.
|
|
224
|
+
*/
|
|
225
|
+
async function discoverViewportsViaCrater(client, options = {}) {
|
|
226
|
+
const height = options.height ?? 900;
|
|
227
|
+
const widthsSeen = /* @__PURE__ */ new Set();
|
|
228
|
+
const viewports = [];
|
|
229
|
+
function pushIfNew(spec) {
|
|
230
|
+
if (!spec) return;
|
|
231
|
+
if (widthsSeen.has(spec.width)) return;
|
|
232
|
+
widthsSeen.add(spec.width);
|
|
233
|
+
viewports.push(spec);
|
|
234
|
+
}
|
|
235
|
+
try {
|
|
236
|
+
const required = await client.getRequiredTestViewports();
|
|
237
|
+
for (const v of required.viewports ?? []) pushIfNew(buildCraterViewport(v.width, height, v.reason || "crater required", "crater-required"));
|
|
238
|
+
} catch {}
|
|
239
|
+
if (client.getCssRuleViewportMap) try {
|
|
240
|
+
const map = await client.getCssRuleViewportMap();
|
|
241
|
+
const extraWidths = /* @__PURE__ */ new Set();
|
|
242
|
+
for (const rule of map.rules ?? []) {
|
|
243
|
+
for (const w of rule.activeAtWidths ?? []) extraWidths.add(w);
|
|
244
|
+
for (const w of rule.inactiveAtWidths ?? []) extraWidths.add(w);
|
|
245
|
+
}
|
|
246
|
+
for (const width of extraWidths) pushIfNew(buildCraterViewport(width, height, "crater rule/viewport map", "crater-rule-map"));
|
|
247
|
+
} catch {}
|
|
248
|
+
return {
|
|
249
|
+
viewports,
|
|
250
|
+
widthsSeen
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Hybrid viewport discovery: prefer Crater v0.18.0 viewport intelligence
|
|
255
|
+
* when available, fall back to regex breakpoints for any widths Crater
|
|
256
|
+
* didn't surface, and tag each viewport with its `source`. The returned
|
|
257
|
+
* `backend` field tells downstream reports which path supplied the list.
|
|
258
|
+
*/
|
|
259
|
+
async function discoverViewportsWithBackend(html, options = {}) {
|
|
260
|
+
const breakpoints = extractBreakpointsFromHtml(html);
|
|
261
|
+
const responsiveBreakpoints = toResponsiveBreakpoints(breakpoints);
|
|
262
|
+
const regexViewports = generateViewports(responsiveBreakpoints, options);
|
|
263
|
+
const client = options.craterClient ?? null;
|
|
264
|
+
if (!client) return {
|
|
265
|
+
breakpoints,
|
|
266
|
+
responsiveBreakpoints,
|
|
267
|
+
viewports: regexViewports,
|
|
268
|
+
backend: "regex"
|
|
269
|
+
};
|
|
270
|
+
const craterResult = await discoverViewportsViaCrater(client, options);
|
|
271
|
+
if (craterResult.viewports.length === 0) return {
|
|
272
|
+
breakpoints,
|
|
273
|
+
responsiveBreakpoints,
|
|
274
|
+
viewports: regexViewports,
|
|
275
|
+
backend: "regex"
|
|
276
|
+
};
|
|
277
|
+
const merged = [...craterResult.viewports];
|
|
278
|
+
let usedFallback = false;
|
|
279
|
+
for (const v of regexViewports) {
|
|
280
|
+
if (craterResult.widthsSeen.has(v.width)) continue;
|
|
281
|
+
merged.push(v);
|
|
282
|
+
if (v.source !== "standard") usedFallback = true;
|
|
283
|
+
}
|
|
284
|
+
const maxViewports = options.maxViewports ?? 20;
|
|
285
|
+
merged.sort((a, b) => a.width - b.width);
|
|
286
|
+
return {
|
|
287
|
+
breakpoints,
|
|
288
|
+
responsiveBreakpoints,
|
|
289
|
+
viewports: merged.slice(0, maxViewports),
|
|
290
|
+
backend: usedFallback ? "hybrid" : "crater"
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
//#endregion
|
|
294
|
+
export { discoverViewports, discoverViewportsViaCrater, discoverViewportsWithBackend, extractBreakpoints, extractBreakpointsFromHtml, extractBreakpointsFromHtmlWithStylesheets, extractResponsiveBreakpointsFromHtml, extractResponsiveBreakpointsFromHtmlWithStylesheets, extractStylesheetHrefsFromHtml, generateViewports, mergeResponsiveBreakpoints, toResponsiveBreakpoints };
|