@zgeoff/testing 0.0.0-stage → 0.0.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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +70 -2
  3. package/dist/cli/build-screen.d.ts +2 -0
  4. package/dist/cli/build-user.d.ts +2 -0
  5. package/dist/cli/collapse-tty-frames.d.ts +1 -0
  6. package/dist/cli/index.d.ts +2 -0
  7. package/dist/cli/parse-osc8-links.d.ts +2 -0
  8. package/dist/cli/spawn-cli.d.ts +2 -0
  9. package/dist/cli/types.d.ts +40 -0
  10. package/dist/process/constants.d.ts +4 -0
  11. package/dist/process/drain-stream.d.ts +1 -0
  12. package/dist/process/index.d.ts +3 -0
  13. package/dist/process/is-line-match.d.ts +1 -0
  14. package/dist/process/probe-group.d.ts +1 -0
  15. package/dist/process/read-free-port.d.ts +1 -0
  16. package/dist/process/read-ready-line.d.ts +5 -0
  17. package/dist/process/run.d.ts +2 -0
  18. package/dist/process/signal-group.d.ts +2 -0
  19. package/dist/process/start.d.ts +2 -0
  20. package/dist/process/types.d.ts +43 -0
  21. package/dist/process/wait-for-group-exit.d.ts +1 -0
  22. package/dist/process/wait-for-outcome.d.ts +14 -0
  23. package/dist/to-exit-code.d.ts +1 -0
  24. package/package.json +54 -4
  25. package/src/cli/build-screen.ts +66 -0
  26. package/src/cli/build-user.ts +32 -0
  27. package/src/cli/collapse-tty-frames.ts +45 -0
  28. package/src/cli/index.ts +12 -0
  29. package/src/cli/parse-osc8-links.ts +15 -0
  30. package/src/cli/spawn-cli.ts +82 -0
  31. package/src/cli/types.ts +96 -0
  32. package/src/process/constants.ts +9 -0
  33. package/src/process/drain-stream.ts +10 -0
  34. package/src/process/index.ts +12 -0
  35. package/src/process/is-line-match.ts +10 -0
  36. package/src/process/probe-group.ts +10 -0
  37. package/src/process/read-free-port.ts +23 -0
  38. package/src/process/read-ready-line.ts +37 -0
  39. package/src/process/run.ts +66 -0
  40. package/src/process/signal-group.ts +12 -0
  41. package/src/process/start.ts +159 -0
  42. package/src/process/types.ts +84 -0
  43. package/src/process/wait-for-group-exit.ts +17 -0
  44. package/src/process/wait-for-outcome.ts +63 -0
  45. package/src/to-exit-code.ts +16 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 zgeoff
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,71 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
+ <h1>@zgeoff/testing</h1>
2
3
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
4
+ <p>
5
+ <a href="https://www.npmjs.com/package/@zgeoff/testing"><img src="https://img.shields.io/npm/v/@zgeoff/testing" alt="npm version"></a>
6
+ <a href="./LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="MIT license"></a>
7
+ </p>
8
+
9
+ <p>
10
+ <a href="../../docs/README.md">Documentation</a> •
11
+ <a href="../../docs/guides/testing-package.md">Testing programs</a>
12
+ </p>
13
+ </div>
14
+
15
+ Drive a real program from a Bun test: type into it in a terminal, or run it as a process and wait
16
+ for it to be ready.
17
+
18
+ A test passes the program's command, a `readonly string[]`, and gets back a handle that cleans up
19
+ after the test. The package knows nothing about how the command was found. In a repo that uses
20
+ [`@zgeoff/rig`](../rig/README.md), `resolveProgram` from `@zgeoff/rig/e2e` supplies it.
21
+
22
+ ## Install
23
+
24
+ ```sh
25
+ bun add -d @zgeoff/testing
26
+ ```
27
+
28
+ The package runs under Bun and needs `bun:test`.
29
+
30
+ ## Use
31
+
32
+ An interactive program runs in a pseudo-terminal. `screen` reads what a person would see, and `user`
33
+ types:
34
+
35
+ ```ts
36
+ import { spawnCLI } from '@zgeoff/testing/cli';
37
+
38
+ const cli = await spawnCLI(['bun', 'src/cli.ts', 'init']);
39
+
40
+ await cli.screen.findByText('Project name?');
41
+ await cli.user.type('ledger');
42
+ await cli.user.pressEnter();
43
+
44
+ expect(await cli.result).toBe(0);
45
+ ```
46
+
47
+ A server or a program with no terminal runs as a process in its own process group:
48
+
49
+ ```ts
50
+ import { run, start } from '@zgeoff/testing/process';
51
+
52
+ const { exitCode, stdout } = await run(command, { args: ['--version'] });
53
+
54
+ await using ledger = await start(command, { ready: { url: '/health' } });
55
+
56
+ await fetch(`${ledger.url}/entries`);
57
+ ```
58
+
59
+ ## Features
60
+
61
+ - `spawnCLI` runs a program in a pseudo-terminal, with `screen` queries, `user` keystrokes, `resize`
62
+ and OSC 8 links.
63
+ - `run` runs a program to its exit, with `input` on stdin and a time limit.
64
+ - `start` picks a free port, waits until the program is ready, and stops the whole process group.
65
+ - Each handle kills its program when the test ends.
66
+ - An exit code is 128 plus the signal number when a signal killed the program.
67
+
68
+ ## Documentation
69
+
70
+ See [Testing programs](../../docs/guides/testing-package.md), and the
71
+ [docs index](../../docs/README.md).
@@ -0,0 +1,2 @@
1
+ import type { Screen } from './types.ts';
2
+ export declare function buildScreen(getOutput: () => string): Screen;
@@ -0,0 +1,2 @@
1
+ import type { User } from './types.ts';
2
+ export declare function buildUser(writeInput: (text: string) => void): User;
@@ -0,0 +1 @@
1
+ export declare function collapseTTYFrames(raw: string): string;
@@ -0,0 +1,2 @@
1
+ export { spawnCLI } from './spawn-cli.ts';
2
+ export type { FindByTextOptions, Key, Screen, ScreenLink, SpawnCLIOptions, SpawnedCLI, TextPattern, User, } from './types.ts';
@@ -0,0 +1,2 @@
1
+ import type { ScreenLink } from './types.ts';
2
+ export declare function parseOSC8Links(raw: string): ScreenLink[];
@@ -0,0 +1,2 @@
1
+ import type { SpawnCLIOptions, SpawnedCLI } from './types.ts';
2
+ export declare function spawnCLI(command: readonly string[], options?: SpawnCLIOptions): Promise<SpawnedCLI>;
@@ -0,0 +1,40 @@
1
+ export interface ScreenLink {
2
+ readonly text: string;
3
+ readonly href: string;
4
+ readonly params: string;
5
+ }
6
+ export interface FindByTextOptions {
7
+ readonly timeoutMs?: number;
8
+ }
9
+ export type TextPattern = string | RegExp;
10
+ export interface Screen {
11
+ readonly getByText: (pattern: TextPattern) => string;
12
+ readonly queryByText: (pattern: TextPattern) => string | null;
13
+ readonly findByText: (pattern: TextPattern, options?: FindByTextOptions) => Promise<string>;
14
+ readonly getAllByText: (pattern: TextPattern) => string[];
15
+ readonly text: () => string;
16
+ readonly links: () => ScreenLink[];
17
+ }
18
+ export type Key = 'up' | 'down' | 'left' | 'right' | 'space' | 'enter' | 'tab' | 'escape' | 'backspace';
19
+ export interface User {
20
+ readonly type: (text: string) => Promise<void>;
21
+ readonly pressEnter: () => Promise<void>;
22
+ readonly press: (key: Key) => Promise<void>;
23
+ readonly cancel: () => Promise<void>;
24
+ }
25
+ export interface SpawnCLIOptions {
26
+ readonly args?: readonly string[];
27
+ readonly cwd?: string;
28
+ readonly env?: Readonly<Record<string, string>>;
29
+ readonly cols?: number;
30
+ readonly rows?: number;
31
+ readonly silent?: boolean;
32
+ }
33
+ export interface SpawnedCLI extends AsyncDisposable {
34
+ readonly screen: Screen;
35
+ readonly user: User;
36
+ readonly resize: (cols: number, rows: number) => void;
37
+ readonly result: Promise<number>;
38
+ readonly exitCode: () => number | null;
39
+ readonly kill: (signal?: NodeJS.Signals) => void;
40
+ }
@@ -0,0 +1,4 @@
1
+ export declare const pollIntervalMs = 50;
2
+ export declare const drainGraceMs = 200;
3
+ export declare const groupDeadlineMs = 5000;
4
+ export declare const defaultWaitMs = 10000;
@@ -0,0 +1 @@
1
+ export declare function drainStream(stream: ReadableStream<Uint8Array>, onText: (text: string) => void): Promise<void>;
@@ -0,0 +1,3 @@
1
+ export { run } from './run.ts';
2
+ export { start } from './start.ts';
3
+ export type { ProcessHandle, Ready, RunOptions, RunResult, Signal, StartOptions, WaitForLineOptions, } from './types.ts';
@@ -0,0 +1 @@
1
+ export declare function isLineMatch(line: string, pattern: string | RegExp): boolean;
@@ -0,0 +1 @@
1
+ export declare function probeGroup(groupID: number): boolean;
@@ -0,0 +1 @@
1
+ export declare function readFreePort(): Promise<number>;
@@ -0,0 +1,5 @@
1
+ import type { Ready } from './types.ts';
2
+ export interface ReadyResult {
3
+ readonly line: string | null;
4
+ }
5
+ export declare function readReadyLine(ready: Ready, baseURL: string, findNextLine: (pattern: string | RegExp) => string | null): Promise<ReadyResult | null>;
@@ -0,0 +1,2 @@
1
+ import type { RunOptions, RunResult } from './types.ts';
2
+ export declare function run(command: readonly string[], options?: RunOptions): Promise<RunResult>;
@@ -0,0 +1,2 @@
1
+ import type { Signal } from './types.ts';
2
+ export declare function signalGroup(groupID: number, signal: Signal | 0): void;
@@ -0,0 +1,2 @@
1
+ import type { ProcessHandle, StartOptions } from './types.ts';
2
+ export declare function start(command: readonly string[], options?: StartOptions): Promise<ProcessHandle>;
@@ -0,0 +1,43 @@
1
+ export type Signal = 'SIGTERM' | 'SIGINT' | 'SIGHUP' | 'SIGKILL';
2
+ type Environment = Readonly<Record<string, string | undefined>>;
3
+ export interface RunOptions {
4
+ readonly args?: readonly string[];
5
+ readonly env?: Environment;
6
+ readonly cwd?: string;
7
+ readonly input?: string;
8
+ readonly timeoutMs?: number;
9
+ }
10
+ export interface RunResult {
11
+ readonly exitCode: number;
12
+ readonly stdout: string;
13
+ readonly stderr: string;
14
+ }
15
+ export type Ready = {
16
+ readonly url: string;
17
+ } | {
18
+ readonly stdout: string | RegExp;
19
+ } | {
20
+ readonly check: () => Promise<boolean>;
21
+ };
22
+ export interface StartOptions {
23
+ readonly args?: readonly string[] | ((port: number) => readonly string[]);
24
+ readonly env?: Environment | ((port: number) => Environment);
25
+ readonly cwd?: string;
26
+ readonly port?: number;
27
+ readonly ready?: Ready;
28
+ readonly readyTimeoutMs?: number;
29
+ }
30
+ export interface WaitForLineOptions {
31
+ readonly timeoutMs?: number;
32
+ }
33
+ export interface ProcessHandle extends AsyncDisposable {
34
+ readonly url: string;
35
+ readonly port: number;
36
+ readonly pid: number;
37
+ readonly readyLine: string | null;
38
+ readonly write: (text: string) => Promise<void>;
39
+ readonly waitForLine: (pattern: string | RegExp, options?: WaitForLineOptions) => Promise<string>;
40
+ readonly output: () => string;
41
+ readonly stop: (signal?: Signal) => Promise<number>;
42
+ }
43
+ export {};
@@ -0,0 +1 @@
1
+ export declare function waitForGroupExit(groupID: number): Promise<void>;
@@ -0,0 +1,14 @@
1
+ export interface WaitProbes {
2
+ readonly deadlineMs: number;
3
+ readonly probeExited: () => boolean;
4
+ readonly settleOutput: () => Promise<unknown>;
5
+ }
6
+ export type WaitOutcome<Value> = {
7
+ readonly kind: 'ready';
8
+ readonly value: Value;
9
+ } | {
10
+ readonly kind: 'exited';
11
+ } | {
12
+ readonly kind: 'timeout';
13
+ };
14
+ export declare function waitForOutcome<Value>(read: () => Promise<Value | null> | Value | null, probes: WaitProbes): Promise<WaitOutcome<Value>>;
@@ -0,0 +1 @@
1
+ export declare function toExitCode(exitCode: number, signal: number | string | null | undefined): number;
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@zgeoff/testing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.0",
4
+ "description": "Drive a real program from a Bun test, in a pseudo-terminal or as a process with a ready check",
5
+ "keywords": [
6
+ "bun",
7
+ "e2e",
8
+ "process",
9
+ "pty",
10
+ "test"
11
+ ],
12
+ "license": "MIT",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/zgeoff/tools.git",
16
+ "directory": "packages/testing"
17
+ },
18
+ "files": [
19
+ "src",
20
+ "!src/**/*.test.ts",
21
+ "dist",
22
+ "!src/test-utils"
23
+ ],
24
+ "type": "module",
25
+ "exports": {
26
+ "./cli": {
27
+ "types": "./dist/cli/index.d.ts",
28
+ "bun": "./src/cli/index.ts",
29
+ "default": "./src/cli/index.ts"
30
+ },
31
+ "./process": {
32
+ "types": "./dist/process/index.d.ts",
33
+ "bun": "./src/process/index.ts",
34
+ "default": "./src/process/index.ts"
35
+ }
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "scripts": {
41
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
42
+ "typecheck": "tsrs"
43
+ },
44
+ "dependencies": {
45
+ "bun-pty": "0.5.2"
46
+ },
47
+ "devDependencies": {
48
+ "@types/bun": "1.4.4",
49
+ "@zgeoff/std": "0.3.2",
50
+ "tsrs": "0.18.0-ts7.1.0-dev.20260929",
51
+ "typescript": "7.0.2"
52
+ },
53
+ "engines": {
54
+ "bun": ">=1.3"
55
+ }
56
+ }
@@ -0,0 +1,66 @@
1
+ import { collapseTTYFrames } from './collapse-tty-frames.ts';
2
+ import { parseOSC8Links } from './parse-osc8-links.ts';
3
+ import type { FindByTextOptions, Screen, TextPattern } from './types.ts';
4
+
5
+ const defaultFindTimeoutMs = 5000;
6
+ const findIntervalMs = 25;
7
+
8
+ // The queries over the bytes a program has written to its terminal so far. `getOutput` is called
9
+ // on each query, so a query sees what the program wrote since the last one.
10
+ export function buildScreen(getOutput: () => string): Screen {
11
+ const getText = () => collapseTTYFrames(getOutput());
12
+
13
+ const getAllByText = (pattern: TextPattern): string[] =>
14
+ getText()
15
+ .split('\n')
16
+ .filter((line) => isMatch(line, pattern));
17
+
18
+ const queryByText = (pattern: TextPattern): string | null => getAllByText(pattern)[0] ?? null;
19
+
20
+ const buildMiss = (pattern: TextPattern): Error =>
21
+ new Error(`no line on the screen matches ${String(pattern)}; the screen:\n${getText()}`);
22
+
23
+ return {
24
+ getByText: (pattern) => {
25
+ const line = queryByText(pattern);
26
+
27
+ if (line === null) {
28
+ throw buildMiss(pattern);
29
+ }
30
+
31
+ return line;
32
+ },
33
+ queryByText,
34
+ // oxlint-disable-next-line zgeoff/verb-contract -- the name follows the testing-library queries
35
+ findByText: async (pattern, options: FindByTextOptions = {}) => {
36
+ const deadline = Date.now() + (options.timeoutMs ?? defaultFindTimeoutMs);
37
+ let line = queryByText(pattern);
38
+
39
+ while (line === null && Date.now() < deadline) {
40
+ await Bun.sleep(findIntervalMs);
41
+
42
+ line = queryByText(pattern);
43
+ }
44
+
45
+ if (line === null) {
46
+ throw buildMiss(pattern);
47
+ }
48
+
49
+ return line;
50
+ },
51
+ getAllByText,
52
+ text: getText,
53
+ links: () => parseOSC8Links(getOutput()),
54
+ };
55
+ }
56
+
57
+ function isMatch(line: string, pattern: TextPattern): boolean {
58
+ if (typeof pattern === 'string') {
59
+ return line.includes(pattern);
60
+ }
61
+
62
+ // A global or sticky pattern moves lastIndex on each test, so a later query would skip a match.
63
+ pattern.lastIndex = 0;
64
+
65
+ return pattern.test(line);
66
+ }
@@ -0,0 +1,32 @@
1
+ import type { Key, User } from './types.ts';
2
+
3
+ const keyCodes = {
4
+ up: '\u001B[A',
5
+ down: '\u001B[B',
6
+ right: '\u001B[C',
7
+ left: '\u001B[D',
8
+ space: ' ',
9
+ enter: '\r',
10
+ tab: '\t',
11
+ escape: '\u001B',
12
+ backspace: '\u007F',
13
+ } as const satisfies Record<Key, string>;
14
+
15
+ const ctrlC = '\u0003';
16
+
17
+ // A person at the keyboard: each method writes the key codes to the terminal.
18
+ export function buildUser(writeInput: (text: string) => void): User {
19
+ // Waits a macrotask, so the program reads the keys before the test goes on.
20
+ const writeThenFlush = async (text: string): Promise<void> => {
21
+ writeInput(text);
22
+
23
+ await Bun.sleep(0);
24
+ };
25
+
26
+ return {
27
+ type: (text) => writeThenFlush(text),
28
+ pressEnter: () => writeThenFlush(keyCodes.enter),
29
+ press: (key) => writeThenFlush(keyCodes[key]),
30
+ cancel: () => writeThenFlush(ctrlC),
31
+ };
32
+ }
@@ -0,0 +1,45 @@
1
+ // Matches a CSI sequence at the sticky position: cursor moves, colours and erases.
2
+ // oxlint-disable-next-line no-control-regex -- a CSI sequence starts with the ESC control character
3
+ const csiPattern = /\u001B\[[0-9;?]*[A-Za-z~]/uy;
4
+
5
+ // Turns the bytes a program wrote to a terminal into the text a person sees: a carriage return
6
+ // restarts the line, a backspace removes a character, an erase-line sequence clears the line, and
7
+ // every other escape sequence goes.
8
+ export function collapseTTYFrames(raw: string): string {
9
+ let committed = '';
10
+ let line = '';
11
+
12
+ for (let index = 0; index < raw.length; index += 1) {
13
+ const character = raw[index];
14
+
15
+ if (character === '\r') {
16
+ // The \n of a CRLF commits the line, so the \r keeps it.
17
+ if (raw[index + 1] !== '\n') {
18
+ line = '';
19
+ }
20
+ } else if (character === '\n') {
21
+ committed += `${line}\n`;
22
+ line = '';
23
+ } else if (character === '\b') {
24
+ line = line.slice(0, -1);
25
+ } else if (character === '\u001B') {
26
+ csiPattern.lastIndex = index;
27
+
28
+ const sequence = csiPattern.exec(raw)?.[0];
29
+
30
+ if (sequence === undefined) {
31
+ line += character;
32
+ } else {
33
+ if (sequence.endsWith('K')) {
34
+ line = '';
35
+ }
36
+
37
+ index += sequence.length - 1;
38
+ }
39
+ } else {
40
+ line += character;
41
+ }
42
+ }
43
+
44
+ return Bun.stripANSI(committed + line);
45
+ }
@@ -0,0 +1,12 @@
1
+ export { spawnCLI } from './spawn-cli.ts';
2
+
3
+ export type {
4
+ FindByTextOptions,
5
+ Key,
6
+ Screen,
7
+ ScreenLink,
8
+ SpawnCLIOptions,
9
+ SpawnedCLI,
10
+ TextPattern,
11
+ User,
12
+ } from './types.ts';
@@ -0,0 +1,15 @@
1
+ import type { ScreenLink } from './types.ts';
2
+
3
+ const linkPattern =
4
+ // oxlint-disable-next-line no-control-regex -- an OSC sequence starts with the ESC control character
5
+ /\u001B\]8;(?<params>[^;\u0007\u001B]*);(?<href>[^\u0007\u001B]+)(?:\u0007|\u001B\\)(?<text>.*?)\u001B\]8;;(?:\u0007|\u001B\\)/gsu;
6
+
7
+ // Reads the terminal hyperlinks that a program wrote, so a test can assert on where a link points
8
+ // and not only on its text.
9
+ export function parseOSC8Links(raw: string): ScreenLink[] {
10
+ return [...raw.matchAll(linkPattern)].map((match) => ({
11
+ text: Bun.stripANSI(match.groups?.['text'] ?? ''),
12
+ href: match.groups?.['href'] ?? '',
13
+ params: match.groups?.['params'] ?? '',
14
+ }));
15
+ }
@@ -0,0 +1,82 @@
1
+ import { onTestFinished } from 'bun:test';
2
+ import { spawn } from 'bun-pty';
3
+ import { toExitCode } from '../to-exit-code.ts';
4
+ import { buildScreen } from './build-screen.ts';
5
+ import { buildUser } from './build-user.ts';
6
+ import type { SpawnCLIOptions, SpawnedCLI } from './types.ts';
7
+
8
+ // Runs a program in a pseudo-terminal, as a person's terminal would, and gives the test its screen
9
+ // and keyboard. A test that spawns a program kills it when the test ends.
10
+ export function spawnCLI(
11
+ command: readonly string[],
12
+ options: SpawnCLIOptions = {},
13
+ ): Promise<SpawnedCLI> {
14
+ const [file, ...commandArgs] = command;
15
+
16
+ if (file === undefined) {
17
+ return Promise.reject(new Error('spawnCLI needs a command with at least a program to run'));
18
+ }
19
+
20
+ const pty = spawn(file, [...commandArgs, ...(options.args ?? [])], {
21
+ name: 'xterm-256color',
22
+ cols: options.cols ?? 80,
23
+ rows: options.rows ?? 24,
24
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
25
+ env: { ...readDefinedEnv(process.env), TERM: 'xterm-256color', ...options.env },
26
+ });
27
+
28
+ const isSilent = options.silent ?? true;
29
+ const output = { text: '' };
30
+ const exit: { code: number | null } = { code: null };
31
+
32
+ pty.onData((chunk) => {
33
+ output.text += chunk;
34
+
35
+ if (!isSilent) {
36
+ process.stdout.write(chunk);
37
+ }
38
+ });
39
+
40
+ const exited = Promise.withResolvers<number>();
41
+ const result = exited.promise;
42
+
43
+ pty.onExit((event) => {
44
+ exit.code = toExitCode(event.exitCode, event.signal);
45
+
46
+ exited.resolve(exit.code);
47
+ });
48
+
49
+ const kill = (signal: NodeJS.Signals = 'SIGTERM'): void => {
50
+ if (exit.code === null) {
51
+ pty.kill(signal);
52
+ }
53
+ };
54
+
55
+ const stopAndWait = async (): Promise<void> => {
56
+ kill('SIGKILL');
57
+
58
+ await result;
59
+ };
60
+
61
+ onTestFinished(stopAndWait);
62
+
63
+ return Promise.resolve({
64
+ screen: buildScreen(() => output.text),
65
+ user: buildUser((text) => {
66
+ pty.write(text);
67
+ }),
68
+ resize: (cols, rows) => {
69
+ pty.resize(cols, rows);
70
+ },
71
+ result,
72
+ exitCode: () => exit.code,
73
+ kill,
74
+ [Symbol.asyncDispose]: stopAndWait,
75
+ });
76
+ }
77
+
78
+ function readDefinedEnv(env: NodeJS.ProcessEnv): Record<string, string> {
79
+ return Object.fromEntries(
80
+ Object.entries(env).flatMap(([key, value]) => (value === undefined ? [] : [[key, value]])),
81
+ );
82
+ }
@@ -0,0 +1,96 @@
1
+ export interface ScreenLink {
2
+ readonly text: string;
3
+
4
+ readonly href: string;
5
+
6
+ // The part of the sequence before the link, such as `id=7`; empty when there is none.
7
+ readonly params: string;
8
+ }
9
+
10
+ export interface FindByTextOptions {
11
+ // How long to wait for a match; 5 s when it is unset.
12
+ readonly timeoutMs?: number;
13
+ }
14
+
15
+ // A string matches a substring of a line, and a RegExp matches a line by `test`.
16
+ export type TextPattern = string | RegExp;
17
+
18
+ export interface Screen {
19
+ // The first line of the screen that matches. Throws with the screen text on a miss.
20
+ readonly getByText: (pattern: TextPattern) => string;
21
+
22
+ // The first line that matches, or null.
23
+ readonly queryByText: (pattern: TextPattern) => string | null;
24
+
25
+ // Waits for a line that matches. Throws with the screen text when the wait runs out.
26
+ readonly findByText: (pattern: TextPattern, options?: FindByTextOptions) => Promise<string>;
27
+
28
+ // Every line that matches, in screen order.
29
+ readonly getAllByText: (pattern: TextPattern) => string[];
30
+
31
+ // The text a person sees: redrawn frames collapsed and escape sequences removed.
32
+ readonly text: () => string;
33
+
34
+ // The OSC 8 hyperlinks the program wrote.
35
+ readonly links: () => ScreenLink[];
36
+ }
37
+
38
+ export type Key =
39
+ | 'up'
40
+ | 'down'
41
+ | 'left'
42
+ | 'right'
43
+ | 'space'
44
+ | 'enter'
45
+ | 'tab'
46
+ | 'escape'
47
+ | 'backspace';
48
+
49
+ export interface User {
50
+ // Writes characters, with no line break.
51
+ readonly type: (text: string) => Promise<void>;
52
+
53
+ readonly pressEnter: () => Promise<void>;
54
+
55
+ readonly press: (key: Key) => Promise<void>;
56
+
57
+ // Writes Ctrl+C.
58
+ readonly cancel: () => Promise<void>;
59
+ }
60
+
61
+ export interface SpawnCLIOptions {
62
+ // Arguments added after the command.
63
+ readonly args?: readonly string[];
64
+
65
+ readonly cwd?: string;
66
+
67
+ // Added to the test's environment. `TERM` is `xterm-256color` unless this sets it.
68
+ readonly env?: Readonly<Record<string, string>>;
69
+
70
+ // The terminal's width; 80 when it is unset.
71
+ readonly cols?: number;
72
+
73
+ // The terminal's height; 24 when it is unset.
74
+ readonly rows?: number;
75
+
76
+ // When false, the program's output also goes to the test runner's terminal. True when it is unset.
77
+ readonly silent?: boolean;
78
+ }
79
+
80
+ export interface SpawnedCLI extends AsyncDisposable {
81
+ readonly screen: Screen;
82
+
83
+ readonly user: User;
84
+
85
+ readonly resize: (cols: number, rows: number) => void;
86
+
87
+ // Resolves with the exit code, which is 128 plus the signal's number when a signal killed the
88
+ // program.
89
+ readonly result: Promise<number>;
90
+
91
+ // The exit code, or null while the program runs.
92
+ readonly exitCode: () => number | null;
93
+
94
+ // Sends the signal, SIGTERM when it is unset. It does nothing once the program has exited.
95
+ readonly kill: (signal?: NodeJS.Signals) => void;
96
+ }
@@ -0,0 +1,9 @@
1
+ export const pollIntervalMs = 50;
2
+
3
+ // A process outside the group, such as one the program started in a group of its own, can hold the
4
+ // output pipes open, so a stop waits only this long for the rest of the output.
5
+ export const drainGraceMs = 200;
6
+
7
+ // How long a stop waits for the group to empty before it sends SIGKILL.
8
+ export const groupDeadlineMs = 5000;
9
+ export const defaultWaitMs = 10_000;
@@ -0,0 +1,10 @@
1
+ export async function drainStream(
2
+ stream: ReadableStream<Uint8Array>,
3
+ onText: (text: string) => void,
4
+ ): Promise<void> {
5
+ const decoder = new TextDecoder();
6
+
7
+ for await (const chunk of stream) {
8
+ onText(decoder.decode(chunk, { stream: true }));
9
+ }
10
+ }
@@ -0,0 +1,12 @@
1
+ export { run } from './run.ts';
2
+ export { start } from './start.ts';
3
+
4
+ export type {
5
+ ProcessHandle,
6
+ Ready,
7
+ RunOptions,
8
+ RunResult,
9
+ Signal,
10
+ StartOptions,
11
+ WaitForLineOptions,
12
+ } from './types.ts';
@@ -0,0 +1,10 @@
1
+ export function isLineMatch(line: string, pattern: string | RegExp): boolean {
2
+ if (typeof pattern === 'string') {
3
+ return line.includes(pattern);
4
+ }
5
+
6
+ // A global or sticky pattern moves lastIndex on each test, so a later line would be skipped.
7
+ pattern.lastIndex = 0;
8
+
9
+ return pattern.test(line);
10
+ }
@@ -0,0 +1,10 @@
1
+ // Tells whether any process still runs in the group.
2
+ export function probeGroup(groupID: number): boolean {
3
+ try {
4
+ process.kill(-groupID, 0);
5
+
6
+ return true;
7
+ } catch {
8
+ return false;
9
+ }
10
+ }
@@ -0,0 +1,23 @@
1
+ import { createServer } from 'node:net';
2
+
3
+ // Asks the OS for a free port on the loopback address. Another process can take the port before
4
+ // the program binds it.
5
+ export function readFreePort(): Promise<number> {
6
+ return new Promise((resolve, reject) => {
7
+ const server = createServer();
8
+
9
+ server.once('error', reject);
10
+
11
+ server.listen(0, '127.0.0.1', () => {
12
+ const address = server.address();
13
+
14
+ server.close(() => {
15
+ if (address !== null && typeof address === 'object') {
16
+ resolve(address.port);
17
+ } else {
18
+ reject(new Error('the OS gave no port'));
19
+ }
20
+ });
21
+ });
22
+ });
23
+ }
@@ -0,0 +1,37 @@
1
+ import type { Ready } from './types.ts';
2
+
3
+ // The result of one readiness check: `line` is the stdout line that matched, or null for a check
4
+ // that matches no line.
5
+ export interface ReadyResult {
6
+ readonly line: string | null;
7
+ }
8
+
9
+ // Runs one readiness check. Only a whole stdout line can match, so a test that parses the ready
10
+ // line never gets half of one.
11
+ export async function readReadyLine(
12
+ ready: Ready,
13
+ baseURL: string,
14
+ findNextLine: (pattern: string | RegExp) => string | null,
15
+ ): Promise<ReadyResult | null> {
16
+ if ('stdout' in ready) {
17
+ const line = findNextLine(ready.stdout);
18
+
19
+ return line === null ? null : { line };
20
+ }
21
+
22
+ if ('check' in ready) {
23
+ const isReady = await ready.check();
24
+
25
+ return isReady ? { line: null } : null;
26
+ }
27
+
28
+ try {
29
+ const response = await fetch(new URL(ready.url, baseURL), {
30
+ signal: AbortSignal.timeout(1000),
31
+ });
32
+
33
+ return response.ok ? { line: null } : null;
34
+ } catch {
35
+ return null;
36
+ }
37
+ }
@@ -0,0 +1,66 @@
1
+ import { toExitCode } from '../to-exit-code.ts';
2
+ import { drainGraceMs } from './constants.ts';
3
+ import { drainStream } from './drain-stream.ts';
4
+ import { signalGroup } from './signal-group.ts';
5
+ import type { RunOptions, RunResult } from './types.ts';
6
+ import { waitForGroupExit } from './wait-for-group-exit.ts';
7
+
8
+ // Runs a program to its exit. The program leads a process group of its own, so a time limit stops
9
+ // every process it forks too.
10
+ export async function run(
11
+ command: readonly string[],
12
+ options: RunOptions = {},
13
+ ): Promise<RunResult> {
14
+ const child = Bun.spawn([...command, ...(options.args ?? [])], {
15
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
16
+ env: { ...process.env, ...options.env },
17
+ stdin: options.input === undefined ? 'ignore' : new Blob([options.input]),
18
+ stdout: 'pipe',
19
+ stderr: 'pipe',
20
+ detached: true,
21
+ });
22
+
23
+ const log = { stdout: '', stderr: '' };
24
+
25
+ const drained = Promise.all([
26
+ drainStream(child.stdout, (text) => {
27
+ log.stdout += text;
28
+ }),
29
+ drainStream(child.stderr, (text) => {
30
+ log.stderr += text;
31
+ }),
32
+ ]);
33
+
34
+ // The wait covers the output pipes too, which a descendant can hold open past the exit.
35
+ const finished = (async () => {
36
+ await child.exited;
37
+ await drained;
38
+
39
+ return true;
40
+ })();
41
+
42
+ const timeoutMs = options.timeoutMs;
43
+
44
+ const hasFinished =
45
+ timeoutMs === undefined
46
+ ? await finished
47
+ : await Promise.race([finished, Bun.sleep(timeoutMs).then(() => false)]);
48
+
49
+ if (!hasFinished) {
50
+ // The leader may be gone while a descendant of its group still runs.
51
+ signalGroup(child.pid, 'SIGKILL');
52
+
53
+ await child.exited;
54
+ await waitForGroupExit(child.pid);
55
+
56
+ await Promise.race([drained, Bun.sleep(drainGraceMs)]);
57
+
58
+ throw new Error(
59
+ `${command.join(' ')} did not exit in ${timeoutMs} ms; its output:\n${log.stdout}${log.stderr}`,
60
+ );
61
+ }
62
+
63
+ const exitCode = await child.exited;
64
+
65
+ return { exitCode: toExitCode(exitCode, child.signalCode), ...log };
66
+ }
@@ -0,0 +1,12 @@
1
+ import type { Signal } from './types.ts';
2
+
3
+ // A group that has already emptied is no error: the signal had nothing left to reach.
4
+ export function signalGroup(groupID: number, signal: Signal | 0): void {
5
+ try {
6
+ process.kill(-groupID, signal);
7
+ } catch (error) {
8
+ if (!(error instanceof Error && 'code' in error && error.code === 'ESRCH')) {
9
+ throw error;
10
+ }
11
+ }
12
+ }
@@ -0,0 +1,159 @@
1
+ import { toExitCode } from '../to-exit-code.ts';
2
+ import { defaultWaitMs, drainGraceMs, groupDeadlineMs } from './constants.ts';
3
+ import { drainStream } from './drain-stream.ts';
4
+ import { isLineMatch } from './is-line-match.ts';
5
+ import { probeGroup } from './probe-group.ts';
6
+ import { readFreePort } from './read-free-port.ts';
7
+ import { readReadyLine } from './read-ready-line.ts';
8
+ import { signalGroup } from './signal-group.ts';
9
+ import type { ProcessHandle, Signal, StartOptions, WaitForLineOptions } from './types.ts';
10
+ import { waitForGroupExit } from './wait-for-group-exit.ts';
11
+ import { waitForOutcome } from './wait-for-outcome.ts';
12
+
13
+ // Starts a program on a free port, passed as `PORT`, and waits for it to be ready. The program
14
+ // leads a process group of its own, so a signal from `stop` or the disposal reaches every process
15
+ // it forks too.
16
+ export async function start(
17
+ command: readonly string[],
18
+ options: StartOptions = {},
19
+ ): Promise<ProcessHandle> {
20
+ const port = await (options.port === undefined ? readFreePort() : Promise.resolve(options.port));
21
+
22
+ const name = command.join(' ');
23
+ const args = typeof options.args === 'function' ? options.args(port) : (options.args ?? []);
24
+ const env = typeof options.env === 'function' ? options.env(port) : options.env;
25
+
26
+ const child = Bun.spawn([...command, ...args], {
27
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
28
+ env: { ...process.env, ...env, PORT: String(port) },
29
+ stdin: 'pipe',
30
+ stdout: 'pipe',
31
+ stderr: 'pipe',
32
+ detached: true,
33
+ });
34
+
35
+ const isRunning = () => child.exitCode === null && child.signalCode === null;
36
+ const log = { all: '', stdout: '', matchedLines: 0 };
37
+
38
+ const drained = Promise.all([
39
+ drainStream(child.stdout, (text) => {
40
+ log.all += text;
41
+ log.stdout += text;
42
+ }),
43
+ drainStream(child.stderr, (text) => {
44
+ log.all += text;
45
+ }),
46
+ ]);
47
+
48
+ const url = `http://127.0.0.1:${port}`;
49
+ const settleOutput = () => Promise.race([drained, Bun.sleep(drainGraceMs)]);
50
+
51
+ const stop = async (signal: Signal = 'SIGTERM'): Promise<number> => {
52
+ signalGroup(child.pid, signal);
53
+
54
+ // A leader that ignores the signal must not hold the stop past the deadline.
55
+ const escalation = setTimeout(() => {
56
+ signalGroup(child.pid, 'SIGKILL');
57
+ }, groupDeadlineMs);
58
+
59
+ let exitCode: number | null;
60
+
61
+ try {
62
+ exitCode = await child.exited;
63
+
64
+ await waitForGroupExit(child.pid);
65
+ } finally {
66
+ clearTimeout(escalation);
67
+ }
68
+
69
+ await settleOutput();
70
+
71
+ return toExitCode(exitCode, child.signalCode);
72
+ };
73
+
74
+ // Each match moves past the line it matched, so the next wait reads only the lines after it.
75
+ const findNextLine = (pattern: string | RegExp): string | null => {
76
+ const lines = log.stdout.split('\n').slice(0, -1);
77
+
78
+ const index = lines.findIndex(
79
+ (line, position) => position >= log.matchedLines && isLineMatch(line, pattern),
80
+ );
81
+
82
+ if (index === -1) {
83
+ return null;
84
+ }
85
+
86
+ log.matchedLines = index + 1;
87
+
88
+ return lines[index] ?? null;
89
+ };
90
+
91
+ const waitForLine = async (
92
+ pattern: string | RegExp,
93
+ lineOptions: WaitForLineOptions = {},
94
+ ): Promise<string> => {
95
+ const timeoutMs = lineOptions.timeoutMs ?? defaultWaitMs;
96
+
97
+ const outcome = await waitForOutcome(() => findNextLine(pattern), {
98
+ deadlineMs: timeoutMs,
99
+ probeExited: () => !isRunning(),
100
+ settleOutput,
101
+ });
102
+
103
+ if (outcome.kind === 'ready') {
104
+ return outcome.value;
105
+ }
106
+
107
+ const reason =
108
+ outcome.kind === 'exited'
109
+ ? `exited before it printed a line that matches ${String(pattern)}`
110
+ : `printed no line that matches ${String(pattern)} in ${timeoutMs} ms`;
111
+
112
+ throw new Error(`${name} ${reason}; its output:\n${log.all}`);
113
+ };
114
+
115
+ const handle: Omit<ProcessHandle, 'readyLine'> = {
116
+ url,
117
+ port,
118
+ pid: child.pid,
119
+ write: async (text) => {
120
+ await child.stdin.write(text);
121
+ await child.stdin.flush();
122
+ },
123
+ waitForLine,
124
+ output: () => log.all,
125
+ stop,
126
+ [Symbol.asyncDispose]: async () => {
127
+ if (isRunning() || probeGroup(child.pid)) {
128
+ await stop('SIGKILL');
129
+ }
130
+ },
131
+ };
132
+
133
+ const ready = options.ready;
134
+
135
+ if (ready === undefined) {
136
+ return { ...handle, readyLine: null };
137
+ }
138
+
139
+ const readyTimeoutMs = options.readyTimeoutMs ?? defaultWaitMs;
140
+
141
+ const outcome = await waitForOutcome(() => readReadyLine(ready, url, findNextLine), {
142
+ deadlineMs: readyTimeoutMs,
143
+ probeExited: () => !isRunning(),
144
+ settleOutput,
145
+ });
146
+
147
+ if (outcome.kind !== 'ready') {
148
+ const exitCode = await stop('SIGKILL');
149
+
150
+ const reason =
151
+ outcome.kind === 'exited'
152
+ ? 'exited before it was ready'
153
+ : `was not ready after ${readyTimeoutMs} ms`;
154
+
155
+ throw new Error(`${name} ${reason} (exit code ${exitCode}); its output:\n${log.all}`);
156
+ }
157
+
158
+ return { ...handle, readyLine: outcome.value.line };
159
+ }
@@ -0,0 +1,84 @@
1
+ export type Signal = 'SIGTERM' | 'SIGINT' | 'SIGHUP' | 'SIGKILL';
2
+
3
+ // Added to the test process's environment. An undefined value removes the variable.
4
+ type Environment = Readonly<Record<string, string | undefined>>;
5
+
6
+ export interface RunOptions {
7
+ readonly args?: readonly string[];
8
+
9
+ readonly env?: Environment;
10
+
11
+ readonly cwd?: string;
12
+
13
+ // Written to the program's stdin, which then closes. Without it, stdin is empty.
14
+ readonly input?: string;
15
+
16
+ // When the program runs longer, its process group gets SIGKILL and the run throws.
17
+ readonly timeoutMs?: number;
18
+ }
19
+
20
+ export interface RunResult {
21
+ readonly exitCode: number;
22
+
23
+ readonly stdout: string;
24
+
25
+ readonly stderr: string;
26
+ }
27
+
28
+ export type Ready =
29
+ | { readonly url: string }
30
+ | { readonly stdout: string | RegExp }
31
+ | { readonly check: () => Promise<boolean> };
32
+
33
+ export interface StartOptions {
34
+ // A function gets the picked port, for a program that takes it by flag.
35
+ readonly args?: readonly string[] | ((port: number) => readonly string[]);
36
+
37
+ // A function gets the picked port, for a program that reads it from another variable. `PORT` is
38
+ // set either way.
39
+ readonly env?: Environment | ((port: number) => Environment);
40
+
41
+ readonly cwd?: string;
42
+
43
+ // The port to give the program. A free port when it is unset.
44
+ readonly port?: number;
45
+
46
+ // How the start knows the program is ready. Without it, the start returns at once.
47
+ readonly ready?: Ready;
48
+
49
+ // How long to wait for the program to be ready; 10 s when it is unset.
50
+ readonly readyTimeoutMs?: number;
51
+ }
52
+
53
+ export interface WaitForLineOptions {
54
+ // How long to wait for a line; 10 s when it is unset.
55
+ readonly timeoutMs?: number;
56
+ }
57
+
58
+ export interface ProcessHandle extends AsyncDisposable {
59
+ // The `http://127.0.0.1:<port>` base the program listens on.
60
+ readonly url: string;
61
+
62
+ readonly port: number;
63
+
64
+ // The program's process ID, which is also the ID of the process group it leads.
65
+ readonly pid: number;
66
+
67
+ // The first whole stdout line that `ready: { stdout }` matched, or null for any other `ready`.
68
+ readonly readyLine: string | null;
69
+
70
+ // Writes to the program's stdin.
71
+ readonly write: (text: string) => Promise<void>;
72
+
73
+ // Resolves with the first whole stdout line after the last line that it or `ready: { stdout }`
74
+ // matched, that matches the pattern.
75
+ readonly waitForLine: (pattern: string | RegExp, options?: WaitForLineOptions) => Promise<string>;
76
+
77
+ // The stdout and stderr so far.
78
+ readonly output: () => string;
79
+
80
+ // Sends the signal, SIGTERM when it is unset, to the program's process group. Waits for the
81
+ // program to exit and the group to empty, with SIGKILL for what is left after 5 s. Returns the
82
+ // exit code, which is 128 plus the signal's number when a signal killed the program.
83
+ readonly stop: (signal?: Signal) => Promise<number>;
84
+ }
@@ -0,0 +1,17 @@
1
+ import { groupDeadlineMs, pollIntervalMs } from './constants.ts';
2
+ import { probeGroup } from './probe-group.ts';
3
+ import { signalGroup } from './signal-group.ts';
4
+
5
+ // A process the program forked can outlive it by a moment, so the wait runs until the group
6
+ // empties, and kills what is left once it passes its deadline.
7
+ export async function waitForGroupExit(groupID: number): Promise<void> {
8
+ const deadline = Date.now() + groupDeadlineMs;
9
+
10
+ while (probeGroup(groupID)) {
11
+ if (Date.now() >= deadline) {
12
+ signalGroup(groupID, 'SIGKILL');
13
+ }
14
+
15
+ await Bun.sleep(pollIntervalMs);
16
+ }
17
+ }
@@ -0,0 +1,63 @@
1
+ import { pollIntervalMs } from './constants.ts';
2
+
3
+ export interface WaitProbes {
4
+ readonly deadlineMs: number;
5
+
6
+ readonly probeExited: () => boolean;
7
+
8
+ // Waits briefly for the output that the program printed before it exited.
9
+ readonly settleOutput: () => Promise<unknown>;
10
+ }
11
+
12
+ export type WaitOutcome<Value> =
13
+ | { readonly kind: 'ready'; readonly value: Value }
14
+ | { readonly kind: 'exited' }
15
+ | { readonly kind: 'timeout' };
16
+
17
+ const pastDeadline = Symbol('pastDeadline');
18
+
19
+ // Polls `read` until it gives a value, the program exits or the deadline passes. After an exit,
20
+ // `read` runs once more on the settled output, so a line printed just before the exit still counts.
21
+ export async function waitForOutcome<Value>(
22
+ read: () => Promise<Value | null> | Value | null,
23
+ probes: WaitProbes,
24
+ ): Promise<WaitOutcome<Value>> {
25
+ const deadline = Date.now() + probes.deadlineMs;
26
+
27
+ while (Date.now() < deadline) {
28
+ const hasExited = probes.probeExited();
29
+
30
+ if (hasExited) {
31
+ await probes.settleOutput();
32
+ }
33
+
34
+ // A read that outlasts the deadline counts for nothing, and one that never settles must not
35
+ // hold the wait past it.
36
+ const remainingMs = Math.max(deadline - Date.now(), 0);
37
+
38
+ const value = await Promise.race([read(), waitPastDeadline(remainingMs)]);
39
+
40
+ // A read that blocked the event loop can win the race and still finish past the deadline.
41
+ if (value === pastDeadline || Date.now() >= deadline) {
42
+ return { kind: 'timeout' };
43
+ }
44
+
45
+ if (value !== null) {
46
+ return { kind: 'ready', value };
47
+ }
48
+
49
+ if (hasExited) {
50
+ return { kind: 'exited' };
51
+ }
52
+
53
+ await Bun.sleep(pollIntervalMs);
54
+ }
55
+
56
+ return { kind: 'timeout' };
57
+ }
58
+
59
+ async function waitPastDeadline(remainingMs: number): Promise<typeof pastDeadline> {
60
+ await Bun.sleep(remainingMs);
61
+
62
+ return pastDeadline;
63
+ }
@@ -0,0 +1,16 @@
1
+ import { constants } from 'node:os';
2
+
3
+ // The exit code of a program, which is 128 plus the signal's number when a signal killed it.
4
+ export function toExitCode(exitCode: number, signal: number | string | null | undefined): number {
5
+ if (signal === null || signal === undefined || signal === 0) {
6
+ return exitCode;
7
+ }
8
+
9
+ if (typeof signal === 'number') {
10
+ return 128 + signal;
11
+ }
12
+
13
+ const number = Object.entries(constants.signals).find(([name]) => name === signal)?.[1];
14
+
15
+ return number === undefined ? exitCode : 128 + number;
16
+ }