The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { setClipboard, stringWidth, tmuxPassthrough } from "@alchemy.run/sigil/ansi"; |
| 2 | /** Terminal-emulator features shared by CLI components. */ |
| 3 | import { detectColorLevel, detectUnicodeSupport } from "@alchemy.run/sigil/capabilities"; |
| 4 | |
| 5 | export const ANSI_RESET = "\u001B[0m"; |
| 6 | export const ANSI_BOLD = "\u001B[1m"; |
| 7 | export const ANSI_DIM = "\u001B[2m"; |
| 8 | |
| 9 | /** Truecolor foreground escape for raw, non-layout output. */ |
| 10 | export const ansiFg = (hex: string) => { |
| 11 | const red = Number.parseInt(hex.slice(1, 3), 16); |
| 12 | const green = Number.parseInt(hex.slice(3, 5), 16); |
| 13 | const blue = Number.parseInt(hex.slice(5, 7), 16); |
| 14 | return `\u001B[38;2;${red};${green};${blue}m`; |
| 15 | }; |
| 16 | |
| 17 | /** |
| 18 | * The canonical color-support decision, shared by raw terminal strings and |
| 19 | * terminal capability detection so the two can never disagree. |
| 20 | */ |
| 21 | export const colorsEnabled = ( |
| 22 | stream: Pick<NodeJS.WriteStream, "isTTY"> = process.stdout, |
| 23 | ): boolean => detectColorLevel(stream) > 0; |
| 24 | |
| 25 | /** The canonical Unicode-support decision for raw terminal strings. */ |
| 26 | export const unicodeEnabled = detectUnicodeSupport; |
| 27 | |
| 28 | /** Environment override for child processes whose piped output returns here. */ |
| 29 | export const pipedColorEnv = (): Record<string, string> => |
| 30 | colorsEnabled() ? { FORCE_COLOR: process.env.FORCE_COLOR ?? "1" } : {}; |
| 31 | |
| 32 | export const paint = (code: string, value: string): string => |
| 33 | colorsEnabled() ? `${code}${value}${ANSI_RESET}` : value; |
| 34 | |
| 35 | export const copyToClipboard = ( |
| 36 | text: string, |
| 37 | stdout: Pick<NodeJS.WriteStream, "write"> = process.stdout, |
| 38 | ): void => { |
| 39 | let sequence = setClipboard(text); |
| 40 | if (process.env.TMUX !== undefined) { |
| 41 | sequence = tmuxPassthrough(sequence); |
| 42 | } |
| 43 | stdout.write(sequence); |
| 44 | }; |
| 45 | |
| 46 | const truncateSegmenter = new Intl.Segmenter(); |
| 47 | |
| 48 | /** Display-width-aware truncation (wide CJK/emoji count by rendered cells). */ |
| 49 | export const truncate = (value: string, width: number): string => { |
| 50 | const max = Math.max(4, width); |
| 51 | if (stringWidth(value) <= max) return value; |
| 52 | let total = 0; |
| 53 | let kept = ""; |
| 54 | for (const { segment } of truncateSegmenter.segment(value)) { |
| 55 | const segmentWidth = stringWidth(segment); |
| 56 | if (total + segmentWidth > max - 1) break; |
| 57 | total += segmentWidth; |
| 58 | kept += segment; |
| 59 | } |
| 60 | return `${kept}…`; |
| 61 | }; |