cliprobe 1.4.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +8 -8
  2. package/dist/cli.js +171 -41
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -150,7 +150,7 @@ npx cliprobe --strict --skip restore -- node ./dist/cli.js server # warnings f
150
150
  | `1` | A check failed, or warned with `--strict` |
151
151
  | `2` | Usage error, or the command could not run |
152
152
 
153
- A command that isn't on `PATH` is reported once, before any check runs, with exit `2` and no report. That makes cliprobe usable as a CI gate.
153
+ A command that can't run is reported once, before any check runs, with exit `2` and no report: one that isn't on `PATH`, a directory, a file without the execute bit (`chmod +x`), or a script whose `#!` interpreter is missing. A file this system can't execute at all, such as a binary built for another platform, makes every check say could-not-run (`ERROR`), so cliprobe exits `2` there too; on Linux, where `/bin/sh` tries such a file as a script, cliprobe recognizes the shell's complaint. That makes cliprobe usable as a CI gate.
154
154
 
155
155
  ## In CI
156
156
 
@@ -270,14 +270,14 @@ A carriage-return redraw only warns because some tools draw a progress meter on
270
270
 
271
271
  ### stdin
272
272
 
273
- Agents and CI runners often start a command with stdin as a pipe that stays open and never receives anything. A program that reads stdin, or asks a question, then waits forever. cliprobe runs the command three ways: with stdin closed (`/dev/null`), with an open pipe, and, if that hangs for 3 seconds, with a pipe it closes after 1 second. Finishing right after the close proves stdin was the cause. Results:
273
+ Agents and CI runners often start a command with stdin as a pipe that stays open and never receives anything. A program that reads stdin, or asks a question, then waits forever. cliprobe runs the command three ways: with stdin closed (`/dev/null`), with an open pipe, and, if that hangs, with a pipe it closes partway through. Finishing only after the close proves stdin was the cause. The open pipe gets 3 seconds, or twice the time the command took with stdin closed plus 1 second if that is longer, so a program that is just slow to answer isn't mistaken for one that waits. The pipe in the third run is closed after 1 second, or after that longer time for a slow command. Each run still stops at `--timeout`. Results:
274
274
 
275
- | Verdict | Meaning |
276
- | ------- | ------------------------------------------------------------------------------------------------------------------------- |
277
- | `PASS` | Finished without waiting for stdin |
278
- | `FAIL` | `--version` or `--help` waited for stdin before answering: they must never need input |
279
- | `WARN` | A probe you wrote printed an unfinished line, like a question, then waited: it prompts even though stdin isn't a terminal |
280
- | `SKIP` | A probe you wrote waited silently, like a filter (`grep pattern`), or the hang wasn't caused by stdin |
275
+ | Verdict | Meaning |
276
+ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
277
+ | `PASS` | Finished without waiting for stdin |
278
+ | `FAIL` | `--version` or `--help` waited for stdin before answering: they must never need input |
279
+ | `WARN` | A probe you wrote printed an unfinished line, like a question, then waited: it prompts even though stdin isn't a terminal |
280
+ | `SKIP` | A probe you wrote waited silently, like a filter (`grep pattern`), the hang wasn't caused by stdin, or the command is too slow for `--timeout` to tell |
281
281
 
282
282
  In the census of the top 100 npm CLIs, 9 of 238 `--help` and `--version` runs failed, each confirmed by hand. he, cssesc and ansi-html read stdin before looking at their arguments. webpack and webpack-dev-server, when webpack-cli is missing, ask whether to install it and wait for an answer without checking for a terminal. With no arguments, 17 tools waited on stdin as filters by design, which is why probes you write never fail this check.
283
283
 
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from "node:module";
3
3
  import { execFile, execFileSync, spawn } from "node:child_process";
4
- import { accessSync, closeSync, constants, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
4
+ import { accessSync, closeSync, constants, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
5
5
  import { delimiter, dirname, join } from "node:path";
6
6
  import { tmpdir } from "node:os";
7
7
  // src/core/interrupt.ts
@@ -218,6 +218,110 @@ function sandbox() {
218
218
  }
219
219
  };
220
220
  }
