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