shapewall 0.0.0-stage → 0.2.2
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/CHANGELOG.md +139 -0
- package/Dockerfile.agent +45 -0
- package/LICENSE +202 -0
- package/NOTICE +12 -0
- package/README.md +651 -2
- package/THIRD_PARTY.md +165 -0
- package/bin/shapewall.js +29 -0
- package/dist/agent/package-lock.json +8384 -0
- package/dist/client/assets/BoardChat-D5SFd8HE.js +28 -0
- package/dist/client/assets/BuzzDialog-HWXBy52W.js +1 -0
- package/dist/client/assets/ChecksPanel-DTdImWoD.js +1 -0
- package/dist/client/assets/History-CEv6b-av.js +1 -0
- package/dist/client/assets/LocalSettings-C4vriEVQ.js +1 -0
- package/dist/client/assets/Management-DCfhcEUY.js +1 -0
- package/dist/client/assets/QuickConnect-DQGgUsl1.js +1 -0
- package/dist/client/assets/ShareDialog-C_plIto0.js +2 -0
- package/dist/client/assets/app-update-dialog-2hPz_N9G.js +1 -0
- package/dist/client/assets/circle-x-BZMPi8Zf.js +1 -0
- package/dist/client/assets/index-ByQRKVit.css +2 -0
- package/dist/client/assets/index-DweQ8Qtu.js +29 -0
- package/dist/client/assets/refresh-cw-CRow0Nbq.js +1 -0
- package/dist/client/assets/runtime-Bft6x_6E.js +4 -0
- package/dist/client/assets/square-A8EnIYLR.js +1 -0
- package/dist/client/assets/tts-dist-DYlBQmwG.js +18 -0
- package/dist/client/assets/tts-en-g2p-BPUtBFGG.js +1 -0
- package/dist/client/assets/tts-ort-wasm-simd-threaded-qh98TCA_.wasm +0 -0
- package/dist/client/assets/tts-ort.wasm.bundle.min-rEkcs_ow.js +12 -0
- package/dist/client/assets/tts-rolldown-runtime-D8NudN84.js +1 -0
- package/dist/client/assets/tts-spacy-en-tokenizer-6SNMl--A.json +1 -0
- package/dist/client/assets/tts-tts.worker-Bzm6aWbv.js +1 -0
- package/dist/client/assets/tts-us_gold-DcjeNMH1.json +92589 -0
- package/dist/client/assets/tts-us_silver-C964mEB5.json +93363 -0
- package/dist/client/assets/ui-CLbws0rx.js +41 -0
- package/dist/client/build-info.json +1 -0
- package/dist/client/favicon.svg +7 -0
- package/dist/client/icons/apple-touch-icon.png +0 -0
- package/dist/client/icons/icon-192.png +0 -0
- package/dist/client/icons/icon-512.png +0 -0
- package/dist/client/icons/maskable-512.png +0 -0
- package/dist/client/index.html +25 -0
- package/dist/client/manifest.webmanifest +15 -0
- package/dist/client/sw.js +53 -0
- package/dist/client/theme-boot.js +27 -0
- package/dist/console/assets/LocalAccountsApp-BQCcmj3x.js +1 -0
- package/dist/console/assets/LocalConsole-Bb2FUDs7.js +1 -0
- package/dist/console/assets/app-update-dialog-DIeYepLZ.js +1 -0
- package/dist/console/assets/console-C7uJLLOn.js +51 -0
- package/dist/console/assets/console-R8IBY3Am.css +2 -0
- package/dist/console/build-info.json +1 -0
- package/dist/console/console.html +21 -0
- package/dist/console/favicon.svg +7 -0
- package/dist/console/icons/apple-touch-icon.png +0 -0
- package/dist/console/icons/icon-192.png +0 -0
- package/dist/console/icons/icon-512.png +0 -0
- package/dist/console/icons/maskable-512.png +0 -0
- package/dist/console/manifest.webmanifest +15 -0
- package/dist/console/theme-boot.js +27 -0
- package/docs/agent-hardening.md +342 -0
- package/docs/agent-recipes.md +187 -0
- package/docs/agent-workflow.md +320 -0
- package/docs/agents.md +894 -0
- package/docs/architecture.md +242 -0
- package/docs/buzz.md +140 -0
- package/docs/capture-warnings.md +57 -0
- package/docs/config.md +489 -0
- package/docs/deployment.md +289 -0
- package/docs/design-system.md +162 -0
- package/docs/github.md +107 -0
- package/docs/hosted.md +764 -0
- package/docs/images/board-overview.png +0 -0
- package/docs/images/journeys.png +0 -0
- package/docs/images/live-comment.png +0 -0
- package/docs/images/phone-comment.png +0 -0
- package/docs/images/phone-overview.png +0 -0
- package/docs/images/variant.png +0 -0
- package/docs/interaction-audits.md +40 -0
- package/docs/journeys.md +137 -0
- package/docs/local-accounts.md +80 -0
- package/docs/notifications.md +237 -0
- package/docs/page-checks.md +69 -0
- package/docs/performance.md +174 -0
- package/docs/starter-agent.md +325 -0
- package/docs/updates.md +87 -0
- package/examples/audits/interaction.audit.json +17 -0
- package/package.json +132 -4
- package/src/accounts/avatar.js +121 -0
- package/src/accounts/local.js +464 -0
- package/src/agent/acp/command.js +204 -0
- package/src/agent/acp/detect.js +75 -0
- package/src/agent/acp/sandbox.js +160 -0
- package/src/agent/agent-health.js +75 -0
- package/src/agent/backends/acp.js +1297 -0
- package/src/agent/backends/index.js +61 -0
- package/src/agent/backends/openai.js +308 -0
- package/src/agent/composer.js +221 -0
- package/src/agent/config.js +338 -0
- package/src/agent/context.js +191 -0
- package/src/agent/control.js +122 -0
- package/src/agent/errors.js +17 -0
- package/src/agent/feedback-loop.js +137 -0
- package/src/agent/manage.js +94 -0
- package/src/agent/next-steps.js +51 -0
- package/src/agent/owner-mcp.js +38 -0
- package/src/agent/plain-text.js +52 -0
- package/src/agent/ratings-core.js +213 -0
- package/src/agent/ratings.js +100 -0
- package/src/agent/reply-text.js +67 -0
- package/src/agent/routes.js +1065 -0
- package/src/agent/run.js +326 -0
- package/src/agent/settings-routes.js +704 -0
- package/src/agent/showable.js +23 -0
- package/src/agent/starter/approvals.js +181 -0
- package/src/agent/starter/build-image.js +90 -0
- package/src/agent/starter/cli.js +163 -0
- package/src/agent/starter/disk.js +53 -0
- package/src/agent/starter/doctor.js +180 -0
- package/src/agent/starter/egress-proxy.js +351 -0
- package/src/agent/starter/gate.js +90 -0
- package/src/agent/starter/loop.js +114 -0
- package/src/agent/starter/model-relay.js +289 -0
- package/src/agent/starter/pause.js +14 -0
- package/src/agent/starter/probe.js +272 -0
- package/src/agent/starter/prompt.js +41 -0
- package/src/agent/starter/push-guard.js +146 -0
- package/src/agent/starter/rpc.js +164 -0
- package/src/agent/starter/runtime.js +287 -0
- package/src/agent/starter/sandbox-main.js +121 -0
- package/src/agent/starter/settings.js +290 -0
- package/src/agent/starter/source.js +69 -0
- package/src/agent/starter/supervisor.js +755 -0
- package/src/agent/starter/sweep.js +46 -0
- package/src/agent/starter/tools.js +524 -0
- package/src/agent/starter/watch.js +84 -0
- package/src/agent/starter/worktree.js +409 -0
- package/src/agent/text-diff.js +210 -0
- package/src/agent/thread-history.js +223 -0
- package/src/agent/threads.js +399 -0
- package/src/agent/tools.js +200 -0
- package/src/agent/turn-changes.js +424 -0
- package/src/agent/undo-state.js +26 -0
- package/src/agent/user-settings.js +308 -0
- package/src/auth/record.js +375 -0
- package/src/broken-links.js +164 -0
- package/src/buzz/client.js +75 -0
- package/src/buzz/config.js +151 -0
- package/src/buzz/environment.js +13 -0
- package/src/buzz/gateway.js +192 -0
- package/src/buzz/routes.js +61 -0
- package/src/buzz/signer-child.js +205 -0
- package/src/buzz/store.js +89 -0
- package/src/buzz/transport.js +60 -0
- package/src/buzz/verify.js +140 -0
- package/src/capture/actions.js +159 -0
- package/src/capture/capture.js +776 -0
- package/src/capture/dom-names.js +189 -0
- package/src/capture/element-map.js +509 -0
- package/src/capture/live.js +827 -0
- package/src/capture/media-scheme.js +317 -0
- package/src/capture/network-summary.js +86 -0
- package/src/capture/pacing.js +34 -0
- package/src/capture/requests.js +167 -0
- package/src/capture/sanitize.js +752 -0
- package/src/checks/accessibility.js +134 -0
- package/src/checks/budgets.js +58 -0
- package/src/checks/cli.js +55 -0
- package/src/checks/comparison.js +113 -0
- package/src/checks/environments.js +32 -0
- package/src/checks/flow-config.js +82 -0
- package/src/checks/flow-origin.js +53 -0
- package/src/checks/flows.js +398 -0
- package/src/checks/lighthouse-auth.js +145 -0
- package/src/checks/lighthouse-findings.js +130 -0
- package/src/checks/lighthouse.js +395 -0
- package/src/checks/robots.js +85 -0
- package/src/checks/routes.js +52 -0
- package/src/checks/run-control.js +259 -0
- package/src/checks/runner.js +724 -0
- package/src/checks/schema.js +133 -0
- package/src/checks/seo-analysis.js +443 -0
- package/src/checks/seo-probe.js +190 -0
- package/src/checks/seo-snapshot.js +99 -0
- package/src/checks/store.js +214 -0
- package/src/checks/transport.js +47 -0
- package/src/cli/args.js +319 -0
- package/src/cli/capture.js +79 -0
- package/src/cli/commands.js +92 -0
- package/src/cli/comments.js +84 -0
- package/src/cli/help.js +243 -0
- package/src/cli/init.js +214 -0
- package/src/cli/misc.js +64 -0
- package/src/cli/notify.js +87 -0
- package/src/cli/open.js +22 -0
- package/src/cli/serve.js +274 -0
- package/src/cli/variant.js +82 -0
- package/src/cli/watch.js +70 -0
- package/src/cli.js +130 -0
- package/src/comment-fields.js +76 -0
- package/src/comments-cli.js +208 -0
- package/src/config-reload.js +100 -0
- package/src/config.js +1061 -0
- package/src/devices-cli.js +21 -0
- package/src/diff.js +95 -0
- package/src/discover.js +284 -0
- package/src/doctor.js +295 -0
- package/src/event-log.js +268 -0
- package/src/events-cli.js +102 -0
- package/src/events.js +113 -0
- package/src/export.js +119 -0
- package/src/feedback.js +246 -0
- package/src/github.js +551 -0
- package/src/hosted/LICENSE.md +105 -0
- package/src/hosted/access-cli.js +78 -0
- package/src/hosted/admin.js +682 -0
- package/src/hosted/agent-approvals.js +163 -0
- package/src/hosted/agent-policy.js +189 -0
- package/src/hosted/app.js +510 -0
- package/src/hosted/auth-routes.js +540 -0
- package/src/hosted/auth.js +536 -0
- package/src/hosted/backup.js +483 -0
- package/src/hosted/board-context.js +35 -0
- package/src/hosted/board-routes.js +486 -0
- package/src/hosted/board-view.js +94 -0
- package/src/hosted/clean-worker.js +24 -0
- package/src/hosted/cleaner.js +89 -0
- package/src/hosted/comments.js +355 -0
- package/src/hosted/console-routes.js +401 -0
- package/src/hosted/cookies.js +18 -0
- package/src/hosted/crypto.js +80 -0
- package/src/hosted/db.js +496 -0
- package/src/hosted/device-routes.js +175 -0
- package/src/hosted/device.js +233 -0
- package/src/hosted/events.js +63 -0
- package/src/hosted/guards.js +172 -0
- package/src/hosted/guest-view.js +65 -0
- package/src/hosted/http.js +39 -0
- package/src/hosted/import.js +300 -0
- package/src/hosted/mail.js +73 -0
- package/src/hosted/mcp-http.js +71 -0
- package/src/hosted/membership.js +114 -0
- package/src/hosted/operator.js +478 -0
- package/src/hosted/ops-cli.js +345 -0
- package/src/hosted/pages.js +146 -0
- package/src/hosted/permissions.js +113 -0
- package/src/hosted/presence.js +372 -0
- package/src/hosted/projects.js +124 -0
- package/src/hosted/public.js +109 -0
- package/src/hosted/push.js +622 -0
- package/src/hosted/quotas.js +115 -0
- package/src/hosted/ratelimit.js +96 -0
- package/src/hosted/rebind.js +316 -0
- package/src/hosted/retention.js +128 -0
- package/src/hosted/server.js +260 -0
- package/src/hosted/setup-link.js +64 -0
- package/src/hosted/setup.js +323 -0
- package/src/hosted/shares.js +444 -0
- package/src/hosted/tailscale.js +204 -0
- package/src/hosted/tenancy.js +301 -0
- package/src/hosted/token-api.js +455 -0
- package/src/hosted/token-events.js +60 -0
- package/src/hosted/tokens.js +57 -0
- package/src/hosted/turnstile.js +49 -0
- package/src/hosted/usercontent.js +154 -0
- package/src/hosted/zip.js +155 -0
- package/src/invocation.js +58 -0
- package/src/journey-paths.js +282 -0
- package/src/journeys.js +189 -0
- package/src/links.js +106 -0
- package/src/local-projects.js +182 -0
- package/src/lock.js +193 -0
- package/src/mcp.js +417 -0
- package/src/mentions.js +151 -0
- package/src/net.js +15 -0
- package/src/notify/config.js +275 -0
- package/src/notify/index.js +301 -0
- package/src/notify/lease.js +73 -0
- package/src/notify/messages.js +212 -0
- package/src/notify/run.js +174 -0
- package/src/pixeldiff.js +49 -0
- package/src/png.js +143 -0
- package/src/reactions.js +111 -0
- package/src/remote/cli.js +133 -0
- package/src/remote/credentials.js +62 -0
- package/src/remote/ids.js +12 -0
- package/src/remote/login.js +155 -0
- package/src/remote/remote-mcp.js +237 -0
- package/src/remote/remote-watch.js +291 -0
- package/src/remote/remote.js +313 -0
- package/src/remote/share-state.js +78 -0
- package/src/remote/share.js +369 -0
- package/src/remote/terminal.js +13 -0
- package/src/serve-state.js +64 -0
- package/src/server/app.js +824 -0
- package/src/server/devices.js +186 -0
- package/src/server/local-console.js +28 -0
- package/src/server/local-user.js +59 -0
- package/src/server/pairing-routes.js +159 -0
- package/src/server/share-routes.js +89 -0
- package/src/server/tailscale.js +97 -0
- package/src/sitemap.js +431 -0
- package/src/store.js +983 -0
- package/src/tokens.js +11 -0
- package/src/update/routes.js +245 -0
- package/src/watch.js +403 -0
- package/src/which.js +58 -0
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import { randomUUID } from 'node:crypto'
|
|
3
|
+
import { performance } from 'node:perf_hooks'
|
|
4
|
+
import { createRequire } from 'node:module'
|
|
5
|
+
import { authFor, boardViewports, getBoard, getEnvironment, joinUrl, selectPages, viewportDevice } from '../config.js'
|
|
6
|
+
import { launchBrowser, resolveStorageState } from '../capture/capture.js'
|
|
7
|
+
import { entryVersion, readManifest } from '../store.js'
|
|
8
|
+
import { fingerprint, reportId, validateReport } from './schema.js'
|
|
9
|
+
import { saveReport, targetFingerprint } from './store.js'
|
|
10
|
+
import { runAction } from '../capture/actions.js'
|
|
11
|
+
import { readFlow, normalizeFlow } from './flow-config.js'
|
|
12
|
+
import { installFlowOriginGuard } from './flow-origin.js'
|
|
13
|
+
import { AXE_VERSION, accessibilityFindings, inspectAccessibility } from './accessibility.js'
|
|
14
|
+
|
|
15
|
+
const require = createRequire(import.meta.url)
|
|
16
|
+
const PLAYWRIGHT_VERSION = require('playwright/package.json').version
|
|
17
|
+
export const FLOW_TIMEOUT_MS = 120000
|
|
18
|
+
export const STEP_TIMEOUT_MS = 20000
|
|
19
|
+
const safeFailure = (id, title, observation) => ({
|
|
20
|
+
id,
|
|
21
|
+
category: 'reliability',
|
|
22
|
+
severity: 'warning',
|
|
23
|
+
title,
|
|
24
|
+
observation,
|
|
25
|
+
impact: 'The requested state was not fully measured. Unknown values are not passing results.',
|
|
26
|
+
nextAction: 'Inspect the original configured state and explicit steps before running again.',
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
function baseReport(config, board, target, environment, viewport, kind, runId, sourceBuild, flowHash) {
|
|
30
|
+
const manifest = readManifest(config, board.id, environment.id)
|
|
31
|
+
return {
|
|
32
|
+
schemaVersion: 1,
|
|
33
|
+
id: reportId(),
|
|
34
|
+
runId,
|
|
35
|
+
boardId: board.id,
|
|
36
|
+
pageId: target.id,
|
|
37
|
+
environment: environment.id,
|
|
38
|
+
viewport: {
|
|
39
|
+
name: viewport,
|
|
40
|
+
width: boardViewports(config, board)[viewport].width,
|
|
41
|
+
height: boardViewports(config, board)[viewport].height,
|
|
42
|
+
},
|
|
43
|
+
captureVersion: entryVersion(manifest?.pages?.[target.id]?.[viewport], manifest),
|
|
44
|
+
sampledSeparately: true,
|
|
45
|
+
state: 'complete',
|
|
46
|
+
auditedAt: new Date().toISOString(),
|
|
47
|
+
profile: {
|
|
48
|
+
runner: kind === 'flow' ? 'playwright-flow' : 'axe',
|
|
49
|
+
version: kind === 'flow' ? PLAYWRIGHT_VERSION : AXE_VERSION,
|
|
50
|
+
mode: kind === 'flow' ? 'timespan' : 'snapshot',
|
|
51
|
+
cache: authFor(config, board).storageState || authFor(config, board).loginScript ? 'auth-preserved' : 'new-context',
|
|
52
|
+
authRole: authFor(config, board).storageState || authFor(config, board).loginScript ? 'configured' : 'anonymous',
|
|
53
|
+
sourceBuild: sourceBuild ? fingerprint(sourceBuild) : null,
|
|
54
|
+
stateFingerprint: targetFingerprint(config, board, target, environment, viewport),
|
|
55
|
+
seo: false,
|
|
56
|
+
production: 'unknown',
|
|
57
|
+
location: 'local',
|
|
58
|
+
sampleCount: 1,
|
|
59
|
+
throttling: { method: 'provided', rttMs: null, throughputKbps: null, cpuSlowdownMultiplier: null },
|
|
60
|
+
...(flowHash ? { flowHash } : {}),
|
|
61
|
+
...(kind === 'accessibility' ? { accessibilityVersion: AXE_VERSION } : {}),
|
|
62
|
+
},
|
|
63
|
+
completeness: {
|
|
64
|
+
window: kind === 'flow' ? 'explicit-flow' : 'accessibility-snapshot',
|
|
65
|
+
network: 'unavailable',
|
|
66
|
+
serviceWorker: null,
|
|
67
|
+
limitations:
|
|
68
|
+
kind === 'flow'
|
|
69
|
+
? [
|
|
70
|
+
'One explicit flow sample. Timing includes browser automation and configured readiness waits, not field interaction latency.',
|
|
71
|
+
'Configured page actions and visual journey paths were not replayed. A later state is separately sampled from the screenshot.',
|
|
72
|
+
]
|
|
73
|
+
: [
|
|
74
|
+
'Automated WCAG rules are not an accessibility certification. Keyboard and assistive technology review is still required.',
|
|
75
|
+
'Only the final top-level document is checked. Frames, closed shadow roots and external asset preloads are excluded.',
|
|
76
|
+
'At most ten thousand document elements are inspected. Raw page content and element selectors are not saved.',
|
|
77
|
+
],
|
|
78
|
+
},
|
|
79
|
+
metrics: {},
|
|
80
|
+
findings: [],
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// One invocation owns one fresh context, one target, one sample. Supplied browser
|
|
85
|
+
// instances are preserved; every context made for authentication is also tracked.
|
|
86
|
+
async function execute({
|
|
87
|
+
config,
|
|
88
|
+
boardId,
|
|
89
|
+
envId,
|
|
90
|
+
pageId,
|
|
91
|
+
viewport,
|
|
92
|
+
flow = null,
|
|
93
|
+
sourceBuild = null,
|
|
94
|
+
browser: suppliedBrowser = null,
|
|
95
|
+
signal,
|
|
96
|
+
}) {
|
|
97
|
+
if (
|
|
98
|
+
sourceBuild !== null &&
|
|
99
|
+
sourceBuild !== undefined &&
|
|
100
|
+
(typeof sourceBuild !== 'string' || !/^[A-Za-z0-9._-]{1,120}$/.test(sourceBuild))
|
|
101
|
+
)
|
|
102
|
+
throw new Error('Source build must be a short opaque build identifier.')
|
|
103
|
+
const board = getBoard(config, boardId),
|
|
104
|
+
environment = getEnvironment(board, envId)
|
|
105
|
+
const targets = selectPages(board, Array.isArray(pageId) ? pageId : [pageId])
|
|
106
|
+
if (targets.length !== 1) throw new Error('Select exactly one configured page for a flow or accessibility audit.')
|
|
107
|
+
const target = targets[0]
|
|
108
|
+
viewport = viewport || (target.viewports.includes('desktop') ? 'desktop' : target.viewports[0])
|
|
109
|
+
if (!target.viewports.includes(viewport)) throw new Error('Select one configured viewport for the selected page.')
|
|
110
|
+
const runId = randomUUID(),
|
|
111
|
+
flowHash = flow ? fingerprint(flow) : null
|
|
112
|
+
const main = baseReport(config, board, target, environment, viewport, flow ? 'flow' : 'accessibility', runId, sourceBuild, flowHash)
|
|
113
|
+
const reports = [main],
|
|
114
|
+
contexts = new Set()
|
|
115
|
+
const closing = new Map()
|
|
116
|
+
const closeContext = (context) => {
|
|
117
|
+
if (!closing.has(context))
|
|
118
|
+
closing.set(
|
|
119
|
+
context,
|
|
120
|
+
context.close().catch(() => {}),
|
|
121
|
+
)
|
|
122
|
+
return closing.get(context)
|
|
123
|
+
}
|
|
124
|
+
let guard
|
|
125
|
+
let browser = suppliedBrowser,
|
|
126
|
+
timer,
|
|
127
|
+
stopped = false,
|
|
128
|
+
stopReject
|
|
129
|
+
const stopPromise = new Promise((_, reject) => {
|
|
130
|
+
stopReject = reject
|
|
131
|
+
})
|
|
132
|
+
const stop = () => {
|
|
133
|
+
stopped = true
|
|
134
|
+
for (const c of contexts) closeContext(c)
|
|
135
|
+
stopReject(new Error('Audit stopped.'))
|
|
136
|
+
}
|
|
137
|
+
const deadline = Math.min(
|
|
138
|
+
FLOW_TIMEOUT_MS,
|
|
139
|
+
Math.max(1000, config.timeouts.page + config.timeouts.settle + 30000 + (flow?.steps.length || 0) * STEP_TIMEOUT_MS),
|
|
140
|
+
)
|
|
141
|
+
timer = setTimeout(stop, deadline)
|
|
142
|
+
signal?.addEventListener('abort', stop, { once: true })
|
|
143
|
+
if (signal?.aborted) stop()
|
|
144
|
+
const work = async () => {
|
|
145
|
+
if (stopped) throw new Error('Stopped')
|
|
146
|
+
if (!browser) {
|
|
147
|
+
browser = await launchBrowser(config)
|
|
148
|
+
if (stopped) {
|
|
149
|
+
await browser.close()
|
|
150
|
+
throw new Error('Stopped')
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const newContext = async (options) => {
|
|
154
|
+
if (stopped) throw new Error('Stopped')
|
|
155
|
+
const context = await browser.newContext(options)
|
|
156
|
+
contexts.add(context)
|
|
157
|
+
if (stopped) {
|
|
158
|
+
await closeContext(context)
|
|
159
|
+
throw new Error('Stopped')
|
|
160
|
+
}
|
|
161
|
+
return context
|
|
162
|
+
}
|
|
163
|
+
const storageState = await resolveStorageState({ newContext }, config, { ...board, baseUrl: environment.baseUrl })
|
|
164
|
+
if (stopped) throw new Error('Stopped')
|
|
165
|
+
if (storageState)
|
|
166
|
+
main.profile.authStateHash = fingerprint(
|
|
167
|
+
typeof storageState === 'string' ? JSON.parse(fs.readFileSync(storageState, 'utf8')) : storageState,
|
|
168
|
+
)
|
|
169
|
+
const size = boardViewports(config, board)[viewport]
|
|
170
|
+
const device = viewportDevice(viewport, size)
|
|
171
|
+
const context = await newContext({
|
|
172
|
+
viewport: { width: size.width, height: size.layoutHeight || size.height },
|
|
173
|
+
deviceScaleFactor: 1,
|
|
174
|
+
isMobile: device.mobile,
|
|
175
|
+
hasTouch: device.touch,
|
|
176
|
+
...(storageState ? { storageState } : {}),
|
|
177
|
+
})
|
|
178
|
+
const page = await context.newPage(),
|
|
179
|
+
original = joinUrl(environment.baseUrl, target.path)
|
|
180
|
+
guard = await installFlowOriginGuard(context, page, new URL(original).origin, closeContext)
|
|
181
|
+
const timeout = Math.min(STEP_TIMEOUT_MS, config.timeouts.page)
|
|
182
|
+
page.setDefaultTimeout(timeout)
|
|
183
|
+
const response = await page.goto(original, { waitUntil: 'load', timeout })
|
|
184
|
+
if (!(target.expectStatus?.length ? target.expectStatus.includes(response?.status()) : response?.status() < 400))
|
|
185
|
+
throw new Error('Unexpected status')
|
|
186
|
+
const initial = new URL(original),
|
|
187
|
+
arrived = new URL(page.url())
|
|
188
|
+
if (arrived.origin !== initial.origin || arrived.pathname !== initial.pathname || arrived.search !== initial.search)
|
|
189
|
+
throw new Error('Unexpected destination')
|
|
190
|
+
if ((authFor(config, board).storageState || authFor(config, board).loginScript) && !target.waitFor)
|
|
191
|
+
throw new Error('Signed in ready selector required')
|
|
192
|
+
if (target.waitFor) await page.locator(target.waitFor).waitFor({ state: 'visible', timeout })
|
|
193
|
+
main.profile.browser = { version: browser.version(), userAgentHash: fingerprint(await page.evaluate('navigator.userAgent')) }
|
|
194
|
+
main.profile.device = { mobile: device.mobile, deviceScaleFactor: 1, screenEmulationDisabled: false }
|
|
195
|
+
main.completeness.serviceWorker = await page.evaluate('!!navigator.serviceWorker?.controller')
|
|
196
|
+
if (flow) {
|
|
197
|
+
main.metrics = {
|
|
198
|
+
flowDurationMs: null,
|
|
199
|
+
completedSteps: 0,
|
|
200
|
+
configuredSteps: flow.steps.length,
|
|
201
|
+
...Object.fromEntries(flow.steps.map((_, i) => [`step${i + 1}DurationMs`, null])),
|
|
202
|
+
}
|
|
203
|
+
const started = performance.now()
|
|
204
|
+
for (let i = 0; i < flow.steps.length; i++) {
|
|
205
|
+
const step = flow.steps[i],
|
|
206
|
+
at = performance.now()
|
|
207
|
+
if (stopped) throw new Error('Stopped')
|
|
208
|
+
guard.assertOrigin()
|
|
209
|
+
let stepTimer
|
|
210
|
+
try {
|
|
211
|
+
await Promise.race([
|
|
212
|
+
(async () => {
|
|
213
|
+
await runAction(page, step.action, i, { timeout, viewport, label: 'step' })
|
|
214
|
+
guard.assertOrigin()
|
|
215
|
+
if (step.ready) await page.locator(step.ready).waitFor({ state: 'visible', timeout })
|
|
216
|
+
guard.assertOrigin()
|
|
217
|
+
})(),
|
|
218
|
+
new Promise((_, reject) => {
|
|
219
|
+
stepTimer = setTimeout(() => {
|
|
220
|
+
closeContext(context)
|
|
221
|
+
reject(new Error('Step deadline.'))
|
|
222
|
+
}, STEP_TIMEOUT_MS)
|
|
223
|
+
}),
|
|
224
|
+
])
|
|
225
|
+
} finally {
|
|
226
|
+
clearTimeout(stepTimer)
|
|
227
|
+
}
|
|
228
|
+
const elapsed = performance.now() - at
|
|
229
|
+
main.metrics[`step${i + 1}DurationMs`] = elapsed
|
|
230
|
+
main.metrics.completedSteps++
|
|
231
|
+
if (step.maxDurationMs !== null && elapsed > step.maxDurationMs)
|
|
232
|
+
main.findings.push({
|
|
233
|
+
id: `flow-step-${i + 1}-budget`,
|
|
234
|
+
category: 'performance',
|
|
235
|
+
severity: 'warning',
|
|
236
|
+
title: 'Configured interaction budget exceeded',
|
|
237
|
+
observation: `Step ${i + 1} took ${Math.round(elapsed)} milliseconds against a ${step.maxDurationMs} millisecond budget.`,
|
|
238
|
+
impact: 'This explicit lab interaction took longer than its configured budget. It is not a field responsiveness measurement.',
|
|
239
|
+
nextAction: 'Repeat deliberately with the same state and inspect the interaction and readiness conditions.',
|
|
240
|
+
})
|
|
241
|
+
}
|
|
242
|
+
main.metrics.flowDurationMs = performance.now() - started
|
|
243
|
+
} else {
|
|
244
|
+
// The page's configured actions, as a capture runs them (one at a time, origin checked around each).
|
|
245
|
+
for (const [index, a] of (target.actions || []).entries()) {
|
|
246
|
+
guard.assertOrigin()
|
|
247
|
+
await runAction(page, a, index, { timeout, viewport })
|
|
248
|
+
guard.assertOrigin()
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
guard.assertOrigin()
|
|
252
|
+
if (!flow || flow.accessibility) {
|
|
253
|
+
const audit = flow ? baseReport(config, board, target, environment, viewport, 'accessibility', runId, sourceBuild, flowHash) : main
|
|
254
|
+
if (flow) {
|
|
255
|
+
Object.assign(audit.profile, {
|
|
256
|
+
browser: main.profile.browser,
|
|
257
|
+
device: main.profile.device,
|
|
258
|
+
...(main.profile.authStateHash ? { authStateHash: main.profile.authStateHash } : {}),
|
|
259
|
+
})
|
|
260
|
+
reports.push(audit)
|
|
261
|
+
}
|
|
262
|
+
audit.completeness.serviceWorker = await page.evaluate('!!navigator.serviceWorker?.controller')
|
|
263
|
+
let axeTimer
|
|
264
|
+
try {
|
|
265
|
+
const result = await Promise.race([
|
|
266
|
+
inspectAccessibility(page),
|
|
267
|
+
new Promise((_, reject) => {
|
|
268
|
+
axeTimer = setTimeout(() => {
|
|
269
|
+
closeContext(context)
|
|
270
|
+
reject(new Error('Accessibility deadline.'))
|
|
271
|
+
}, 20000)
|
|
272
|
+
}),
|
|
273
|
+
])
|
|
274
|
+
if (result.unsupported) {
|
|
275
|
+
audit.state = 'unsupported'
|
|
276
|
+
audit.findings.push(
|
|
277
|
+
safeFailure(
|
|
278
|
+
'axe-size-limit',
|
|
279
|
+
'Accessibility snapshot exceeds the element limit',
|
|
280
|
+
'The document exceeded the bounded engine inspection size. No passing result was recorded.',
|
|
281
|
+
),
|
|
282
|
+
)
|
|
283
|
+
} else {
|
|
284
|
+
guard.assertOrigin()
|
|
285
|
+
const normalized = accessibilityFindings(result)
|
|
286
|
+
audit.metrics = normalized.metrics
|
|
287
|
+
audit.findings.push(...normalized.findings)
|
|
288
|
+
if (normalized.partial) audit.state = 'partial'
|
|
289
|
+
}
|
|
290
|
+
} catch {
|
|
291
|
+
audit.state = 'failed'
|
|
292
|
+
audit.findings.push(
|
|
293
|
+
safeFailure(
|
|
294
|
+
'axe-failed',
|
|
295
|
+
'Accessibility snapshot could not finish',
|
|
296
|
+
'The local accessibility engine could not inspect the requested final state.',
|
|
297
|
+
),
|
|
298
|
+
)
|
|
299
|
+
} finally {
|
|
300
|
+
clearTimeout(axeTimer)
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
guard.assertOrigin()
|
|
304
|
+
}
|
|
305
|
+
try {
|
|
306
|
+
await Promise.race([work(), stopPromise])
|
|
307
|
+
} catch {
|
|
308
|
+
const current = reports.at(-1)
|
|
309
|
+
current.state = 'failed'
|
|
310
|
+
current.findings.push(
|
|
311
|
+
safeFailure(
|
|
312
|
+
guard?.violated ? 'flow-origin-blocked' : stopped ? 'audit-stopped' : 'flow-failed',
|
|
313
|
+
guard?.violated
|
|
314
|
+
? 'Navigation outside the audit boundary was blocked'
|
|
315
|
+
: stopped
|
|
316
|
+
? 'Audit stopped before completion'
|
|
317
|
+
: 'Configured state could not be measured',
|
|
318
|
+
guard?.violated
|
|
319
|
+
? 'A document navigation or popup attempted to leave the audit boundary. No later configured actions were executed.'
|
|
320
|
+
: stopped
|
|
321
|
+
? 'The deadline or cancellation stopped this single sample. Completed steps were not replayed.'
|
|
322
|
+
: 'Navigation, authentication, an explicit step or its ready condition did not complete. Completed steps were not replayed.',
|
|
323
|
+
),
|
|
324
|
+
)
|
|
325
|
+
} finally {
|
|
326
|
+
stopped = true
|
|
327
|
+
clearTimeout(timer)
|
|
328
|
+
signal?.removeEventListener('abort', stop)
|
|
329
|
+
await Promise.allSettled([...contexts].map(closeContext))
|
|
330
|
+
if (!suppliedBrowser) await browser?.close().catch(() => {})
|
|
331
|
+
}
|
|
332
|
+
return Promise.all(reports.map((report) => saveReport(config, validateReport(report))))
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export function runFlowAudit(options) {
|
|
336
|
+
// Public input is always normalized; normalized actions are never accepted as
|
|
337
|
+
// an alternative way around the bounded explicit-file schema.
|
|
338
|
+
const flow = normalizeFlow(options.flow)
|
|
339
|
+
return execute({ ...options, pageId: flow.pageId, viewport: flow.viewport, flow })
|
|
340
|
+
}
|
|
341
|
+
export function runAccessibilityAudit(options) {
|
|
342
|
+
if (!options.pageId) throw new Error('Accessibility audits require one explicit configured page.')
|
|
343
|
+
return execute({ ...options, flow: null })
|
|
344
|
+
}
|
|
345
|
+
function output(reports, flags, out) {
|
|
346
|
+
out(
|
|
347
|
+
flags.json
|
|
348
|
+
? JSON.stringify({ schemaVersion: 1, reports }, null, 2)
|
|
349
|
+
: `Saved ${reports.length} private diagnostic reports from one explicit sample.`,
|
|
350
|
+
)
|
|
351
|
+
return reports.some((report) => report.state !== 'complete') ? 2 : 0
|
|
352
|
+
}
|
|
353
|
+
async function withCancellation(run) {
|
|
354
|
+
const controller = new AbortController()
|
|
355
|
+
const cancel = () => controller.abort()
|
|
356
|
+
process.on('SIGINT', cancel)
|
|
357
|
+
process.on('SIGTERM', cancel)
|
|
358
|
+
try {
|
|
359
|
+
return await run(controller.signal)
|
|
360
|
+
} finally {
|
|
361
|
+
process.off('SIGINT', cancel)
|
|
362
|
+
process.off('SIGTERM', cancel)
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
export async function flowCommand(config, _positional, flags, out, _err = () => {}) {
|
|
366
|
+
if (['only', 'viewport', 'seo', 'limit'].some((key) => flags[key] !== undefined && flags[key] !== null))
|
|
367
|
+
throw new Error('The flow file selects its page and viewport. Do not combine flow with other selection or navigation-check flags.')
|
|
368
|
+
const flow = readFlow(flags['flow-file'], config.dir)
|
|
369
|
+
const reports = await withCancellation((signal) =>
|
|
370
|
+
execute({
|
|
371
|
+
config,
|
|
372
|
+
boardId: flags.board,
|
|
373
|
+
envId: flags.env,
|
|
374
|
+
pageId: flow.pageId,
|
|
375
|
+
viewport: flow.viewport,
|
|
376
|
+
flow,
|
|
377
|
+
sourceBuild: flags['source-build'],
|
|
378
|
+
signal,
|
|
379
|
+
}),
|
|
380
|
+
)
|
|
381
|
+
return output(reports, flags, out)
|
|
382
|
+
}
|
|
383
|
+
export async function accessibilityCommand(config, _positional, flags, out, _err = () => {}) {
|
|
384
|
+
if (['flow-file', 'seo', 'limit'].some((key) => flags[key] !== undefined && flags[key] !== null))
|
|
385
|
+
throw new Error('Accessibility selects one page and viewport. Flow and navigation-check flags are not applicable.')
|
|
386
|
+
const reports = await withCancellation((signal) =>
|
|
387
|
+
runAccessibilityAudit({
|
|
388
|
+
config,
|
|
389
|
+
boardId: flags.board,
|
|
390
|
+
envId: flags.env,
|
|
391
|
+
pageId: flags.only,
|
|
392
|
+
viewport: flags.viewport,
|
|
393
|
+
sourceBuild: flags['source-build'],
|
|
394
|
+
signal,
|
|
395
|
+
}),
|
|
396
|
+
)
|
|
397
|
+
return output(reports, flags, out)
|
|
398
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import { fingerprint } from './schema.js'
|
|
3
|
+
|
|
4
|
+
export class AuditTargetError extends Error {
|
|
5
|
+
constructor(code) {
|
|
6
|
+
super(code)
|
|
7
|
+
this.code = code
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const unsupported = () => {
|
|
12
|
+
throw new AuditTargetError('unsupported-auth')
|
|
13
|
+
}
|
|
14
|
+
const cookieKeys = new Set(['name', 'value', 'domain', 'path', 'expires', 'httpOnly', 'secure', 'sameSite'])
|
|
15
|
+
|
|
16
|
+
// Playwright storage state is not a Lighthouse flag. Translate only the
|
|
17
|
+
// cookie and localStorage state supported by this prepared Chromium adapter.
|
|
18
|
+
export function translateStorageState(input) {
|
|
19
|
+
let state = input
|
|
20
|
+
if (typeof input === 'string') {
|
|
21
|
+
if (fs.statSync(input).size > 1024 * 1024) unsupported()
|
|
22
|
+
state = JSON.parse(fs.readFileSync(input, 'utf8'))
|
|
23
|
+
}
|
|
24
|
+
if (!state) unsupported()
|
|
25
|
+
if (
|
|
26
|
+
Object.keys(state).some((key) => !['cookies', 'origins'].includes(key)) ||
|
|
27
|
+
!Array.isArray(state.cookies) ||
|
|
28
|
+
!Array.isArray(state.origins) ||
|
|
29
|
+
state.cookies.length > 200 ||
|
|
30
|
+
state.origins.length > 20
|
|
31
|
+
)
|
|
32
|
+
unsupported()
|
|
33
|
+
const cookies = state.cookies.map((cookie) => {
|
|
34
|
+
if (!cookie || Object.keys(cookie).some((key) => !cookieKeys.has(key))) unsupported()
|
|
35
|
+
if (![cookie.name, cookie.value, cookie.domain, cookie.path].every((s) => typeof s === 'string')) unsupported()
|
|
36
|
+
if (!['Strict', 'Lax', 'None', undefined].includes(cookie.sameSite)) unsupported()
|
|
37
|
+
if (cookie.expires !== undefined && !Number.isFinite(cookie.expires)) unsupported()
|
|
38
|
+
const converted = { ...cookie }
|
|
39
|
+
if (converted.expires === -1) delete converted.expires
|
|
40
|
+
return converted
|
|
41
|
+
})
|
|
42
|
+
const origins = state.origins.map((entry) => {
|
|
43
|
+
if (
|
|
44
|
+
!entry ||
|
|
45
|
+
(Object.hasOwn(entry, 'indexedDB') && (!Array.isArray(entry.indexedDB) || entry.indexedDB.length)) ||
|
|
46
|
+
Object.keys(entry).some((key) => !['origin', 'localStorage', 'indexedDB'].includes(key))
|
|
47
|
+
)
|
|
48
|
+
unsupported()
|
|
49
|
+
let url
|
|
50
|
+
try {
|
|
51
|
+
url = new URL(entry.origin)
|
|
52
|
+
} catch {
|
|
53
|
+
unsupported()
|
|
54
|
+
}
|
|
55
|
+
if (
|
|
56
|
+
!['http:', 'https:'].includes(url.protocol) ||
|
|
57
|
+
entry.origin !== url.origin ||
|
|
58
|
+
!Array.isArray(entry.localStorage) ||
|
|
59
|
+
entry.localStorage.length > 200
|
|
60
|
+
)
|
|
61
|
+
unsupported()
|
|
62
|
+
for (const item of entry.localStorage) if (!item || typeof item.name !== 'string' || typeof item.value !== 'string') unsupported()
|
|
63
|
+
return { origin: entry.origin, localStorage: entry.localStorage.map(({ name, value }) => ({ name, value })) }
|
|
64
|
+
})
|
|
65
|
+
if (Buffer.byteLength(JSON.stringify({ cookies, origins })) > 1024 * 1024) unsupported()
|
|
66
|
+
return { cookies, origins, hash: fingerprint({ cookies, origins }) }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export async function applyStorageState(page, prepared) {
|
|
70
|
+
if (prepared.cookies.length) await page.browserContext().setCookie(...prepared.cookies)
|
|
71
|
+
if (prepared.origins.length)
|
|
72
|
+
await page.evaluateOnNewDocument((origins) => {
|
|
73
|
+
// eslint-disable-next-line no-undef -- evaluated in the target browser
|
|
74
|
+
const entry = origins.find((item) => item.origin === location.origin)
|
|
75
|
+
if (entry) for (const item of entry.localStorage) localStorage.setItem(item.name, item.value)
|
|
76
|
+
}, prepared.origins)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function sameTarget(actual, expected) {
|
|
80
|
+
try {
|
|
81
|
+
const a = new URL(actual),
|
|
82
|
+
b = new URL(expected)
|
|
83
|
+
const pathname = (url) => url.pathname.replace(/\/+$/, '') || '/'
|
|
84
|
+
return a.origin === b.origin && pathname(a) === pathname(b) && a.search === b.search
|
|
85
|
+
} catch {
|
|
86
|
+
return false
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Lighthouse runs the original action set only; the app-capture actions and
|
|
91
|
+
// options (tap, mouse, hold, waitForFunction, optional, viewports, ...) and a
|
|
92
|
+
// page timeout or localStorage seed are reported as unsupported, not half-run.
|
|
93
|
+
const LIGHTHOUSE_ACTIONS = ['click', 'fill', 'press', 'hover', 'wait', 'waitFor', 'scrollTo']
|
|
94
|
+
export function assertSupportedActions(page) {
|
|
95
|
+
if (
|
|
96
|
+
page.localStorage ||
|
|
97
|
+
(page.actions || []).some(
|
|
98
|
+
(action) => !LIGHTHOUSE_ACTIONS.includes(action.type) || action.optional || action.viewports || action.force || action.timeout,
|
|
99
|
+
)
|
|
100
|
+
)
|
|
101
|
+
throw new AuditTargetError('unsupported-actions')
|
|
102
|
+
const selectors = [page.waitFor, ...(page.actions || []).map((action) => action.selector)].filter(Boolean)
|
|
103
|
+
if (selectors.some((selector) => /^(?:text|role|xpath|id|data-testid)=|>>|:has-text\(/.test(selector)))
|
|
104
|
+
throw new AuditTargetError('unsupported-actions')
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function verifyTarget(page, expected, pageConfig, timeout) {
|
|
108
|
+
if (!sameTarget(page.url(), expected)) throw new AuditTargetError('wrong-target')
|
|
109
|
+
if (pageConfig.waitFor) {
|
|
110
|
+
try {
|
|
111
|
+
await page.waitForSelector(pageConfig.waitFor, { visible: true, timeout })
|
|
112
|
+
} catch {
|
|
113
|
+
throw new AuditTargetError('not-ready')
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (!sameTarget(page.url(), expected)) throw new AuditTargetError('wrong-target')
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export async function runConfiguredActions(page, actions, timeout) {
|
|
120
|
+
for (const action of actions || []) {
|
|
121
|
+
if (action.type === 'click') await page.locator(action.selector).setTimeout(timeout).click()
|
|
122
|
+
else if (action.type === 'fill') await page.locator(action.selector).setTimeout(timeout).fill(action.value)
|
|
123
|
+
else if (action.type === 'hover') await page.locator(action.selector).setTimeout(timeout).hover()
|
|
124
|
+
else if (action.type === 'wait') await new Promise((resolve) => setTimeout(resolve, action.ms))
|
|
125
|
+
else if (action.type === 'waitFor') await page.waitForSelector(action.selector, { visible: true, timeout })
|
|
126
|
+
// eslint-disable-next-line no-undef -- evaluated in the target browser
|
|
127
|
+
else if (action.type === 'scrollTo') await page.evaluate((y) => scrollTo(0, y), action.y)
|
|
128
|
+
else if (action.type === 'press') {
|
|
129
|
+
const keys = action.key.split('+'),
|
|
130
|
+
key = keys.pop(),
|
|
131
|
+
held = []
|
|
132
|
+
try {
|
|
133
|
+
for (const modifier of keys) {
|
|
134
|
+
const name = modifier === 'ControlOrMeta' ? (process.platform === 'darwin' ? 'Meta' : 'Control') : modifier
|
|
135
|
+
if (!['Control', 'Meta', 'Alt', 'Shift'].includes(name)) throw new AuditTargetError('unsupported-actions')
|
|
136
|
+
await page.keyboard.down(name)
|
|
137
|
+
held.push(name)
|
|
138
|
+
}
|
|
139
|
+
await page.keyboard.press(key)
|
|
140
|
+
} finally {
|
|
141
|
+
for (const modifier of held.reverse()) await page.keyboard.up(modifier)
|
|
142
|
+
}
|
|
143
|
+
} else throw new AuditTargetError('unsupported-actions')
|
|
144
|
+
}
|
|
145
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// Pinned-runner observations, with deliberately static public-safe text.
|
|
2
|
+
// Resource URLs, DOM snippets, selectors and upstream error text stay out.
|
|
3
|
+
const OPPORTUNITIES = {
|
|
4
|
+
'render-blocking-insight': [
|
|
5
|
+
'Render blocking resources',
|
|
6
|
+
'Some resources delay the first visible content.',
|
|
7
|
+
'Defer noncritical scripts and styles, then audit the same page again.',
|
|
8
|
+
],
|
|
9
|
+
'unused-css-rules': [
|
|
10
|
+
'Unused styles',
|
|
11
|
+
'Styles were downloaded that were not used during this navigation.',
|
|
12
|
+
'Split critical styles from styles used only by other views.',
|
|
13
|
+
],
|
|
14
|
+
'unused-javascript': [
|
|
15
|
+
'Unused JavaScript',
|
|
16
|
+
'JavaScript was downloaded that was not used during this navigation.',
|
|
17
|
+
'Load optional features when they are needed and reduce the initial bundle.',
|
|
18
|
+
],
|
|
19
|
+
'image-delivery-insight': [
|
|
20
|
+
'Image delivery',
|
|
21
|
+
'The runner identified image delivery savings.',
|
|
22
|
+
'Resize and compress image assets for the displayed dimensions.',
|
|
23
|
+
],
|
|
24
|
+
'total-byte-weight': [
|
|
25
|
+
'Resource weight',
|
|
26
|
+
'The navigation downloaded a large resource payload.',
|
|
27
|
+
'Review large initial resources and remove unnecessary transfers.',
|
|
28
|
+
],
|
|
29
|
+
'font-display-insight': [
|
|
30
|
+
'Font display',
|
|
31
|
+
'Font loading can delay visible text.',
|
|
32
|
+
'Use an appropriate font display policy and preload only critical fonts.',
|
|
33
|
+
],
|
|
34
|
+
'legacy-javascript-insight': [
|
|
35
|
+
'Legacy JavaScript',
|
|
36
|
+
'The runner identified JavaScript intended for older browsers.',
|
|
37
|
+
'Review the browser target and avoid unnecessary polyfills for supported clients.',
|
|
38
|
+
],
|
|
39
|
+
'duplicated-javascript-insight': [
|
|
40
|
+
'Duplicate JavaScript',
|
|
41
|
+
'The runner identified duplicated JavaScript.',
|
|
42
|
+
'Deduplicate shared dependencies and review bundle boundaries.',
|
|
43
|
+
],
|
|
44
|
+
'forced-reflow-insight': [
|
|
45
|
+
'Forced layout work',
|
|
46
|
+
'Script activity triggered layout work during navigation.',
|
|
47
|
+
'Batch layout reads and writes and audit the same profile again.',
|
|
48
|
+
],
|
|
49
|
+
'dom-size-insight': [
|
|
50
|
+
'Document size',
|
|
51
|
+
'The runner identified document structure overhead.',
|
|
52
|
+
'Reduce unnecessary elements in the initially rendered view.',
|
|
53
|
+
],
|
|
54
|
+
'errors-in-console': [
|
|
55
|
+
'Browser errors',
|
|
56
|
+
'The runner observed browser errors during navigation.',
|
|
57
|
+
'Reproduce this page locally and inspect its browser console.',
|
|
58
|
+
],
|
|
59
|
+
deprecations: [
|
|
60
|
+
'Deprecated browser behavior',
|
|
61
|
+
'The runner identified deprecated browser behavior.',
|
|
62
|
+
'Review browser deprecation warnings and update the affected implementation.',
|
|
63
|
+
],
|
|
64
|
+
'uses-document-write': [
|
|
65
|
+
'Blocking document writes',
|
|
66
|
+
'The page uses document writes that may block rendering.',
|
|
67
|
+
'Replace blocking document writes with normal document updates.',
|
|
68
|
+
],
|
|
69
|
+
'no-vulnerable-libraries': [
|
|
70
|
+
'Dependency review',
|
|
71
|
+
'The runner identified a dependency requiring review.',
|
|
72
|
+
'Review the installed dependency versions against their maintained releases.',
|
|
73
|
+
],
|
|
74
|
+
}
|
|
75
|
+
export const finiteMetric = (value) => (typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1e15 ? value : null)
|
|
76
|
+
|
|
77
|
+
export function lighthouseMetrics(lhr) {
|
|
78
|
+
const audits = lhr?.audits || {}
|
|
79
|
+
const value = (id) => finiteMetric(audits[id]?.numericValue)
|
|
80
|
+
const resources = audits['network-requests']?.details?.items
|
|
81
|
+
const sizes = Array.isArray(resources) ? resources.map((item) => finiteMetric(item.transferSize)) : null
|
|
82
|
+
return {
|
|
83
|
+
largestContentfulPaintMs: value('largest-contentful-paint'),
|
|
84
|
+
cumulativeLayoutShift: value('cumulative-layout-shift'),
|
|
85
|
+
firstContentfulPaintMs: value('first-contentful-paint'),
|
|
86
|
+
totalBlockingTimeMs: value('total-blocking-time'),
|
|
87
|
+
speedIndexMs: value('speed-index'),
|
|
88
|
+
lighthouseLabScore: finiteMetric(lhr?.categories?.performance?.score == null ? null : lhr.categories.performance.score * 100),
|
|
89
|
+
lighthouseSeoLabScore: finiteMetric(lhr?.categories?.seo?.score == null ? null : lhr.categories.seo.score * 100),
|
|
90
|
+
transferredResourceBytes: sizes?.every((size) => size !== null) ? finiteMetric(sizes.reduce((a, b) => a + b, 0)) : null,
|
|
91
|
+
observedRequests: Array.isArray(resources) ? resources.length : null,
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function lighthouseFindings(lhr, cap = 10) {
|
|
96
|
+
return Object.entries(OPPORTUNITIES)
|
|
97
|
+
.map(([id, [title, observation, nextAction]]) => {
|
|
98
|
+
const audit = lhr?.audits?.[id]
|
|
99
|
+
if (
|
|
100
|
+
!audit ||
|
|
101
|
+
typeof audit.score !== 'number' ||
|
|
102
|
+
!Number.isFinite(audit.score) ||
|
|
103
|
+
audit.score < 0 ||
|
|
104
|
+
audit.score >= 1 ||
|
|
105
|
+
['notApplicable', 'manual', 'error'].includes(audit.scoreDisplayMode)
|
|
106
|
+
)
|
|
107
|
+
return null
|
|
108
|
+
const saving =
|
|
109
|
+
finiteMetric(audit.details?.overallSavingsMs) ||
|
|
110
|
+
finiteMetric(audit.metricSavings?.LCP) ||
|
|
111
|
+
finiteMetric(audit.metricSavings?.FCP) ||
|
|
112
|
+
0
|
|
113
|
+
return {
|
|
114
|
+
saving,
|
|
115
|
+
finding: {
|
|
116
|
+
id,
|
|
117
|
+
category: 'performance',
|
|
118
|
+
severity: audit.score < 0.5 ? 'warning' : 'advisory',
|
|
119
|
+
title,
|
|
120
|
+
observation: saving ? `${observation} Estimated saving ${Math.round(saving)} ms.` : observation,
|
|
121
|
+
impact: 'This can affect load speed or implementation quality for this lab profile.',
|
|
122
|
+
nextAction,
|
|
123
|
+
},
|
|
124
|
+
}
|
|
125
|
+
})
|
|
126
|
+
.filter(Boolean)
|
|
127
|
+
.sort((a, b) => b.saving - a.saving)
|
|
128
|
+
.slice(0, cap)
|
|
129
|
+
.map((item) => item.finding)
|
|
130
|
+
}
|