@kud/cli-shot 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2014 Ryan L McIntyre
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.
@@ -0,0 +1,21 @@
1
+ Symbols Nerd Font Mono, from Nerd Fonts v3.5.1 (https://github.com/ryanoasis/nerd-fonts),
2
+ converted from TTF to WOFF2 without other changes. The font is MIT-licensed
3
+ (see LICENSE); the icon sets it carries keep their own licences:
4
+
5
+ | Icon set name | upstream | version | license |
6
+ |------------------------|-------------------------------------------------------|-----------------|-------------|
7
+ | Codicons | https://github.com/microsoft/vscode-codicons | 0.0.45 | CC BY 4.0 |
8
+ | Devicons | https://github.com/devicons/devicon | 2.17.0 | MIT |
9
+ | extraglyphs | https://github.com/source-foundry/Hack | - | MIT |
10
+ | Font Awesome | https://github.com/FortAwesome/Font-Awesome | 6.5.1 | CC BY 4.0 |
11
+ | Font Awesome Extension | https://github.com/AndreLZGava/font-awesome-extension | 0.0.3 | MIT |
12
+ | Font Logos | https://github.com/lukas-w/font-logos | 1.3.0 | unlicensed |
13
+ | MaterialDesign | https://github.com/Templarian/MaterialDesign-Font | Oct 6, 2022 | Apache 2.0 |
14
+ | Octicons | https://github.com/primer/octicons | 18.3.0 | MIT |
15
+ | Seti and original | https://github.com/jesseweed/seti-ui | 0.8.1 | MIT |
16
+ | Pomicons | https://github.com/gabrielelana/pomicons | 1.001 | OFL 1.1 RFN |
17
+ | Powerline Extra | https://github.com/ryanoasis/powerline-extra-symbols | 1.200 | MIT |
18
+ | Powerline Symbols | https://github.com/powerline/powerline | 1.000 (ca 2013) | MIT |
19
+ | Power Symbols IEC | https://github.com/jloughry/Unicode | Feb 2015 | MIT |
20
+ | Weather Icons | https://github.com/erikflowers/weather-icons | 2.0.10 (1.100) | OFL 1.1 |
21
+
@@ -0,0 +1,37 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>{{title}}</title>
7
+ {{base}}
8
+ <script>
9
+ // ?theme=light|dark pins the chrome; anything else follows the system.
10
+ {
11
+ const theme = new URLSearchParams(location.search).get("theme")
12
+ if (theme === "light" || theme === "dark") {
13
+ document.documentElement.dataset.theme = theme
14
+ }
15
+ if (new URLSearchParams(location.search).has("capture")) {
16
+ document.documentElement.dataset.capture = ""
17
+ }
18
+ }
19
+ </script>
20
+ <link
21
+ rel="preload"
22
+ href="assets/fonts/SymbolsNerdFontMono-Regular.woff2"
23
+ as="font"
24
+ type="font/woff2"
25
+ crossorigin
26
+ />
27
+ <link rel="stylesheet" href="assets/xterm.css" />
28
+ <link rel="stylesheet" href="assets/chrome.css" />
29
+ <script type="module" src="assets/player.js"></script>
30
+ </head>
31
+ <body>
32
+ <main class="demo">
33
+ <h1 class="visually-hidden">{{title}}</h1>
34
+ {{screens}}
35
+ </main>
36
+ </body>
37
+ </html>
@@ -0,0 +1,267 @@
1
+ // Replays the asciicast v2 recordings named on the page into xterm.js — the
2
+ // same emulator, in its browser build, that resolved the capture, so the last
3
+ // frame here is the frame the PNG shows. Replay only: no input reaches the
4
+ // terminal, and nothing is ever executed.
5
+ import { Terminal } from "./xterm.mjs"
6
+
7
+ const SPEEDS = [1, 2]
8
+ const ANSI = [
9
+ "black",
10
+ "red",
11
+ "green",
12
+ "yellow",
13
+ "blue",
14
+ "magenta",
15
+ "cyan",
16
+ "white",
17
+ "brightBlack",
18
+ "brightRed",
19
+ "brightGreen",
20
+ "brightYellow",
21
+ "brightBlue",
22
+ "brightMagenta",
23
+ "brightCyan",
24
+ "brightWhite",
25
+ ]
26
+
27
+ const root = document.documentElement
28
+ const token = (name) => getComputedStyle(root).getPropertyValue(name).trim()
29
+
30
+ // Every colour comes from chrome.css, so the palette has one home.
31
+ const theme = () => ({
32
+ background: token("--term-bg"),
33
+ foreground: token("--term-fg"),
34
+ cursor: token("--term-cursor"),
35
+ cursorAccent: token("--term-bg"),
36
+ selectionBackground: token("--term-selection"),
37
+ ...Object.fromEntries(
38
+ ANSI.map((name, i) => [name, token(`--term-ansi-${i}`)]),
39
+ ),
40
+ })
41
+
42
+ export const parseCast = (text) => {
43
+ const [first, ...rest] = text.split("\n").filter((line) => line.trim())
44
+ const header = JSON.parse(first)
45
+ if (header.version !== 2) {
46
+ throw new Error(`unsupported asciicast version ${header.version}`)
47
+ }
48
+
49
+ // idle_time_limit shortens long pauses — applied once here so playback
50
+ // only ever deals with final times.
51
+ const limit = header.idle_time_limit
52
+ let shift = 0
53
+ let previous = 0
54
+ const events = []
55
+ for (const line of rest) {
56
+ const [time, code, data] = JSON.parse(line)
57
+ if (limit !== undefined && time - previous > limit) {
58
+ shift += time - previous - limit
59
+ }
60
+ previous = time
61
+ if (code === "o" || code === "r") events.push([time - shift, code, data])
62
+ }
63
+ return { header, events }
64
+ }
65
+
66
+ const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)")
67
+
68
+ // ?capture is how --format gif and mp4 film the page: nothing plays on its
69
+ // own, and the recording is stepped from outside, one frame at a time, so the
70
+ // result depends on the recording's clock rather than the browser's.
71
+ const capturing = new URLSearchParams(location.search).has("capture")
72
+
73
+ const mount = async (figure) => {
74
+ const host = figure.querySelector(".window-term")
75
+ const response = await fetch(figure.dataset.cast)
76
+ if (!response.ok) throw new Error(`${figure.dataset.cast}: ${response.status}`)
77
+ const { header, events } = parseCast(await response.text())
78
+
79
+ const fontSize = Number(token("--term-font-size")) || 14
80
+ const term = new Terminal({
81
+ cols: header.width,
82
+ rows: header.height,
83
+ fontFamily: token("--term-font"),
84
+ fontSize,
85
+ lineHeight: Number(token("--term-line-height")) || 1,
86
+ theme: theme(),
87
+ disableStdin: true,
88
+ cursorBlink: false,
89
+ cursorInactiveStyle: "block",
90
+ scrollback: 0,
91
+ })
92
+ term.open(host)
93
+ // Nothing to type into: keep the hidden textarea out of the tab order.
94
+ host.querySelector("textarea")?.setAttribute("tabindex", "-1")
95
+
96
+ // Scale rather than reflow. The recording was made at a fixed size, and
97
+ // re-wrapping it to a phone's width would draw a screen that never existed.
98
+ const fit = () => {
99
+ const screen = term.element.querySelector(".xterm-screen")
100
+ const width = screen.offsetWidth
101
+ const height = screen.offsetHeight
102
+ host.style.setProperty("--term-width", `${width}px`)
103
+ const scale = Math.min(1, host.clientWidth / width)
104
+ term.element.style.transform = scale < 1 ? `scale(${scale})` : ""
105
+ host.style.height = `${Math.ceil(height * scale)}px`
106
+ }
107
+ fit()
108
+ new ResizeObserver(fit).observe(figure.parentElement)
109
+
110
+ // Playback runs on the recording's own clock, so pausing and changing speed
111
+ // carry on from the same moment rather than restarting it.
112
+ const controls = {
113
+ toggle: figure.querySelector('[data-action="toggle"]'),
114
+ restart: figure.querySelector('[data-action="restart"]'),
115
+ speed: figure.querySelector('[data-action="speed"]'),
116
+ }
117
+ let timer
118
+ let next = 0
119
+ let position = 0
120
+ let speed = SPEEDS[0]
121
+ let playing = false
122
+ let ticked = 0
123
+
124
+ const apply = ([, code, data]) => {
125
+ if (code === "o") term.write(data)
126
+ else {
127
+ const [cols, rows] = data.split("x").map(Number)
128
+ if (cols && rows) term.resize(cols, rows)
129
+ }
130
+ }
131
+
132
+ const setPlaying = (value) => {
133
+ playing = value
134
+ figure.dataset.state = value ? "playing" : "paused"
135
+ controls.toggle?.setAttribute("aria-label", value ? "Pause" : "Play")
136
+ }
137
+
138
+ const rewind = () => {
139
+ term.reset()
140
+ term.resize(header.width, header.height)
141
+ next = 0
142
+ position = 0
143
+ }
144
+
145
+ const advance = () => {
146
+ const now = performance.now()
147
+ position += ((now - ticked) / 1000) * speed
148
+ ticked = now
149
+ }
150
+
151
+ const step = () => {
152
+ advance()
153
+ while (next < events.length && events[next][0] <= position) apply(events[next++])
154
+ if (next < events.length) {
155
+ timer = setTimeout(step, ((events[next][0] - position) / speed) * 1000)
156
+ } else {
157
+ setPlaying(false)
158
+ }
159
+ }
160
+
161
+ const play = () => {
162
+ clearTimeout(timer)
163
+ if (next >= events.length) rewind()
164
+ setPlaying(true)
165
+ ticked = performance.now()
166
+ step()
167
+ }
168
+
169
+ const pause = () => {
170
+ if (!playing) return
171
+ clearTimeout(timer)
172
+ advance()
173
+ setPlaying(false)
174
+ }
175
+
176
+ // Before anything plays, the window holds the last frame: the screen the
177
+ // PNG shows, never an empty terminal.
178
+ const showLast = () => {
179
+ rewind()
180
+ events.forEach(apply)
181
+ next = events.length
182
+ setPlaying(false)
183
+ }
184
+
185
+ controls.toggle?.addEventListener("click", () => (playing ? pause() : play()))
186
+ controls.restart?.addEventListener("click", () => {
187
+ rewind()
188
+ play()
189
+ })
190
+ controls.speed?.addEventListener("click", () => {
191
+ if (playing) advance()
192
+ speed = SPEEDS[(SPEEDS.indexOf(speed) + 1) % SPEEDS.length]
193
+ const other = SPEEDS[(SPEEDS.indexOf(speed) + 1) % SPEEDS.length]
194
+ controls.speed.textContent = `${speed}×`
195
+ controls.speed.setAttribute(
196
+ "aria-label",
197
+ `Playback speed ${speed}×, switch to ${other}×`,
198
+ )
199
+ if (playing) {
200
+ clearTimeout(timer)
201
+ step()
202
+ }
203
+ })
204
+
205
+ if (capturing) {
206
+ rewind()
207
+ window.cliShotCapture = {
208
+ times: events.map(([time]) => time),
209
+ // Applies events up to `count`, then waits for xterm to parse them and
210
+ // for two frames to paint, so a screenshot taken next shows them.
211
+ until: (count) =>
212
+ new Promise((resolve) => {
213
+ while (next < count) apply(events[next++])
214
+ term.write("", () =>
215
+ requestAnimationFrame(() => requestAnimationFrame(resolve)),
216
+ )
217
+ }),
218
+ }
219
+ figure.dataset.capture = "ready"
220
+ return
221
+ }
222
+
223
+ showLast()
224
+
225
+ // Plays once, the first time it scrolls into view, and never on its own
226
+ // under reduced motion. Leaving view mid-play pauses it; coming back resumes.
227
+ let autoplayed = false
228
+ let pausedByScroll = false
229
+ new IntersectionObserver(
230
+ ([entry]) => {
231
+ if (entry.isIntersecting) {
232
+ if (!autoplayed && !reducedMotion.matches) {
233
+ autoplayed = true
234
+ rewind()
235
+ play()
236
+ } else if (pausedByScroll) {
237
+ pausedByScroll = false
238
+ play()
239
+ }
240
+ } else if (playing) {
241
+ pausedByScroll = true
242
+ pause()
243
+ }
244
+ },
245
+ { threshold: 0.5 },
246
+ ).observe(figure)
247
+ }
248
+
249
+ const start = async () => {
250
+ // xterm measures its cell from the font in place when it opens; measuring
251
+ // before the icon font arrives would size the grid against a fallback.
252
+ const size = `${token("--term-font-size") || 14}px`
253
+ await Promise.allSettled([
254
+ document.fonts.load(`${size} "Symbols Nerd Font Mono"`, ""),
255
+ document.fonts.load(`${size} ${token("--term-font")}`, "W"),
256
+ ])
257
+
258
+ for (const figure of document.querySelectorAll(".window[data-cast]")) {
259
+ mount(figure).catch((error) => {
260
+ figure.querySelector(".window-term").textContent =
261
+ `Could not load this recording (${error.message}).`
262
+ console.error(error)
263
+ })
264
+ }
265
+ }
266
+
267
+ start()
@@ -1,202 +0,0 @@
1
- import { cpus } from 'os';
2
- import { dirname, join } from 'path';
3
- import { mkdirSync, existsSync, accessSync, constants } from 'fs';
4
- import { createRequire } from 'module';
5
- import { spawn } from 'node-pty';
6
- import headless from '@xterm/headless';
7
- import { SerializeAddon } from '@xterm/addon-serialize';
8
- import { execFileSync } from 'child_process';
9
-
10
- // src/index.ts
11
- var { Terminal } = headless;
12
- var TICK_MS = 60;
13
- var HELPER_FAILURE = /execvp\(\d\) failed|posix_spawnp failed/;
14
- var explainSpawnFailure = (error, command) => {
15
- const message = error instanceof Error ? error.message : String(error);
16
- const helper = helperPath();
17
- const notExecutable = message.includes("posix_spawnp") && helper !== void 0 && !isExecutable(helper);
18
- return new Error(
19
- `Could not open a pty for ${command}: ${message}
20
- ` + (notExecutable ? ` node-pty's helper is not executable. Fix with:
21
- chmod +x ${helper}
22
- It ships without the mode bit when install scripts are blocked;
23
- npm approve-scripts node-pty makes it survive a reinstall.` : ` Check that the command exists and is executable.`),
24
- { cause: error }
25
- );
26
- };
27
- var helperPath = () => {
28
- const candidate = createRequire(import.meta.url).resolve("node-pty").replace(
29
- /node-pty\/.*$/,
30
- `node-pty/prebuilds/${process.platform}-${process.arch}/spawn-helper`
31
- );
32
- return existsSync(candidate) ? candidate : void 0;
33
- };
34
- var isExecutable = (path) => {
35
- try {
36
- accessSync(path, constants.X_OK);
37
- return true;
38
- } catch {
39
- return false;
40
- }
41
- };
42
- var capture = (command, args = [], {
43
- cols = 110,
44
- rows = 32,
45
- settle = 350,
46
- timeout = 15e3,
47
- env,
48
- keys
49
- } = {}) => new Promise((resolve, reject) => {
50
- const term = new Terminal({ cols, rows, allowProposedApi: true });
51
- const serializer = new SerializeAddon();
52
- term.loadAddon(serializer);
53
- let pty;
54
- try {
55
- pty = spawn(command, [...args], {
56
- name: "xterm-256color",
57
- cols,
58
- rows,
59
- env: { ...process.env, ...env }
60
- });
61
- } catch (error) {
62
- reject(explainSpawnFailure(error, command));
63
- return;
64
- }
65
- let raw = 0;
66
- let rawText = "";
67
- let sentKeys = false;
68
- let finished = false;
69
- let previous = "";
70
- const finish = () => {
71
- if (finished) return;
72
- finished = true;
73
- clearInterval(poll);
74
- clearTimeout(hard);
75
- try {
76
- pty.kill();
77
- } catch {
78
- }
79
- term.write("", () => resolve(serializer.serialize()));
80
- };
81
- const grid = () => {
82
- const buffer = term.buffer.active;
83
- const lines = [];
84
- for (let y = 0; y < buffer.length; y++) {
85
- lines.push(buffer.getLine(y)?.translateToString(true) ?? "");
86
- }
87
- return lines.join("\n");
88
- };
89
- let stableFor = 0;
90
- const poll = setInterval(() => {
91
- const current = grid();
92
- if (current !== previous || !current.trim()) {
93
- previous = current;
94
- stableFor = 0;
95
- return;
96
- }
97
- stableFor += TICK_MS;
98
- if (stableFor < settle) return;
99
- if (keys && !sentKeys) {
100
- sentKeys = true;
101
- pty.write(keys);
102
- previous = "";
103
- stableFor = 0;
104
- return;
105
- }
106
- finish();
107
- }, TICK_MS);
108
- const hard = setTimeout(finish, timeout);
109
- pty.onData((data) => {
110
- raw += data.length;
111
- if (rawText.length < 2048) rawText += data;
112
- term.write(data);
113
- });
114
- pty.onExit(({ exitCode }) => {
115
- if (exitCode !== 0 && (raw === 0 || HELPER_FAILURE.test(rawText))) {
116
- finished = true;
117
- clearInterval(poll);
118
- clearTimeout(hard);
119
- reject(
120
- explainSpawnFailure(
121
- new Error(`the command exited ${exitCode} without drawing a screen`),
122
- command
123
- )
124
- );
125
- return;
126
- }
127
- finish();
128
- });
129
- });
130
- var listScreens = (command, args = []) => {
131
- const printed = execFileSync(command, [...args, "--screen", "list"], {
132
- encoding: "utf8"
133
- });
134
- return printed.split("\n").map((line) => line.trim()).filter(Boolean);
135
- };
136
- var DEFAULT_FONT = "JetBrainsMono Nerd Font Mono";
137
- var toImage = (ansi, output, { font = DEFAULT_FONT, freezeArgs = [] } = {}) => {
138
- const args = [
139
- "--language",
140
- "ansi",
141
- "--output",
142
- output,
143
- "--font.family",
144
- font,
145
- ...freezeArgs
146
- ];
147
- mkdirSync(dirname(output), { recursive: true });
148
- try {
149
- execFileSync("freeze", args, { input: ansi });
150
- return output;
151
- } catch (error) {
152
- const detail = String(error.stdout ?? "").trim();
153
- throw new Error(
154
- `freeze failed for ${output}
155
- command: freeze ${args.join(" ")}
156
- input: ${ansi.length} chars over stdin
157
- ` + (detail ? ` said: ${detail.replace(/\s+/g, " ")}` : ""),
158
- { cause: error }
159
- );
160
- }
161
- };
162
-
163
- // src/index.ts
164
- var drivenScreen = (args) => {
165
- const at = args.indexOf("--screen");
166
- return at === -1 ? void 0 : args[at + 1];
167
- };
168
- var screenArgs = (args, screen, mock) => [
169
- ...args,
170
- ...mock && !args.includes("--mock") ? ["--mock"] : [],
171
- ...drivenScreen(args) === void 0 ? ["--screen", screen] : []
172
- ];
173
- var shootScreen = async (screen, { command, args = [], out, mock = true, ...rest }) => {
174
- const ansi = await capture(command, screenArgs(args, screen, mock), rest);
175
- return toImage(ansi, join(out, `${screen}.png`), rest);
176
- };
177
- var defaultConcurrency = () => Math.max(2, Math.min(8, cpus().length));
178
- var pool = async (items, limit, run) => {
179
- const results = new Array(items.length);
180
- let next = 0;
181
- const worker = async () => {
182
- for (let i = next++; i < items.length; i = next++) {
183
- results[i] = await run(items[i], i);
184
- }
185
- };
186
- await Promise.all(
187
- Array.from({ length: Math.min(limit, items.length) }, worker)
188
- );
189
- return results;
190
- };
191
- var shootAll = async (options) => {
192
- const pinned = drivenScreen(options.args ?? []);
193
- if (pinned) return [await shootScreen(pinned, options)];
194
- const screens = listScreens(options.command, options.args ?? []);
195
- return pool(
196
- screens,
197
- options.concurrency ?? defaultConcurrency(),
198
- (screen) => shootScreen(screen, options)
199
- );
200
- };
201
-
202
- export { DEFAULT_FONT, capture, drivenScreen, listScreens, shootAll, shootScreen, toImage };