The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { 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. */ |
| 5 | export 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. */ |
| 15 | interface Run { |
| 16 | readonly pen: string; |
| 17 | readonly text: string; |
| 18 | } |
| 19 | type Line = ReadonlyArray<Run>; |
| 20 | |
| 21 | interface 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 | |
| 33 | export 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. */ |
| 41 | export const TERMINAL_OUTPUT_TAIL_CHARS = 64 * 1024; |
| 42 | |
| 43 | const LIVE_LINES = 64; |
| 44 | |
| 45 | const MAX_PENDING_ESCAPE = 64; |
| 46 | |
| 47 | const ESC = "\u001b"; |
| 48 | |
| 49 | function 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. |
| 54 | const lineLengths = new WeakMap<Line, number>(); |
| 55 | |
| 56 | function 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 | |
| 65 | const lineWidths = new WeakMap<Line, number>(); |
| 66 | const ZERO_WIDTH = /[\p{Mark}\p{Default_Ignorable_Code_Point}]/u; |
| 67 | const ASCII = /^[\x00-\x7f]*$/u; |
| 68 | |
| 69 | function characterWidth(character: string): number { |
| 70 | return ZERO_WIDTH.test(character) ? 0 : eastAsianWidth(character.codePointAt(0)!); |
| 71 | } |
| 72 | |
| 73 | function 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 | |
| 80 | function 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. |
| 90 | const MAX_LINE_RUNS = 2_048; |
| 91 | |
| 92 | function 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 | |
| 134 | function 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. */ |
| 145 | function 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 | |
| 177 | function 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. */ |
| 195 | function 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 | |
| 207 | function 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 | |
| 220 | interface 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 | |
| 231 | function 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 | |
| 246 | function 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. */ |
| 260 | function 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 | |
| 280 | function 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 | |
| 313 | const STRING_SEQUENCE_INTRODUCERS = new Set(["]", "P", "X", "_", "^"]); |
| 314 | |
| 315 | /** Length of a complete escape sequence starting at `index` (an ESC), or -1 if unfinished. */ |
| 316 | function 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 | if (code >= 0x40 && code <= 0x7e) return cursor - index + 1; |
| 325 | } |
| 326 | return -1; |
| 327 | } |
| 328 | if (STRING_SEQUENCE_INTRODUCERS.has(next)) { |
| 329 | // BEL/ST ends string sequences; also stop at newlines so stray binary introducers cannot hide later output. |
| 330 | for (let cursor = index + 2; cursor < input.length; cursor += 1) { |
| 331 | if (input[cursor] === "\u0007") return cursor - index + 1; |
| 332 | if (input[cursor] === "\n") return cursor - index; |
| 333 | // Like xterm.js, an ESC that does not start ST ends the string and begins the next sequence. |
| 334 | if (input[cursor] === ESC) { |
| 335 | if (cursor + 1 >= input.length) return -1; |
| 336 | return input[cursor + 1] === "\\" ? cursor - index + 2 : cursor - index; |
| 337 | } |
| 338 | } |
| 339 | return -1; |
| 340 | } |
| 341 | // ECMA-35: any intermediate bytes (0x20-0x2F, e.g. charset designations, DECALN) precede one final byte. |
| 342 | let cursor = index + 1; |
| 343 | while ( |
| 344 | cursor < input.length && |
| 345 | input.charCodeAt(cursor) >= 0x20 && |
| 346 | input.charCodeAt(cursor) <= 0x2f |
| 347 | ) { |
| 348 | cursor += 1; |
| 349 | } |
| 350 | if (cursor >= input.length) return -1; |
| 351 | // After intermediates, a control or ESC is not a final byte; end before it so it is still processed. |
| 352 | const final = input.charCodeAt(cursor); |
| 353 | if (cursor > index + 1 && (final < 0x30 || final > 0x7e)) return cursor - index; |
| 354 | return cursor - index + 1; |
| 355 | } |
| 356 | |
| 357 | const penTransitions = new Map<string, string>(); |
| 358 | |
| 359 | // Colon color sub-parameters carry an optional color-space id absent from the semicolon form. |
| 360 | function csiParams(params: string): Array<number> { |
| 361 | const numbers: Array<number> = []; |
| 362 | // After a semicolon-form 38/48/58 the next part is its mode, then that many |
| 363 | // colour values; tracking them keeps a value from being read as a code. |
| 364 | let pending: "code" | "mode" | number = "code"; |
| 365 | for (const part of params.split(";")) { |
| 366 | const sub = part.split(":").map(Number); |
| 367 | const head = sub[0]!; |
| 368 | if (typeof pending === "number") { |
| 369 | numbers.push(head); |
| 370 | pending = pending > 1 ? pending - 1 : "code"; |
| 371 | continue; |
| 372 | } |
| 373 | if (pending === "mode") { |
| 374 | pending = "code"; |
| 375 | if (sub.length === 1) { |
| 376 | numbers.push(head); |
| 377 | if (head === 5 || head === 2) pending = head === 5 ? 1 : 3; |
| 378 | continue; |
| 379 | } |
| 380 | // xterm also takes the mode's fields after colons (`38;2:255:0:0`). |
| 381 | if (head === 2 && sub.length >= 5) sub.splice(1, 1); |
| 382 | numbers.push(...sub.slice(0, head === 5 ? 2 : head === 2 ? 4 : 1)); |
| 383 | continue; |
| 384 | } |
| 385 | if (sub.length === 1) { |
| 386 | numbers.push(head); |
| 387 | if (head === 38 || head === 48 || head === 58) pending = "mode"; |
| 388 | continue; |
| 389 | } |
| 390 | if (head !== 38 && head !== 48 && head !== 58) { |
| 391 | // Other sub-parameters pick a style variant (`4:3` curly underline); keep |
| 392 | // only the head, except that `4:0` turns underline off. |
| 393 | numbers.push(head === 4 && sub[1] === 0 ? 24 : head); |
| 394 | continue; |
| 395 | } |
| 396 | if (sub[1] === 2 && sub.length >= 6) sub.splice(2, 1); |
| 397 | // The group is one parameter, so fields past its mode's length must not |
| 398 | // leak out as SGR codes of their own. Indexed colour has no colour-space id. |
| 399 | numbers.push(...sub.slice(0, sub[1] === 5 ? 3 : sub[1] === 2 ? 5 : 2)); |
| 400 | } |
| 401 | return numbers; |
| 402 | } |
| 403 | |
| 404 | class Terminal { |
| 405 | settledHead: string; |
| 406 | settledTail: string; |
| 407 | lines: Array<Line>; |
| 408 | row: number; |
| 409 | col: number; |
| 410 | pen: string; |
| 411 | saved: { row: number; col: number } | null; |
| 412 | /** Output was discarded on purpose (scrollback cleared or window over budget). */ |
| 413 | dropped = false; |
| 414 | readonly maxChars: number; |
| 415 | /** Lines created during this feed, which it may extend in place. */ |
| 416 | private readonly owned = new WeakSet<Line>(); |
| 417 | |
| 418 | constructor(screen: TerminalScreen, maxChars: number) { |
| 419 | this.maxChars = maxChars; |
| 420 | [this.settledHead, this.settledTail] = screen.settled; |
| 421 | this.lines = screen.lines.slice(); |
| 422 | this.row = screen.row; |
| 423 | this.col = screen.col; |
| 424 | this.pen = screen.pen; |
| 425 | this.saved = screen.saved; |
| 426 | } |
| 427 | |
| 428 | write(text: string): void { |
| 429 | let line = this.lines[this.row]!; |
| 430 | const length = lineWidth(line); |
| 431 | const width = textWidth(text); |
| 432 | if (this.col === length && this.owned.has(line)) { |
| 433 | const units = lineLength(line); |
| 434 | pushRun(line as Array<Run>, { pen: this.pen, text }); |
| 435 | lineWidths.set(line, length + width); |
| 436 | lineLengths.set(line, units + text.length); |
| 437 | } else { |
| 438 | line = writeLine(line, this.col, text, this.pen); |
| 439 | this.owned.add(line); |
| 440 | } |
| 441 | this.col += width; |
| 442 | if (line.length > MAX_LINE_RUNS) { |
| 443 | // Flatten old runs so later trimming stays cheap. |
| 444 | const keep = line.length - MAX_LINE_RUNS / 8; |
| 445 | const plain = line |
| 446 | .slice(0, keep) |
| 447 | .map((run) => run.text) |
| 448 | .join(""); |
| 449 | const columns = lineWidth(line); |
| 450 | const units = lineLength(line); |
| 451 | line = [{ pen: "", text: plain }, ...line.slice(keep)]; |
| 452 | lineWidths.set(line, columns); |
| 453 | lineLengths.set(line, units); |
| 454 | this.owned.add(line); |
| 455 | } |
| 456 | // The output budget is UTF-16 units; cursor positions are terminal columns. |
| 457 | const current = lineLength(line); |
| 458 | if (current > this.maxChars) { |
| 459 | const removed = trimLineStart(line as Array<Run>, current - this.maxChars); |
| 460 | this.dropped = true; |
| 461 | this.col = Math.max(0, this.col - removed); |
| 462 | if (this.saved !== null && this.saved.row === this.row) { |
| 463 | this.saved = { ...this.saved, col: Math.max(0, this.saved.col - removed) }; |
| 464 | } |
| 465 | } |
| 466 | this.lines[this.row] = line; |
| 467 | } |
| 468 | |
| 469 | newline(): void { |
| 470 | this.row += 1; |
| 471 | this.col = 0; |
| 472 | if (this.row === this.lines.length) this.lines.push([]); |
| 473 | while (this.lines.length > LIVE_LINES) this.scrollOut(); |
| 474 | } |
| 475 | |
| 476 | scrollOut(): number { |
| 477 | const line = this.lines.shift()!; |
| 478 | this.settle(line); |
| 479 | this.row -= 1; |
| 480 | if (this.saved !== null) this.saved = { ...this.saved, row: Math.max(0, this.saved.row - 1) }; |
| 481 | return lineLength(line); |
| 482 | } |
| 483 | |
| 484 | settle(line: Line): void { |
| 485 | this.settledTail += `${serializeLine(line)}\n`; |
| 486 | if (this.settledHead.length + this.settledTail.length > 2 * this.maxChars) { |
| 487 | [this.settledHead, this.settledTail = ""] = terminalOutputTailParts( |
| 488 | [this.settledHead, this.settledTail], |
| 489 | this.maxChars, |
| 490 | ).parts; |
| 491 | this.dropped = true; |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | moveTo(row: number, col: number): void { |
| 496 | this.row = Math.max(0, Math.min(this.lines.length - 1, row)); |
| 497 | // A huge column (ESC[999999999C) would otherwise pad a line past any string limit. |
| 498 | this.col = Math.max(0, Math.min(2 * TERMINAL_OUTPUT_TAIL_CHARS, col)); |
| 499 | } |
| 500 | |
| 501 | csi(params: string, final: string): void { |
| 502 | if (!/^[\d;:]*$/u.test(params) || (final !== "m" && params.includes(":"))) return; |
| 503 | if (final === "m") { |
| 504 | const key = `${this.pen}|${params}`; |
| 505 | let pen = penTransitions.get(key); |
| 506 | if (pen === undefined) { |
| 507 | const attributes = parsePen(this.pen); |
| 508 | applySgr(attributes, params === "" ? [] : csiParams(params)); |
| 509 | pen = formatPen(attributes); |
| 510 | if (penTransitions.size >= 512) penTransitions.clear(); |
| 511 | penTransitions.set(key, pen); |
| 512 | } |
| 513 | this.pen = pen; |
| 514 | return; |
| 515 | } |
| 516 | const numbers = params === "" ? [] : csiParams(params); |
| 517 | const count = Math.max(1, numbers[0] || 1); |
| 518 | switch (final) { |
| 519 | case "A": |
| 520 | return this.moveTo(this.row - count, this.col); |
| 521 | case "B": |
| 522 | return this.moveTo(this.row + count, this.col); |
| 523 | case "C": |
| 524 | return this.moveTo(this.row, this.col + count); |
| 525 | case "D": |
| 526 | return this.moveTo(this.row, this.col - count); |
| 527 | case "E": |
| 528 | return this.moveTo(this.row + count, 0); |
| 529 | case "F": |
| 530 | return this.moveTo(this.row - count, 0); |
| 531 | case "G": |
| 532 | return this.moveTo(this.row, count - 1); |
| 533 | case "H": |
| 534 | case "f": |
| 535 | // Rows count from the top of the window: there is no fixed screen height. |
| 536 | return this.moveTo(count - 1, Math.max(1, numbers[1] || 1) - 1); |
| 537 | case "K": |
| 538 | this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, numbers[0] ?? 0); |
| 539 | return; |
| 540 | case "J": { |
| 541 | const mode = numbers[0] ?? 0; |
| 542 | if (mode === 0) { |
| 543 | this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, 0); |
| 544 | this.lines.length = this.row + 1; |
| 545 | } else if (mode === 1) { |
| 546 | for (let row = 0; row < this.row; row += 1) this.lines[row] = []; |
| 547 | this.lines[this.row] = eraseLine(this.lines[this.row]!, this.col, 1); |
| 548 | } else if (mode === 3) { |
| 549 | if (this.settledHead !== "" || this.settledTail !== "") this.dropped = true; |
| 550 | this.settledHead = ""; |
| 551 | this.settledTail = ""; |
| 552 | } else if (mode === 2) { |
| 553 | this.lines = [[]]; |
| 554 | this.row = 0; |
| 555 | this.col = 0; |
| 556 | } |
| 557 | return; |
| 558 | } |
| 559 | case "s": |
| 560 | this.saved = { row: this.row, col: this.col }; |
| 561 | return; |
| 562 | case "u": |
| 563 | if (this.saved !== null) this.moveTo(this.saved.row, this.saved.col); |
| 564 | return; |
| 565 | default: |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | escape(sequence: string): void { |
| 570 | if (sequence[1] === "[") { |
| 571 | this.csi(sequence.slice(2, -1), sequence.at(-1)!); |
| 572 | } else if (sequence === `${ESC}7`) { |
| 573 | this.saved = { row: this.row, col: this.col }; |
| 574 | } else if (sequence === `${ESC}8`) { |
| 575 | if (this.saved !== null) this.moveTo(this.saved.row, this.saved.col); |
| 576 | } else if (sequence === `${ESC}M`) { |
| 577 | this.moveTo(this.row - 1, this.col); |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | /** Applies `input`; returns the unfinished escape left at its end. */ |
| 582 | feed(input: string): string { |
| 583 | let printable = 0; |
| 584 | const flush = (end: number) => { |
| 585 | if (end > printable) this.write(input.slice(printable, end)); |
| 586 | }; |
| 587 | for (let index = 0; index < input.length; index += 1) { |
| 588 | const code = input.charCodeAt(index); |
| 589 | if (code === 0x09 || (code >= 0x20 && code !== 0x7f && (code < 0x80 || code > 0x9f))) { |
| 590 | continue; |
| 591 | } |
| 592 | flush(index); |
| 593 | printable = index + 1; |
| 594 | if (code === 0x0a) this.newline(); |
| 595 | else if (code === 0x0d) this.col = 0; |
| 596 | else if (code === 0x08) this.col = Math.max(0, this.col - 1); |
| 597 | else if (code === 0x1b) { |
| 598 | const length = escapeLength(input, index); |
| 599 | if (length === -1) { |
| 600 | const fragment = input.slice(index); |
| 601 | if (fragment.length <= MAX_PENDING_ESCAPE) return fragment; |
| 602 | // Retain the introducer and possible ST prefix so long string payloads stay hidden until termination. |
| 603 | if (STRING_SEQUENCE_INTRODUCERS.has(fragment[1]!)) { |
| 604 | return fragment.slice(0, 2) + (fragment.endsWith(ESC) ? ESC : ""); |
| 605 | } |
| 606 | return ""; |
| 607 | } |
| 608 | this.escape(input.slice(index, index + length)); |
| 609 | index += length - 1; |
| 610 | printable = index + 1; |
| 611 | } |
| 612 | } |
| 613 | const last = input.charCodeAt(input.length - 1); |
| 614 | if (last >= 0xd800 && last <= 0xdbff) { |
| 615 | flush(input.length - 1); |
| 616 | return input.slice(-1); |
| 617 | } |
| 618 | flush(input.length); |
| 619 | return ""; |
| 620 | } |
| 621 | } |
| 622 | |
| 623 | /** The active style at `index` of `text` and where a cut there may safely start. */ |
| 624 | function styleAt(text: string, index: number): { readonly start: number; readonly prefix: string } { |
| 625 | const lineStart = text.lastIndexOf("\n", index - 1) + 1; |
| 626 | let prefix = ""; |
| 627 | let cursor = lineStart; |
| 628 | while (cursor < index) { |
| 629 | const found = text.indexOf(`${ESC}[`, cursor); |
| 630 | if (found === -1 || found >= index) break; |
| 631 | const end = text.indexOf("m", found); |
| 632 | if (end === -1) break; |
| 633 | if (end >= index) return { start: end + 1, prefix: text.slice(found, end + 1) }; |
| 634 | prefix = text.slice(found, end + 1); |
| 635 | cursor = end + 1; |
| 636 | } |
| 637 | return { start: index, prefix: prefix === sgr("") ? "" : prefix }; |
| 638 | } |
| 639 | |
| 640 | /** Keeps the last `maxChars`, preferring to start on a fresh line. */ |
| 641 | export function terminalOutputTail( |
| 642 | text: string, |
| 643 | maxChars: number, |
| 644 | ): { readonly text: string; readonly truncated: boolean } { |
| 645 | if (text.length <= maxChars) return { text, truncated: false }; |
| 646 | let start = text.length - maxChars; |
| 647 | const newline = text.indexOf("\n", start); |
| 648 | // Drop the partial first line unless that would discard most of the tail. |
| 649 | if (newline !== -1 && newline - start < maxChars / 4) { |
| 650 | return { text: text.slice(newline + 1), truncated: true }; |
| 651 | } |
| 652 | // Cutting inside a line: never split an escape, and keep the colour in force. |
| 653 | const style = styleAt(text, start); |
| 654 | start = style.start; |
| 655 | // Never start on a lone low surrogate. |
| 656 | const first = text.charCodeAt(start); |
| 657 | if (first >= 0xdc00 && first <= 0xdfff) start += 1; |
| 658 | return { text: style.prefix + text.slice(start), truncated: true }; |
| 659 | } |
| 660 | |
| 661 | /** |
| 662 | * terminalOutputTail of the parts' concatenation, kept as parts. V8 copies a concatenated string |
| 663 | * the first time it is searched or sliced, so a newline cut slices only the part it lands in. |
| 664 | */ |
| 665 | function terminalOutputTailParts( |
| 666 | parts: readonly [string, ...Array<string>], |
| 667 | maxChars: number, |
| 668 | ): { readonly parts: readonly [string, ...Array<string>]; readonly truncated: boolean } { |
| 669 | let total = 0; |
| 670 | for (const part of parts) total += part.length; |
| 671 | if (total <= maxChars) return { parts, truncated: false }; |
| 672 | const start = total - maxChars; |
| 673 | let offset = 0; |
| 674 | for (let index = 0; index < parts.length; index += 1) { |
| 675 | const part = parts[index]!; |
| 676 | if (offset + part.length > start) { |
| 677 | const newline = part.indexOf("\n", Math.max(0, start - offset)); |
| 678 | if (newline !== -1) { |
| 679 | if (offset + newline - start >= maxChars / 4) break; |
| 680 | return { parts: [part.slice(newline + 1), ...parts.slice(index + 1)], truncated: true }; |
| 681 | } |
| 682 | } |
| 683 | offset += part.length; |
| 684 | } |
| 685 | return { parts: [terminalOutputTail(parts.join(""), maxChars).text], truncated: true }; |
| 686 | } |
| 687 | |
| 688 | export function appendTerminalOutput( |
| 689 | state: TerminalOutputState, |
| 690 | chunk: string, |
| 691 | maxChars: number = TERMINAL_OUTPUT_TAIL_CHARS, |
| 692 | ): TerminalOutputState { |
| 693 | const input = state.pending + chunk; |
| 694 | if (input.length === 0) return state; |
| 695 | const terminal = new Terminal(state.screen, maxChars); |
| 696 | const pending = terminal.feed(input); |
| 697 | let truncated = state.truncated; |
| 698 | let windowChars = terminal.lines.reduce((total, line) => total + lineLength(line), 0); |
| 699 | while (windowChars > maxChars && terminal.row > 0) windowChars -= terminal.scrollOut(); |
| 700 | // Lines below a cursor that moved up can't scroll out; they keep only their ends. |
| 701 | if (windowChars > maxChars) { |
| 702 | let budget = maxChars; |
| 703 | for (let row = 0; row <= terminal.row; row += 1) budget -= lineLength(terminal.lines[row]!); |
| 704 | for (let row = terminal.row + 1; row < terminal.lines.length; row += 1) { |
| 705 | const line = terminal.lines[row]!; |
| 706 | const length = lineLength(line); |
| 707 | const keep = Math.max(0, Math.min(length, budget)); |
| 708 | if (keep < length) { |
| 709 | truncated = true; |
| 710 | const runs = line.slice(); |
| 711 | const removed = trimLineStart(runs, length - keep); |
| 712 | terminal.lines[row] = runs; |
| 713 | if (terminal.saved !== null && terminal.saved.row === row) { |
| 714 | terminal.saved = { |
| 715 | ...terminal.saved, |
| 716 | col: Math.max(0, terminal.saved.col - removed), |
| 717 | }; |
| 718 | } |
| 719 | } |
| 720 | budget -= lineLength(terminal.lines[row]!); |
| 721 | } |
| 722 | } |
| 723 | if (terminal.dropped) truncated = true; |
| 724 | const settled = terminalOutputTailParts([terminal.settledHead, terminal.settledTail], maxChars); |
| 725 | const window = terminal.lines.map(serializeLine).join("\n"); |
| 726 | const tail = terminalOutputTailParts([...settled.parts, window], maxChars); |
| 727 | return { |
| 728 | text: tail.parts.reduce((text, part) => text + part, ""), |
| 729 | truncated: truncated || settled.truncated || tail.truncated, |
| 730 | pending, |
| 731 | screen: { |
| 732 | settled: [settled.parts[0], settled.parts[1] ?? ""], |
| 733 | lines: terminal.lines, |
| 734 | row: terminal.row, |
| 735 | col: terminal.col, |
| 736 | pen: terminal.pen, |
| 737 | saved: terminal.saved, |
| 738 | }, |
| 739 | }; |
| 740 | } |
| 741 | |
| 742 | /** Rebuilds state from empty, including cursor/style/pending escapes, so later raw chunks fold identically. */ |
| 743 | export function terminalOutputResumeText(state: TerminalOutputState): string { |
| 744 | const { screen } = state; |
| 745 | const lastRow = screen.lines.length - 1; |
| 746 | // Moves are relative to the last line, and a viewer only holds the lines in `text`. |
| 747 | let reachable = 0; |
| 748 | let cursor = 0; |
| 749 | while (reachable < LIVE_LINES - 1) { |
| 750 | const newline = state.text.indexOf("\n", cursor); |
| 751 | if (newline === -1) break; |
| 752 | reachable += 1; |
| 753 | cursor = newline + 1; |
| 754 | } |
| 755 | const up = (row: number) => Math.min(lastRow - row, reachable); |
| 756 | const goTo = (row: number, col: number) => |
| 757 | (up(row) > 0 ? `${ESC}[${up(row)}A` : "") + `${ESC}[${col + 1}G`; |
| 758 | let suffix = ""; |
| 759 | if (screen.saved !== null) { |
| 760 | suffix += `${goTo(screen.saved.row, screen.saved.col)}${ESC}7`; |
| 761 | if (up(screen.saved.row) > 0) suffix += `${ESC}[${up(screen.saved.row)}B`; |
| 762 | } |
| 763 | if ( |
| 764 | screen.saved !== null || |
| 765 | screen.row < lastRow || |
| 766 | screen.col !== lineWidth(screen.lines[screen.row]!) |
| 767 | ) { |
| 768 | suffix += goTo(screen.row, screen.col); |
| 769 | } |
| 770 | if (screen.pen !== "") suffix += sgr(screen.pen); |
| 771 | return state.text + suffix + state.pending; |
| 772 | } |
| 773 | |
| 774 | export function normalizeTerminalOutput( |
| 775 | text: string, |
| 776 | maxChars: number = TERMINAL_OUTPUT_TAIL_CHARS, |
| 777 | ): { readonly text: string; readonly truncated: boolean } { |
| 778 | const state = appendTerminalOutput(EMPTY_TERMINAL_OUTPUT, text, maxChars); |
| 779 | return { text: state.text, truncated: state.truncated }; |
| 780 | } |
| 781 | |
| 782 | export interface TerminalSpan { |
| 783 | readonly text: string; |
| 784 | readonly style: TerminalSpanStyle | null; |
| 785 | } |
| 786 | |
| 787 | export interface TerminalSpanStyle { |
| 788 | /** CSS colours, already resolved against the palette. */ |
| 789 | readonly color?: string; |
| 790 | readonly backgroundColor?: string; |
| 791 | readonly fontWeight?: "600"; |
| 792 | readonly opacity?: number; |
| 793 | readonly fontStyle?: "italic"; |
| 794 | readonly textDecorationLine?: "underline" | "line-through" | "underline line-through"; |
| 795 | } |
| 796 | |
| 797 | export const TERMINAL_PALETTES = { |
| 798 | dark: [ |
| 799 | "#3b4048", |
| 800 | "#f47067", |
| 801 | "#57ab5a", |
| 802 | "#c69026", |
| 803 | "#539bf5", |
| 804 | "#b083f0", |
| 805 | "#39c5cf", |
| 806 | "#adbac7", |
| 807 | "#768390", |
| 808 | "#ff938a", |
| 809 | "#6bc46d", |
| 810 | "#daaa3f", |
| 811 | "#6cb6ff", |
| 812 | "#dcbdfb", |
| 813 | "#56d4dd", |
| 814 | "#cdd9e5", |
| 815 | ], |
| 816 | light: [ |
| 817 | "#24292f", |
| 818 | "#cf222e", |
| 819 | "#116329", |
| 820 | "#7d4e00", |
| 821 | "#0550ae", |
| 822 | "#8250df", |
| 823 | "#1b7c83", |
| 824 | "#6e7781", |
| 825 | "#57606a", |
| 826 | "#a40e26", |
| 827 | "#1a7f37", |
| 828 | "#633c01", |
| 829 | "#0969da", |
| 830 | "#6639ba", |
| 831 | "#3192aa", |
| 832 | "#8c959f", |
| 833 | ], |
| 834 | } as const; |
| 835 | |
| 836 | function xtermColor(index: number, palette: ReadonlyArray<string>): string { |
| 837 | if (index < 16) return palette[index]!; |
| 838 | if (index >= 232) { |
| 839 | const level = 8 + (index - 232) * 10; |
| 840 | return `rgb(${level},${level},${level})`; |
| 841 | } |
| 842 | const cube = index - 16; |
| 843 | const channel = (value: number) => (value === 0 ? 0 : 55 + value * 40); |
| 844 | return `rgb(${channel(Math.floor(cube / 36))},${channel(Math.floor(cube / 6) % 6)},${channel(cube % 6)})`; |
| 845 | } |
| 846 | |
| 847 | function resolveColor( |
| 848 | code: string, |
| 849 | base: number, |
| 850 | palette: ReadonlyArray<string>, |
| 851 | ): string | undefined { |
| 852 | const parts = code.split(";").map(Number); |
| 853 | const head = parts[0]!; |
| 854 | if (head === base + 8) { |
| 855 | if (parts[1] === 5) return xtermColor(parts[2]!, palette); |
| 856 | return `rgb(${parts[2]},${parts[3]},${parts[4]})`; |
| 857 | } |
| 858 | if (head >= base && head <= base + 7) return palette[head - base]; |
| 859 | if (head >= base + 60 && head <= base + 67) return palette[head - base - 52]; |
| 860 | return undefined; |
| 861 | } |
| 862 | |
| 863 | type Rgb = readonly [number, number, number]; |
| 864 | |
| 865 | function parseCssColor(color: string): Rgb | undefined { |
| 866 | if (color.startsWith("#") && color.length === 7) { |
| 867 | return [1, 3, 5].map((offset) => |
| 868 | Number.parseInt(color.slice(offset, offset + 2), 16), |
| 869 | ) as unknown as Rgb; |
| 870 | } |
| 871 | const match = /^rgb\((\d+),(\d+),(\d+)\)$/u.exec(color); |
| 872 | return match === null ? undefined : [Number(match[1]), Number(match[2]), Number(match[3])]; |
| 873 | } |
| 874 | |
| 875 | function luminance([r, g, b]: Rgb): number { |
| 876 | const channel = (value: number) => { |
| 877 | const scaled = value / 255; |
| 878 | return scaled <= 0.03928 ? scaled / 12.92 : ((scaled + 0.055) / 1.055) ** 2.4; |
| 879 | }; |
| 880 | return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b); |
| 881 | } |
| 882 | |
| 883 | function contrastRatio(a: Rgb, b: Rgb): number { |
| 884 | const [first, second] = [luminance(a), luminance(b)]; |
| 885 | return (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05); |
| 886 | } |
| 887 | |
| 888 | function spanStyle(pen: string, palette: ReadonlyArray<string>): TerminalSpanStyle | null { |
| 889 | if (pen === "") return null; |
| 890 | const attributes = parsePen(pen); |
| 891 | let color = attributes.fg === "" ? undefined : resolveColor(attributes.fg, 30, palette); |
| 892 | let backgroundColor = attributes.bg === "" ? undefined : resolveColor(attributes.bg, 40, palette); |
| 893 | if (attributes.inverse) { |
| 894 | [color, backgroundColor] = [backgroundColor, color ?? palette[7]]; |
| 895 | } |
| 896 | // Badges like "PASS" on green assume a terminal's own palette; keep their text readable. |
| 897 | if (backgroundColor !== undefined) { |
| 898 | const background = parseCssColor(backgroundColor); |
| 899 | const foreground = color === undefined ? undefined : parseCssColor(color); |
| 900 | if ( |
| 901 | background !== undefined && |
| 902 | (foreground === undefined || contrastRatio(foreground, background) < 3) |
| 903 | ) { |
| 904 | color = luminance(background) > 0.3 ? "#1f2328" : "#ffffff"; |
| 905 | } |
| 906 | } |
| 907 | const textDecorationLine = attributes.underline |
| 908 | ? attributes.strike |
| 909 | ? "underline line-through" |
| 910 | : "underline" |
| 911 | : attributes.strike |
| 912 | ? "line-through" |
| 913 | : undefined; |
| 914 | return { |
| 915 | ...(color === undefined ? {} : { color }), |
| 916 | ...(backgroundColor === undefined ? {} : { backgroundColor }), |
| 917 | ...(attributes.bold ? { fontWeight: "600" } : {}), |
| 918 | ...(attributes.dim ? { opacity: 0.65 } : {}), |
| 919 | ...(attributes.italic ? { fontStyle: "italic" } : {}), |
| 920 | ...(textDecorationLine === undefined ? {} : { textDecorationLine }), |
| 921 | }; |
| 922 | } |
| 923 | |
| 924 | /** Caps styled spans at maxSpans, then emits one plain remainder to bound DOM/native nodes. */ |
| 925 | export function terminalOutputSpans( |
| 926 | text: string, |
| 927 | palette: ReadonlyArray<string>, |
| 928 | maxSpans = 2_000, |
| 929 | ): ReadonlyArray<TerminalSpan> { |
| 930 | const spans: Array<TerminalSpan> = []; |
| 931 | const styles = new Map<string, TerminalSpanStyle | null>(); |
| 932 | let pen = ""; |
| 933 | let cursor = 0; |
| 934 | const push = (end: number) => { |
| 935 | if (end <= cursor) return; |
| 936 | let style = styles.get(pen); |
| 937 | if (style === undefined) { |
| 938 | style = spanStyle(pen, palette); |
| 939 | styles.set(pen, style); |
| 940 | } |
| 941 | spans.push({ text: text.slice(cursor, end), style }); |
| 942 | }; |
| 943 | while (cursor < text.length) { |
| 944 | const escape = text.indexOf(`${ESC}[`, cursor); |
| 945 | if (escape === -1 || spans.length >= maxSpans) break; |
| 946 | push(escape); |
| 947 | const end = text.indexOf("m", escape); |
| 948 | if (end === -1) break; |
| 949 | const params = text.slice(escape + 2, end); |
| 950 | pen = params === "0" ? "" : params.replace(/^0;/u, ""); |
| 951 | cursor = end + 1; |
| 952 | } |
| 953 | if (cursor < text.length) { |
| 954 | if (spans.length >= maxSpans) { |
| 955 | spans.push({ text: terminalOutputPlainText(text.slice(cursor)), style: null }); |
| 956 | } else { |
| 957 | push(text.length); |
| 958 | } |
| 959 | } |
| 960 | return spans; |
| 961 | } |
| 962 | |
| 963 | const SGR_PATTERN = new RegExp(`${ESC}\\[[0-9;:]*m`, "gu"); |
| 964 | |
| 965 | export function terminalOutputPlainText(text: string): string { |
| 966 | return text.replace(SGR_PATTERN, ""); |
| 967 | } |