@kerf-js/cli 0.0.0-stage → 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/LICENSE +16 -0
- package/README.md +554 -2
- package/bin/kerf.mjs +15 -0
- package/docs/async.md +50 -0
- package/docs/browser.md +53 -0
- package/docs/config.md +127 -0
- package/docs/core.md +30 -0
- package/docs/deploy.md +108 -0
- package/docs/design.md +106 -0
- package/docs/entrypoints.md +83 -0
- package/docs/fonts.md +118 -0
- package/docs/icons.md +108 -0
- package/docs/lists.md +25 -0
- package/docs/meta.md +92 -0
- package/docs/plugins.md +166 -0
- package/docs/props.md +88 -0
- package/docs/reactivity.md +26 -0
- package/docs/rules.md +39 -0
- package/docs/rust.md +253 -0
- package/docs/start-short.md +10 -0
- package/docs/start.md +642 -0
- package/docs/state.md +122 -0
- package/docs/style.md +82 -0
- package/docs/surface.md +158 -0
- package/docs/testing.md +81 -0
- package/docs/theme.md +263 -0
- package/docs/ui-state.md +105 -0
- package/docs/verify.md +61 -0
- package/package.json +47 -3
- package/src/add/config.mjs +93 -0
- package/src/add/errors.mjs +2 -0
- package/src/add/setup.mjs +88 -0
- package/src/add-rust.mjs +178 -0
- package/src/add.mjs +392 -0
- package/src/agents-md.mjs +240 -0
- package/src/alias.mjs +70 -0
- package/src/audit/page.mjs +313 -0
- package/src/audit/report.mjs +69 -0
- package/src/audit/utils.mjs +5 -0
- package/src/audit.mjs +319 -0
- package/src/browser/cli.mjs +53 -0
- package/src/browser/client.mjs +299 -0
- package/src/browser/commands.mjs +258 -0
- package/src/capture.mjs +21 -0
- package/src/catalog/audit.mjs +129 -0
- package/src/catalog/auth.mjs +40 -0
- package/src/catalog/compiler.mjs +337 -0
- package/src/catalog/contracts.mjs +18 -0
- package/src/catalog/database.mjs +52 -0
- package/src/catalog/deploy.mjs +117 -0
- package/src/catalog/design.mjs +159 -0
- package/src/catalog/forms.mjs +25 -0
- package/src/catalog/hydration.mjs +29 -0
- package/src/catalog/icons.mjs +24 -0
- package/src/catalog/media.mjs +163 -0
- package/src/catalog/metadata.mjs +116 -0
- package/src/catalog/plugins.mjs +228 -0
- package/src/catalog/realtime.mjs +195 -0
- package/src/catalog/rust.mjs +75 -0
- package/src/catalog/server-functions.mjs +100 -0
- package/src/catalog/state.mjs +39 -0
- package/src/catalog/style-groups.mjs +54 -0
- package/src/catalog/tests.mjs +127 -0
- package/src/catalog/text.mjs +200 -0
- package/src/catalog/ui-state.mjs +42 -0
- package/src/catalog.mjs +103 -0
- package/src/check/runtime.mjs +280 -0
- package/src/check.mjs +321 -0
- package/src/cli/authoring.mjs +213 -0
- package/src/cli/project.mjs +302 -0
- package/src/cli.mjs +340 -0
- package/src/config.d.ts +1 -0
- package/src/config.mjs +5 -0
- package/src/contributions.mjs +119 -0
- package/src/db-layer.mjs +41 -0
- package/src/deploy/cdn.mjs +142 -0
- package/src/deploy/files.mjs +266 -0
- package/src/deploy/fit.mjs +166 -0
- package/src/deploy/hosts.mjs +126 -0
- package/src/deploy/index/cli.mjs +20 -0
- package/src/deploy/index/environment.mjs +69 -0
- package/src/deploy/index/steps.mjs +87 -0
- package/src/deploy/index.mjs +387 -0
- package/src/deploy/needs.mjs +149 -0
- package/src/design-checks/accessible-names.mjs +62 -0
- package/src/design-checks/contrast.mjs +43 -0
- package/src/design-checks/csp.mjs +60 -0
- package/src/design-checks/files.mjs +59 -0
- package/src/design-checks/heading-links.mjs +61 -0
- package/src/design-checks/interaction.mjs +65 -0
- package/src/design-checks/jsx.mjs +67 -0
- package/src/design-checks/layout-values.mjs +68 -0
- package/src/design-checks/native-controls.mjs +48 -0
- package/src/design-checks/outline.mjs +39 -0
- package/src/design-checks/reporter.mjs +37 -0
- package/src/design-checks/rules.mjs +274 -0
- package/src/design-checks/values.mjs +262 -0
- package/src/design-checks.mjs +49 -0
- package/src/diag.mjs +98 -0
- package/src/docs.mjs +228 -0
- package/src/doctor.mjs +42 -0
- package/src/files.mjs +60 -0
- package/src/fix.mjs +48 -0
- package/src/gate/after.mjs +40 -0
- package/src/gate/before.mjs +54 -0
- package/src/gate/classify.mjs +72 -0
- package/src/gate/mutation.mjs +209 -0
- package/src/gate/resolve-cases.mjs +22 -0
- package/src/gate/result.mjs +63 -0
- package/src/gate/run.mjs +75 -0
- package/src/gate.mjs +178 -0
- package/src/index.mjs +9 -0
- package/src/infer/box-props.cjs +140 -0
- package/src/infer/core-boxes.cjs +46 -0
- package/src/infer/derived-writes.cjs +95 -0
- package/src/infer/engine/checks.cjs +193 -0
- package/src/infer/engine/flow.cjs +293 -0
- package/src/infer/engine/report.cjs +158 -0
- package/src/infer/engine/utils.cjs +15 -0
- package/src/infer/engine.cjs +265 -0
- package/src/infer/facts/sites.cjs +114 -0
- package/src/infer/facts.cjs +345 -0
- package/src/infer/hosts.cjs +161 -0
- package/src/infer/lsp.mjs +240 -0
- package/src/infer/session.cjs +161 -0
- package/src/infer/shadow.cjs +54 -0
- package/src/infer/worker.cjs +145 -0
- package/src/jsx-scan.mjs +128 -0
- package/src/kerf.mjs +98 -0
- package/src/load-config/schema.mjs +300 -0
- package/src/load-config.mjs +302 -0
- package/src/map.mjs +177 -0
- package/src/mcp/browser-tools.mjs +155 -0
- package/src/mcp.mjs +273 -0
- package/src/meta-table.mjs +63 -0
- package/src/mutate.mjs +224 -0
- package/src/plugin-checks.mjs +118 -0
- package/src/plugins.mjs +258 -0
- package/src/project.mjs +310 -0
- package/src/props-checks.mjs +64 -0
- package/src/props-listener.mjs +56 -0
- package/src/react-checks.mjs +67 -0
- package/src/server-state-checks.mjs +34 -0
- package/src/share-checks.mjs +158 -0
- package/src/site.mjs +46 -0
- package/src/slots.mjs +181 -0
- package/src/start/build.mjs +116 -0
- package/src/start/routes.mjs +38 -0
- package/src/start.mjs +394 -0
- package/src/state-checks/core-state.mjs +223 -0
- package/src/state-checks/modules.mjs +17 -0
- package/src/state-checks/scan.mjs +232 -0
- package/src/state-checks/server-graph.mjs +65 -0
- package/src/state-checks.mjs +189 -0
- package/src/style/find.mjs +121 -0
- package/src/style.mjs +327 -0
- package/src/surface-checks.mjs +384 -0
- package/src/tailwind.mjs +23 -0
- package/src/tasks.mjs +261 -0
- package/src/test-rules/context.mjs +109 -0
- package/src/test-rules/file-rules.mjs +279 -0
- package/src/test-rules/rule-helpers.mjs +244 -0
- package/src/test-rules/syntax.mjs +223 -0
- package/src/test-rules/test-rules.mjs +127 -0
- package/src/testdiff.mjs +219 -0
- package/src/tests.mjs +120 -0
- package/src/text-checks.mjs +332 -0
- package/src/tokens.mjs +33 -0
- package/src/trust/scan.mjs +95 -0
- package/src/trust.mjs +394 -0
- package/src/workspace.mjs +182 -0
- package/ts-plugin/context.js +57 -0
- package/ts-plugin/index.js +17 -0
- package/ts-plugin/mapping.js +65 -0
- package/ts-plugin/package.json +1 -0
- package/ts-plugin/proxy.js +144 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { diagnostic } from '../diag.mjs'
|
|
2
|
+
|
|
3
|
+
/** What a rule means in a veneer app, where veneer is how it usually happens. */
|
|
4
|
+
const VENEER = {
|
|
5
|
+
'heading-order':
|
|
6
|
+
"veneer's titled parts (Accordion, Chart, ActivityFeed) are h3, for a page section under an h2: one placed elsewhere takes `level`, or the place gets the heading it lacks. ",
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const say = {
|
|
10
|
+
L001: (f) =>
|
|
11
|
+
`${f.tag} (\`${f.selector}\`) has no accessible name (${f.rule}): a screen reader announces only its role. When the source has text, CSS hid it at this width.`,
|
|
12
|
+
L002: (f) =>
|
|
13
|
+
`${f.tag} (\`${f.selector}\`) is an image with no text alternative (${f.rule}): a screen reader reads its file name.`,
|
|
14
|
+
L003: (f) =>
|
|
15
|
+
`${f.tag} (\`${f.selector}\`): ${f.contrast ? `${f.contrast.fgColor} on ${f.contrast.bgColor} is ${f.contrast.contrastRatio}:1 at ${f.contrast.fontSize}, under ${f.contrast.expectedContrastRatio}` : 'its text contrast is too low'}.`,
|
|
16
|
+
L004: (f) => `${f.tag} (\`${f.selector}\`): ${f.help} (axe \`${f.rule}\`).`,
|
|
17
|
+
L031: (f) =>
|
|
18
|
+
`The layout moved by ${f.cls} (CLS) while the page loaded, with no one touching it${f.moved.length ? `: ${f.moved.join(', ')} moved` : ''}. Over 0.1 costs Lighthouse's Performance score.`,
|
|
19
|
+
L010: (f) => `Console error${f.at ? ` at ${f.at}` : ''}: ${f.text}`,
|
|
20
|
+
L011: (f) =>
|
|
21
|
+
f.at === '/favicon.ico'
|
|
22
|
+
? 'The page names no icon, so the browser asked for /favicon.ico and got a 404: Lighthouse counts it as a console error. Add `<link rel="icon">` through `site.head`, or a `public/favicon.ico`.'
|
|
23
|
+
: `The browser logged an error${f.at ? ` for ${f.at}` : ''}: ${f.text}`,
|
|
24
|
+
L012: (f) =>
|
|
25
|
+
`A deprecated browser API is in use${f.at ? ` at ${f.at}` : ''}: ${f.text}. Lighthouse marks Best Practices down for it.`,
|
|
26
|
+
L013: (f) =>
|
|
27
|
+
`Chrome logged a ${f.text} issue for the page. Lighthouse marks Best Practices down for it.`,
|
|
28
|
+
L020: () => 'The page has no `<title>`: search results and tabs show its URL.',
|
|
29
|
+
L021: () => 'The page has no meta description: search results make one up from the page.',
|
|
30
|
+
L022: () =>
|
|
31
|
+
'`<html>` has no `lang`: screen readers guess the language, and translation offers go wrong.',
|
|
32
|
+
L023: () =>
|
|
33
|
+
'No `<meta name="viewport" content="width=device-width, initial-scale=1">`: a phone renders the page at 980px and shrinks it.',
|
|
34
|
+
L024: (f) =>
|
|
35
|
+
`Search engines are told not to index this page, by ${f.text}.${f.header ? ' The audited endpoint serves this header: check its host or proxy rules as well as the page head.' : ''}`,
|
|
36
|
+
L025: (f) => `The page answered ${f.text}.`,
|
|
37
|
+
L030: (f) =>
|
|
38
|
+
`The page scrolls sideways on a phone: it is ${f.text} wider than the screen.${f.wide?.length ? ` Past the edge: ${f.wide.join(', ')}` : ''}`,
|
|
39
|
+
}
|
|
40
|
+
/** A page may ask not to be indexed, and a host's preview URL does on its behalf: L024 says so without failing. */
|
|
41
|
+
const SEVERITY = { L021: 'warning', L024: 'warning', L030: 'warning', L031: 'warning' }
|
|
42
|
+
|
|
43
|
+
export function reportFindings(findings, routes, forms, indexing = 'auto') {
|
|
44
|
+
const diagnostics = [...findings.values()]
|
|
45
|
+
.map((f) => {
|
|
46
|
+
const pages = routes.filter((r) => f.routes.has(r))
|
|
47
|
+
const on = `${forms.filter((x) => f.forms.has(x)).join(' and ')}, ${pages.length === 1 ? pages[0] : `${pages.length} pages (${pages.slice(0, 3).join(', ')}${pages.length > 3 ? ', …' : ''})`}`
|
|
48
|
+
const severity =
|
|
49
|
+
(f.code === 'L031' && f.cls > 0.1) || (f.code === 'L024' && indexing === 'public')
|
|
50
|
+
? 'error'
|
|
51
|
+
: (SEVERITY[f.code] ?? 'error')
|
|
52
|
+
// an axe rule outside L001–L003 carries its own fix: the rule's first remedy, and its page
|
|
53
|
+
const help =
|
|
54
|
+
f.code === 'L004'
|
|
55
|
+
? `${f.fix ? `${f.fix}. ` : ''}${VENEER[f.rule] ?? ''}The rule: https://dequeuniversity.com/rules/axe/4.14/${f.rule}`
|
|
56
|
+
: undefined
|
|
57
|
+
return diagnostic({
|
|
58
|
+
code: f.code,
|
|
59
|
+
severity,
|
|
60
|
+
file: pages[0],
|
|
61
|
+
why: `${say[f.code](f)} (${on})`,
|
|
62
|
+
help,
|
|
63
|
+
})
|
|
64
|
+
})
|
|
65
|
+
.sort((a, b) =>
|
|
66
|
+
a.severity === b.severity ? a.code.localeCompare(b.code) : a.severity === 'error' ? -1 : 1,
|
|
67
|
+
)
|
|
68
|
+
return diagnostics
|
|
69
|
+
}
|
package/src/audit.mjs
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
// `kerf audit` and the last step of `kerf build`: the built pages in a clean headless Chrome, at a phone's width and a
|
|
2
|
+
// desktop's, read the way a crawler, a screen reader and Lighthouse read them. `kerf check` reads source; some failures
|
|
3
|
+
// only exist once CSS and a breakpoint have had their say (a button whose text a phone hides has no name), so this
|
|
4
|
+
// looks at the rendered page. No automation library: the DevTools protocol over the WebSocket Node already has.
|
|
5
|
+
//
|
|
6
|
+
// L001–L004 axe-core's rules, the ones Lighthouse grades (names, images, contrast, the rest), L010–L013 console and issues,
|
|
7
|
+
// L020–L025 the head a crawler reads, L030–L031 sideways scroll on a phone and layout shift.
|
|
8
|
+
|
|
9
|
+
import { spawn } from 'node:child_process'
|
|
10
|
+
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs'
|
|
11
|
+
import { createServer } from 'node:http'
|
|
12
|
+
import { tmpdir } from 'node:os'
|
|
13
|
+
import { extname, join, relative, resolve, sep } from 'node:path'
|
|
14
|
+
import { findChrome } from './browser/client.mjs'
|
|
15
|
+
import { diagnostic } from './diag.mjs'
|
|
16
|
+
import { fail, sleep } from './audit/utils.mjs'
|
|
17
|
+
import { auditPage } from './audit/page.mjs'
|
|
18
|
+
import { reportFindings } from './audit/report.mjs'
|
|
19
|
+
import { loadConfig } from './load-config.mjs'
|
|
20
|
+
|
|
21
|
+
/** The two widths Lighthouse's defaults stand for: its mobile run (a Moto G Power) and its desktop run. */
|
|
22
|
+
export const FORMS = {
|
|
23
|
+
phone: { width: 412, height: 823, deviceScaleFactor: 1.75, mobile: true },
|
|
24
|
+
desktop: { width: 1350, height: 940, deviceScaleFactor: 1, mobile: false },
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const TYPES = {
|
|
28
|
+
'.html': 'text/html; charset=utf-8',
|
|
29
|
+
'.js': 'text/javascript',
|
|
30
|
+
'.mjs': 'text/javascript',
|
|
31
|
+
'.css': 'text/css',
|
|
32
|
+
'.json': 'application/json',
|
|
33
|
+
'.svg': 'image/svg+xml',
|
|
34
|
+
'.png': 'image/png',
|
|
35
|
+
'.jpg': 'image/jpeg',
|
|
36
|
+
'.jpeg': 'image/jpeg',
|
|
37
|
+
'.webp': 'image/webp',
|
|
38
|
+
'.avif': 'image/avif',
|
|
39
|
+
'.gif': 'image/gif',
|
|
40
|
+
'.ico': 'image/x-icon',
|
|
41
|
+
'.woff2': 'font/woff2',
|
|
42
|
+
'.woff': 'font/woff',
|
|
43
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
44
|
+
'.xml': 'application/xml',
|
|
45
|
+
'.wasm': 'application/wasm',
|
|
46
|
+
'.webmanifest': 'application/manifest+json',
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The public directory a build wrote: the newer of `.output/public` (server presets) and `dist` (Netlify, Vercel static). */
|
|
50
|
+
export function builtPublic(root) {
|
|
51
|
+
const found = ['.output/public', 'dist']
|
|
52
|
+
.map((d) => join(root, d))
|
|
53
|
+
.filter((d) => existsSync(join(d, 'index.html')))
|
|
54
|
+
return (
|
|
55
|
+
found.sort(
|
|
56
|
+
(a, b) => statSync(join(b, 'index.html')).mtimeMs - statSync(join(a, 'index.html')).mtimeMs,
|
|
57
|
+
)[0] ?? null
|
|
58
|
+
)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Every prerendered page under `dir`, as its URL path. */
|
|
62
|
+
export function pagesIn(dir) {
|
|
63
|
+
const out = []
|
|
64
|
+
const walk = (d) => {
|
|
65
|
+
for (const e of readdirSync(d, { withFileTypes: true })) {
|
|
66
|
+
if (e.name.startsWith('.') || e.name.startsWith('_')) continue
|
|
67
|
+
const f = join(d, e.name)
|
|
68
|
+
if (e.isDirectory()) walk(f)
|
|
69
|
+
else if (e.name.endsWith('.html') && !/^(404|200|500)\.html$/.test(e.name)) {
|
|
70
|
+
const rel = relative(dir, f).split(sep).join('/')
|
|
71
|
+
out.push(`/${rel.replace(/(^|\/)index\.html$/, '$1').replace(/\.html$/, '')}`)
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
walk(dir)
|
|
76
|
+
return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* One page for each kind: `/` and each top-level page, then the first page of each section at each depth (the docs'
|
|
81
|
+
* 1,600 pages share a few layouts, and a layout's fault shows on its first page).
|
|
82
|
+
*/
|
|
83
|
+
export function samplePages(pages, max = 30) {
|
|
84
|
+
const seen = new Map()
|
|
85
|
+
for (const p of pages) {
|
|
86
|
+
const parts = p.split('/').filter(Boolean)
|
|
87
|
+
const key = parts.length <= 1 ? p : `${parts[0]}/${parts.length}`
|
|
88
|
+
if (!seen.has(key)) seen.set(key, p)
|
|
89
|
+
}
|
|
90
|
+
return [...seen.values()].slice(0, max)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** A static server over a build's public directory, for the audit's Chrome. */
|
|
94
|
+
export function serveStatic(dir) {
|
|
95
|
+
dir = resolve(dir)
|
|
96
|
+
const server = createServer((req, res) => {
|
|
97
|
+
const path = decodeURIComponent(new URL(req.url, 'http://x').pathname)
|
|
98
|
+
const tries = [path, `${path}/index.html`, `${path.replace(/\/$/, '')}.html`].map((p) =>
|
|
99
|
+
resolve(dir, `.${p}`),
|
|
100
|
+
)
|
|
101
|
+
const file = tries.find(
|
|
102
|
+
(f) => (f === dir || f.startsWith(dir + sep)) && existsSync(f) && statSync(f).isFile(),
|
|
103
|
+
)
|
|
104
|
+
const missing = join(dir, '404.html')
|
|
105
|
+
if (!file) {
|
|
106
|
+
res.writeHead(404, { 'content-type': TYPES['.html'] })
|
|
107
|
+
// a doctype even here: a frame showing this would put Chrome in Quirks Mode, an issue of the audit's own making
|
|
108
|
+
return res.end(
|
|
109
|
+
existsSync(missing)
|
|
110
|
+
? readFileSync(missing)
|
|
111
|
+
: '<!doctype html><title>Not found</title><p>Not found</p>',
|
|
112
|
+
)
|
|
113
|
+
}
|
|
114
|
+
res.writeHead(200, { 'content-type': TYPES[extname(file)] ?? 'application/octet-stream' })
|
|
115
|
+
res.end(readFileSync(file))
|
|
116
|
+
})
|
|
117
|
+
return new Promise((ok) => {
|
|
118
|
+
server.listen(0, '127.0.0.1', () =>
|
|
119
|
+
ok({ url: `http://127.0.0.1:${server.address().port}`, close: () => server.close() }),
|
|
120
|
+
)
|
|
121
|
+
})
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** A clean headless Chrome (its own empty profile: no extensions, nothing stored) and a DevTools protocol client. As root (a container, CI) Chrome only starts unsandboxed. */
|
|
125
|
+
async function chrome(exe) {
|
|
126
|
+
const profile = mkdtempSync(join(tmpdir(), 'kerf-audit-'))
|
|
127
|
+
const child = spawn(
|
|
128
|
+
exe,
|
|
129
|
+
[
|
|
130
|
+
`--user-data-dir=${profile}`,
|
|
131
|
+
'--headless=new',
|
|
132
|
+
'--remote-debugging-port=0',
|
|
133
|
+
'--no-first-run',
|
|
134
|
+
'--no-default-browser-check',
|
|
135
|
+
'--disable-extensions',
|
|
136
|
+
'--disable-background-networking',
|
|
137
|
+
'--mute-audio',
|
|
138
|
+
...(process.getuid?.() === 0 ? ['--no-sandbox'] : []),
|
|
139
|
+
'about:blank',
|
|
140
|
+
],
|
|
141
|
+
{ stdio: 'ignore' },
|
|
142
|
+
)
|
|
143
|
+
const portFile = join(profile, 'DevToolsActivePort')
|
|
144
|
+
for (let i = 0; !existsSync(portFile) || !readFileSync(portFile, 'utf8').includes('\n'); i++) {
|
|
145
|
+
if (i > 150 || child.exitCode !== null) {
|
|
146
|
+
child.kill()
|
|
147
|
+
throw fail('E_NO_CHROME', `Chrome at ${exe} didn't start`)
|
|
148
|
+
}
|
|
149
|
+
await sleep(100)
|
|
150
|
+
}
|
|
151
|
+
const [port, path] = readFileSync(portFile, 'utf8').split('\n')
|
|
152
|
+
const ws = new WebSocket(`ws://127.0.0.1:${port}${path}`)
|
|
153
|
+
await new Promise((ok, no) => {
|
|
154
|
+
ws.onopen = ok
|
|
155
|
+
ws.onerror = () => no(fail('E_CDP', 'could not reach Chrome over the DevTools protocol'))
|
|
156
|
+
})
|
|
157
|
+
let next = 0
|
|
158
|
+
const waiting = new Map()
|
|
159
|
+
const listeners = new Set()
|
|
160
|
+
ws.onmessage = (e) => {
|
|
161
|
+
const m = JSON.parse(e.data)
|
|
162
|
+
if (m.id !== undefined) {
|
|
163
|
+
const w = waiting.get(m.id)
|
|
164
|
+
waiting.delete(m.id)
|
|
165
|
+
if (m.error) w?.no(fail('E_CDP', m.error.message))
|
|
166
|
+
else w?.ok(m.result)
|
|
167
|
+
} else for (const on of listeners) on(m)
|
|
168
|
+
}
|
|
169
|
+
const send = (method, params = {}, sessionId) =>
|
|
170
|
+
new Promise((ok, no) => {
|
|
171
|
+
const id = ++next
|
|
172
|
+
waiting.set(id, { ok, no })
|
|
173
|
+
ws.send(JSON.stringify({ id, method, params, sessionId }))
|
|
174
|
+
})
|
|
175
|
+
const close = () => {
|
|
176
|
+
try {
|
|
177
|
+
ws.close()
|
|
178
|
+
} catch {}
|
|
179
|
+
child.kill()
|
|
180
|
+
// Chrome holds the profile a moment after it's told to go.
|
|
181
|
+
setTimeout(() => rmSync(profile, { recursive: true, force: true }), 500).unref()
|
|
182
|
+
}
|
|
183
|
+
return {
|
|
184
|
+
send,
|
|
185
|
+
on: (fn) => {
|
|
186
|
+
listeners.add(fn)
|
|
187
|
+
return () => listeners.delete(fn)
|
|
188
|
+
},
|
|
189
|
+
close,
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* The app's own pages as a test on a path (`src/routes`, `[id]` and `[...rest]` included). A build served as files has
|
|
195
|
+
* only its prerendered pages: a request for one of the others is the server's to answer, not a missing file.
|
|
196
|
+
*/
|
|
197
|
+
export function appRoutes(root) {
|
|
198
|
+
const dir = join(root, 'src', 'routes')
|
|
199
|
+
if (!existsSync(dir)) return () => false
|
|
200
|
+
const tests = []
|
|
201
|
+
const walk = (at, prefix) => {
|
|
202
|
+
for (const e of readdirSync(at, { withFileTypes: true })) {
|
|
203
|
+
const name = e.name.replace(/^\(.*\)$/, '')
|
|
204
|
+
if (e.isDirectory()) {
|
|
205
|
+
walk(join(at, e.name), name ? `${prefix}/${name}` : prefix)
|
|
206
|
+
continue
|
|
207
|
+
}
|
|
208
|
+
if (
|
|
209
|
+
!/\.[jt]sx?$/.test(e.name) ||
|
|
210
|
+
/\.(server|test|spec)\./.test(e.name) ||
|
|
211
|
+
e.name.startsWith('_')
|
|
212
|
+
)
|
|
213
|
+
continue
|
|
214
|
+
const leaf = e.name.replace(/\.[jt]sx?$/, '')
|
|
215
|
+
const path = leaf === 'index' ? prefix : `${prefix}/${leaf}`
|
|
216
|
+
const re = path
|
|
217
|
+
.split('/')
|
|
218
|
+
.map((seg) =>
|
|
219
|
+
/^\[\.\.\.\w+\]$/.test(seg)
|
|
220
|
+
? '\0'
|
|
221
|
+
: /^\[\w+\]$/.test(seg)
|
|
222
|
+
? '[^/]+'
|
|
223
|
+
: seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'),
|
|
224
|
+
)
|
|
225
|
+
.join('/')
|
|
226
|
+
.replace(/\/\0/g, '(?:/.+)?')
|
|
227
|
+
tests.push(new RegExp(`^${re || ''}/?$`))
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
walk(dir, '')
|
|
231
|
+
return (path) => tests.some((t) => t.test(path))
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* @param {string} root project root
|
|
236
|
+
* @param {{ url?: string, dir?: string, routes?: string[], all?: boolean, max?: number, forms?: (keyof FORMS)[], concurrency?: number, indexing?: 'auto' | 'public' | 'private' }} [options]
|
|
237
|
+
* `url`: audit a running site (a deploy, `kerf start`); else `dir`, a build's public directory (found when left out)
|
|
238
|
+
* @returns {Promise<{ ok: boolean, skipped?: string, base: string, pages: string[], diagnostics: object[], ms: number }>}
|
|
239
|
+
*/
|
|
240
|
+
export async function audit(root, options = {}) {
|
|
241
|
+
const t = performance.now()
|
|
242
|
+
const loaded = options.indexing === undefined ? await loadConfig(root) : undefined
|
|
243
|
+
if (loaded?.diagnostics?.some((d) => d.severity === 'error'))
|
|
244
|
+
throw new Error('Fix kerf.config before auditing, or pass --indexing explicitly')
|
|
245
|
+
const configured = loaded?.config?.build?.audit
|
|
246
|
+
const indexing =
|
|
247
|
+
options.indexing ?? (typeof configured === 'object' ? configured.indexing : undefined) ?? 'auto'
|
|
248
|
+
if (!['auto', 'public', 'private'].includes(indexing))
|
|
249
|
+
throw new Error('indexing must be auto, public or private')
|
|
250
|
+
const exe = findChrome()
|
|
251
|
+
const forms = options.forms ?? ['phone', 'desktop']
|
|
252
|
+
const skip = (why) => ({
|
|
253
|
+
ok: true,
|
|
254
|
+
skipped: why,
|
|
255
|
+
base: options.url ?? '',
|
|
256
|
+
pages: [],
|
|
257
|
+
diagnostics: [diagnostic({ code: 'L000', severity: 'warning', file: 'kerf.config.ts', why })],
|
|
258
|
+
ms: 0,
|
|
259
|
+
})
|
|
260
|
+
if (!exe)
|
|
261
|
+
return skip(
|
|
262
|
+
'No Chrome or Chromium here, so the built pages were not audited (L001–L030). Set `KERF_CHROME`, or run `kerf audit --url <deploy>` where there is one.',
|
|
263
|
+
)
|
|
264
|
+
let base = options.url?.replace(/\/$/, '')
|
|
265
|
+
let server
|
|
266
|
+
let routes = options.routes
|
|
267
|
+
if (!base) {
|
|
268
|
+
const dir = options.dir ?? builtPublic(root)
|
|
269
|
+
if (!dir) return skip('No built pages to audit: run `kerf build` first, or pass `--url`.')
|
|
270
|
+
const pages = pagesIn(dir)
|
|
271
|
+
if (!pages.length)
|
|
272
|
+
return skip(
|
|
273
|
+
`No prerendered pages in ${relative(root, dir)} to audit: pass \`--url\` to audit a running server.`,
|
|
274
|
+
)
|
|
275
|
+
routes ??= options.all ? pages : samplePages(pages, options.max)
|
|
276
|
+
server = await serveStatic(dir)
|
|
277
|
+
base = server.url
|
|
278
|
+
}
|
|
279
|
+
routes ??= ['/']
|
|
280
|
+
const served = appRoutes(root)
|
|
281
|
+
const browser = await chrome(exe)
|
|
282
|
+
const findings = new Map()
|
|
283
|
+
try {
|
|
284
|
+
const jobs = routes.flatMap((route) => forms.map((form) => ({ route, form })))
|
|
285
|
+
let i = 0
|
|
286
|
+
const worker = async () => {
|
|
287
|
+
for (let job; (job = jobs[i++]);) {
|
|
288
|
+
for (const f of await auditPage({
|
|
289
|
+
browser,
|
|
290
|
+
url: `${base}${job.route}`,
|
|
291
|
+
form: job.form,
|
|
292
|
+
statics: !!server,
|
|
293
|
+
served,
|
|
294
|
+
forms: FORMS,
|
|
295
|
+
})) {
|
|
296
|
+
const key = `${f.code} ${f.key}`
|
|
297
|
+
const seen = findings.get(key) ?? { ...f, routes: new Set(), forms: new Set() }
|
|
298
|
+
seen.routes.add(job.route)
|
|
299
|
+
seen.forms.add(job.form)
|
|
300
|
+
findings.set(key, seen)
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
await Promise.all(
|
|
305
|
+
Array.from({ length: Math.min(options.concurrency ?? 1, jobs.length) }, worker),
|
|
306
|
+
)
|
|
307
|
+
} finally {
|
|
308
|
+
browser.close()
|
|
309
|
+
server?.close()
|
|
310
|
+
}
|
|
311
|
+
const diagnostics = reportFindings(findings, routes, forms, indexing)
|
|
312
|
+
return {
|
|
313
|
+
ok: !diagnostics.some((d) => d.severity === 'error'),
|
|
314
|
+
base: options.url ?? base,
|
|
315
|
+
pages: routes,
|
|
316
|
+
diagnostics,
|
|
317
|
+
ms: Math.round(performance.now() - t),
|
|
318
|
+
}
|
|
319
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// `kerf browser <command>`: JSON on stdout with --json, a readable form on stderr otherwise.
|
|
2
|
+
|
|
3
|
+
import { browser, browserUsage, cliParams } from './commands.mjs'
|
|
4
|
+
|
|
5
|
+
export { browserUsage }
|
|
6
|
+
|
|
7
|
+
export async function browserCommand(args, { print, say, io }) {
|
|
8
|
+
const [cmd, ...words] = args.positional
|
|
9
|
+
if (!cmd || cmd === 'help') {
|
|
10
|
+
say(browserUsage)
|
|
11
|
+
return cmd ? 0 : 2
|
|
12
|
+
}
|
|
13
|
+
try {
|
|
14
|
+
const result = await browser(args.root, cmd, cliParams(cmd, words, args.flags), {
|
|
15
|
+
url: args.flags.url,
|
|
16
|
+
tab: args.flags.tab,
|
|
17
|
+
})
|
|
18
|
+
if (args.json) print(result)
|
|
19
|
+
else io.stdout.write(`${human(cmd, result)}\n`)
|
|
20
|
+
return result?.ok === false ? 1 : 0
|
|
21
|
+
} catch (error) {
|
|
22
|
+
if (error.code === 'E_USAGE') throw error
|
|
23
|
+
if (args.json)
|
|
24
|
+
print({
|
|
25
|
+
ok: false,
|
|
26
|
+
error: { code: error.code ?? 'E_INTERNAL', message: error.message, tabs: error.tabs },
|
|
27
|
+
})
|
|
28
|
+
say(`kerf browser ${cmd}: ${error.message}`)
|
|
29
|
+
return 1
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function human(cmd, r) {
|
|
34
|
+
const text = (v) =>
|
|
35
|
+
typeof v === 'string' ? v : v?.path ? `(${v.chars} chars in ${v.path})\n${v.head}` : ''
|
|
36
|
+
if (cmd === 'snapshot')
|
|
37
|
+
return [
|
|
38
|
+
`${r.title} ${r.url}`,
|
|
39
|
+
r.delta ?? text(r.tree),
|
|
40
|
+
r.graph ? `\n# graph\n${text(r.graph)}` : '',
|
|
41
|
+
r.errors?.length
|
|
42
|
+
? `\n# errors\n${r.errors.map((e) => `${e.message}${e.at ? ` (at ${e.at})` : ''}`).join('\n')}`
|
|
43
|
+
: '',
|
|
44
|
+
]
|
|
45
|
+
.filter(Boolean)
|
|
46
|
+
.join('\n')
|
|
47
|
+
if (cmd === 'act') return `${r.target}: ${r.changes}`
|
|
48
|
+
if (cmd === 'assert')
|
|
49
|
+
return `${r.ok ? 'ok' : 'FAIL'} ${r.target} ${JSON.stringify(r.expected)}${r.ok ? '' : `, got ${JSON.stringify(r.actual)}`}`
|
|
50
|
+
if (cmd === 'graph') return text(r.graph)
|
|
51
|
+
if (cmd === 'record' && r.code) return r.code
|
|
52
|
+
return JSON.stringify(r, null, 2)
|
|
53
|
+
}
|