221
+ // src/core/which.ts
222
+ function isExecutableFile(path) {
223
+ try {
224
+ accessSync(path, constants.X_OK);
225
+ return statSync(path).isFile();
226
+ } catch {
227
+ return false;
228
+ }
229
+ }
230
+ /**
231
+ * Where `command` would be found, as spawn() looks for it: a path with a slash
232
+ * as given, otherwise each PATH entry in turn (an empty entry is the current
233
+ * directory). Under a PTY, a missing command is only a line of shell output, so
234
+ * the terminal checks ask first.
235
+ */
236
+ function findCommand(command, path = process.env["PATH"] ?? "/usr/bin:/bin") {
237
+ if (command.includes("/")) return isExecutableFile(command) ? command : void 0;
238
+ for (const dir of path.split(delimiter)) {
239
+ const candidate = join(dir || ".", command);
240
+ if (isExecutableFile(candidate)) return candidate;
241
+ }
242
+ }
243
+ /** The first bytes of a file, or nothing when it can't be read (execute-only, say). */
244
+ function head(path, bytes = 512) {
245
+ let fd;
246
+ try {
247
+ fd = openSync(path, "r");
248
+ const buffer = Buffer.alloc(bytes);
249
+ return buffer.subarray(0, readSync(fd, buffer, 0, bytes, 0));
250
+ } catch {
251
+ return Buffer.alloc(0);
252
+ } finally {
253
+ if (fd !== void 0) closeSync(fd);
254
+ }
255
+ }
256
+ /** Why the interpreter named on a `#!` line can't run, if it can't. */
257
+ function interpreterProblem(command, file, path) {
258
+ const start = head(file, 256);
259
+ if (start.subarray(0, 2).toString("latin1") !== "#!") return void 0;
260
+ const [interpreter = "", first] = (start.toString("utf8").slice(2).split("\n")[0] ?? "").trim().split(/[ \t]+/);
261
+ if (interpreter === "") return void 0;
262
+ try {
263
+ statSync(interpreter);
264
+ } catch {
265
+ return `${command}: interpreter ${interpreter} not found`;
266
+ }
267
+ if (!isExecutableFile(interpreter)) return `${command}: interpreter ${interpreter} is not executable`;
268
+ if (/(^|\/)env$/.test(interpreter) && first !== void 0 && !first.startsWith("-")) {
269
+ if (!first.includes("=") && findCommand(first, path) === void 0) return `${command}: interpreter ${first} not found (${interpreter} ${first})`;
270
+ }
271
+ }
272
+ /**
273
+ * Why `command` can't run, or undefined if it looks runnable: not found, a
274
+ * directory, not executable, or a `#!` interpreter that is missing. Asked before
275
+ * any check, so the user sees the cause once instead of an error per probe.
276
+ */
277
+ function commandProblem(command, path = process.env["PATH"] ?? "/usr/bin:/bin") {
278
+ if (command.includes("/")) {
279
+ let isFile;
280
+ try {
281
+ const stat = statSync(command);
282
+ if (stat.isDirectory()) return `${command} is a directory`;
283
+ isFile = stat.isFile();
284
+ } catch {
285
+ return `command not found: ${command}`;
286
+ }
287
+ if (!isFile) return `${command} is not a regular file`;
288
+ if (!isExecutableFile(command)) return `${command} is not executable (chmod +x?)`;
289
+ return interpreterProblem(command, command, path);
290
+ }
291
+ const file = findCommand(command, path);
292
+ if (file === void 0) return `command not found: ${command}`;
293
+ return interpreterProblem(command, file, path);
294
+ }
295
+ /** The reason given for a file this system can't run as a program. */
296
+ const notAProgram = (command, how) => `${command} is not a program this system can run (${how})`;
297
+ /**
298
+ * Whether `command` resolves to a file that no shell or kernel would run as a
299
+ * program of this system: no `#!` line, and a NUL byte near its start, which no
300
+ * script has. Alone this could be a binary run through binfmt_misc, so callers
301
+ * also need the run to have exited 126 or 127.
302
+ */
303
+ function cannotExecute(command, path = process.env["PATH"] ?? "/usr/bin:/bin") {
304
+ const file = findCommand(command, path);
305
+ if (file === void 0) return false;
306
+ const start = head(file);
307
+ return start.subarray(0, 2).toString("latin1") !== "#!" && start.includes(0);
308
+ }
309
+ /**
310
+ * Whether a run ended because the system could not run the file at all. On
311
+ * Linux, spawn() hands a file the kernel can't execute (ENOEXEC) to /bin/sh,
312
+ * as execvp() does, so a binary that isn't one for this system "runs" and exits
313
+ * 126 or 127 with the shell's complaint, prefixed by the file's path. Only a
314
+ * file with no `#!` line and a NUL byte near its start counts, as no script has
315
+ * one: a binary run through binfmt_misc, or a script without `#!`, is left alone.
316
+ * Returns the reason, or undefined.
317
+ */
318
+ function shellFallbackError(command, exitCode, stderr, path = process.env["PATH"] ?? "/usr/bin:/bin") {
319
+ if (exitCode !== 126 && exitCode !== 127) return void 0;
320
+ const file = findCommand(command, path);
321
+ if (file === void 0 || !cannotExecute(command, path)) return void 0;
322
+ if (!stderr.startsWith(`${command}: `) && !stderr.startsWith(`${file}: `)) return void 0;
323
+ return notAProgram(command, `/bin/sh tried it as a script and exited ${exitCode}`);
324
+ }
221
325
  // src/core/run.ts
