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