@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,299 @@
|
|
|
1
|
+
// The `kerf browser` transport: commands go to the dev server, which relays them to an open tab of the app (@kerf-js/core/agent
|
|
2
|
+
// in the page). No browser automation library: the page is whatever browser the agent or person already has open. When
|
|
3
|
+
// there is none (CI, a sandbox), `launch` starts a plain headless Chrome on the app as a host page, and `screenshot`
|
|
4
|
+
// reads it over the DevTools protocol.
|
|
5
|
+
|
|
6
|
+
import { spawn } from 'node:child_process'
|
|
7
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
8
|
+
import { join } from 'node:path'
|
|
9
|
+
import { loadConfig } from '../load-config.mjs'
|
|
10
|
+
|
|
11
|
+
/** The dev server: `--url`, else what the kerf() plugin wrote to `.kerf/dev.json`, else `environments.dev.url`. */
|
|
12
|
+
export async function devUrl(root, given) {
|
|
13
|
+
if (given) return given.replace(/\/$/, '')
|
|
14
|
+
const file = join(root, '.kerf', 'dev.json')
|
|
15
|
+
if (existsSync(file)) {
|
|
16
|
+
try {
|
|
17
|
+
return JSON.parse(readFileSync(file, 'utf8')).url.replace(/\/$/, '')
|
|
18
|
+
} catch {}
|
|
19
|
+
}
|
|
20
|
+
const { config } = await loadConfig(root).catch(() => ({ config: {} }))
|
|
21
|
+
return (config.environments?.dev?.url ?? 'http://localhost:5173').replace(/\/$/, '')
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const fail = (code, message, extra) => Object.assign(new Error(message), { code, ...extra })
|
|
25
|
+
|
|
26
|
+
async function request(url, init) {
|
|
27
|
+
try {
|
|
28
|
+
const res = await fetch(`${url}/__kerf/agent`, {
|
|
29
|
+
...init,
|
|
30
|
+
headers: { 'x-kerf-agent': '1', 'content-type': 'application/json' },
|
|
31
|
+
})
|
|
32
|
+
if (res.status === 404)
|
|
33
|
+
throw fail(
|
|
34
|
+
'E_NO_BRIDGE',
|
|
35
|
+
`${url} is not a kerf dev server (no /__kerf/agent): serve the app with the kerf() Vite plugin`,
|
|
36
|
+
)
|
|
37
|
+
return await res.json()
|
|
38
|
+
} catch (e) {
|
|
39
|
+
if (e.code) throw e
|
|
40
|
+
throw fail('E_NO_DEV', `no dev server answers at ${url}: start it (vite), or pass --url`)
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Run one command in a tab (the focused one, else the most recent). */
|
|
45
|
+
export async function call(root, cmd, args = {}, { url, tab, timeout } = {}) {
|
|
46
|
+
const base = await devUrl(root, url)
|
|
47
|
+
const out = await request(base, {
|
|
48
|
+
method: 'POST',
|
|
49
|
+
body: JSON.stringify({ cmd, args, tab, timeout }),
|
|
50
|
+
})
|
|
51
|
+
if (!out.ok) throw fail(out.code ?? 'E_PAGE', out.error, { tabs: out.tabs })
|
|
52
|
+
return out.result
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function tabs(root, { url } = {}) {
|
|
56
|
+
const base = await devUrl(root, url)
|
|
57
|
+
const out = await request(base, { method: 'GET' })
|
|
58
|
+
return { url: base, agent: out.agent, tabs: out.tabs }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Wait until a tab is connected (after `launch` or `navigate`). KERF_BROWSER_WAIT_MS lengthens it: a cold Chrome on a busy CI runner can take longer. */
|
|
62
|
+
export async function waitForTab(
|
|
63
|
+
root,
|
|
64
|
+
{ url, ms = Number(process.env.KERF_BROWSER_WAIT_MS) || 15_000, check } = {},
|
|
65
|
+
) {
|
|
66
|
+
const until = Date.now() + ms
|
|
67
|
+
for (;;) {
|
|
68
|
+
check?.()
|
|
69
|
+
let connected
|
|
70
|
+
try {
|
|
71
|
+
connected = await tabs(root, { url })
|
|
72
|
+
} catch (e) {
|
|
73
|
+
if (Date.now() > until) throw e
|
|
74
|
+
}
|
|
75
|
+
check?.()
|
|
76
|
+
if (connected?.tabs.length) return connected
|
|
77
|
+
if (Date.now() > until) throw fail('E_NO_TAB', 'no tab connected in time')
|
|
78
|
+
await new Promise((r) => {
|
|
79
|
+
setTimeout(r, 150)
|
|
80
|
+
})
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// ---- a host page when the agent has no browser ------------------------------------------------------------------
|
|
85
|
+
|
|
86
|
+
const chromes = {
|
|
87
|
+
darwin: [
|
|
88
|
+
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
|
89
|
+
'/Applications/Chromium.app/Contents/MacOS/Chromium',
|
|
90
|
+
'/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
|
|
91
|
+
],
|
|
92
|
+
linux: [
|
|
93
|
+
'/usr/bin/google-chrome',
|
|
94
|
+
'/usr/bin/google-chrome-stable',
|
|
95
|
+
'/usr/bin/chromium',
|
|
96
|
+
'/usr/bin/chromium-browser',
|
|
97
|
+
'/snap/bin/chromium',
|
|
98
|
+
],
|
|
99
|
+
win32: [
|
|
100
|
+
'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
|
|
101
|
+
'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
|
|
102
|
+
],
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function findChrome() {
|
|
106
|
+
const env = process.env.KERF_CHROME ?? process.env.CHROME_PATH
|
|
107
|
+
if (env && existsSync(env)) return env
|
|
108
|
+
return (chromes[process.platform] ?? []).find((p) => existsSync(p)) ?? null
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const stateFile = (root) => join(root, '.kerf', 'browser', 'chrome.json')
|
|
112
|
+
|
|
113
|
+
// Report only URL structure, never credentials, query parameters or fragments.
|
|
114
|
+
function safeUrl(value) {
|
|
115
|
+
try {
|
|
116
|
+
const url = new URL(value)
|
|
117
|
+
url.username = ''
|
|
118
|
+
url.password = ''
|
|
119
|
+
url.search = ''
|
|
120
|
+
url.hash = ''
|
|
121
|
+
return url.href.slice(0, 500)
|
|
122
|
+
} catch {
|
|
123
|
+
return '[invalid URL]'
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async function devtoolsJson(port, path, signal) {
|
|
128
|
+
const response = await fetch(`http://127.0.0.1:${port}${path}`, { signal })
|
|
129
|
+
if (!response.ok || !response.body) throw new Error('DevTools endpoint unavailable')
|
|
130
|
+
const reader = response.body.getReader()
|
|
131
|
+
const chunks = []
|
|
132
|
+
let size = 0
|
|
133
|
+
try {
|
|
134
|
+
for (;;) {
|
|
135
|
+
const { value, done } = await reader.read()
|
|
136
|
+
if (done) break
|
|
137
|
+
size += value.length
|
|
138
|
+
if (size > 32_768) throw new Error('DevTools response too large')
|
|
139
|
+
chunks.push(value)
|
|
140
|
+
}
|
|
141
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
142
|
+
} finally {
|
|
143
|
+
await reader.cancel().catch(() => {})
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Append bounded, failure-only DevTools evidence without replacing the launch error. */
|
|
148
|
+
export async function diagnoseLaunch(error, profile, expected) {
|
|
149
|
+
try {
|
|
150
|
+
const port = readFileSync(join(profile, 'DevToolsActivePort'), 'utf8').split('\n')[0]
|
|
151
|
+
if (!/^\d{1,5}$/.test(port) || +port < 1 || +port > 65535) throw new Error('invalid port')
|
|
152
|
+
const signal = AbortSignal.timeout(750)
|
|
153
|
+
const [version, targets] = await Promise.all([
|
|
154
|
+
devtoolsJson(port, '/json/version', signal).catch(() => null),
|
|
155
|
+
devtoolsJson(port, '/json/list', signal).catch(() => null),
|
|
156
|
+
])
|
|
157
|
+
const browser =
|
|
158
|
+
typeof version?.Browser === 'string'
|
|
159
|
+
? (version.Browser.match(/^(?:Chrome|Chromium|HeadlessChrome|Edg)\/[0-9.]+/)?.[0] ??
|
|
160
|
+
'unavailable')
|
|
161
|
+
: 'unavailable'
|
|
162
|
+
const pages = Array.isArray(targets)
|
|
163
|
+
? targets
|
|
164
|
+
.filter((target) => target?.type === 'page')
|
|
165
|
+
.slice(0, 10)
|
|
166
|
+
.map((target) => ({
|
|
167
|
+
url: safeUrl(target.url),
|
|
168
|
+
state:
|
|
169
|
+
typeof target.attached === 'boolean'
|
|
170
|
+
? target.attached
|
|
171
|
+
? 'attached'
|
|
172
|
+
: 'not attached'
|
|
173
|
+
: target.webSocketDebuggerUrl
|
|
174
|
+
? 'debuggable'
|
|
175
|
+
: 'no debugger',
|
|
176
|
+
}))
|
|
177
|
+
: 'unavailable'
|
|
178
|
+
error.message += `; DevTools: ${JSON.stringify({ browser, expected: safeUrl(expected), pages })}`
|
|
179
|
+
} catch {
|
|
180
|
+
error.message += `; DevTools unavailable; expected: ${safeUrl(expected)}`
|
|
181
|
+
}
|
|
182
|
+
return error
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Start a headless Chrome on `route` (a plain page; @kerf-js/core/agent connects back to the dev server).
|
|
187
|
+
* @param {string} root
|
|
188
|
+
* @param {string} [route]
|
|
189
|
+
* @param {{ url?: string | undefined, headed?: boolean | undefined }} [options]
|
|
190
|
+
*/
|
|
191
|
+
export async function launch(root, route = '/', { url, headed = false } = {}) {
|
|
192
|
+
const exe = findChrome()
|
|
193
|
+
if (!exe)
|
|
194
|
+
throw fail(
|
|
195
|
+
'E_NO_CHROME',
|
|
196
|
+
'no Chrome or Chromium found; open the app in your own browser instead, or set KERF_CHROME',
|
|
197
|
+
)
|
|
198
|
+
close(root)
|
|
199
|
+
const base = await devUrl(root, url)
|
|
200
|
+
const profile = join(root, '.kerf', 'browser', 'profile')
|
|
201
|
+
mkdirSync(profile, { recursive: true })
|
|
202
|
+
const args = [
|
|
203
|
+
`--user-data-dir=${profile}`,
|
|
204
|
+
'--remote-debugging-port=0',
|
|
205
|
+
'--no-first-run',
|
|
206
|
+
'--no-default-browser-check',
|
|
207
|
+
'--disable-background-timer-throttling',
|
|
208
|
+
'--disable-renderer-backgrounding',
|
|
209
|
+
...(headed ? [] : ['--headless=new']),
|
|
210
|
+
...(process.getuid?.() === 0
|
|
211
|
+
? ['--no-sandbox']
|
|
212
|
+
: []) /* Chrome won't start as root with its sandbox: a container, CI */,
|
|
213
|
+
`${base}${route.startsWith('/') ? route : `/${route}`}`,
|
|
214
|
+
]
|
|
215
|
+
const child = spawn(exe, args, { detached: true, stdio: ['ignore', 'ignore', 'pipe'] })
|
|
216
|
+
let stderr = '',
|
|
217
|
+
failure = null
|
|
218
|
+
child.stderr.on('data', (chunk) => {
|
|
219
|
+
stderr = (stderr + chunk.toString()).slice(-4096)
|
|
220
|
+
})
|
|
221
|
+
child.on('error', (error) => {
|
|
222
|
+
failure = `spawn: ${error.message}`
|
|
223
|
+
})
|
|
224
|
+
child.on('exit', (code, signal) => {
|
|
225
|
+
failure = `exit: ${code}, signal: ${signal}`
|
|
226
|
+
})
|
|
227
|
+
child.unref()
|
|
228
|
+
child.stderr.unref?.()
|
|
229
|
+
writeFileSync(stateFile(root), JSON.stringify({ pid: child.pid, profile, exe }))
|
|
230
|
+
try {
|
|
231
|
+
const t = await waitForTab(root, {
|
|
232
|
+
url,
|
|
233
|
+
check: () => {
|
|
234
|
+
if (failure) throw fail('E_CHROME', `Chrome ${failure}; stderr: ${stderr}`)
|
|
235
|
+
},
|
|
236
|
+
})
|
|
237
|
+
return { launched: true, pid: child.pid, headless: !headed, ...t }
|
|
238
|
+
} catch (error) {
|
|
239
|
+
await diagnoseLaunch(error, profile, args.at(-1))
|
|
240
|
+
close(root)
|
|
241
|
+
child.stderr.destroy()
|
|
242
|
+
error.message += ` (Chrome ${failure ?? 'still running'}; stderr: ${stderr})`
|
|
243
|
+
throw error
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export function close(root) {
|
|
248
|
+
const file = stateFile(root)
|
|
249
|
+
if (!existsSync(file)) return { closed: false }
|
|
250
|
+
const { pid } = JSON.parse(readFileSync(file, 'utf8'))
|
|
251
|
+
try {
|
|
252
|
+
process.kill(pid)
|
|
253
|
+
} catch {}
|
|
254
|
+
rmSync(file, { force: true })
|
|
255
|
+
return { closed: true, pid }
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** A PNG of the launched Chrome's page (DevTools protocol). An agent's own browser takes its own screenshots. */
|
|
259
|
+
export async function screenshot(root, out) {
|
|
260
|
+
const file = stateFile(root)
|
|
261
|
+
if (!existsSync(file))
|
|
262
|
+
throw fail(
|
|
263
|
+
'E_NO_CHROME',
|
|
264
|
+
'screenshot needs `kerf browser launch`; in your own browser, use its screenshot tool',
|
|
265
|
+
)
|
|
266
|
+
const { profile } = JSON.parse(readFileSync(file, 'utf8'))
|
|
267
|
+
const [port] = readFileSync(join(profile, 'DevToolsActivePort'), 'utf8').split('\n')
|
|
268
|
+
const targets = await (await fetch(`http://127.0.0.1:${port}/json`)).json()
|
|
269
|
+
const page = targets.find((t) => t.type === 'page')
|
|
270
|
+
if (!page) throw fail('E_NO_TAB', 'the launched Chrome has no page')
|
|
271
|
+
const ws = new WebSocket(page.webSocketDebuggerUrl)
|
|
272
|
+
await new Promise((ok, no) => {
|
|
273
|
+
ws.onopen = ok
|
|
274
|
+
ws.onerror = () => no(fail('E_CDP', 'could not reach the page over the DevTools protocol'))
|
|
275
|
+
})
|
|
276
|
+
const data = await new Promise((ok, no) => {
|
|
277
|
+
ws.onmessage = (e) => {
|
|
278
|
+
const m = JSON.parse(e.data)
|
|
279
|
+
if (m.id !== 1) return
|
|
280
|
+
if (m.error) no(fail('E_CDP', m.error.message))
|
|
281
|
+
else ok(m.result.data)
|
|
282
|
+
}
|
|
283
|
+
ws.send(JSON.stringify({ id: 1, method: 'Page.captureScreenshot', params: { format: 'png' } }))
|
|
284
|
+
})
|
|
285
|
+
ws.close()
|
|
286
|
+
const path = out ?? join(root, '.kerf', 'browser', `screenshot-${Date.now()}.png`)
|
|
287
|
+
mkdirSync(join(path, '..'), { recursive: true })
|
|
288
|
+
writeFileSync(path, Buffer.from(data, 'base64'))
|
|
289
|
+
return { path }
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Big payloads go to a file; the reply holds the path (research 05: snapshots pile up in context). */
|
|
293
|
+
export function spill(root, name, text, limit = 8000) {
|
|
294
|
+
if (typeof text !== 'string' || text.length <= limit) return text
|
|
295
|
+
const path = join(root, '.kerf', 'browser', `${name}-${Date.now()}.txt`)
|
|
296
|
+
mkdirSync(join(path, '..'), { recursive: true })
|
|
297
|
+
writeFileSync(path, text)
|
|
298
|
+
return { path, chars: text.length, head: `${text.slice(0, 1200)}\n…` }
|
|
299
|
+
}
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
// `kerf browser` commands, shared by the CLI and the `kerf mcp` browser tools. Each takes structured params and
|
|
2
|
+
// returns JSON; the page side is @kerf-js/core/agent (packages/core/src/agent.ts).
|
|
3
|
+
|
|
4
|
+
import { mkdirSync, writeFileSync } from 'node:fs'
|
|
5
|
+
import { dirname, isAbsolute, join } from 'node:path'
|
|
6
|
+
import { call, close, launch, screenshot, spill, tabs, waitForTab } from './client.mjs'
|
|
7
|
+
|
|
8
|
+
export const actions = [
|
|
9
|
+
'click',
|
|
10
|
+
'dblclick',
|
|
11
|
+
'hover',
|
|
12
|
+
'focus',
|
|
13
|
+
'clear',
|
|
14
|
+
'fill',
|
|
15
|
+
'type',
|
|
16
|
+
'press',
|
|
17
|
+
'select',
|
|
18
|
+
'check',
|
|
19
|
+
'uncheck',
|
|
20
|
+
]
|
|
21
|
+
export const expectations = [
|
|
22
|
+
'visible',
|
|
23
|
+
'absent',
|
|
24
|
+
'text',
|
|
25
|
+
'exactText',
|
|
26
|
+
'value',
|
|
27
|
+
'checked',
|
|
28
|
+
'unchecked',
|
|
29
|
+
'disabled',
|
|
30
|
+
'enabled',
|
|
31
|
+
'focused',
|
|
32
|
+
'count',
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
const sleep = (ms) =>
|
|
36
|
+
new Promise((r) => {
|
|
37
|
+
setTimeout(r, ms)
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @param {string} root project root
|
|
42
|
+
* @param {string} cmd
|
|
43
|
+
* @param {Record<string, any>} p params
|
|
44
|
+
* @param {{ url?: string, tab?: string }} [o] dev server URL and tab
|
|
45
|
+
*/
|
|
46
|
+
export async function browser(root, cmd, p = {}, o = {}) {
|
|
47
|
+
const page = (name, args, extra) => call(root, name, args, { ...o, ...extra })
|
|
48
|
+
switch (cmd) {
|
|
49
|
+
case 'tabs':
|
|
50
|
+
return tabs(root, o)
|
|
51
|
+
case 'launch':
|
|
52
|
+
return launch(root, p.route ?? '/', { url: o.url, headed: p.headed })
|
|
53
|
+
case 'close':
|
|
54
|
+
return close(root)
|
|
55
|
+
case 'open':
|
|
56
|
+
return await openPage(root, p, o, page)
|
|
57
|
+
case 'snapshot': {
|
|
58
|
+
const out = await page('snapshot', {
|
|
59
|
+
interactive: p.interactive,
|
|
60
|
+
scope: p.scope,
|
|
61
|
+
delta: p.delta,
|
|
62
|
+
graph: p.graph,
|
|
63
|
+
})
|
|
64
|
+
if (!p.full) {
|
|
65
|
+
if (out.tree) out.tree = spill(root, 'snapshot', out.tree)
|
|
66
|
+
if (out.graph) out.graph = spill(root, 'graph', out.graph)
|
|
67
|
+
}
|
|
68
|
+
return out
|
|
69
|
+
}
|
|
70
|
+
case 'act':
|
|
71
|
+
return page('act', { target: p.target, action: p.action, value: p.value })
|
|
72
|
+
case 'assert':
|
|
73
|
+
return page('assert', { target: p.target, expect: p.expect, timeout: p.timeout })
|
|
74
|
+
case 'graph': {
|
|
75
|
+
const out = await page('graph', { filter: p.filter })
|
|
76
|
+
return {
|
|
77
|
+
graph: p.full ? out.graph : spill(root, 'graph', out.graph),
|
|
78
|
+
nodes: out.nodes.length,
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
case 'set':
|
|
82
|
+
return page('set', { name: p.name, value: p.value })
|
|
83
|
+
case 'time':
|
|
84
|
+
return page('time', { op: p.op, ms: p.ms, reload: p.reload })
|
|
85
|
+
case 'net':
|
|
86
|
+
return page('net', { op: p.op, ms: p.ms })
|
|
87
|
+
case 'record': {
|
|
88
|
+
const out = await page('record', {
|
|
89
|
+
op: p.op,
|
|
90
|
+
text: p.text,
|
|
91
|
+
component: p.component,
|
|
92
|
+
from: p.from,
|
|
93
|
+
props: p.props,
|
|
94
|
+
imports: p.imports,
|
|
95
|
+
name: p.name,
|
|
96
|
+
})
|
|
97
|
+
if (p.op === 'code' && p.out) {
|
|
98
|
+
const file = isAbsolute(p.out) ? p.out : join(root, p.out)
|
|
99
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
100
|
+
writeFileSync(file, out.code)
|
|
101
|
+
return { ...out, written: file }
|
|
102
|
+
}
|
|
103
|
+
return out
|
|
104
|
+
}
|
|
105
|
+
case 'logs':
|
|
106
|
+
return page('logs', {})
|
|
107
|
+
case 'overlay':
|
|
108
|
+
return page('overlay', { show: p.show })
|
|
109
|
+
case 'info':
|
|
110
|
+
return page('info', {})
|
|
111
|
+
case 'reload':
|
|
112
|
+
return page('reload', {})
|
|
113
|
+
case 'screenshot':
|
|
114
|
+
return screenshot(root, p.out && (isAbsolute(p.out) ? p.out : join(root, p.out)))
|
|
115
|
+
default:
|
|
116
|
+
throw Object.assign(new Error(`unknown browser command ${cmd}`), { code: 'E_USAGE' })
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function openPage(root, p, o, page) {
|
|
121
|
+
const before = await page('info', {})
|
|
122
|
+
await page('navigate', { to: p.route ?? '/' })
|
|
123
|
+
// Same tab id after the load (@kerf-js/core/agent keeps it in sessionStorage); wait for the new document to say hello.
|
|
124
|
+
const until = Date.now() + 15_000
|
|
125
|
+
do {
|
|
126
|
+
await sleep(150)
|
|
127
|
+
try {
|
|
128
|
+
const info = await page('info', {}, { timeout: 2000 })
|
|
129
|
+
if (info.url !== before.url || p.route === new URL(before.url).pathname) return info
|
|
130
|
+
} catch {}
|
|
131
|
+
} while (Date.now() <= until)
|
|
132
|
+
return waitForTab(root, o)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** `button "Add Banana"`, `label Coupon`, `text Cart`, `@e5` → a target, and how many words it took. */
|
|
136
|
+
export function parseTarget(words) {
|
|
137
|
+
const [a, b] = words
|
|
138
|
+
if (!a)
|
|
139
|
+
throw Object.assign(
|
|
140
|
+
new Error('missing target: <role> <name>, label <text>, text <text>, or @ref'),
|
|
141
|
+
{ code: 'E_USAGE' },
|
|
142
|
+
)
|
|
143
|
+
if (a.startsWith('@')) return [a, 1]
|
|
144
|
+
if (a === 'label') return [{ label: b }, 2]
|
|
145
|
+
if (a === 'text') return [{ text: b }, 2]
|
|
146
|
+
return [
|
|
147
|
+
b === undefined || b === '-' ? { role: a } : { role: a, name: b },
|
|
148
|
+
b === undefined ? 1 : 2,
|
|
149
|
+
]
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** CLI words → params. */
|
|
153
|
+
export function cliParams(cmd, words, flags) {
|
|
154
|
+
const num = (v) => (v === undefined ? undefined : Number(v))
|
|
155
|
+
switch (cmd) {
|
|
156
|
+
case 'launch':
|
|
157
|
+
case 'open':
|
|
158
|
+
return { route: words[0] ?? '/', headed: !!flags.headed }
|
|
159
|
+
case 'snapshot':
|
|
160
|
+
return {
|
|
161
|
+
interactive: !!flags.interactive,
|
|
162
|
+
delta: !!flags.delta,
|
|
163
|
+
graph: flags['graph-only'] ? 'only' : flags['no-graph'] ? false : (flags.graph ?? true),
|
|
164
|
+
scope: flags.scope ? parseScope(flags.scope) : undefined,
|
|
165
|
+
full: !!flags.full,
|
|
166
|
+
}
|
|
167
|
+
case 'act': {
|
|
168
|
+
const [target, n] = parseTarget(words)
|
|
169
|
+
const action = words[n] ?? 'click'
|
|
170
|
+
if (!actions.includes(action))
|
|
171
|
+
throw Object.assign(new Error(`unknown action ${action}: ${actions.join(', ')}`), {
|
|
172
|
+
code: 'E_USAGE',
|
|
173
|
+
})
|
|
174
|
+
return { target, action, value: words[n + 1] }
|
|
175
|
+
}
|
|
176
|
+
case 'assert': {
|
|
177
|
+
const [target, n] = parseTarget(words)
|
|
178
|
+
const kind = words[n] ?? 'visible'
|
|
179
|
+
if (!expectations.includes(kind))
|
|
180
|
+
throw Object.assign(new Error(`unknown expectation ${kind}: ${expectations.join(', ')}`), {
|
|
181
|
+
code: 'E_USAGE',
|
|
182
|
+
})
|
|
183
|
+
const v = words[n + 1]
|
|
184
|
+
return {
|
|
185
|
+
target,
|
|
186
|
+
expect: {
|
|
187
|
+
[kind]:
|
|
188
|
+
kind === 'count'
|
|
189
|
+
? Number(v)
|
|
190
|
+
: ['text', 'exactText', 'value'].includes(kind)
|
|
191
|
+
? (v ?? '')
|
|
192
|
+
: true,
|
|
193
|
+
},
|
|
194
|
+
timeout: num(flags.timeout),
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
case 'graph':
|
|
198
|
+
return { filter: words[0], full: !!flags.full }
|
|
199
|
+
case 'set': {
|
|
200
|
+
let value = words[1]
|
|
201
|
+
try {
|
|
202
|
+
value = JSON.parse(words[1])
|
|
203
|
+
} catch {}
|
|
204
|
+
return { name: words[0], value }
|
|
205
|
+
}
|
|
206
|
+
case 'time':
|
|
207
|
+
return { op: words[0] ?? 'status', ms: num(words[1]), reload: !!flags.reload }
|
|
208
|
+
case 'net':
|
|
209
|
+
return { op: words[0] ?? 'status', ms: num(words[1]) }
|
|
210
|
+
case 'record':
|
|
211
|
+
return {
|
|
212
|
+
op: words[0] ?? 'code',
|
|
213
|
+
text: words.slice(1).join(' '),
|
|
214
|
+
component: flags.component,
|
|
215
|
+
from: flags.from,
|
|
216
|
+
props: flags.props,
|
|
217
|
+
name: flags.name,
|
|
218
|
+
out: flags.out,
|
|
219
|
+
}
|
|
220
|
+
case 'overlay':
|
|
221
|
+
return { show: words[0] === undefined ? undefined : words[0] !== 'off' }
|
|
222
|
+
case 'screenshot':
|
|
223
|
+
return { out: flags.out }
|
|
224
|
+
default:
|
|
225
|
+
return {}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const parseScope = (s) =>
|
|
230
|
+
s.startsWith('@')
|
|
231
|
+
? s
|
|
232
|
+
: (() => {
|
|
233
|
+
const i = s.indexOf(':')
|
|
234
|
+
return i < 0 ? { role: s } : { role: s.slice(0, i), name: s.slice(i + 1) }
|
|
235
|
+
})()
|
|
236
|
+
|
|
237
|
+
export const browserUsage = `usage: kerf browser <command> [--json] [--url <dev server>] [--tab <id>]
|
|
238
|
+
|
|
239
|
+
The page is the app open in any browser (yours, an agent's, or \`launch\`); the dev server relays to it.
|
|
240
|
+
In a browser that runs JS, the same commands are \`await __kerf__.agent.run('<command>', args)\`.
|
|
241
|
+
|
|
242
|
+
tabs tabs connected to the dev server
|
|
243
|
+
launch [route] [--headed] start a headless Chrome on the app (when you have no browser)
|
|
244
|
+
open <route> navigate the tab
|
|
245
|
+
snapshot [--interactive] [--delta] [--scope role:name|@ref] [--graph-only|--no-graph] [--full]
|
|
246
|
+
roles, names and refs, plus the reactive graph (Cart.total = 42.5 ← …)
|
|
247
|
+
act <role> <name> <action> [value] click dblclick hover focus clear fill type press select check uncheck
|
|
248
|
+
act @e5 <action> [value] (or: act label <text> …, act text <text> …)
|
|
249
|
+
assert <target> <expectation> [v] visible absent text exactText value checked unchecked disabled enabled focused count
|
|
250
|
+
graph [filter] the named reactive graph
|
|
251
|
+
set <Name.box> <json> write state by its graph name (dev only)
|
|
252
|
+
time pause [--reload]|advance <ms>|resume|status
|
|
253
|
+
net offline|online|latency <ms>|drop|reset|status
|
|
254
|
+
record start|stop|note <text>|code [--component App --from ./App --props '{…}' --out file.test.tsx]
|
|
255
|
+
logs console errors/warnings and uncaught errors since the last call
|
|
256
|
+
overlay [on|off] the graph panel in the page (Alt+Shift+G)
|
|
257
|
+
screenshot [--out file.png] launched Chrome only; use your own browser's screenshot otherwise
|
|
258
|
+
close stop the launched Chrome`
|
package/src/capture.mjs
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// `kerf capture …` runs @kerf-js/capture's command from the project, so the CLI itself carries no browser driver.
|
|
2
|
+
import { createRequire } from 'node:module'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { pathToFileURL } from 'node:url'
|
|
5
|
+
|
|
6
|
+
/** Runs `kerf capture <argv>` with the project's @kerf-js/capture; resolves with its exit code. */
|
|
7
|
+
export async function commandCapture(argv, root) {
|
|
8
|
+
let entry
|
|
9
|
+
try {
|
|
10
|
+
entry = createRequire(join(root, 'package.json')).resolve('@kerf-js/capture/cli')
|
|
11
|
+
} catch {
|
|
12
|
+
throw Object.assign(
|
|
13
|
+
new Error(
|
|
14
|
+
'kerf capture needs @kerf-js/capture in this project: pnpm add -D @kerf-js/capture',
|
|
15
|
+
),
|
|
16
|
+
{ code: 'E_USAGE' },
|
|
17
|
+
)
|
|
18
|
+
}
|
|
19
|
+
const { main } = await import(pathToFileURL(entry).href)
|
|
20
|
+
return main(argv)
|
|
21
|
+
}
|