222
326
  const STDERR_CAP = 65536;
223
327
  const STDOUT_CAP = 1048576;
@@ -317,7 +421,7 @@ function run$1(command, args, { closedStdout = false, timeout, env: overrides =
317
421
  finish({
318
422
  exitCode: null,
319
423
  signal: null,
320
- spawnError: error instanceof Error ? error.message : String(error)
424
+ spawnError: spawnMessage(command, error)
321
425
  });
322
426
  return;
323
427
  }
@@ -386,9 +490,11 @@ function run$1(command, args, { closedStdout = false, timeout, env: overrides =
386
490
  }
387
491
  proc.stdout?.destroy();
388
492
  proc.stderr?.destroy();
493
+ const notRun = timedOut ? void 0 : shellFallbackError(command, exitCode, stderr);
389
494
  finish({
390
495
  exitCode,
391
- signal: exitSignal
496
+ signal: exitSignal,
497
+ ...notRun === void 0 ? {} : { spawnError: notRun }
392
498
  });
393
499
  })();
394
500
  });
@@ -405,7 +511,7 @@ function run$1(command, args, { closedStdout = false, timeout, env: overrides =
405
511
  finish({
406
512
  exitCode: null,
407
513
  signal: null,
408
- spawnError: error.message
514
+ spawnError: spawnMessage(command, error)
409
515
  });
410
516
  });
411
517
  proc.on("close", () => {
@@ -414,6 +520,11 @@ function run$1(command, args, { closedStdout = false, timeout, env: overrides =
414
520
  });
415
521
  });
416
522
  }
523
+ /** Why spawn() failed; "spawn ENOEXEC" names neither the file nor the problem. */
524
+ function spawnMessage(command, error) {
525
+ if (!(error instanceof Error)) return String(error);
526
+ return "code" in error && error.code === "ENOEXEC" ? notAProgram(command, "exec format error") : error.message;
527
+ }
417
528
  /**
418
529
  * Waits up to `ms` for what the program left running to finish on its own, as
419
530
  * children stopped by their parent take a moment to exit, and returns what is
@@ -1720,33 +1831,13 @@ const pipeEscapesCheck = {
1720
1831
  return results;
1721
1832
  }
1722
1833
  };
1723
- // src/core/which.ts
1724
- function isExecutableFile(path) {
1725
- try {
1726
- accessSync(path, constants.X_OK);
1727
- return statSync(path).isFile();
1728
- } catch {
1729
- return false;
1730
- }
1731
- }
1732
- /**
1733
- * Where `command` would be found, as spawn() looks for it: a path with a slash
1734
- * as given, otherwise each PATH entry in turn (an empty entry is the current
1735
- * directory). Under a PTY, a missing command is only a line of shell output, so
1736
- * the terminal checks ask first.
1737
- */
1738
- function findCommand(command, path = process.env["PATH"] ?? "/usr/bin:/bin") {
1739
- if (command.includes("/")) return isExecutableFile(command) ? command : void 0;
1740
- for (const dir of path.split(delimiter)) {
1741
- const candidate = join(dir || ".", command);
1742
- if (isExecutableFile(candidate)) return candidate;
1743
- }
1744
- }
1745
1834
  // src/checks/restore.ts
1746
1835
  function listLabels(modes) {
1747
1836
  const labels = modes.map((m) => m.label);
1748
1837
  return labels.length <= 1 ? labels[0] ?? "" : `${labels.slice(0, -1).join(", ")} and ${labels.at(-1) ?? ""}`;
1749
1838
  }
1839
+ /** The PTY wrapper's own complaint when it can't exec the program. */
1840
+ const WRAPPER_EXEC_FAILED = /^sh: [^\n]*(cannot execute|exec format error)/i;
1750
1841
  /** What the Ctrl-C key sends to a terminal. */
1751
1842
  const CTRL_C_KEY = "";
1752
1843
  const showSequence = (sequence) => sequence.replaceAll("\x1B", "ESC");
