@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,240 @@
|
|
|
1
|
+
// `kerf agents-md`: AGENTS.md generated from the installed kerf (exports, the codes its compiler reports) and this
|
|
2
|
+
// project's tasks. Under 9 KB (PLAN §7, raised from 8 KB in 2026-11). Never edited by hand: `--check` fails when it is stale.
|
|
3
|
+
|
|
4
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
|
5
|
+
import { join, resolve } from 'node:path'
|
|
6
|
+
import { sourceAlias } from './alias.mjs'
|
|
7
|
+
import { catalog } from './catalog.mjs'
|
|
8
|
+
import { commandsPage, installed, readDoc } from './docs.mjs'
|
|
9
|
+
import { loadConfig } from './load-config.mjs'
|
|
10
|
+
import { agentsSection } from './contributions.mjs'
|
|
11
|
+
import { tasks } from './tasks.mjs'
|
|
12
|
+
|
|
13
|
+
export const limit = 9 * 1024
|
|
14
|
+
|
|
15
|
+
/** `T001, T002, T003, P007` → `T001–T003, P007`: runs of consecutive codes as ranges (three or more). */
|
|
16
|
+
export function ranges(codes) {
|
|
17
|
+
const out = []
|
|
18
|
+
for (let i = 0; i < codes.length;) {
|
|
19
|
+
let j = i
|
|
20
|
+
const num = (c) => Number(c.slice(1))
|
|
21
|
+
while (
|
|
22
|
+
j + 1 < codes.length &&
|
|
23
|
+
codes[j + 1][0] === codes[i][0] &&
|
|
24
|
+
num(codes[j + 1]) === num(codes[j]) + 1
|
|
25
|
+
)
|
|
26
|
+
j++
|
|
27
|
+
out.push(j - i >= 2 ? `${codes[i]}–${codes[j]}` : codes.slice(i, j + 1).join(', '))
|
|
28
|
+
i = j + 1
|
|
29
|
+
}
|
|
30
|
+
return out.join(', ')
|
|
31
|
+
}
|
|
32
|
+
/** PLAN §3.1 primitives an agent may reach for; listed as missing when the installed kerf doesn't export them. */
|
|
33
|
+
const planned = [
|
|
34
|
+
'state',
|
|
35
|
+
'derived',
|
|
36
|
+
'resource',
|
|
37
|
+
'Boundary',
|
|
38
|
+
'watch',
|
|
39
|
+
'onMount',
|
|
40
|
+
'onCleanup',
|
|
41
|
+
'context',
|
|
42
|
+
'defineState',
|
|
43
|
+
'flush',
|
|
44
|
+
'untrack',
|
|
45
|
+
'batch',
|
|
46
|
+
]
|
|
47
|
+
/** Commands AGENTS.md leaves to `kerf tasks --json`: rarely run by hand, or taught elsewhere in it (`kerf map` in the intro). */
|
|
48
|
+
const elsewhere = new Set([
|
|
49
|
+
'agents-md',
|
|
50
|
+
'doctor',
|
|
51
|
+
'map',
|
|
52
|
+
'mcp',
|
|
53
|
+
'plugins',
|
|
54
|
+
'start',
|
|
55
|
+
'style',
|
|
56
|
+
'surfaces',
|
|
57
|
+
'tasks',
|
|
58
|
+
'tokens',
|
|
59
|
+
])
|
|
60
|
+
/** The app-facing part of subpaths whose other exports are helpers compiled code calls. */
|
|
61
|
+
const entryPoints = {
|
|
62
|
+
'@kerf-js/core/dom': ['render', 'hydrate'],
|
|
63
|
+
'@kerf-js/core/ssr': ['renderToString', 'renderToStringAsync'],
|
|
64
|
+
'@kerf-js/core/browser': ['online', 'visible', 'lifecycle', 'media', 'on', 'interval'],
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The Full stack section, with this app's alias for its source. */
|
|
68
|
+
function fullStack(root) {
|
|
69
|
+
const alias = sourceAlias(root)
|
|
70
|
+
const text = readDoc('start-short')
|
|
71
|
+
return alias
|
|
72
|
+
? text.replaceAll('#/', alias)
|
|
73
|
+
: text.replace(
|
|
74
|
+
/ Import your own code as [^(]*\(`src\/server\/todos`\); generated files are/,
|
|
75
|
+
' Generated files are',
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** This project's AGENTS.md, written from what the installed kerf reports: the text, where it goes, and whether kerf's own part is over the limit. */
|
|
80
|
+
export async function agentsMd(root) {
|
|
81
|
+
root = resolve(root)
|
|
82
|
+
const info = installed(root)
|
|
83
|
+
const list = await tasks(root)
|
|
84
|
+
const sections = (await loadConfig(root)).contributions
|
|
85
|
+
.filter((c) => c.manifest.agents)
|
|
86
|
+
.map((c) => agentsSection(c.manifest.agents))
|
|
87
|
+
const core = info.exports['@kerf-js/core'] ?? []
|
|
88
|
+
const missing = planned.filter((n) => !core.includes(n))
|
|
89
|
+
|
|
90
|
+
// Style-group codes (D0xx, W060) and `kerf style` belong to the Styling section, which only a kerf with @kerf-js/core/style gets.
|
|
91
|
+
const styled = info.exports['@kerf-js/core/style']?.includes('group')
|
|
92
|
+
const dcodes = catalog
|
|
93
|
+
.filter((e) => e.code.startsWith('D0') && (e.by === 'cli' || info.status[e.code]?.implemented))
|
|
94
|
+
.map((e) => e.code)
|
|
95
|
+
.sort()
|
|
96
|
+
const startApp = existsSync(join(root, 'src', 'routes'))
|
|
97
|
+
const tcodes = catalog
|
|
98
|
+
.filter((e) => e.code.startsWith('T') && info.status[e.code]?.implemented)
|
|
99
|
+
.map((e) => e.code)
|
|
100
|
+
|
|
101
|
+
const text = page({ root, info, core, missing, tcodes, startApp, styled, dcodes, list }, sections)
|
|
102
|
+
const bytes = Buffer.byteLength(text)
|
|
103
|
+
// the limit is kerf's own text: plugin sections have their own 1 KB each (P112) on top
|
|
104
|
+
return {
|
|
105
|
+
path: join(root, 'AGENTS.md'),
|
|
106
|
+
text,
|
|
107
|
+
bytes,
|
|
108
|
+
overLimit:
|
|
109
|
+
Buffer.byteLength(
|
|
110
|
+
page({ root, info, core, missing, tcodes, startApp, styled, dcodes, list }, []),
|
|
111
|
+
) > limit,
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function pageIntro({ root, info, core, missing }) {
|
|
116
|
+
return [
|
|
117
|
+
`# AGENTS.md`,
|
|
118
|
+
'',
|
|
119
|
+
`<!-- Generated by \`kerf agents-md\` from kerf@${info.kerf.version}. Do not edit: change kerf.config.ts and regenerate. -->`,
|
|
120
|
+
'',
|
|
121
|
+
`This is a **kerf** app. It is not React: components run once, state is a box, and`,
|
|
122
|
+
`React hooks don't exist. Run \`kerf check --json\` after every change; each diagnostic gives code, location, why and fix.`,
|
|
123
|
+
'',
|
|
124
|
+
'Start with `.kerf/map.md` (`kerf map`): what this app has and what to call.',
|
|
125
|
+
...(existsSync(join(root, 'src', 'theme.css'))
|
|
126
|
+
? ['', "`src/theme.css` is this app's CSS; `kerf docs theme` changes the look."]
|
|
127
|
+
: []),
|
|
128
|
+
'',
|
|
129
|
+
'## Rules',
|
|
130
|
+
'',
|
|
131
|
+
readDoc('rules'),
|
|
132
|
+
...(core.includes('resource')
|
|
133
|
+
? [
|
|
134
|
+
'10. **Async data is `resource(signal => fetch(…))`** (`.value .pending .error .refresh()`), never `derived(async …)` (W012).',
|
|
135
|
+
core.includes('Boundary')
|
|
136
|
+
? ' Loading and errors: `<Boundary pending={…} error={(e, retry) => …}>`.'
|
|
137
|
+
: '',
|
|
138
|
+
]
|
|
139
|
+
: []),
|
|
140
|
+
'',
|
|
141
|
+
'**Leave props untyped**: `kerf docs props`.',
|
|
142
|
+
'',
|
|
143
|
+
`## API in kerf@${info.kerf.version}`,
|
|
144
|
+
'',
|
|
145
|
+
`- \`@kerf-js/core\`: ${core
|
|
146
|
+
.filter((n) => planned.includes(n))
|
|
147
|
+
.map((n) => `\`${n}\``)
|
|
148
|
+
.join(', ')}` + (core.includes('state') ? ', `state.linked`' : ''),
|
|
149
|
+
...['@kerf-js/core/dom', '@kerf-js/core/ssr']
|
|
150
|
+
.map((mod, i, all) => {
|
|
151
|
+
const names = entryPoints[mod].filter((n) => info.exports[mod]?.includes(n))
|
|
152
|
+
const last = all
|
|
153
|
+
.slice(i + 1)
|
|
154
|
+
.every((m) => !entryPoints[m].some((n) => info.exports[m]?.includes(n)))
|
|
155
|
+
return names.length
|
|
156
|
+
? `- \`${mod}\`: ${names.map((n) => `\`${n}\``).join(', ')}.${last ? ' Never import the rest.' : ''}`
|
|
157
|
+
: ''
|
|
158
|
+
})
|
|
159
|
+
.filter(Boolean),
|
|
160
|
+
info.exports['@kerf-js/core/browser']
|
|
161
|
+
? `- \`@kerf-js/core/browser\`: ${entryPoints['@kerf-js/core/browser']
|
|
162
|
+
.filter((n) => info.exports['@kerf-js/core/browser'].includes(n))
|
|
163
|
+
.map((n) => `\`${n}\``)
|
|
164
|
+
.join(
|
|
165
|
+
', ',
|
|
166
|
+
)}. Create them in setup (W051); server-rendered \`media\` needs \`ssr\` (W054). More: \`kerf docs browser\`; hover and press as state: \`kerf docs ui-state\`.`
|
|
167
|
+
: '',
|
|
168
|
+
info.exports['@kerf-js/core/surface']
|
|
169
|
+
? '- `@kerf-js/core/surface`: canvas and WebGL, never raw `<canvas>`: `kerf docs surface`.'
|
|
170
|
+
: '',
|
|
171
|
+
info.exports['@kerf-js/core/test']
|
|
172
|
+
? `- \`@kerf-js/core/test\`: ${info.exports['@kerf-js/core/test']
|
|
173
|
+
.filter((n) => !['canvasCalls', 'cleanup', 'fakeMeasure', 'leaks'].includes(n))
|
|
174
|
+
.map((n) => `\`${n}\``)
|
|
175
|
+
.join(
|
|
176
|
+
', ',
|
|
177
|
+
)}, and \`expect(fn).toTouchAtMost(n, { runs })\`. Query by role/label/text; \`user\` actions and \`clock.advance\` end in \`flush()\`, so never sleep or \`waitFor\`.`
|
|
178
|
+
: '',
|
|
179
|
+
missing.length
|
|
180
|
+
? `- Not in this version yet: ${missing.map((n) => `\`${n}\``).join(', ')}. Don't import them.`
|
|
181
|
+
: '',
|
|
182
|
+
'',
|
|
183
|
+
]
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// with plugins: the `kerf plugins` command and their sections; without, neither
|
|
187
|
+
function page({ root, info, core, missing, tcodes, startApp, styled, dcodes, list }, plugins) {
|
|
188
|
+
return [
|
|
189
|
+
...pageIntro({ root, info, core, missing }),
|
|
190
|
+
'## Diagnostics',
|
|
191
|
+
'',
|
|
192
|
+
'`kerf docs <code>` explains one. Also flagged: an early `return` in a `.map` callback (W013), raw `addEventListener`, `setInterval` or sockets with no cleanup (W050), and a `watch` that folds a stream (W052) or copies a live value into `state` (W056).',
|
|
193
|
+
'',
|
|
194
|
+
tcodes.length
|
|
195
|
+
? `Test checks (\`kerf check\` on test files): ${ranges(tcodes)}. No assertion, tautologies, sleeps, \`container\`/selectors/test ids, mocking kerf, snapshots, conditional \`expect\`, \`.only\`/\`.skip\`. To allow one: \`// kerf-allow T00x: <reason>\`.`
|
|
196
|
+
: '',
|
|
197
|
+
'',
|
|
198
|
+
'Before a change is done, see it work (`kerf browser snapshot|act|assert`, or `__kerf__.agent` in your own browser) and run `kerf test --gate`: new tests must fail on the old code and kill a mutant (T010, T011, T020). `kerf build` audits its pages at phone and desktop width (L-codes) and fails on an error. More: `kerf docs verify`.',
|
|
199
|
+
'',
|
|
200
|
+
'Before publishing, set `build.audit.indexing` (`public` or `private`) and audit the deployed URL: `kerf audit --url <url> --indexing public`. Never drop a private noindex for a score.',
|
|
201
|
+
'',
|
|
202
|
+
...(startApp ? ['## Full stack', '', fullStack(root), ''] : []),
|
|
203
|
+
...(styled
|
|
204
|
+
? [
|
|
205
|
+
'## Styling',
|
|
206
|
+
'',
|
|
207
|
+
`**Run \`kerf style find <what it is>\` first**, then reuse a group or add an axis value; never class lists. New: \`const card = group('card', { base: { pad: 'group' }, axes: { status: { late: { tone: 'critical' } } } })\` from \`@kerf-js/core/style\`, \`<li {...card({ status })}>\`. Tokens only. ${ranges(dcodes)}, W060: \`kerf docs style\`, \`kerf docs design\`; \`kerf fix\` applies the safe fixes.`,
|
|
208
|
+
'',
|
|
209
|
+
]
|
|
210
|
+
: []),
|
|
211
|
+
'## Commands',
|
|
212
|
+
'',
|
|
213
|
+
commandsPage(
|
|
214
|
+
// the Styling section teaches `kerf fix`
|
|
215
|
+
{
|
|
216
|
+
...list,
|
|
217
|
+
tasks: list.tasks.filter((t) => !elsewhere.has(t.name) && !(styled && t.name === 'fix')),
|
|
218
|
+
},
|
|
219
|
+
{ planned: false },
|
|
220
|
+
),
|
|
221
|
+
'',
|
|
222
|
+
'`kerf tasks --json` lists the rest.',
|
|
223
|
+
'',
|
|
224
|
+
...(plugins.length ? ['## Plugins', '', ...plugins] : []),
|
|
225
|
+
'## More',
|
|
226
|
+
'',
|
|
227
|
+
`\`kerf docs <topic>\` or \`kerf mcp\`: \`rules\`, \`props\`, \`lists\`, \`async\`, \`testing\`, \`browser\`, \`verify\`, ${startApp ? '`start`, ' : ''}${info.exports['@kerf-js/core/style'] ? '`style`, ' : ''}${info.exports['@kerf-js/core/surface'] ? '`surface`, ' : ''}\`config\`, \`diagnostics\`, \`commands\`.`,
|
|
228
|
+
'',
|
|
229
|
+
]
|
|
230
|
+
.filter((line, i, all) => !(line === '' && all[i - 1] === ''))
|
|
231
|
+
.join('\n')
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Write AGENTS.md, or with `check` only compare. Returns whether the file on disk was current. */
|
|
235
|
+
export async function writeAgentsMd(root, { check = false } = {}) {
|
|
236
|
+
const out = await agentsMd(root)
|
|
237
|
+
const current = existsSync(out.path) && readFileSync(out.path, 'utf8') === out.text
|
|
238
|
+
if (!check && !current) writeFileSync(out.path, out.text)
|
|
239
|
+
return { ...out, current, written: !check && !current }
|
|
240
|
+
}
|
package/src/alias.mjs
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// An app's import aliases are its own: tsconfig `paths` (which Vite follows too), plus package.json `imports` if it has
|
|
2
|
+
// them. `#/*` is only what create-kerf writes. `local` is how the checks follow a project import, so an aliased file
|
|
3
|
+
// gets the same analysis as a relative one.
|
|
4
|
+
|
|
5
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
6
|
+
import { dirname, join, resolve } from 'node:path'
|
|
7
|
+
import ts from 'typescript'
|
|
8
|
+
|
|
9
|
+
const cache = new Map()
|
|
10
|
+
|
|
11
|
+
/** `{ prefix, suffix, target }` for each alias declared in `dir`, longest prefix first; `target` has a `*` to fill. */
|
|
12
|
+
function rulesIn(dir) {
|
|
13
|
+
const rules = []
|
|
14
|
+
const add = (pattern, target) => {
|
|
15
|
+
const [prefix, suffix = ''] = pattern.split('*')
|
|
16
|
+
rules.push({ prefix, suffix, exact: !pattern.includes('*'), target })
|
|
17
|
+
}
|
|
18
|
+
const tsconfig = join(dir, 'tsconfig.json')
|
|
19
|
+
if (existsSync(tsconfig)) {
|
|
20
|
+
const host = { ...ts.sys, readDirectory: () => [] }
|
|
21
|
+
const { options } = ts.parseJsonConfigFileContent(
|
|
22
|
+
ts.readConfigFile(tsconfig, (path) => ts.sys.readFile(path)).config,
|
|
23
|
+
host,
|
|
24
|
+
dir,
|
|
25
|
+
)
|
|
26
|
+
const base = options.pathsBasePath ?? options.baseUrl ?? dir
|
|
27
|
+
for (const [pattern, [target]] of Object.entries(options.paths ?? {}))
|
|
28
|
+
add(pattern, resolve(base, target))
|
|
29
|
+
}
|
|
30
|
+
const pkg = join(dir, 'package.json')
|
|
31
|
+
if (existsSync(pkg)) {
|
|
32
|
+
for (const [pattern, target] of Object.entries(
|
|
33
|
+
JSON.parse(readFileSync(pkg, 'utf8')).imports ?? {},
|
|
34
|
+
)) {
|
|
35
|
+
if (typeof target === 'string' && target.startsWith('.')) add(pattern, resolve(dir, target))
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return rules.sort((a, b) => b.prefix.length - a.prefix.length)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The rules of the nearest project root above `dir`. */
|
|
42
|
+
function rulesFor(dir) {
|
|
43
|
+
if (cache.has(dir)) return cache.get(dir)
|
|
44
|
+
const parent = dirname(dir)
|
|
45
|
+
const isRoot = existsSync(join(dir, 'tsconfig.json')) || existsSync(join(dir, 'package.json'))
|
|
46
|
+
const rules = isRoot ? rulesIn(dir) : parent === dir ? [] : rulesFor(parent)
|
|
47
|
+
cache.set(dir, rules)
|
|
48
|
+
return rules
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The absolute path a project import points at, before extensions; null for a package. */
|
|
52
|
+
export function local(fromAbs, spec) {
|
|
53
|
+
if (spec.startsWith('.')) return join(dirname(fromAbs), spec)
|
|
54
|
+
for (const { prefix, suffix, exact, target } of rulesFor(dirname(fromAbs))) {
|
|
55
|
+
if (exact ? spec === prefix : spec.startsWith(prefix) && spec.endsWith(suffix)) {
|
|
56
|
+
return exact
|
|
57
|
+
? target
|
|
58
|
+
: target.replace('*', spec.slice(prefix.length, spec.length - suffix.length))
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return null
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The prefix that maps to `<root>/src/`, like `#/`; null when the app has none. */
|
|
65
|
+
export function sourceAlias(root) {
|
|
66
|
+
const rule = rulesFor(resolve(root)).find(
|
|
67
|
+
(r) => r.target === join(resolve(root), 'src', '*') && !r.suffix,
|
|
68
|
+
)
|
|
69
|
+
return rule?.prefix ?? null
|
|
70
|
+
}
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { fileURLToPath } from 'node:url'
|
|
3
|
+
import { fail, sleep } from './utils.mjs'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* axe-core is what Lighthouse runs for Accessibility and for Agentic Browsing's accessibility tree: the WCAG 2 A and AA
|
|
7
|
+
* rules, and the best-practice ones Lighthouse also grades. `region` (all content in landmarks) Lighthouse leaves out.
|
|
8
|
+
*/
|
|
9
|
+
const AXE = {
|
|
10
|
+
runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa'] },
|
|
11
|
+
rules: {
|
|
12
|
+
'heading-order': { enabled: true },
|
|
13
|
+
'empty-heading': { enabled: true },
|
|
14
|
+
tabindex: { enabled: true },
|
|
15
|
+
'duplicate-id-aria': { enabled: true },
|
|
16
|
+
'image-redundant-alt': { enabled: true },
|
|
17
|
+
'skip-link': { enabled: true },
|
|
18
|
+
'landmark-one-main': { enabled: true },
|
|
19
|
+
list: { enabled: true },
|
|
20
|
+
listitem: { enabled: true },
|
|
21
|
+
region: { enabled: false },
|
|
22
|
+
},
|
|
23
|
+
resultTypes: ['violations'],
|
|
24
|
+
}
|
|
25
|
+
/** axe rules with a code of their own; every other violation is L004, with the rule's id. */
|
|
26
|
+
const RULES = {
|
|
27
|
+
...Object.fromEntries(
|
|
28
|
+
[
|
|
29
|
+
'button-name',
|
|
30
|
+
'link-name',
|
|
31
|
+
'input-button-name',
|
|
32
|
+
'label',
|
|
33
|
+
'select-name',
|
|
34
|
+
'aria-command-name',
|
|
35
|
+
'aria-input-field-name',
|
|
36
|
+
'aria-toggle-field-name',
|
|
37
|
+
'aria-progressbar-name',
|
|
38
|
+
'aria-meter-name',
|
|
39
|
+
'aria-tooltip-name',
|
|
40
|
+
'aria-treeitem-name',
|
|
41
|
+
'aria-dialog-name',
|
|
42
|
+
'frame-title',
|
|
43
|
+
'summary-name',
|
|
44
|
+
].map((r) => [r, 'L001']),
|
|
45
|
+
),
|
|
46
|
+
...Object.fromEntries(
|
|
47
|
+
['image-alt', 'role-img-alt', 'svg-img-alt', 'input-image-alt', 'object-alt', 'area-alt'].map(
|
|
48
|
+
(r) => [r, 'L002'],
|
|
49
|
+
),
|
|
50
|
+
),
|
|
51
|
+
'color-contrast': 'L003',
|
|
52
|
+
}
|
|
53
|
+
let axe
|
|
54
|
+
const axeSource = () =>
|
|
55
|
+
(axe ??= readFileSync(fileURLToPath(import.meta.resolve('axe-core/axe.min.js')), 'utf8'))
|
|
56
|
+
/** The issue types Lighthouse's `inspector-issues` audit counts (low contrast is axe's, as L003). */
|
|
57
|
+
const ISSUES = new Set([
|
|
58
|
+
'MixedContentIssue',
|
|
59
|
+
'CookieIssue',
|
|
60
|
+
'BlockedByResponseIssue',
|
|
61
|
+
'HeavyAdIssue',
|
|
62
|
+
'ContentSecurityPolicyIssue',
|
|
63
|
+
'SharedArrayBufferIssue',
|
|
64
|
+
'CorsIssue',
|
|
65
|
+
'AttributionReportingIssue',
|
|
66
|
+
'QuirksModeIssue',
|
|
67
|
+
'FederatedAuthRequestIssue',
|
|
68
|
+
'BounceTrackingIssue',
|
|
69
|
+
'StylesheetLoadingIssue',
|
|
70
|
+
])
|
|
71
|
+
|
|
72
|
+
/** In the page: how far the layout moved without a person asking (CLS, summed), and the first elements that moved. */
|
|
73
|
+
const SHIFT = `new Promise(ok => {
|
|
74
|
+
let cls = 0
|
|
75
|
+
const moved = []
|
|
76
|
+
new PerformanceObserver(list => {
|
|
77
|
+
for (const e of list.getEntries()) {
|
|
78
|
+
if (e.hadRecentInput) continue
|
|
79
|
+
cls += e.value
|
|
80
|
+
for (const s of e.sources ?? []) {
|
|
81
|
+
if (!s.node || s.node.nodeType !== 1 || moved.length === 3) continue
|
|
82
|
+
const open = s.node.outerHTML.slice(0, s.node.outerHTML.indexOf('>') + 1)
|
|
83
|
+
moved.push(open.length > 120 ? open.slice(0, 117) + '…>' : open)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}).observe({ type: 'layout-shift', buffered: true })
|
|
87
|
+
setTimeout(() => ok({ cls: Math.round(cls * 1000) / 1000, moved }), 50)
|
|
88
|
+
})`
|
|
89
|
+
|
|
90
|
+
/** In the page: what a crawler reads from the head, and what pokes past a phone's right edge. */
|
|
91
|
+
const HEAD = `(() => {
|
|
92
|
+
const meta = n => document.querySelector('meta[name="' + n + '"]')?.getAttribute('content')?.trim() ?? null
|
|
93
|
+
const wide = []
|
|
94
|
+
const edge = innerWidth + 1
|
|
95
|
+
if (document.documentElement.scrollWidth > edge) {
|
|
96
|
+
for (const el of document.body.querySelectorAll('*')) {
|
|
97
|
+
const r = el.getBoundingClientRect()
|
|
98
|
+
if (r.right > edge && r.width > 0 && getComputedStyle(el).position !== 'fixed' && !(el.parentElement && el.parentElement.getBoundingClientRect().right > edge)) {
|
|
99
|
+
const open = el.outerHTML.slice(0, el.outerHTML.indexOf('>') + 1)
|
|
100
|
+
wide.push(open.length > 120 ? open.slice(0, 117) + '…>' : open)
|
|
101
|
+
if (wide.length === 3) break
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
title: document.title.trim(), lang: document.documentElement.getAttribute('lang') ?? '', description: meta('description'),
|
|
107
|
+
viewport: meta('viewport'), robots: meta('robots'), scroll: document.documentElement.scrollWidth - innerWidth, wide,
|
|
108
|
+
icon: !!document.querySelector('link[rel~="icon"]'),
|
|
109
|
+
}
|
|
110
|
+
})()`
|
|
111
|
+
|
|
112
|
+
function listenPage({ browser, sessionId, found, statics, served, loaded, document }) {
|
|
113
|
+
const where = (u, line) =>
|
|
114
|
+
u
|
|
115
|
+
? `${u.replace(/^https?:\/\/127\.0\.0\.1:\d+/, '')}${line === undefined ? '' : `:${line + 1}`}`
|
|
116
|
+
: ''
|
|
117
|
+
const off = browser.on((m) => {
|
|
118
|
+
if (m.sessionId !== sessionId) return
|
|
119
|
+
const p = m.params
|
|
120
|
+
if (m.method === 'Page.loadEventFired') loaded()
|
|
121
|
+
else if (m.method === 'Network.responseReceived' && p.type === 'Document' && !document.value)
|
|
122
|
+
document.value = p.response
|
|
123
|
+
else if (m.method === 'Runtime.exceptionThrown') {
|
|
124
|
+
const d = p.exceptionDetails
|
|
125
|
+
found.push({
|
|
126
|
+
code: 'L010',
|
|
127
|
+
key: d.exception?.description?.split('\n')[0] ?? d.text,
|
|
128
|
+
at: where(d.url, d.lineNumber),
|
|
129
|
+
text: d.exception?.description?.split('\n')[0] ?? d.text,
|
|
130
|
+
})
|
|
131
|
+
} else if (
|
|
132
|
+
m.method === 'Runtime.consoleAPICalled' &&
|
|
133
|
+
(p.type === 'error' || p.type === 'assert')
|
|
134
|
+
) {
|
|
135
|
+
const text = p.args
|
|
136
|
+
.map((a) => a.value ?? a.description ?? '')
|
|
137
|
+
.join(' ')
|
|
138
|
+
.split('\n')[0]
|
|
139
|
+
const top = p.stackTrace?.callFrames?.[0]
|
|
140
|
+
found.push({ code: 'L010', key: text, at: where(top?.url, top?.lineNumber), text })
|
|
141
|
+
} else if (m.method === 'Log.entryAdded' && p.entry.level === 'error') {
|
|
142
|
+
// a build's pages served as files have no server: its realtime and function routes answer 404 here and nowhere else
|
|
143
|
+
if (statics && /\/_kerf\/(rt|ws|fn|data|m|x)\b/.test(`${p.entry.url ?? ''} ${p.entry.text}`))
|
|
144
|
+
return
|
|
145
|
+
if (
|
|
146
|
+
statics &&
|
|
147
|
+
p.entry.url &&
|
|
148
|
+
/status of 404/.test(p.entry.text) &&
|
|
149
|
+
served(new URL(p.entry.url).pathname)
|
|
150
|
+
)
|
|
151
|
+
return
|
|
152
|
+
// the favicon: Chrome asks for it lazily, once a session, so the head probe asks instead (below)
|
|
153
|
+
if ((p.entry.url ?? '').endsWith('/favicon.ico')) return
|
|
154
|
+
found.push({
|
|
155
|
+
code: 'L011',
|
|
156
|
+
key: `${p.entry.url ?? ''} ${p.entry.text}`,
|
|
157
|
+
at: where(p.entry.url),
|
|
158
|
+
text: p.entry.text,
|
|
159
|
+
})
|
|
160
|
+
} else if (m.method === 'Audits.issueAdded') {
|
|
161
|
+
const { code, details } = p.issue
|
|
162
|
+
if (code === 'DeprecationIssue') {
|
|
163
|
+
const d = details.deprecationIssueDetails
|
|
164
|
+
found.push({
|
|
165
|
+
code: 'L012',
|
|
166
|
+
key: d.type,
|
|
167
|
+
at: where(d.sourceCodeLocation?.url, d.sourceCodeLocation?.lineNumber),
|
|
168
|
+
text: d.type,
|
|
169
|
+
})
|
|
170
|
+
} else if (ISSUES.has(code))
|
|
171
|
+
found.push({
|
|
172
|
+
code: 'L013',
|
|
173
|
+
key: code,
|
|
174
|
+
text: code.replace(/Issue$/, '').replace(/([a-z])([A-Z])/g, '$1 $2'),
|
|
175
|
+
})
|
|
176
|
+
}
|
|
177
|
+
})
|
|
178
|
+
return off
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function inspectHead(send, document, f, found) {
|
|
182
|
+
if (document.value && document.value.status >= 400)
|
|
183
|
+
found.push({
|
|
184
|
+
code: 'L025',
|
|
185
|
+
key: String(document.value.status),
|
|
186
|
+
text: `HTTP ${document.value.status}`,
|
|
187
|
+
})
|
|
188
|
+
const header = Object.entries(document.value?.headers ?? {}).find(
|
|
189
|
+
([k]) => k.toLowerCase() === 'x-robots-tag',
|
|
190
|
+
)?.[1]
|
|
191
|
+
const head = (await send('Runtime.evaluate', { expression: HEAD, returnByValue: true })).result
|
|
192
|
+
.value
|
|
193
|
+
if (!head.icon) {
|
|
194
|
+
const status = (
|
|
195
|
+
await send('Runtime.evaluate', {
|
|
196
|
+
expression: `fetch('/favicon.ico', { method: 'HEAD' }).then(r => r.status, () => 0)`,
|
|
197
|
+
awaitPromise: true,
|
|
198
|
+
returnByValue: true,
|
|
199
|
+
})
|
|
200
|
+
).result.value
|
|
201
|
+
if (status >= 400)
|
|
202
|
+
found.push({ code: 'L011', key: 'favicon', at: '/favicon.ico', text: `HTTP ${status}` })
|
|
203
|
+
}
|
|
204
|
+
if (!head.title) found.push({ code: 'L020', key: 'title' })
|
|
205
|
+
if (!head.description) found.push({ code: 'L021', key: 'description' })
|
|
206
|
+
if (!head.lang) found.push({ code: 'L022', key: 'lang' })
|
|
207
|
+
if (!head.viewport || !/width=device-width/.test(head.viewport))
|
|
208
|
+
found.push({ code: 'L023', key: 'viewport' })
|
|
209
|
+
const noindex = [
|
|
210
|
+
header && /noindex|none/i.test(header) && `the \`x-robots-tag: ${header}\` header`,
|
|
211
|
+
head.robots &&
|
|
212
|
+
/noindex|none/i.test(head.robots) &&
|
|
213
|
+
`<meta name="robots" content="${head.robots}">`,
|
|
214
|
+
].filter(Boolean)
|
|
215
|
+
if (noindex.length)
|
|
216
|
+
found.push({
|
|
217
|
+
code: 'L024',
|
|
218
|
+
key: noindex.join(),
|
|
219
|
+
text: noindex.join(' and '),
|
|
220
|
+
header: !!header,
|
|
221
|
+
})
|
|
222
|
+
if (f.mobile && head.scroll > 0)
|
|
223
|
+
found.push({
|
|
224
|
+
code: 'L030',
|
|
225
|
+
key: head.wide.join() || 'page',
|
|
226
|
+
text: `${head.scroll}px`,
|
|
227
|
+
wide: head.wide,
|
|
228
|
+
})
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function inspectAxe(send, url, found) {
|
|
232
|
+
await send('Runtime.evaluate', { expression: axeSource() })
|
|
233
|
+
const { result, exceptionDetails } = await send('Runtime.evaluate', {
|
|
234
|
+
expression: `axe.run(document, ${JSON.stringify(AXE)}).then(r => r.violations)`,
|
|
235
|
+
awaitPromise: true,
|
|
236
|
+
returnByValue: true,
|
|
237
|
+
})
|
|
238
|
+
if (exceptionDetails)
|
|
239
|
+
throw fail(
|
|
240
|
+
'E_AUDIT',
|
|
241
|
+
`axe-core failed on ${url}: ${exceptionDetails.exception?.description ?? exceptionDetails.text}`,
|
|
242
|
+
)
|
|
243
|
+
for (const v of result.value) {
|
|
244
|
+
for (const n of v.nodes) {
|
|
245
|
+
const tag = n.html.slice(0, n.html.indexOf('>') + 1)
|
|
246
|
+
found.push({
|
|
247
|
+
code: RULES[v.id] ?? 'L004',
|
|
248
|
+
key: `${v.id} ${n.target.join(' ')}`,
|
|
249
|
+
rule: v.id,
|
|
250
|
+
help: v.help,
|
|
251
|
+
fix: n.failureSummary
|
|
252
|
+
?.replace(/^Fix (any|all) of the following:\s*/, '')
|
|
253
|
+
.split('\n')[0]
|
|
254
|
+
.trim(),
|
|
255
|
+
selector: n.target.join(' '),
|
|
256
|
+
tag: tag.length > 160 ? `${tag.slice(0, 157)}…>` : tag,
|
|
257
|
+
contrast: v.id === 'color-contrast' ? n.any[0]?.data : undefined,
|
|
258
|
+
})
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Audit one page in one form factor: what Chrome said while it loaded, its head, its layout, and axe-core's rules. */
|
|
264
|
+
export async function auditPage({ browser, url, form, statics, served, forms }) {
|
|
265
|
+
const { targetId } = await browser.send('Target.createTarget', { url: 'about:blank' })
|
|
266
|
+
const { sessionId } = await browser.send('Target.attachToTarget', { targetId, flatten: true })
|
|
267
|
+
const send = (m, p) => browser.send(m, p, sessionId)
|
|
268
|
+
const found = []
|
|
269
|
+
const document = { value: null }
|
|
270
|
+
let loaded
|
|
271
|
+
const load = new Promise((ok) => {
|
|
272
|
+
loaded = ok
|
|
273
|
+
})
|
|
274
|
+
const off = listenPage({ browser, sessionId, found, statics, served, loaded, document })
|
|
275
|
+
|
|
276
|
+
try {
|
|
277
|
+
const f = forms[form]
|
|
278
|
+
await Promise.all(
|
|
279
|
+
['Page.enable', 'Runtime.enable', 'Log.enable', 'Network.enable', 'Audits.enable'].map((m) =>
|
|
280
|
+
send(m),
|
|
281
|
+
),
|
|
282
|
+
)
|
|
283
|
+
await send('Emulation.setDeviceMetricsOverride', {
|
|
284
|
+
width: f.width,
|
|
285
|
+
height: f.height,
|
|
286
|
+
deviceScaleFactor: f.deviceScaleFactor,
|
|
287
|
+
mobile: f.mobile,
|
|
288
|
+
})
|
|
289
|
+
await send('Emulation.setTouchEmulationEnabled', {
|
|
290
|
+
enabled: f.mobile,
|
|
291
|
+
maxTouchPoints: f.mobile ? 5 : 1,
|
|
292
|
+
})
|
|
293
|
+
await send('Page.navigate', { url })
|
|
294
|
+
await Promise.race([load, sleep(15_000)])
|
|
295
|
+
await sleep(800) // hydration's errors, and a font swap's shift, land after load
|
|
296
|
+
await inspectHead(send, document, f, found)
|
|
297
|
+
const shift = (
|
|
298
|
+
await send('Runtime.evaluate', { expression: SHIFT, awaitPromise: true, returnByValue: true })
|
|
299
|
+
).result.value
|
|
300
|
+
if (shift.cls > 0.05)
|
|
301
|
+
found.push({
|
|
302
|
+
code: 'L031',
|
|
303
|
+
key: shift.moved.join() || 'page',
|
|
304
|
+
cls: shift.cls,
|
|
305
|
+
moved: shift.moved,
|
|
306
|
+
})
|
|
307
|
+
await inspectAxe(send, url, found)
|
|
308
|
+
return found
|
|
309
|
+
} finally {
|
|
310
|
+
off()
|
|
311
|
+
await browser.send('Target.closeTarget', { targetId }).catch(() => {})
|
|
312
|
+
}
|
|
313
|
+
}
|