@kud/cli-shot 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Erwann Mest
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 ADDED
@@ -0,0 +1,115 @@
1
+ <div align="center">
2
+
3
+ # ๐Ÿ“ธ cli-shot
4
+
5
+ <img src="https://img.shields.io/npm/v/@kud/cli-shot?style=flat-square" alt="npm version" />
6
+ <img src="https://img.shields.io/badge/licence-MIT-blue?style=flat-square" alt="MIT licence" />
7
+ <img src="https://img.shields.io/badge/node-%3E%3D20-brightgreen?style=flat-square" alt="Node >=20" />
8
+
9
+ **Automatic screenshots of interactive CLIs โ€” pty capture, terminal emulation, PNG out.**
10
+
11
+ [Website](https://kud.io/projects/cli-shot) ยท
12
+ [Documentation](https://kud.io/projects/cli-shot/docs) ยท
13
+ [npm](https://www.npmjs.com/package/@kud/cli-shot)
14
+
15
+ </div>
16
+
17
+ Point it at a CLI. It asks which screens the CLI has, opens each one, and writes
18
+ an image per screen. No per-project script, no keystroke tables, no hand-cropped
19
+ window captures that go stale the next time the UI moves.
20
+
21
+ ## Features
22
+
23
+ - **Screens discovered, not hardcoded** โ€” asks the CLI via `--screen list`, so a tab you add shows up in the next run without touching this package
24
+ - **Real terminal emulation** โ€” the pty stream is resolved to the grid a user would see, rather than every redraw concatenated
25
+ - **Fixtures by default** โ€” `--mock` is on unless you opt out, because a screenshot outlives the moment it was taken
26
+ - **Deterministic and headless** โ€” fixed size, fixed data, no window manager, runnable in CI
27
+ - **Scriptable last mile** โ€” `--keys` reaches state a screen name can't address
28
+
29
+ ## Install
30
+
31
+ ```sh
32
+ npm install --global @kud/cli-shot
33
+ brew install charmbracelet/tap/freeze # the renderer
34
+ ```
35
+
36
+ ## Usage
37
+
38
+ ```sh
39
+ cli-shot --out assets/screenshots -- pcloud
40
+ ```
41
+
42
+ Everything after `--` is the command being driven. That separation matters: it
43
+ lets the driven CLI have its own `--mock` or `--screen` without colliding with
44
+ cli-shot's flags.
45
+
46
+ ```sh
47
+ cli-shot --out shots --screen sync -- pcloud # one screen
48
+ cli-shot --out shots --list -- pcloud # what screens exist
49
+ cli-shot --out shots --keys $'jjj\r' -- pcloud # drive deeper first
50
+ cli-shot --out shots --no-mock -- pcloud # real data (careful)
51
+ ```
52
+
53
+ | flag | |
54
+ | --------------------- | ----------------------------------------------------- |
55
+ | `-o, --out <dir>` | directory to write PNGs into |
56
+ | `-s, --screen <name>` | shoot one screen instead of every screen |
57
+ | `--list` | print the screens the command offers, and stop |
58
+ | `--cols` / `--rows` | terminal size (default 110ร—32) |
59
+ | `--settle <ms>` | silence that counts as finished drawing (default 800) |
60
+ | `--keys <sequence>` | keystrokes sent once the screen has drawn |
61
+ | `--no-mock` | drive real data instead of fixtures |
62
+
63
+ ## The contract
64
+
65
+ A CLI is shootable when it implements three things:
66
+
67
+ | | |
68
+ | ----------------- | ------------------------------------------------------ |
69
+ | `--mock` | swap **every** data source to fixtures, all or nothing |
70
+ | `--screen <name>` | open directly on that screen |
71
+ | `--screen list` | print the screen names, one per line |
72
+
73
+ `--screen list` is what keeps this package generic: cli-shot asks rather than
74
+ knowing. Add a tab to your app and it appears in the next run's output without
75
+ this package being touched โ€” and a tab nobody ever captured stops being
76
+ invisible.
77
+
78
+ Mock data is the default, deliberately. A folder listing says more about someone
79
+ than they usually intend, and a screenshot outlives the moment it was taken.
80
+
81
+ ## How it works
82
+
83
+ ```
84
+ node-pty โ†’ @xterm/headless โ†’ serialize โ†’ freeze โ†’ png
85
+ ```
86
+
87
+ The middle step is the one that isn't obvious. A pty hands back **every redraw
88
+ in order**, not a picture of the screen โ€” write that straight out and you render
89
+ the whole animation concatenated, with the alternate-screen escape on top. So
90
+ the stream is fed through a real terminal emulator, which resolves cursor moves,
91
+ clears and repaints into the grid a user would actually be looking at. Only that
92
+ grid is serialised.
93
+
94
+ ## Limits
95
+
96
+ **Terminal graphics protocols don't survive.** Inline images (iTerm2, sixel) are
97
+ escape sequences carrying base64 payloads; no ANSI renderer can rasterise them.
98
+ A CLI drawing thumbnails needs a real terminal and a window capture for those
99
+ screens.
100
+
101
+ **Compound state needs `--keys`.** `--screen` addresses which screen; scroll
102
+ position, an open dialog or a filtered view are beyond what a name can carry.
103
+
104
+ ## Related
105
+
106
+ - [@kud/cli-testing](https://github.com/kud/cli-testing) โ€” the test-side sibling.
107
+ Same app contract, no dependency between them.
108
+
109
+ ## Licence
110
+
111
+ MIT ยฉ Erwann Mest
112
+
113
+ ---
114
+
115
+ ๐Ÿ“š **Full documentation โ†’ [cli-shot/docs](https://kud.io/projects/cli-shot/docs)**
@@ -0,0 +1,160 @@
1
+ import { dirname, join } from 'path';
2
+ import { mkdirSync, existsSync, accessSync, constants } from 'fs';
3
+ import { createRequire } from 'module';
4
+ import { spawn } from 'node-pty';
5
+ import headless from '@xterm/headless';
6
+ import { SerializeAddon } from '@xterm/addon-serialize';
7
+ import { execFileSync } from 'child_process';
8
+
9
+ // src/index.ts
10
+ var { Terminal } = headless;
11
+ var explainSpawnFailure = (error, command) => {
12
+ const message = error instanceof Error ? error.message : String(error);
13
+ const helper = helperPath();
14
+ const notExecutable = message.includes("posix_spawnp") && helper !== void 0 && !isExecutable(helper);
15
+ return new Error(
16
+ `Could not open a pty for ${command}: ${message}
17
+ ` + (notExecutable ? ` node-pty's helper is not executable. Fix with:
18
+ chmod +x ${helper}
19
+ It ships without the mode bit when install scripts are blocked;
20
+ npm approve-scripts node-pty makes it survive a reinstall.` : ` Check that the command exists and is executable.`),
21
+ { cause: error }
22
+ );
23
+ };
24
+ var helperPath = () => {
25
+ const candidate = createRequire(import.meta.url).resolve("node-pty").replace(
26
+ /node-pty\/.*$/,
27
+ `node-pty/prebuilds/${process.platform}-${process.arch}/spawn-helper`
28
+ );
29
+ return existsSync(candidate) ? candidate : void 0;
30
+ };
31
+ var isExecutable = (path) => {
32
+ try {
33
+ accessSync(path, constants.X_OK);
34
+ return true;
35
+ } catch {
36
+ return false;
37
+ }
38
+ };
39
+ var capture = (command, args = [], {
40
+ cols = 110,
41
+ rows = 32,
42
+ settle = 800,
43
+ timeout = 15e3,
44
+ env,
45
+ keys
46
+ } = {}) => new Promise((resolve, reject) => {
47
+ const term = new Terminal({ cols, rows, allowProposedApi: true });
48
+ const serializer = new SerializeAddon();
49
+ term.loadAddon(serializer);
50
+ let pty;
51
+ try {
52
+ pty = spawn(command, [...args], {
53
+ name: "xterm-256color",
54
+ cols,
55
+ rows,
56
+ env: { ...process.env, ...env }
57
+ });
58
+ } catch (error) {
59
+ reject(explainSpawnFailure(error, command));
60
+ return;
61
+ }
62
+ let raw = 0;
63
+ let idle;
64
+ let sentKeys = false;
65
+ let finished = false;
66
+ const finish = () => {
67
+ if (finished) return;
68
+ finished = true;
69
+ clearTimeout(idle);
70
+ clearTimeout(hard);
71
+ try {
72
+ pty.kill();
73
+ } catch {
74
+ }
75
+ term.write("", () => resolve(serializer.serialize()));
76
+ };
77
+ const drawn = () => {
78
+ const buffer = term.buffer.active;
79
+ for (let y = 0; y < buffer.length; y++) {
80
+ if ((buffer.getLine(y)?.translateToString(true) ?? "").trim())
81
+ return true;
82
+ }
83
+ return false;
84
+ };
85
+ const onSettled = () => {
86
+ if (!drawn()) {
87
+ idle = setTimeout(onSettled, settle);
88
+ return;
89
+ }
90
+ if (keys && !sentKeys) {
91
+ sentKeys = true;
92
+ pty.write(keys);
93
+ idle = setTimeout(onSettled, settle);
94
+ return;
95
+ }
96
+ finish();
97
+ };
98
+ const hard = setTimeout(finish, timeout);
99
+ pty.onData((data) => {
100
+ raw += data.length;
101
+ term.write(data);
102
+ clearTimeout(idle);
103
+ idle = setTimeout(onSettled, settle);
104
+ });
105
+ pty.onExit(({ exitCode }) => {
106
+ clearTimeout(idle);
107
+ if (exitCode !== 0 && raw === 0) {
108
+ finished = true;
109
+ clearTimeout(hard);
110
+ reject(
111
+ explainSpawnFailure(
112
+ new Error(`exited ${exitCode} without drawing anything`),
113
+ command
114
+ )
115
+ );
116
+ return;
117
+ }
118
+ idle = setTimeout(onSettled, 0);
119
+ });
120
+ });
121
+ var listScreens = (command, args = []) => {
122
+ const printed = execFileSync(command, [...args, "--screen", "list"], {
123
+ encoding: "utf8"
124
+ });
125
+ return printed.split("\n").map((line) => line.trim()).filter(Boolean);
126
+ };
127
+ var toImage = (ansi, output, { freezeArgs = [] } = {}) => {
128
+ const args = ["--language", "ansi", "--output", output, ...freezeArgs];
129
+ mkdirSync(dirname(output), { recursive: true });
130
+ try {
131
+ execFileSync("freeze", args, { input: ansi });
132
+ return output;
133
+ } catch (error) {
134
+ const detail = String(error.stdout ?? "").trim();
135
+ throw new Error(
136
+ `freeze failed for ${output}
137
+ command: freeze ${args.join(" ")}
138
+ input: ${ansi.length} chars over stdin
139
+ ` + (detail ? ` said: ${detail.replace(/\s+/g, " ")}` : ""),
140
+ { cause: error }
141
+ );
142
+ }
143
+ };
144
+
145
+ // src/index.ts
146
+ var screenArgs = (args, screen, mock) => [...args, ...mock ? ["--mock"] : [], "--screen", screen];
147
+ var shootScreen = async (screen, { command, args = [], out, mock = true, ...rest }) => {
148
+ const ansi = await capture(command, screenArgs(args, screen, mock), rest);
149
+ return toImage(ansi, join(out, `${screen}.png`), rest);
150
+ };
151
+ var shootAll = async (options) => {
152
+ const screens = listScreens(options.command, options.args ?? []);
153
+ const written = [];
154
+ for (const screen of screens) {
155
+ written.push(await shootScreen(screen, options));
156
+ }
157
+ return written;
158
+ };
159
+
160
+ export { capture, listScreens, shootAll, shootScreen, toImage };
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.js ADDED
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ import { listScreens, shootScreen, shootAll } from './chunk-AE27RX6D.js';
3
+ import { Command } from 'commander';
4
+
5
+ var separator = process.argv.indexOf("--");
6
+ var driven = separator === -1 ? [] : process.argv.slice(separator + 1);
7
+ var own = separator === -1 ? process.argv : process.argv.slice(0, separator);
8
+ var program = new Command();
9
+ program.name("cli-shot").description(
10
+ "Screenshot an interactive CLI, one image per screen.\n\nThe command to drive follows `--`:\n cli-shot --out assets/screenshots -- pcloud"
11
+ ).requiredOption("-o, --out <dir>", "directory to write PNGs into").option("-s, --screen <name>", "shoot one screen instead of every screen").option("--list", "print the screens the command offers, and stop").option("--cols <n>", "terminal columns", "110").option("--rows <n>", "terminal rows", "32").option("--settle <ms>", "silence that counts as finished drawing", "800").option("--keys <sequence>", "keystrokes to send once the screen has drawn").option("--no-mock", "drive real data instead of fixtures").parse(own);
12
+ var options = program.opts();
13
+ if (driven.length === 0) {
14
+ console.error(
15
+ "No command to drive. Put it after `--`, e.g.\n cli-shot --out shots -- pcloud"
16
+ );
17
+ process.exit(1);
18
+ }
19
+ var [command, ...args] = driven;
20
+ var shoot = {
21
+ command,
22
+ args,
23
+ out: options.out,
24
+ mock: options.mock,
25
+ cols: Number(options.cols),
26
+ rows: Number(options.rows),
27
+ settle: Number(options.settle),
28
+ keys: options.keys
29
+ };
30
+ if (options.list) {
31
+ console.log(listScreens(command, args).join("\n"));
32
+ process.exit(0);
33
+ }
34
+ var written = options.screen ? [await shootScreen(options.screen, shoot)] : await shootAll(shoot);
35
+ for (const path of written) console.log(path);
@@ -0,0 +1,39 @@
1
+ type CaptureOptions = {
2
+ cols?: number;
3
+ rows?: number;
4
+ /** Milliseconds of silence that count as "finished drawing". */
5
+ settle?: number;
6
+ /** Hard limit before the child is killed regardless. */
7
+ timeout?: number;
8
+ env?: NodeJS.ProcessEnv;
9
+ /** Keystrokes sent once the first draw has settled, for state a flag cannot name. */
10
+ keys?: string;
11
+ };
12
+ declare const capture: (command: string, args?: readonly string[], { cols, rows, settle, timeout, env, keys, }?: CaptureOptions) => Promise<string>;
13
+
14
+ type RenderOptions = {
15
+ /** Extra flags passed straight to freeze, e.g. ["--theme", "nord"]. */
16
+ freezeArgs?: readonly string[];
17
+ };
18
+ declare const toImage: (ansi: string, output: string, { freezeArgs }?: RenderOptions) => string;
19
+
20
+ declare const listScreens: (command: string, args?: readonly string[]) => string[];
21
+
22
+ type ShootOptions = CaptureOptions & RenderOptions & {
23
+ /** The CLI to drive. */
24
+ command: string;
25
+ /** Arguments before the ones this adds. */
26
+ args?: readonly string[];
27
+ /** Directory the PNGs are written to. */
28
+ out: string;
29
+ /**
30
+ * Drive from fixtures. On by default, and it should stay that way: a
31
+ * folder listing says more about someone than they usually intend, and a
32
+ * screenshot outlives the moment it was taken.
33
+ */
34
+ mock?: boolean;
35
+ };
36
+ declare const shootScreen: (screen: string, { command, args, out, mock, ...rest }: ShootOptions) => Promise<string>;
37
+ declare const shootAll: (options: ShootOptions) => Promise<string[]>;
38
+
39
+ export { type CaptureOptions, type RenderOptions, type ShootOptions, capture, listScreens, shootAll, shootScreen, toImage };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { capture, listScreens, shootAll, shootScreen, toImage } from './chunk-AE27RX6D.js';
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@kud/cli-shot",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Automatic screenshots of interactive CLIs โ€” pty capture, terminal emulation, PNG out",
6
+ "license": "MIT",
7
+ "homepage": "https://kud.io/projects/cli-shot",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/kud/cli-shot.git"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "scripts": {
27
+ "build": "tsup",
28
+ "dev": "tsup --watch",
29
+ "typecheck": "tsc --noEmit",
30
+ "test": "vitest run",
31
+ "test:watch": "vitest"
32
+ },
33
+ "dependencies": {
34
+ "@xterm/addon-serialize": "0.14.0",
35
+ "@xterm/headless": "6.0.0",
36
+ "commander": "15.0.0",
37
+ "node-pty": "1.1.0"
38
+ },
39
+ "devDependencies": {
40
+ "@types/node": "22.20.1",
41
+ "tsup": "8.5.1",
42
+ "typescript": "5.9.3",
43
+ "vitest": "4.1.10"
44
+ },
45
+ "allowScripts": {
46
+ "node-pty@1.1.0": true
47
+ },
48
+ "bin": {
49
+ "cli-shot": "dist/cli.js"
50
+ }
51
+ }