@@ -1784,7 +1875,10 @@ async function restore(command, args, { timeout, interrupt }) {
1784
1875
  afterMs: CTRL_C_DELAY_MS
1785
1876
  } } : {}
1786
1877
  });
1787
- const judgement = judgeRestore(r);
1878
+ const judgement = judgeRestore(r.spawnError === void 0 && (r.exitCode === 126 || r.exitCode === 127 || WRAPPER_EXEC_FAILED.test(r.output)) && cannotExecute(command) ? {
1879
+ ...r,
1880
+ spawnError: notAProgram(command, "the terminal's shell could not exec it")
1881
+ } : r);
1788
1882
  return {
1789
1883
  check: "restore",
1790
1884
  invocation: [command, ...args],
@@ -1896,10 +1990,29 @@ const startupCheck = {
1896
1990
  }
1897
1991
  };
1898
1992
  // src/checks/stdin.ts
1899
- /** How long the program gets with stdin left open before it counts as waiting. */
1993
+ /** The least time the program gets with stdin left open before it counts as waiting. */
1900
1994
  const STDIN_WAIT_MS = 3e3;
1901
- /** When the confirming run closes stdin, and how long it then gets to finish. */
1995
+ /** The earliest the confirming run closes stdin, and the least time it then gets to finish. */
1902
1996
  const STDIN_CLOSE_AFTER_MS = 1e3;
1997
+ const STDIN_GRACE_MS = 3e3;
1998
+ /**
1999
+ * How long a run must go past the one with stdin closed before stdin can be
2000
+ * blamed: twice that time and a second more, so a program that is merely slow
2001
+ * (3 to 4 s to answer) finishes well within it.
2002
+ */
2003
+ const stdinMargin = (closedMs) => 2 * closedMs + 1e3;
2004
+ /**
2005
+ * Whether the runs prove the program waited for stdin: it hung with stdin open
2006
+ * for well past the time it needed with stdin closed, and in the confirming run
2007
+ * it finished after stdin was closed, not before.
2008
+ */
2009
+ function provenByClose(runs) {
2010
+ const { closed, open, closing } = runs;
2011
+ const openMs = runs.openMs ?? 3e3;
2012
+ const closeAfterMs = runs.closeAfterMs ?? 1e3;
2013
+ return open?.timedOut === true && openMs >= stdinMargin(closed.durationMs) && closing !== void 0 && !closing.timedOut && closing.durationMs >= closeAfterMs;
2014
+ }
2015
+ const seconds = (ms) => `${Math.round(ms / 100) / 10} s`;
1903
2016
  /** The last line printed before waiting, when it reads like a question left on the line. */
