@cnc-tools/conform 0.0.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +169 -1
- package/dist/executable.d.ts +40 -0
- package/dist/executable.js +109 -0
- package/dist/harness.d.ts +80 -0
- package/dist/harness.js +208 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +5 -0
- package/dist/process.d.ts +112 -0
- package/dist/process.js +324 -0
- package/package.json +46 -4
package/README.md
CHANGED
|
@@ -1,3 +1,171 @@
|
|
|
1
1
|
# @cnc-tools/conform
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@cnc-tools/conform` runs live differential conformance suites over vanilla Vitest `it("...", async (ctx) => ...)` tests, with no checked-in recordings and no custom test entry point.
|
|
4
|
+
|
|
5
|
+
It has zero runtime dependencies (Node.js `>=22.19.0` builtins only) and declares `vitest` (`^4.1.10`) as a type-only peer dependency, so callers can import `@cnc-tools/conform` inside Vitest configs or outside a Vitest run without loading `vitest` at runtime.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add -D @cnc-tools/conform vitest
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Quick start
|
|
14
|
+
|
|
15
|
+
Define a harness with a reference executable, a session factory that creates an isolated world for each executable, and typed operations:
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { rm } from "node:fs/promises";
|
|
19
|
+
import { fileURLToPath } from "node:url";
|
|
20
|
+
import {
|
|
21
|
+
cliJsonContract,
|
|
22
|
+
conformOp,
|
|
23
|
+
createTempRoot,
|
|
24
|
+
defineConformHarness,
|
|
25
|
+
ManagedProcessPool,
|
|
26
|
+
pinnedEnv,
|
|
27
|
+
type ConformExecutable,
|
|
28
|
+
type ConformSession,
|
|
29
|
+
} from "@cnc-tools/conform";
|
|
30
|
+
|
|
31
|
+
class CliSession implements ConformSession {
|
|
32
|
+
readonly #pool = new ManagedProcessPool();
|
|
33
|
+
readonly #root: string;
|
|
34
|
+
readonly #executable: ConformExecutable;
|
|
35
|
+
|
|
36
|
+
private constructor(root: string, executable: ConformExecutable) {
|
|
37
|
+
this.#root = root;
|
|
38
|
+
this.#executable = executable;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
static async start(executable: ConformExecutable): Promise<CliSession> {
|
|
42
|
+
const root = await createTempRoot("conform-cli-");
|
|
43
|
+
return new CliSession(root, executable);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
run(argv: readonly string[]) {
|
|
47
|
+
return this.#pool.exec({
|
|
48
|
+
executable: this.#executable,
|
|
49
|
+
argv,
|
|
50
|
+
cwd: this.#root,
|
|
51
|
+
env: pinnedEnv({ home: this.#root }),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async close(): Promise<void> {
|
|
56
|
+
await this.#pool.close();
|
|
57
|
+
await rm(this.#root, { recursive: true, force: true });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export const openCli = defineConformHarness({
|
|
62
|
+
// Sessions run in their own temporary directories, so script arguments must be absolute paths.
|
|
63
|
+
reference: {
|
|
64
|
+
file: process.execPath,
|
|
65
|
+
args: [fileURLToPath(new URL("../dist/bin/my-cli.js", import.meta.url))],
|
|
66
|
+
},
|
|
67
|
+
start: (executable) => CliSession.start(executable),
|
|
68
|
+
ops: {
|
|
69
|
+
run: conformOp({
|
|
70
|
+
run: (session: CliSession, argv: readonly string[]) => session.run(argv),
|
|
71
|
+
contract: (result) =>
|
|
72
|
+
cliJsonContract(result, {
|
|
73
|
+
maskFields: { timestamp: "<timestamp>" },
|
|
74
|
+
}),
|
|
75
|
+
}),
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Write vanilla Vitest tests that pass `ctx` to `openCli(ctx)`:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
import { expect, it } from "vitest";
|
|
84
|
+
import { openCli } from "./harness.ts";
|
|
85
|
+
|
|
86
|
+
it("prints status as JSON", async (ctx) => {
|
|
87
|
+
const cli = openCli(ctx);
|
|
88
|
+
const result = await cli.run(["status", "--json"]);
|
|
89
|
+
expect(result.exit).toBe(0);
|
|
90
|
+
expect(result.stdoutJson).toMatchObject({ ok: true });
|
|
91
|
+
});
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Running reference-only vs differential mode
|
|
95
|
+
|
|
96
|
+
- **Reference-only mode (`CONFORM_BIN` unset or empty):** `open(ctx)` starts one session against `reference` lazily on the first op call, runs each op once, and returns its result directly to the test's `expect(...)` assertions.
|
|
97
|
+
- **Differential mode (`CONFORM_BIN` set):** `open(ctx)` starts two isolated sessions (`reference` and `target`) lazily on the first op call, runs every op concurrently on both, compares `contract(target)` against `contract(reference)` with `ctx.expect` on ops that define `contract`, and returns `target`'s result so the test body's explicit `expect(...)` assertions verify the target executable directly.
|
|
98
|
+
|
|
99
|
+
`CONFORM_BIN` is parsed with shell-free POSIX word splitting (`splitCommandLine`), so you can pass either a binary path or a command with leading arguments:
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
# Reference-only run
|
|
103
|
+
vitest run --project conform
|
|
104
|
+
|
|
105
|
+
# Differential run against a compiled binary (for example, a Go port)
|
|
106
|
+
CONFORM_BIN=./bin/my-cli-go vitest run --project conform
|
|
107
|
+
|
|
108
|
+
# Differential run with leading arguments (pass absolute script paths when sessions run in temporary directories)
|
|
109
|
+
CONFORM_BIN="node /abs/path/to/alt/cli.js --strict" vitest run --project conform
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Only a relative program path containing `/` resolves against `cwd` (default `process.cwd()`). Bare program names resolve through `PATH`, and leading arguments pass through unchanged. Shell operators and expansions (`|`, `&`, `;`, `<`, `>`, `$`, backticks, globs, and `~`) outside quotes are rejected with a `TypeError`.
|
|
113
|
+
|
|
114
|
+
## Vitest project guidance
|
|
115
|
+
|
|
116
|
+
Conformance tests spawn real processes and isolated temporary worlds, so keep them in a dedicated Vitest project (for example, `conform`) that runs on demand via `--project conform` (or in CI) rather than during bare unit-test runs:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
import { availableParallelism } from "node:os";
|
|
120
|
+
import { defineConfig } from "vitest/config";
|
|
121
|
+
|
|
122
|
+
function namedProjects(argv: readonly string[]): string[] {
|
|
123
|
+
return argv.flatMap((arg, index) => {
|
|
124
|
+
if (arg.startsWith("--project=")) return [arg.slice("--project=".length)];
|
|
125
|
+
const next = argv[index + 1];
|
|
126
|
+
return arg === "--project" && next !== undefined ? [next] : [];
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const selected = namedProjects(process.argv);
|
|
131
|
+
const runConform = Boolean(process.env["CI"]) || selected.includes("conform");
|
|
132
|
+
const conformOnly = selected.length > 0 && selected.every((name) => name === "conform");
|
|
133
|
+
|
|
134
|
+
export default defineConfig({
|
|
135
|
+
test: {
|
|
136
|
+
// Vitest 4 reads `sequence.concurrent` from the root config rather than a project config,
|
|
137
|
+
// so enable it at the root only for conform-only runs to avoid making other projects concurrent.
|
|
138
|
+
...(conformOnly ? { sequence: { concurrent: true } } : {}),
|
|
139
|
+
projects: [
|
|
140
|
+
...(runConform
|
|
141
|
+
? [
|
|
142
|
+
{
|
|
143
|
+
test: {
|
|
144
|
+
name: "conform",
|
|
145
|
+
include: ["test/conform/**/*.test.ts"],
|
|
146
|
+
environment: "node",
|
|
147
|
+
maxWorkers: availableParallelism(),
|
|
148
|
+
maxConcurrency: 2,
|
|
149
|
+
testTimeout: 60_000,
|
|
150
|
+
hookTimeout: 60_000,
|
|
151
|
+
sequence: { concurrent: true, groupOrder: 1 },
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
]
|
|
155
|
+
: []),
|
|
156
|
+
],
|
|
157
|
+
},
|
|
158
|
+
});
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Because each test opens its own isolated session(s) via `open(ctx)`, running tests concurrently within a file (`sequence.concurrent: true` with a bounded `maxConcurrency`) speeds up suites safely without cross-test interference.
|
|
162
|
+
|
|
163
|
+
## Modules
|
|
164
|
+
|
|
165
|
+
- `src/executable.ts`: `CONFORM_BIN` resolution (`CONFORM_BIN_VARIABLE`, `conformTargetExecutable`, `resolveConformExecutable`) and shell-free POSIX word splitting (`splitCommandLine`, `InvalidCommandLine`).
|
|
166
|
+
- `src/process.ts`: detached process-group CLI execution (`execCli`, `ManagedProcessPool`, `ProcessStopError`, `parseJsonStream`, `jsonObject`), deterministic environments (`pinnedEnv`), canonical temp roots (`createTempRoot`), and `SIGTERM` → grace → `SIGKILL` process-group teardown (including Linux `/proc` zombie filtering via `groupRunning` and `processRunning`).
|
|
167
|
+
- `src/harness.ts`: `defineConformHarness({ reference, start, ops })`, `conformOp(...)`, `maskJsonFields(...)`, and `cliJsonContract(...)` integrating with Vitest's `TestContext` (`ctx.expect`, `ctx.onTestFinished`, and `ctx.signal`).
|
|
168
|
+
|
|
169
|
+
## Teardown and timeouts
|
|
170
|
+
|
|
171
|
+
`open(ctx)` registers cleanup on both `ctx.onTestFinished` and `ctx.signal`. On normal pass or failure, `ctx.onTestFinished` closes every started session. On a Vitest timeout or cancellation, `ctx.signal` triggers immediate teardown (killing detached child process groups through `ManagedProcessPool`) while `ctx.onTestFinished` awaits the same shutdown promise so cleanup finishes before the worker exits.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** The environment variable that names the target executable for differential conformance runs. */
|
|
2
|
+
export declare const CONFORM_BIN_VARIABLE = "CONFORM_BIN";
|
|
3
|
+
/** A command line that cannot be split into shell-free POSIX words, or that names no program. */
|
|
4
|
+
export declare class InvalidCommandLine extends Error {
|
|
5
|
+
readonly name = "InvalidCommandLine";
|
|
6
|
+
}
|
|
7
|
+
/** A program and the fixed leading arguments passed before each command's own arguments. */
|
|
8
|
+
export interface ConformExecutable {
|
|
9
|
+
readonly file: string;
|
|
10
|
+
readonly args: readonly string[];
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Splits `command` into words as a POSIX shell does, without running a shell: whitespace separates words; single
|
|
14
|
+
* quotes keep everything up to the next single quote; double quotes keep everything up to the next unescaped double
|
|
15
|
+
* quote, where a backslash escapes `"`, `\`, `$`, and backtick; a backslash outside quotes escapes the next
|
|
16
|
+
* character. Shell operators or expansions outside quotes (`|`, `&`, `;`, `<`, `>`, `(`, `)`, `$`, backtick,
|
|
17
|
+
* `*`, `?`, `[`, `~`, `#`), trailing backslashes, and unclosed quotes throw `InvalidCommandLine`.
|
|
18
|
+
*/
|
|
19
|
+
export declare function splitCommandLine(command: string): readonly string[];
|
|
20
|
+
/**
|
|
21
|
+
* Resolves `commandLine` into a `ConformExecutable`: its first word is the program, and the remaining words come
|
|
22
|
+
* before each invocation's own arguments. A relative program containing `/` resolves against `base`; a bare program
|
|
23
|
+
* name stays as-is for `PATH` lookup. Throws `InvalidCommandLine` if splitting fails or no program is named.
|
|
24
|
+
*/
|
|
25
|
+
export declare function resolveConformExecutable(commandLine: string, base: string): ConformExecutable;
|
|
26
|
+
/** Options for reading the target executable from the environment. */
|
|
27
|
+
export interface ConformTargetOptions {
|
|
28
|
+
/** Environment to inspect; default `process.env`. */
|
|
29
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
30
|
+
/** Base directory for resolving relative paths containing `/`; default `process.cwd()`. */
|
|
31
|
+
readonly cwd?: string;
|
|
32
|
+
/** Environment variable name; default `CONFORM_BIN`. */
|
|
33
|
+
readonly variable?: string;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Reads the target executable from `variable` (default `CONFORM_BIN`) in `env`. Returns `undefined` when the
|
|
37
|
+
* variable is unset or empty (reference-only mode). Throws a `TypeError` naming the variable when the value cannot be
|
|
38
|
+
* split or names no program.
|
|
39
|
+
*/
|
|
40
|
+
export declare function conformTargetExecutable(options?: ConformTargetOptions): ConformExecutable | undefined;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// Command-line splitting and `CONFORM_BIN` resolution without a shell. Pure except for optional `process.cwd()` /
|
|
2
|
+
// `process.env` defaults. Loads only Node builtins, never vitest.
|
|
3
|
+
import { isAbsolute, resolve } from "node:path";
|
|
4
|
+
/** The environment variable that names the target executable for differential conformance runs. */
|
|
5
|
+
export const CONFORM_BIN_VARIABLE = "CONFORM_BIN";
|
|
6
|
+
/** A command line that cannot be split into shell-free POSIX words, or that names no program. */
|
|
7
|
+
export class InvalidCommandLine extends Error {
|
|
8
|
+
name = "InvalidCommandLine";
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Splits `command` into words as a POSIX shell does, without running a shell: whitespace separates words; single
|
|
12
|
+
* quotes keep everything up to the next single quote; double quotes keep everything up to the next unescaped double
|
|
13
|
+
* quote, where a backslash escapes `"`, `\`, `$`, and backtick; a backslash outside quotes escapes the next
|
|
14
|
+
* character. Shell operators or expansions outside quotes (`|`, `&`, `;`, `<`, `>`, `(`, `)`, `$`, backtick,
|
|
15
|
+
* `*`, `?`, `[`, `~`, `#`), trailing backslashes, and unclosed quotes throw `InvalidCommandLine`.
|
|
16
|
+
*/
|
|
17
|
+
export function splitCommandLine(command) {
|
|
18
|
+
const words = [];
|
|
19
|
+
let word;
|
|
20
|
+
let index = 0;
|
|
21
|
+
const add = (text) => {
|
|
22
|
+
word = (word ?? "") + text;
|
|
23
|
+
};
|
|
24
|
+
while (index < command.length) {
|
|
25
|
+
const char = command[index] ?? "";
|
|
26
|
+
if (/\s/u.test(char)) {
|
|
27
|
+
if (word !== undefined)
|
|
28
|
+
words.push(word);
|
|
29
|
+
word = undefined;
|
|
30
|
+
index += 1;
|
|
31
|
+
}
|
|
32
|
+
else if (char === "'") {
|
|
33
|
+
const end = command.indexOf("'", index + 1);
|
|
34
|
+
if (end === -1)
|
|
35
|
+
throw new InvalidCommandLine(`${JSON.stringify(command)} has an unclosed single quote`);
|
|
36
|
+
add(command.slice(index + 1, end));
|
|
37
|
+
index = end + 1;
|
|
38
|
+
}
|
|
39
|
+
else if (char === '"') {
|
|
40
|
+
let text = "";
|
|
41
|
+
index += 1;
|
|
42
|
+
while (command[index] !== '"') {
|
|
43
|
+
if (index >= command.length) {
|
|
44
|
+
throw new InvalidCommandLine(`${JSON.stringify(command)} has an unclosed double quote`);
|
|
45
|
+
}
|
|
46
|
+
const next = command[index + 1] ?? "";
|
|
47
|
+
if (command[index] === "\\" && ['"', "\\", "$", "`"].includes(next)) {
|
|
48
|
+
text += next;
|
|
49
|
+
index += 2;
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
text += command[index] ?? "";
|
|
53
|
+
index += 1;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
add(text);
|
|
57
|
+
index += 1;
|
|
58
|
+
}
|
|
59
|
+
else if (char === "\\") {
|
|
60
|
+
if (index + 1 >= command.length) {
|
|
61
|
+
throw new InvalidCommandLine(`${JSON.stringify(command)} ends in a backslash`);
|
|
62
|
+
}
|
|
63
|
+
add(command[index + 1] ?? "");
|
|
64
|
+
index += 2;
|
|
65
|
+
}
|
|
66
|
+
else if ("|&;<>()$`*?[~#".includes(char)) {
|
|
67
|
+
throw new InvalidCommandLine(`${JSON.stringify(command)} has ${JSON.stringify(char)} outside quotes, and the harness runs no shell`);
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
add(char);
|
|
71
|
+
index += 1;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (word !== undefined)
|
|
75
|
+
words.push(word);
|
|
76
|
+
return words;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Resolves `commandLine` into a `ConformExecutable`: its first word is the program, and the remaining words come
|
|
80
|
+
* before each invocation's own arguments. A relative program containing `/` resolves against `base`; a bare program
|
|
81
|
+
* name stays as-is for `PATH` lookup. Throws `InvalidCommandLine` if splitting fails or no program is named.
|
|
82
|
+
*/
|
|
83
|
+
export function resolveConformExecutable(commandLine, base) {
|
|
84
|
+
const [program, ...args] = splitCommandLine(commandLine);
|
|
85
|
+
if (program === undefined)
|
|
86
|
+
throw new InvalidCommandLine(`${JSON.stringify(commandLine)} names no program`);
|
|
87
|
+
const file = program.includes("/") && !isAbsolute(program) ? resolve(base, program) : program;
|
|
88
|
+
return { file, args };
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Reads the target executable from `variable` (default `CONFORM_BIN`) in `env`. Returns `undefined` when the
|
|
92
|
+
* variable is unset or empty (reference-only mode). Throws a `TypeError` naming the variable when the value cannot be
|
|
93
|
+
* split or names no program.
|
|
94
|
+
*/
|
|
95
|
+
export function conformTargetExecutable(options = {}) {
|
|
96
|
+
const env = options.env ?? process.env;
|
|
97
|
+
const variable = options.variable ?? CONFORM_BIN_VARIABLE;
|
|
98
|
+
const value = env[variable];
|
|
99
|
+
if (value === undefined || value === "")
|
|
100
|
+
return undefined;
|
|
101
|
+
try {
|
|
102
|
+
return resolveConformExecutable(value, options.cwd ?? process.cwd());
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
if (!(error instanceof InvalidCommandLine))
|
|
106
|
+
throw error;
|
|
107
|
+
throw new TypeError(`conform: ${variable} ${error.message}. Write it as a POSIX shell would split it into words, with no operators or expansions.`, { cause: error });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import type { TestContext } from "vitest";
|
|
2
|
+
import { type ConformExecutable } from "./executable.ts";
|
|
3
|
+
import type { ExecCliResult } from "./process.ts";
|
|
4
|
+
/** One isolated session managed by a conform harness. */
|
|
5
|
+
export interface ConformSession {
|
|
6
|
+
close(): void | Promise<void>;
|
|
7
|
+
}
|
|
8
|
+
/** The slice of Vitest's `TestContext` that `open(ctx)` uses. */
|
|
9
|
+
export type ConformTestContext = Pick<TestContext, "expect" | "onTestFinished" | "signal">;
|
|
10
|
+
/**
|
|
11
|
+
* One operation exposed on a conform handle. `run` executes against a single session. When `contract` is provided,
|
|
12
|
+
* differential mode compares `contract(targetResult, ...args)` against `contract(referenceResult, ...args)` using
|
|
13
|
+
* `ctx.expect`. Method syntax keeps parameter types bivariant so ops with different arities fit one `ConformOpMap`.
|
|
14
|
+
*/
|
|
15
|
+
export interface ConformOp<Session extends ConformSession, Args extends readonly unknown[] = readonly unknown[], Result = unknown, Contract = unknown> {
|
|
16
|
+
run(session: Session, ...args: Args): Result | Promise<Result>;
|
|
17
|
+
contract?(result: Result, ...args: Args): Contract;
|
|
18
|
+
}
|
|
19
|
+
/** Any op belonging to a `Session`, as stored in a harness's `ops` record. */
|
|
20
|
+
export type AnyConformOp<Session extends ConformSession> = ConformOp<Session>;
|
|
21
|
+
/** Map of named ops for a harness. */
|
|
22
|
+
export type ConformOpMap<Session extends ConformSession> = {
|
|
23
|
+
readonly [name: string]: AnyConformOp<Session>;
|
|
24
|
+
};
|
|
25
|
+
/** Helper that preserves inferred `Args`, `Result`, and `Contract` types for one op definition. */
|
|
26
|
+
export declare function conformOp<Session extends ConformSession, Args extends readonly unknown[], Result, Contract = unknown>(op: ConformOp<Session, Args, Result, Contract>): ConformOp<Session, Args, Result, Contract>;
|
|
27
|
+
/** Call signature exposed on a conform handle for one op. */
|
|
28
|
+
export type ConformOpCall<Op> = Op extends ConformOp<infer _Session, infer Args, infer Result, infer _Contract> ? (...args: Args) => Promise<Awaited<Result>> : never;
|
|
29
|
+
/** Handle returned by `open(ctx)` inside a Vitest test. */
|
|
30
|
+
export type ConformHandle<Ops> = {
|
|
31
|
+
readonly [Name in keyof Ops]: ConformOpCall<Ops[Name]>;
|
|
32
|
+
};
|
|
33
|
+
/** Configuration for `defineConformHarness`. */
|
|
34
|
+
export interface ConformHarnessOptions<Session extends ConformSession, Ops extends ConformOpMap<Session>> {
|
|
35
|
+
/** Reference executable (for example, the TypeScript CLI). */
|
|
36
|
+
readonly reference: ConformExecutable;
|
|
37
|
+
/** Starts an isolated session against `executable`. Receives `ctx.signal` so startup can abort on timeout. */
|
|
38
|
+
readonly start: (executable: ConformExecutable, signal: AbortSignal) => Session | Promise<Session>;
|
|
39
|
+
/** Named operations exposed on the handle returned by `open(ctx)`. */
|
|
40
|
+
readonly ops: Ops;
|
|
41
|
+
/** Environment to read `CONFORM_BIN` from on each `open(ctx)`; default `process.env`. */
|
|
42
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
43
|
+
/** Base directory for resolving a relative `CONFORM_BIN` containing `/`; default `process.cwd()`. */
|
|
44
|
+
readonly cwd?: string;
|
|
45
|
+
/** Environment variable name for the target executable; default `CONFORM_BIN`. */
|
|
46
|
+
readonly variable?: string;
|
|
47
|
+
}
|
|
48
|
+
/** Function returned by `defineConformHarness`, called inside a vanilla Vitest test with `ctx`. */
|
|
49
|
+
export type OpenConformHandle<Ops> = (ctx: ConformTestContext) => ConformHandle<Ops>;
|
|
50
|
+
/**
|
|
51
|
+
* Defines a reusable differential conformance harness. Calling the returned `open(ctx)` inside a vanilla Vitest test
|
|
52
|
+
* returns a handle whose methods:
|
|
53
|
+
*
|
|
54
|
+
* - Start the session(s) lazily on the first op call: only `reference` when `CONFORM_BIN` is unset or empty, or two
|
|
55
|
+
* isolated sessions (`reference` and `target`) when `CONFORM_BIN` is set.
|
|
56
|
+
* - Run each op concurrently on both sessions in differential mode, compare `contract(target)` against
|
|
57
|
+
* `contract(reference)` with `ctx.expect`, and return `target`'s result to the test body.
|
|
58
|
+
* - Close all started sessions via both `ctx.signal` (immediate teardown on Vitest timeout or cancellation) and
|
|
59
|
+
* `ctx.onTestFinished` (always awaits teardown on pass or failure, including concurrent tests).
|
|
60
|
+
*/
|
|
61
|
+
export declare function defineConformHarness<Session extends ConformSession, Ops extends ConformOpMap<Session>>(options: ConformHarnessOptions<Session, Ops>): OpenConformHandle<Ops>;
|
|
62
|
+
/**
|
|
63
|
+
* Recursively replaces string values of matching keys in a parsed JSON value with their replacement placeholders.
|
|
64
|
+
* Non-string values (such as JSON Schema property objects or `null`) are preserved unchanged.
|
|
65
|
+
*/
|
|
66
|
+
export declare function maskJsonFields(value: unknown, replacements: Readonly<Record<string, string>>): unknown;
|
|
67
|
+
/** Machine-readable CLI contract projected by `cliJsonContract`. */
|
|
68
|
+
export interface CliJsonContract {
|
|
69
|
+
readonly exit: number;
|
|
70
|
+
readonly stdoutJson?: unknown;
|
|
71
|
+
readonly stderrJson?: unknown;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Projects a CLI result to its machine-readable contract (`exit`, plus `stdoutJson` and `stderrJson` when present,
|
|
75
|
+
* with optional recursive string field masking via `maskFields`). Human-mode text layout is omitted so ports can
|
|
76
|
+
* render native human UI while explicit test assertions check pipeable stdout and semantic UI facts.
|
|
77
|
+
*/
|
|
78
|
+
export declare function cliJsonContract(ran: Pick<ExecCliResult, "exit" | "stdoutJson" | "stderrJson">, options?: {
|
|
79
|
+
readonly maskFields?: Readonly<Record<string, string>>;
|
|
80
|
+
}): CliJsonContract;
|
package/dist/harness.js
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// Differential conformance harness for vanilla Vitest tests (`it("...", async (ctx) => ...)`).
|
|
2
|
+
// Imports only `TestContext` as a type from `vitest`, so this module carries no runtime dependency on vitest.
|
|
3
|
+
import { CONFORM_BIN_VARIABLE, conformTargetExecutable } from "./executable.js";
|
|
4
|
+
/** Helper that preserves inferred `Args`, `Result`, and `Contract` types for one op definition. */
|
|
5
|
+
export function conformOp(op) {
|
|
6
|
+
return op;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Defines a reusable differential conformance harness. Calling the returned `open(ctx)` inside a vanilla Vitest test
|
|
10
|
+
* returns a handle whose methods:
|
|
11
|
+
*
|
|
12
|
+
* - Start the session(s) lazily on the first op call: only `reference` when `CONFORM_BIN` is unset or empty, or two
|
|
13
|
+
* isolated sessions (`reference` and `target`) when `CONFORM_BIN` is set.
|
|
14
|
+
* - Run each op concurrently on both sessions in differential mode, compare `contract(target)` against
|
|
15
|
+
* `contract(reference)` with `ctx.expect`, and return `target`'s result to the test body.
|
|
16
|
+
* - Close all started sessions via both `ctx.signal` (immediate teardown on Vitest timeout or cancellation) and
|
|
17
|
+
* `ctx.onTestFinished` (always awaits teardown on pass or failure, including concurrent tests).
|
|
18
|
+
*/
|
|
19
|
+
export function defineConformHarness(options) {
|
|
20
|
+
return (ctx) => {
|
|
21
|
+
const targetExecutable = conformTargetExecutable({
|
|
22
|
+
env: options.env ?? process.env,
|
|
23
|
+
cwd: options.cwd ?? process.cwd(),
|
|
24
|
+
variable: options.variable ?? CONFORM_BIN_VARIABLE,
|
|
25
|
+
});
|
|
26
|
+
let started;
|
|
27
|
+
let closing;
|
|
28
|
+
const sessions = new Set();
|
|
29
|
+
const rollbackErrors = [];
|
|
30
|
+
const closeAll = () => {
|
|
31
|
+
closing ??= (async () => {
|
|
32
|
+
if (started !== undefined) {
|
|
33
|
+
// Wait for any in-flight start() calls to settle so sessions that finished starting still get closed.
|
|
34
|
+
await started.catch(() => { });
|
|
35
|
+
}
|
|
36
|
+
const results = await Promise.allSettled([...sessions].map((session) => Promise.resolve().then(() => session.close())));
|
|
37
|
+
const errors = [
|
|
38
|
+
...rollbackErrors,
|
|
39
|
+
...results.flatMap((result) => (result.status === "rejected" ? [result.reason] : [])),
|
|
40
|
+
];
|
|
41
|
+
if (errors.length === 1)
|
|
42
|
+
throw errors[0];
|
|
43
|
+
if (errors.length > 1) {
|
|
44
|
+
throw new Error(errors.map(errorMessage).join("\n"), { cause: errors });
|
|
45
|
+
}
|
|
46
|
+
})();
|
|
47
|
+
return closing;
|
|
48
|
+
};
|
|
49
|
+
const onAbort = () => {
|
|
50
|
+
// Kick off teardown immediately on timeout or cancellation; onTestFinished awaits the same promise.
|
|
51
|
+
void closeAll().catch(() => { });
|
|
52
|
+
};
|
|
53
|
+
if (ctx.signal.aborted) {
|
|
54
|
+
onAbort();
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
ctx.signal.addEventListener("abort", onAbort, { once: true });
|
|
58
|
+
}
|
|
59
|
+
ctx.onTestFinished(async () => {
|
|
60
|
+
ctx.signal.removeEventListener("abort", onAbort);
|
|
61
|
+
await closeAll();
|
|
62
|
+
});
|
|
63
|
+
const ensureStarted = () => {
|
|
64
|
+
if (closing !== undefined || ctx.signal.aborted) {
|
|
65
|
+
return Promise.reject(stoppedError(ctx.signal));
|
|
66
|
+
}
|
|
67
|
+
started ??= (async () => {
|
|
68
|
+
if (targetExecutable === undefined) {
|
|
69
|
+
const reference = await options.start(options.reference, ctx.signal);
|
|
70
|
+
sessions.add(reference);
|
|
71
|
+
return { reference };
|
|
72
|
+
}
|
|
73
|
+
const [refSettled, targetSettled] = await Promise.allSettled([
|
|
74
|
+
Promise.resolve().then(() => options.start(options.reference, ctx.signal)),
|
|
75
|
+
Promise.resolve().then(() => options.start(targetExecutable, ctx.signal)),
|
|
76
|
+
]);
|
|
77
|
+
if (refSettled.status === "rejected") {
|
|
78
|
+
if (targetSettled.status === "rejected") {
|
|
79
|
+
throw new Error(`conform: both reference and target failed to start: ${errorMessage(refSettled.reason)}; ${errorMessage(targetSettled.reason)}`, { cause: [refSettled.reason, targetSettled.reason] });
|
|
80
|
+
}
|
|
81
|
+
// Close the surviving target session directly without re-entering `closing`.
|
|
82
|
+
try {
|
|
83
|
+
await targetSettled.value.close();
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
rollbackErrors.push(error);
|
|
87
|
+
}
|
|
88
|
+
throw refSettled.reason;
|
|
89
|
+
}
|
|
90
|
+
if (targetSettled.status === "rejected") {
|
|
91
|
+
// Close the surviving reference session directly without re-entering `closing`.
|
|
92
|
+
try {
|
|
93
|
+
await refSettled.value.close();
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
rollbackErrors.push(error);
|
|
97
|
+
}
|
|
98
|
+
throw targetSettled.reason;
|
|
99
|
+
}
|
|
100
|
+
sessions.add(refSettled.value);
|
|
101
|
+
sessions.add(targetSettled.value);
|
|
102
|
+
return { reference: refSettled.value, target: targetSettled.value };
|
|
103
|
+
})();
|
|
104
|
+
return started;
|
|
105
|
+
};
|
|
106
|
+
const handle = {};
|
|
107
|
+
for (const [name, op] of Object.entries(options.ops)) {
|
|
108
|
+
handle[name] = async (...args) => {
|
|
109
|
+
if (closing !== undefined || ctx.signal.aborted) {
|
|
110
|
+
throw stoppedError(ctx.signal);
|
|
111
|
+
}
|
|
112
|
+
const pair = await ensureStarted();
|
|
113
|
+
if (closing !== undefined || ctx.signal.aborted) {
|
|
114
|
+
throw stoppedError(ctx.signal);
|
|
115
|
+
}
|
|
116
|
+
if (pair.target === undefined) {
|
|
117
|
+
return await op.run(pair.reference, ...args);
|
|
118
|
+
}
|
|
119
|
+
const target = pair.target;
|
|
120
|
+
const [refSettled, targetSettled] = await Promise.allSettled([
|
|
121
|
+
Promise.resolve().then(() => op.run(pair.reference, ...args)),
|
|
122
|
+
Promise.resolve().then(() => op.run(target, ...args)),
|
|
123
|
+
]);
|
|
124
|
+
if (refSettled.status === "rejected" && targetSettled.status === "rejected") {
|
|
125
|
+
throw targetSettled.reason;
|
|
126
|
+
}
|
|
127
|
+
if (refSettled.status === "rejected") {
|
|
128
|
+
throw new Error(`conform ${formatOpLabel(name, args)}: reference threw while target succeeded: ${errorMessage(refSettled.reason)}`, { cause: refSettled.reason });
|
|
129
|
+
}
|
|
130
|
+
if (targetSettled.status === "rejected") {
|
|
131
|
+
throw new Error(`conform ${formatOpLabel(name, args)}: target threw while reference succeeded: ${errorMessage(targetSettled.reason)}`, { cause: targetSettled.reason });
|
|
132
|
+
}
|
|
133
|
+
const refResult = refSettled.value;
|
|
134
|
+
const targetResult = targetSettled.value;
|
|
135
|
+
if (op.contract !== undefined) {
|
|
136
|
+
const refContract = op.contract(refResult, ...args);
|
|
137
|
+
const targetContract = op.contract(targetResult, ...args);
|
|
138
|
+
ctx.expect(targetContract, `conform ${formatOpLabel(name, args)}`).toEqual(refContract);
|
|
139
|
+
}
|
|
140
|
+
return targetResult;
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
return handle;
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
function stoppedError(signal) {
|
|
147
|
+
if (signal.aborted && signal.reason !== undefined)
|
|
148
|
+
return signal.reason;
|
|
149
|
+
return new Error("conform: session is closed");
|
|
150
|
+
}
|
|
151
|
+
function errorMessage(error) {
|
|
152
|
+
return error instanceof Error ? error.message : String(error);
|
|
153
|
+
}
|
|
154
|
+
function formatOpLabel(name, args) {
|
|
155
|
+
if (args.length === 0)
|
|
156
|
+
return `${name}()`;
|
|
157
|
+
const preview = args
|
|
158
|
+
.map((arg) => {
|
|
159
|
+
if (typeof arg === "string")
|
|
160
|
+
return JSON.stringify(truncate(arg, 80));
|
|
161
|
+
if (typeof arg === "number" || typeof arg === "boolean" || arg === null)
|
|
162
|
+
return String(arg);
|
|
163
|
+
if (typeof arg === "function")
|
|
164
|
+
return "<fn>";
|
|
165
|
+
try {
|
|
166
|
+
const json = JSON.stringify(arg);
|
|
167
|
+
return json === undefined ? "<value>" : truncate(json, 80);
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
return "<value>";
|
|
171
|
+
}
|
|
172
|
+
})
|
|
173
|
+
.join(", ");
|
|
174
|
+
return `${name}(${preview})`;
|
|
175
|
+
}
|
|
176
|
+
function truncate(text, max) {
|
|
177
|
+
return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Recursively replaces string values of matching keys in a parsed JSON value with their replacement placeholders.
|
|
181
|
+
* Non-string values (such as JSON Schema property objects or `null`) are preserved unchanged.
|
|
182
|
+
*/
|
|
183
|
+
export function maskJsonFields(value, replacements) {
|
|
184
|
+
if (Array.isArray(value))
|
|
185
|
+
return value.map((entry) => maskJsonFields(entry, replacements));
|
|
186
|
+
if (typeof value !== "object" || value === null)
|
|
187
|
+
return value;
|
|
188
|
+
return Object.fromEntries(Object.entries(value).map(([key, entry]) => {
|
|
189
|
+
const replacement = Object.hasOwn(replacements, key) ? replacements[key] : undefined;
|
|
190
|
+
return [
|
|
191
|
+
key,
|
|
192
|
+
replacement !== undefined && typeof entry === "string" ? replacement : maskJsonFields(entry, replacements),
|
|
193
|
+
];
|
|
194
|
+
}));
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Projects a CLI result to its machine-readable contract (`exit`, plus `stdoutJson` and `stderrJson` when present,
|
|
198
|
+
* with optional recursive string field masking via `maskFields`). Human-mode text layout is omitted so ports can
|
|
199
|
+
* render native human UI while explicit test assertions check pipeable stdout and semantic UI facts.
|
|
200
|
+
*/
|
|
201
|
+
export function cliJsonContract(ran, options = {}) {
|
|
202
|
+
const mask = (value) => options.maskFields === undefined ? value : maskJsonFields(value, options.maskFields);
|
|
203
|
+
return {
|
|
204
|
+
exit: ran.exit,
|
|
205
|
+
...(ran.stdoutJson === undefined ? {} : { stdoutJson: mask(ran.stdoutJson) }),
|
|
206
|
+
...(ran.stderrJson === undefined ? {} : { stderrJson: mask(ran.stderrJson) }),
|
|
207
|
+
};
|
|
208
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { CONFORM_BIN_VARIABLE, InvalidCommandLine, conformTargetExecutable, resolveConformExecutable, splitCommandLine, type ConformExecutable, type ConformTargetOptions, } from "./executable.ts";
|
|
2
|
+
export { cliJsonContract, conformOp, defineConformHarness, maskJsonFields, type AnyConformOp, type CliJsonContract, type ConformHandle, type ConformHarnessOptions, type ConformOp, type ConformOpCall, type ConformOpMap, type ConformSession, type ConformTestContext, type OpenConformHandle, } from "./harness.ts";
|
|
3
|
+
export { ManagedProcessPool, ProcessStopError, createTempRoot, execCli, groupRunning, jsonObject, parseJsonStream, pinnedEnv, processRunning, type ExecCliOptions, type ExecCliResult, type PinnedEnvOptions, } from "./process.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @cnc-tools/conform: live differential conformance testing over vanilla Vitest.
|
|
2
|
+
// Depends only on Node builtins and vitest types.
|
|
3
|
+
export { CONFORM_BIN_VARIABLE, InvalidCommandLine, conformTargetExecutable, resolveConformExecutable, splitCommandLine, } from "./executable.js";
|
|
4
|
+
export { cliJsonContract, conformOp, defineConformHarness, maskJsonFields, } from "./harness.js";
|
|
5
|
+
export { ManagedProcessPool, ProcessStopError, createTempRoot, execCli, groupRunning, jsonObject, parseJsonStream, pinnedEnv, processRunning, } from "./process.js";
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import type { ConformExecutable } from "./executable.ts";
|
|
2
|
+
/** A spawned CLI invocation whose process group still had running processes after `SIGKILL`. */
|
|
3
|
+
export declare class ProcessStopError extends Error {
|
|
4
|
+
readonly name = "ProcessStopError";
|
|
5
|
+
}
|
|
6
|
+
/** Options for `execCli`. */
|
|
7
|
+
export interface ExecCliOptions {
|
|
8
|
+
/** Executable file and fixed leading arguments. */
|
|
9
|
+
readonly executable: ConformExecutable;
|
|
10
|
+
/** Arguments passed after `executable.args`. */
|
|
11
|
+
readonly argv: readonly string[];
|
|
12
|
+
/** Working directory for the child process. */
|
|
13
|
+
readonly cwd: string;
|
|
14
|
+
/** Exact environment passed to the child process. */
|
|
15
|
+
readonly env: Readonly<Record<string, string | undefined>>;
|
|
16
|
+
/** Optional stdin content; when omitted, stdin is closed (`"ignore"`). */
|
|
17
|
+
readonly stdin?: string;
|
|
18
|
+
/** Signal that stops the spawned process group (`SIGTERM` -> grace -> `SIGKILL`). */
|
|
19
|
+
readonly signal?: AbortSignal;
|
|
20
|
+
/** Label used in error messages; default `${executable.file} ${argv.join(" ")}`. */
|
|
21
|
+
readonly label?: string;
|
|
22
|
+
/** Whether to parse stdout and stderr as JSON; default `true`. */
|
|
23
|
+
readonly parseJson?: boolean;
|
|
24
|
+
/** Grace period in ms after `SIGTERM` before `SIGKILL`; default 2000. */
|
|
25
|
+
readonly stopGraceMs?: number;
|
|
26
|
+
/** Confirmation period in ms after `SIGKILL` before throwing `ProcessStopError`; default 2000. */
|
|
27
|
+
readonly killConfirmMs?: number;
|
|
28
|
+
}
|
|
29
|
+
/** Captured result of one CLI invocation. */
|
|
30
|
+
export interface ExecCliResult {
|
|
31
|
+
readonly exit: number;
|
|
32
|
+
readonly stdout: string;
|
|
33
|
+
readonly stderr: string;
|
|
34
|
+
/** Parsed JSON from stdout when `parseJson` is enabled and stdout holds valid JSON. */
|
|
35
|
+
readonly stdoutJson?: unknown;
|
|
36
|
+
/** Parsed JSON from stderr when `parseJson` is enabled and stderr holds valid JSON. */
|
|
37
|
+
readonly stderrJson?: unknown;
|
|
38
|
+
}
|
|
39
|
+
/** Parses a stream as JSON; returns `undefined` when the stream is blank or not valid JSON. */
|
|
40
|
+
export declare function parseJsonStream(text: string): unknown;
|
|
41
|
+
/**
|
|
42
|
+
* Narrows a parsed JSON stream value (such as `ran.stdoutJson` or `ran.stderrJson`) to a plain record, throwing a
|
|
43
|
+
* `TypeError` when it is missing, null, primitive, or an array.
|
|
44
|
+
*/
|
|
45
|
+
export declare function jsonObject(value: unknown, label?: string): Record<string, unknown>;
|
|
46
|
+
/**
|
|
47
|
+
* Creates a temporary directory under `os.tmpdir()` with `prefix` and resolves symlinks via `realpath`, avoiding
|
|
48
|
+
* symlinked temp-dir mismatches (such as `/var` -> `/private/var` on macOS) when mapping real paths to virtual paths.
|
|
49
|
+
*/
|
|
50
|
+
export declare function createTempRoot(prefix: string): Promise<string>;
|
|
51
|
+
/** Options for `pinnedEnv`. */
|
|
52
|
+
export interface PinnedEnvOptions {
|
|
53
|
+
/** Isolated `HOME` directory for the spawned process. */
|
|
54
|
+
readonly home: string;
|
|
55
|
+
/** Base `PATH` value; defaults to `process.env.PATH ?? "/usr/bin:/bin"`. */
|
|
56
|
+
readonly path?: string;
|
|
57
|
+
/** Directories prepended to `PATH` (for example, offline CLI stand-ins). */
|
|
58
|
+
readonly pathPrepend?: readonly string[];
|
|
59
|
+
/** Additional variables to set, or `null` to delete a default variable (such as `NO_COLOR: null`). */
|
|
60
|
+
readonly overrides?: Readonly<Record<string, string | null | undefined>>;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Builds a minimal, deterministic CLI environment with only `PATH`, `HOME`, `TZ=UTC`, `LC_ALL=C.UTF-8`,
|
|
64
|
+
* `LANG=C.UTF-8`, and `NO_COLOR=1`, plus any `pathPrepend` directories and `overrides`. Nothing else from the host
|
|
65
|
+
* environment leaks into the child process.
|
|
66
|
+
*/
|
|
67
|
+
export declare function pinnedEnv(options: PinnedEnvOptions): Record<string, string>;
|
|
68
|
+
/**
|
|
69
|
+
* Spawns `executable` with `argv` in its own detached process group, captures stdout, stderr, and exit code, and
|
|
70
|
+
* tears down the entire process group if `signal` aborts. Throws if the process is terminated by a signal, fails to
|
|
71
|
+
* spawn, or is stopped via `signal` (throwing `ProcessStopError` if processes remain after `SIGKILL`).
|
|
72
|
+
*/
|
|
73
|
+
export declare function execCli(options: ExecCliOptions): Promise<ExecCliResult>;
|
|
74
|
+
/**
|
|
75
|
+
* Tracks active async work and spawned CLI process groups for one session. Calling `stop()` or `close()` aborts every
|
|
76
|
+
* in-flight operation's signal, waits for every operation and process group teardown to settle, and rejects any later
|
|
77
|
+
* work.
|
|
78
|
+
*/
|
|
79
|
+
export declare class ManagedProcessPool {
|
|
80
|
+
#private;
|
|
81
|
+
/** Whether `stop()` or `close()` has been called. */
|
|
82
|
+
get closed(): boolean;
|
|
83
|
+
/** Runs `work` with the pool's abort signal and tracks its promise until it settles. */
|
|
84
|
+
run<T>(work: (signal: AbortSignal) => Promise<T>): Promise<T>;
|
|
85
|
+
/** Spawns a CLI command tracked by this pool; `stop()` / `close()` terminates its process group. */
|
|
86
|
+
exec(options: Omit<ExecCliOptions, "signal">): Promise<ExecCliResult>;
|
|
87
|
+
/**
|
|
88
|
+
* Aborts every in-flight operation's signal, waits for all tracked work to settle, and returns any
|
|
89
|
+
* `ProcessStopError`s from process groups that did not exit after `SIGKILL`. Idempotent.
|
|
90
|
+
*/
|
|
91
|
+
stop(): Promise<ProcessStopError[]>;
|
|
92
|
+
/** Stops every in-flight operation and throws if any process group failed to exit after `SIGKILL`. */
|
|
93
|
+
close(): Promise<void>;
|
|
94
|
+
}
|
|
95
|
+
/** One process's state and process group, parsed from its `/proc/<pid>/stat` line. */
|
|
96
|
+
export interface ProcStat {
|
|
97
|
+
/** State letter: `R` running, `S` sleeping, `Z` zombie, `X` dead, and so on. */
|
|
98
|
+
readonly state: string;
|
|
99
|
+
readonly pgrp: number;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Parses the state and process group from a Linux `/proc/<pid>/stat` line: `pid (comm) state ppid pgrp ...`.
|
|
103
|
+
* Because `comm` inside parentheses may contain spaces or parentheses, fields start after the line's last `)`.
|
|
104
|
+
*/
|
|
105
|
+
export declare function parseProcStat(line: string): ProcStat;
|
|
106
|
+
/**
|
|
107
|
+
* Whether any non-exited process in process group `pgid` is still running, ignoring zombies when Linux `/proc` is
|
|
108
|
+
* mounted.
|
|
109
|
+
*/
|
|
110
|
+
export declare function groupRunning(pgid: number): Promise<boolean>;
|
|
111
|
+
/** Whether process `pid` is still running, ignoring zombies when Linux `/proc` is mounted. */
|
|
112
|
+
export declare function processRunning(pid: number): Promise<boolean>;
|
package/dist/process.js
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
// Detached process-group CLI runner and lifecycle pool. Spawns CLI executables with pinned environments, optional
|
|
2
|
+
// stdin, stdout/stderr/exit capture, JSON stream parsing, and `SIGTERM` -> grace -> `SIGKILL` process-group teardown.
|
|
3
|
+
// On Linux with `/proc` mounted, process-group checks ignore zombies left behind by non-reaping container PID 1s.
|
|
4
|
+
// Loads only Node builtins, never vitest.
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
import { mkdtemp, readdir, readFile, realpath } from "node:fs/promises";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
10
|
+
/** Default wall-clock grace period after `SIGTERM` before escalating to `SIGKILL`. */
|
|
11
|
+
const DEFAULT_STOP_GRACE_MS = 2_000;
|
|
12
|
+
/** Default wall-clock window after `SIGKILL` to confirm every process in the group has exited. */
|
|
13
|
+
const DEFAULT_KILL_CONFIRM_MS = 2_000;
|
|
14
|
+
/** How often teardown polls whether any process in the group is still running. */
|
|
15
|
+
const GROUP_POLL_MS = 20;
|
|
16
|
+
/** A spawned CLI invocation whose process group still had running processes after `SIGKILL`. */
|
|
17
|
+
export class ProcessStopError extends Error {
|
|
18
|
+
name = "ProcessStopError";
|
|
19
|
+
}
|
|
20
|
+
/** Parses a stream as JSON; returns `undefined` when the stream is blank or not valid JSON. */
|
|
21
|
+
export function parseJsonStream(text) {
|
|
22
|
+
if (text.trim() === "")
|
|
23
|
+
return undefined;
|
|
24
|
+
try {
|
|
25
|
+
return JSON.parse(text);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Narrows a parsed JSON stream value (such as `ran.stdoutJson` or `ran.stderrJson`) to a plain record, throwing a
|
|
33
|
+
* `TypeError` when it is missing, null, primitive, or an array.
|
|
34
|
+
*/
|
|
35
|
+
export function jsonObject(value, label = "JSON document") {
|
|
36
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
37
|
+
throw new TypeError(`expected ${label} to be a JSON object, got ${JSON.stringify(value)}`);
|
|
38
|
+
}
|
|
39
|
+
return value;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Creates a temporary directory under `os.tmpdir()` with `prefix` and resolves symlinks via `realpath`, avoiding
|
|
43
|
+
* symlinked temp-dir mismatches (such as `/var` -> `/private/var` on macOS) when mapping real paths to virtual paths.
|
|
44
|
+
*/
|
|
45
|
+
export async function createTempRoot(prefix) {
|
|
46
|
+
return await realpath(await mkdtemp(join(tmpdir(), prefix)));
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Builds a minimal, deterministic CLI environment with only `PATH`, `HOME`, `TZ=UTC`, `LC_ALL=C.UTF-8`,
|
|
50
|
+
* `LANG=C.UTF-8`, and `NO_COLOR=1`, plus any `pathPrepend` directories and `overrides`. Nothing else from the host
|
|
51
|
+
* environment leaks into the child process.
|
|
52
|
+
*/
|
|
53
|
+
export function pinnedEnv(options) {
|
|
54
|
+
const basePath = options.path ?? process.env["PATH"] ?? "/usr/bin:/bin";
|
|
55
|
+
const fullPath = options.pathPrepend === undefined || options.pathPrepend.length === 0
|
|
56
|
+
? basePath
|
|
57
|
+
: `${options.pathPrepend.join(":")}:${basePath}`;
|
|
58
|
+
const env = {
|
|
59
|
+
PATH: fullPath,
|
|
60
|
+
HOME: options.home,
|
|
61
|
+
TZ: "UTC",
|
|
62
|
+
LC_ALL: "C.UTF-8",
|
|
63
|
+
LANG: "C.UTF-8",
|
|
64
|
+
NO_COLOR: "1",
|
|
65
|
+
};
|
|
66
|
+
if (options.overrides !== undefined) {
|
|
67
|
+
for (const [key, value] of Object.entries(options.overrides)) {
|
|
68
|
+
if (value === null) {
|
|
69
|
+
delete env[key];
|
|
70
|
+
}
|
|
71
|
+
else if (value !== undefined) {
|
|
72
|
+
env[key] = value;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return env;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Spawns `executable` with `argv` in its own detached process group, captures stdout, stderr, and exit code, and
|
|
80
|
+
* tears down the entire process group if `signal` aborts. Throws if the process is terminated by a signal, fails to
|
|
81
|
+
* spawn, or is stopped via `signal` (throwing `ProcessStopError` if processes remain after `SIGKILL`).
|
|
82
|
+
*/
|
|
83
|
+
export async function execCli(options) {
|
|
84
|
+
const { executable, argv, cwd, env, stdin, signal } = options;
|
|
85
|
+
const what = options.label ?? (argv.length === 0 ? executable.file : `${executable.file} ${argv.join(" ")}`);
|
|
86
|
+
if (signal?.aborted)
|
|
87
|
+
throw new Error(`${what} was stopped before it started`);
|
|
88
|
+
const child = spawn(executable.file, [...executable.args, ...argv], {
|
|
89
|
+
cwd,
|
|
90
|
+
env,
|
|
91
|
+
stdio: [stdin === undefined ? "ignore" : "pipe", "pipe", "pipe"],
|
|
92
|
+
detached: true,
|
|
93
|
+
});
|
|
94
|
+
let stdout = "";
|
|
95
|
+
let stderr = "";
|
|
96
|
+
child.stdout?.setEncoding("utf8").on("data", (chunk) => (stdout += chunk));
|
|
97
|
+
child.stderr?.setEncoding("utf8").on("data", (chunk) => (stderr += chunk));
|
|
98
|
+
if (stdin !== undefined && child.stdin !== null) {
|
|
99
|
+
// A child that exits without reading stdin triggers EPIPE; its exit status carries the outcome.
|
|
100
|
+
child.stdin.on("error", () => { });
|
|
101
|
+
child.stdin.end(stdin);
|
|
102
|
+
}
|
|
103
|
+
const stopGraceMs = options.stopGraceMs ?? DEFAULT_STOP_GRACE_MS;
|
|
104
|
+
const killConfirmMs = options.killConfirmMs ?? DEFAULT_KILL_CONFIRM_MS;
|
|
105
|
+
let stopping;
|
|
106
|
+
const ended = new Promise((resolve, reject) => {
|
|
107
|
+
const cleanup = () => {
|
|
108
|
+
child.off("error", onError);
|
|
109
|
+
child.off("close", onClose);
|
|
110
|
+
signal?.removeEventListener("abort", onStop);
|
|
111
|
+
};
|
|
112
|
+
const onError = (error) => {
|
|
113
|
+
cleanup();
|
|
114
|
+
reject(error);
|
|
115
|
+
};
|
|
116
|
+
const onClose = (code, closeSignal) => {
|
|
117
|
+
cleanup();
|
|
118
|
+
resolve({ code, signal: closeSignal });
|
|
119
|
+
};
|
|
120
|
+
const onStop = () => {
|
|
121
|
+
stopping = stopProcessGroup(child.pid, what, stopGraceMs, killConfirmMs);
|
|
122
|
+
// If process-group teardown fails (for example ProcessStopError when a process survives SIGKILL),
|
|
123
|
+
// `close` may never fire; detach listeners, destroy stdio pipes, and reject immediately.
|
|
124
|
+
stopping.catch((error) => {
|
|
125
|
+
cleanup();
|
|
126
|
+
child.stdin?.destroy();
|
|
127
|
+
child.stdout?.destroy();
|
|
128
|
+
child.stderr?.destroy();
|
|
129
|
+
reject(error);
|
|
130
|
+
});
|
|
131
|
+
};
|
|
132
|
+
child.once("error", onError);
|
|
133
|
+
child.once("close", onClose);
|
|
134
|
+
signal?.addEventListener("abort", onStop, { once: true });
|
|
135
|
+
});
|
|
136
|
+
let end;
|
|
137
|
+
try {
|
|
138
|
+
end = await ended;
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
if (stopping !== undefined)
|
|
142
|
+
await stopping.catch(() => { });
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
if (stopping !== undefined) {
|
|
146
|
+
await stopping;
|
|
147
|
+
throw new Error(`${what} was stopped when the session closed`);
|
|
148
|
+
}
|
|
149
|
+
if (end.code === null)
|
|
150
|
+
throw new Error(`${what} ended on ${end.signal ?? "a signal"}`);
|
|
151
|
+
const shouldParseJson = options.parseJson ?? true;
|
|
152
|
+
const stdoutJson = shouldParseJson ? parseJsonStream(stdout) : undefined;
|
|
153
|
+
const stderrJson = shouldParseJson ? parseJsonStream(stderr) : undefined;
|
|
154
|
+
return {
|
|
155
|
+
exit: end.code,
|
|
156
|
+
stdout,
|
|
157
|
+
stderr,
|
|
158
|
+
...(stdoutJson === undefined ? {} : { stdoutJson }),
|
|
159
|
+
...(stderrJson === undefined ? {} : { stderrJson }),
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Tracks active async work and spawned CLI process groups for one session. Calling `stop()` or `close()` aborts every
|
|
164
|
+
* in-flight operation's signal, waits for every operation and process group teardown to settle, and rejects any later
|
|
165
|
+
* work.
|
|
166
|
+
*/
|
|
167
|
+
export class ManagedProcessPool {
|
|
168
|
+
#stop = new AbortController();
|
|
169
|
+
#running = new Set();
|
|
170
|
+
#stopped;
|
|
171
|
+
/** Whether `stop()` or `close()` has been called. */
|
|
172
|
+
get closed() {
|
|
173
|
+
return this.#stopped !== undefined;
|
|
174
|
+
}
|
|
175
|
+
/** Runs `work` with the pool's abort signal and tracks its promise until it settles. */
|
|
176
|
+
run(work) {
|
|
177
|
+
if (this.#stopped !== undefined)
|
|
178
|
+
return Promise.reject(new Error("the session is closed"));
|
|
179
|
+
let running;
|
|
180
|
+
try {
|
|
181
|
+
running = work(this.#stop.signal);
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
return Promise.reject(error instanceof Error ? error : new Error(String(error)));
|
|
185
|
+
}
|
|
186
|
+
this.#running.add(running);
|
|
187
|
+
const forget = () => {
|
|
188
|
+
this.#running.delete(running);
|
|
189
|
+
};
|
|
190
|
+
// Attach rejection handler so callers dropping the promise never trigger unhandled rejections.
|
|
191
|
+
void running.then(forget, forget);
|
|
192
|
+
return running;
|
|
193
|
+
}
|
|
194
|
+
/** Spawns a CLI command tracked by this pool; `stop()` / `close()` terminates its process group. */
|
|
195
|
+
exec(options) {
|
|
196
|
+
return this.run((signal) => execCli({ ...options, signal }));
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Aborts every in-flight operation's signal, waits for all tracked work to settle, and returns any
|
|
200
|
+
* `ProcessStopError`s from process groups that did not exit after `SIGKILL`. Idempotent.
|
|
201
|
+
*/
|
|
202
|
+
stop() {
|
|
203
|
+
this.#stopped ??= this.#stopAll();
|
|
204
|
+
return this.#stopped;
|
|
205
|
+
}
|
|
206
|
+
/** Stops every in-flight operation and throws if any process group failed to exit after `SIGKILL`. */
|
|
207
|
+
async close() {
|
|
208
|
+
const unstopped = await this.stop();
|
|
209
|
+
if (unstopped.length > 0)
|
|
210
|
+
throw new Error(unstopped.map((error) => error.message).join("\n"));
|
|
211
|
+
}
|
|
212
|
+
async #stopAll() {
|
|
213
|
+
this.#stop.abort();
|
|
214
|
+
const settled = await Promise.allSettled(this.#running);
|
|
215
|
+
return settled.flatMap((each) => each.status === "rejected" && each.reason instanceof ProcessStopError ? [each.reason] : []);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Parses the state and process group from a Linux `/proc/<pid>/stat` line: `pid (comm) state ppid pgrp ...`.
|
|
220
|
+
* Because `comm` inside parentheses may contain spaces or parentheses, fields start after the line's last `)`.
|
|
221
|
+
*/
|
|
222
|
+
export function parseProcStat(line) {
|
|
223
|
+
const fields = line
|
|
224
|
+
.slice(line.lastIndexOf(")") + 1)
|
|
225
|
+
.trim()
|
|
226
|
+
.split(" ");
|
|
227
|
+
const [state, , pgrp] = fields;
|
|
228
|
+
if (state === undefined || pgrp === undefined || !/^-?\d+$/u.test(pgrp)) {
|
|
229
|
+
throw new Error(`can't read the process stat line ${JSON.stringify(line)}`);
|
|
230
|
+
}
|
|
231
|
+
return { state, pgrp: Number(pgrp) };
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Whether any non-exited process in process group `pgid` is still running, ignoring zombies when Linux `/proc` is
|
|
235
|
+
* mounted.
|
|
236
|
+
*/
|
|
237
|
+
export async function groupRunning(pgid) {
|
|
238
|
+
if (!signalFinds(-pgid))
|
|
239
|
+
return false;
|
|
240
|
+
if (!(await procMounted()))
|
|
241
|
+
return true;
|
|
242
|
+
const pids = (await readdir("/proc")).filter((entry) => /^\d+$/u.test(entry)).map(Number);
|
|
243
|
+
const stats = await Promise.all(pids.map((pid) => readStat(pid)));
|
|
244
|
+
return stats.some((result) => result.kind === "stat" && result.stat.pgrp === pgid && !exited(result.stat.state));
|
|
245
|
+
}
|
|
246
|
+
/** Whether process `pid` is still running, ignoring zombies when Linux `/proc` is mounted. */
|
|
247
|
+
export async function processRunning(pid) {
|
|
248
|
+
if (!signalFinds(pid))
|
|
249
|
+
return false;
|
|
250
|
+
if (!(await procMounted()))
|
|
251
|
+
return true;
|
|
252
|
+
const result = await readStat(pid);
|
|
253
|
+
if (result.kind === "gone")
|
|
254
|
+
return false;
|
|
255
|
+
if (result.kind === "unreadable")
|
|
256
|
+
return true;
|
|
257
|
+
return !exited(result.stat.state);
|
|
258
|
+
}
|
|
259
|
+
async function stopProcessGroup(pid, what, stopGraceMs, killConfirmMs) {
|
|
260
|
+
if (pid === undefined)
|
|
261
|
+
return;
|
|
262
|
+
signalGroup(pid, "SIGTERM");
|
|
263
|
+
if (await groupStopped(pid, stopGraceMs))
|
|
264
|
+
return;
|
|
265
|
+
signalGroup(pid, "SIGKILL");
|
|
266
|
+
if (await groupStopped(pid, killConfirmMs))
|
|
267
|
+
return;
|
|
268
|
+
throw new ProcessStopError(`${what} left processes running in its process group ${pid} after SIGKILL`);
|
|
269
|
+
}
|
|
270
|
+
async function groupStopped(pid, budgetMs) {
|
|
271
|
+
const deadline = performance.now() + budgetMs;
|
|
272
|
+
while (performance.now() < deadline) {
|
|
273
|
+
if (!(await groupRunning(pid)))
|
|
274
|
+
return true;
|
|
275
|
+
await delay(Math.min(GROUP_POLL_MS, Math.max(0, deadline - performance.now())));
|
|
276
|
+
}
|
|
277
|
+
return !(await groupRunning(pid));
|
|
278
|
+
}
|
|
279
|
+
function signalGroup(pid, signal) {
|
|
280
|
+
try {
|
|
281
|
+
process.kill(-pid, signal);
|
|
282
|
+
}
|
|
283
|
+
catch (error) {
|
|
284
|
+
// ESRCH: the process group is already gone.
|
|
285
|
+
if (codeOf(error) !== "ESRCH")
|
|
286
|
+
throw error;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
function exited(state) {
|
|
290
|
+
return state === "Z" || state === "X";
|
|
291
|
+
}
|
|
292
|
+
function signalFinds(target) {
|
|
293
|
+
try {
|
|
294
|
+
process.kill(target, 0);
|
|
295
|
+
return true;
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
// EPERM: the target exists, and this user cannot signal it.
|
|
299
|
+
return codeOf(error) === "EPERM";
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
let mounted;
|
|
303
|
+
function procMounted() {
|
|
304
|
+
mounted ??= readFile("/proc/self/stat", "utf8").then(() => true, () => false);
|
|
305
|
+
return mounted;
|
|
306
|
+
}
|
|
307
|
+
async function readStat(pid) {
|
|
308
|
+
let line;
|
|
309
|
+
try {
|
|
310
|
+
line = await readFile(`/proc/${pid}/stat`, "utf8");
|
|
311
|
+
}
|
|
312
|
+
catch (error) {
|
|
313
|
+
const code = codeOf(error);
|
|
314
|
+
if (code === "ENOENT" || code === "ESRCH")
|
|
315
|
+
return { kind: "gone" };
|
|
316
|
+
if (code === "EACCES" || code === "EPERM")
|
|
317
|
+
return { kind: "unreadable" };
|
|
318
|
+
throw error;
|
|
319
|
+
}
|
|
320
|
+
return { kind: "stat", stat: parseProcStat(line) };
|
|
321
|
+
}
|
|
322
|
+
function codeOf(error) {
|
|
323
|
+
return typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
|
|
324
|
+
}
|
package/package.json
CHANGED
|
@@ -1,9 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cnc-tools/conform",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Conform: live differential conformance testing over vanilla Vitest",
|
|
5
|
+
"license": "MIT",
|
|
5
6
|
"repository": {
|
|
6
7
|
"type": "git",
|
|
7
|
-
"url": "git+https://github.com/vercel-labs/cnc.git"
|
|
8
|
+
"url": "git+https://github.com/vercel-labs/cnc.git",
|
|
9
|
+
"directory": "libs/conform/ts"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist",
|
|
13
|
+
"CHANGELOG.md"
|
|
14
|
+
],
|
|
15
|
+
"type": "module",
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"import": "./dist/index.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public",
|
|
25
|
+
"registry": "https://registry.npmjs.org/"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@types/node": "^24.19.1",
|
|
29
|
+
"esbuild": "^0.27.7",
|
|
30
|
+
"typescript": "^7.0.2",
|
|
31
|
+
"vitest": "4.1.10"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"vitest": "^4.1.10"
|
|
35
|
+
},
|
|
36
|
+
"peerDependenciesMeta": {
|
|
37
|
+
"vitest": {
|
|
38
|
+
"optional": true
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
"engines": {
|
|
42
|
+
"node": ">=22.19.0"
|
|
43
|
+
},
|
|
44
|
+
"scripts": {
|
|
45
|
+
"build": "tsc -p tsconfig.build.json",
|
|
46
|
+
"typecheck": "tsc --noEmit",
|
|
47
|
+
"test": "pnpm run test:default && pnpm run test:integration",
|
|
48
|
+
"test:default": "vitest run --project default --project sanity",
|
|
49
|
+
"test:integration": "vitest run --project integration --passWithNoTests"
|
|
8
50
|
}
|
|
9
|
-
}
|
|
51
|
+
}
|