proofed-cli 0.1.3 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +176 -122
- package/dist/action/requests.js +130 -0
- package/dist/{server.js → action/server.js} +17 -3
- package/dist/changes.js +7 -1
- package/dist/{args.js → check/args.js} +31 -3
- package/dist/check/cache.js +89 -0
- package/dist/{check.js → check/check.js} +86 -40
- package/dist/{doctor.js → check/doctor.js} +55 -19
- package/dist/check/help.js +139 -0
- package/dist/{list.js → check/list.js} +27 -15
- package/dist/{pipeline.js → check/pipeline.js} +106 -68
- package/dist/{render.js → check/render.js} +22 -15
- package/dist/check/run.js +277 -0
- package/dist/check/targetfilter.js +10 -0
- package/dist/check/textcheck.js +162 -0
- package/dist/env.js +6 -0
- package/dist/fix/agent.js +21 -0
- package/dist/fix/claude.js +30 -0
- package/dist/fix/codex.js +71 -0
- package/dist/fix/fixsetup.js +76 -0
- package/dist/fix/fixtarget.js +48 -0
- package/dist/fix/models.js +67 -0
- package/dist/github.js +62 -14
- package/dist/integrations/claude-stop.js +104 -0
- package/dist/integrations/cli.js +63 -0
- package/dist/integrations/mcp.js +130 -0
- package/dist/kane/creditmeter.js +104 -0
- package/dist/kane/kane.js +131 -0
- package/dist/kane/kaneauth.js +84 -0
- package/dist/kane/kaneversion.js +13 -0
- package/dist/paths.js +32 -0
- package/dist/process.js +65 -0
- package/dist/proofed.js +34 -16
- package/dist/{live.js → report/live.js} +1 -1
- package/dist/{livefile.js → report/livefile.js} +1 -1
- package/dist/{report.js → report/report.js} +105 -125
- package/dist/report/reportdata.js +120 -0
- package/dist/{result.js → report/result.js} +12 -7
- package/dist/{runfile.js → report/runfile.js} +2 -2
- package/dist/report/runresult.js +5 -0
- package/dist/scenarios.js +41 -19
- package/dist/secrets.js +74 -0
- package/dist/{cdp.js → targets/cdp.js} +20 -6
- package/dist/targets/chrome.js +98 -0
- package/dist/{clip.js → targets/clip.js} +21 -11
- package/dist/{precheck.js → targets/precheck.js} +53 -20
- package/dist/targets/preparetarget.js +350 -0
- package/dist/{recorder.js → targets/recorder.js} +154 -19
- package/dist/{serve.js → targets/serve.js} +9 -13
- package/dist/{target.js → targets/target.js} +42 -7
- package/dist/targets/targetchecks.js +139 -0
- package/dist/timing.js +25 -0
- package/dist/types.js +1 -0
- package/dist/which.js +26 -13
- package/docs/cli.md +370 -0
- package/package.json +10 -5
- package/dist/cache.js +0 -48
- package/dist/chrome.js +0 -77
- package/dist/help.js +0 -133
- package/dist/kane.js +0 -75
- package/dist/kaneauth.js +0 -48
- package/dist/models.js +0 -44
- package/dist/requests.js +0 -58
- package/dist/run.js +0 -173
- /package/dist/{deps.js → targets/deps.js} +0 -0
package/dist/scenarios.js
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
|
+
import { gitPath, matchesPath } from "./paths.js";
|
|
1
2
|
import { execFileSync } from "node:child_process";
|
|
2
3
|
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
3
|
-
import {
|
|
4
|
+
import { posix, join } from "node:path";
|
|
5
|
+
import { env } from "./env.js";
|
|
6
|
+
export function checkScenarioId(id, platform = process.platform) {
|
|
7
|
+
if (!id || id === "." || id === ".." || /[/\\\0]/.test(id))
|
|
8
|
+
throw new Error("unsafe scenario id");
|
|
9
|
+
if (platform === "win32" && (/[<>:"|?*\x00-\x1f]/.test(id) || /[. ]$/.test(id) || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(id)))
|
|
10
|
+
throw new Error("unsafe scenario id on Windows");
|
|
11
|
+
}
|
|
4
12
|
// A scenario is a Markdown file: a small frontmatter block, then the plain-English objective Kane runs.
|
|
5
13
|
// ---
|
|
6
14
|
// name: Promo code total
|
|
@@ -16,25 +24,37 @@ export function parseScenario(file, text) {
|
|
|
16
24
|
const meta = new Map();
|
|
17
25
|
for (const line of head.split("\n")) {
|
|
18
26
|
const kv = /^(\w+):\s*(.*)$/.exec(line.trim());
|
|
19
|
-
if (kv)
|
|
20
|
-
|
|
27
|
+
if (kv) {
|
|
28
|
+
const raw = kv[2].trim();
|
|
29
|
+
const single = /^'((?:[^']|'')*)'$/.exec(raw);
|
|
30
|
+
const double = /^"((?:[^"\\]|\\.)*)"$/.exec(raw);
|
|
31
|
+
meta.set(kv[1], single ? single[1].replaceAll("''", "'") : double ? JSON.parse(raw) : raw);
|
|
32
|
+
}
|
|
21
33
|
}
|
|
22
34
|
const list = (raw = "") => raw
|
|
23
35
|
.replace(/^\[|\]$/g, "")
|
|
24
36
|
.split(",")
|
|
25
37
|
.map((s) => s.trim().replace(/^["']|["']$/g, ""))
|
|
26
38
|
.filter(Boolean);
|
|
27
|
-
|
|
39
|
+
file = gitPath(file);
|
|
40
|
+
const id = posix.basename(file, ".md");
|
|
41
|
+
checkScenarioId(id);
|
|
28
42
|
const objective = body.trim();
|
|
29
43
|
if (!objective)
|
|
30
44
|
throw new Error(`${file}: empty objective`);
|
|
45
|
+
const timeout = meta.get("timeout_minutes");
|
|
46
|
+
const timeoutMinutes = timeout === undefined ? undefined : Number(timeout);
|
|
47
|
+
if (timeoutMinutes !== undefined && !(Number.isInteger(timeoutMinutes) && timeoutMinutes >= 1 && timeoutMinutes <= 30))
|
|
48
|
+
throw new Error(`${file}: timeout_minutes must be a whole number from 1 to 30`);
|
|
31
49
|
return {
|
|
50
|
+
...Object.fromEntries([...meta].filter(([key]) => ["target", "execution", "app", "device", "os_version", "launch", "cdp_endpoint"].includes(key))),
|
|
32
51
|
id,
|
|
33
52
|
file,
|
|
34
53
|
name: meta.get("name") ?? id,
|
|
35
54
|
paths: list(meta.get("paths")),
|
|
36
|
-
url: meta.get("url") ?? "/",
|
|
55
|
+
url: meta.get("url") ?? (meta.has("target") && meta.get("target") !== "web" ? "" : "/"),
|
|
37
56
|
objective,
|
|
57
|
+
...(timeoutMinutes && { timeoutMinutes }),
|
|
38
58
|
};
|
|
39
59
|
}
|
|
40
60
|
export function loadScenarios(dir) {
|
|
@@ -51,7 +71,7 @@ export function readScenarios(dir) {
|
|
|
51
71
|
if (!existsSync(dir) || !statSync(dir).isDirectory())
|
|
52
72
|
return { missing: true, scenarios, errors };
|
|
53
73
|
for (const f of readdirSync(dir).filter((f) => f.endsWith(".md")).sort()) {
|
|
54
|
-
const file = join(dir, f);
|
|
74
|
+
const file = gitPath(join(dir, f));
|
|
55
75
|
try {
|
|
56
76
|
scenarios.push(parseScenario(file, readFileSync(file, "utf8")));
|
|
57
77
|
}
|
|
@@ -69,21 +89,23 @@ export function loadScenariosOr(dir, rev) {
|
|
|
69
89
|
if (!rev)
|
|
70
90
|
return [];
|
|
71
91
|
const git = (...args) => execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
.map((f) => parseScenario(f, git("show", `${rev}:${f}`)));
|
|
78
|
-
}
|
|
79
|
-
catch {
|
|
80
|
-
return [];
|
|
81
|
-
}
|
|
92
|
+
return git("ls-tree", "-z", "--name-only", rev, "--", `${gitPath(dir).replace(/\/$/, "")}/`)
|
|
93
|
+
.split("\0")
|
|
94
|
+
.filter((f) => f.endsWith(".md"))
|
|
95
|
+
.sort()
|
|
96
|
+
.map((f) => parseScenario(f, git("show", `${rev}:./${f}`)));
|
|
82
97
|
}
|
|
98
|
+
export const touches = (s, file) => gitPath(file) === gitPath(s.file) || s.paths.some((glob) => matchesPath(file, glob));
|
|
83
99
|
// A scenario runs when the diff touches one of its paths, or the scenario file itself.
|
|
84
100
|
// No `paths` means "always run".
|
|
85
101
|
export function affectedBy(scenarios, changed) {
|
|
86
|
-
return scenarios.filter((s) => s.paths.length === 0 ||
|
|
87
|
-
|
|
88
|
-
|
|
102
|
+
return scenarios.filter((s) => s.paths.length === 0 || changed.some((file) => touches(s, file)));
|
|
103
|
+
}
|
|
104
|
+
export function pickScenarios({ changed, only, rev }) {
|
|
105
|
+
const all = loadScenariosOr(env("PROOFED_SCENARIOS", ".proofed/scenarios"), rev);
|
|
106
|
+
const unknown = only?.filter((id) => !all.some((s) => s.id === id));
|
|
107
|
+
if (unknown?.length)
|
|
108
|
+
throw new Error(`No scenario ${unknown.join(", ")} in ${env("PROOFED_SCENARIOS", ".proofed/scenarios")}.`);
|
|
109
|
+
const selected = only?.length ? all.filter((s) => only.includes(s.id)) : changed ? affectedBy(all, changed) : all;
|
|
110
|
+
return { selected, skipped: all.filter((s) => !selected.includes(s)).map((s) => s.name) };
|
|
89
111
|
}
|
package/dist/secrets.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Job credentials an agent must not see, and must not get into a commit, a report or the dashboard.
|
|
2
|
+
import { closeSync, openSync, readFileSync, readSync, statSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
// Not given to Claude or Codex. The agent's own key is added back by its runner.
|
|
5
|
+
export const JOB_SECRETS = [
|
|
6
|
+
"GITHUB_TOKEN", "GH_TOKEN", "LT_USERNAME", "LT_ACCESS_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "CODEX_API_KEY", "CODEX_AUTH_JSON",
|
|
7
|
+
"ACTIONS_ID_TOKEN_REQUEST_TOKEN", "ACTIONS_ID_TOKEN_REQUEST_URL", "ACTIONS_RUNTIME_TOKEN", "ACTIONS_RUNTIME_URL",
|
|
8
|
+
];
|
|
9
|
+
const VALUES = ["GITHUB_TOKEN", "GH_TOKEN", "LT_ACCESS_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "CODEX_API_KEY", "CODEX_AUTH_JSON", "ACTIONS_ID_TOKEN_REQUEST_TOKEN", "ACTIONS_RUNTIME_TOKEN"];
|
|
10
|
+
export function withoutJobSecrets(env, keep = []) {
|
|
11
|
+
return Object.fromEntries(Object.entries(env).filter(([name]) => keep.includes(name) || !JOB_SECRETS.includes(name)));
|
|
12
|
+
}
|
|
13
|
+
// Only read the auth file that the action staged for this run.
|
|
14
|
+
function codexAuth(env) {
|
|
15
|
+
if (env.CODEX_AUTH_JSON)
|
|
16
|
+
return env.CODEX_AUTH_JSON;
|
|
17
|
+
if (!env.PROOFED_CODEX_HOME)
|
|
18
|
+
return undefined;
|
|
19
|
+
try {
|
|
20
|
+
return readFileSync(join(env.PROOFED_CODEX_HOME, "auth.json"), "utf8");
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
// The values as they appear in the clear and in the forms git and HTTP headers carry them.
|
|
27
|
+
// Longest first, so masking a short value never leaves part of a longer one.
|
|
28
|
+
export function secretValues(env = process.env) {
|
|
29
|
+
const auth = codexAuth(env);
|
|
30
|
+
const values = VALUES.map((name) => name === "CODEX_AUTH_JSON" ? auth : env[name]);
|
|
31
|
+
if (auth) {
|
|
32
|
+
try {
|
|
33
|
+
const json = JSON.parse(auth);
|
|
34
|
+
values.push(json?.OPENAI_API_KEY, json?.tokens?.access_token, json?.tokens?.refresh_token, json?.tokens?.id_token);
|
|
35
|
+
}
|
|
36
|
+
catch { /* The raw value is still masked. */ }
|
|
37
|
+
}
|
|
38
|
+
const raw = values.filter((value) => typeof value === "string" && value.length >= 8);
|
|
39
|
+
const encoded = raw.flatMap((v) => [Buffer.from(`x-access-token:${v}`).toString("base64"), Buffer.from(v).toString("base64")]);
|
|
40
|
+
return [...new Set([...raw, ...encoded])].sort((a, b) => b.length - a.length);
|
|
41
|
+
}
|
|
42
|
+
export const maskSecrets = (text, values = secretValues()) => values.reduce((t, v) => t.replaceAll(v, "***"), text);
|
|
43
|
+
// The first of `files` that holds a job credential. An agent can still read the credentials of the
|
|
44
|
+
// job's own processes (/proc/<pid>/environ), so what it writes is checked before anything leaves the runner.
|
|
45
|
+
export function fileWithSecret(files, values = secretValues()) {
|
|
46
|
+
if (values.length === 0)
|
|
47
|
+
return undefined;
|
|
48
|
+
const needles = values.map((value) => Buffer.from(value));
|
|
49
|
+
const overlap = Math.max(1, ...needles.map((value) => value.length)) - 1;
|
|
50
|
+
const chunk = 64 * 1024;
|
|
51
|
+
const buffer = Buffer.allocUnsafe(chunk + overlap);
|
|
52
|
+
return files.find((file) => {
|
|
53
|
+
if (!statSync(file, { throwIfNoEntry: false })?.isFile())
|
|
54
|
+
return false;
|
|
55
|
+
const fd = openSync(file, "r");
|
|
56
|
+
try {
|
|
57
|
+
let kept = 0;
|
|
58
|
+
for (;;) {
|
|
59
|
+
const read = readSync(fd, buffer, kept, chunk, null);
|
|
60
|
+
if (read === 0)
|
|
61
|
+
return false;
|
|
62
|
+
const scanned = buffer.subarray(0, kept + read);
|
|
63
|
+
if (needles.some((value) => scanned.includes(value)))
|
|
64
|
+
return true;
|
|
65
|
+
// A credential can start in this chunk and end in the next one.
|
|
66
|
+
kept = Math.min(scanned.length, overlap);
|
|
67
|
+
scanned.copy(buffer, 0, scanned.length - kept);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
closeSync(fd);
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
}
|
|
@@ -1,12 +1,24 @@
|
|
|
1
1
|
// A minimal Chrome DevTools Protocol client over the browser websocket.
|
|
2
2
|
// Only the events Proofed listens to are typed.
|
|
3
|
-
export
|
|
4
|
-
|
|
3
|
+
export const cdpUrl = (endpoint, path) => new URL(`/json/${path}`, endpoint);
|
|
4
|
+
export async function connectCdp(endpoint, signal) {
|
|
5
|
+
const { webSocketDebuggerUrl } = (await (await fetch(cdpUrl(endpoint, "version"), { signal })).json());
|
|
6
|
+
signal?.throwIfAborted();
|
|
5
7
|
const ws = new WebSocket(webSocketDebuggerUrl);
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
const opened = Promise.withResolvers();
|
|
9
|
+
ws.onopen = () => opened.resolve();
|
|
10
|
+
ws.onerror = () => opened.reject(new Error("Could not connect to Chrome over CDP"));
|
|
11
|
+
const abort = () => {
|
|
12
|
+
opened.reject(signal?.reason);
|
|
13
|
+
ws.close();
|
|
14
|
+
};
|
|
15
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
16
|
+
try {
|
|
17
|
+
await opened.promise;
|
|
18
|
+
}
|
|
19
|
+
finally {
|
|
20
|
+
signal?.removeEventListener("abort", abort);
|
|
21
|
+
}
|
|
10
22
|
let lastId = 0;
|
|
11
23
|
const pending = new Map();
|
|
12
24
|
const listeners = new Map();
|
|
@@ -32,6 +44,8 @@ export async function connectCdp(endpoint) {
|
|
|
32
44
|
};
|
|
33
45
|
return {
|
|
34
46
|
send(method, params = {}, sessionId) {
|
|
47
|
+
if (ws.readyState !== WebSocket.OPEN)
|
|
48
|
+
return Promise.reject(new Error("CDP connection closed"));
|
|
35
49
|
const id = ++lastId;
|
|
36
50
|
ws.send(JSON.stringify({ id, method, params, ...(sessionId && { sessionId }) }));
|
|
37
51
|
return new Promise((resolve, reject) => pending.set(id, { resolve: (v) => resolve(v), reject }));
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { killTree } from "../process.js";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join, win32 } from "node:path";
|
|
6
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
7
|
+
import { adopt, stopping } from "../children.js";
|
|
8
|
+
import { log } from "../log.js";
|
|
9
|
+
import { cdpUrl } from "./cdp.js";
|
|
10
|
+
export function chromeCandidates(env = process.env, platform = process.platform) {
|
|
11
|
+
return [env.CHROME_PATH, ...(platform === "win32"
|
|
12
|
+
? [env.ProgramFiles ?? "C:\\Program Files", env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)", env.LOCALAPPDATA]
|
|
13
|
+
.filter((p) => !!p).map((p) => win32.join(p, "Google", "Chrome", "Application", "chrome.exe"))
|
|
14
|
+
: ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/usr/bin/chromium"])]
|
|
15
|
+
.filter((p) => !!p);
|
|
16
|
+
}
|
|
17
|
+
export const findChrome = (env = process.env, platform = process.platform) => chromeCandidates(env, platform).find((p) => existsSync(p));
|
|
18
|
+
const chromePath = () => {
|
|
19
|
+
const found = findChrome();
|
|
20
|
+
if (!found)
|
|
21
|
+
throw new Error("Chrome not found; set CHROME_PATH");
|
|
22
|
+
return found;
|
|
23
|
+
};
|
|
24
|
+
// We start Chrome ourselves (instead of letting Kane do it) so the recorder can attach to the same browser.
|
|
25
|
+
// Chrome picks a free debugging port and writes it to DevToolsActivePort in its profile folder.
|
|
26
|
+
// A cold runner can take a while to start the first Chrome, so it gets 30 s and one more try.
|
|
27
|
+
export async function launchChrome({ headless = true } = {}) {
|
|
28
|
+
for (let attempt = 1;; attempt++) {
|
|
29
|
+
try {
|
|
30
|
+
return await startChrome(headless);
|
|
31
|
+
}
|
|
32
|
+
catch (e) {
|
|
33
|
+
if (attempt >= 2 || stopping())
|
|
34
|
+
throw e;
|
|
35
|
+
log(`${e instanceof Error ? e.message : e}; starting Chrome again`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
async function startChrome(headless) {
|
|
40
|
+
const bin = chromePath();
|
|
41
|
+
const profile = mkdtempSync(join(tmpdir(), "proofed-chrome-"));
|
|
42
|
+
const proc = spawn(bin, [
|
|
43
|
+
"--remote-debugging-port=0",
|
|
44
|
+
`--user-data-dir=${profile}`,
|
|
45
|
+
"--window-size=1280,800",
|
|
46
|
+
"--no-first-run",
|
|
47
|
+
"--no-default-browser-check",
|
|
48
|
+
"--mute-audio",
|
|
49
|
+
// A throwaway profile has nothing to protect; without this, macOS shows a keychain dialog when HOME has no login keychain.
|
|
50
|
+
"--use-mock-keychain",
|
|
51
|
+
// Several pages are open at once (the start-page check opens one per scenario). Chrome would lower the priority of
|
|
52
|
+
// the ones in the background, and on a busy macOS runner they then answer CDP calls tens of seconds late.
|
|
53
|
+
"--disable-renderer-backgrounding",
|
|
54
|
+
"--disable-background-timer-throttling",
|
|
55
|
+
"--disable-backgrounding-occluded-windows",
|
|
56
|
+
...(headless ? ["--headless=new"] : []),
|
|
57
|
+
...(process.env.CI ? ["--no-sandbox"] : []),
|
|
58
|
+
"about:blank",
|
|
59
|
+
], { stdio: "ignore", detached: process.platform !== "win32", windowsHide: true });
|
|
60
|
+
let failure;
|
|
61
|
+
const exitedDuringStart = new AbortController();
|
|
62
|
+
const signal = AbortSignal.any([exitedDuringStart.signal, AbortSignal.timeout(30_000)]);
|
|
63
|
+
const kill = (signal = "SIGTERM") => killTree(proc.pid, signal);
|
|
64
|
+
const { promise: exited, resolve: done } = Promise.withResolvers();
|
|
65
|
+
const release = adopt({ kill, exited });
|
|
66
|
+
const finished = (error) => {
|
|
67
|
+
failure = error;
|
|
68
|
+
exitedDuringStart.abort();
|
|
69
|
+
// The browser can exit before its renderer and GPU helpers.
|
|
70
|
+
if (process.platform !== "win32")
|
|
71
|
+
kill("SIGKILL");
|
|
72
|
+
release();
|
|
73
|
+
done();
|
|
74
|
+
// A profile is a few megabytes, one per Chrome; a laptop keeps its temp folder.
|
|
75
|
+
try {
|
|
76
|
+
rmSync(profile, { recursive: true, force: true, maxRetries: 2 });
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
// A helper still writing into it; the OS cleans the temp folder eventually.
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
proc.once("error", finished);
|
|
83
|
+
proc.once("exit", (code) => finished(new Error(`Chrome exited with code ${code} on start`)));
|
|
84
|
+
while (!signal.aborted) {
|
|
85
|
+
const port = existsSync(join(profile, "DevToolsActivePort"))
|
|
86
|
+
? readFileSync(join(profile, "DevToolsActivePort"), "utf8").split("\n")[0]?.trim()
|
|
87
|
+
: undefined;
|
|
88
|
+
if (port) {
|
|
89
|
+
const endpoint = `http://127.0.0.1:${port}`;
|
|
90
|
+
const ok = await fetch(cdpUrl(endpoint, "version"), { signal }).then((r) => r.ok, () => false);
|
|
91
|
+
if (ok && !signal.aborted)
|
|
92
|
+
return { endpoint, close: () => kill() };
|
|
93
|
+
}
|
|
94
|
+
await delay(200, undefined, { signal }).catch(() => { });
|
|
95
|
+
}
|
|
96
|
+
kill();
|
|
97
|
+
throw failure ?? new Error("Chrome did not open its debugging port");
|
|
98
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { execFileSync } from "node:child_process";
|
|
2
|
-
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { connectCdp } from "./cdp.js";
|
|
5
5
|
const FPS = 25;
|
|
@@ -229,6 +229,8 @@ export async function makeClip({ frames, actions, focus, endpoint, marks = [] },
|
|
|
229
229
|
const { frameTree } = await page("Page.getFrameTree");
|
|
230
230
|
await page("Page.setDocumentContent", { frameId: frameTree.frame.id, html: STAGE(size) });
|
|
231
231
|
let shown;
|
|
232
|
+
let drawing;
|
|
233
|
+
let rendered;
|
|
232
234
|
for (let n = 0; n < count; n++) {
|
|
233
235
|
const t = n / FPS;
|
|
234
236
|
const cam = shots[n];
|
|
@@ -236,20 +238,28 @@ export async function makeClip({ frames, actions, focus, endpoint, marks = [] },
|
|
|
236
238
|
const source = time.frameAt(t).file;
|
|
237
239
|
const c = pointer(t);
|
|
238
240
|
const k = ui * Math.sqrt(cam.z);
|
|
241
|
+
const overlay = {
|
|
242
|
+
tx: size.width / 2 - cam.x * cam.z,
|
|
243
|
+
ty: size.height / 2 - cam.y * cam.z,
|
|
244
|
+
z: cam.z,
|
|
245
|
+
cursor: c && { ...toScreen(c), opacity: c.opacity, k: k * c.press },
|
|
246
|
+
ripple: c?.ripple && { ...toScreen(c.ripple), p: c.ripple.p, k },
|
|
247
|
+
};
|
|
248
|
+
const next = JSON.stringify(overlay);
|
|
249
|
+
const file = join(dir, `${String(n).padStart(5, "0")}.jpg`);
|
|
250
|
+
if (rendered && shown === source && drawing === next) {
|
|
251
|
+
copyFileSync(rendered, file);
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
239
254
|
await page("Runtime.evaluate", {
|
|
240
255
|
awaitPromise: true,
|
|
241
|
-
expression: `paint(${JSON.stringify({
|
|
242
|
-
src: source === shown ? undefined : `data:image/jpeg;base64,${readFileSync(source).toString("base64")}`,
|
|
243
|
-
tx: size.width / 2 - cam.x * cam.z,
|
|
244
|
-
ty: size.height / 2 - cam.y * cam.z,
|
|
245
|
-
z: cam.z,
|
|
246
|
-
cursor: c && { ...toScreen(c), opacity: c.opacity, k: k * c.press },
|
|
247
|
-
ripple: c?.ripple && { ...toScreen(c.ripple), p: c.ripple.p, k },
|
|
248
|
-
})})`,
|
|
256
|
+
expression: `paint(${shown === source ? next : JSON.stringify({ ...overlay, src: `data:image/jpeg;base64,${readFileSync(source).toString("base64")}` })})`,
|
|
249
257
|
});
|
|
250
|
-
shown = source;
|
|
251
258
|
const { data } = await page("Page.captureScreenshot", { format: "jpeg", quality: 90 });
|
|
252
|
-
writeFileSync(
|
|
259
|
+
writeFileSync(file, Buffer.from(data, "base64"));
|
|
260
|
+
shown = source;
|
|
261
|
+
drawing = next;
|
|
262
|
+
rendered = file;
|
|
253
263
|
}
|
|
254
264
|
await cdp.send("Target.closeTarget", { targetId });
|
|
255
265
|
}
|
|
@@ -9,8 +9,8 @@ import { join } from "node:path";
|
|
|
9
9
|
import { setTimeout as delay } from "node:timers/promises";
|
|
10
10
|
import { connectCdp } from "./cdp.js";
|
|
11
11
|
import { launchChrome } from "./chrome.js";
|
|
12
|
-
import { log } from "
|
|
13
|
-
import { BLANK_PAGE } from "
|
|
12
|
+
import { log } from "../log.js";
|
|
13
|
+
import { BLANK_PAGE } from "../report/runfile.js";
|
|
14
14
|
const LOAD_TIMEOUT = 15_000;
|
|
15
15
|
// How long a loaded page gets to put something on screen.
|
|
16
16
|
const SETTLE = 3_000;
|
|
@@ -18,6 +18,9 @@ const SETTLE = 3_000;
|
|
|
18
18
|
// be about to render, and the exception may be someone else's (an analytics script).
|
|
19
19
|
const RECHECK = 10_000;
|
|
20
20
|
const POLL = 250;
|
|
21
|
+
// Target creation, attachment and CDP replies also need time when Chrome is busy.
|
|
22
|
+
const CHECK_TIMEOUT = LOAD_TIMEOUT + SETTLE + RECHECK + 20_000;
|
|
23
|
+
const SCREENSHOT_GRACE = 5_000;
|
|
21
24
|
// Any text, or an element that shows something without text.
|
|
22
25
|
const PAINTED = `(() => {
|
|
23
26
|
const body = document.body;
|
|
@@ -28,8 +31,8 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
|
28
31
|
const limit = (ms) => delay(ms, undefined, { ref: false });
|
|
29
32
|
// "TypeError: Cannot read properties of null (reading '1')", without the stack.
|
|
30
33
|
const message = (d) => (d.exception?.description ?? (d.exception?.value !== undefined ? String(d.exception.value) : d.text)).split("\n")[0].trim();
|
|
31
|
-
// The URLs that crashed while loading. Screenshots go into `dir`.
|
|
32
|
-
export async function findCrashes(urls, dir) {
|
|
34
|
+
// The URLs that crashed while loading. Screenshots go into `dir`. Tests on a starved runner pass a longer time limit.
|
|
35
|
+
export async function findCrashes(urls, dir, checkTimeout = CHECK_TIMEOUT) {
|
|
33
36
|
const crashes = new Map();
|
|
34
37
|
if (urls.length === 0)
|
|
35
38
|
return crashes;
|
|
@@ -42,7 +45,7 @@ export async function findCrashes(urls, dir) {
|
|
|
42
45
|
const opened = Date.now();
|
|
43
46
|
const cdp = await connectCdp(chrome.endpoint);
|
|
44
47
|
await Promise.all(urls.map(async (url, i) => {
|
|
45
|
-
const crash = await
|
|
48
|
+
const crash = await crashOf(cdp, url, join(dir, `crash-${i}.jpg`), checkTimeout).catch(() => undefined);
|
|
46
49
|
if (crash)
|
|
47
50
|
crashes.set(url, crash);
|
|
48
51
|
}));
|
|
@@ -58,43 +61,73 @@ export async function findCrashes(urls, dir) {
|
|
|
58
61
|
}
|
|
59
62
|
return crashes;
|
|
60
63
|
}
|
|
61
|
-
async function
|
|
64
|
+
async function detectCrash(cdp, url) {
|
|
62
65
|
const { targetId } = await cdp.send("Target.createTarget", { url: "about:blank" });
|
|
63
66
|
const { sessionId } = await cdp.send("Target.attachToTarget", { targetId, flatten: true });
|
|
64
67
|
const page = (method, params = {}) => cdp.send(method, params, sessionId);
|
|
65
68
|
const errors = [];
|
|
66
|
-
|
|
67
|
-
const
|
|
69
|
+
const load = Promise.withResolvers();
|
|
70
|
+
const loaded = new Set();
|
|
71
|
+
let navigationLoader;
|
|
68
72
|
cdp.on("Runtime.exceptionThrown", ({ exceptionDetails }, from) => from === sessionId && errors.push(message(exceptionDetails)));
|
|
69
|
-
|
|
73
|
+
// The initial about:blank can finish loading first, and the real load can arrive before the navigate reply.
|
|
74
|
+
cdp.on("Page.lifecycleEvent", ({ loaderId, name }, from) => {
|
|
75
|
+
if (from !== sessionId || name !== "load")
|
|
76
|
+
return;
|
|
77
|
+
if (loaderId === navigationLoader)
|
|
78
|
+
load.resolve(true);
|
|
79
|
+
else if (!navigationLoader)
|
|
80
|
+
loaded.add(loaderId);
|
|
81
|
+
});
|
|
70
82
|
await page("Page.enable");
|
|
83
|
+
await page("Page.setLifecycleEventsEnabled", { enabled: true });
|
|
71
84
|
await page("Runtime.enable");
|
|
72
|
-
const { errorText } = await page("Page.navigate", { url });
|
|
73
|
-
if (errorText)
|
|
74
|
-
return undefined;
|
|
75
|
-
|
|
85
|
+
const { errorText, loaderId } = await page("Page.navigate", { url });
|
|
86
|
+
if (errorText || !loaderId)
|
|
87
|
+
return undefined;
|
|
88
|
+
navigationLoader = loaderId;
|
|
89
|
+
if (!loaded.has(loaderId) && !(await Promise.race([load.promise, limit(LOAD_TIMEOUT)])))
|
|
90
|
+
return undefined;
|
|
76
91
|
// `blank` only turns true on a definite answer; an evaluation lost to a navigation counts as unknown.
|
|
77
92
|
let blank = false;
|
|
78
93
|
let rechecking = false;
|
|
94
|
+
// The recheck also waits for a timer in the page itself. It fires only after every timer the app set before it,
|
|
95
|
+
// so on a starved machine an app that renders a few seconds after load still gets to render first.
|
|
96
|
+
let pageWaited = true;
|
|
79
97
|
for (let until = Date.now() + SETTLE;; await sleep(POLL)) {
|
|
80
98
|
const painted = await page("Runtime.evaluate", { expression: PAINTED, returnByValue: true }).then(({ result }) => result.value, () => undefined);
|
|
81
99
|
if (painted === true)
|
|
82
100
|
return undefined;
|
|
83
101
|
blank = painted === false;
|
|
84
|
-
if (Date.now() < until)
|
|
102
|
+
if (Date.now() < until || !pageWaited)
|
|
85
103
|
continue;
|
|
86
104
|
if (rechecking || !blank || errors.length === 0)
|
|
87
105
|
break;
|
|
88
106
|
rechecking = true;
|
|
89
|
-
until
|
|
107
|
+
until = Date.now() + RECHECK;
|
|
108
|
+
pageWaited = false;
|
|
109
|
+
const waited = () => (pageWaited = true);
|
|
110
|
+
void page("Runtime.evaluate", { expression: `new Promise((r) => setTimeout(r, ${RECHECK}))`, awaitPromise: true }).then(waited, waited);
|
|
90
111
|
}
|
|
91
112
|
const error = blank ? errors[0] : undefined;
|
|
92
|
-
|
|
113
|
+
return error ? { error, page } : undefined;
|
|
114
|
+
}
|
|
115
|
+
async function crashOf(cdp, url, file, checkTimeout) {
|
|
116
|
+
const deadline = Date.now() + checkTimeout;
|
|
117
|
+
const crash = await Promise.race([detectCrash(cdp, url), limit(checkTimeout)]);
|
|
118
|
+
if (!crash)
|
|
93
119
|
return undefined;
|
|
94
|
-
//
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
120
|
+
// Give late verdicts time for a screenshot. A stalled capture only costs the picture.
|
|
121
|
+
const screenshot = await Promise.race([
|
|
122
|
+
crash.page("Page.captureScreenshot", { format: "jpeg", quality: 80 }),
|
|
123
|
+
limit(Math.max(deadline - Date.now(), SCREENSHOT_GRACE)),
|
|
124
|
+
]).then((capture) => {
|
|
125
|
+
if (!capture)
|
|
126
|
+
return undefined;
|
|
127
|
+
writeFileSync(file, Buffer.from(capture.data, "base64"));
|
|
128
|
+
return file;
|
|
129
|
+
}).catch(() => undefined);
|
|
130
|
+
return { error: crash.error, screenshot };
|
|
98
131
|
}
|
|
99
132
|
// A normal failed result, so the report, the run file, the dashboard and the fixer need nothing new.
|
|
100
133
|
// The verdict is ours, in the shape Kane gives one. Kane never ran, so there are no steps or credits,
|