1904
2017
  function promptLine(r) {
1905
2018
  const last = stripEscapes(r.stdout.toString("utf8") + r.stderr).split("\n").at(-1) ?? "";
@@ -1925,11 +2038,21 @@ function judgeStdin(runs, defaultProbe) {
1925
2038
  verdict: "pass",
1926
2039
  reason: "finished without waiting for stdin"
1927
2040
  };
2041
+ const openMs = runs.openMs ?? 3e3;
2042
+ const closeAfterMs = runs.closeAfterMs ?? 1e3;
2043
+ if (openMs < stdinMargin(closed.durationMs)) return {
2044
+ verdict: "skip",
2045
+ reason: `takes ${closed.durationMs} ms even with stdin closed, too close to --timeout to tell whether an open stdin makes it wait; raise --timeout`
2046
+ };
1928
2047
  if (!closing || closing.timedOut) return {
1929
2048
  verdict: "skip",
1930
2049
  reason: "hung with stdin open, but closing stdin didn't end it, so the cause isn't proven"
1931
2050
  };
1932
- const evidence = `${closed.durationMs} ms with stdin closed; still running after ${STDIN_WAIT_MS / 1e3} s with stdin open; finished ${closing.durationMs - STDIN_CLOSE_AFTER_MS} ms after stdin closed`;
2051
+ if (!provenByClose(runs)) return {
2052
+ verdict: "skip",
2053
+ reason: "hung once with stdin open, but finished before stdin was closed the next time, so the cause isn't proven"
2054
+ };
2055
+ const evidence = `${closed.durationMs} ms with stdin closed; still running after ${seconds(openMs)} with stdin open; finished ${closing.durationMs - closeAfterMs} ms after stdin closed`;
1933
2056
  if (defaultProbe) return {
1934
2057
  verdict: "fail",
1935
2058
  reason: "waited for stdin before answering, so an agent or CI step that leaves stdin open hangs forever",
@@ -1951,21 +2074,27 @@ async function stdinRuns(command, args, timeout) {
1951
2074
  const closed = await run$1(command, args, { timeout });
1952
2075
  if (closed.timedOut) return { closed };
1953
2076
  if (closed.spawnError) return { closed };
2077
+ const margin = stdinMargin(closed.durationMs);
2078
+ const openMs = Math.min(timeout, Math.max(STDIN_WAIT_MS, margin));
1954
2079
  const open = await run$1(command, args, {
1955
- timeout: STDIN_WAIT_MS,
2080
+ timeout: openMs,
1956
2081
  stdin: "open"
1957
2082
  });
1958
- if (!open.timedOut) return {
2083
+ if (!open.timedOut || openMs < margin) return {
1959
2084
  closed,
1960
- open
2085
+ open,
2086
+ openMs
1961
2087
  };
2088
+ const closeAfterMs = Math.max(STDIN_CLOSE_AFTER_MS, margin);
1962
2089
  return {
1963
2090
  closed,
1964
2091
  open,
2092
+ openMs,
1965
2093
  closing: await run$1(command, args, {
1966
- timeout: 4e3,
1967
- stdin: { closeAfterMs: STDIN_CLOSE_AFTER_MS }
1968
- })
2094
+ timeout: closeAfterMs + Math.max(STDIN_GRACE_MS, margin),
2095
+ stdin: { closeAfterMs }
2096
+ }),
2097
+ closeAfterMs
1969
2098
  };
1970
2099
  }
1971
2100
  async function stdinCheck(command, args, defaultProbe, ctx) {
@@ -1980,14 +2109,14 @@ async function stdinCheck(command, args, defaultProbe, ctx) {
1980
2109
  };
1981
2110
  const runs = await stdinRuns(command, args, ctx.timeout);
1982
2111
  if (runs.closed.timedOut) markLongRunning(ctx, command, args);
1983
- const proven = runs.open?.timedOut === true && runs.closing !== void 0 && !runs.closing.timedOut;
2112
+ const proven = provenByClose(runs);
1984
2113
  return {
1985
2114
  check: "stdin",
1986
2115
  invocation: [command, ...args],
1987
2116
  ...judgeStdin(runs, defaultProbe),
1988
2117
  closedMs: runs.closed.spawnError ? null : runs.closed.durationMs,
1989
2118
  waitedForStdin: proven,
1990
- finishedAfterCloseMs: proven && runs.closing ? runs.closing.durationMs - STDIN_CLOSE_AFTER_MS : null
2119
+ finishedAfterCloseMs: proven && runs.closing ? runs.closing.durationMs - (runs.closeAfterMs ?? 1e3) : null
1991
2120
  };
1992
2121
  }
1993
2122
  // src/checks/index.ts
@@ -2151,7 +2280,7 @@ function formatHuman({ version, command, checks, strict, results }, { color }) {
2151
2280
  lines.push("");
2152
2281
  if (checks.length > 1) lines.push(check);
2153
2282
  for (const r of results.filter((result) => result.check === check)) {
2154
- lines.push(` ${paint(r.verdict)} ${safe(shellJoin(r.invocation)).padEnd(width)} ${r.reason}`);
2283
+ lines.push(` ${paint(r.verdict)} ${safe(shellJoin(r.invocation)).padEnd(width)} ${safe(r.reason)}`);
2155
2284
  if (r.evidence) lines.push(` ${" ".repeat(5)} ${" ".repeat(width)} ${safe(r.evidence).slice(0, 200)}`);
2156
2285
  }
2157
2286
  }
@@ -2533,8 +2662,9 @@ async function run(argv, io) {
2533
2662
  err("cliprobe: Windows is not supported yet (the closed-pipe check needs mkfifo).\n");
2534
2663
  return 2;
2535
2664
  }
2536
- if (findCommand(opts.command) === void 0) {
2537
- err(`cliprobe: command not found: ${safe(opts.command)}\n`);
2665
+ const problem = commandProblem(opts.command);
2666
+ if (problem !== void 0) {
2667
+ err(`cliprobe: ${safe(problem)}\n`);
2538
2668
  return 2;
2539
2669
  }
2540
2670
  const own = opts.bare || opts.args.length > 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cliprobe",
3
- "version": "1.4.0",
3
+ "version": "1.4.1",
4
4
  "description": "Black-box test any command-line program for terminal-edge bugs: crashes on a closed pipe (| head), color and control codes leaking into pipes, hangs waiting on stdin, broken Ctrl-C handling, child processes left running after SIGTERM, a terminal left broken after Ctrl-C, and control characters from file names reaching your terminal.",
5
5
  "type": "module",
6
6
  "bin": {