cliprobe 1.9.0 → 1.11.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.
@@ -0,0 +1,339 @@
1
+ /**
2
+ * cliprobe as a library: run the checks from a test suite or a script and get the
3
+ * report as data.
4
+ *
5
+ * import { failing, probe } from 'cliprobe';
6
+ *
7
+ * const report = await probe('node ./dist/cli.js', { probes: ['serve --port 0'] });
8
+ * expect(failing(report)).toEqual([]);
9
+ *
10
+ * The report is exactly what `cliprobe --format json` prints, described by
11
+ * `cliprobe/schema.json`. Within 1.x the functions, their options and the
12
+ * report's fields are only added to.
13
+ */
14
+ /** `info` is the only verdict of an info check: a measurement or observation, never a failure. */
15
+ type Verdict = "pass" | "fail" | "warn" | "skip" | "error" | "info";
16
+ /** A signal's name, such as "SIGINT": a plain string, so the published types need no @types/node. */
17
+ type SignalName = string;
18
+ /** One check's outcome for one invocation, with the evidence that led to it. */
19
+ interface Result {
20
+ check: string;
21
+ invocation: string[];
22
+ verdict: Verdict;
23
+ reason: string;
24
+ evidence?: string;
25
+ /**
26
+ * Set when the config file accepts this failure or warning: why. The verdict
27
+ * stays as it is, but the result no longer counts toward the exit code.
28
+ */
29
+ accepted?: {
30
+ reason: string;
31
+ };
32
+ }
33
+ /** The name of every check, in the order they run and are reported. */
34
+ export declare const CHECK_NAMES: readonly ["closed-pipe", "write-error", "slow-pipe", "color", "pipe-escapes", "stdin", "ctrl-c", "sigterm", "restore", "control-chars", "startup", "baseline"];
35
+ type CheckName = (typeof CHECK_NAMES)[number];
36
+ /** The file `cliprobe` reads from the current directory when no command is given. */
37
+ export declare const CONFIG_FILE = "cliprobe.config.json";
38
+ /** Why a run could not start; `ProbeError.code`. */
39
+ type ProbeErrorCode = "USAGE" | "COMMAND" | "PLATFORM";
40
+ /**
41
+ * A run that could not start, which the CLI reports with exit 2: a mistake in the
42
+ * options or the config file (`USAGE`), a command that can't be run (`COMMAND`),
43
+ * or a platform cliprobe doesn't support (`PLATFORM`). A program that runs and
44
+ * fails a check is not an error: that is a result in the report.
45
+ */
46
+ export declare class ProbeError extends Error {
47
+ override readonly name: string;
48
+ readonly code: ProbeErrorCode;
49
+ constructor(code: ProbeErrorCode, message: string);
50
+ }
51
+ /** The names --format takes. */
52
+ type Format = "human" | "json" | "markdown" | "junit" | "github";
53
+ /** The format names, in the order --help lists them. */
54
+ export declare const FORMAT_NAMES: readonly Format[];
55
+ interface BaselineResult extends Result {
56
+ exitCode: number | null;
57
+ stdoutLines: number;
58
+ stderrLines: number;
59
+ }
60
+ interface ClosedPipeResult extends Result {
61
+ baseline: {
62
+ exitCode: number | null;
63
+ signal: SignalName | null;
64
+ stdoutBytes: number;
65
+ };
66
+ closed: {
67
+ exitCode: number | null;
68
+ signal: SignalName | null;
69
+ timedOut: boolean;
70
+ stderr: string;
71
+ };
72
+ }
73
+ interface ColorResult extends Result {
74
+ pipe: {
75
+ exitCode: number | null;
76
+ stdoutStyled: boolean;
77
+ stderrStyled: boolean;
78
+ };
79
+ tty: {
80
+ exitCode: number | null;
81
+ timedOut: boolean;
82
+ styled: boolean;
83
+ } | null;
84
+ noColor: {
85
+ exitCode: number | null;
86
+ timedOut: boolean;
87
+ styled: boolean;
88
+ } | null;
89
+ }
90
+ interface ControlCharsResult extends Result {
91
+ /** Kinds of hostile names that reached the terminal unescaped. */
92
+ terminalRaw: string[];
93
+ /** Kinds that reached a pipe unescaped. Normal for ls and find, so not judged. */
94
+ pipeRaw: string[];
95
+ }
96
+ interface CtrlCResult extends Result {
97
+ /** Milliseconds after start that SIGINT was sent; null if the program had already exited. */
98
+ sentAfterMs: number | null;
99
+ /** Milliseconds from SIGINT to exit; null if it was not sent. */
100
+ exitedAfterMs: number | null;
101
+ exitCode: number | null;
102
+ signal: SignalName | null;
103
+ /** Command lines of the processes it left running after it exited, in its group or started by it. */
104
+ leftRunning: string[];
105
+ /** The end of what it printed to stderr after SIGINT. */
106
+ stderrAfter: string;
107
+ }
108
+ type ControlKind = "cursor" | "erase" | "mode" | "hyperlink" | "title" | "osc" | "redraw" | "escape" | "reset" | "string" | "c1";
109
+ interface OpenMode {
110
+ label: string;
111
+ /** The sequence that switched it on, as printed. */
112
+ sequence: string;
113
+ /** 1-based line of that sequence. */
114
+ line: number;
115
+ }
116
+ interface PipeEscapesResult extends Result {
117
+ /** Kinds of control code found on each stream, without repeats. */
118
+ stdoutKinds: ControlKind[];
119
+ stderrKinds: ControlKind[];
120
+ }
121
+ interface RestoreResult extends Result {
122
+ /** Whether Ctrl-C was sent; false when the program exited first. */
123
+ interrupted: boolean;
124
+ /** The modes it left switched on, with the sequence that switched each on. */
125
+ openModes: OpenMode[];
126
+ /**
127
+ * The terminal settings (stty) it switched off and left off, such as icanon and echo
128
+ * for raw mode; null when they couldn't be read. Added in 1.6.
129
+ */
130
+ settingsOff: string[] | null;
131
+ }
132
+ interface SigtermResult extends Result {
133
+ /** Milliseconds after start that SIGTERM was sent; null if the program had already exited. */
134
+ sentAfterMs: number | null;
135
+ /** Milliseconds from SIGTERM to exit; null if it was not sent or the program ignored it. */
136
+ exitedAfterMs: number | null;
137
+ exitCode: number | null;
138
+ signal: SignalName | null;
139
+ /** Command lines of the processes it left running after it exited, in its group or started by it. */
140
+ leftRunning: string[];
141
+ /** The end of what it printed to stderr after SIGTERM. */
142
+ stderrAfter: string;
143
+ }
144
+ interface StartupResult extends Result {
145
+ /** Wall time of each timed run, in milliseconds. */
146
+ runsMs: number[];
147
+ medianMs: number | null;
148
+ }
149
+ interface StdinResult extends Result {
150
+ closedMs: number | null;
151
+ waitedForStdin: boolean;
152
+ /** Milliseconds from closing stdin to the program finishing, when that was measured. */
153
+ finishedAfterCloseMs: number | null;
154
+ }
155
+ interface SlowPipeResult extends Result {
156
+ /** The run with stdout in a file, where no write waits: all of the output. */
157
+ baseline: {
158
+ exitCode: number | null;
159
+ signal: SignalName | null;
160
+ stdoutBytes: number;
161
+ };
162
+ /** The run with stdout in a pipe that was read late; null when it didn't run. */
163
+ slow: {
164
+ exitCode: number | null;
165
+ signal: SignalName | null;
166
+ timedOut: boolean;
167
+ stdoutBytes: number;
168
+ } | null;
169
+ }
170
+ interface WriteErrorResult extends Result {
171
+ baseline: {
172
+ exitCode: number | null;
173
+ signal: SignalName | null;
174
+ stdoutBytes: number;
175
+ };
176
+ /** The run with stdout on /dev/full; null when it didn't run. */
177
+ full: {
178
+ exitCode: number | null;
179
+ signal: SignalName | null;
180
+ timedOut: boolean;
181
+ stderr: string;
182
+ } | null;
183
+ }
184
+ /**
185
+ * Version of the report's shape, described by `schema.json` in the package.
186
+ * It changes only with a major release of cliprobe.
187
+ */
188
+ declare const SCHEMA_VERSION = 1;
189
+ /** A check's own measurements: its result without the fields every result shares. */
190
+ type Details<T extends Result> = Omit<T, keyof Result>;
191
+ /** What `details` holds for each check, as `schema.json` describes it. */
192
+ interface DetailsByCheck {
193
+ "closed-pipe": Details<ClosedPipeResult>;
194
+ "write-error": Details<WriteErrorResult>;
195
+ "slow-pipe": Details<SlowPipeResult>;
196
+ color: Details<ColorResult>;
197
+ "pipe-escapes": Details<PipeEscapesResult>;
198
+ stdin: Details<StdinResult>;
199
+ "ctrl-c": Details<CtrlCResult>;
200
+ sigterm: Details<SigtermResult>;
201
+ restore: Details<RestoreResult>;
202
+ "control-chars": Details<ControlCharsResult>;
203
+ startup: Details<StartupResult>;
204
+ baseline: Details<BaselineResult>;
205
+ }
206
+ /** One check's outcome for one invocation. */
207
+ interface ResultOf<C extends CheckName> {
208
+ check: C;
209
+ /** The command and the arguments that ran. */
210
+ invocation: string[];
211
+ verdict: Verdict;
212
+ /** A sentence for a person; its wording may change, so match on `check` and `verdict`. */
213
+ reason: string;
214
+ /** The line that led to the verdict, when there is one to quote. */
215
+ evidence?: string;
216
+ /** Set when `accept` covers this failure or warning: it no longer fails the run. */
217
+ accepted?: {
218
+ reason: string;
219
+ };
220
+ /** The check's own measurements. */
221
+ details: DetailsByCheck[C];
222
+ }
223
+ /** A result of any check; `result.check` narrows `result.details` to that check's. */
224
+ type ReportResult = { [C in CheckName]: ResultOf<C>; }[CheckName];
225
+ /**
226
+ * One run of cliprobe: what `--format json` prints and what `probe()` returns.
227
+ * Within 1.x, fields are only added.
228
+ */
229
+ interface JsonReport {
230
+ tool: "cliprobe";
231
+ schemaVersion: typeof SCHEMA_VERSION;
232
+ /** The cliprobe version that made the report. */
233
+ version: string;
234
+ /** The command under test, without its arguments. */
235
+ command: string;
236
+ /** The checks that ran, in order. */
237
+ checks: CheckName[];
238
+ /** Whether warnings fail the run too. */
239
+ strict: boolean;
240
+ /** How many results have each verdict. */
241
+ summary: Record<Verdict, number>;
242
+ results: ReportResult[];
243
+ }
244
+ /** A failure or warning the project knows about and lets pass. */
245
+ export interface Accept {
246
+ check: CheckName;
247
+ /** The probe's arguments, as written in `probes`; every probe when left out. */
248
+ probe?: string | readonly string[] | undefined;
249
+ /** Why it is accepted; shown in every report. */
250
+ reason: string;
251
+ }
252
+ /**
253
+ * How to probe a program: the keys of `cliprobe.config.json`, without `command`.
254
+ * Arguments are a string, split like a shell command line (quotes and
255
+ * backslashes, no variables or wildcards), or an array, taken as it is.
256
+ */
257
+ export interface ProbeOptions {
258
+ /** More invocations, each the arguments after the program, as `--probe`. */
259
+ probes?: readonly (string | readonly string[])[] | undefined;
260
+ /** Probe the program alone instead of `--version` and `--help`, as `--bare`. */
261
+ bare?: boolean | undefined;
262
+ /** `false` leaves out `--version` and `--help`, so only `probes` run. Default `true`. */
263
+ defaultProbes?: boolean | undefined;
264
+ /** Run only these checks, as `--check`; the info checks run only when named. */
265
+ checks?: readonly CheckName[] | undefined;
266
+ /** Leave these checks out, as `--skip`. */
267
+ skip?: readonly CheckName[] | undefined;
268
+ /** Warnings fail too, as `--strict`: it changes `exitCode()` and `failing()`. */
269
+ strict?: boolean | undefined;
270
+ /** Kill a probe after this many milliseconds. Default 15000. */
271
+ timeout?: number | undefined;
272
+ /** Known failures and warnings: each stays in the report but no longer fails the run. */
273
+ accept?: readonly Accept[] | undefined;
274
+ }
275
+ /** A config file's content: the program, then the options of `probe()`, all filled in. */
276
+ export interface ProbeConfig {
277
+ /** The program: the command, then any arguments that belong to it. */
278
+ command: string[];
279
+ probes: string[][];
280
+ bare: boolean;
281
+ defaultProbes: boolean;
282
+ checks: CheckName[];
283
+ skip: CheckName[];
284
+ strict: boolean;
285
+ timeout: number | undefined;
286
+ accept: {
287
+ check: CheckName;
288
+ probe?: string[];
289
+ reason: string;
290
+ }[];
291
+ }
292
+ /**
293
+ * Runs cliprobe's checks on a program and returns the report.
294
+ *
295
+ * `command` is the whole program, as a config file's `command`: with
296
+ * `'node ./dist/cli.js'`, the probes are `--version`, `--help` and each of
297
+ * `options.probes`, all after the script.
298
+ *
299
+ * A check that fails is a result, never an exception. It rejects with a
300
+ * `ProbeError` only when the run can't start: a mistake in the options
301
+ * (`code: 'USAGE'`), a command that can't be run (`'COMMAND'`), or Windows
302
+ * (`'PLATFORM'`).
303
+ *
304
+ * The program runs in the current directory, without a shell, with a temporary
305
+ * HOME and a minimal environment. Only probe programs you trust.
306
+ */
307
+ export declare function probe(command: string | readonly string[], options?: ProbeOptions): Promise<JsonReport>;
308
+ /**
309
+ * Reads a config file, `cliprobe.config.json` in the current directory unless
310
+ * `path` says otherwise, so a test can probe exactly what `npx cliprobe` does:
311
+ *
312
+ * const { command, ...options } = readConfig();
313
+ * const report = await probe(command, options);
314
+ *
315
+ * It throws a `ProbeError` with `code: 'USAGE'` for a file that is missing or has a mistake.
316
+ */
317
+ export declare function readConfig(path?: string): ProbeConfig;
318
+ /**
319
+ * The report as text in one of the CLI's formats: `human` (the default), `json`,
320
+ * `markdown`, `junit` or `github`. Text from the probed program is escaped as in
321
+ * the CLI, so the result is safe to print. `color` paints the verdicts of the
322
+ * human format; it is off unless asked for.
323
+ */
324
+ export declare function formatReport(report: JsonReport, format?: Format, options?: {
325
+ color?: boolean | undefined;
326
+ }): string;
327
+ /**
328
+ * The results that fail the run: every `fail`, and with `strict` every `warn`,
329
+ * except those `accept` covers. Empty when the CLI would exit 0 or 2.
330
+ */
331
+ export declare function failing(report: JsonReport): ReportResult[];
332
+ /**
333
+ * The exit code the CLI gives this report: 0 no failures, 1 a check failed (or
334
+ * warned, with `strict`), 2 nothing could be judged because the command could not run.
335
+ */
336
+ export declare function exitCode(report: JsonReport): 0 | 1 | 2;
337
+ /** The cliprobe version, as in the report's `version`. */
338
+ export declare const version: string;
339
+ export type { CheckName, DetailsByCheck, Format, ProbeErrorCode, JsonReport as Report, ReportResult, ResultOf, Verdict };
package/dist/index.js ADDED
@@ -0,0 +1,108 @@
1
+ import { O as runInterruptCleanups, _ as CONFIG_FILE, a as toJsonReport, b as ProbeError, c as failsRun, g as CHECK_NAMES, h as VERSION, i as fromJsonReport, l as prepare, m as planFromConfig, n as FORMAT_NAMES, o as execute, r as isFormat, s as exitCodeFor, t as FORMATS, v as loadConfig, x as UsageError, y as validateConfig } from "./report-6mELXFtT.js";
2
+ // src/index.ts
3
+ /**
4
+ * cliprobe as a library: run the checks from a test suite or a script and get the
5
+ * report as data.
6
+ *
7
+ * import { failing, probe } from 'cliprobe';
8
+ *
9
+ * const report = await probe('node ./dist/cli.js', { probes: ['serve --port 0'] });
10
+ * expect(failing(report)).toEqual([]);
11
+ *
12
+ * The report is exactly what `cliprobe --format json` prints, described by
13
+ * `cliprobe/schema.json`. Within 1.x the functions, their options and the
14
+ * report's fields are only added to.
15
+ */
16
+ let cleansUpOnExit = false;
17
+ /**
18
+ * A probe runs in its own process group, so nothing stops it when the process
19
+ * that called probe() ends early (a test runner told to quit). On exit, kill
20
+ * whatever is still running and remove the temporary directories.
21
+ */
22
+ function cleanUpOnExit() {
23
+ if (cleansUpOnExit) return;
24
+ cleansUpOnExit = true;
25
+ process.once("exit", runInterruptCleanups);
26
+ }
27
+ /**
28
+ * Runs cliprobe's checks on a program and returns the report.
29
+ *
30
+ * `command` is the whole program, as a config file's `command`: with
31
+ * `'node ./dist/cli.js'`, the probes are `--version`, `--help` and each of
32
+ * `options.probes`, all after the script.
33
+ *
34
+ * A check that fails is a result, never an exception. It rejects with a
35
+ * `ProbeError` only when the run can't start: a mistake in the options
36
+ * (`code: 'USAGE'`), a command that can't be run (`'COMMAND'`), or Windows
37
+ * (`'PLATFORM'`).
38
+ *
39
+ * The program runs in the current directory, without a shell, with a temporary
40
+ * HOME and a minimal environment. Only probe programs you trust.
41
+ */
42
+ async function probe(command, options = {}) {
43
+ const plan = planFromConfig(validateConfig({
44
+ ...options,
45
+ command
46
+ }, "probe()"), "probe()");
47
+ const checks = prepare(plan);
48
+ cleanUpOnExit();
49
+ const { report } = await execute(plan, checks);
50
+ return toJsonReport(report);
51
+ }
52
+ const isCheckName = (name) => CHECK_NAMES.includes(name);
53
+ /**
54
+ * Reads a config file, `cliprobe.config.json` in the current directory unless
55
+ * `path` says otherwise, so a test can probe exactly what `npx cliprobe` does:
56
+ *
57
+ * const { command, ...options } = readConfig();
58
+ * const report = await probe(command, options);
59
+ *
60
+ * It throws a `ProbeError` with `code: 'USAGE'` for a file that is missing or has a mistake.
61
+ */
62
+ function readConfig(path = CONFIG_FILE) {
63
+ const config = loadConfig(path);
64
+ const names = (key, list) => {
65
+ const unknown = list.find((name) => !isCheckName(name));
66
+ if (unknown !== void 0) throw new UsageError(`${path}: "${key}" names an unknown check "${unknown}" (available: ${CHECK_NAMES.join(", ")})`);
67
+ return list.filter(isCheckName);
68
+ };
69
+ return {
70
+ ...config,
71
+ checks: names("checks", config.checks),
72
+ skip: names("skip", config.skip),
73
+ accept: config.accept.map((accept, i) => {
74
+ const [check] = names(`accept[${i}].check`, [accept.check]);
75
+ return {
76
+ ...accept,
77
+ check: check ?? "closed-pipe"
78
+ };
79
+ })
80
+ };
81
+ }
82
+ /**
83
+ * The report as text in one of the CLI's formats: `human` (the default), `json`,
84
+ * `markdown`, `junit` or `github`. Text from the probed program is escaped as in
85
+ * the CLI, so the result is safe to print. `color` paints the verdicts of the
86
+ * human format; it is off unless asked for.
87
+ */
88
+ function formatReport(report, format = "human", options = {}) {
89
+ if (!isFormat(format)) throw new UsageError(`formatReport(): unknown format "${String(format)}" (one of ${FORMAT_NAMES.join(", ")})`);
90
+ return FORMATS[format](fromJsonReport(report), { color: options.color ?? false });
91
+ }
92
+ /**
93
+ * The results that fail the run: every `fail`, and with `strict` every `warn`,
94
+ * except those `accept` covers. Empty when the CLI would exit 0 or 2.
95
+ */
96
+ function failing(report) {
97
+ return report.results.filter((r) => failsRun(r, report.strict));
98
+ }
99
+ /**
100
+ * The exit code the CLI gives this report: 0 no failures, 1 a check failed (or
101
+ * warned, with `strict`), 2 nothing could be judged because the command could not run.
102
+ */
103
+ function exitCode(report) {
104
+ return exitCodeFor(report.results, report.strict);
105
+ }
106
+ /** The cliprobe version, as in the report's `version`. */
107
+ const version = VERSION;
108
+ export { CHECK_NAMES, CONFIG_FILE, FORMAT_NAMES, ProbeError, exitCode, failing, formatReport, probe, readConfig, version };