webperf-snippets 0.1.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/README.md +139 -0
- package/package.json +54 -0
- package/snippets/CoreWebVitals/CLS.js +88 -0
- package/snippets/CoreWebVitals/INP.js +432 -0
- package/snippets/CoreWebVitals/LCP-Image-Entropy.js +198 -0
- package/snippets/CoreWebVitals/LCP-Subparts.js +286 -0
- package/snippets/CoreWebVitals/LCP-Trail.js +184 -0
- package/snippets/CoreWebVitals/LCP-Video-Candidate.js +228 -0
- package/snippets/CoreWebVitals/LCP.js +135 -0
- package/snippets/CoreWebVitals/WORKFLOWS.md +203 -0
- package/snippets/DevTools-Overrides/Fetch-XHR-Timeline-inject.js +73 -0
- package/snippets/DevTools-Overrides/Fetch-XHR-Timeline-read.js +191 -0
- package/snippets/Interaction/Forced-Synchronous-Layout.js +286 -0
- package/snippets/Interaction/Input-Latency-Breakdown.js +199 -0
- package/snippets/Interaction/Interactions.js +220 -0
- package/snippets/Interaction/Layout-Shift-Loading-and-Interaction.js +266 -0
- package/snippets/Interaction/Long-Animation-Frames-Helpers.js +397 -0
- package/snippets/Interaction/Long-Animation-Frames-Script-Attribution.js +137 -0
- package/snippets/Interaction/Long-Animation-Frames.js +298 -0
- package/snippets/Interaction/LongTask.js +203 -0
- package/snippets/Interaction/Scroll-Performance.js +359 -0
- package/snippets/Interaction/WORKFLOWS.md +205 -0
- package/snippets/Loading/Back-Forward-Cache.js +473 -0
- package/snippets/Loading/CSS-Media-Queries-Analysis.js +512 -0
- package/snippets/Loading/Cache-Strategy-Analysis.js +808 -0
- package/snippets/Loading/Client-Side-Redirect-Detection.js +337 -0
- package/snippets/Loading/Content-Visibility.js +352 -0
- package/snippets/Loading/Critical-CSS-Detection.js +329 -0
- package/snippets/Loading/Event-Processing-Time.js +179 -0
- package/snippets/Loading/FCP.js +101 -0
- package/snippets/Loading/Find-Above-The-Fold-Lazy-Loaded-Images.js +264 -0
- package/snippets/Loading/Find-Images-With-Lazy-and-Fetchpriority.js +155 -0
- package/snippets/Loading/Find-non-Lazy-Loaded-Images-outside-of-the-viewport.js +300 -0
- package/snippets/Loading/Find-render-blocking-resources.js +161 -0
- package/snippets/Loading/First-And-Third-Party-Script-Info.js +269 -0
- package/snippets/Loading/First-And-Third-Party-Script-Timings.js +295 -0
- package/snippets/Loading/Fonts-Preloaded-Loaded-and-used-above-the-fold.js +317 -0
- package/snippets/Loading/Inline-CSS-Info-and-Size.js +234 -0
- package/snippets/Loading/Inline-Script-Info-and-Size.js +323 -0
- package/snippets/Loading/JS-Execution-Time-Breakdown.js +336 -0
- package/snippets/Loading/Prefetch-Resource-Validation.js +456 -0
- package/snippets/Loading/Priority-Hints-Audit.js +336 -0
- package/snippets/Loading/Resource-Hints-Validation.js +503 -0
- package/snippets/Loading/Resource-Hints.js +400 -0
- package/snippets/Loading/SSR-Hydration-Data-Analysis.js +364 -0
- package/snippets/Loading/Script-Loading.js +332 -0
- package/snippets/Loading/Service-Worker-Analysis.js +192 -0
- package/snippets/Loading/TTFB-Resources.js +115 -0
- package/snippets/Loading/TTFB-Sub-Parts.js +117 -0
- package/snippets/Loading/TTFB.js +37 -0
- package/snippets/Loading/Validate-Preload-Async-Defer-Scripts.js +394 -0
- package/snippets/Loading/WORKFLOWS.md +163 -0
- package/snippets/Media/Image-Element-Audit.js +350 -0
- package/snippets/Media/SVG-Embedded-Bitmap-Analysis.js +225 -0
- package/snippets/Media/Video-Element-Audit.js +282 -0
- package/snippets/Media/WORKFLOWS.md +190 -0
- package/snippets/README.md +98 -0
- package/snippets/Resources/Network-Bandwidth-Connection-Quality.js +103 -0
- package/snippets/Resources/WORKFLOWS.md +173 -0
- package/src/bin.js +229 -0
- package/src/decision-tree.js +19 -0
- package/src/load-snippet.js +23 -0
- package/src/reporters/human.js +179 -0
- package/src/reporters/json.js +3 -0
- package/src/runner.js +61 -0
- package/src/workflows/audit.js +21 -0
- package/src/workflows/cwv.js +10 -0
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
## Common Workflows
|
|
2
|
+
|
|
3
|
+
### Network Quality Assessment
|
|
4
|
+
|
|
5
|
+
When the user asks about network performance, connection quality, or adaptive loading:
|
|
6
|
+
|
|
7
|
+
1. **Network-Bandwidth-Connection-Quality.js** - Analyze network bandwidth, effective connection type, RTT, downlink, save-data mode
|
|
8
|
+
|
|
9
|
+
### Adaptive Loading Strategy
|
|
10
|
+
|
|
11
|
+
When implementing adaptive loading or the user asks "how to optimize for slow connections":
|
|
12
|
+
|
|
13
|
+
1. **Network-Bandwidth-Connection-Quality.js** - Detect connection quality
|
|
14
|
+
2. Cross-reference with **webperf-loading** skill:
|
|
15
|
+
- TTFB.js (measure server response on slow connections)
|
|
16
|
+
- Find-render-blocking-resources.js (identify heavy resources to defer)
|
|
17
|
+
- Resource-Hints-Validation.js (optimize preconnect for slow networks)
|
|
18
|
+
3. Cross-reference with **webperf-media** skill:
|
|
19
|
+
- Image-Element-Audit.js (implement responsive images based on connection)
|
|
20
|
+
- Video-Element-Audit.js (adjust video quality based on connection)
|
|
21
|
+
|
|
22
|
+
### Save-Data Mode Detection
|
|
23
|
+
|
|
24
|
+
When the user asks about save-data or data-saving features:
|
|
25
|
+
|
|
26
|
+
1. **Network-Bandwidth-Connection-Quality.js** - Check if save-data is enabled
|
|
27
|
+
2. If save-data is enabled, recommend:
|
|
28
|
+
- Reducing image quality
|
|
29
|
+
- Disabling autoplay videos
|
|
30
|
+
- Deferring non-critical resources
|
|
31
|
+
- Using low-res thumbnails
|
|
32
|
+
|
|
33
|
+
### Mobile/Slow Connection Optimization
|
|
34
|
+
|
|
35
|
+
When the user asks "optimize for mobile" or "slow connection users":
|
|
36
|
+
|
|
37
|
+
1. **Network-Bandwidth-Connection-Quality.js** - Assess connection type
|
|
38
|
+
2. Cross-reference with **webperf-loading** skill:
|
|
39
|
+
- TTFB.js (critical for slow connections)
|
|
40
|
+
- Find-render-blocking-resources.js (minimize blocking on slow networks)
|
|
41
|
+
- Critical-CSS-Detection.js (inline critical CSS to reduce RTT)
|
|
42
|
+
- Prefetch-Resource-Validation.js (avoid excessive prefetch on slow connections)
|
|
43
|
+
|
|
44
|
+
## Decision Tree
|
|
45
|
+
|
|
46
|
+
Use this decision tree to automatically run follow-up snippets based on results:
|
|
47
|
+
|
|
48
|
+
### After Network-Bandwidth-Connection-Quality.js
|
|
49
|
+
|
|
50
|
+
- **If effectiveType is "slow-2g" or "2g"** → Very slow connection, recommend:
|
|
51
|
+
1. Run **webperf-loading:Critical-CSS-Detection.js** (inline critical CSS)
|
|
52
|
+
2. Run **webperf-media:Image-Element-Audit.js** (implement aggressive lazy loading)
|
|
53
|
+
3. Run **webperf-loading:Prefetch-Resource-Validation.js** (remove prefetch to save bandwidth)
|
|
54
|
+
4. Run **webperf-core-web-vitals:LCP.js** (LCP is heavily impacted by slow connections)
|
|
55
|
+
5. Recommend minimal resource strategy
|
|
56
|
+
|
|
57
|
+
- **If effectiveType is "3g"** → Moderate connection, recommend:
|
|
58
|
+
1. Run **webperf-loading:Find-render-blocking-resources.js** (minimize blocking)
|
|
59
|
+
2. Run **webperf-media:Image-Element-Audit.js** (responsive images)
|
|
60
|
+
3. Run **webperf-loading:Resource-Hints-Validation.js** (optimize preconnect)
|
|
61
|
+
4. Run **webperf-core-web-vitals:INP.js** (high latency can impact interaction responsiveness)
|
|
62
|
+
5. Implement adaptive image quality
|
|
63
|
+
|
|
64
|
+
- **If effectiveType is "4g" or better** → Good connection, recommend:
|
|
65
|
+
1. Standard optimization practices
|
|
66
|
+
2. Consider strategic prefetch for navigation
|
|
67
|
+
3. Higher quality media is acceptable
|
|
68
|
+
|
|
69
|
+
- **If save-data is enabled** → User explicitly wants to save data, recommend:
|
|
70
|
+
1. Reduce image quality aggressively
|
|
71
|
+
2. Disable autoplay videos
|
|
72
|
+
3. Defer non-critical resources
|
|
73
|
+
4. Remove prefetch/preload hints
|
|
74
|
+
5. Show "high quality" toggle option
|
|
75
|
+
|
|
76
|
+
- **If RTT > 300ms** → High latency, recommend:
|
|
77
|
+
1. Run **webperf-loading:TTFB.js** (latency impacts TTFB)
|
|
78
|
+
2. Run **webperf-loading:TTFB-Sub-Parts.js** (break down latency components)
|
|
79
|
+
3. Run **webperf-loading:Resource-Hints-Validation.js** (preconnect critical for high RTT)
|
|
80
|
+
4. Run **webperf-loading:Service-Worker-Analysis.js** (caching is critical for high latency)
|
|
81
|
+
5. Minimize number of origins
|
|
82
|
+
6. Use HTTP/2 or HTTP/3 for multiplexing
|
|
83
|
+
|
|
84
|
+
- **If downlink < 1 Mbps** → Very limited bandwidth, recommend:
|
|
85
|
+
1. Run **webperf-media:Image-Element-Audit.js** (aggressive compression)
|
|
86
|
+
2. Run **webperf-media:Video-Element-Audit.js** (disable autoplay)
|
|
87
|
+
3. Run **webperf-loading:Prefetch-Resource-Validation.js** (remove prefetch)
|
|
88
|
+
4. Implement bandwidth-aware loading
|
|
89
|
+
|
|
90
|
+
- **If downlink > 10 Mbps** → Good bandwidth, consider:
|
|
91
|
+
- Higher quality media
|
|
92
|
+
- Strategic prefetch
|
|
93
|
+
- Preloading next-page resources
|
|
94
|
+
|
|
95
|
+
### Adaptive Loading Implementation Guide
|
|
96
|
+
|
|
97
|
+
Based on Network Information API results, implement these strategies:
|
|
98
|
+
|
|
99
|
+
**For slow-2g / 2g (< 50 Kbps):** (`effectiveType: "slow-2g"` or `"2g"`)
|
|
100
|
+
- Serve low-res images (quality: 30-40)
|
|
101
|
+
- Disable autoplay videos
|
|
102
|
+
- Remove all prefetch hints
|
|
103
|
+
- Inline all critical CSS
|
|
104
|
+
- Defer all non-critical JavaScript
|
|
105
|
+
- Use system fonts (no webfonts)
|
|
106
|
+
- Aggressive lazy loading (load on scroll + buffer)
|
|
107
|
+
|
|
108
|
+
**For 3g (50-700 Kbps):** (`effectiveType: "3g"`)
|
|
109
|
+
- Serve medium-res images (quality: 60-70)
|
|
110
|
+
- Disable autoplay videos
|
|
111
|
+
- Limited prefetch (critical only)
|
|
112
|
+
- Inline critical CSS only
|
|
113
|
+
- Defer non-critical JavaScript
|
|
114
|
+
- Preload 1-2 critical fonts
|
|
115
|
+
- Standard lazy loading
|
|
116
|
+
|
|
117
|
+
**For 4g+ (> 700 Kbps):** (`effectiveType: "4g"`)
|
|
118
|
+
- Serve high-res images (quality: 80-90)
|
|
119
|
+
- Allow autoplay videos (muted)
|
|
120
|
+
- Strategic prefetch for navigation
|
|
121
|
+
- Standard CSS loading and JavaScript loading
|
|
122
|
+
- Preload critical fonts
|
|
123
|
+
- Standard lazy loading
|
|
124
|
+
|
|
125
|
+
**For save-data mode:** (`navigator.connection.saveData === true`)
|
|
126
|
+
- Override connection type, treat as worse than actual
|
|
127
|
+
- Show "Load high quality" toggle
|
|
128
|
+
- Disable autoplay entirely
|
|
129
|
+
- Minimal images, minimal quality
|
|
130
|
+
- No prefetch, no preload (except critical)
|
|
131
|
+
|
|
132
|
+
### Performance Budget by Connection Type
|
|
133
|
+
|
|
134
|
+
Adjust performance budgets based on connection quality:
|
|
135
|
+
|
|
136
|
+
**slow-2g / 2g:**
|
|
137
|
+
- Total page weight: < 500KB
|
|
138
|
+
- Images: < 200KB total
|
|
139
|
+
- JavaScript: < 100KB total
|
|
140
|
+
- No videos
|
|
141
|
+
|
|
142
|
+
**3g:**
|
|
143
|
+
- Total page weight: < 1.5MB
|
|
144
|
+
- Images: < 800KB total
|
|
145
|
+
- JavaScript: < 300KB total
|
|
146
|
+
- Videos: < 3MB (only if critical)
|
|
147
|
+
|
|
148
|
+
**4g+:**
|
|
149
|
+
- Total page weight: < 3MB
|
|
150
|
+
- Images: < 2MB total
|
|
151
|
+
- JavaScript: < 1MB total
|
|
152
|
+
- Videos: < 10MB
|
|
153
|
+
|
|
154
|
+
### Network Information API Limitations
|
|
155
|
+
|
|
156
|
+
Be aware of API limitations and fallbacks:
|
|
157
|
+
|
|
158
|
+
**API not available:**
|
|
159
|
+
- Safari does not support Network Information API
|
|
160
|
+
- Fallback: Use TTFB as proxy for connection quality
|
|
161
|
+
- Fallback: Device detection (mobile = assume slow)
|
|
162
|
+
- Fallback: User preference toggle
|
|
163
|
+
|
|
164
|
+
**API values are estimates:**
|
|
165
|
+
- effectiveType is based on recent observations
|
|
166
|
+
- Values can change during session
|
|
167
|
+
- Re-check periodically for long sessions
|
|
168
|
+
|
|
169
|
+
**Privacy considerations:**
|
|
170
|
+
- Some browsers limit precision for privacy
|
|
171
|
+
- Values may be rounded or capped
|
|
172
|
+
- Consider user privacy when making decisions
|
|
173
|
+
|
package/src/bin.js
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from "node:util";
|
|
3
|
+
import { loadSnippet } from "./load-snippet.js";
|
|
4
|
+
import { runSnippets, VIEWPORT_PRESETS } from "./runner.js";
|
|
5
|
+
import { cwvWorkflow } from "./workflows/cwv.js";
|
|
6
|
+
import { auditWorkflow } from "./workflows/audit.js";
|
|
7
|
+
import { nextSteps } from "./decision-tree.js";
|
|
8
|
+
import { reportHuman } from "./reporters/human.js";
|
|
9
|
+
import { reportJson } from "./reporters/json.js";
|
|
10
|
+
|
|
11
|
+
const WORKFLOWS = {
|
|
12
|
+
"core-web-vitals": cwvWorkflow,
|
|
13
|
+
audit: auditWorkflow,
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const SNIPPET_ALIASES = {
|
|
17
|
+
LCP: "CoreWebVitals/LCP",
|
|
18
|
+
CLS: "CoreWebVitals/CLS",
|
|
19
|
+
"LCP-Subparts": "CoreWebVitals/LCP-Subparts",
|
|
20
|
+
fonts: "Loading/Fonts-Preloaded-Loaded-and-used-above-the-fold",
|
|
21
|
+
"Fonts-Preloaded-Loaded-and-used-above-the-fold":
|
|
22
|
+
"Loading/Fonts-Preloaded-Loaded-and-used-above-the-fold",
|
|
23
|
+
// Tier 1 — Loading
|
|
24
|
+
"render-blocking": "Loading/Find-render-blocking-resources",
|
|
25
|
+
"Find-render-blocking-resources": "Loading/Find-render-blocking-resources",
|
|
26
|
+
"resource-hints": "Loading/Resource-Hints-Validation",
|
|
27
|
+
"Resource-Hints-Validation": "Loading/Resource-Hints-Validation",
|
|
28
|
+
"preload-scripts": "Loading/Validate-Preload-Async-Defer-Scripts",
|
|
29
|
+
"Validate-Preload-Async-Defer-Scripts": "Loading/Validate-Preload-Async-Defer-Scripts",
|
|
30
|
+
"priority-hints": "Loading/Priority-Hints-Audit",
|
|
31
|
+
"Priority-Hints-Audit": "Loading/Priority-Hints-Audit",
|
|
32
|
+
"critical-css": "Loading/Critical-CSS-Detection",
|
|
33
|
+
"Critical-CSS-Detection": "Loading/Critical-CSS-Detection",
|
|
34
|
+
ttfb: "Loading/TTFB-Sub-Parts",
|
|
35
|
+
"TTFB-Sub-Parts": "Loading/TTFB-Sub-Parts",
|
|
36
|
+
"script-parties": "Loading/First-And-Third-Party-Script-Info",
|
|
37
|
+
"First-And-Third-Party-Script-Info": "Loading/First-And-Third-Party-Script-Info",
|
|
38
|
+
"script-loading": "Loading/Script-Loading",
|
|
39
|
+
"Script-Loading": "Loading/Script-Loading",
|
|
40
|
+
// Tier 2 — Media
|
|
41
|
+
"lazy-atf": "Loading/Find-Above-The-Fold-Lazy-Loaded-Images",
|
|
42
|
+
"Find-Above-The-Fold-Lazy-Loaded-Images": "Loading/Find-Above-The-Fold-Lazy-Loaded-Images",
|
|
43
|
+
"lazy-conflict": "Loading/Find-Images-With-Lazy-and-Fetchpriority",
|
|
44
|
+
"Find-Images-With-Lazy-and-Fetchpriority": "Loading/Find-Images-With-Lazy-and-Fetchpriority",
|
|
45
|
+
"eager-below-fold": "Loading/Find-non-Lazy-Loaded-Images-outside-of-the-viewport",
|
|
46
|
+
"Find-non-Lazy-Loaded-Images-outside-of-the-viewport":
|
|
47
|
+
"Loading/Find-non-Lazy-Loaded-Images-outside-of-the-viewport",
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const USAGE = `webperf-snippets <url> [options]
|
|
51
|
+
|
|
52
|
+
Run curated WebPerf Snippets headlessly via Playwright.
|
|
53
|
+
|
|
54
|
+
Options:
|
|
55
|
+
--workflow <name> Workflow to run (default: core-web-vitals)
|
|
56
|
+
Workflows: core-web-vitals, audit
|
|
57
|
+
--snippet <name> Run a single snippet by alias or Category/Name path
|
|
58
|
+
Aliases: LCP, CLS, LCP-Subparts, fonts,
|
|
59
|
+
render-blocking, resource-hints, preload-scripts,
|
|
60
|
+
priority-hints, critical-css, ttfb,
|
|
61
|
+
script-parties, script-loading,
|
|
62
|
+
lazy-atf, lazy-conflict, eager-below-fold
|
|
63
|
+
--json Output JSON instead of formatted text
|
|
64
|
+
--viewport <preset> Viewport preset: mobile (default), tablet, desktop
|
|
65
|
+
--wait <ms> Post-load wait before evaluating (default: 3000)
|
|
66
|
+
--budget-lcp <ms> Exit 1 if LCP exceeds this value
|
|
67
|
+
--budget-cls <score> Exit 1 if CLS exceeds this value
|
|
68
|
+
--verbose Show all items, even for passing checks
|
|
69
|
+
--headed Show the browser window (debug)
|
|
70
|
+
-h, --help Show this help
|
|
71
|
+
|
|
72
|
+
Examples:
|
|
73
|
+
npx webperf-snippets https://web.dev
|
|
74
|
+
npx webperf-snippets https://web.dev --workflow audit
|
|
75
|
+
npx webperf-snippets https://web.dev --json
|
|
76
|
+
npx webperf-snippets https://web.dev --snippet LCP-Subparts
|
|
77
|
+
npx webperf-snippets https://web.dev --snippet render-blocking
|
|
78
|
+
npx webperf-snippets https://web.dev --snippet fonts
|
|
79
|
+
npx webperf-snippets https://web.dev --budget-lcp 2500
|
|
80
|
+
`;
|
|
81
|
+
|
|
82
|
+
function fail(message, code = 2) {
|
|
83
|
+
process.stderr.write(`${message}\n`);
|
|
84
|
+
process.exit(code);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function resolveSnippetPath(name) {
|
|
88
|
+
return SNIPPET_ALIASES[name] ?? name;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function buildItems(values) {
|
|
92
|
+
if (values.snippet) {
|
|
93
|
+
const path = resolveSnippetPath(values.snippet);
|
|
94
|
+
return [{ id: values.snippet, path, source: loadSnippet(path) }];
|
|
95
|
+
}
|
|
96
|
+
const workflowName = values.workflow ?? "core-web-vitals";
|
|
97
|
+
const workflow = WORKFLOWS[workflowName];
|
|
98
|
+
if (!workflow) fail(`Unknown workflow: ${workflowName}`);
|
|
99
|
+
return workflow.steps.map((step) => ({
|
|
100
|
+
id: step.id,
|
|
101
|
+
path: step.path,
|
|
102
|
+
source: loadSnippet(step.path),
|
|
103
|
+
}));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function checkBudgets(results, values) {
|
|
107
|
+
const violations = [];
|
|
108
|
+
const lcpBudget = values["budget-lcp"] ? Number(values["budget-lcp"]) : null;
|
|
109
|
+
const clsBudget = values["budget-cls"] ? Number(values["budget-cls"]) : null;
|
|
110
|
+
|
|
111
|
+
for (const r of results) {
|
|
112
|
+
if (r.status !== "ok") continue;
|
|
113
|
+
if (r.metric === "LCP" && lcpBudget != null && r.value > lcpBudget) {
|
|
114
|
+
violations.push(`LCP ${r.value}ms exceeds budget ${lcpBudget}ms`);
|
|
115
|
+
}
|
|
116
|
+
if (r.metric === "CLS" && clsBudget != null && r.value > clsBudget) {
|
|
117
|
+
violations.push(`CLS ${r.value} exceeds budget ${clsBudget}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return violations;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function main() {
|
|
124
|
+
let parsed;
|
|
125
|
+
try {
|
|
126
|
+
parsed = parseArgs({
|
|
127
|
+
options: {
|
|
128
|
+
workflow: { type: "string" },
|
|
129
|
+
snippet: { type: "string" },
|
|
130
|
+
json: { type: "boolean" },
|
|
131
|
+
wait: { type: "string" },
|
|
132
|
+
"budget-lcp": { type: "string" },
|
|
133
|
+
"budget-cls": { type: "string" },
|
|
134
|
+
viewport: { type: "string" },
|
|
135
|
+
verbose: { type: "boolean" },
|
|
136
|
+
headed: { type: "boolean" },
|
|
137
|
+
help: { type: "boolean", short: "h" },
|
|
138
|
+
},
|
|
139
|
+
allowPositionals: true,
|
|
140
|
+
});
|
|
141
|
+
} catch (err) {
|
|
142
|
+
fail(err.message);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const { values, positionals } = parsed;
|
|
146
|
+
|
|
147
|
+
if (values.help) {
|
|
148
|
+
process.stdout.write(USAGE);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const url = positionals[0];
|
|
153
|
+
if (!url) {
|
|
154
|
+
process.stdout.write(USAGE);
|
|
155
|
+
process.exit(2);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const items = buildItems(values);
|
|
159
|
+
const waitMs = values.wait ? Number(values.wait) : 3000;
|
|
160
|
+
const viewportName = values.viewport ?? "mobile";
|
|
161
|
+
const viewport = VIEWPORT_PRESETS[viewportName];
|
|
162
|
+
if (!viewport) {
|
|
163
|
+
fail(`Unknown viewport preset: "${viewportName}". Choose from: ${Object.keys(VIEWPORT_PRESETS).join(", ")}`);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const initial = await runSnippets({
|
|
167
|
+
url,
|
|
168
|
+
items,
|
|
169
|
+
waitMs,
|
|
170
|
+
headless: !values.headed,
|
|
171
|
+
viewport,
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
// Apply decision tree to spawn follow-up steps.
|
|
175
|
+
const followUps = nextSteps(initial.results);
|
|
176
|
+
let followUpRun = { results: [], pageErrors: [] };
|
|
177
|
+
if (followUps.length > 0) {
|
|
178
|
+
const followItems = followUps.map((f) => ({
|
|
179
|
+
id: f.id,
|
|
180
|
+
path: f.path,
|
|
181
|
+
source: loadSnippet(f.path),
|
|
182
|
+
reason: f.reason,
|
|
183
|
+
}));
|
|
184
|
+
// v0.1 limitation: follow-ups re-navigate. Acceptable for now; consolidate
|
|
185
|
+
// into a single page session in v0.2 if perf becomes a problem.
|
|
186
|
+
followUpRun = await runSnippets({
|
|
187
|
+
url,
|
|
188
|
+
items: followItems,
|
|
189
|
+
waitMs,
|
|
190
|
+
headless: !values.headed,
|
|
191
|
+
viewport,
|
|
192
|
+
});
|
|
193
|
+
// Carry forward the human-readable reason so reporters can show it.
|
|
194
|
+
followUpRun.results = followUpRun.results.map((r) => {
|
|
195
|
+
const f = followUps.find((x) => x.id === r.id);
|
|
196
|
+
return f ? { ...r, reason: f.reason } : r;
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const payload = {
|
|
201
|
+
url,
|
|
202
|
+
navMs: initial.navMs,
|
|
203
|
+
results: [...initial.results, ...followUpRun.results],
|
|
204
|
+
pageErrors: [...initial.pageErrors, ...(followUpRun.pageErrors ?? [])],
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const output = values.json ? reportJson(payload) : reportHuman({ ...payload, verbose: values.verbose });
|
|
208
|
+
process.stdout.write(output + "\n");
|
|
209
|
+
|
|
210
|
+
// Exit codes.
|
|
211
|
+
const violations = checkBudgets(payload.results, values);
|
|
212
|
+
if (violations.length > 0) {
|
|
213
|
+
if (!values.json) {
|
|
214
|
+
for (const v of violations) process.stderr.write(`Budget violation: ${v}\n`);
|
|
215
|
+
}
|
|
216
|
+
process.exit(1);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const anyError = payload.results.some((r) => r.status === "error");
|
|
220
|
+
const anyAuditViolation = payload.results.some(
|
|
221
|
+
(r) => Array.isArray(r.issues) && r.issues.some((i) => i.severity === "error"),
|
|
222
|
+
);
|
|
223
|
+
process.exit(anyError || anyAuditViolation ? 1 : 0);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
main().catch((err) => {
|
|
227
|
+
process.stderr.write(`Error: ${err.stack ?? err.message}\n`);
|
|
228
|
+
process.exit(1);
|
|
229
|
+
});
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Declarative follow-ups: if a result matches the predicate, append the step.
|
|
2
|
+
// Mirrors the WORKFLOWS.md decision trees from the snippet catalogue.
|
|
3
|
+
const RULES = [
|
|
4
|
+
{
|
|
5
|
+
when: (r) => r.id === "LCP" && r.status === "ok" && r.value > 2500,
|
|
6
|
+
append: { id: "LCP-Subparts", path: "CoreWebVitals/LCP-Subparts" },
|
|
7
|
+
reason: "LCP > 2.5s — drilling into sub-parts",
|
|
8
|
+
},
|
|
9
|
+
];
|
|
10
|
+
|
|
11
|
+
export function nextSteps(results) {
|
|
12
|
+
const followUps = [];
|
|
13
|
+
for (const result of results) {
|
|
14
|
+
for (const rule of RULES) {
|
|
15
|
+
if (rule.when(result)) followUps.push({ ...rule.append, reason: rule.reason });
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return followUps;
|
|
19
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
|
+
|
|
5
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
6
|
+
const PKG_ROOT = resolve(HERE, "..");
|
|
7
|
+
|
|
8
|
+
// Resolution order: bundled (published package) → workspace root (dev).
|
|
9
|
+
const SNIPPET_DIRS = [
|
|
10
|
+
join(PKG_ROOT, "snippets"),
|
|
11
|
+
resolve(PKG_ROOT, "..", "snippets"),
|
|
12
|
+
];
|
|
13
|
+
|
|
14
|
+
export function loadSnippet(relativePath) {
|
|
15
|
+
for (const dir of SNIPPET_DIRS) {
|
|
16
|
+
try {
|
|
17
|
+
return readFileSync(join(dir, `${relativePath}.js`), "utf8");
|
|
18
|
+
} catch {
|
|
19
|
+
// try next directory
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
throw new Error(`Snippet not found: ${relativePath}`);
|
|
23
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { styleText } from "node:util";
|
|
2
|
+
|
|
3
|
+
const RATING_ICON = {
|
|
4
|
+
good: "🟢",
|
|
5
|
+
"needs-improvement": "🟡",
|
|
6
|
+
poor: "🔴",
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
const RATING_STYLE = {
|
|
10
|
+
good: "green",
|
|
11
|
+
"needs-improvement": "yellow",
|
|
12
|
+
poor: "red",
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
function formatValue(value, unit) {
|
|
16
|
+
if (unit === "ms") {
|
|
17
|
+
return value >= 1000 ? `${(value / 1000).toFixed(2)}s` : `${value}ms`;
|
|
18
|
+
}
|
|
19
|
+
if (unit === "score") return value.toFixed(4);
|
|
20
|
+
return String(value);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function paint(rating, text) {
|
|
24
|
+
return styleText(RATING_STYLE[rating] ?? "white", text);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function pad(text, len) {
|
|
28
|
+
const visibleLen = text.replace(/\[\d+m/g, "").length;
|
|
29
|
+
return text + " ".repeat(Math.max(0, len - visibleLen));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const DISPLAY_WARN = new Set(["block", "auto", "unknown"]);
|
|
33
|
+
|
|
34
|
+
function renderFontsResult(r) {
|
|
35
|
+
const d = r.details ?? {};
|
|
36
|
+
const lines = [];
|
|
37
|
+
|
|
38
|
+
lines.push(styleText("bold", ` Fonts — preloaded: ${d.preloadedCount ?? 0} loaded: ${d.loadedCount ?? 0} used above fold: ${d.usedAboveFoldCount ?? 0}`));
|
|
39
|
+
|
|
40
|
+
if (r.items?.length) {
|
|
41
|
+
lines.push("");
|
|
42
|
+
lines.push(styleText("dim", " Loaded fonts:"));
|
|
43
|
+
lines.push(styleText("dim", ` ${"Family".padEnd(20)} ${"Weight".padEnd(8)} ${"Style".padEnd(10)} Display`));
|
|
44
|
+
for (const f of r.items) {
|
|
45
|
+
const displayWarning = DISPLAY_WARN.has(f.display) ? styleText("yellow", ` ⚠ ${f.display}`) : styleText("green", ` ${f.display}`);
|
|
46
|
+
lines.push(` ${f.family.padEnd(20)} ${f.weight.padEnd(8)} ${f.style.padEnd(10)}${displayWarning}`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (r.usedFonts?.length) {
|
|
51
|
+
lines.push("");
|
|
52
|
+
lines.push(styleText("dim", " Used above fold:"));
|
|
53
|
+
lines.push(styleText("dim", ` ${"Family".padEnd(20)} ${"Weight".padEnd(8)} ${"Style".padEnd(10)} Elements`));
|
|
54
|
+
const sorted = [...r.usedFonts].sort((a, b) => b.elements - a.elements);
|
|
55
|
+
for (const f of sorted) {
|
|
56
|
+
lines.push(` ${f.family.padEnd(20)} ${f.weight.padEnd(8)} ${f.style.padEnd(10)} ${f.elements}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (r.issues?.length) {
|
|
61
|
+
lines.push("");
|
|
62
|
+
lines.push(styleText("dim", " Issues:"));
|
|
63
|
+
for (const issue of r.issues) {
|
|
64
|
+
const color = issue.severity === "error" ? "red" : "yellow";
|
|
65
|
+
lines.push(` ${styleText(color, issue.severity === "error" ? "✗" : "⚠")} ${issue.message}`);
|
|
66
|
+
}
|
|
67
|
+
} else {
|
|
68
|
+
lines.push("");
|
|
69
|
+
lines.push(` ${styleText("green", "✓")} Font loading looks optimized`);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return lines.join("\n");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function renderAuditResult(r, verbose) {
|
|
76
|
+
const lines = [];
|
|
77
|
+
const id = r.id ?? r.script;
|
|
78
|
+
const errors = (r.issues ?? []).filter((i) => i.severity === "error");
|
|
79
|
+
const warnings = (r.issues ?? []).filter((i) => i.severity === "warning");
|
|
80
|
+
|
|
81
|
+
const icon = errors.length ? "🔴" : warnings.length ? "🟡" : "🟢";
|
|
82
|
+
const countSuffix = r.count > 0 ? styleText("dim", ` (${r.count})`) : "";
|
|
83
|
+
lines.push(` ${icon} ${id}${countSuffix}`);
|
|
84
|
+
|
|
85
|
+
if (r.issues?.length) {
|
|
86
|
+
for (const issue of r.issues) {
|
|
87
|
+
const color = issue.severity === "error" ? "red" : issue.severity === "warning" ? "yellow" : "blue";
|
|
88
|
+
const sym = issue.severity === "error" ? "✗" : issue.severity === "warning" ? "⚠" : "ℹ";
|
|
89
|
+
lines.push(` ${styleText(color, sym)} ${issue.message}`);
|
|
90
|
+
}
|
|
91
|
+
} else {
|
|
92
|
+
lines.push(` ${styleText("green", "✓")} No issues`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const isGreen = errors.length === 0 && warnings.length === 0;
|
|
96
|
+
const MAX_ITEMS = 10;
|
|
97
|
+
const items = r.items ?? [];
|
|
98
|
+
if (items.length > 0 && (!isGreen || verbose)) {
|
|
99
|
+
lines.push("");
|
|
100
|
+
const shown = items.slice(0, MAX_ITEMS);
|
|
101
|
+
for (const item of shown) {
|
|
102
|
+
const name = item.shortName ?? item.resource ?? item.url ?? item.src ?? item.selector ?? item.filename ?? "";
|
|
103
|
+
const tag = item.type ?? item.tag ?? item.strategy ?? item.media ?? "";
|
|
104
|
+
const timing = item.responseEndMs != null ? `${item.responseEndMs}ms` : item.durationMs != null ? `${item.durationMs}ms` : "";
|
|
105
|
+
const cols = [tag, name, timing].filter(Boolean).join(" ");
|
|
106
|
+
lines.push(` ${styleText("dim", `· ${cols}`)}`);
|
|
107
|
+
}
|
|
108
|
+
if (items.length > MAX_ITEMS) {
|
|
109
|
+
lines.push(` ${styleText("dim", `… and ${items.length - MAX_ITEMS} more`)}`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (r.reason) {
|
|
114
|
+
lines.push(` ${styleText("dim", `↳ ${r.reason}`)}`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return lines.join("\n");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function renderResult(r, verbose) {
|
|
121
|
+
if (r.status === "error") {
|
|
122
|
+
return ` ${styleText("red", "✗")} ${pad(r.id, 16)} ${styleText("dim", r.error)}`;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (r.script === "Fonts-Preloaded-Loaded-and-used-above-the-fold") {
|
|
126
|
+
return renderFontsResult(r);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (Array.isArray(r.issues)) {
|
|
130
|
+
return renderAuditResult(r, verbose);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const icon = RATING_ICON[r.rating] ?? "·";
|
|
134
|
+
const valueText = paint(r.rating, formatValue(r.value, r.unit));
|
|
135
|
+
const ratingText = styleText("dim", r.rating ?? "");
|
|
136
|
+
const detail = r.details?.element ? styleText("dim", r.details.element) : "";
|
|
137
|
+
|
|
138
|
+
let out = ` ${icon} ${pad(r.id, 16)} ${pad(valueText, 10)} ${pad(ratingText, 20)} ${detail}`;
|
|
139
|
+
|
|
140
|
+
if (r.metric === "LCP" && r.details?.subParts) {
|
|
141
|
+
const sp = r.details.subParts;
|
|
142
|
+
const rows = [
|
|
143
|
+
["TTFB", sp.ttfb],
|
|
144
|
+
["Resource Load Delay", sp.resourceLoadDelay],
|
|
145
|
+
["Resource Load Time", sp.resourceLoadTime],
|
|
146
|
+
["Element Render Delay", sp.elementRenderDelay],
|
|
147
|
+
];
|
|
148
|
+
out += "\n";
|
|
149
|
+
out += rows
|
|
150
|
+
.map(([name, info]) => {
|
|
151
|
+
const status = info.overTarget ? styleText("red", "🔴") : styleText("green", "✓");
|
|
152
|
+
return ` ${status} ${pad(name, 22)} ${pad(`${info.value}ms`, 8)} ${pad(`${info.percent}%`, 6)}`;
|
|
153
|
+
})
|
|
154
|
+
.join("\n");
|
|
155
|
+
if (r.details.slowestPhase) {
|
|
156
|
+
out += `\n ${styleText("blue", "→ Slowest:")} ${r.details.slowestPhase}`;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (r.reason) {
|
|
161
|
+
out += `\n ${styleText("dim", `↳ ${r.reason}`)}`;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return out;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export function reportHuman({ url, navMs, results, pageErrors, verbose }) {
|
|
168
|
+
const lines = [];
|
|
169
|
+
lines.push(styleText(["bold"], `WebPerf Snippets — ${url}`));
|
|
170
|
+
lines.push(styleText("dim", `Navigated in ${navMs}ms`));
|
|
171
|
+
lines.push("");
|
|
172
|
+
for (const r of results) lines.push(renderResult(r, verbose));
|
|
173
|
+
if (pageErrors?.length) {
|
|
174
|
+
lines.push("");
|
|
175
|
+
lines.push(styleText("yellow", "Page errors during run:"));
|
|
176
|
+
for (const err of pageErrors) lines.push(` ${styleText("dim", err)}`);
|
|
177
|
+
}
|
|
178
|
+
return lines.join("\n");
|
|
179
|
+
}
|
package/src/runner.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { chromium } from "playwright";
|
|
2
|
+
|
|
3
|
+
export const VIEWPORT_PRESETS = {
|
|
4
|
+
mobile: { width: 375, height: 812 },
|
|
5
|
+
tablet: { width: 768, height: 1024 },
|
|
6
|
+
desktop: { width: 1280, height: 800 },
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
const DEFAULT_NAV_TIMEOUT = 30000;
|
|
10
|
+
|
|
11
|
+
// Snippets are IIFEs. Playwright evaluates a string as an expression, so we
|
|
12
|
+
// trim trailing semicolons to keep the IIFE call as a single expression and
|
|
13
|
+
// recover its return value in Node.
|
|
14
|
+
function toExpression(source) {
|
|
15
|
+
return source.trim().replace(/;\s*$/, "");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function runSnippets({
|
|
19
|
+
url,
|
|
20
|
+
items,
|
|
21
|
+
waitMs = 3000,
|
|
22
|
+
headless = true,
|
|
23
|
+
viewport = VIEWPORT_PRESETS.mobile,
|
|
24
|
+
navTimeout = DEFAULT_NAV_TIMEOUT,
|
|
25
|
+
}) {
|
|
26
|
+
const browser = await chromium.launch({ headless });
|
|
27
|
+
try {
|
|
28
|
+
const context = await browser.newContext({ viewport });
|
|
29
|
+
const page = await context.newPage();
|
|
30
|
+
|
|
31
|
+
const pageErrors = [];
|
|
32
|
+
page.on("pageerror", (err) => pageErrors.push(err.message));
|
|
33
|
+
|
|
34
|
+
const navStart = Date.now();
|
|
35
|
+
await page.goto(url, { waitUntil: "load", timeout: navTimeout });
|
|
36
|
+
if (waitMs > 0) await page.waitForTimeout(waitMs);
|
|
37
|
+
const navMs = Date.now() - navStart;
|
|
38
|
+
|
|
39
|
+
const results = [];
|
|
40
|
+
for (const item of items) {
|
|
41
|
+
try {
|
|
42
|
+
const result = await page.evaluate(toExpression(item.source));
|
|
43
|
+
if (result && typeof result === "object") {
|
|
44
|
+
results.push({ id: item.id, ...result });
|
|
45
|
+
} else {
|
|
46
|
+
results.push({
|
|
47
|
+
id: item.id,
|
|
48
|
+
status: "error",
|
|
49
|
+
error: "Snippet did not return an object — check the IIFE return statement",
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
} catch (err) {
|
|
53
|
+
results.push({ id: item.id, status: "error", error: err.message });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return { url, navMs, results, pageErrors };
|
|
58
|
+
} finally {
|
|
59
|
+
await browser.close();
|
|
60
|
+
}
|
|
61
|
+
}
|