Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

terminalOutput.ts

872 lines30.4 KB

1/**
2 * Turns raw terminal bytes (already decoded to text) into a bounded tail that
3 * a timeline can show. Runs on the server before output crosses the wire, and
4 * again on clients when they splice appends onto what they hold, so both sides
5 * must reach the same state from the same input.
6 *
7 * It models a small terminal: the last `LIVE_LINES` lines form a window that
8 * cursor movement can rewrite, so `\r` progress bars and multi-line redraws
9 * (docker pull, pnpm, test reporters) keep only their latest frame. Older lines
10 * are fixed text. The model has no width, so lines never wrap.
11 *
12 * - Colours and text attributes (SGR) survive as canonical `ESC[0;…m` codes.
13 * Every line starts from the default style and resets at its end, so any line
14 * boundary is a safe place to cut. `terminalOutputSpans` reads them back.
15 * - Cursor moves, line and screen erases, and save/restore are applied. Other
16 * escape sequences (titles, modes) and control characters are dropped.
17 * - Only the last `maxChars` survive, cut at a line boundary when possible.
18 *
19 * Chunks can split an escape sequence, so the unfinished fragment is carried in
20 * `pending` until the next chunk arrives.
21 */
22export interface TerminalOutputState {
23 /** What to show: fixed lines, then the window. Contains only SGR escapes. */
24 readonly text: string;
25 /** True once anything was dropped from the front. */
26 readonly truncated: boolean;
27 /** An unfinished escape sequence awaiting the next chunk. */
28 readonly pending: string;
29 readonly screen: TerminalScreen;
31​
32/** A styled stretch of one line. `pen` is canonical SGR parameters, "" for default. */
33interface Run {
34 readonly pen: string;
35 readonly text: string;
37type Line = ReadonlyArray<Run>;
38​
39interface TerminalScreen {
40 /** Serialized lines, each ending in `\n`, that scrolled out of the window. */
41 readonly settled: string;
42 /** The live window; never empty. */
43 readonly lines: ReadonlyArray<Line>;
44 readonly row: number;
45 readonly col: number;
46 readonly pen: string;
47 readonly saved: { readonly row: number; readonly col: number } | null;
49​
50export const EMPTY_TERMINAL_OUTPUT: TerminalOutputState = {
51 text: "",
52 truncated: false,
53 pending: "",
54 screen: { settled: "", lines: [[]], row: 0, col: 0, pen: "", saved: null },
55};
56​
57/** The default tail kept for one running command, in UTF-16 code units. */
58export const TERMINAL_OUTPUT_TAIL_CHARS = 64 * 1024;
59​
60/** Lines that cursor movement can still reach; older output is fixed. */
61const LIVE_LINES = 64;
62​
63// Longest fragment we will hold waiting for an escape sequence to finish.
64const MAX_PENDING_ESCAPE = 64;
65​
66const ESC = "\u001b";
67​
68function sgr(pen: string): string {
69 return pen === "" ? `${ESC}[0m` : `${ESC}[0;${pen}m`;
71​
72// Lengths of lines already measured. Lines are never mutated once a feed ends.
73const lineLengths = new WeakMap<Line, number>();
74​
75function lineLength(line: Line): number {
76 const cached = lineLengths.get(line);
77 if (cached !== undefined) return cached;
78 let length = 0;
79 for (const run of line) length += run.text.length;
80 lineLengths.set(line, length);
81 return length;
83​
84// Past this many style changes, a line's oldest runs lose their style. Rendering
85// already caps spans, and it keeps per-write work bounded on colour-per-character output.
86const MAX_LINE_RUNS = 2_048;
87​
88/** Runs covering columns [start, end) of `line`. */
89function sliceLine(line: Line, start: number, end: number): Array<Run> {
90 const out: Array<Run> = [];
91 let offset = 0;
92 for (const run of line) {
93 const runEnd = offset + run.text.length;
94 if (runEnd > start && offset < end) {
95 out.push({
96 pen: run.pen,
97 text: run.text.slice(Math.max(0, start - offset), Math.min(run.text.length, end - offset)),
98 });
99 }
100 offset = runEnd;
101 if (offset >= end) break;
102 }
103 return out;
105​
106function pushRun(runs: Array<Run>, run: Run): void {
107 if (run.text.length === 0) return;
108 const last = runs.at(-1);
109 if (last !== undefined && last.pen === run.pen) {
110 runs[runs.length - 1] = { pen: last.pen, text: last.text + run.text };
111 } else {
112 runs.push(run);
113 }
115​
116/** Drops the first `count` columns of a line this feed owns, in place. */
117function trimLineStart(runs: Array<Run>, count: number): void {
118 let dropped = 0;
119 let remaining = count;
120 while (remaining > 0 && dropped < runs.length) {
121 const run = runs[dropped]!;
122 if (run.text.length <= remaining) {
123 remaining -= run.text.length;
124 dropped += 1;
125 } else {
126 runs[dropped] = { pen: run.pen, text: run.text.slice(remaining) };
127 remaining = 0;
128 }
129 }
130 if (dropped > 0) runs.splice(0, dropped);
132​
133/** `line` with `text` written over it from `col`, as a terminal overwrites. */
134function writeLine(line: Line, col: number, text: string, pen: string): Line {
135 const length = lineLength(line);
136 if (col === length) {
137 // The common case: printing at the end of the line.
138 const runs = line.slice();
139 pushRun(runs, { pen, text });
140 return runs;
141 }
142 const runs: Array<Run> = [];
143 for (const run of sliceLine(line, 0, Math.min(col, length))) pushRun(runs, run);
144 if (col > length) pushRun(runs, { pen: "", text: " ".repeat(col - length) });
145 pushRun(runs, { pen, text });
146 for (const run of sliceLine(line, col + text.length, length)) pushRun(runs, run);
147 return runs;
149​
150/** Erase in line: 0 cursor to end, 1 start to cursor, 2 whole line. */
151function eraseLine(line: Line, col: number, mode: number): Line {
152 const length = lineLength(line);
153 if (mode === 0) return sliceLine(line, 0, col);
154 if (mode === 1) {
155 const runs: Array<Run> = [];
156 pushRun(runs, { pen: "", text: " ".repeat(Math.min(col + 1, length)) });
157 for (const run of sliceLine(line, col + 1, length)) pushRun(runs, run);
158 return runs;
159 }
160 return [];
162​
163function serializeLine(line: Line): string {
164 let out = "";
165 let current = "";
166 for (const run of line) {
167 if (run.pen !== current) {
168 out += sgr(run.pen);
169 current = run.pen;
170 }
171 out += run.text;
172 }
173 return current === "" ? out : out + sgr("");
175​
176interface Attributes {
177 bold: boolean;
178 dim: boolean;
179 italic: boolean;
180 underline: boolean;
181 strike: boolean;
182 inverse: boolean;
183 fg: string;
184 bg: string;
186​
187function parsePen(pen: string): Attributes {
188 const attributes: Attributes = {
189 bold: false,
190 dim: false,
191 italic: false,
192 underline: false,
193 strike: false,
194 inverse: false,
195 fg: "",
196 bg: "",
197 };
198 if (pen !== "") applySgr(attributes, pen.split(";").map(Number));
199 return attributes;
201​
202function formatPen(attributes: Attributes): string {
203 const parts: Array<string> = [];
204 if (attributes.bold) parts.push("1");
205 if (attributes.dim) parts.push("2");
206 if (attributes.italic) parts.push("3");
207 if (attributes.underline) parts.push("4");
208 if (attributes.inverse) parts.push("7");
209 if (attributes.strike) parts.push("9");
210 if (attributes.fg !== "") parts.push(attributes.fg);
211 if (attributes.bg !== "") parts.push(attributes.bg);
212 return parts.join(";");
214​
215/** Reads an extended colour (`5;n` or `2;r;g;b`) starting at `index`; returns the code and next index. */
216function extendedColor(
217 code: number,
218 params: ReadonlyArray<number>,
219 index: number,
220): [string | undefined, number] {
221 const mode = params[index + 1];
222 if (mode === 5) {
223 const value = params[index + 2];
224 return value === undefined || value > 255
225 ? [undefined, index + 3]
226 : [`${code};5;${value}`, index + 3];
227 }
228 if (mode === 2) {
229 const [r, g, b] = [params[index + 2], params[index + 3], params[index + 4]];
230 if (r === undefined || g === undefined || b === undefined) return [undefined, index + 5];
231 return [`${code};2;${r & 255};${g & 255};${b & 255}`, index + 5];
232 }
233 return [undefined, index + 2];
235​
236function applySgr(attributes: Attributes, params: ReadonlyArray<number>): void {
237 if (params.length === 0) params = [0];
238 for (let index = 0; index < params.length;) {
239 const code = params[index]!;
240 if (code === 0 || Number.isNaN(code)) {
241 Object.assign(attributes, parsePen(""));
242 } else if (code === 1) attributes.bold = true;
243 else if (code === 2) attributes.dim = true;
244 else if (code === 3) attributes.italic = true;
245 else if (code === 4) attributes.underline = true;
246 else if (code === 7) attributes.inverse = true;
247 else if (code === 9) attributes.strike = true;
248 else if (code === 22) attributes.bold = attributes.dim = false;
249 else if (code === 23) attributes.italic = false;
250 else if (code === 24) attributes.underline = false;
251 else if (code === 27) attributes.inverse = false;
252 else if (code === 29) attributes.strike = false;
253 else if ((code >= 30 && code <= 37) || (code >= 90 && code <= 97)) attributes.fg = String(code);
254 else if ((code >= 40 && code <= 47) || (code >= 100 && code <= 107))
255 attributes.bg = String(code);
256 else if (code === 39) attributes.fg = "";
257 else if (code === 49) attributes.bg = "";
258 else if (code === 38 || code === 48) {
259 const [color, next] = extendedColor(code, params, index);
260 if (color !== undefined) attributes[code === 38 ? "fg" : "bg"] = color;
261 index = next;
262 continue;
263 }
264 index += 1;
265 }
267​
268const STRING_SEQUENCE_INTRODUCERS = new Set(["]", "P", "X", "_", "^"]);
269​
270/** Length of a complete escape sequence starting at `index` (an ESC), or -1 if unfinished. */
271function escapeLength(input: string, index: number): number {
272 const next = input[index + 1];
273 if (next === undefined) return -1;
274 if (next === "[") {
275 // CSI: parameters/intermediates, then a final byte in @-~.
276 for (let cursor = index + 2; cursor < input.length; cursor += 1) {
277 const code = input.charCodeAt(cursor);
278 if (code >= 0x40 && code <= 0x7e) return cursor - index + 1;
279 }
280 return -1;
281 }
282 if (STRING_SEQUENCE_INTRODUCERS.has(next)) {
283 // OSC/DCS/SOS/APC/PM end at BEL or ST (ESC \). A newline also ends one (and is
284 // kept), so a stray introducer in binary output can't hide everything after it.
285 for (let cursor = index + 2; cursor < input.length; cursor += 1) {
286 if (input[cursor] === "\u0007") return cursor - index + 1;
287 if (input[cursor] === "\n") return cursor - index;
288 if (input[cursor] === ESC) {
289 if (cursor + 1 >= input.length) return -1;
290 if (input[cursor + 1] === "\\") return cursor - index + 2;
291 }
292 }
293 return -1;
294 }
295 // Charset designation (ESC ( B) takes three; other two-byte sequences (ESC 7) two.
296 if (next === "(" || next === ")" || next === "*" || next === "+") {
297 return index + 2 < input.length ? 3 : -1;
298 }
299 return 2;
301​
302const penTransitions = new Map<string, string>();
303​
304/** CSI parameters as numbers. Colon sub-parameters (`38:2::r:g:b`) carry an optional
305 colour-space id that the semicolon form (`38;2;r;g;b`) has no slot for. */
306function csiParams(params: string): Array<number> {
307 const numbers: Array<number> = [];
308 for (const part of params.split(";")) {
309 if (!part.includes(":")) {
310 numbers.push(Number(part));
311 continue;
312 }
313 const sub = part.split(":").map(Number);
314 if ((sub[0] === 38 || sub[0] === 48) && sub[1] === 2 && sub.length >= 6) sub.splice(2, 1);
315 numbers.push(...sub);
316 }
317 return numbers;
319​
320/** A mutable copy of the screen, for applying one chunk. */
321class Terminal {
322 settled: string;
323 lines: Array<Line>;
324 row: number;
325 col: number;
326 pen: string;
327 saved: { row: number; col: number } | null;
328 /** Output was discarded on purpose (scrollback cleared or window over budget). */
329 dropped = false;
330 readonly maxChars: number;
331 /** Lines created during this feed, which it may extend in place. */
332 private readonly owned = new WeakSet<Line>();
333​
334 constructor(screen: TerminalScreen, maxChars: number) {
335 this.maxChars = maxChars;
336 this.settled = screen.settled;
337 this.lines = screen.lines.slice();
338 this.row = screen.row;
339 this.col = screen.col;
340 this.pen = screen.pen;
341 this.saved = screen.saved;
342 }
343​
344 write(text: string): void {
345 let line = this.lines[this.row]!;
346 const length = lineLength(line);
347 if (this.col === length && this.owned.has(line)) {
348 // Printing at the end of a line this feed already copied: extend it in place.
349 pushRun(line as Array<Run>, { pen: this.pen, text });
350 lineLengths.set(line, length + text.length);
351 } else {
352 line = writeLine(line, this.col, text, this.pen);
353 this.owned.add(line);
354 }
355 this.col += text.length;
356 if (line.length > MAX_LINE_RUNS) {
357 // Fold all but the newest runs into one plain run, so trimming below eats it cheaply.
358 const keep = line.length - MAX_LINE_RUNS / 8;
359 const plain = line
360 .slice(0, keep)
361 .map((run) => run.text)
362 .join("");
363 line = [{ pen: "", text: plain }, ...line.slice(keep)];
364 this.owned.add(line);
365 }
366 // A line keeps only its last `maxChars` columns, trimmed on every write so the
367 // result never depends on how the output was split into chunks.
368 let current = lineLength(line);
369 if (current > this.maxChars) {
370 let removed = current - this.maxChars;
371 if (!this.owned.has(line)) {
372 line = line.slice();
373 this.owned.add(line);
374 }
375 trimLineStart(line as Array<Run>, removed);
376 // Never start on a lone low surrogate.
377 const first = line[0]?.text.charCodeAt(0) ?? 0;
378 if (first >= 0xdc00 && first <= 0xdfff) {
379 trimLineStart(line as Array<Run>, 1);
380 removed += 1;
381 }
382 current -= removed;
383 this.dropped = true;
384 this.col = Math.max(0, this.col - removed);
385 if (this.saved !== null && this.saved.row === this.row) {
386 this.saved = { ...this.saved, col: Math.max(0, this.saved.col - removed) };
387 }
388 }
389 lineLengths.set(line, current);
390 this.lines[this.row] = line;
391 }
392​
393 newline(): void {
394 this.row += 1;
395 this.col = 0;
396 if (this.row === this.lines.length) this.lines.push([]);
397 while (this.lines.length > LIVE_LINES) this.scrollOut();
398 }
399​
400 /** Moves the top line out of the window into scrollback; returns its length. */
401 scrollOut(): number {
402 const line = this.lines.shift()!;
403 this.settle(line);
404 this.row -= 1;
405 if (this.saved !== null) this.saved = { ...this.saved, row: Math.max(0, this.saved.row - 1) };
406 return lineLength(line);
407 }
408​
409 /** Fixes a line that left the window, keeping scrollback near the tail size as it grows. */
410 settle(line: Line): void {
411 this.settled += `${serializeLine(line)}\n`;
412 if (this.settled.length > 2 * this.maxChars) {
413 this.settled = terminalOutputTail(this.settled, this.maxChars).text;
414 this.dropped = true;
415 }
416 }
417​
418 moveTo(row: number, col: number): void {
419 this.row = Math.max(0, Math.min(this.lines.length - 1, row));
420 // A huge column (ESC[999999999C) would otherwise pad a line past any string limit.
421 this.col = Math.max(0, Math.min(TERMINAL_OUTPUT_TAIL_CHARS, col));
422 }
423​
424 csi(params: string, final: string): void {
425 if (/^[?>=]/u.test(params)) return; // Mode switches (cursor visibility, bracketed paste).
426 const numbers = params === "" ? [] : csiParams(params);
427 const count = Math.max(1, numbers[0] || 1);
428 switch (final) {
429 case "m": {
430 // Colourful output repeats a handful of transitions, so they are cached.
431 const key = `${this.pen}|${params}`;
432 let pen = penTransitions.get(key);
433 if (pen === undefined) {
434 const attributes = parsePen(this.pen);
435 applySgr(attributes, numbers);
436 pen = formatPen(attributes);
437 if (penTransitions.size >= 512) penTransitions.clear();
438 penTransitions.set(key, pen);
439 }
440 this.pen = pen;
441 return;
442 }
443 case "A":
444 return this.moveTo(this.row - count, this.col);
445 case "B":
446 return this.moveTo(this.row + count, this.col);
447 case "C":
448 return this.moveTo(this.row, this.col + count);
449 case "D":
450 return this.moveTo(this.row, this.col - count);
451 case "E":
452 return this.moveTo(this.row + count, 0);
453 case "F":
454 return this.moveTo(this.row - count, 0);
455 case "G":
456 return this.moveTo(this.row, count - 1);
457 case "H":
458 case "f":
459 // Rows count from the top of the window: there is no fixed screen height.
460 return this.moveTo(count - 1, Math.max(1, numbers[1] || 1) - 1);
461 case "K":
462 this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, numbers[0] ?? 0);
463 return;
464 case "J": {
465 const mode = numbers[0] ?? 0;
466 if (mode === 0) {
467 this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, 0);
468 this.lines.length = this.row + 1;
469 } else if (mode === 1) {
470 for (let row = 0; row < this.row; row += 1) this.lines[row] = [];
471 this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, 1);
472 } else if (mode === 3) {
473 // Clear scrollback: what already scrolled out goes, the window stays.
474 if (this.settled !== "") this.dropped = true;
475 this.settled = "";
476 } else {
477 // A cleared screen starts the window over; what scrolled out stays.
478 this.lines = [[]];
479 this.row = 0;
480 this.col = 0;
481 }
482 return;
483 }
484 case "s":
485 this.saved = { row: this.row, col: this.col };
486 return;
487 case "u":
488 if (this.saved !== null) this.moveTo(this.saved.row, this.saved.col);
489 return;
490 default:
491 }
492 }
493​
494 escape(sequence: string): void {
495 if (sequence[1] === "[") {
496 this.csi(sequence.slice(2, -1), sequence.at(-1)!);
497 } else if (sequence === `${ESC}7`) {
498 this.saved = { row: this.row, col: this.col };
499 } else if (sequence === `${ESC}8`) {
500 if (this.saved !== null) this.moveTo(this.saved.row, this.saved.col);
501 } else if (sequence === `${ESC}M`) {
502 this.moveTo(this.row - 1, this.col); // Reverse line feed.
503 }
504 }
505​
506 /** Applies `input`; returns the unfinished escape left at its end. */
507 feed(input: string): string {
508 let printable = 0;
509 const flush = (end: number) => {
510 if (end > printable) this.write(input.slice(printable, end));
511 };
512 for (let index = 0; index < input.length; index += 1) {
513 const code = input.charCodeAt(index);
514 // Printable text, including tabs, is batched into one write.
515 if (code === 0x09 || (code >= 0x20 && code !== 0x7f && (code < 0x80 || code > 0x9f))) {
516 continue;
517 }
518 flush(index);
519 printable = index + 1;
520 if (code === 0x0a) this.newline();
521 else if (code === 0x0d) this.col = 0;
522 else if (code === 0x08) this.col = Math.max(0, this.col - 1);
523 else if (code === 0x1b) {
524 const length = escapeLength(input, index);
525 if (length === -1) {
526 const fragment = input.slice(index);
527 if (fragment.length <= MAX_PENDING_ESCAPE) return fragment;
528 // A long string sequence keeps only its introducer (and a trailing ESC that
529 // may start its ST), so the payload stays hidden until it ends.
530 if (STRING_SEQUENCE_INTRODUCERS.has(fragment[1]!)) {
531 return fragment.slice(0, 2) + (fragment.endsWith(ESC) ? ESC : "");
532 }
533 // Any other runaway sequence is noise; drop it instead of waiting forever.
534 return "";
535 }
536 this.escape(input.slice(index, index + length));
537 index += length - 1;
538 printable = index + 1;
539 }
540 // Other C0, DEL and C1 controls carry no visible text.
541 }
542 flush(input.length);
543 return "";
544 }
546​
547/** The active style at `index` of `text` and where a cut there may safely start. */
548function styleAt(text: string, index: number): { readonly start: number; readonly prefix: string } {
549 const lineStart = text.lastIndexOf("\n", index - 1) + 1;
550 let prefix = "";
551 let cursor = lineStart;
552 while (cursor < index) {
553 const found = text.indexOf(`${ESC}[`, cursor);
554 if (found === -1 || found >= index) break;
555 const end = text.indexOf("m", found);
556 if (end === -1) break;
557 if (end >= index) return { start: end + 1, prefix: text.slice(found, end + 1) };
558 prefix = text.slice(found, end + 1);
559 cursor = end + 1;
560 }
561 return { start: index, prefix: prefix === sgr("") ? "" : prefix };
563​
564/** Keeps the last `maxChars`, preferring to start on a fresh line. */
565export function terminalOutputTail(
566 text: string,
567 maxChars: number,
568): { readonly text: string; readonly truncated: boolean } {
569 if (text.length <= maxChars) return { text, truncated: false };
570 let start = text.length - maxChars;
571 const newline = text.indexOf("\n", start);
572 // Drop the partial first line unless that would discard most of the tail.
573 if (newline !== -1 && newline - start < maxChars / 4) {
574 return { text: text.slice(newline + 1), truncated: true };
575 }
576 // Cutting inside a line: never split an escape, and keep the colour in force.
577 const style = styleAt(text, start);
578 start = style.start;
579 // Never start on a lone low surrogate.
580 const first = text.charCodeAt(start);
581 if (first >= 0xdc00 && first <= 0xdfff) start += 1;
582 return { text: style.prefix + text.slice(start), truncated: true };
584​
585/** Appends one decoded chunk and returns the new bounded state. */
586export function appendTerminalOutput(
587 state: TerminalOutputState,
588 chunk: string,
589 maxChars: number = TERMINAL_OUTPUT_TAIL_CHARS,
590): TerminalOutputState {
591 const input = state.pending + chunk;
592 if (input.length === 0) return state;
593 const terminal = new Terminal(state.screen, maxChars);
594 const pending = terminal.feed(input);
595 let truncated = state.truncated;
596 // The window as a whole stays within the tail too: oldest lines scroll out early.
597 let windowChars = terminal.lines.reduce((total, line) => total + lineLength(line), 0);
598 while (windowChars > maxChars && terminal.row > 0) windowChars -= terminal.scrollOut();
599 // Lines below a cursor that moved up can't scroll out; they keep only their ends.
600 if (windowChars > maxChars) {
601 let budget = maxChars;
602 for (let row = 0; row <= terminal.row; row += 1) budget -= lineLength(terminal.lines[row]!);
603 for (let row = terminal.row + 1; row < terminal.lines.length; row += 1) {
604 const line = terminal.lines[row]!;
605 const length = lineLength(line);
606 const keep = Math.max(0, Math.min(length, budget));
607 if (keep < length) {
608 truncated = true;
609 terminal.lines[row] = sliceLine(line, length - keep, length);
610 if (terminal.saved !== null && terminal.saved.row === row) {
611 terminal.saved = {
612 ...terminal.saved,
613 col: Math.max(0, terminal.saved.col - (length - keep)),
614 };
615 }
616 }
617 budget -= keep;
618 }
619 }
620 if (terminal.dropped) truncated = true;
621 const settled = terminalOutputTail(terminal.settled, maxChars);
622 const window = terminal.lines.map(serializeLine).join("\n");
623 const tail = terminalOutputTail(settled.text + window, maxChars);
624 return {
625 text: tail.text,
626 truncated: truncated || settled.truncated || tail.truncated,
627 pending,
628 screen: {
629 settled: settled.text,
630 lines: terminal.lines,
631 row: terminal.row,
632 col: terminal.col,
633 pen: terminal.pen,
634 saved: terminal.saved,
635 },
636 };
638​
639/**
640 * Text that rebuilds `state` when fed to an empty state: the output, then the
641 * cursor, style and any unfinished escape. A viewer that starts from it (or
642 * resyncs to it) applies later raw chunks exactly as the server does.
643 */
644export function terminalOutputResumeText(state: TerminalOutputState): string {
645 const { screen } = state;
646 const lastRow = screen.lines.length - 1;
647 // Moves are relative to the last line, and a viewer only holds the lines in `text`.
648 const shownLines = state.text.split("\n").length;
649 const reachable = Math.min(LIVE_LINES, shownLines) - 1;
650 const up = (row: number) => Math.min(lastRow - row, reachable);
651 const goTo = (row: number, col: number) =>
652 (up(row) > 0 ? `${ESC}[${up(row)}A` : "") + `${ESC}[${col + 1}G`;
653 let suffix = "";
654 if (screen.saved !== null) {
655 suffix += `${goTo(screen.saved.row, screen.saved.col)}${ESC}7`;
656 if (up(screen.saved.row) > 0) suffix += `${ESC}[${up(screen.saved.row)}B`;
657 }
658 if (
659 screen.saved !== null ||
660 screen.row < lastRow ||
661 screen.col !== lineLength(screen.lines[screen.row]!)
662 ) {
663 suffix += goTo(screen.row, screen.col);
664 }
665 if (screen.pen !== "") suffix += sgr(screen.pen);
666 return state.text + suffix + state.pending;
668​
669/** Normalizes a complete output string in one pass. */
670export function normalizeTerminalOutput(
671 text: string,
672 maxChars: number = TERMINAL_OUTPUT_TAIL_CHARS,
673): { readonly text: string; readonly truncated: boolean } {
674 const state = appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, text, maxChars);
675 return { text: state.text, truncated: state.truncated };
677​
678/** A stretch of shown output with one style. */
679export interface TerminalSpan {
680 readonly text: string;
681 readonly style: TerminalSpanStyle | null;
683​
684/** A span's style, usable as-is by a web or React Native `style` prop. */
685export interface TerminalSpanStyle {
686 /** CSS colours, already resolved against the palette. */
687 readonly color?: string;
688 readonly backgroundColor?: string;
689 readonly fontWeight?: "600";
690 readonly opacity?: number;
691 readonly fontStyle?: "italic";
692 readonly textDecorationLine?: "underline" | "line-through" | "underline line-through";
694​
695/** The 16 standard terminal colours, chosen to stay readable on each app theme. */
696export const TERMINAL_PALETTES = {
697 dark: [
698 "#3b4048",
699 "#f47067",
700 "#57ab5a",
701 "#c69026",
702 "#539bf5",
703 "#b083f0",
704 "#39c5cf",
705 "#adbac7",
706 "#768390",
707 "#ff938a",
708 "#6bc46d",
709 "#daaa3f",
710 "#6cb6ff",
711 "#dcbdfb",
712 "#56d4dd",
713 "#cdd9e5",
714 ],
715 light: [
716 "#24292f",
717 "#cf222e",
718 "#116329",
719 "#7d4e00",
720 "#0550ae",
721 "#8250df",
722 "#1b7c83",
723 "#6e7781",
724 "#57606a",
725 "#a40e26",
726 "#1a7f37",
727 "#633c01",
728 "#0969da",
729 "#6639ba",
730 "#3192aa",
731 "#8c959f",
732 ],
733} as const;
734​
735function xtermColor(index: number, palette: ReadonlyArray<string>): string {
736 if (index < 16) return palette[index]!;
737 if (index >= 232) {
738 const level = 8 + (index - 232) * 10;
739 return `rgb(${level},${level},${level})`;
740 }
741 const cube = index - 16;
742 const channel = (value: number) => (value === 0 ? 0 : 55 + value * 40);
743 return `rgb(${channel(Math.floor(cube / 36))},${channel(Math.floor(cube / 6) % 6)},${channel(cube % 6)})`;
745​
746function resolveColor(
747 code: string,
748 base: number,
749 palette: ReadonlyArray<string>,
750): string | undefined {
751 const parts = code.split(";").map(Number);
752 const head = parts[0]!;
753 if (head === base + 8) {
754 if (parts[1] === 5) return xtermColor(parts[2]!, palette);
755 return `rgb(${parts[2]},${parts[3]},${parts[4]})`;
756 }
757 if (head >= base && head <= base + 7) return palette[head - base];
758 if (head >= base + 60 && head <= base + 67) return palette[head - base - 52];
759 return undefined;
761​
762type Rgb = readonly [number, number, number];
763​
764/** Reads the `#rrggbb` and `rgb(r,g,b)` colours this module produces. */
765function parseCssColor(color: string): Rgb | undefined {
766 if (color.startsWith("#") && color.length === 7) {
767 return [1, 3, 5].map((offset) =>
768 Number.parseInt(color.slice(offset, offset + 2), 16),
769 ) as unknown as Rgb;
770 }
771 const match = /^rgb\((\d+),(\d+),(\d+)\)$/u.exec(color);
772 return match === null ? undefined : [Number(match[1]), Number(match[2]), Number(match[3])];
774​
775function luminance([r, g, b]: Rgb): number {
776 const channel = (value: number) => {
777 const scaled = value / 255;
778 return scaled <= 0.03928 ? scaled / 12.92 : ((scaled + 0.055) / 1.055) ** 2.4;
779 };
780 return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
782​
783function contrastRatio(a: Rgb, b: Rgb): number {
784 const [first, second] = [luminance(a), luminance(b)];
785 return (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05);
787​
788function spanStyle(pen: string, palette: ReadonlyArray<string>): TerminalSpanStyle | null {
789 if (pen === "") return null;
790 const attributes = parsePen(pen);
791 let color = attributes.fg === "" ? undefined : resolveColor(attributes.fg, 30, palette);
792 let backgroundColor = attributes.bg === "" ? undefined : resolveColor(attributes.bg, 40, palette);
793 if (attributes.inverse) {
794 [color, backgroundColor] = [backgroundColor, color ?? palette[7]];
795 }
796 // Badges like "PASS" on green assume a terminal's own palette; keep their text readable.
797 if (backgroundColor !== undefined) {
798 const background = parseCssColor(backgroundColor);
799 const foreground = color === undefined ? undefined : parseCssColor(color);
800 if (
801 background !== undefined &&
802 (foreground === undefined || contrastRatio(foreground, background) < 3)
803 ) {
804 color = luminance(background) > 0.35 ? "#1f2328" : "#ffffff";
805 }
806 }
807 const textDecorationLine = attributes.underline
808 ? attributes.strike
809 ? "underline line-through"
810 : "underline"
811 : attributes.strike
812 ? "line-through"
813 : undefined;
814 return {
815 ...(color === undefined ? {} : { color }),
816 ...(backgroundColor === undefined ? {} : { backgroundColor }),
817 ...(attributes.bold ? { fontWeight: "600" } : {}),
818 ...(attributes.dim ? { opacity: 0.65 } : {}),
819 ...(attributes.italic ? { fontStyle: "italic" } : {}),
820 ...(textDecorationLine === undefined ? {} : { textDecorationLine }),
821 };
823​
824/**
825 * Splits shown output into styled spans for rendering. Past `maxSpans` the rest
826 * is one plain span, so a pathological stream of colour changes cannot turn
827 * into tens of thousands of DOM or native nodes.
828 */
829export function terminalOutputSpans(
830 text: string,
831 palette: ReadonlyArray<string>,
832 maxSpans = 2_000,
833): ReadonlyArray<TerminalSpan> {
834 const spans: Array<TerminalSpan> = [];
835 const styles = new Map<string, TerminalSpanStyle | null>();
836 let pen = "";
837 let cursor = 0;
838 const push = (end: number) => {
839 if (end <= cursor) return;
840 let style = styles.get(pen);
841 if (style === undefined) {
842 style = spanStyle(pen, palette);
843 styles.set(pen, style);
844 }
845 spans.push({ text: text.slice(cursor, end), style });
846 };
847 while (cursor < text.length) {
848 const escape = text.indexOf(`${ESC}[`, cursor);
849 if (escape === -1 || spans.length >= maxSpans) break;
850 push(escape);
851 const end = text.indexOf("m", escape);
852 if (end === -1) break;
853 const params = text.slice(escape + 2, end);
854 pen = params === "0" ? "" : params.replace(/^0;/u, "");
855 cursor = end + 1;
856 }
857 if (cursor < text.length) {
858 if (spans.length >= maxSpans) {
859 spans.push({ text: terminalOutputPlainText(text.slice(cursor)), style: null });
860 } else {
861 push(text.length);
862 }
863 }
864 return spans;
866​
867const SGR_PATTERN = new RegExp(`${ESC}\\[[0-9;]*m`, "gu");
868​
869/** Shown output without its colour codes. */
870export function terminalOutputPlainText(text: string): string {
871 return text.replace(SGR_PATTERN, "");