cliprobe 1.8.1 → 1.10.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/dist/cli.js CHANGED
@@ -1,2704 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { createRequire } from "node:module";
3
- import { execFile, execFileSync, spawn } from "node:child_process";
4
- import { accessSync, closeSync, constants, existsSync, lstatSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
5
- import { delimiter, dirname, join, resolve, sep } from "node:path";
6
- import { tmpdir } from "node:os";
2
+ import { C as shellJoin, D as onInterrupt, E as handleInterrupts, S as MAX_TIMEOUT_MS, T as safe, _ as CONFIG_FILE, b as ProbeError, d as describeAccept, f as mainProbe, h as VERSION, l as prepare, m as planFromConfig, n as FORMAT_NAMES, o as execute, p as planFromArgs, r as isFormat, s as exitCodeFor, t as FORMATS, u as DEFAULT_TIMEOUT_MS, v as loadConfig, w as shellSplit, x as UsageError } from "./report-DuFcZAqG.js";
3
+ import { accessSync, constants, existsSync, lstatSync, readlinkSync, realpathSync, rmSync, statSync } from "node:fs";
4
+ import { dirname, resolve, sep } from "node:path";
7
5
  import { chmod, mkdir, rename, rm, writeFile } from "node:fs/promises";
8
- // src/core/interrupt.ts
9
- const cleanups = /* @__PURE__ */ new Set();
10
- /** Registers `cleanup` until the returned function is called. */
11
- function onInterrupt(cleanup) {
12
- cleanups.add(cleanup);
13
- return () => {
14
- cleanups.delete(cleanup);
15
- };
16
- }
17
- /** Runs every registered cleanup, newest first, so processes die before their directories go. */
18
- function runInterruptCleanups() {
19
- const pending = [...cleanups].reverse();
20
- cleanups.clear();
21
- for (const cleanup of pending) try {
22
- cleanup();
23
- } catch {}
24
- }
25
- /** The signals that stop cliprobe and how a shell reports each: 128 plus its number. */
26
- const INTERRUPT_SIGNALS = /* @__PURE__ */ new Map([
27
- ["SIGHUP", 129],
28
- ["SIGINT", 130],
29
- ["SIGTERM", 143]
30
- ]);
31
- /**
32
- * On SIGINT, SIGTERM or SIGHUP: cleans up, then dies by the same signal, so the
33
- * shell or CI runner sees 130, 143 or 129 as for any other program.
34
- */
35
- function handleInterrupts(target = process) {
36
- const signals = [...INTERRUPT_SIGNALS.keys()];
37
- for (const [signal, code] of INTERRUPT_SIGNALS) target.once(signal, () => {
38
- runInterruptCleanups();
39
- for (const s of signals) target.removeAllListeners(s);
40
- try {
41
- target.kill(target.pid, signal);
42
- } catch {
43
- target.exit(code);
44
- }
45
- });
46
- }
47
- // src/core/group.ts
48
- const isGone = (state) => state.startsWith("Z") || state.startsWith("X");
49
- /** Fields of a /proc/<pid>/stat line; the name may hold spaces and parentheses. */
50
- function parseProcStat(line) {
51
- const open = line.indexOf("(");
52
- const close = line.lastIndexOf(")");
53
- const fields = line.slice(close + 1).trim().split(" ");
54
- return {
55
- name: line.slice(open + 1, close),
56
- state: fields[0] ?? "",
57
- ppid: Number(fields[1] ?? ""),
58
- pgid: Number(fields[2] ?? ""),
59
- start: fields[19] ?? ""
60
- };
61
- }
62
- /** Every running process, without zombies, read from `<root>`. */
63
- function tableFromProc(root = "/proc", keep = () => true) {
64
- const table = [];
65
- for (const entry of readdirSync(root)) {
66
- if (!/^\d+$/.test(entry)) continue;
67
- try {
68
- const stat = parseProcStat(readFileSync(`${root}/${entry}/stat`, "utf8"));
69
- if (isGone(stat.state) || !keep(stat)) continue;
70
- const cmdline = readFileSync(`${root}/${entry}/cmdline`, "utf8").split("\0").filter(Boolean).join(" ");
71
- table.push({
72
- pid: Number(entry),
73
- ppid: stat.ppid,
74
- pgid: stat.pgid,
75
- start: stat.start,
76
- command: cmdline || stat.name
77
- });
78
- } catch {}
79
- }
80
- return table.sort((a, b) => a.pid - b.pid);
81
- }
82
- /** lstart is the only start time macOS ps gives; LC_ALL=C keeps its format fixed. */
83
- const PS_ARGS = [
84
- "-A",
85
- "-o",
86
- "pid=,ppid=,pgid=,lstart=,stat=,args="
87
- ];
88
- const PS_ENV = {
89
- ...process.env,
90
- LC_ALL: "C"
91
- };
92
- const PS_LINE = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+(\S+)\s+(.*)$/;
93
- /** Running processes from `ps -A -o pid=,ppid=,pgid=,lstart=,stat=,args=` output. */
94
- function parsePsTable(out) {
95
- const table = [];
96
- for (const line of out.split("\n")) {
97
- const m = PS_LINE.exec(line);
98
- if (!m || isGone(m[5] ?? "")) continue;
99
- table.push({
100
- pid: Number(m[1]),
101
- ppid: Number(m[2]),
102
- pgid: Number(m[3]),
103
- start: m[4] ?? "",
104
- command: (m[6] ?? "").trim()
105
- });
106
- }
107
- return table.sort((a, b) => a.pid - b.pid);
108
- }
109
- /**
110
- * A snapshot of every running process, read at once: from /proc on Linux, from
111
- * ps elsewhere. `platform` and `ps` are parameters so tests can take the ps path
112
- * on Linux and see it fail.
113
- */
114
- function processTable(platform = process.platform, ps = "ps") {
115
- if (platform === "linux") return tableFromProc();
116
- try {
117
- return parsePsTable(execFileSync(ps, PS_ARGS, {
118
- encoding: "utf8",
119
- env: PS_ENV
120
- }));
121
- } catch {
122
- return [];
123
- }
124
- }
125
- /** processTable() without blocking: on macOS, ps takes a few milliseconds. */
126
- function processTableAsync(platform = process.platform, ps = "ps") {
127
- if (platform === "linux") return Promise.resolve(tableFromProc());
128
- return new Promise((resolve) => {
129
- execFile(ps, PS_ARGS, {
130
- encoding: "utf8",
131
- env: PS_ENV
132
- }, (error, out) => {
133
- resolve(error ? [] : parsePsTable(out));
134
- });
135
- });
136
- }
137
- /**
138
- * What one run started, followed by parent PID as well as by process group: a
139
- * child in its own group or session (Node's `detached`, setsid, daemons) leaves
140
- * the program's group, and once the program exits it is reparented, so only a
141
- * snapshot taken while the program runs links it to the program.
142
- */
143
- var ProcessTree = class {
144
- #root;
145
- #groups;
146
- /** Descendants seen so far, by PID, with their start time. */
147
- #seen = /* @__PURE__ */ new Map();
148
- /**
149
- * @param root the program's PID
150
- * @param groups the process groups whose members belong to the run, read
151
- * each time: the program's own, and the one under a pseudo-terminal
152
- */
153
- constructor(root, groups) {
154
- this.#root = root;
155
- this.#groups = groups;
156
- }
157
- /** Once the program has exited and been reaped, its PID may belong to another process. */
158
- programExited() {
159
- this.#root = void 0;
160
- }
161
- /** Records the program's descendants from a snapshot taken while it runs. */
162
- record(table) {
163
- for (const p of this.running(table)) this.#seen.set(p.pid, p.start);
164
- }
165
- /**
166
- * The run's processes in `table`: the program, the members of its groups,
167
- * the descendants recorded earlier (the same PID and start time), and
168
- * everything below any of them. cliprobe itself is never one of them.
169
- */
170
- running(table) {
171
- const groups = new Set(this.#groups());
172
- const found = /* @__PURE__ */ new Map();
173
- const candidates = table.filter((p) => p.pid !== 1 && p.pid !== process.pid);
174
- for (const p of candidates) if (p.pid === this.#root || groups.has(p.pgid) || this.#seen.has(p.pid) && this.#seen.get(p.pid) === p.start) found.set(p.pid, p);
175
- let grew = true;
176
- while (grew) {
177
- grew = false;
178
- for (const p of candidates) if (!found.has(p.pid) && found.has(p.ppid)) {
179
- found.set(p.pid, p);
180
- grew = true;
181
- }
182
- }
183
- return [...found.values()].sort((a, b) => a.pid - b.pid);
184
- }
185
- };
186
- /**
187
- * SIGKILLs the given processes, the run's groups, and every group that one of
188
- * the processes leads, so what they started after the snapshot goes too.
189
- */
190
- function killAll(processes, groups) {
191
- const targets = new Set(groups.map((g) => -g));
192
- for (const p of processes) {
193
- targets.add(p.pid);
194
- if (p.pgid === p.pid) targets.add(-p.pid);
195
- }
196
- targets.delete(-process.pid);
197
- targets.delete(process.pid);
198
- targets.delete(-1);
199
- targets.delete(1);
200
- targets.delete(0);
201
- for (const target of targets) try {
202
- process.kill(target, "SIGKILL");
203
- } catch {}
204
- }
205
- // src/core/sandbox.ts
206
- /** A minimal environment: no tokens or config from the caller's shell. */
207
- function sandbox() {
208
- const dir = mkdtempSync(join(tmpdir(), "cliprobe-"));
209
- return {
210
- dir,
211
- env: {
212
- PATH: process.env["PATH"] ?? "/usr/bin:/bin",
213
- LANG: process.env["LANG"] ?? "C.UTF-8",
214
- HOME: dir,
215
- TMPDIR: dir,
216
- TERM: "dumb",
217
- CI: "1",
218
- NO_UPDATE_NOTIFIER: "1"
219
- }
220
- };
221
- }
222
- // src/core/which.ts
223
- function isExecutableFile(path) {
224
- try {
225
- accessSync(path, constants.X_OK);
226
- return statSync(path).isFile();
227
- } catch {
228
- return false;
229
- }
230
- }
231
- /**
232
- * Where `command` would be found, as spawn() looks for it: a path with a slash
233
- * as given, otherwise each PATH entry in turn (an empty entry is the current
234
- * directory). Under a PTY, a missing command is only a line of shell output, so
235
- * the terminal checks ask first.
236
- */
237
- function findCommand(command, path = process.env["PATH"] ?? "/usr/bin:/bin") {
238
- if (command.includes("/")) return isExecutableFile(command) ? command : void 0;
239
- for (const dir of path.split(delimiter)) {
240
- const candidate = join(dir || ".", command);
241
- if (isExecutableFile(candidate)) return candidate;
242
- }
243
- }
244
- /** The first bytes of a file, or nothing when it can't be read (execute-only, say). */
245
- function head(path, bytes = 512) {
246
- let fd;
247
- try {
248
- fd = openSync(path, "r");
249
- const buffer = Buffer.alloc(bytes);
250
- return buffer.subarray(0, readSync(fd, buffer, 0, bytes, 0));
251
- } catch {
252
- return Buffer.alloc(0);
253
- } finally {
254
- if (fd !== void 0) closeSync(fd);
255
- }
256
- }
257
- /** Why the interpreter named on a `#!` line can't run, if it can't. */
258
- function interpreterProblem(command, file, path) {
259
- const start = head(file, 256);
260
- if (start.subarray(0, 2).toString("latin1") !== "#!") return void 0;
261
- const [interpreter = "", first] = (start.toString("utf8").slice(2).split("\n")[0] ?? "").trim().split(/[ \t]+/);
262
- if (interpreter === "") return void 0;
263
- try {
264
- statSync(interpreter);
265
- } catch {
266
- return `${command}: interpreter ${interpreter} not found`;
267
- }
268
- if (!isExecutableFile(interpreter)) return `${command}: interpreter ${interpreter} is not executable`;
269
- if (/(^|\/)env$/.test(interpreter) && first !== void 0 && !first.startsWith("-")) {
270
- if (!first.includes("=") && findCommand(first, path) === void 0) return `${command}: interpreter ${first} not found (${interpreter} ${first})`;
271
- }
272
- }
273
- /**
274
- * Why `command` can't run, or undefined if it looks runnable: not found, a
275
- * directory, not executable, or a `#!` interpreter that is missing. Asked before
276
- * any check, so the user sees the cause once instead of an error per probe.
277
- */
278
- function commandProblem(command, path = process.env["PATH"] ?? "/usr/bin:/bin") {
279
- if (command.includes("/")) {
280
- let isFile;
281
- try {
282
- const stat = statSync(command);
283
- if (stat.isDirectory()) return `${command} is a directory`;
284
- isFile = stat.isFile();
285
- } catch {
286
- return `command not found: ${command}`;
287
- }
288
- if (!isFile) return `${command} is not a regular file`;
289
- if (!isExecutableFile(command)) return `${command} is not executable (chmod +x?)`;
290
- return interpreterProblem(command, command, path);
291
- }
292
- const file = findCommand(command, path);
293
- if (file === void 0) return `command not found: ${command}`;
294
- return interpreterProblem(command, file, path);
295
- }
296
- /** The reason given for a file this system can't run as a program. */
297
- const notAProgram = (command, how) => `${command} is not a program this system can run (${how})`;
298
- /**
299
- * Whether `command` resolves to a file that no shell or kernel would run as a
300
- * program of this system: no `#!` line, and a NUL byte near its start, which no
301
- * script has. Alone this could be a binary run through binfmt_misc, so callers
302
- * also need the run to have exited 126 or 127.
303
- */
304
- function cannotExecute(command, path = process.env["PATH"] ?? "/usr/bin:/bin") {
305
- const file = findCommand(command, path);
306
- if (file === void 0) return false;
307
- const start = head(file);
308
- return start.subarray(0, 2).toString("latin1") !== "#!" && start.includes(0);
309
- }
310
- /**
311
- * Whether a run ended because the system could not run the file at all. On
312
- * Linux, spawn() hands a file the kernel can't execute (ENOEXEC) to /bin/sh,
313
- * as execvp() does, so a binary that isn't one for this system "runs" and exits
314
- * 126 or 127 with the shell's complaint, prefixed by the file's path. Only a
315
- * file with no `#!` line and a NUL byte near its start counts, as no script has
316
- * one: a binary run through binfmt_misc, or a script without `#!`, is left alone.
317
- * Returns the reason, or undefined.
318
- */
319
- function shellFallbackError(command, exitCode, stderr, path = process.env["PATH"] ?? "/usr/bin:/bin") {
320
- if (exitCode !== 126 && exitCode !== 127) return void 0;
321
- const file = findCommand(command, path);
322
- if (file === void 0 || !cannotExecute(command, path)) return void 0;
323
- if (!stderr.startsWith(`${command}: `) && !stderr.startsWith(`${file}: `)) return void 0;
324
- return notAProgram(command, `/bin/sh tried it as a script and exited ${exitCode}`);
325
- }
326
- // src/core/run.ts
327
- const STDERR_CAP = 65536;
328
- /** A device on Linux that accepts no data: every write to it fails with ENOSPC. */
329
- const DEV_FULL = "/dev/full";
330
- /** Whether this system has /dev/full (Linux does; macOS doesn't). */
331
- const hasDevFull = () => existsSync(DEV_FULL);
332
- const STDOUT_CAP = 1048576;
333
- /**
334
- * The longest delay setTimeout takes (2^31 - 1 ms, about 24.8 days). Node turns
335
- * anything longer into 1 ms, which would kill every probe at once.
336
- */
337
- const MAX_TIMEOUT_MS = 2 ** 31 - 1;
338
- /** How often the process table is read while the program runs, to learn its descendants. */
339
- const TREE_POLL_MS = 200;
340
- /** How long to wait for the output pipes to close once everything the run started is gone. */
341
- const CLOSE_WAIT_MS = 1e3;
342
- /** How often to look for leftovers while waiting for them to finish. */
343
- const LEFTOVER_POLL_MS = 50;
344
- const delay = (ms) => new Promise((resolve) => {
345
- setTimeout(resolve, ms);
346
- });
347
- /**
348
- * Runs one invocation. With `closedStdout`, stdout is the write end of a FIFO
349
- * whose read end is closed before the program starts, so its first write to
350
- * stdout fails (EPIPE, or SIGPIPE for programs that keep the default handler).
351
- * With `fullStdout`, stdout is /dev/full, so every write fails with ENOSPC.
352
- */
353
- function run$1(command, args, { closedStdout = false, fullStdout = false, timeout, env: overrides = {}, extraGroup, signal, stdin = "null", leftoversMs = 250 }) {
354
- const { dir, env: base } = sandbox();
355
- const env = { ...base };
356
- for (const [key, value] of Object.entries(overrides)) if (value === void 0) delete env[key];
357
- else env[key] = value;
358
- let stdoutFd = "pipe";
359
- if (closedStdout) {
360
- const fifo = join(dir, "stdout.fifo");
361
- execFileSync("mkfifo", [fifo]);
362
- const reader = openSync(fifo, constants.O_RDONLY | constants.O_NONBLOCK);
363
- stdoutFd = openSync(fifo, constants.O_WRONLY | constants.O_NONBLOCK);
364
- closeSync(reader);
365
- } else if (fullStdout) stdoutFd = openSync(DEV_FULL, "w");
366
- return new Promise((resolve) => {
367
- let stdoutBytes = 0;
368
- const stdoutChunks = [];
369
- let stderr = "";
370
- let timedOut = false;
371
- let finished = false;
372
- let exited = false;
373
- let signalSentMs;
374
- let stderrAtSignal;
375
- let leftRunning;
376
- let exitMs;
377
- let tree;
378
- let pollTimer;
379
- const start = performance.now();
380
- const groups = () => {
381
- const extra = extraGroup?.();
382
- return [...child?.pid === void 0 ? [] : [child.pid], ...extra === void 0 ? [] : [extra]];
383
- };
384
- /** Kills everything the run started, from a fresh look at the process table. */
385
- const killRun = () => {
386
- if (tree) killAll(tree.running(processTable()), groups());
387
- };
388
- const unregister = onInterrupt(() => {
389
- killRun();
390
- rmSync(dir, {
391
- recursive: true,
392
- force: true
393
- });
394
- });
395
- const finish = (outcome) => {
396
- if (finished) return;
397
- finished = true;
398
- clearInterval(pollTimer);
399
- unregister();
400
- if (typeof stdoutFd === "number") closeSync(stdoutFd);
401
- rmSync(dir, {
402
- recursive: true,
403
- force: true
404
- });
405
- const stdout = Buffer.concat(stdoutChunks).subarray(0, STDOUT_CAP);
406
- resolve({
407
- stdoutBytes,
408
- stdout,
409
- stderr,
410
- timedOut,
411
- durationMs: exitMs ?? Math.round(performance.now() - start),
412
- ...signalSentMs === void 0 ? {} : {
413
- signalSentMs,
414
- stderrAtSignal: stderrAtSignal ?? 0
415
- },
416
- ...leftRunning === void 0 ? {} : { leftRunning },
417
- ...outcome
418
- });
419
- };
420
- let child;
421
- try {
422
- child = spawn(command, [...args], {
423
- env,
424
- stdio: [
425
- stdin === "null" ? "ignore" : "pipe",
426
- stdoutFd,
427
- "pipe"
428
- ],
429
- detached: true
430
- });
431
- } catch (error) {
432
- finish({
433
- exitCode: null,
434
- signal: null,
435
- spawnError: spawnMessage(command, error)
436
- });
437
- return;
438
- }
439
- const proc = child;
440
- if (proc.pid !== void 0) {
441
- tree = new ProcessTree(proc.pid, groups);
442
- let polling = false;
443
- pollTimer = setInterval(() => {
444
- if (polling || exited) return;
445
- polling = true;
446
- (async () => {
447
- const table = await processTableAsync();
448
- polling = false;
449
- if (!exited) tree?.record(table);
450
- })();
451
- }, TREE_POLL_MS);
452
- }
453
- const recordTree = () => {
454
- tree?.record(processTable());
455
- };
456
- const timer = setTimeout(() => {
457
- timedOut = true;
458
- recordTree();
459
- killRun();
460
- }, Math.min(timeout, MAX_TIMEOUT_MS));
461
- const signalTimer = signal && setTimeout(() => {
462
- if (exited || proc.pid === void 0) return;
463
- recordTree();
464
- signalSentMs = Math.round(performance.now() - start);
465
- stderrAtSignal = stderr.length;
466
- try {
467
- process.kill(signal.to === "process" ? proc.pid : -proc.pid, signal.name);
468
- } catch {}
469
- }, signal.afterMs);
470
- const closeTimer = typeof stdin === "object" ? setTimeout(() => proc.stdin?.destroy(), stdin.closeAfterMs) : void 0;
471
- let closed = false;
472
- let onClosed;
473
- const outputClosed = new Promise((resolveClosed) => {
474
- onClosed = resolveClosed;
475
- });
476
- proc.on("exit", (exitCode, exitSignal) => {
477
- exited = true;
478
- exitMs = Math.round(performance.now() - start);
479
- clearTimeout(timer);
480
- clearTimeout(signalTimer);
481
- clearTimeout(closeTimer);
482
- clearInterval(pollTimer);
483
- tree?.programExited();
484
- proc.stdin?.destroy();
485
- (async () => {
486
- if (tree) {
487
- const left = await watchLeftovers(tree, timedOut ? 0 : leftoversMs);
488
- killAll(left, groups());
489
- leftRunning = left.map((p) => ({
490
- pid: p.pid,
491
- command: p.command
492
- }));
493
- }
494
- if (!closed) {
495
- let giveUp;
496
- const gaveUp = new Promise((resolveWait) => {
497
- giveUp = setTimeout(resolveWait, CLOSE_WAIT_MS);
498
- });
499
- await Promise.race([outputClosed, gaveUp]);
500
- clearTimeout(giveUp);
501
- }
502
- proc.stdout?.destroy();
503
- proc.stderr?.destroy();
504
- const notRun = timedOut ? void 0 : shellFallbackError(command, exitCode, stderr);
505
- finish({
506
- exitCode,
507
- signal: exitSignal,
508
- ...notRun === void 0 ? {} : { spawnError: notRun }
509
- });
510
- })();
511
- });
512
- proc.stdout?.on("data", (chunk) => {
513
- if (stdoutBytes < STDOUT_CAP) stdoutChunks.push(chunk);
514
- stdoutBytes += chunk.length;
515
- });
516
- proc.stderr?.on("data", (chunk) => {
517
- if (stderr.length < STDERR_CAP) stderr += chunk.toString("utf8");
518
- });
519
- proc.on("error", (error) => {
520
- clearTimeout(timer);
521
- clearTimeout(signalTimer);
522
- finish({
523
- exitCode: null,
524
- signal: null,
525
- spawnError: spawnMessage(command, error)
526
- });
527
- });
528
- proc.on("close", () => {
529
- closed = true;
530
- onClosed?.();
531
- });
532
- });
533
- }
534
- /** Why spawn() failed; "spawn ENOEXEC" names neither the file nor the problem. */
535
- function spawnMessage(command, error) {
536
- if (!(error instanceof Error)) return String(error);
537
- return "code" in error && error.code === "ENOEXEC" ? notAProgram(command, "exec format error") : error.message;
538
- }
539
- /**
540
- * Waits up to `ms` for what the program left running to finish on its own, as
541
- * children stopped by their parent take a moment to exit, and returns what is
542
- * still running then.
543
- */
544
- async function watchLeftovers(tree, ms) {
545
- const deadline = performance.now() + ms;
546
- let left = tree.running(processTable());
547
- while (left.length > 0 && performance.now() < deadline) {
548
- await delay(LEFTOVER_POLL_MS);
549
- left = tree.running(processTable());
550
- }
551
- return left;
552
- }
553
- // src/checks/baseline.ts
554
- /** A flag no real program defines. */
555
- const UNKNOWN_FLAG = "--cliprobe-unknown-flag";
556
- /** A program that ignores unknown flags may start its default action; don't wait long. */
557
- const UNKNOWN_FLAG_TIMEOUT_MS = 5e3;
558
- const lines = (text) => text.split("\n").filter((l) => l.trim() !== "");
559
- /** The first line printed, labelled with its stream, as evidence. */
560
- function firstLine(r) {
561
- const out = lines(r.stdout.toString("utf8"))[0];
562
- if (out !== void 0) return `stdout: ${out}`;
563
- const err = lines(r.stderr)[0];
564
- return err === void 0 ? "" : `stderr: ${err}`;
565
- }
566
- const exitText$1 = (r) => r.signal ? `was stopped by ${r.signal}` : `exited ${r.exitCode}`;
567
- /** Each describes one convention scripts and agents rely on; observations, never verdicts. */
568
- function describeVersion(r) {
569
- const out = lines(r.stdout.toString("utf8"));
570
- if (r.exitCode !== 0) return {
571
- reason: `${exitText$1(r)}; there may be no --version`,
572
- evidence: firstLine(r)
573
- };
574
- if (out.length === 1) return {
575
- reason: "printed one line to stdout",
576
- evidence: out[0] ?? ""
577
- };
578
- if (out.length > 1) return {
579
- reason: `printed ${out.length} lines to stdout; one line is easier for scripts to parse`,
580
- evidence: `first line: ${out[0] ?? ""}`
581
- };
582
- if (lines(r.stderr).length) return {
583
- reason: "printed the version to stderr, not stdout",
584
- evidence: firstLine(r)
585
- };
586
- return { reason: "printed nothing" };
587
- }
588
- function describeHelp(r) {
589
- const out = lines(r.stdout.toString("utf8"));
590
- const err = lines(r.stderr);
591
- if (out.length && r.exitCode === 0) {
592
- const noun = out.length === 1 ? "line" : "lines";
593
- return { reason: `printed ${out.length} ${noun} to stdout and exited 0` };
594
- }
595
- if (out.length) return { reason: `printed help to stdout but ${exitText$1(r)}` };
596
- if (err.length) return { reason: `printed help to stderr and ${exitText$1(r)}, so "--help | less" and agents reading stdout get nothing` };
597
- return { reason: `printed nothing and ${exitText$1(r)}` };
598
- }
599
- function describeUnknownFlag(r) {
600
- if (r.timedOut) return { reason: `still running after ${UNKNOWN_FLAG_TIMEOUT_MS / 1e3} s; it may have ignored the flag and started its default action` };
601
- const evidence = firstLine(r);
602
- const withEvidence = (reason) => evidence ? {
603
- reason,
604
- evidence
605
- } : { reason };
606
- if (r.exitCode === 0) return withEvidence("exited 0, so a script cannot tell the flag was wrong");
607
- if (lines(r.stdout.toString("utf8")).length) return withEvidence(`${exitText$1(r)}, but printed its message to stdout rather than stderr`);
608
- if (lines(r.stderr).length) return withEvidence(`${exitText$1(r)} with its message on stderr`);
609
- return { reason: `${exitText$1(r)} without saying why` };
610
- }
611
- async function probe(command, args, timeout, describe) {
612
- const r = await run$1(command, args, { timeout });
613
- const base = {
614
- check: "baseline",
615
- invocation: [command, ...args]
616
- };
617
- if (r.spawnError) return {
618
- ...base,
619
- verdict: "error",
620
- reason: `could not start: ${r.spawnError}`,
621
- exitCode: null,
622
- stdoutLines: 0,
623
- stderrLines: 0
624
- };
625
- const { reason, evidence } = r.timedOut && describe !== describeUnknownFlag ? {
626
- reason: "timed out",
627
- evidence: void 0
628
- } : describe(r);
629
- return {
630
- ...base,
631
- verdict: "info",
632
- reason,
633
- ...evidence ? { evidence } : {},
634
- exitCode: r.exitCode,
635
- stdoutLines: lines(r.stdout.toString("utf8")).length,
636
- stderrLines: lines(r.stderr).length
637
- };
638
- }
639
- const baselineCheck = {
640
- name: "baseline",
641
- kind: "info",
642
- summary: "--version prints one line, --help goes to stdout, an unknown flag exits non-zero",
643
- async run(target, ctx) {
644
- const [first] = target.probes;
645
- const prefix = first?.own ? first.args : target.programArgs ?? [];
646
- return [
647
- await probe(target.command, [...prefix, "--version"], ctx.timeout, describeVersion),
648
- await probe(target.command, [...prefix, "--help"], ctx.timeout, describeHelp),
649
- await probe(target.command, [...prefix, UNKNOWN_FLAG], Math.min(ctx.timeout, UNKNOWN_FLAG_TIMEOUT_MS), describeUnknownFlag)
650
- ];
651
- }
652
- };
653
- // src/core/evidence.ts
654
- /** Signs that a program reported a write failure or crashed with a stack trace. */
655
- const ERROR_RE = /EPIPE|broken ?pipe|BrokenPipeError|Unhandled 'error' event|^\s+at .+:\d+:\d+\)?$/im;
656
- /** Signs of a stack trace from Node, Python, Go or Rust. */
657
- const TRACE_RE = /Traceback \(most recent call last\)|^\s+at .+:\d+:\d+\)?$|^panic: |^goroutine \d+ \[|thread '.+' panicked/m;
658
- /** Lines worth quoting as the error message, best first. */
659
- const CRASH_MESSAGES = [/^(\w*Error\b|panic:)/, ERROR_RE];
660
- /**
661
- * Picks the most useful evidence from a crash: the error message plus the first
662
- * stack frame in the program's own code (not Node internals), which usually
663
- * points at the faulty line. `messages` ranks the patterns for the message line.
664
- */
665
- function crashEvidence(stderr, messages = CRASH_MESSAGES) {
666
- const lines = stderr.split("\n").map((l) => l.trim()).filter(Boolean);
667
- let message = "";
668
- for (const pattern of messages) {
669
- message = lines.find((l) => pattern.test(l)) ?? "";
670
- if (message) break;
671
- }
672
- message ||= lines[0] ?? "";
673
- const frame = lines.find((l) => l.startsWith("at ") && !/\bnode:/.test(l))?.match(/(?:file:\/\/)?(\/[^\s()]+:\d+:\d+)/)?.[1];
674
- if (!frame) return message;
675
- const cwd = process.cwd() + "/";
676
- return `${message} (at ${frame.startsWith(cwd) ? frame.slice(cwd.length) : frame})`;
677
- }
678
- /**
679
- * Adds to a SKIP that a probe exited with a failure code, so a probe that never ran
680
- * as intended (a typo, `--probe watch` running `node watch`) doesn't pass for a quiet
681
- * skip. The evidence is the error line from stderr, when there is one.
682
- */
683
- function noteFailedExit(judgement, r) {
684
- if (judgement.verdict !== "skip" || r.exitCode === null || r.exitCode === 0) return judgement;
685
- const message = crashEvidence(r.stderr);
686
- return {
687
- ...judgement,
688
- reason: `${judgement.reason}; it exited ${r.exitCode}, so the probe may not have run as intended`,
689
- ...message && judgement.evidence === void 0 ? { evidence: `stderr: ${message}` } : {}
690
- };
691
- }
692
- // src/core/long-running.ts
693
- /**
694
- * Once one check has seen a probe still running at the timeout (a server, a
695
- * watcher, a full-screen program), later checks watch it this long instead, so
696
- * the timeout is paid once rather than once per check.
697
- */
698
- const LONG_RUN_WINDOW_MS = 3e3;
699
- const key = (command, args) => JSON.stringify([command, ...args]);
700
- function isLongRunning(ctx, command, args) {
701
- return ctx.longRunning?.has(key(command, args)) === true;
702
- }
703
- /** How long to let a normal run of this probe go: the timeout, or the short window once it is known to keep running. */
704
- function probeTimeout(ctx, command, args) {
705
- return isLongRunning(ctx, command, args) ? Math.min(ctx.timeout, LONG_RUN_WINDOW_MS) : ctx.timeout;
706
- }
707
- function markLongRunning(ctx, command, args) {
708
- ctx.longRunning?.add(key(command, args));
709
- }
710
- /** "still running after 15 s", from a run that was stopped at its timeout. */
711
- const stillRunning = (durationMs) => `still running after ${Math.round(durationMs / 1e3)} s`;
712
- // src/checks/closed-pipe.ts
713
- /** A program that writes an error to stderr only once its stdout is closed. */
714
- const newWriteError = (base, closed) => ERROR_RE.test(closed.stderr) && !ERROR_RE.test(base.stderr);
715
- /**
716
- * For a program that keeps running (a server, a watcher): there is no normal exit
717
- * to compare with, but a crash once stdout is closed is still a crash.
718
- */
719
- function judgeLongRunning$1(base, closed) {
720
- if (!closed.timedOut && newWriteError(base, closed)) return {
721
- verdict: "fail",
722
- reason: `crashed when stdout was closed, while a normal run kept running (exit ${closed.exitCode})`,
723
- evidence: crashEvidence(closed.stderr)
724
- };
725
- if (closed.signal === "SIGPIPE") return {
726
- verdict: "pass",
727
- reason: "stopped by SIGPIPE, the conventional exit"
728
- };
729
- if (base.stdoutBytes === 0) return {
730
- verdict: "skip",
731
- reason: `${stillRunning(base.durationMs)} without writing to stdout, so a closed stdout was never touched`
732
- };
733
- if (!closed.timedOut) return {
734
- verdict: "pass",
735
- reason: "exited quietly when stdout was closed"
736
- };
737
- if (newWriteError(base, closed)) return {
738
- verdict: "warn",
739
- reason: "printed a write error when stdout was closed, and kept running",
740
- evidence: crashEvidence(closed.stderr)
741
- };
742
- return {
743
- verdict: "pass",
744
- reason: `${stillRunning(base.durationMs)}; with stdout closed it kept running without a write error`
745
- };
746
- }
747
- /** Compares a normal run with a closed-stdout run of the same invocation. */
748
- function judge$1(base, closed) {
749
- if (base.spawnError) return {
750
- verdict: "error",
751
- reason: `could not start: ${base.spawnError}`
752
- };
753
- if (base.timedOut) return judgeLongRunning$1(base, closed);
754
- if (base.stdoutBytes === 0) return noteFailedExit({
755
- verdict: "skip",
756
- reason: "wrote nothing to stdout, so a closed stdout is never touched"
757
- }, base);
758
- if (closed.timedOut) return {
759
- verdict: "fail",
760
- reason: "hung after stdout was closed"
761
- };
762
- if (closed.signal === "SIGPIPE") return {
763
- verdict: "pass",
764
- reason: "stopped by SIGPIPE, the conventional exit"
765
- };
766
- const newError = newWriteError(base, closed);
767
- if (newError && closed.exitCode !== base.exitCode) return {
768
- verdict: "fail",
769
- reason: `crashed when stdout was closed (exit ${base.exitCode} -> ${closed.exitCode})`,
770
- evidence: crashEvidence(closed.stderr)
771
- };
772
- if (newError) return {
773
- verdict: "warn",
774
- reason: "printed a write error but kept its exit code",
775
- evidence: crashEvidence(closed.stderr)
776
- };
777
- if (closed.exitCode !== base.exitCode) return {
778
- verdict: "pass",
779
- reason: `exited quietly with code ${closed.exitCode}`
780
- };
781
- return {
782
- verdict: "pass",
783
- reason: "exited quietly"
784
- };
785
- }
786
- async function closedPipe(command, args, ctx) {
787
- const base = await run$1(command, args, {
788
- closedStdout: false,
789
- timeout: probeTimeout(ctx, command, args)
790
- });
791
- if (base.timedOut) markLongRunning(ctx, command, args);
792
- const closed = await run$1(command, args, {
793
- closedStdout: true,
794
- timeout: base.timedOut ? Math.min(ctx.timeout, LONG_RUN_WINDOW_MS) : ctx.timeout
795
- });
796
- return {
797
- check: "closed-pipe",
798
- invocation: [command, ...args],
799
- ...judge$1(base, closed),
800
- baseline: {
801
- exitCode: base.exitCode,
802
- signal: base.signal,
803
- stdoutBytes: base.stdoutBytes
804
- },
805
- closed: {
806
- exitCode: closed.exitCode,
807
- signal: closed.signal,
808
- timedOut: closed.timedOut,
809
- stderr: closed.stderr.slice(-2e3)
810
- }
811
- };
812
- }
813
- const closedPipeCheck = {
814
- name: "closed-pipe",
815
- kind: "check",
816
- summary: "crashes or hangs when stdout is closed early (| head, grep -q, an agent)",
817
- async run(target, ctx) {
818
- const results = [];
819
- for (const { args } of target.probes) results.push(await closedPipe(target.command, args, ctx));
820
- return results;
821
- }
822
- };
823
- // src/core/ansi.ts
824
- const SGR = /\x1b\[([0-9;:]*)m/g;
825
- /** SGR params that only turn something off. A sequence made only of these is not styling. */
826
- const RESETS = /* @__PURE__ */ new Set([
827
- "",
828
- "0",
829
- "22",
830
- "23",
831
- "24",
832
- "25",
833
- "27",
834
- "28",
835
- "29",
836
- "39",
837
- "49",
838
- "54",
839
- "55",
840
- "59"
841
- ]);
842
- /**
843
- * Finds the first SGR sequence that sets a color or style (red, bold, 256-color,
844
- * truecolor...). Pure resets are ignored: some programs always print them, and
845
- * they change nothing on screen.
846
- */
847
- function findStyle(text) {
848
- for (const match of text.matchAll(SGR)) {
849
- if ((match[1] ?? "").split(/[;:]/).every((p) => RESETS.has(p))) continue;
850
- const before = text.slice(0, match.index);
851
- const start = before.lastIndexOf("\n") + 1;
852
- const newline = text.indexOf("\n", match.index);
853
- const end = newline === -1 ? text.length : newline;
854
- return {
855
- sequence: match[0],
856
- line: before.split("\n").length,
857
- text: text.slice(start, end).slice(0, 120)
858
- };
859
- }
860
- }
861
- /**
862
- * Every control code findControls() knows, as alternatives tried in this order at each
863
- * position, so one sequence is never counted twice:
864
- * - csi: ESC [ parameter bytes, intermediate bytes, one final byte;
865
- * - osc: ESC ] number ; text, ended by BEL or ESC ;
866
- * - oscOther: any other OSC, such as ESC ] 104 BEL (no ";");
867
- * - string: DCS, SOS, PM or APC (ESC P, X, ^ or _), with its text when ST ends it;
868
- * - reset: ESC c, a full reset that clears the screen;
869
- * - escape: any other ESC sequence: intermediates (ESC ( B) or one final byte (ESC 7);
870
- * - c1: an 8-bit CSI, OSC, DCS, SOS, PM or APC introducer, with what it carries;
871
- * - redraw: a carriage return that does not end a CRLF line: a line being redrawn.
872
- * ESC \ (ST) alone ends a string and starts nothing.
873
- */
874
- const CONTROL = new RegExp([
875
- String.raw`(?<csi>\x1b\[(?<params>[0-?]*)[ -/]*(?<final>[@-~]))`,
876
- String.raw`(?<osc>\x1b\](?<code>\d*);[^\x07\x1b]*(?:\x07|\x1b\\))`,
877
- String.raw`(?<oscOther>\x1b\][^\x07\x1b]*(?:\x07|\x1b\\))`,
878
- String.raw`(?<string>\x1b[PX^_](?:[^\x1b]*\x1b\\)?)`,
879
- String.raw`(?<reset>\x1bc)`,
880
- String.raw`(?<escape>\x1b(?:[ -/]+[0-~]|[0-OQ-WYZ\x60-bd-~]))`,
881
- String.raw`(?<c1>\x9b[0-?]*[ -/]*[@-~]?|[\x90\x98\x9d\x9e\x9f][^\x07\x1b\x9c]*(?:\x07|\x9c|\x1b\\)?)`,
882
- String.raw`(?<redraw>\r(?!\n))`
883
- ].join("|"), "g");
884
- /** How each kind reads in a report. */
885
- const CONTROL_LABELS = {
886
- cursor: "cursor movement",
887
- erase: "line or screen erase",
888
- mode: "terminal mode switch (such as hiding the cursor)",
889
- hyperlink: "hyperlink (OSC 8)",
890
- title: "window title",
891
- osc: "operating system command (OSC)",
892
- redraw: "carriage-return redraw",
893
- escape: "other escape sequence (such as saving the cursor or switching the character set)",
894
- reset: "full terminal reset (ESC c)",
895
- string: "device control string (DCS, APC, PM or SOS)",
896
- c1: "8-bit control sequence (C1)"
897
- };
898
- function csiKind(params, final) {
899
- if (final === "m") return void 0;
900
- if (final === "K" || final === "J") return "erase";
901
- if ((final === "h" || final === "l") && params.startsWith("?")) return "mode";
902
- return "cursor";
903
- }
904
- function oscKind(code) {
905
- if (code === "8") return "hyperlink";
906
- if (code === "0" || code === "1" || code === "2") return "title";
907
- return "osc";
908
- }
909
- function hitAt(text, index, sequence, kind, warnOnly) {
910
- const before = text.slice(0, index);
911
- const start = before.lastIndexOf("\n") + 1;
912
- const newline = text.indexOf("\n", index);
913
- const end = newline === -1 ? text.length : newline;
914
- return {
915
- kind,
916
- sequence,
917
- line: before.split("\n").length,
918
- text: text.slice(start, end).slice(0, 120),
919
- warnOnly
920
- };
921
- }
922
- /** The kind of one CONTROL match, and whether it may only warn; undefined for SGR. */
923
- function classify(g) {
924
- if (g["csi"] !== void 0) {
925
- const kind = csiKind(g["params"] ?? "", g["final"] ?? "");
926
- return kind && [kind, false];
927
- }
928
- if (g["osc"] !== void 0) return [oscKind(g["code"] ?? ""), false];
929
- if (g["redraw"] !== void 0) return ["redraw", false];
930
- if (g["oscOther"] !== void 0) return ["osc", true];
931
- if (g["string"] !== void 0) return ["string", true];
932
- if (g["reset"] !== void 0) return ["reset", true];
933
- if (g["escape"] !== void 0) return ["escape", true];
934
- return ["c1", true];
935
- }
936
- /**
937
- * Every terminal control code in the text other than color and style (SGR):
938
- * cursor movement, erases, mode switches, OSC sequences such as hyperlinks and
939
- * window titles, carriage returns that redraw a line, and (warn-only) the other
940
- * ESC sequences, control strings and 8-bit controls. In reading order.
941
- */
942
- function findControls(text) {
943
- const hits = [];
944
- for (const m of text.matchAll(CONTROL)) {
945
- const found = classify(m.groups ?? {});
946
- if (found) hits.push(hitAt(text, m.index, m[0], ...found));
947
- }
948
- return hits;
949
- }
950
- const ANY_ESCAPE = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
951
- /** The text with CSI and OSC escape sequences (color, cursor, links, titles) removed. */
952
- function stripEscapes(text) {
953
- return text.replace(ANY_ESCAPE, "");
954
- }
955
- /** The modes that leave a shell broken when a program forgets them. */
956
- const TERMINAL_MODES = [
957
- {
958
- label: "hidden cursor",
959
- codes: [25],
960
- inverted: true
961
- },
962
- {
963
- label: "alternate screen",
964
- codes: [
965
- 47,
966
- 1047,
967
- 1049
968
- ]
969
- },
970
- {
971
- label: "mouse reporting",
972
- codes: [
973
- 9,
974
- 1e3,
975
- 1001,
976
- 1002,
977
- 1003,
978
- 1005,
979
- 1006,
980
- 1015
981
- ]
982
- },
983
- {
984
- label: "focus reporting",
985
- codes: [1004]
986
- },
987
- {
988
- label: "bracketed paste",
989
- codes: [2004]
990
- },
991
- {
992
- label: "line wrapping off",
993
- codes: [7],
994
- inverted: true
995
- }
996
- ];
997
- /** DEC private mode set or reset (ESC [ ? numbers h|l), or a full reset (ESC c). */
998
- const DEC_MODE = /\x1b\[\?([\d;]+)([hl])|\x1bc/g;
999
- /**
1000
- * The terminal modes the text leaves switched on, in the order they were
1001
- * switched on. A mode counts as on from its first switch-on until a later
1002
- * switch-off or a full reset, so a program that restores everything leaves none.
1003
- */
1004
- function findOpenModes(text) {
1005
- const open = /* @__PURE__ */ new Map();
1006
- for (const m of text.matchAll(DEC_MODE)) {
1007
- if (m[2] === void 0) {
1008
- open.clear();
1009
- continue;
1010
- }
1011
- const set = m[2] === "h";
1012
- for (const code of (m[1] ?? "").split(";").map(Number)) {
1013
- const mode = TERMINAL_MODES.find((t) => t.codes.includes(code));
1014
- if (!mode) continue;
1015
- if (!(mode.inverted ? !set : set)) open.delete(mode);
1016
- else if (!open.has(mode)) {
1017
- const line = text.slice(0, m.index).split("\n").length;
1018
- open.set(mode, {
1019
- label: mode.label,
1020
- sequence: m[0],
1021
- line,
1022
- index: m.index
1023
- });
1024
- }
1025
- }
1026
- }
1027
- return [...open.values()].sort((a, b) => a.index - b.index).map(({ label, sequence, line }) => ({
1028
- label,
1029
- sequence,
1030
- line
1031
- }));
1032
- }
1033
- let cached;
1034
- /** Whether this machine can run a program under a PTY, detected once. */
1035
- function ptySupport() {
1036
- cached ??= detect();
1037
- return cached;
1038
- }
1039
- function detect() {
1040
- if (process.platform === "darwin") try {
1041
- execFileSync("script", [
1042
- "-q",
1043
- "/dev/null",
1044
- "true"
1045
- ], {
1046
- stdio: "ignore",
1047
- timeout: 5e3
1048
- });
1049
- return {
1050
- ok: true,
1051
- flavor: "bsd"
1052
- };
1053
- } catch {
1054
- return {
1055
- ok: false,
1056
- reason: "script(1) did not run"
1057
- };
1058
- }
1059
- if (process.platform === "linux") {
1060
- try {
1061
- if (execFileSync("script", ["--version"], {
1062
- encoding: "utf8",
1063
- stdio: [
1064
- "ignore",
1065
- "pipe",
1066
- "pipe"
1067
- ],
1068
- timeout: 5e3
1069
- }).includes("util-linux")) return {
1070
- ok: true,
1071
- flavor: "util-linux"
1072
- };
1073
- } catch (error) {
1074
- if (error instanceof Error && "code" in error && error.code === "ENOENT") return {
1075
- ok: false,
1076
- reason: "script(1) not found; install the package that has it (Debian and Ubuntu: bsdutils; Fedora: util-linux-script; Alpine: util-linux-misc)"
1077
- };
1078
- }
1079
- return {
1080
- ok: false,
1081
- reason: "script(1) is not the util-linux version"
1082
- };
1083
- }
1084
- return {
1085
- ok: false,
1086
- reason: `no PTY support on ${process.platform}`
1087
- };
1088
- }
1089
- /** Quotes one argument for a POSIX shell. */
1090
- function shellQuote(arg) {
1091
- return `'${arg.replaceAll("'", `'\\''`)}'`;
1092
- }
1093
- /**
1094
- * The script(1) arguments that run `command args...` under a PTY.
1095
- *
1096
- * A small /bin/sh wrapper writes its PID to `pidFile`, sets the window size and
1097
- * then execs the program, so the PID is the program's and the program leads its
1098
- * own session and process group. Everything after the script reaches the
1099
- * program as argv; only the util-linux form needs quoting, because its -c takes
1100
- * a single string.
1101
- */
1102
- function ptyArgs(flavor, pidFile, command, args, cols = 80, rows = 24, settingsFile) {
1103
- const size = `stty cols ${cols} rows ${rows} 2>/dev/null`;
1104
- const setup = settingsFile === void 0 ? `echo $$ > "$1"; shift; ${size}; exec "$@"` : `echo $$ > "$1"; s=$2; shift 2; ${size}; stty -a > "$s.before" 2>/dev/null; trap true INT; "$@"; c=$?; stty -a > "$s.after" 2>/dev/null; exit $c`;
1105
- const argv = settingsFile === void 0 ? [
1106
- pidFile,
1107
- command,
1108
- ...args
1109
- ] : [
1110
- pidFile,
1111
- settingsFile,
1112
- command,
1113
- ...args
1114
- ];
1115
- if (flavor === "bsd") return [
1116
- "-q",
1117
- "/dev/null",
1118
- "/bin/sh",
1119
- "-c",
1120
- setup,
1121
- "sh",
1122
- ...argv
1123
- ];
1124
- return [
1125
- "-qec",
1126
- `exec /bin/sh -c ${shellQuote(setup)} sh ${argv.map(shellQuote).join(" ")}`,
1127
- "/dev/null"
1128
- ];
1129
- }
1130
- /** The terminal settings that leave a shell unusable when a program exits with them off. */
1131
- const WATCHED_SETTINGS = [
1132
- "icanon",
1133
- "echo",
1134
- "isig",
1135
- "iexten",
1136
- "opost",
1137
- "onlcr",
1138
- "icrnl",
1139
- "ixon"
1140
- ];
1141
- /**
1142
- * The watched settings that were on in `before` and are off in `after`, both the
1143
- * output of `stty -a`, where BSD and GNU stty alike print a setting that is off as
1144
- * `-name`. Compared with the terminal as the program found it, not fixed values.
1145
- */
1146
- function settingsOff(before, after) {
1147
- const words = (text) => new Set(text.split(/[\s;]+/));
1148
- const was = words(before);
1149
- const now = words(after);
1150
- return WATCHED_SETTINGS.filter((name) => was.has(name) && now.has(`-${name}`));
1151
- }
1152
- /** BSD script echoes the EOF it forwards from /dev/null as "^D" and two backspaces. */
1153
- const BSD_EOF_ECHO = "^D\b\b";
1154
- /** Undoes the terminal's output processing: the EOF echo, and \n turned into \r\n. */
1155
- function cleanPtyOutput(raw, flavor) {
1156
- let text = raw.toString("utf8");
1157
- if (flavor === "bsd" && text.startsWith(BSD_EOF_ECHO)) text = text.slice(4);
1158
- return text.replaceAll("\r\n", "\n");
1159
- }
1160
- /**
1161
- * Runs a program with stdin, stdout and stderr on a PTY, an 80x24 window and
1162
- * TERM=xterm-256color. Without `input`, stdin is /dev/null behind the PTY: the
1163
- * program reads one EOF, and a second read blocks until the timeout. With it,
1164
- * the terminal's line discipline handles what is typed, so Ctrl-C (\x03) becomes
1165
- * SIGINT for the program, or a keypress if the program turned that off.
1166
- */
1167
- async function runPty(command, args, { timeout, env = {}, input, settings = false }) {
1168
- const support = ptySupport();
1169
- if (!support.ok) throw new Error(`no PTY: ${support.reason}`);
1170
- const dir = mkdtempSync(join(tmpdir(), "cliprobe-pty-"));
1171
- const unregister = onInterrupt(() => rmSync(dir, {
1172
- recursive: true,
1173
- force: true
1174
- }));
1175
- const pidFile = join(dir, "pid");
1176
- let launcher = "script";
1177
- const settingsFile = settings ? join(dir, "stty") : void 0;
1178
- let argv = ptyArgs(support.flavor, pidFile, command, args, 80, 24, settingsFile);
1179
- let keyboard;
1180
- let inputSentMs;
1181
- let typeTimer;
1182
- let watchTimer;
1183
- const closeKeyboard = () => {
1184
- if (keyboard !== void 0) closeSync(keyboard);
1185
- keyboard = void 0;
1186
- };
1187
- const start = performance.now();
1188
- if (input) {
1189
- const fifo = join(dir, "keyboard");
1190
- execFileSync("mkfifo", [fifo]);
1191
- keyboard = openSync(fifo, constants.O_RDWR);
1192
- argv = [
1193
- "-c",
1194
- "cat -- \"$1\" 2>/dev/null | { shift; exec script \"$@\"; }",
1195
- "sh",
1196
- fifo,
1197
- ...argv
1198
- ];
1199
- launcher = "/bin/sh";
1200
- typeTimer = setTimeout(() => {
1201
- if (programState(pidFile) !== "running") return;
1202
- inputSentMs = Math.round(performance.now() - start);
1203
- if (keyboard !== void 0) writeSync(keyboard, input.data);
1204
- }, input.afterMs);
1205
- watchTimer = setInterval(() => {
1206
- if (programState(pidFile) !== "gone") return;
1207
- clearInterval(watchTimer);
1208
- closeKeyboard();
1209
- }, EXIT_POLL_MS);
1210
- }
1211
- try {
1212
- const result = await run$1(launcher, argv, {
1213
- timeout,
1214
- env: {
1215
- TERM: "xterm-256color",
1216
- SHELL: "/bin/sh",
1217
- ...env
1218
- },
1219
- extraGroup: () => programGroup(pidFile)
1220
- });
1221
- return {
1222
- output: cleanPtyOutput(result.stdout, support.flavor),
1223
- exitCode: result.exitCode,
1224
- timedOut: result.timedOut,
1225
- ...result.spawnError === void 0 ? {} : { spawnError: result.spawnError },
1226
- scriptStderr: result.stderr,
1227
- truncated: result.stdoutBytes > result.stdout.length,
1228
- ...inputSentMs === void 0 ? {} : { inputSentMs },
1229
- ...readSettings(settingsFile, result.timedOut)
1230
- };
1231
- } finally {
1232
- clearTimeout(typeTimer);
1233
- clearInterval(watchTimer);
1234
- closeKeyboard();
1235
- unregister();
1236
- rmSync(dir, {
1237
- recursive: true,
1238
- force: true
1239
- });
1240
- }
1241
- }
1242
- /** The settings the program left off, when the wrapper could read them after it. */
1243
- function readSettings(file, timedOut) {
1244
- if (file === void 0 || timedOut) return {};
1245
- try {
1246
- return { settingsOff: settingsOff(readFileSync(`${file}.before`, "utf8"), readFileSync(`${file}.after`, "utf8")) };
1247
- } catch {
1248
- return {};
1249
- }
1250
- }
1251
- /** How often to look for the end of a program that is being typed to. */
1252
- const EXIT_POLL_MS = 50;
1253
- function programGroup(pidFile) {
1254
- try {
1255
- const pid = Number(readFileSync(pidFile, "utf8").trim());
1256
- return Number.isInteger(pid) && pid > 1 ? pid : void 0;
1257
- } catch {
1258
- return;
1259
- }
1260
- }
1261
- /**
1262
- * Whether the program under the PTY has started, is running, or has exited.
1263
- * Asks about the program itself (or the wrapper that runs it and reads the
1264
- * settings it left, which ends right after it), which script(1) reaps, not its group: a child
1265
- * it left behind can stay a zombie for good where nothing reaps orphans, as in
1266
- * a container without an init process.
1267
- */
1268
- function programState(pidFile) {
1269
- const pid = programGroup(pidFile);
1270
- if (pid === void 0) return "starting";
1271
- try {
1272
- process.kill(pid, 0);
1273
- return "running";
1274
- } catch {
1275
- return "gone";
1276
- }
1277
- }
1278
- // src/checks/color.ts
1279
- /**
1280
- * Every color run gets a terminal type that supports color, so a program cannot
1281
- * pass by seeing TERM=dumb, and no CI variable, which some color libraries treat
1282
- * as a reason to force color on.
1283
- */
1284
- const COLOR_ENV = {
1285
- TERM: "xterm-256color",
1286
- CI: void 0
1287
- };
1288
- const describeHit = (stream, hit) => `${stream} line ${hit.line}: ${hit.text}`;
1289
- /** The first verdict the pipe run alone can settle, if any. */
1290
- function judgePipe(pipe) {
1291
- if (pipe.spawnError) return {
1292
- verdict: "error",
1293
- reason: `could not start: ${pipe.spawnError}`
1294
- };
1295
- const stdoutHit = findStyle(pipe.stdout.toString("utf8"));
1296
- if (stdoutHit) return {
1297
- verdict: "fail",
1298
- reason: "printed color codes into a pipe",
1299
- evidence: describeHit("stdout", stdoutHit)
1300
- };
1301
- const stderrHit = findStyle(pipe.stderr);
1302
- if (stderrHit) return {
1303
- verdict: "warn",
1304
- reason: "printed color codes to stderr when it was a pipe",
1305
- evidence: describeHit("stderr", stderrHit)
1306
- };
1307
- if (pipe.timedOut) return {
1308
- verdict: "skip",
1309
- reason: `${stillRunning(pipe.durationMs)} with no color in a pipe so far; a terminal is compared only for a command that finishes`
1310
- };
1311
- }
1312
- function judgeColor(runs) {
1313
- const fromPipe = judgePipe(runs.pipe);
1314
- if (fromPipe) return fromPipe;
1315
- const { tty, noColor } = runs;
1316
- if (!tty) return {
1317
- verdict: "skip",
1318
- reason: `no color in a pipe; no terminal to compare with (${runs.noPty ?? "no PTY"})`
1319
- };
1320
- if (tty.timedOut) return {
1321
- verdict: "skip",
1322
- reason: "no color in a pipe; in a terminal it waited for input, so it was not compared"
1323
- };
1324
- if (!findStyle(tty.output)) {
1325
- if (!(runs.pipe.stdoutBytes > 0 || runs.pipe.stderr.length > 0 || tty.output)) return noteFailedExit({
1326
- verdict: "skip",
1327
- reason: "printed nothing, so there is no color to check"
1328
- }, runs.pipe);
1329
- return {
1330
- verdict: "pass",
1331
- reason: "no color in a pipe or in a terminal"
1332
- };
1333
- }
1334
- if (!noColor || noColor.timedOut) return {
1335
- verdict: "skip",
1336
- reason: "colors only in a terminal; the NO_COLOR run did not finish"
1337
- };
1338
- const noColorHit = findStyle(noColor.output);
1339
- if (noColorHit) return {
1340
- verdict: "warn",
1341
- reason: "ignores NO_COLOR: still prints color in a terminal",
1342
- evidence: describeHit("terminal", noColorHit)
1343
- };
1344
- return {
1345
- verdict: "pass",
1346
- reason: "colors only in a terminal, and NO_COLOR turns it off"
1347
- };
1348
- }
1349
- /** Runs only as many probes as the verdict needs: a pipe, then a terminal, then NO_COLOR. */
1350
- async function colorRuns(command, args, ctx) {
1351
- const { timeout } = ctx;
1352
- const pipe = await run$1(command, args, {
1353
- timeout: probeTimeout(ctx, command, args),
1354
- env: COLOR_ENV
1355
- });
1356
- if (pipe.timedOut) markLongRunning(ctx, command, args);
1357
- if (judgePipe(pipe)) return { pipe };
1358
- const support = ptySupport();
1359
- if (!support.ok) return {
1360
- pipe,
1361
- noPty: support.reason
1362
- };
1363
- const tty = await runPty(command, args, {
1364
- timeout,
1365
- env: COLOR_ENV
1366
- });
1367
- if (tty.timedOut || !findStyle(tty.output)) return {
1368
- pipe,
1369
- tty
1370
- };
1371
- return {
1372
- pipe,
1373
- tty,
1374
- noColor: await runPty(command, args, {
1375
- timeout,
1376
- env: {
1377
- ...COLOR_ENV,
1378
- NO_COLOR: "1"
1379
- }
1380
- })
1381
- };
1382
- }
1383
- const summarize = (r) => r ? {
1384
- exitCode: r.exitCode,
1385
- timedOut: r.timedOut,
1386
- styled: findStyle(r.output) !== void 0
1387
- } : null;
1388
- async function color(command, args, ctx) {
1389
- const runs = await colorRuns(command, args, ctx);
1390
- return {
1391
- check: "color",
1392
- invocation: [command, ...args],
1393
- ...judgeColor(runs),
1394
- pipe: {
1395
- exitCode: runs.pipe.exitCode,
1396
- stdoutStyled: findStyle(runs.pipe.stdout.toString("utf8")) !== void 0,
1397
- stderrStyled: findStyle(runs.pipe.stderr) !== void 0
1398
- },
1399
- tty: summarize(runs.tty),
1400
- noColor: summarize(runs.noColor)
1401
- };
1402
- }
1403
- const colorCheck = {
1404
- name: "color",
1405
- kind: "check",
1406
- summary: "prints color codes into pipes, or ignores NO_COLOR in a terminal",
1407
- async run(target, ctx) {
1408
- const results = [];
1409
- for (const { args } of target.probes) results.push(await color(target.command, args, ctx));
1410
- return results;
1411
- }
1412
- };
1413
- // src/core/fixture.ts
1414
- /** Written in probe arguments; replaced with the path of a directory of hostile file names. */
1415
- const FIXTURE_PLACEHOLDER = "{fixture}";
1416
- const ESC = String.fromCharCode(27);
1417
- const BEL = String.fromCharCode(7);
1418
- const C1_CSI = String.fromCharCode(155);
1419
- const RIGHT_TO_LEFT_OVERRIDE = String.fromCharCode(8238);
1420
- /**
1421
- * File names a program may print. ESC sequences can drive the terminal (fail);
1422
- * C1 controls, carriage returns and newlines can hide or forge output (warn); a
1423
- * bidirectional override reorders text, but GNU ls and find print it raw too
1424
- * (note only).
1425
- */
1426
- const HOSTILE_NAMES = [
1427
- {
1428
- kind: "osc",
1429
- name: `title-${ESC}]0;cliprobe${BEL}.txt`,
1430
- marker: `${ESC}]0;cliprobe${BEL}`,
1431
- label: "an escape sequence that sets the window title",
1432
- severity: "fail"
1433
- },
1434
- {
1435
- kind: "csi",
1436
- name: `clear-${ESC}[2J.txt`,
1437
- marker: `${ESC}[2J`,
1438
- label: "an escape sequence that clears the screen",
1439
- severity: "fail"
1440
- },
1441
- {
1442
- kind: "c1",
1443
- name: `c1-${C1_CSI}2J.txt`,
1444
- marker: `${C1_CSI}2J`,
1445
- label: "a C1 control character",
1446
- severity: "warn"
1447
- },
1448
- {
1449
- kind: "cr",
1450
- name: "cr-\rspoof.txt",
1451
- marker: "cr-\rspoof",
1452
- label: "a carriage return",
1453
- severity: "warn"
1454
- },
1455
- {
1456
- kind: "newline",
1457
- name: "nl-\nspoof.txt",
1458
- marker: "nl-\nspoof",
1459
- label: "a newline",
1460
- severity: "warn"
1461
- },
1462
- {
1463
- kind: "bidi",
1464
- name: `bidi-${RIGHT_TO_LEFT_OVERRIDE}txt.exe`,
1465
- marker: `${RIGHT_TO_LEFT_OVERRIDE}txt`,
1466
- label: "a bidirectional override",
1467
- severity: "note"
1468
- }
1469
- ];
1470
- /** An ordinary name; seeing it in the output shows the program listed the directory. */
1471
- const PLAIN_NAME = "plain.txt";
1472
- /** Creates a temporary directory holding the hostile names and one plain file. */
1473
- function createFixture() {
1474
- const dir = mkdtempSync(join(tmpdir(), "cliprobe-fixture-"));
1475
- for (const { name } of HOSTILE_NAMES) writeFileSync(join(dir, name), "");
1476
- writeFileSync(join(dir, PLAIN_NAME), "");
1477
- return {
1478
- dir,
1479
- realDir: realpathSync(dir),
1480
- cleanup: () => rmSync(dir, {
1481
- recursive: true,
1482
- force: true
1483
- })
1484
- };
1485
- }
1486
- function usesFixture(args) {
1487
- return args.some((a) => a.includes(FIXTURE_PLACEHOLDER));
1488
- }
1489
- /** Replaces the placeholder in every argument, including inside `--dir={fixture}`. */
1490
- function expandFixture(args, dir) {
1491
- return args.map((a) => a.replaceAll(FIXTURE_PLACEHOLDER, dir));
1492
- }
1493
- /**
1494
- * Puts the placeholder back wherever the fixture's path appears in report text,
1495
- * so reports show {fixture} rather than a path that no longer exists.
1496
- */
1497
- function collapseFixture(text, fixture) {
1498
- return text.replaceAll(fixture.realDir, FIXTURE_PLACEHOLDER).replaceAll(fixture.dir, FIXTURE_PLACEHOLDER);
1499
- }
1500
- /**
1501
- * Removes the hostile names' dangerous parts from output, for checks other than
1502
- * control-chars: a lister that prints them raw into a pipe is doing its job, and
1503
- * control-chars judges how they reach a terminal.
1504
- */
1505
- function withoutHostileNames(text) {
1506
- let out = text;
1507
- for (const { marker } of HOSTILE_NAMES) out = out.replaceAll(marker, "");
1508
- return out;
1509
- }
1510
- function collapseValue(value, fixture) {
1511
- if (typeof value === "string") return collapseFixture(value, fixture);
1512
- if (Array.isArray(value)) return value.map((v) => collapseValue(v, fixture));
1513
- if (value && typeof value === "object" && !Buffer.isBuffer(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, collapseValue(v, fixture)]));
1514
- return value;
1515
- }
1516
- /** collapseFixture applied to every string in the results: invocation, reason, evidence and data. */
1517
- function collapseResults(results, fixture) {
1518
- return results.map((r) => {
1519
- const data = Object.fromEntries(Object.entries(r).map(([k, v]) => [k, collapseValue(v, fixture)]));
1520
- const c = (text) => collapseFixture(text, fixture);
1521
- return {
1522
- ...data,
1523
- check: r.check,
1524
- invocation: r.invocation.map(c),
1525
- verdict: r.verdict,
1526
- reason: c(r.reason),
1527
- ...r.evidence === void 0 ? {} : { evidence: c(r.evidence) }
1528
- };
1529
- });
1530
- }
1531
- // src/checks/control-chars.ts
1532
- const ENV$1 = {
1533
- TERM: "xterm-256color",
1534
- CI: void 0
1535
- };
1536
- /** The hostile names whose dangerous part appears in the output unescaped. */
1537
- function rawNames(output) {
1538
- return HOSTILE_NAMES.filter((h) => output.includes(h.marker));
1539
- }
1540
- const listLabels$2 = (names) => {
1541
- const labels = names.map((h) => h.label);
1542
- return labels.length <= 1 ? labels[0] ?? "" : `${labels.slice(0, -1).join(", ")} and ${labels.at(-1) ?? ""}`;
1543
- };
1544
- const evidenceFor = (names) => `file names printed raw: ${names.map((h) => h.name).join(", ")}`;
1545
- function judgeControlChars(runs) {
1546
- if (!runs.usesFixture) return {
1547
- verdict: "skip",
1548
- reason: "no {fixture} in the arguments; add a probe that takes a path, e.g. --probe \"ls {fixture}\""
1549
- };
1550
- const { pipe, tty } = runs;
1551
- if (pipe?.spawnError) return {
1552
- verdict: "error",
1553
- reason: `could not start: ${pipe.spawnError}`
1554
- };
1555
- if (!tty) return {
1556
- verdict: "skip",
1557
- reason: `no terminal to check with (${runs.noPty ?? "no PTY"})`
1558
- };
1559
- if (tty.timedOut && !tty.output.includes("plain.txt")) return {
1560
- verdict: "skip",
1561
- reason: "still running in a terminal at the timeout, and had not printed the file names in {fixture}"
1562
- };
1563
- if (!tty.output.includes("plain.txt")) {
1564
- const skip = {
1565
- verdict: "skip",
1566
- reason: "did not print the file names in {fixture}, so there was nothing to escape"
1567
- };
1568
- return pipe ? noteFailedExit(skip, pipe) : skip;
1569
- }
1570
- const raw = rawNames(tty.output);
1571
- const failing = raw.filter((h) => h.severity === "fail");
1572
- if (failing.length) return {
1573
- verdict: "fail",
1574
- reason: `sent ${failing.length > 1 ? "escape sequences" : "an escape sequence"} from file names to the terminal unescaped`,
1575
- evidence: evidenceFor(failing)
1576
- };
1577
- const warning = raw.filter((h) => h.severity === "warn");
1578
- if (warning.length) return {
1579
- verdict: "warn",
1580
- reason: `printed ${listLabels$2(warning)} from file names unescaped, which can hide or forge output`,
1581
- evidence: evidenceFor(warning)
1582
- };
1583
- const noted = raw.filter((h) => h.severity === "note");
1584
- return {
1585
- verdict: "pass",
1586
- reason: `escaped control characters in file names${noted.length ? `; printed ${listLabels$2(noted)} as is` : ""}`
1587
- };
1588
- }
1589
- async function controlCharsRuns(command, args, fixtureDir, ctx) {
1590
- const usesFixture = fixtureDir !== void 0 && args.some((a) => a.includes(fixtureDir));
1591
- if (!usesFixture) return { usesFixture };
1592
- const pipe = await run$1(command, args, {
1593
- timeout: probeTimeout(ctx, command, args),
1594
- env: ENV$1
1595
- });
1596
- if (pipe.spawnError) return {
1597
- usesFixture,
1598
- pipe
1599
- };
1600
- if (pipe.timedOut) markLongRunning(ctx, command, args);
1601
- const support = ptySupport();
1602
- if (!support.ok) return {
1603
- usesFixture,
1604
- pipe,
1605
- noPty: support.reason
1606
- };
1607
- return {
1608
- usesFixture,
1609
- pipe,
1610
- tty: await runPty(command, args, {
1611
- timeout: probeTimeout(ctx, command, args),
1612
- env: ENV$1
1613
- })
1614
- };
1615
- }
1616
- const kinds = (output) => output === void 0 ? [] : rawNames(output).map((h) => h.kind);
1617
- async function controlChars(command, args, fixtureDir, ctx) {
1618
- const runs = await controlCharsRuns(command, args, fixtureDir, ctx);
1619
- const pipeOutput = runs.pipe && runs.pipe.stdout.toString("utf8") + runs.pipe.stderr;
1620
- return {
1621
- check: "control-chars",
1622
- invocation: [command, ...args],
1623
- ...judgeControlChars(runs),
1624
- terminalRaw: kinds(runs.tty?.output),
1625
- pipeRaw: kinds(pipeOutput)
1626
- };
1627
- }
1628
- const controlCharsCheck = {
1629
- name: "control-chars",
1630
- kind: "check",
1631
- summary: "prints control characters from file names raw to the terminal",
1632
- async run(target, ctx) {
1633
- if (target.fixtureDir === void 0) {
1634
- const own = target.probes.filter((p) => p.own);
1635
- return (own.length ? own.map((p) => [target.command, ...p.args]) : [[target.command, ...target.programArgs ?? []]]).map((invocation) => ({
1636
- check: "control-chars",
1637
- invocation,
1638
- ...judgeControlChars({ usesFixture: false }),
1639
- terminalRaw: [],
1640
- pipeRaw: []
1641
- }));
1642
- }
1643
- const dir = target.fixtureDir;
1644
- const results = [];
1645
- for (const { args } of target.probes.filter((p) => p.args.some((a) => a.includes(dir)))) results.push(await controlChars(target.command, args, dir, ctx));
1646
- return results;
1647
- }
1648
- };
1649
- // src/checks/sigterm.ts
1650
- /** How long the program runs before SIGTERM. */
1651
- const SIGTERM_DELAY_MS = 1e3;
1652
- /** How long it gets to exit after SIGTERM. */
1653
- const SIGTERM_GRACE_MS = 3e3;
1654
- /** How long its children get to follow it once it has exited. */
1655
- const SIGTERM_LEFTOVERS_MS = 1e3;
1656
- /** Lines worth quoting from a trace printed on SIGTERM, best first. */
1657
- const TRACE_MESSAGES$1 = [/^(\w*Error\b|\w*Exception\b|panic:)/, TRACE_RE];
1658
- const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "es"}`;
1659
- /** "1 process" or "3 processes", and the evidence naming the first one, for a check that reports leftovers. */
1660
- function describeLeftovers(left) {
1661
- const [first] = left;
1662
- const more = left.length > 1 ? ` (and ${left.length - 1} more)` : "";
1663
- return {
1664
- count: plural(left.length, "process"),
1665
- evidence: `still running: ${first?.command ?? ""}${more}`
1666
- };
1667
- }
1668
- function judgeSigterm(r) {
1669
- if (r.spawnError) return {
1670
- verdict: "error",
1671
- reason: `could not start: ${r.spawnError}`
1672
- };
1673
- if (r.signalSentMs === void 0) return noteFailedExit({
1674
- verdict: "skip",
1675
- reason: `finished in ${r.durationMs} ms, before SIGTERM at ${SIGTERM_DELAY_MS} ms; probe a command that keeps running`
1676
- }, r);
1677
- if (r.timedOut) return {
1678
- verdict: "warn",
1679
- reason: `ignored SIGTERM: still running ${SIGTERM_GRACE_MS / 1e3} s later, so docker stop or a process manager has to kill it`
1680
- };
1681
- const left = r.leftRunning ?? [];
1682
- if (left.length > 0) {
1683
- const { count, evidence } = describeLeftovers(left);
1684
- return {
1685
- verdict: "warn",
1686
- reason: `exited on SIGTERM but left ${count} running, which keep ports and files busy`,
1687
- evidence
1688
- };
1689
- }
1690
- const after = r.stderr.slice(r.stderrAtSignal ?? 0);
1691
- if (TRACE_RE.test(after)) return {
1692
- verdict: "warn",
1693
- reason: "printed a stack trace on SIGTERM",
1694
- evidence: crashEvidence(after, TRACE_MESSAGES$1)
1695
- };
1696
- const ms = `${r.durationMs - r.signalSentMs} ms`;
1697
- return {
1698
- verdict: "pass",
1699
- reason: `${r.signal ? `stopped by ${r.signal}` : `exited with code ${r.exitCode}`} in ${ms} and left nothing running`
1700
- };
1701
- }
1702
- async function sigterm(command, args) {
1703
- const r = await run$1(command, args, {
1704
- timeout: 4e3,
1705
- signal: {
1706
- name: "SIGTERM",
1707
- afterMs: SIGTERM_DELAY_MS,
1708
- to: "process"
1709
- },
1710
- stdin: "open",
1711
- leftoversMs: SIGTERM_LEFTOVERS_MS
1712
- });
1713
- const sent = r.signalSentMs;
1714
- return {
1715
- check: "sigterm",
1716
- invocation: [command, ...args],
1717
- ...judgeSigterm(r),
1718
- sentAfterMs: sent ?? null,
1719
- exitedAfterMs: sent === void 0 || r.timedOut ? null : r.durationMs - sent,
1720
- exitCode: r.exitCode,
1721
- signal: r.signal,
1722
- leftRunning: (r.leftRunning ?? []).map((m) => m.command),
1723
- stderrAfter: sent === void 0 ? "" : r.stderr.slice(r.stderrAtSignal ?? 0).slice(-2e3)
1724
- };
1725
- }
1726
- const sigtermCheck = {
1727
- name: "sigterm",
1728
- kind: "check",
1729
- summary: "ignores SIGTERM, or exits on it and leaves its child processes running",
1730
- async run(target) {
1731
- const own = target.probes.filter((p) => p.own);
1732
- if (own.length === 0) return [{
1733
- check: "sigterm",
1734
- invocation: [target.command, ...target.programArgs ?? []],
1735
- verdict: "skip",
1736
- reason: "needs a probe that keeps running, such as a watch or serve command (--probe), or --bare",
1737
- sentAfterMs: null,
1738
- exitedAfterMs: null,
1739
- exitCode: null,
1740
- signal: null,
1741
- leftRunning: [],
1742
- stderrAfter: ""
1743
- }];
1744
- const results = [];
1745
- for (const { args } of own) results.push(await sigterm(target.command, args));
1746
- return results;
1747
- }
1748
- };
1749
- // src/checks/ctrl-c.ts
1750
- /** How long the program runs before Ctrl-C. */
1751
- const CTRL_C_DELAY_MS = 1e3;
1752
- /** How long it gets to exit after Ctrl-C. */
1753
- const CTRL_C_GRACE_MS = 3e3;
1754
- /** How long the rest of its group gets to follow it once it has exited. */
1755
- const CTRL_C_LEFTOVERS_MS = 1e3;
1756
- /** Lines worth quoting from a trace printed on Ctrl-C, best first. */
1757
- const TRACE_MESSAGES = [/^(KeyboardInterrupt|\w*Error\b|\w*Exception\b|panic:)/, TRACE_RE];
1758
- /**
1759
- * `bare` is true for the --bare probe, the command with no arguments. A REPL run that
1760
- * way (python3) gets a pipe as stdin, reads it as a script and doesn't stop on SIGINT,
1761
- * which no one at a terminal sees; restore, under a terminal, skips REPLs too (#43).
1762
- */
1763
- function judgeCtrlC(r, bare = false) {
1764
- if (r.spawnError) return {
1765
- verdict: "error",
1766
- reason: `could not start: ${r.spawnError}`
1767
- };
1768
- if (r.signalSentMs === void 0) return noteFailedExit({
1769
- verdict: "skip",
1770
- reason: `finished in ${r.durationMs} ms, before Ctrl-C at ${CTRL_C_DELAY_MS} ms; probe a command that keeps running`
1771
- }, r);
1772
- if (r.timedOut) {
1773
- if (bare && r.stdoutBytes === 0 && r.stderr === "") return {
1774
- verdict: "skip",
1775
- reason: `still running ${CTRL_C_GRACE_MS / 1e3} s after Ctrl-C without printing anything, as a REPL does when stdin is a pipe (it waits for a script, not a keypress); run it in a terminal to check its Ctrl-C`
1776
- };
1777
- return {
1778
- verdict: "fail",
1779
- reason: `ignored Ctrl-C: still running ${CTRL_C_GRACE_MS / 1e3} s later`
1780
- };
1781
- }
1782
- const after = r.stderr.slice(r.stderrAtSignal ?? 0);
1783
- const ms = `${r.durationMs - r.signalSentMs} ms`;
1784
- if (TRACE_RE.test(after)) return {
1785
- verdict: "fail",
1786
- reason: "printed a stack trace on Ctrl-C",
1787
- evidence: crashEvidence(after, TRACE_MESSAGES)
1788
- };
1789
- const left = r.leftRunning ?? [];
1790
- if (left.length > 0) {
1791
- const { count, evidence } = describeLeftovers(left);
1792
- return {
1793
- verdict: "warn",
1794
- reason: `exited on Ctrl-C in ${ms} but left ${count} running that ignored it`,
1795
- evidence
1796
- };
1797
- }
1798
- if (r.signal) return {
1799
- verdict: "pass",
1800
- reason: `stopped by ${r.signal} in ${ms}`
1801
- };
1802
- if (r.exitCode === 130) return {
1803
- verdict: "pass",
1804
- reason: `exited with 130, the Ctrl-C convention, in ${ms}`
1805
- };
1806
- if (r.exitCode === 0) return {
1807
- verdict: "warn",
1808
- reason: `exited 0 after Ctrl-C, so a script cannot tell it was interrupted (130 is the convention)`
1809
- };
1810
- return {
1811
- verdict: "pass",
1812
- reason: `exited with code ${r.exitCode} in ${ms} (130 is the convention)`
1813
- };
1814
- }
1815
- async function ctrlC(command, args, bare = args.length === 0) {
1816
- const r = await run$1(command, args, {
1817
- timeout: 4e3,
1818
- signal: {
1819
- name: "SIGINT",
1820
- afterMs: CTRL_C_DELAY_MS
1821
- },
1822
- stdin: "open",
1823
- leftoversMs: CTRL_C_LEFTOVERS_MS
1824
- });
1825
- const sent = r.signalSentMs;
1826
- return {
1827
- check: "ctrl-c",
1828
- invocation: [command, ...args],
1829
- ...judgeCtrlC(r, bare),
1830
- sentAfterMs: sent ?? null,
1831
- exitedAfterMs: sent === void 0 || r.timedOut ? null : r.durationMs - sent,
1832
- exitCode: r.exitCode,
1833
- signal: r.signal,
1834
- leftRunning: (r.leftRunning ?? []).map((m) => m.command),
1835
- stderrAfter: sent === void 0 ? "" : r.stderr.slice(r.stderrAtSignal ?? 0).slice(-2e3)
1836
- };
1837
- }
1838
- const ctrlCCheck = {
1839
- name: "ctrl-c",
1840
- kind: "check",
1841
- summary: "ignores Ctrl-C, or prints a stack trace when interrupted",
1842
- async run(target) {
1843
- const own = target.probes.filter((p) => p.own);
1844
- if (own.length === 0) return [{
1845
- check: "ctrl-c",
1846
- invocation: [target.command, ...target.programArgs ?? []],
1847
- verdict: "skip",
1848
- reason: "needs a probe that keeps running, such as a watch or serve command (--probe), or --bare",
1849
- sentAfterMs: null,
1850
- exitedAfterMs: null,
1851
- exitCode: null,
1852
- signal: null,
1853
- leftRunning: [],
1854
- stderrAfter: ""
1855
- }];
1856
- const results = [];
1857
- for (const { args, bare } of own) results.push(await ctrlC(target.command, args, bare));
1858
- return results;
1859
- }
1860
- };
1861
- // src/checks/pipe-escapes.ts
1862
- /** As in the color check: a capable TERM, so a program can't pass by seeing TERM=dumb, and no CI. */
1863
- const ENV = {
1864
- TERM: "xterm-256color",
1865
- CI: void 0
1866
- };
1867
- const kindsOf = (hits) => [...new Set(hits.map((h) => h.kind))];
1868
- function listLabels$1(kinds) {
1869
- const labels = kinds.map((k) => CONTROL_LABELS[k]);
1870
- return labels.length <= 1 ? labels[0] ?? "" : `${labels.slice(0, -1).join(", ")} and ${labels.at(-1) ?? ""}`;
1871
- }
1872
- /**
1873
- * Escape sequences (cursor, erase, mode, hyperlink, title, other OSC) in a pipe fail: no
1874
- * real tool in the censuses printed one there except by mistake. A carriage-return redraw
1875
- * alone only warns, because some tools draw a progress meter on stderr by design (curl).
1876
- * The sequences added in 1.5 (other ESC sequences, a full reset, control strings, OSC
1877
- * without ";", 8-bit controls) only warn until a census calibrates them (#42).
1878
- */
1879
- function judgePipeEscapes(r) {
1880
- if (r.spawnError) return {
1881
- verdict: "error",
1882
- reason: `could not start: ${r.spawnError}`
1883
- };
1884
- const stdout = r.stdout.toString("utf8");
1885
- const hits = [...findControls(stdout).map((hit) => ({
1886
- stream: "stdout",
1887
- hit
1888
- })), ...findControls(r.stderr).map((hit) => ({
1889
- stream: "stderr",
1890
- hit
1891
- }))];
1892
- const escape = hits.find((h) => h.hit.kind !== "redraw" && !h.hit.warnOnly);
1893
- const newEscape = hits.find((h) => h.hit.warnOnly);
1894
- const first = escape ?? newEscape ?? hits[0];
1895
- if (first) {
1896
- const kinds = [...new Set(hits.map((h) => h.hit.kind))];
1897
- const evidence = `${first.stream} line ${first.hit.line}: ${first.hit.text}`;
1898
- if (escape) return {
1899
- verdict: "fail",
1900
- reason: `printed terminal control codes into a pipe: ${listLabels$1(kinds)}`,
1901
- evidence
1902
- };
1903
- if (newEscape) return {
1904
- verdict: "warn",
1905
- reason: `printed terminal control codes into a pipe: ${listLabels$1(kinds)}; a new finding, so only a warning for now`,
1906
- evidence
1907
- };
1908
- return {
1909
- verdict: "warn",
1910
- reason: "redrew lines with carriage returns in a pipe, as a progress meter does",
1911
- evidence
1912
- };
1913
- }
1914
- if (!stdout && !r.stderr) return r.timedOut ? {
1915
- verdict: "skip",
1916
- reason: `${stillRunning(r.durationMs)} and printed nothing so far`
1917
- } : noteFailedExit({
1918
- verdict: "skip",
1919
- reason: "printed nothing, so there is nothing to check"
1920
- }, r);
1921
- if (r.timedOut) return {
1922
- verdict: "pass",
1923
- reason: `no cursor, erase, hyperlink, title or redraw codes in a pipe (${stillRunning(r.durationMs)})`
1924
- };
1925
- return {
1926
- verdict: "pass",
1927
- reason: "no cursor, erase, hyperlink, title or redraw codes in a pipe"
1928
- };
1929
- }
1930
- async function pipeEscapes(command, args, ctx, fixture = false) {
1931
- const raw = await run$1(command, args, {
1932
- timeout: probeTimeout(ctx, command, args),
1933
- env: ENV
1934
- });
1935
- if (raw.timedOut) markLongRunning(ctx, command, args);
1936
- const r = fixture ? {
1937
- ...raw,
1938
- stdout: Buffer.from(withoutHostileNames(raw.stdout.toString("utf8"))),
1939
- stderr: withoutHostileNames(raw.stderr)
1940
- } : raw;
1941
- return {
1942
- check: "pipe-escapes",
1943
- invocation: [command, ...args],
1944
- ...judgePipeEscapes(r),
1945
- stdoutKinds: kindsOf(findControls(r.stdout.toString("utf8"))),
1946
- stderrKinds: kindsOf(findControls(r.stderr))
1947
- };
1948
- }
1949
- const pipeEscapesCheck = {
1950
- name: "pipe-escapes",
1951
- kind: "check",
1952
- summary: "prints spinners, cursor codes, hyperlinks or titles into a pipe",
1953
- async run(target, ctx) {
1954
- const results = [];
1955
- for (const { args } of target.probes) results.push(await pipeEscapes(target.command, args, ctx, target.fixtureDir !== void 0));
1956
- return results;
1957
- }
1958
- };
1959
- // src/checks/restore.ts
1960
- function listLabels(modes) {
1961
- return listWords(modes.map((m) => m.label));
1962
- }
1963
- function listWords(labels) {
1964
- return labels.length <= 1 ? labels[0] ?? "" : `${labels.slice(0, -1).join(", ")} and ${labels.at(-1) ?? ""}`;
1965
- }
1966
- /** The PTY wrapper's own complaint when it can't exec the program. */
1967
- const WRAPPER_EXEC_FAILED = /^sh: [^\n]*(cannot execute|exec format error)/i;
1968
- /** What the Ctrl-C key sends to a terminal. */
1969
- const CTRL_C_KEY = "";
1970
- function judgeRestore(r) {
1971
- if (r.spawnError) return {
1972
- verdict: "error",
1973
- reason: `could not start: ${r.spawnError}`
1974
- };
1975
- const interrupted = r.inputSentMs !== void 0;
1976
- if (r.timedOut) return {
1977
- verdict: "skip",
1978
- reason: interrupted ? `still running ${CTRL_C_GRACE_MS / 1e3} s after Ctrl-C, so how it leaves the terminal wasn't seen (REPLs and some full-screen programs quit only on a second Ctrl-C)` : "waited for input in a terminal, so it never finished"
1979
- };
1980
- if (r.truncated) return {
1981
- verdict: "skip",
1982
- reason: "printed more than 1 MiB in a terminal, so the end of its output, where it would restore the terminal, was not kept"
1983
- };
1984
- const when = interrupted ? "after Ctrl-C" : "when it exited";
1985
- const open = findOpenModes(r.output);
1986
- const off = r.settingsOff ?? [];
1987
- if (open.length > 0 || off.length > 0) {
1988
- const parts = open.length > 0 ? [`with ${listLabels(open)}`] : [];
1989
- const evidence = open.map((m) => `${m.sequence} on line ${m.line}, never undone`);
1990
- if (off.length > 0) {
1991
- const raw = off.includes("icanon") && off.includes("echo");
1992
- const flags = off.map((name) => `-${name}`);
1993
- parts.push(raw ? `in raw mode (${listWords(off)} off)` : `with ${listWords(off)} off (${flags.join(" ")})`);
1994
- evidence.push(`stty settings never restored: ${flags.join(" ")}`);
1995
- }
1996
- const fix = off.length > 0 ? "; `stty sane` undoes it" : "";
1997
- return {
1998
- verdict: "warn",
1999
- reason: `left the terminal ${parts.join(" and ")} ${when}${fix}`,
2000
- evidence: evidence.join("; ")
2001
- };
2002
- }
2003
- return {
2004
- verdict: "pass",
2005
- reason: `left no terminal mode switched on${r.settingsOff === void 0 ? "" : " and the terminal's settings as it found them"} ${when}`
2006
- };
2007
- }
2008
- async function restore(command, args, { timeout, interrupt }) {
2009
- const r = await runPty(command, args, {
2010
- timeout: interrupt ? 4e3 : timeout,
2011
- ...interrupt ? { input: {
2012
- data: CTRL_C_KEY,
2013
- afterMs: CTRL_C_DELAY_MS
2014
- } } : {},
2015
- settings: true
2016
- });
2017
- const notRun = r.spawnError === void 0 && (r.exitCode === 126 || r.exitCode === 127 || WRAPPER_EXEC_FAILED.test(r.output)) && cannotExecute(command);
2018
- const judgement = judgeRestore(notRun ? {
2019
- ...r,
2020
- spawnError: notAProgram(command, "the terminal's shell could not exec it")
2021
- } : r);
2022
- return {
2023
- check: "restore",
2024
- invocation: [command, ...args],
2025
- ...judgement,
2026
- interrupted: r.inputSentMs !== void 0,
2027
- openModes: judgement.verdict === "warn" ? findOpenModes(r.output) : [],
2028
- settingsOff: notRun ? null : r.settingsOff ?? null
2029
- };
2030
- }
2031
- const restoreCheck = {
2032
- name: "restore",
2033
- kind: "check",
2034
- summary: "leaves the cursor hidden, the alternate screen or mouse mode on after Ctrl-C",
2035
- async run(target, ctx) {
2036
- const support = ptySupport();
2037
- const notRun = findCommand(target.command) === void 0 ? {
2038
- verdict: "error",
2039
- reason: "could not start: command not found"
2040
- } : support.ok ? void 0 : {
2041
- verdict: "skip",
2042
- reason: `needs a terminal (${support.reason})`
2043
- };
2044
- const results = [];
2045
- for (const { args, own } of target.probes) {
2046
- if (notRun) {
2047
- const result = {
2048
- check: "restore",
2049
- invocation: [target.command, ...args],
2050
- ...notRun,
2051
- interrupted: false,
2052
- openModes: [],
2053
- settingsOff: null
2054
- };
2055
- results.push(result);
2056
- continue;
2057
- }
2058
- results.push(await restore(target.command, args, {
2059
- timeout: ctx.timeout,
2060
- interrupt: own
2061
- }));
2062
- }
2063
- return results;
2064
- }
2065
- };
2066
- function median(values) {
2067
- const sorted = [...values].sort((a, b) => a - b);
2068
- const mid = Math.floor(sorted.length / 2);
2069
- return sorted.length % 2 ? sorted[mid] ?? 0 : Math.round(((sorted[mid - 1] ?? 0) + (sorted[mid] ?? 0)) / 2);
2070
- }
2071
- /**
2072
- * Median wall time of one invocation: `<command> --version` by default, how long a
2073
- * user waits for the simplest answer; or the probe exactly as given, so that
2074
- * `node ./dist/cli.js --version` times the CLI rather than Node.
2075
- */
2076
- async function startup(command, args, timeout) {
2077
- const base = {
2078
- check: "startup",
2079
- invocation: [command, ...args]
2080
- };
2081
- const warmUp = await run$1(command, args, { timeout });
2082
- if (warmUp.spawnError) return {
2083
- ...base,
2084
- verdict: "error",
2085
- reason: `could not start: ${warmUp.spawnError}`,
2086
- runsMs: [],
2087
- medianMs: null
2088
- };
2089
- if (warmUp.timedOut) return {
2090
- ...base,
2091
- verdict: "error",
2092
- reason: "timed out",
2093
- runsMs: [],
2094
- medianMs: null
2095
- };
2096
- if (warmUp.exitCode !== 0) return {
2097
- ...base,
2098
- verdict: "skip",
2099
- reason: `exited ${warmUp.exitCode ?? warmUp.signal}, so its time is not a fair startup measure`,
2100
- runsMs: [],
2101
- medianMs: null
2102
- };
2103
- const runsMs = [];
2104
- for (let i = 0; i < 5; i++) {
2105
- const r = await run$1(command, args, { timeout });
2106
- if (r.timedOut || r.spawnError) return {
2107
- ...base,
2108
- verdict: "error",
2109
- reason: "a timed run did not finish",
2110
- runsMs,
2111
- medianMs: null
2112
- };
2113
- runsMs.push(r.durationMs);
2114
- }
2115
- const mid = median(runsMs);
2116
- return {
2117
- ...base,
2118
- verdict: "info",
2119
- reason: `median ${mid} ms over 5 runs (min ${Math.min(...runsMs)}, max ${Math.max(...runsMs)})`,
2120
- runsMs,
2121
- medianMs: mid
2122
- };
2123
- }
2124
- const startupCheck = {
2125
- name: "startup",
2126
- kind: "info",
2127
- summary: "median wall time of --version, or of the given probe, over 5 runs",
2128
- async run(target, ctx) {
2129
- const [first] = target.probes;
2130
- const args = first?.own ? first.args : [...target.programArgs ?? [], "--version"];
2131
- return [await startup(target.command, args, ctx.timeout)];
2132
- }
2133
- };
2134
- // src/checks/stdin.ts
2135
- /** The least time the program gets with stdin left open before it counts as waiting. */
2136
- const STDIN_WAIT_MS = 3e3;
2137
- /** The earliest the confirming run closes stdin, and the least time it then gets to finish. */
2138
- const STDIN_CLOSE_AFTER_MS = 1e3;
2139
- const STDIN_GRACE_MS = 3e3;
2140
- /**
2141
- * How long a run must go past the one with stdin closed before stdin can be
2142
- * blamed: twice that time and a second more, so a program that is merely slow
2143
- * (3 to 4 s to answer) finishes well within it.
2144
- */
2145
- const stdinMargin = (closedMs) => 2 * closedMs + 1e3;
2146
- /**
2147
- * Whether the runs prove the program waited for stdin: it hung with stdin open
2148
- * for well past the time it needed with stdin closed, and in the confirming run
2149
- * it finished after stdin was closed, not before.
2150
- */
2151
- function provenByClose(runs) {
2152
- const { closed, open, closing } = runs;
2153
- const openMs = runs.openMs ?? 3e3;
2154
- const closeAfterMs = runs.closeAfterMs ?? 1e3;
2155
- return open?.timedOut === true && openMs >= stdinMargin(closed.durationMs) && closing !== void 0 && !closing.timedOut && closing.durationMs >= closeAfterMs;
2156
- }
2157
- const seconds = (ms) => `${Math.round(ms / 100) / 10} s`;
2158
- /** The last line printed before waiting, when it reads like a question left on the line. */
2159
- function promptLine(r) {
2160
- const last = stripEscapes(r.stdout.toString("utf8") + r.stderr).split("\n").at(-1) ?? "";
2161
- if (last.includes("\r") || last.trim() === "") return void 0;
2162
- return last;
2163
- }
2164
- /**
2165
- * `defaultProbe` is true for cliprobe's own `--version` and `--help` probes, which
2166
- * must never wait for input. For probes the user wrote, waiting can be the point
2167
- * (a filter such as `grep pattern`), so only a prompt-like wait warns.
2168
- */
2169
- function judgeStdin(runs, defaultProbe) {
2170
- const { closed, open, closing } = runs;
2171
- if (closed.spawnError) return {
2172
- verdict: "error",
2173
- reason: `could not start: ${closed.spawnError}`
2174
- };
2175
- if (closed.timedOut) return {
2176
- verdict: "skip",
2177
- reason: "doesn't finish even with stdin closed, so stdin isn't what it waits for"
2178
- };
2179
- if (!open || !open.timedOut) return {
2180
- verdict: "pass",
2181
- reason: "finished without waiting for stdin"
2182
- };
2183
- const openMs = runs.openMs ?? 3e3;
2184
- const closeAfterMs = runs.closeAfterMs ?? 1e3;
2185
- if (openMs < stdinMargin(closed.durationMs)) return {
2186
- verdict: "skip",
2187
- reason: `takes ${closed.durationMs} ms even with stdin closed, too close to --timeout to tell whether an open stdin makes it wait; raise --timeout`
2188
- };
2189
- if (!closing || closing.timedOut) return {
2190
- verdict: "skip",
2191
- reason: "hung with stdin open, but closing stdin didn't end it, so the cause isn't proven"
2192
- };
2193
- if (!provenByClose(runs)) return {
2194
- verdict: "skip",
2195
- reason: "hung once with stdin open, but finished before stdin was closed the next time, so the cause isn't proven"
2196
- };
2197
- const evidence = `${closed.durationMs} ms with stdin closed; still running after ${seconds(openMs)} with stdin open; finished ${closing.durationMs - closeAfterMs} ms after stdin closed`;
2198
- if (defaultProbe) return {
2199
- verdict: "fail",
2200
- reason: "waited for stdin before answering, so an agent or CI step that leaves stdin open hangs forever",
2201
- evidence
2202
- };
2203
- const prompt = promptLine(open);
2204
- if (prompt !== void 0) return {
2205
- verdict: "warn",
2206
- reason: "seems to prompt for input even though stdin isn't a terminal",
2207
- evidence: `prompt: ${prompt.slice(0, 120)}; ${evidence}`
2208
- };
2209
- return {
2210
- verdict: "skip",
2211
- reason: "reads stdin like a filter and waits until it closes; give it input or </dev/null",
2212
- evidence
2213
- };
2214
- }
2215
- async function stdinRuns(command, args, timeout) {
2216
- const closed = await run$1(command, args, { timeout });
2217
- if (closed.timedOut) return { closed };
2218
- if (closed.spawnError) return { closed };
2219
- const margin = stdinMargin(closed.durationMs);
2220
- const openMs = Math.min(timeout, Math.max(STDIN_WAIT_MS, margin));
2221
- const open = await run$1(command, args, {
2222
- timeout: openMs,
2223
- stdin: "open"
2224
- });
2225
- if (!open.timedOut || openMs < margin) return {
2226
- closed,
2227
- open,
2228
- openMs
2229
- };
2230
- const closeAfterMs = Math.max(STDIN_CLOSE_AFTER_MS, margin);
2231
- return {
2232
- closed,
2233
- open,
2234
- openMs,
2235
- closing: await run$1(command, args, {
2236
- timeout: closeAfterMs + Math.max(STDIN_GRACE_MS, margin),
2237
- stdin: { closeAfterMs }
2238
- }),
2239
- closeAfterMs
2240
- };
2241
- }
2242
- async function stdinCheck(command, args, defaultProbe, ctx) {
2243
- if (isLongRunning(ctx, command, args)) return {
2244
- check: "stdin",
2245
- invocation: [command, ...args],
2246
- verdict: "skip",
2247
- reason: "keeps running even with stdin closed, so stdin isn't what it waits for",
2248
- closedMs: null,
2249
- waitedForStdin: false,
2250
- finishedAfterCloseMs: null
2251
- };
2252
- const runs = await stdinRuns(command, args, ctx.timeout);
2253
- if (runs.closed.timedOut) markLongRunning(ctx, command, args);
2254
- const proven = provenByClose(runs);
2255
- return {
2256
- check: "stdin",
2257
- invocation: [command, ...args],
2258
- ...judgeStdin(runs, defaultProbe),
2259
- closedMs: runs.closed.spawnError ? null : runs.closed.durationMs,
2260
- waitedForStdin: proven,
2261
- finishedAfterCloseMs: proven && runs.closing ? runs.closing.durationMs - (runs.closeAfterMs ?? 1e3) : null
2262
- };
2263
- }
2264
- const stdinCheckDefinition = {
2265
- name: "stdin",
2266
- kind: "check",
2267
- summary: "waits for stdin when it is an open pipe, as agents and CI runners leave it",
2268
- async run(target, ctx) {
2269
- const results = [];
2270
- for (const { args, own } of target.probes) results.push(await stdinCheck(target.command, args, !own, ctx));
2271
- return results;
2272
- }
2273
- };
2274
- // src/checks/write-error.ts
2275
- /** A stack trace that only the failed writes brought out. */
2276
- const newTrace = (base, full) => TRACE_RE.test(full.stderr) && !TRACE_RE.test(base.stderr);
2277
- /** The first line it printed to stderr, as evidence of how it reported the error. */
2278
- const stderrLine = (r) => {
2279
- const message = crashEvidence(r.stderr);
2280
- return message ? { evidence: message } : {};
2281
- };
2282
- const EXITED_ZERO = "exited 0 though every write to stdout failed (no space left on device), so `> file` on a full disk looks like success";
2283
- /** For a program that keeps running: only how it ends, if it ends, is judged. */
2284
- function judgeLongRunning(base, full) {
2285
- if (full.timedOut) return {
2286
- verdict: "pass",
2287
- reason: `${stillRunning(base.durationMs)}; with stdout on a full disk it kept running`
2288
- };
2289
- if (newTrace(base, full)) return {
2290
- verdict: "warn",
2291
- reason: "crashed with a stack trace when a write to stdout failed",
2292
- evidence: crashEvidence(full.stderr)
2293
- };
2294
- if (full.exitCode === 0) return {
2295
- verdict: "warn",
2296
- reason: EXITED_ZERO
2297
- };
2298
- return {
2299
- verdict: "pass",
2300
- reason: `stopped when a write to stdout failed (${exitText(full)})`,
2301
- ...stderrLine(full)
2302
- };
2303
- }
2304
- const exitText = (r) => r.signal ? `stopped by ${r.signal}` : `exit ${r.exitCode}`;
2305
- /**
2306
- * Compares a normal run with a run whose stdout is /dev/full, where every write
2307
- * fails with ENOSPC. A careful program says so and exits non-zero, as GNU
2308
- * coreutils, git and Python do. Warn-only until a census shows no false warns.
2309
- */
2310
- function judge(base, full) {
2311
- if (base.spawnError) return {
2312
- verdict: "error",
2313
- reason: `could not start: ${base.spawnError}`
2314
- };
2315
- if (base.stdoutBytes === 0) return noteFailedExit({
2316
- verdict: "skip",
2317
- reason: base.timedOut ? `${stillRunning(base.durationMs)} without writing to stdout, so a failed write never happened` : "wrote nothing to stdout, so a failed write never happens"
2318
- }, base);
2319
- if (!full) return {
2320
- verdict: "skip",
2321
- reason: "no /dev/full on this system (it needs Linux)"
2322
- };
2323
- if (base.timedOut) return judgeLongRunning(base, full);
2324
- if (full.timedOut) return {
2325
- verdict: "warn",
2326
- reason: "hung when a write to stdout failed",
2327
- ...stderrLine(full)
2328
- };
2329
- if (newTrace(base, full)) return {
2330
- verdict: "warn",
2331
- reason: `crashed with a stack trace when a write to stdout failed (${exitText(full)})`,
2332
- evidence: crashEvidence(full.stderr)
2333
- };
2334
- if (full.exitCode === 0) return {
2335
- verdict: "warn",
2336
- reason: EXITED_ZERO
2337
- };
2338
- return {
2339
- verdict: "pass",
2340
- reason: `reported the failed write (${exitText(full)})`,
2341
- ...stderrLine(full)
2342
- };
2343
- }
2344
- async function writeError(command, args, ctx) {
2345
- const base = await run$1(command, args, { timeout: probeTimeout(ctx, command, args) });
2346
- if (base.timedOut) markLongRunning(ctx, command, args);
2347
- const full = !base.spawnError && base.stdoutBytes > 0 && hasDevFull() ? await run$1(command, args, {
2348
- fullStdout: true,
2349
- timeout: base.timedOut ? Math.min(ctx.timeout, LONG_RUN_WINDOW_MS) : ctx.timeout
2350
- }) : void 0;
2351
- return {
2352
- check: "write-error",
2353
- invocation: [command, ...args],
2354
- ...judge(base, full),
2355
- baseline: {
2356
- exitCode: base.exitCode,
2357
- signal: base.signal,
2358
- stdoutBytes: base.stdoutBytes
2359
- },
2360
- full: full ? {
2361
- exitCode: full.exitCode,
2362
- signal: full.signal,
2363
- timedOut: full.timedOut,
2364
- stderr: full.stderr.slice(-2e3)
2365
- } : null
2366
- };
2367
- }
2368
- // src/checks/index.ts
2369
- /** Every check, in the order they run and are reported. */
2370
- const CHECKS = [
2371
- closedPipeCheck,
2372
- {
2373
- name: "write-error",
2374
- kind: "check",
2375
- summary: "exits 0 or crashes when writing stdout fails (a full disk)",
2376
- async run(target, ctx) {
2377
- const results = [];
2378
- for (const { args } of target.probes) results.push(await writeError(target.command, args, ctx));
2379
- return results;
2380
- }
2381
- },
2382
- colorCheck,
2383
- pipeEscapesCheck,
2384
- stdinCheckDefinition,
2385
- ctrlCCheck,
2386
- sigtermCheck,
2387
- restoreCheck,
2388
- controlCharsCheck,
2389
- startupCheck,
2390
- baselineCheck
2391
- ];
2392
- /**
2393
- * Picks checks by name, keeping registry order, then leaves out those in `skip`.
2394
- * No names selects every check of kind "check": info checks only run when named,
2395
- * because they never fail and baseline sends a flag the user did not ask for.
2396
- */
2397
- function selectChecks(names, skip = []) {
2398
- const known = new Set(CHECKS.map((c) => c.name));
2399
- return {
2400
- checks: (names.length === 0 ? CHECKS.filter((c) => c.kind === "check") : CHECKS.filter((c) => names.includes(c.name))).filter((c) => !skip.includes(c.name)),
2401
- unknown: [...new Set([...names, ...skip].filter((n) => !known.has(n)))]
2402
- };
2403
- }
2404
- // src/core/safe.ts
2405
- /**
2406
- * C0 and C1 controls, DEL, Unicode line separators and bidirectional overrides:
2407
- * everything that can drive a terminal, forge a line, or reorder what is shown.
2408
- */
2409
- const UNSAFE = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
2410
- /** The same, minus C0, which JSON.stringify already escapes. */
2411
- const JSON_UNSAFE = /[\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
2412
- const hex = (c, width) => c.charCodeAt(0).toString(16).padStart(width, "0");
2413
- /**
2414
- * Escapes text from a target (its output, its arguments, file names) for one
2415
- * line of our own report: `\x1b`, `\x0a`, `\u202e`. It can no longer drive the
2416
- * terminal, break the line, or disguise itself.
2417
- */
2418
- function safe(text) {
2419
- return text.replace(UNSAFE, (c) => c.charCodeAt(0) <= 255 ? `\\x${hex(c, 2)}` : `\\u${hex(c, 4)}`);
2420
- }
2421
- /** JSON.stringify, plus \u escapes for the characters it leaves raw. Parses back identically. */
2422
- function safeJson(value) {
2423
- return JSON.stringify(value, null, 2).replace(JSON_UNSAFE, (c) => `\\u${hex(c, 4)}`);
2424
- }
2425
- // src/core/quote.ts
2426
- /** Characters a POSIX shell takes literally in a word; `{fixture}` stays readable. */
2427
- const PLAIN = /^[\w@%+=:,./{}-]+$/;
2428
- /**
2429
- * Joins a command and its arguments the way you would type them in a shell,
2430
- * single-quoting any argument with spaces, quotes or other special characters,
2431
- * so `python3 -c 'import time; time.sleep(30)'` doesn't read as five words.
2432
- * Only for display: cliprobe never runs a shell.
2433
- */
2434
- function shellJoin(args) {
2435
- return args.map((a) => PLAIN.test(a) ? a : `'${a.replaceAll("'", `'\\''`)}'`).join(" ");
2436
- }
2437
- /**
2438
- * Splits `text` into arguments the way a POSIX shell splits a command line:
2439
- * on unquoted whitespace, with '...' taken literally, "..." honoring \" \\ \$ \`,
2440
- * and a backslash escaping the next character. Nothing is expanded: no
2441
- * variables, wildcards or ~. Throws on an unclosed quote or a trailing backslash.
2442
- */
2443
- function shellSplit(text) {
2444
- const words = [];
2445
- let word = "";
2446
- let inWord = false;
2447
- for (let i = 0; i < text.length; i++) {
2448
- const c = text.charAt(i);
2449
- if (c === "'") {
2450
- const end = text.indexOf("'", i + 1);
2451
- if (end < 0) throw new Error("has an unclosed single quote");
2452
- word += text.slice(i + 1, end);
2453
- inWord = true;
2454
- i = end;
2455
- } else if (c === "\"") {
2456
- inWord = true;
2457
- for (i++;; i++) {
2458
- if (i >= text.length) throw new Error("has an unclosed double quote");
2459
- const d = text.charAt(i);
2460
- if (d === "\"") break;
2461
- const next = text.charAt(i + 1);
2462
- if (d === "\\" && next !== "" && "\"\\$`\n".includes(next)) {
2463
- i++;
2464
- if (next !== "\n") word += next;
2465
- } else word += d;
2466
- }
2467
- } else if (c === "\\") {
2468
- if (i + 1 >= text.length) throw new Error("ends with a backslash");
2469
- i++;
2470
- if (text.charAt(i) !== "\n") {
2471
- word += text.charAt(i);
2472
- inWord = true;
2473
- }
2474
- } else if (c === " " || c === " " || c === "\n") {
2475
- if (inWord) words.push(word);
2476
- word = "";
2477
- inWord = false;
2478
- } else {
2479
- word += c;
2480
- inWord = true;
2481
- }
2482
- }
2483
- if (inWord) words.push(word);
2484
- return words;
2485
- }
2486
- // src/report/summary.ts
2487
- function countVerdicts(results) {
2488
- const counts = {
2489
- pass: 0,
2490
- fail: 0,
2491
- warn: 0,
2492
- skip: 0,
2493
- error: 0,
2494
- info: 0
2495
- };
2496
- for (const r of results) counts[r.verdict]++;
2497
- return counts;
2498
- }
2499
- /** How many failures and warnings the config file accepts, so they don't fail the run. */
2500
- const countAccepted = (results) => results.filter((r) => r.accepted).length;
2501
- /**
2502
- * "2 failed, 0 warned, 2 passed, 2 skipped", plus info and could-not-run when
2503
- * present, a note when --strict makes warnings fail, and how many of the failures
2504
- * and warnings the config file accepts.
2505
- */
2506
- function summaryLine(c, strict = false, accepted = 0) {
2507
- const info = c.info ? `, ${c.info} info` : "";
2508
- const errors = c.error ? `, ${c.error} could not run` : "";
2509
- const mode = strict ? " (--strict: warnings fail)" : "";
2510
- const known = accepted ? ` (${accepted} accepted in the config)` : "";
2511
- return `${c.fail} failed, ${c.warn} warned, ${c.pass} passed, ${c.skip} skipped${info}${errors}${mode}${known}`;
2512
- }
2513
- // src/report/human.ts
2514
- const COLORS = {
2515
- pass: 32,
2516
- fail: 31,
2517
- warn: 33,
2518
- skip: 90,
2519
- error: 35,
2520
- info: 36
2521
- };
2522
- const CUT = " ... (--json has the rest)";
2523
- /**
2524
- * Evidence for one line of the report: escaped as safe() does, with a backslash from
2525
- * the program doubled, so the text `\x1b` can't pass for a real escape. Past the limit
2526
- * it ends at a word, or between two escapes, never inside one, and says it was cut.
2527
- */
2528
- function showEvidence(evidence, limit = 200) {
2529
- const pieces = Array.from(evidence, (c) => c === "\\" ? "\\\\" : safe(c));
2530
- let shown = "";
2531
- let wordEnd = 0;
2532
- for (const piece of pieces) {
2533
- if (shown.length + piece.length > limit) return (wordEnd > limit * .6 ? shown.slice(0, wordEnd) : shown) + CUT;
2534
- if (piece === " ") wordEnd = shown.length;
2535
- shown += piece;
2536
- }
2537
- return shown;
2538
- }
2539
- function formatHuman({ version, command, checks, strict, results }, { color }) {
2540
- const paint = (verdict) => {
2541
- const label = verdict.toUpperCase().padEnd(5);
2542
- return color ? `\x1b[${COLORS[verdict]}m${label}\x1b[0m` : label;
2543
- };
2544
- const shownInvocation = (invocation) => safe(shellJoin(invocation));
2545
- const width = Math.max(0, ...results.map((r) => shownInvocation(r.invocation).length).filter((length) => length <= 40));
2546
- const indent = ` ${" ".repeat(5)} ${" ".repeat(width)} `;
2547
- const noun = checks.length === 1 ? "check" : "checks";
2548
- const lines = [`cliprobe ${version}: ${checks.join(", ")} ${noun} for ${safe(command)}`];
2549
- for (const check of checks) {
2550
- lines.push("");
2551
- if (checks.length > 1) lines.push(check);
2552
- for (const r of results.filter((result) => result.check === check)) {
2553
- const invocation = shownInvocation(r.invocation);
2554
- if (invocation.length > width) lines.push(` ${paint(r.verdict)} ${invocation}`, `${indent}${safe(r.reason)}`);
2555
- else lines.push(` ${paint(r.verdict)} ${invocation.padEnd(width)} ${safe(r.reason)}`);
2556
- if (r.evidence) lines.push(`${indent}${showEvidence(r.evidence)}`);
2557
- if (r.accepted) lines.push(`${indent}accepted: ${safe(r.accepted.reason)}`);
2558
- }
2559
- }
2560
- lines.push("", summaryLine(countVerdicts(results), strict, countAccepted(results)));
2561
- return lines.join("\n") + "\n";
2562
- }
2563
- /**
2564
- * The report as JSON. Each result keeps the fields every check shares at the top
2565
- * and moves the check's own measurements into `details`.
2566
- */
2567
- function formatJson({ version, command, checks, strict, results }) {
2568
- return safeJson({
2569
- tool: "cliprobe",
2570
- schemaVersion: 1,
2571
- version,
2572
- command,
2573
- checks,
2574
- strict,
2575
- summary: countVerdicts(results),
2576
- results: results.map(({ check, invocation, verdict, reason, evidence, accepted, ...details }) => ({
2577
- check,
2578
- invocation,
2579
- verdict,
2580
- reason,
2581
- ...evidence === void 0 ? {} : { evidence },
2582
- ...accepted === void 0 ? {} : { accepted },
2583
- details
2584
- }))
2585
- }) + "\n";
2586
- }
2587
- // src/report/junit.ts
2588
- const XML_ESCAPES = {
2589
- "&": "&amp;",
2590
- "<": "&lt;",
2591
- ">": "&gt;",
2592
- "\"": "&quot;",
2593
- "'": "&apos;"
2594
- };
2595
- /**
2596
- * Text that is always well-formed XML 1.0: safe() first turns every control
2597
- * character (most of which XML forbids even when escaped) into a visible escape,
2598
- * then the five markup characters become entities.
2599
- */
2600
- function xml(text) {
2601
- return safe(text).replace(/[&<>"']/g, (c) => XML_ESCAPES[c] ?? c);
2602
- }
2603
- /** A failure, or with --strict a warning, that the config file doesn't accept. */
2604
- const fails = (r, strict) => !r.accepted && (r.verdict === "fail" || strict && r.verdict === "warn");
2605
- /** JUnit's count attributes for a suite or the whole run; with --strict, warnings are failures. */
2606
- function totals(results, strict) {
2607
- const c = countVerdicts(results);
2608
- const failures = results.filter((r) => fails(r, strict)).length;
2609
- return `tests="${results.length}" failures="${failures}" errors="${c.error}" skipped="${c.skip}"`;
2610
- }
2611
- function testcase(r, strict) {
2612
- const open = ` <testcase classname="cliprobe.${xml(r.check)}" name="${xml(shellJoin(r.invocation))}"`;
2613
- const message = `message="${xml(r.reason)}"`;
2614
- const body = r.evidence ? xml(r.evidence) : "";
2615
- const failure = (type) => `${open}>\n <failure ${message} type="${type}">${body}</failure>\n </testcase>`;
2616
- if (fails(r, strict)) return failure(r.verdict);
2617
- if (r.verdict === "error") return `${open}>\n <error ${message} type="error">${body}</error>\n </testcase>`;
2618
- if (r.verdict === "skip") return `${open}>\n <skipped ${message}/>\n </testcase>`;
2619
- const accepted = r.accepted ? `\nAccepted: ${xml(r.accepted.reason)}` : "";
2620
- return `${open}>\n <system-out>${`${r.verdict.toUpperCase()}: ${xml(r.reason)}${r.evidence ? `\n${body}` : ""}${accepted}`}</system-out>\n </testcase>`;
2621
- }
2622
- /** JUnit XML: one testsuite per check, one testcase per result. */
2623
- function formatJunit({ version, command, checks, strict, results }) {
2624
- const suites = checks.map((check) => {
2625
- const own = results.filter((r) => r.check === check);
2626
- return [
2627
- ` <testsuite name="${xml(check)}" ${totals(own, strict)}>`,
2628
- ...own.map((r) => testcase(r, strict)),
2629
- " </testsuite>"
2630
- ].join("\n");
2631
- });
2632
- return [
2633
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
2634
- `<testsuites name="cliprobe ${xml(version)}: ${xml(command)}" ${totals(results, strict)}>`,
2635
- ...suites,
2636
- "</testsuites>",
2637
- ""
2638
- ].join("\n");
2639
- }
2640
- // src/report/markdown.ts
2641
- /**
2642
- * A code span that shows any text literally: control characters escaped onto one
2643
- * line, `|` escaped so a table cell can't be split, and a fence longer than any
2644
- * run of backticks inside.
2645
- */
2646
- function code(text, { inTable }) {
2647
- const body = inTable ? safe(text).replaceAll("|", "\\|") : safe(text);
2648
- const longest = Math.max(0, ...(body.match(/`+/g) ?? []).map((run) => run.length));
2649
- const fence = "`".repeat(longest + 1);
2650
- const pad = body.startsWith("`") || body.endsWith("`") ? " " : "";
2651
- return `${fence}${pad}${body}${pad}${fence}`;
2652
- }
2653
- /**
2654
- * Prose for inside a table cell. Only characters that act mid-line are escaped:
2655
- * emphasis, code, links, HTML, entities and the cell separator. Line-start syntax
2656
- * (`#`, `-`, `1.`) can't trigger there, so it stays readable.
2657
- */
2658
- function prose(text) {
2659
- return safe(text).replace(/[\\`*_[\]<>|~&]/g, (c) => `\\${c}`);
2660
- }
2661
- function row(r, strict) {
2662
- const verdict = r.verdict === "error" || !r.accepted && (r.verdict === "fail" || strict && r.verdict === "warn") ? `**${r.verdict.toUpperCase()}**` : r.verdict.toUpperCase();
2663
- const evidence = (r.evidence ? `<br>${code(r.evidence.slice(0, 300), { inTable: true })}` : "") + (r.accepted ? `<br>Accepted: ${prose(r.accepted.reason)}` : "");
2664
- return `| ${[
2665
- prose(r.check),
2666
- verdict,
2667
- code(shellJoin(r.invocation), { inTable: true }),
2668
- prose(r.reason) + evidence
2669
- ].join(" | ")} |`;
2670
- }
2671
- /** GitHub-flavored Markdown, for a job summary ($GITHUB_STEP_SUMMARY) or a PR comment. */
2672
- function formatMarkdown({ version, command, strict, results }) {
2673
- return [
2674
- `## cliprobe ${version}: ${code(command, { inTable: false })}`,
2675
- "",
2676
- summaryLine(countVerdicts(results), strict, countAccepted(results)),
2677
- "",
2678
- "| Check | Verdict | Invocation | Result |",
2679
- "| --- | --- | --- | --- |",
2680
- ...results.map((r) => row(r, strict)),
2681
- ""
2682
- ].join("\n");
2683
- }
2684
- // src/report/index.ts
2685
- /** The format names, in the order --help lists them. */
2686
- const FORMAT_NAMES = [
2687
- "human",
2688
- "json",
2689
- "markdown",
2690
- "junit"
2691
- ];
2692
- function isFormat(name) {
2693
- return FORMAT_NAMES.includes(name);
2694
- }
2695
- /** Every output format; the Record type makes a missing formatter a type error. */
2696
- const FORMATS = {
2697
- human: formatHuman,
2698
- json: formatJson,
2699
- markdown: formatMarkdown,
2700
- junit: formatJunit
2701
- };
2702
6
  // src/report/write.ts
2703
7
  /** Why a report can't be written to a path, in words for the person who gave it. */
2704
8
  var ReportPathError = class extends Error {};
@@ -2840,20 +144,6 @@ async function writeReportFile(path, text) {
2840
144
  unregister();
2841
145
  }
2842
146
  }
2843
- // src/version.ts
2844
- /**
2845
- * Read from the package manifest at runtime. Works from both `src/` (development)
2846
- * and `dist/` (published): each sits one level below the package root.
2847
- */
2848
- function readVersion() {
2849
- const manifest = createRequire(import.meta.url)("../package.json");
2850
- if (typeof manifest === "object" && manifest !== null && "version" in manifest && typeof manifest.version === "string") return manifest.version;
2851
- return "0.0.0";
2852
- }
2853
- const VERSION = readVersion();
2854
- // src/cli/usage.ts
2855
- /** A mistake in how cliprobe was called, or in its config file: reported with exit 2. */
2856
- var UsageError = class extends Error {};
2857
147
  // src/cli/args.ts
2858
148
  /** Every option cliprobe takes, to tell a forgotten value from a value that starts with -. */
2859
149
  const OPTIONS = /* @__PURE__ */ new Set([
@@ -2881,8 +171,6 @@ const PATH_OPTIONS = /* @__PURE__ */ new Set([
2881
171
  ]);
2882
172
  /** The option name in an argument such as --format=json. */
2883
173
  const flagOf = (arg) => arg.split("=")[0] ?? arg;
2884
- /** How long a probe may run when neither --timeout nor a config file says. */
2885
- const DEFAULT_TIMEOUT_MS = 15e3;
2886
174
  function parseArgs(argv) {
2887
175
  const opts = {
2888
176
  format: "human",
@@ -2912,7 +200,10 @@ function parseArgs(argv) {
2912
200
  const inline = a.includes("=");
2913
201
  const v = inline ? a.slice(a.indexOf("=") + 1) : argv[++i];
2914
202
  if (v === void 0 || v === "") throw new UsageError(`${flag} needs ${what}`);
2915
- if (!inline && v.startsWith("-")) throw new UsageError(`${flag} needs ${what}, got option "${v}"${PATH_OPTIONS.has(flag) && !OPTIONS.has(flagOf(v)) ? `; use ${flag}=${v} or ./${v} for a value that starts with -` : ""}`);
203
+ if (!inline && v.startsWith("-")) {
204
+ const hint = PATH_OPTIONS.has(flag) && !OPTIONS.has(flagOf(v)) ? `; use ${flag}=${v} or ./${v} for a value that starts with -` : "";
205
+ throw new UsageError(`${flag} needs ${what}, got option "${v}"${hint}`);
206
+ }
2916
207
  return v;
2917
208
  };
2918
209
  if (a === "--json") opts.format = "json";
@@ -2963,117 +254,6 @@ function parseArgs(argv) {
2963
254
  }
2964
255
  return opts;
2965
256
  }
2966
- /** The arguments given after the command, the empty --bare probe, or the default --version and --help. */
2967
- function mainProbe(opts) {
2968
- if (opts.bare) return [[]];
2969
- return opts.args.length ? [opts.args] : [["--version"], ["--help"]];
2970
- }
2971
- // src/cli/config.ts
2972
- /** The file `cliprobe` reads from the current directory when no command is given. */
2973
- const CONFIG_FILE = "cliprobe.config.json";
2974
- const KEYS = /* @__PURE__ */ new Set([
2975
- "$schema",
2976
- "command",
2977
- "probes",
2978
- "bare",
2979
- "checks",
2980
- "skip",
2981
- "strict",
2982
- "timeout",
2983
- "accept"
2984
- ]);
2985
- const ACCEPT_KEYS = /* @__PURE__ */ new Set([
2986
- "check",
2987
- "probe",
2988
- "reason"
2989
- ]);
2990
- const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2991
- const isStrings = (value) => Array.isArray(value) && value.every((v) => typeof v === "string");
2992
- /** Reads a config file's text. Every problem is a usage error that names the key. */
2993
- function parseConfig(text, path) {
2994
- const bad = (message) => new UsageError(`${path}: ${message}`);
2995
- let json;
2996
- try {
2997
- json = JSON.parse(text);
2998
- } catch (error) {
2999
- throw bad(`not valid JSON (${error instanceof Error ? error.message : String(error)})`);
3000
- }
3001
- if (!isObject(json)) throw bad("must hold a JSON object");
3002
- const unknownKey = Object.keys(json).find((key) => !KEYS.has(key));
3003
- if (unknownKey !== void 0) throw bad(`unknown key "${unknownKey}" (known: ${[...KEYS].slice(1).join(", ")})`);
3004
- /** Arguments as a string, split like --probe, or as an array of strings, taken as they are. */
3005
- const words = (value, key) => {
3006
- if (isStrings(value)) return value;
3007
- if (typeof value !== "string") throw bad(`"${key}" must be a string or an array of strings`);
3008
- try {
3009
- return shellSplit(value);
3010
- } catch (error) {
3011
- throw bad(`"${key}" ${error instanceof Error ? error.message : String(error)}`);
3012
- }
3013
- };
3014
- const flag = (key) => {
3015
- const value = json[key];
3016
- if (value === void 0) return false;
3017
- if (typeof value !== "boolean") throw bad(`"${key}" must be true or false`);
3018
- return value;
3019
- };
3020
- const names = (key) => {
3021
- const value = json[key];
3022
- if (value === void 0) return [];
3023
- if (!isStrings(value)) throw bad(`"${key}" must be an array of check names`);
3024
- return value;
3025
- };
3026
- const list = (key) => {
3027
- const value = json[key];
3028
- if (value === void 0) return [];
3029
- if (!Array.isArray(value)) throw bad(`"${key}" must be an array`);
3030
- return value;
3031
- };
3032
- if (json["command"] === void 0) throw bad("needs a \"command\", the program to probe");
3033
- const command = words(json["command"], "command");
3034
- if (command.length === 0 || command[0] === "") throw bad("\"command\" is empty");
3035
- const probes = list("probes").map((probe, i) => {
3036
- const args = words(probe, `probes[${i}]`);
3037
- if (args.length === 0) throw bad(`"probes[${i}]" is empty; use "bare": true for no arguments`);
3038
- return args;
3039
- });
3040
- const timeout = json["timeout"];
3041
- if (timeout !== void 0 && (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout <= 0 || timeout > MAX_TIMEOUT_MS)) throw bad(`"timeout" must be a whole number of milliseconds from 1 to ${MAX_TIMEOUT_MS}`);
3042
- const accept = list("accept").map((entry, i) => {
3043
- const key = `accept[${i}]`;
3044
- if (!isObject(entry)) throw bad(`"${key}" must be an object with "check" and "reason"`);
3045
- const extra = Object.keys(entry).find((k) => !ACCEPT_KEYS.has(k));
3046
- if (extra !== void 0) throw bad(`"${key}" has an unknown key "${extra}"`);
3047
- const { check, reason, probe } = entry;
3048
- if (typeof check !== "string" || check === "") throw bad(`"${key}" needs a "check" name`);
3049
- if (typeof reason !== "string" || reason.trim() === "") throw bad(`"${key}" needs a "reason": say why the finding is accepted`);
3050
- return {
3051
- check,
3052
- reason,
3053
- ...probe === void 0 ? {} : { probe: words(probe, `${key}.probe`) }
3054
- };
3055
- });
3056
- return {
3057
- command,
3058
- probes,
3059
- bare: flag("bare"),
3060
- checks: names("checks"),
3061
- skip: names("skip"),
3062
- strict: flag("strict"),
3063
- timeout,
3064
- accept
3065
- };
3066
- }
3067
- /** Reads and parses a config file; a file that can't be read is a usage error too. */
3068
- function loadConfig(path) {
3069
- let text;
3070
- try {
3071
- text = readFileSync(path, "utf8");
3072
- } catch (error) {
3073
- throw new UsageError(`cannot read the config file ${path}: ${error instanceof Error && "code" in error && error.code === "ENOENT" ? "no such file" : error instanceof Error ? error.message : ""}`);
3074
- }
3075
- return parseConfig(text, path);
3076
- }
3077
257
  // src/cli/help.ts
3078
258
  const HELP = `cliprobe ${VERSION}: test a command-line program for terminal-edge bugs
3079
259
 
@@ -3159,7 +339,9 @@ Options:
3159
339
  --skip <name> Leave this check out; repeat it or use commas for several
3160
340
  --strict Exit 1 on a warning too, not only on a failure
3161
341
  --format <name> Output format: human (default), json, markdown (a CI job
3162
- summary or PR comment) or junit (XML for CI test reports)
342
+ summary or PR comment), junit (XML for CI test reports)
343
+ or github (the human report, then an annotation for each
344
+ failure and warning, for a GitHub Actions step)
3163
345
  --json Same as --format json
3164
346
  -o, --output-file <path>
3165
347
  Write the --format report to a file (replaced atomically,
@@ -3184,12 +366,16 @@ current directory, so a project's run is just "npx cliprobe":
3184
366
  ]
3185
367
  }
3186
368
  "command" is the program, script included, so probes don't repeat it. Also
3187
- "bare", "checks", "skip" and "timeout", as the options. "accept" lists known
369
+ "bare", "checks", "skip" and "timeout", as the options, and "defaultProbes":
370
+ false to leave out --version and --help. "accept" lists known
3188
371
  failures and warnings: each stays in the report with its reason but no longer
3189
372
  changes the exit code; leave "probe" out to accept a check for every probe.
3190
373
  Options add to the file: --probe and --skip join its lists, --check and
3191
374
  --timeout replace its values.
3192
375
 
376
+ As a library: import { probe } from 'cliprobe' runs the same checks from a test
377
+ suite and returns the JSON report as an object; see the README.
378
+
3193
379
  Exit codes: 0 no failures, 1 a check failed (or warned, with --strict), 2 usage
3194
380
  error (or a bad config file), could not run, or could not write the report.
3195
381
  Runs the target in the current directory without a shell, with stdin closed
@@ -3197,119 +383,7 @@ Runs the target in the current directory without a shell, with stdin closed
3197
383
  temporary HOME and a minimal environment. Only run programs you trust. When a
3198
384
  probe exits, or when cliprobe is stopped, it kills whatever the probe left
3199
385
  running and removes its temporary files.`;
3200
- // src/cli/plan.ts
3201
- const same = (a, b) => a.length === b.length && a.every((word, i) => word === b[i]);
3202
- const shown = (args) => args.length ? `"${shellJoin(args)}"` : "the bare command";
3203
- /** The plan for a command given on the command line; null when there is none. */
3204
- function planFromArgs(opts) {
3205
- if (opts.command === void 0) return null;
3206
- const own = opts.bare || opts.args.length > 0;
3207
- return {
3208
- command: opts.command,
3209
- programArgs: [],
3210
- probes: [...mainProbe(opts).map((args) => ({
3211
- args,
3212
- own,
3213
- ...opts.bare ? { bare: true } : {}
3214
- })), ...opts.probes.map((args) => ({
3215
- args,
3216
- own: true
3217
- }))],
3218
- checks: opts.checks,
3219
- skip: opts.skip,
3220
- strict: opts.strict,
3221
- timeout: opts.timeout,
3222
- accept: []
3223
- };
3224
- }
3225
- /**
3226
- * The plan for a config file. The command line adds to it: its probes and skips
3227
- * join the file's, --bare and --strict switch on what the file left off, and
3228
- * --check and --timeout replace the file's.
3229
- */
3230
- function planFromConfig(config, path, opts) {
3231
- const bad = (message) => new UsageError(`${path}: ${message}`);
3232
- const [command = "", ...programArgs] = config.command;
3233
- const bare = opts.bare || config.bare;
3234
- const probes = mainProbe({
3235
- bare,
3236
- args: []
3237
- }).map((args) => ({
3238
- args,
3239
- own: bare,
3240
- ...bare ? { bare } : {}
3241
- }));
3242
- for (const args of [...config.probes, ...opts.probes]) {
3243
- if (probes.some((p) => same(p.args, args))) throw bad(`the probe ${shown(args)} is given twice, or already runs`);
3244
- probes.push({
3245
- args,
3246
- own: true
3247
- });
3248
- }
3249
- const known = new Set(CHECKS.map((c) => c.name));
3250
- for (const { check, probe } of config.accept) {
3251
- if (!known.has(check)) throw bad(`"accept" names an unknown check "${check}" (available: ${[...known].join(", ")})`);
3252
- if (probe !== void 0 && !probes.some((p) => same(p.args, probe))) {
3253
- const running = probes.map((p) => shown(p.args)).join(", ");
3254
- throw bad(`"accept" names ${shown(probe)}, which isn't a probe of this run (${running})`);
3255
- }
3256
- }
3257
- return {
3258
- command,
3259
- programArgs,
3260
- probes,
3261
- checks: opts.checks.length ? opts.checks : config.checks,
3262
- skip: [.../* @__PURE__ */ new Set([...config.skip, ...opts.skip])],
3263
- strict: opts.strict || config.strict,
3264
- timeout: opts.timeoutGiven ? opts.timeout : config.timeout ?? 15e3,
3265
- accept: config.accept,
3266
- configPath: path
3267
- };
3268
- }
3269
- /** Whether an accepted finding is this result: the same check and, when it names one, the same probe. */
3270
- const matches = (accept, r, plan) => accept.check === r.check && (accept.probe === void 0 || same(r.invocation, [
3271
- plan.command,
3272
- ...plan.programArgs,
3273
- ...accept.probe
3274
- ]));
3275
- /**
3276
- * Marks the failures and warnings the config accepts. A verdict never changes;
3277
- * an accepted result only stops counting toward the exit code.
3278
- */
3279
- function applyAccepts(results, plan) {
3280
- const used = /* @__PURE__ */ new Set();
3281
- return {
3282
- results: results.map((r) => {
3283
- if (r.verdict !== "fail" && r.verdict !== "warn") return r;
3284
- const accept = plan.accept.find((a) => matches(a, r, plan));
3285
- if (!accept) return r;
3286
- used.add(accept);
3287
- return {
3288
- ...r,
3289
- accepted: { reason: accept.reason }
3290
- };
3291
- }),
3292
- stale: plan.accept.filter((a) => {
3293
- if (used.has(a)) return false;
3294
- const own = results.filter((r) => matches(a, r, plan));
3295
- return own.length > 0 && own.every((r) => r.verdict === "pass");
3296
- })
3297
- };
3298
- }
3299
- /** How a stale accepted finding is named in the note about it. */
3300
- const describeAccept = ({ check, probe }) => probe === void 0 ? check : `${check} for ${shown(probe)}`;
3301
386
  // src/cli/program.ts
3302
- /**
3303
- * 0 no failures, 1 a check failed (or, with `strict`, warned), 2 nothing could be
3304
- * judged because something could not run. A failure or warning the config file
3305
- * accepts doesn't count.
3306
- */
3307
- function exitCodeFor(results, strict = false) {
3308
- const counts = (r) => !r.accepted && (r.verdict === "fail" || strict && r.verdict === "warn");
3309
- if (results.some(counts)) return 1;
3310
- if (!results.some((r) => r.verdict !== "error" && r.verdict !== "skip") && results.some((r) => r.verdict === "error")) return 2;
3311
- return 0;
3312
- }
3313
387
  /** The whole CLI: parses argv, runs the checks, reports, and returns the exit code. */
3314
388
  async function run(argv, io) {
3315
389
  const out = io.stdout;
@@ -3331,77 +405,27 @@ async function run(argv, io) {
3331
405
  return 0;
3332
406
  }
3333
407
  let plan;
408
+ let checks;
3334
409
  try {
3335
410
  plan = planFromArgs(opts);
3336
411
  const path = opts.config ?? (plan === null && existsSync("cliprobe.config.json") ? "cliprobe.config.json" : null);
3337
412
  if (path !== null) plan = planFromConfig(loadConfig(path), path, opts);
413
+ if (plan === null) {
414
+ err(`cliprobe: no command given, and no ${CONFIG_FILE} in this directory\nUsage: cliprobe [options] -- <command> [args...]\n`);
415
+ return 2;
416
+ }
417
+ checks = prepare(plan, io.platform);
3338
418
  } catch (error) {
3339
- if (!(error instanceof UsageError)) throw error;
419
+ if (!(error instanceof ProbeError)) throw error;
3340
420
  err(`cliprobe: ${safe(error.message)}\n`);
3341
421
  return 2;
3342
422
  }
3343
- if (plan === null) {
3344
- err(`cliprobe: no command given, and no ${CONFIG_FILE} in this directory\nUsage: cliprobe [options] -- <command> [args...]\n`);
3345
- return 2;
3346
- }
3347
- const { checks, unknown } = selectChecks(plan.checks, plan.skip);
3348
- if (unknown.length) {
3349
- const available = CHECKS.map((c) => c.name).join(", ");
3350
- err(`cliprobe: unknown check ${unknown.map((n) => `"${n}"`).join(", ")} (available: ${available})\n`);
3351
- return 2;
3352
- }
3353
- if (checks.length === 0) {
3354
- err("cliprobe: --skip leaves no check to run\n");
3355
- return 2;
3356
- }
3357
- if (io.platform === "win32") {
3358
- err("cliprobe: Windows is not supported yet (the closed-pipe check needs mkfifo).\n");
3359
- return 2;
3360
- }
3361
- const problem = commandProblem(plan.command);
3362
- if (problem !== void 0) {
3363
- err(`cliprobe: ${safe(problem)}\n`);
3364
- return 2;
3365
- }
3366
423
  const pathProblem = opts.outputFile === void 0 ? void 0 : reportPathProblem(opts.outputFile);
3367
424
  if (pathProblem !== void 0) {
3368
425
  err(`cliprobe: cannot write the report to ${safe(opts.outputFile ?? "")}: ${safe(pathProblem)}\n`);
3369
426
  return 2;
3370
427
  }
3371
- const probes = plan.probes.map((p) => ({
3372
- ...p,
3373
- args: [...plan.programArgs, ...p.args]
3374
- }));
3375
- const fixture = probes.some((p) => usesFixture(p.args)) ? createFixture() : void 0;
3376
- const unregister = fixture && onInterrupt(() => fixture.cleanup());
3377
- const results = [];
3378
- try {
3379
- const target = {
3380
- command: plan.command,
3381
- ...plan.programArgs.length ? { programArgs: plan.programArgs } : {},
3382
- probes: fixture ? probes.map((p) => ({
3383
- ...p,
3384
- args: expandFixture(p.args, fixture.dir)
3385
- })) : probes,
3386
- ...fixture ? { fixtureDir: fixture.dir } : {}
3387
- };
3388
- const ctx = {
3389
- timeout: plan.timeout,
3390
- longRunning: /* @__PURE__ */ new Set()
3391
- };
3392
- for (const check of checks) results.push(...await check.run(target, ctx));
3393
- } finally {
3394
- unregister?.();
3395
- fixture?.cleanup();
3396
- }
3397
- const accepted = applyAccepts(fixture ? collapseResults(results, fixture) : results, plan);
3398
- const report = {
3399
- version: VERSION,
3400
- command: plan.command,
3401
- checks: checks.map((c) => c.name),
3402
- strict: plan.strict,
3403
- results: accepted.results
3404
- };
428
+ const { report, stale } = await execute(plan, checks);
3405
429
  const { color } = io;
3406
430
  if (opts.outputFile) {
3407
431
  let failure;
@@ -3416,7 +440,7 @@ async function run(argv, io) {
3416
440
  return 2;
3417
441
  }
3418
442
  } else out(FORMATS[opts.format](report, { color }));
3419
- for (const stale of accepted.stale) err(`cliprobe: ${safe(plan.configPath ?? "cliprobe.config.json")} accepts ${safe(describeAccept(stale))}, which passed: remove it from "accept"\n`);
443
+ for (const accept of stale) err(`cliprobe: ${safe(plan.configPath ?? "cliprobe.config.json")} accepts ${safe(describeAccept(accept))}, which passed: remove it from "accept"\n`);
3420
444
  return exitCodeFor(report.results, plan.strict);
3421
445
  }
3422
446
  // src/cli/main.ts