proofed-cli 0.0.0-stage → 0.1.1
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 +21 -0
- package/README.md +286 -2
- package/bin/node-version.cjs +11 -0
- package/bin/proofed.cjs +14 -0
- package/dist/args.js +156 -0
- package/dist/cache.js +48 -0
- package/dist/cdp.js +46 -0
- package/dist/changes.js +59 -0
- package/dist/check.js +334 -0
- package/dist/children.js +33 -0
- package/dist/chrome.js +77 -0
- package/dist/clip.js +270 -0
- package/dist/doctor.js +133 -0
- package/dist/github.js +143 -0
- package/dist/help.js +124 -0
- package/dist/kane.js +75 -0
- package/dist/list.js +82 -0
- package/dist/live.js +139 -0
- package/dist/livefile.js +83 -0
- package/dist/log.js +7 -0
- package/dist/models.js +44 -0
- package/dist/pipeline.js +194 -0
- package/dist/precheck.js +111 -0
- package/dist/proofed.js +70 -0
- package/dist/recorder.js +209 -0
- package/dist/render.js +426 -0
- package/dist/report.js +328 -0
- package/dist/requests.js +58 -0
- package/dist/result.js +135 -0
- package/dist/run.js +164 -0
- package/dist/runfile.js +11 -0
- package/dist/scenarios.js +89 -0
- package/dist/serve.js +82 -0
- package/dist/server.js +24 -0
- package/dist/setuperror.js +11 -0
- package/dist/target.js +132 -0
- package/dist/which.js +28 -0
- package/package.json +44 -4
package/dist/check.js
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
// `proofed check`: the PR check, run on this machine against the local change. Picks the scenarios
|
|
2
|
+
// the change touches, skips the passes it already paid for, makes sure the app answers, runs the
|
|
3
|
+
// rest with Kane in Chrome and says what broke: drawn live in a terminal, as plain lines in a pipe,
|
|
4
|
+
// as one JSON document with --json.
|
|
5
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { join, resolve } from "node:path";
|
|
7
|
+
import { CACHE_FILE, DEFAULT_CREDITS, cacheKey, estimate, readCache, writeCache } from "./cache.js";
|
|
8
|
+
import { findBase, localChanges, mergeBaseOf, repoRoot } from "./changes.js";
|
|
9
|
+
import { killChildren, stopChildren } from "./children.js";
|
|
10
|
+
import { findChrome } from "./chrome.js";
|
|
11
|
+
import { setLog } from "./log.js";
|
|
12
|
+
import { runAll } from "./pipeline.js";
|
|
13
|
+
import { colorOn, LiveView, PlainView } from "./render.js";
|
|
14
|
+
import { askedScenario } from "./requests.js";
|
|
15
|
+
import { buildDoc, errorDoc, quote, sameCommand, scenarioDoc } from "./result.js";
|
|
16
|
+
import { creditsOf } from "./run.js";
|
|
17
|
+
import { affectedBy, readScenarios } from "./scenarios.js";
|
|
18
|
+
import { answers, startApp } from "./serve.js";
|
|
19
|
+
import { SetupError } from "./setuperror.js";
|
|
20
|
+
import { isHttpUrl, resolveTarget } from "./target.js";
|
|
21
|
+
import { findKane } from "./which.js";
|
|
22
|
+
export const RESULT_FILE = "result.json";
|
|
23
|
+
export const outDirOf = (flags, io) => resolve(io.cwd, flags.out || io.env.PROOFED_OUT?.trim() || ".proofed-out");
|
|
24
|
+
export const scenariosDirOf = (flags, io) => flags.scenarios || io.env.PROOFED_SCENARIOS?.trim() || ".proofed/scenarios";
|
|
25
|
+
// Clips must never end up committed in the app's repo.
|
|
26
|
+
export function ensureOut(out) {
|
|
27
|
+
mkdirSync(out, { recursive: true });
|
|
28
|
+
const ignore = join(out, ".gitignore");
|
|
29
|
+
if (!existsSync(ignore))
|
|
30
|
+
writeFileSync(ignore, "*\n");
|
|
31
|
+
}
|
|
32
|
+
// Run from a folder inside the repo, the default scenarios folder isn't there; say where it is.
|
|
33
|
+
export function scenariosMissing(dir, flags, io, command) {
|
|
34
|
+
const root = flags.scenarios ? undefined : repoRoot(io.cwd);
|
|
35
|
+
if (root && root !== realpathSync(io.cwd) && existsSync(join(root, dir))) {
|
|
36
|
+
return new SetupError("wrong_directory", `${dir} is at the repository root, not in ${io.cwd}.`, `Run it from the root: cd ${quote(root)} && proofed ${command}`);
|
|
37
|
+
}
|
|
38
|
+
return new SetupError("scenarios_missing", `No scenarios: ${dir} doesn't exist here (${io.cwd}).`, `Run proofed in the app's repo, pass --scenarios <dir>, or check one thing: proofed check "the cart total updates"`);
|
|
39
|
+
}
|
|
40
|
+
export function makeView(flags, io) {
|
|
41
|
+
// An agent's shell shows stderr next to stdout: with --json, only progress goes there, since
|
|
42
|
+
// the details and the summary are in the document.
|
|
43
|
+
if (flags.json)
|
|
44
|
+
return new PlainView(io.stderr, { color: colorOn(io.env, false), brief: true });
|
|
45
|
+
if (io.stdout.isTTY && io.env.TERM !== "dumb") {
|
|
46
|
+
const view = new LiveView(io.stdout, { color: colorOn(io.env, true), err: io.stderr });
|
|
47
|
+
io.stdout.on?.("resize", () => view.draw());
|
|
48
|
+
return view;
|
|
49
|
+
}
|
|
50
|
+
return new PlainView(io.stdout, { color: colorOn(io.env, false), err: io.stderr });
|
|
51
|
+
}
|
|
52
|
+
const fromNote = (s) => (s.from.startsWith("--") ? "" : ` (url from ${s.from})`);
|
|
53
|
+
// Flags that say where the app and the scenarios are and how to run, so a printed command runs
|
|
54
|
+
// the same way. Not --no-cache or --dry-run: those were about this run.
|
|
55
|
+
function rerunFlags(flags) {
|
|
56
|
+
const pass = [
|
|
57
|
+
["--url", flags.url],
|
|
58
|
+
["--serve", flags.serve],
|
|
59
|
+
["--build", flags.build],
|
|
60
|
+
["--serve-timeout", flags.serveTimeout?.toString()],
|
|
61
|
+
["--base", flags.base],
|
|
62
|
+
["--scenarios", flags.scenarios],
|
|
63
|
+
["--out", flags.out],
|
|
64
|
+
["--concurrency", flags.concurrency?.toString()],
|
|
65
|
+
];
|
|
66
|
+
const on = [flags.reuse && "--reuse", flags.headed && "--headed", flags.json && "--json"].filter((f) => !!f);
|
|
67
|
+
return [...pass.flatMap(([name, v]) => (v ? [`${name} ${quote(v)}`] : [])), ...on];
|
|
68
|
+
}
|
|
69
|
+
export async function check(flags, text, io, view = makeView(flags, io)) {
|
|
70
|
+
const started = Date.now();
|
|
71
|
+
const out = outDirOf(flags, io);
|
|
72
|
+
const dir = scenariosDirOf(flags, io);
|
|
73
|
+
const rerun = { text, flags: rerunFlags(flags), selection: flags.only ? `--only ${flags.only.join(",")}` : flags.all ? "--all" : undefined };
|
|
74
|
+
const finished = new Map();
|
|
75
|
+
let app;
|
|
76
|
+
const write = (doc) => {
|
|
77
|
+
ensureOut(out);
|
|
78
|
+
writeFileSync(join(out, RESULT_FILE), `${JSON.stringify(doc, null, 2)}\n`);
|
|
79
|
+
if (flags.json)
|
|
80
|
+
io.stdout.write(`${JSON.stringify(doc, null, 2)}\n`);
|
|
81
|
+
};
|
|
82
|
+
// Ctrl-C (or a kill) mid-run: Kane, every Chrome and the app go first, then the exit.
|
|
83
|
+
// The run that was going ends on its own once Kane is killed; its result is dropped, the
|
|
84
|
+
// interrupt writes the document and sets the exit code.
|
|
85
|
+
let selected = [];
|
|
86
|
+
let interrupted;
|
|
87
|
+
const interrupt = (signal) => {
|
|
88
|
+
// A second Ctrl-C doesn't wait for anything.
|
|
89
|
+
if (interrupted) {
|
|
90
|
+
killChildren();
|
|
91
|
+
process.exit(130);
|
|
92
|
+
}
|
|
93
|
+
view.close();
|
|
94
|
+
io.stderr.write(`\nInterrupted (${signal}): stopping Kane, Chrome and the app. Kane may have spent credits before reporting them.\n`);
|
|
95
|
+
interrupted = (async () => {
|
|
96
|
+
await stopChildren();
|
|
97
|
+
await app?.stop();
|
|
98
|
+
const done = selected.filter((s) => finished.has(s.id)).map((s) => scenarioDoc({ scenario: s, result: finished.get(s.id) }, rerun));
|
|
99
|
+
write(errorDoc(new SetupError("interrupted", `Stopped by ${signal} before the check finished. Kane may have spent credits before reporting them.`, "Run the check again and let it finish; passes so far are cached."), 130, done));
|
|
100
|
+
return 130;
|
|
101
|
+
})();
|
|
102
|
+
};
|
|
103
|
+
// SIGHUP: a closed terminal tab or a dropped SSH session. Unhandled, it ends Node without
|
|
104
|
+
// stopping Kane, which runs on in its own process group and keeps spending credits.
|
|
105
|
+
const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
106
|
+
for (const signal of SIGNALS)
|
|
107
|
+
process.on(signal, interrupt);
|
|
108
|
+
try {
|
|
109
|
+
const doc = await run();
|
|
110
|
+
if (interrupted)
|
|
111
|
+
return await interrupted;
|
|
112
|
+
write(doc);
|
|
113
|
+
if (doc.dryRun && flags.json) {
|
|
114
|
+
view.close();
|
|
115
|
+
}
|
|
116
|
+
else if (doc.dryRun) {
|
|
117
|
+
for (const d of doc.scenarios)
|
|
118
|
+
view.info(`${d.cached ? "cached: " : "would run:"} ${d.id} (${d.name})${d.cached ? "" : `, about ${d.estimatedCredits} credits`}`);
|
|
119
|
+
view.info(`${doc.summary}. Dry run: nothing ran, no credits spent.`);
|
|
120
|
+
view.info(doc.next);
|
|
121
|
+
view.close();
|
|
122
|
+
}
|
|
123
|
+
else if (doc.scenarios.length === 0) {
|
|
124
|
+
// Nothing to run; the reason is already on screen.
|
|
125
|
+
view.close();
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
view.done(doc);
|
|
129
|
+
}
|
|
130
|
+
return doc.exitCode;
|
|
131
|
+
}
|
|
132
|
+
catch (e) {
|
|
133
|
+
if (interrupted)
|
|
134
|
+
return await interrupted;
|
|
135
|
+
// Anything unexpected is exit 3 with a document too: exit 1 means "a scenario failed", and an
|
|
136
|
+
// old result.json left in place would say the previous run's verdict.
|
|
137
|
+
const known = e instanceof SetupError;
|
|
138
|
+
if (!known && flags.verbose && e instanceof Error)
|
|
139
|
+
io.stderr.write(`${e.stack}\n`);
|
|
140
|
+
const doc = errorDoc(known ? e : new SetupError("internal", `Proofed hit an unexpected error: ${e instanceof Error ? e.message : String(e)}`, "Run it again with --verbose for the stack; nothing was checked."));
|
|
141
|
+
write(doc);
|
|
142
|
+
view.fail(doc);
|
|
143
|
+
return 3;
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
await app?.stop();
|
|
147
|
+
for (const signal of SIGNALS)
|
|
148
|
+
process.off(signal, interrupt);
|
|
149
|
+
}
|
|
150
|
+
async function run() {
|
|
151
|
+
const loaded = readScenarios(dir);
|
|
152
|
+
if (!text && loaded.missing)
|
|
153
|
+
throw scenariosMissing(dir, flags, io, "check");
|
|
154
|
+
if (!text && loaded.errors.length) {
|
|
155
|
+
const [first] = loaded.errors;
|
|
156
|
+
throw new SetupError("scenario_invalid", loaded.errors.map((e) => `${e.file}: ${e.message}`).join("\n"), `Fix the frontmatter of ${first.file} (see proofed list).`);
|
|
157
|
+
}
|
|
158
|
+
const all = loaded.scenarios;
|
|
159
|
+
const base = text ? undefined : findBase(io.cwd, flags.base);
|
|
160
|
+
const changed = base?.rev ? localChanges(io.cwd, base.rev) : undefined;
|
|
161
|
+
const common = {
|
|
162
|
+
base: base?.rev ?? null,
|
|
163
|
+
changedFiles: changed?.length ?? null,
|
|
164
|
+
seconds: 0,
|
|
165
|
+
out,
|
|
166
|
+
rerun,
|
|
167
|
+
estimatedCredits: 0,
|
|
168
|
+
};
|
|
169
|
+
let skipped;
|
|
170
|
+
let selection;
|
|
171
|
+
if (text) {
|
|
172
|
+
selected = [askedScenario("terminal", text)];
|
|
173
|
+
skipped = all.map((s) => ({ id: s.id, name: s.name, why: "only your text is checked" }));
|
|
174
|
+
selection = "your text";
|
|
175
|
+
}
|
|
176
|
+
else if (flags.only) {
|
|
177
|
+
const unknown = flags.only.filter((id) => !all.some((s) => s.id === id));
|
|
178
|
+
if (unknown.length) {
|
|
179
|
+
throw new SetupError("unknown_scenario", `No scenario ${unknown.join(", ")} in ${dir}. Scenarios: ${all.map((s) => s.id).join(", ") || "none"}.`, `Use ids from proofed list, e.g. proofed check --only ${all[0]?.id ?? "<id>"}`);
|
|
180
|
+
}
|
|
181
|
+
selected = all.filter((s) => flags.only.includes(s.id));
|
|
182
|
+
skipped = all.filter((s) => !selected.includes(s)).map((s) => ({ id: s.id, name: s.name, why: "not in --only" }));
|
|
183
|
+
selection = "--only";
|
|
184
|
+
}
|
|
185
|
+
else if (flags.all || !changed) {
|
|
186
|
+
selected = all;
|
|
187
|
+
skipped = [];
|
|
188
|
+
selection = flags.all ? "--all" : `every scenario, ${base?.why ?? "no base branch"}`;
|
|
189
|
+
}
|
|
190
|
+
else if (changed.length === 0) {
|
|
191
|
+
const summary = `Nothing changed against ${base.rev}.`;
|
|
192
|
+
view.info(`${summary} Use --all to run every scenario.`);
|
|
193
|
+
return buildDoc({ ...common, items: [], skipped: all.map((s) => ({ id: s.id, name: s.name, why: "nothing changed" })), url: null, idle: { summary, next: `Nothing to check. To run every scenario anyway: ${sameCommand(rerun, "--all")}` } });
|
|
194
|
+
}
|
|
195
|
+
else {
|
|
196
|
+
selected = affectedBy(all, changed);
|
|
197
|
+
skipped = all.filter((s) => !selected.includes(s)).map((s) => ({ id: s.id, name: s.name, why: "the change does not touch its paths" }));
|
|
198
|
+
selection = `changes against ${base.rev} (${changed.length} file${changed.length === 1 ? "" : "s"})`;
|
|
199
|
+
if (selected.length === 0) {
|
|
200
|
+
const summary = `No scenario covers the ${changed.length} changed file${changed.length === 1 ? "" : "s"}.`;
|
|
201
|
+
view.info(`${summary} Use --all to run every scenario.`);
|
|
202
|
+
return buildDoc({ ...common, items: [], skipped, url: null, idle: { summary, next: `Nothing to check. To run every scenario anyway: ${sameCommand(rerun, "--all")}` } });
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
const target = resolveTarget({ flags: { url: flags.url, serve: flags.serve, build: flags.build }, env: io.env, cwd: io.cwd });
|
|
206
|
+
const url = target.url?.value;
|
|
207
|
+
if (url !== undefined && !isHttpUrl(url)) {
|
|
208
|
+
throw new SetupError("url_invalid", `"${url}" (${target.url.from}) is not an http(s) URL.`, "Pass a full URL, e.g. --url http://localhost:5173");
|
|
209
|
+
}
|
|
210
|
+
const baseId = base?.rev ? mergeBaseOf(io.cwd, base.rev) : "";
|
|
211
|
+
let appState;
|
|
212
|
+
const cacheFile = join(out, CACHE_FILE);
|
|
213
|
+
const cache = readCache(cacheFile);
|
|
214
|
+
const keys = new Map();
|
|
215
|
+
const items = new Map();
|
|
216
|
+
for (const s of selected) {
|
|
217
|
+
if (s.file && url && changed && !flags.noCache) {
|
|
218
|
+
const key = cacheKey(s, new URL(s.url, url).href, changed, undefined, baseId);
|
|
219
|
+
keys.set(s.id, key);
|
|
220
|
+
const hit = cache.passes[s.id];
|
|
221
|
+
if (hit?.key === key)
|
|
222
|
+
items.set(s.id, { scenario: s, cached: hit });
|
|
223
|
+
}
|
|
224
|
+
if (!items.has(s.id))
|
|
225
|
+
items.set(s.id, { scenario: s, estimate: s.file ? estimate(cache, s.id) : DEFAULT_CREDITS });
|
|
226
|
+
}
|
|
227
|
+
const toRun = selected.filter((s) => "estimate" in items.get(s.id));
|
|
228
|
+
const cachedPasses = selected.flatMap((s) => {
|
|
229
|
+
const item = items.get(s.id);
|
|
230
|
+
return "cached" in item ? [{ id: s.id, name: s.name, cachedAt: item.cached.passedAt }] : [];
|
|
231
|
+
});
|
|
232
|
+
const estimatedCredits = toRun.reduce((sum, s) => sum + items.get(s.id).estimate, 0);
|
|
233
|
+
const plan = {
|
|
234
|
+
run: toRun,
|
|
235
|
+
cached: cachedPasses,
|
|
236
|
+
total: text ? 1 : all.length,
|
|
237
|
+
selection,
|
|
238
|
+
url,
|
|
239
|
+
estimate: estimatedCredits,
|
|
240
|
+
concurrency: flags.concurrency ?? (Number(io.env.PROOFED_CONCURRENCY) || 3),
|
|
241
|
+
dryRun: flags.dryRun,
|
|
242
|
+
};
|
|
243
|
+
const showPlan = () => {
|
|
244
|
+
view.plan(plan);
|
|
245
|
+
if (target.url && !target.url.from.startsWith("--"))
|
|
246
|
+
view.info(`url ${target.url.value} from ${target.url.from}`);
|
|
247
|
+
};
|
|
248
|
+
const docOf = (list, extra = {}) => buildDoc({ ...common, items: list, skipped, url: url ?? null, app: appState, estimatedCredits, seconds: Math.round((Date.now() - started) / 1000), ...extra });
|
|
249
|
+
if (flags.dryRun) {
|
|
250
|
+
showPlan();
|
|
251
|
+
return docOf(selected.map((s) => items.get(s.id)), { dryRun: true });
|
|
252
|
+
}
|
|
253
|
+
if (toRun.length === 0) {
|
|
254
|
+
showPlan();
|
|
255
|
+
return docOf(selected.map((s) => items.get(s.id)));
|
|
256
|
+
}
|
|
257
|
+
// The cheap checks first: nothing starts unless Kane and Chrome are both there.
|
|
258
|
+
const kane = findKane(io.env);
|
|
259
|
+
if (!kane.path) {
|
|
260
|
+
throw new SetupError("kane_missing", `Kane CLI not found (${kane.from}).`, io.env.KANE_CLI ? "Point KANE_CLI at the kane-cli binary, or unset it." : "npm install -g @testmuai/kane-cli, then kane-cli login");
|
|
261
|
+
}
|
|
262
|
+
if (!findChrome())
|
|
263
|
+
throw new SetupError("chrome_missing", "Chrome not found.", "Install Google Chrome, or set CHROME_PATH to its binary.");
|
|
264
|
+
if (!url) {
|
|
265
|
+
throw new SetupError("no_url", "Proofed doesn't know where the app runs.", `Pass --url http://localhost:5173 (and --serve "npm run dev" to have Proofed start it), set PROOFED_URL, or write .proofed/config.json: { "url": "http://localhost:5173", "serve": "npm run dev" }`);
|
|
266
|
+
}
|
|
267
|
+
ensureOut(out);
|
|
268
|
+
const runLog = join(out, "run.log");
|
|
269
|
+
writeFileSync(runLog, "");
|
|
270
|
+
setLog((line) => {
|
|
271
|
+
appendFileSync(runLog, `${line}\n`);
|
|
272
|
+
if (flags.verbose)
|
|
273
|
+
view.log(line);
|
|
274
|
+
});
|
|
275
|
+
showPlan();
|
|
276
|
+
if (await answers(url)) {
|
|
277
|
+
// With a build configured, what answers was built from some earlier code, and a pass on it
|
|
278
|
+
// would be a pass nobody saw.
|
|
279
|
+
if (target.build && !flags.reuse) {
|
|
280
|
+
throw new SetupError("app_already_running", `Something already answers at ${url}, so Proofed can't build and serve the current code there (build: ${target.build.value}). It may be serving an old build.`, `Stop the server on that port and run the check again, or pass --reuse to test what is running as it is.`);
|
|
281
|
+
}
|
|
282
|
+
appState = "reused";
|
|
283
|
+
view.info(`The app answers at ${url}; using it as it is${target.build ? " (--reuse: not rebuilt, passes are not cached)" : ""}.`);
|
|
284
|
+
}
|
|
285
|
+
else if (target.serve) {
|
|
286
|
+
const logFile = join(out, "serve.log");
|
|
287
|
+
writeFileSync(logFile, "");
|
|
288
|
+
const t0 = Date.now();
|
|
289
|
+
app = await startApp({
|
|
290
|
+
url,
|
|
291
|
+
serve: target.serve.value,
|
|
292
|
+
build: target.build?.value,
|
|
293
|
+
cwd: target.dir,
|
|
294
|
+
logFile,
|
|
295
|
+
timeoutSeconds: flags.serveTimeout ?? 60,
|
|
296
|
+
onPhase: (line) => view.phase(line),
|
|
297
|
+
});
|
|
298
|
+
appState = "started";
|
|
299
|
+
const from = [target.build && `build from ${target.build.from}`, `serve from ${target.serve.from}`].filter(Boolean).join(", ");
|
|
300
|
+
view.info(`Started the app in ${Math.round((Date.now() - t0) / 1000)} s (${from}); its output is in ${logFile}`);
|
|
301
|
+
}
|
|
302
|
+
else {
|
|
303
|
+
throw new SetupError("app_not_reachable", `Nothing answers at ${url}${fromNote(target.url)}.`, `Start the app first, or pass the command that serves it: proofed check --serve "npm run dev"`);
|
|
304
|
+
}
|
|
305
|
+
view.start();
|
|
306
|
+
const cacheable = !(appState === "reused" && target.build);
|
|
307
|
+
const onEvent = (e) => {
|
|
308
|
+
view.event(e);
|
|
309
|
+
if (e.type !== "finished")
|
|
310
|
+
return;
|
|
311
|
+
finished.set(e.id, e.result);
|
|
312
|
+
const key = keys.get(e.id);
|
|
313
|
+
if (!key)
|
|
314
|
+
return;
|
|
315
|
+
if (e.result.end?.credits_consumed !== undefined)
|
|
316
|
+
cache.last[e.id] = { credits: creditsOf(e.result) };
|
|
317
|
+
if (e.result.outcome === "passed" && cacheable) {
|
|
318
|
+
const clip = e.result.clip && { ...(e.result.clip.mp4 && { mp4: resolve(e.result.clip.mp4) }), jpg: resolve(e.result.clip.jpg) };
|
|
319
|
+
cache.passes[e.id] = { key, passedAt: new Date().toISOString(), seconds: e.result.seconds, ...(clip && { clip }) };
|
|
320
|
+
}
|
|
321
|
+
else {
|
|
322
|
+
delete cache.passes[e.id];
|
|
323
|
+
}
|
|
324
|
+
writeCache(cacheFile, cache);
|
|
325
|
+
};
|
|
326
|
+
const results = await runAll(toRun, out, plan.concurrency, { baseUrl: url, headless: !flags.headed, onEvent });
|
|
327
|
+
const byId = new Map(results.map((r) => [r.scenario.id, r]));
|
|
328
|
+
return docOf(selected.map((s) => {
|
|
329
|
+
const r = byId.get(s.id);
|
|
330
|
+
return r ? { scenario: s, result: r } : items.get(s.id);
|
|
331
|
+
}));
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
export const readResult = (out) => JSON.parse(readFileSync(join(out, RESULT_FILE), "utf8"));
|
package/dist/children.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
const children = new Set();
|
|
2
|
+
let stopped = false;
|
|
3
|
+
// Set once a stop begins: a run that is still going must not start a retry or a new Chrome.
|
|
4
|
+
export const stopping = () => stopped;
|
|
5
|
+
// Returns the function that forgets the process once it's gone. A process started after the stop
|
|
6
|
+
// began (a run that was between two steps) is killed at once.
|
|
7
|
+
export function adopt(child) {
|
|
8
|
+
if (stopped) {
|
|
9
|
+
child.kill("SIGKILL");
|
|
10
|
+
return () => { };
|
|
11
|
+
}
|
|
12
|
+
children.add(child);
|
|
13
|
+
return () => void children.delete(child);
|
|
14
|
+
}
|
|
15
|
+
// SIGTERM first, so Chrome closes its helpers; whatever is left after `grace` gets SIGKILL. Every
|
|
16
|
+
// child gets the SIGKILL, even one that exited: a process group can outlive its leader.
|
|
17
|
+
export async function stopChildren(grace = 1500) {
|
|
18
|
+
stopped = true;
|
|
19
|
+
const all = [...children];
|
|
20
|
+
for (const c of all)
|
|
21
|
+
c.kill("SIGTERM");
|
|
22
|
+
await Promise.race([Promise.all(all.map((c) => c.exited)), new Promise((r) => setTimeout(r, grace))]);
|
|
23
|
+
for (const c of all)
|
|
24
|
+
c.kill("SIGKILL");
|
|
25
|
+
children.clear();
|
|
26
|
+
}
|
|
27
|
+
// For an exit that can't wait.
|
|
28
|
+
export function killChildren() {
|
|
29
|
+
stopped = true;
|
|
30
|
+
for (const c of children)
|
|
31
|
+
c.kill("SIGKILL");
|
|
32
|
+
children.clear();
|
|
33
|
+
}
|
package/dist/chrome.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { adopt, stopping } from "./children.js";
|
|
6
|
+
import { log } from "./log.js";
|
|
7
|
+
const candidates = [
|
|
8
|
+
process.env.CHROME_PATH,
|
|
9
|
+
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
10
|
+
"/usr/bin/google-chrome",
|
|
11
|
+
"/usr/bin/google-chrome-stable",
|
|
12
|
+
"/usr/bin/chromium",
|
|
13
|
+
];
|
|
14
|
+
export const findChrome = () => candidates.find((p) => !!p && existsSync(p));
|
|
15
|
+
const chromePath = () => {
|
|
16
|
+
const found = findChrome();
|
|
17
|
+
if (!found)
|
|
18
|
+
throw new Error("Chrome not found; set CHROME_PATH");
|
|
19
|
+
return found;
|
|
20
|
+
};
|
|
21
|
+
// We start Chrome ourselves (instead of letting Kane do it) so the recorder can attach to the same browser.
|
|
22
|
+
// Chrome picks a free debugging port and writes it to DevToolsActivePort in its profile folder.
|
|
23
|
+
// A cold runner can take a while to start the first Chrome, so it gets 30 s and one more try.
|
|
24
|
+
export async function launchChrome({ headless = true } = {}) {
|
|
25
|
+
for (let attempt = 1;; attempt++) {
|
|
26
|
+
try {
|
|
27
|
+
return await startChrome(headless);
|
|
28
|
+
}
|
|
29
|
+
catch (e) {
|
|
30
|
+
if (attempt >= 2 || stopping())
|
|
31
|
+
throw e;
|
|
32
|
+
log(`${e instanceof Error ? e.message : e}; starting Chrome again`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
async function startChrome(headless) {
|
|
37
|
+
const profile = mkdtempSync(join(tmpdir(), "proofed-chrome-"));
|
|
38
|
+
const proc = spawn(chromePath(), [
|
|
39
|
+
"--remote-debugging-port=0",
|
|
40
|
+
`--user-data-dir=${profile}`,
|
|
41
|
+
"--window-size=1280,800",
|
|
42
|
+
"--no-first-run",
|
|
43
|
+
"--no-default-browser-check",
|
|
44
|
+
"--mute-audio",
|
|
45
|
+
...(headless ? ["--headless=new"] : []),
|
|
46
|
+
...(process.env.CI ? ["--no-sandbox"] : []),
|
|
47
|
+
"about:blank",
|
|
48
|
+
], { stdio: "ignore" });
|
|
49
|
+
let exited;
|
|
50
|
+
const release = adopt({ kill: (signal) => proc.kill(signal), exited: new Promise((r) => proc.once("exit", r)) });
|
|
51
|
+
proc.on("exit", (code) => {
|
|
52
|
+
exited = code;
|
|
53
|
+
release();
|
|
54
|
+
// A profile is a few megabytes, one per Chrome; a laptop keeps its temp folder.
|
|
55
|
+
try {
|
|
56
|
+
rmSync(profile, { recursive: true, force: true, maxRetries: 2 });
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
// A helper still writing into it; the OS cleans the temp folder eventually.
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
const deadline = Date.now() + 30_000;
|
|
63
|
+
while (Date.now() < deadline && exited === undefined) {
|
|
64
|
+
const port = existsSync(join(profile, "DevToolsActivePort"))
|
|
65
|
+
? readFileSync(join(profile, "DevToolsActivePort"), "utf8").split("\n")[0]?.trim()
|
|
66
|
+
: undefined;
|
|
67
|
+
if (port) {
|
|
68
|
+
const endpoint = `http://127.0.0.1:${port}`;
|
|
69
|
+
const ok = await fetch(`${endpoint}/json/version`).then((r) => r.ok, () => false);
|
|
70
|
+
if (ok)
|
|
71
|
+
return { endpoint, close: () => proc.kill() };
|
|
72
|
+
}
|
|
73
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
74
|
+
}
|
|
75
|
+
proc.kill();
|
|
76
|
+
throw new Error(exited !== undefined ? `Chrome exited with code ${exited} on start` : "Chrome did not open its debugging port");
|
|
77
|
+
}
|