ccleanup 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,283 @@
1
+ import { messages } from "../i18n/messages.js";
2
+ import { formatAge, formatDate, formatSize, tildify } from "../lib/format.js";
3
+ import { cut, fit, sanitize, skip, stripAnsi, width } from "../lib/text.js";
4
+ import { line } from "./line.js";
5
+ const SPARE = 1;
6
+ const KEY_WIDTH = 15;
7
+ const CONFIRM_ROWS = 5;
8
+ /**
9
+ * Draws a rounded box with a title in its top border.
10
+ *
11
+ * @param theme - Theme of the output: colors, depth and glyph set
12
+ * @param title - Title written in the top border
13
+ * @param body - One list of segments per inner line
14
+ * @param inner - Width inside the borders, padding included
15
+ * @param tone - Color of the border and the title
16
+ * @returns The box, its width being inner plus the two borders
17
+ */
18
+ export function box(theme, title, body, inner, tone) {
19
+ const { box: glyphs } = theme.glyphs;
20
+ const border = (text) => theme.paint(text, { fg: tone });
21
+ const label = cut(` ${title} `, Math.max(0, inner - 2), theme.glyphs.ellipsis);
22
+ const rest = Math.max(0, inner - width(label) - 1);
23
+ const top = border(`${glyphs.tl}${glyphs.h}`) +
24
+ theme.paint(label, { fg: tone, bold: true }) +
25
+ border(`${glyphs.h.repeat(rest)}${glyphs.tr}`);
26
+ const lines = [top];
27
+ for (const segments of body) {
28
+ lines.push(`${border(glyphs.v)} ${line(theme, segments, inner - 2, {}, true)} ${border(glyphs.v)}`);
29
+ }
30
+ lines.push(border(`${glyphs.bl}${glyphs.h.repeat(inner)}${glyphs.br}`));
31
+ return { lines, width: inner + 2 };
32
+ }
33
+ /**
34
+ * Lays a box over the middle of a screen area, the rest of that area dimmed behind it.
35
+ *
36
+ * @param theme - Theme of the output
37
+ * @param lines - The whole frame, one string per terminal row
38
+ * @param over - Box to lay over it
39
+ * @param from - First row of the area, the header above it stays as it is
40
+ * @param to - Row after the area, the status line and footer below it stay too
41
+ * @param cols - Terminal width in cells
42
+ * @returns A new frame
43
+ */
44
+ export function overlay(theme, lines, over, from, to, cols) {
45
+ const dim = { fg: "muted", dim: true };
46
+ const behind = (text) => (text.trim() ? theme.paint(text, dim) : text);
47
+ const out = lines.map((row, i) => (i >= from && i < to ? behind(stripAnsi(row)) : row));
48
+ // A box taller than the area keeps its bottom border, so it never looks cut.
49
+ const area = Math.max(0, to - from);
50
+ const shown = over.lines.length > area && area > 1
51
+ ? [...over.lines.slice(0, area - 1), over.lines.at(-1)]
52
+ : over.lines.slice(0, area);
53
+ const y0 = from + Math.max(0, Math.floor((area - shown.length) / 2));
54
+ const x0 = Math.max(0, Math.floor((cols - over.width) / 2));
55
+ // A blank cell on each side keeps the dimmed rows off the border.
56
+ const end = x0 + over.width;
57
+ shown.forEach((boxLine, i) => {
58
+ const plain = stripAnsi(lines[y0 + i] ?? "");
59
+ const left = fit(cut(plain, Math.max(0, x0 - 1), ""), Math.max(0, x0 - 1));
60
+ const right = cut(skip(plain, end + 1), Math.max(0, cols - SPARE - end - 1), "");
61
+ const margin = (cells) => " ".repeat(Math.max(0, Math.min(1, cells)));
62
+ out[y0 + i] =
63
+ behind(left) + margin(x0) + boxLine + margin(cols - SPARE - end) + behind(right);
64
+ });
65
+ return out;
66
+ }
67
+ /**
68
+ * The help panel: every key by section, then the legend of marks, tags and sizes.
69
+ *
70
+ * Sections go side by side when the terminal is wide enough, else one under the other,
71
+ * cut to the height available.
72
+ *
73
+ * @param state - Frame state, read only
74
+ * @param cols - Terminal width in cells
75
+ * @param rows - Rows the box may take, borders included
76
+ * @returns The box
77
+ */
78
+ export function helpBox(state, cols, rows) {
79
+ const { theme, lang } = state;
80
+ const { guide } = messages(lang);
81
+ const sections = guide.sections.map((section) => [
82
+ [[section.title, { fg: "accent", bold: true }]],
83
+ ...section.rows.map(([key, action]) => [
84
+ [fit(key, KEY_WIDTH), { fg: "text", bold: true }],
85
+ [action, { fg: "muted" }],
86
+ ]),
87
+ ]);
88
+ const { glyphs } = theme;
89
+ const legend = [
90
+ [[guide.legendTitle, { fg: "accent", bold: true }]],
91
+ [
92
+ [glyphs.marked, { fg: "pink", bold: true }],
93
+ [` ${guide.legend.marked} `],
94
+ [glyphs.unmarked, { fg: "muted" }],
95
+ [` ${guide.legend.markable}`, { fg: "muted" }],
96
+ ],
97
+ [
98
+ [messages(lang).open, { fg: "accent", bold: true }],
99
+ [` ${guide.legend.open}`, { fg: "muted" }],
100
+ ],
101
+ [
102
+ [messages(lang).recent, { fg: "ok" }],
103
+ [
104
+ ` ${state.includeRecent ? guide.legend.recentAllowed : guide.legend.recent}`,
105
+ { fg: "muted" },
106
+ ],
107
+ ],
108
+ [[guide.legend.sizes, { fg: "muted" }]],
109
+ ];
110
+ const footer = [[], [[guide.close, { fg: "muted", dim: true }]]];
111
+ const textWidth = (segments) => width(segments.map(([text]) => text).join(""));
112
+ const column = Math.max(...sections.flat().map(textWidth));
113
+ const across = Math.max(...legend.map(textWidth));
114
+ const gap = 4;
115
+ const twoColumns = cols - SPARE - 4 >= 2 * column + gap + 2;
116
+ // Two columns when they fit, then the legend across.
117
+ let body;
118
+ if (twoColumns) {
119
+ const half = Math.ceil(sections.length / 2);
120
+ const left = sections.slice(0, half).flatMap((s, i) => (i > 0 ? [[], ...s] : s));
121
+ const right = sections.slice(half).flatMap((s, i) => (i > 0 ? [[], ...s] : s));
122
+ body = Array.from({ length: Math.max(left.length, right.length) }, (_, i) => {
123
+ const l = left[i] ?? [];
124
+ return [...l, [" ".repeat(column - textWidth(l) + gap)], ...(right[i] ?? [])];
125
+ });
126
+ }
127
+ else {
128
+ body = sections.flatMap((s, i) => (i > 0 ? [[], ...s] : s));
129
+ }
130
+ body = [...body, [], ...legend, ...footer];
131
+ // Taller than the screen: the arrows scroll it.
132
+ const room = Math.max(1, rows - 2);
133
+ if (body.length > room) {
134
+ const visible = Math.max(1, room - 1);
135
+ const scroll = Math.min(state.helpScroll, Math.max(0, body.length - visible));
136
+ state.helpScroll = scroll;
137
+ const more = scroll + visible < body.length;
138
+ body = [
139
+ ...body.slice(scroll, scroll + visible),
140
+ [[more ? theme.glyphs.ellipsis : "", { fg: "muted" }]],
141
+ ];
142
+ }
143
+ else {
144
+ state.helpScroll = 0;
145
+ }
146
+ // As wide as the content, so the list stays visible, dimmed, on both sides.
147
+ const content = Math.max(twoColumns ? 2 * column + gap : column, across);
148
+ const inner = Math.max(20, Math.min(cols - SPARE - 4, content + 2));
149
+ return box(theme, guide.title, body, inner, "accent");
150
+ }
151
+ /**
152
+ * The deletion question: how many sessions and bytes, the first ones by name, those the
153
+ * search hides, and a reminder that it cannot be undone.
154
+ *
155
+ * @param state - Frame state with the targets of the deletion
156
+ * @param cols - Terminal width in cells
157
+ * @returns The box
158
+ */
159
+ export function confirmBox(state, cols, rows) {
160
+ const { theme, lang, targets, hiddenTargets } = state;
161
+ const m = messages(lang);
162
+ const bytes = targets.reduce((sum, session) => sum + session.bytes, 0);
163
+ const inner = Math.max(24, Math.min(cols - SPARE - 4, 72));
164
+ const body = [
165
+ [[m.confirm(targets.length, formatSize(bytes, lang)), { fg: "warn", bold: true }]],
166
+ ];
167
+ if (hiddenTargets > 0)
168
+ body.push([[m.confirmHidden(hiddenTargets), { fg: "muted" }]]);
169
+ body.push([]);
170
+ // Fixed lines: question, note, blanks, warning, keys and borders.
171
+ const fixed = (hiddenTargets > 0 ? 7 : 6) + 2;
172
+ const listed = Math.max(0, Math.min(CONFIRM_ROWS, rows - fixed - 1));
173
+ const first = targets.slice(0, listed);
174
+ const project = Math.min(24, Math.max(0, ...first.map((session) => width(session.project))));
175
+ for (const session of first) {
176
+ body.push([
177
+ [fit(formatSize(session.bytes, lang), 9, "right"), { fg: "muted" }],
178
+ [" "],
179
+ [fit(session.project, project, "left", theme.glyphs.ellipsis), { fg: "text" }],
180
+ [" "],
181
+ [session.title || "-", { fg: "muted" }],
182
+ ]);
183
+ }
184
+ if (targets.length > first.length && first.length > 0) {
185
+ body.push([
186
+ [" ".repeat(11)],
187
+ [m.confirmMore(targets.length - first.length), { fg: "muted" }],
188
+ ]);
189
+ }
190
+ const [yes = "y"] = m.confirmKeys;
191
+ const keys = [
192
+ [yes, { fg: "warn", bold: true }],
193
+ [` ${m.keys.yes} `, { fg: "muted" }],
194
+ [`${m.keyNames.no}, ${m.keyNames.esc}`, { fg: "accent", bold: true }],
195
+ [` ${m.keys.no}`, { fg: "muted" }],
196
+ ];
197
+ body.push([], [[m.confirmFinal(targets.length), { fg: "muted" }]], []);
198
+ // Too short: drop the blank lines first, never the keys or the hidden note.
199
+ let fitted = body;
200
+ if (fitted.length + 3 > rows)
201
+ fitted = body.filter((segments) => segments.length > 0);
202
+ const room = Math.max(1, rows - 3);
203
+ if (room < 2 && hiddenTargets > 0) {
204
+ fitted = [[...fitted[0], [` ${m.confirmHidden(hiddenTargets)}`, { fg: "muted" }]]];
205
+ }
206
+ fitted = [...fitted.slice(0, room), keys];
207
+ return box(theme, m.confirmTitle, fitted, inner, "warn");
208
+ }
209
+ /**
210
+ * Text of one line of the details: a muted label, then the value.
211
+ *
212
+ * @param label - Name of the field
213
+ * @param value - Segments of the value
214
+ * @returns The segments of the line
215
+ */
216
+ function field(label, value) {
217
+ return [[fit(label, 10), { fg: "muted" }], ...value];
218
+ }
219
+ /**
220
+ * State of a session in words, the strongest first.
221
+ *
222
+ * @param state - Frame state, for the marks
223
+ * @param session - Session under the cursor
224
+ * @param key - Its sessionKey
225
+ * @returns The word and its color
226
+ */
227
+ function stateOf(state, session, key) {
228
+ const { states } = messages(state.lang).details;
229
+ if (session.open)
230
+ return [states.open, { fg: "accent", bold: true }];
231
+ if (state.marked.has(key))
232
+ return [states.marked, { fg: "pink", bold: true }];
233
+ if (session.recent)
234
+ return [states.recent, { fg: "ok" }];
235
+ return [states.idle, { fg: "muted" }];
236
+ }
237
+ /**
238
+ * Details of the session under the cursor: full title, folder, id, config folder, dates,
239
+ * sizes by part, state and the command that resumes it.
240
+ *
241
+ * @param state - Frame state, read only
242
+ * @param session - Session under the cursor
243
+ * @param key - Its sessionKey
244
+ * @param cols - Terminal width in cells
245
+ * @returns The lines of the panel, DETAILS_ROWS of them
246
+ */
247
+ export function detailsBox(state, session, key, cols) {
248
+ const { theme, lang, now } = state;
249
+ const m = messages(lang).details;
250
+ const dot = [" / ", { fg: "muted", dim: true }];
251
+ const parts = session.parts
252
+ .filter((part) => part.bytes > 0)
253
+ .flatMap((part, i) => [
254
+ ...(i > 0 ? [[", ", { fg: "muted" }]] : []),
255
+ [`${m.parts[part.kind]} `, { fg: "muted" }],
256
+ [formatSize(part.bytes, lang), { fg: "text" }],
257
+ ]);
258
+ const dates = [];
259
+ if (session.startedAt)
260
+ dates.push([formatDate(session.startedAt, lang), { fg: "text" }], dot, [
261
+ `${m.modified} `,
262
+ { fg: "muted" },
263
+ ]);
264
+ dates.push([formatDate(session.mtime, lang), { fg: "text" }], [` (${formatAge(now - session.mtime, lang)})`, { fg: "muted" }]);
265
+ const body = [
266
+ [[session.title || "-", { fg: "text", bold: true }]],
267
+ field(m.folder, [
268
+ [session.cwd ? tildify(session.cwd) : session.project, { fg: "text" }],
269
+ dot,
270
+ [`${m.config} `, { fg: "muted" }],
271
+ [sanitize(tildify(session.configDir)), { fg: "text" }],
272
+ ]),
273
+ field(m.resume, [[`claude --resume ${session.id}`, { fg: "accent" }]]),
274
+ field(session.startedAt ? m.started : m.modified, dates),
275
+ field(m.size, [
276
+ [formatSize(session.bytes, lang), { fg: "text", bold: true }],
277
+ ...(parts.length > 0 ? [[" ("], ...parts, [")"]] : []),
278
+ ]),
279
+ field(m.state, [stateOf(state, session, key)]),
280
+ ];
281
+ return box(theme, m.title, body, Math.max(20, cols - SPARE - 4), "muted").lines.map((row) => ` ${row}`);
282
+ }
283
+ export const DETAILS_ROWS = 8;
@@ -0,0 +1,61 @@
1
+ import { ESC } from "../lib/text.js";
2
+ // Alternate screen, hidden cursor, no autowrap, bracketed paste
3
+ const ENTER = `${ESC}[?1049h${ESC}[?25l${ESC}[?7l${ESC}[?2004h${ESC}[2J`;
4
+ const LEAVE = `${ESC}[0m${ESC}[?2004l${ESC}[?7h${ESC}[?25h${ESC}[?1049l`;
5
+ const SYNC_START = `${ESC}[?2026h`;
6
+ const SYNC_END = `${ESC}[?2026l`;
7
+ /**
8
+ * Creates the full-screen output: alternate screen, hidden cursor, and a renderer that
9
+ * only rewrites the lines that changed, inside a synchronized update, so nothing flickers.
10
+ *
11
+ * @param output - Terminal output stream
12
+ * @returns The screen, not entered yet
13
+ */
14
+ export function createScreen(output) {
15
+ let previous = [];
16
+ let active = false;
17
+ let clear = false;
18
+ return {
19
+ get active() {
20
+ return active;
21
+ },
22
+ enter() {
23
+ if (active)
24
+ return;
25
+ active = true;
26
+ previous = [];
27
+ output.write(ENTER);
28
+ },
29
+ leave() {
30
+ if (!active)
31
+ return;
32
+ active = false;
33
+ output.write(LEAVE);
34
+ },
35
+ draw(lines) {
36
+ if (!active)
37
+ return;
38
+ let out = "";
39
+ const count = Math.max(lines.length, previous.length);
40
+ for (let i = 0; i < count; i++) {
41
+ const line = lines[i] ?? "";
42
+ if (line === previous[i])
43
+ continue;
44
+ out += `${ESC}[${i + 1};1H${line}${ESC}[0m${ESC}[K`;
45
+ }
46
+ previous = lines;
47
+ if (clear)
48
+ out = `${ESC}[2J${out}`;
49
+ clear = false;
50
+ if (out)
51
+ output.write(SYNC_START + out + SYNC_END);
52
+ },
53
+ invalidate() {
54
+ previous = [];
55
+ clear = true;
56
+ },
57
+ size() {
58
+ return { cols: output.columns || 80, rows: output.rows || 24 };
59
+ },
60
+ };
61
+ }
@@ -0,0 +1,307 @@
1
+ import { BEL, ESC } from "../lib/text.js";
2
+ // Palette for dark backgrounds, around the Claude terracotta accent
3
+ const DARK = {
4
+ text: [232, 228, 238],
5
+ muted: [139, 134, 151],
6
+ accent: [217, 119, 87],
7
+ pink: [236, 106, 156],
8
+ ok: [74, 222, 128],
9
+ warn: [251, 191, 36],
10
+ err: [248, 113, 113],
11
+ info: [103, 232, 249],
12
+ selFg: [246, 232, 238],
13
+ selBg: [58, 34, 48],
14
+ logoTopLeft: [255, 192, 154],
15
+ logoTopRight: [247, 168, 200],
16
+ logoBottomLeft: [194, 85, 58],
17
+ logoBottomRight: [184, 51, 106],
18
+ logoShadow: [58, 30, 22],
19
+ paper: [28, 25, 32],
20
+ glow: [255, 224, 163],
21
+ ember: [138, 59, 42],
22
+ };
23
+ // Palette for light backgrounds: darker hues so text keeps an AA contrast
24
+ const LIGHT = {
25
+ text: [42, 37, 48],
26
+ muted: [107, 100, 117],
27
+ accent: [180, 83, 47],
28
+ pink: [192, 57, 122],
29
+ ok: [21, 128, 61],
30
+ warn: [161, 98, 7],
31
+ err: [185, 28, 28],
32
+ info: [14, 116, 144],
33
+ selFg: [42, 21, 32],
34
+ selBg: [246, 220, 228],
35
+ logoTopLeft: [217, 119, 79],
36
+ logoTopRight: [192, 80, 126],
37
+ logoBottomLeft: [143, 58, 34],
38
+ logoBottomRight: [126, 31, 74],
39
+ logoShadow: [222, 204, 196],
40
+ paper: [250, 247, 244],
41
+ glow: [214, 110, 40],
42
+ ember: [226, 190, 170],
43
+ };
44
+ // 16-color foreground codes; the background code is the same plus 10
45
+ const BASIC = {
46
+ text: 39,
47
+ muted: 90,
48
+ accent: 33,
49
+ pink: 35,
50
+ ok: 32,
51
+ warn: 33,
52
+ err: 31,
53
+ info: 36,
54
+ selFg: 39,
55
+ selBg: 49,
56
+ logoTopLeft: 33,
57
+ logoTopRight: 35,
58
+ logoBottomLeft: 31,
59
+ logoBottomRight: 35,
60
+ logoShadow: 90,
61
+ paper: 49,
62
+ glow: 33,
63
+ ember: 31,
64
+ };
65
+ /**
66
+ * Builds a one-character string from a code point, for the glyph tables.
67
+ *
68
+ * @param code - Unicode code point
69
+ * @returns The character
70
+ */
71
+ function cp(code) {
72
+ return String.fromCodePoint(code);
73
+ }
74
+ // Unicode glyphs, built from code points so the source stays ASCII
75
+ const UNICODE_GLYPHS = {
76
+ cursor: cp(0x276f),
77
+ marked: cp(0x2726),
78
+ unmarked: cp(0x00b7),
79
+ caret: cp(0x258f),
80
+ ellipsis: cp(0x2026),
81
+ ok: cp(0x2713),
82
+ err: cp(0x2717),
83
+ sortDown: cp(0x2193),
84
+ sortUp: cp(0x2191),
85
+ bar: cp(0x2501),
86
+ track: cp(0x2501),
87
+ spinner: [0x280b, 0x2819, 0x2839, 0x2838, 0x283c, 0x2834, 0x2826, 0x2827, 0x2807, 0x280f].map(cp),
88
+ box: {
89
+ tl: cp(0x256d),
90
+ tr: cp(0x256e),
91
+ bl: cp(0x2570),
92
+ br: cp(0x256f),
93
+ h: cp(0x2500),
94
+ v: cp(0x2502),
95
+ },
96
+ };
97
+ // ASCII twins, for the Linux console, non UTF-8 locales and CCLEANUP_ASCII=1
98
+ const ASCII_GLYPHS = {
99
+ cursor: ">",
100
+ marked: "x",
101
+ unmarked: ".",
102
+ caret: "_",
103
+ ellipsis: "...",
104
+ ok: "+",
105
+ err: "!",
106
+ sortDown: "v",
107
+ sortUp: "^",
108
+ bar: "#",
109
+ track: "-",
110
+ spinner: ["|", "/", "-", "\\"],
111
+ box: { tl: "+", tr: "+", bl: "+", br: "+", h: "-", v: "|" },
112
+ };
113
+ /**
114
+ * Mixes two colors.
115
+ *
116
+ * @param from - Color at ratio 0
117
+ * @param to - Color at ratio 1
118
+ * @param ratio - Position between the two, clamped to 0..1
119
+ * @returns The interpolated color, components rounded
120
+ */
121
+ export function mix(from, to, ratio) {
122
+ const t = Math.min(1, Math.max(0, ratio));
123
+ return from.map((value, i) => Math.round(value + (to[i] - value) * t));
124
+ }
125
+ const OSC11_REPLY = new RegExp(String.raw `${ESC}\]11;rgb:([0-9a-f]{1,4})/([0-9a-f]{1,4})/([0-9a-f]{1,4})`, "i");
126
+ const DA1_REPLY = new RegExp(String.raw `${ESC}\[\?[\d;]*c`);
127
+ /**
128
+ * Converts a color to the nearest entry of the 256-color palette.
129
+ *
130
+ * @param rgb - Color to convert
131
+ * @returns An index in the 6x6x6 cube (16-231) or in the gray ramp (232-255)
132
+ */
133
+ function to256([r, g, b]) {
134
+ if (r === g && g === b) {
135
+ if (r < 8)
136
+ return 16;
137
+ if (r > 248)
138
+ return 231;
139
+ return Math.round(((r - 8) / 247) * 24) + 232;
140
+ }
141
+ const step = (value) => value < 48 ? 0 : value < 115 ? 1 : Math.floor((value - 35) / 40);
142
+ return 16 + 36 * step(r) + 6 * step(g) + step(b);
143
+ }
144
+ /**
145
+ * Number of colors the output supports.
146
+ *
147
+ * Node's heuristics are the base. An empty NO_COLOR counts as unset (no-color.org) and
148
+ * FORCE_COLOR wins over NO_COLOR, which also avoids the warning Node prints when both are
149
+ * set. A forced color never goes below 16 colors, a TERM ending in 256color gets at least
150
+ * 256, and any TERM but dumb gets at least 16.
151
+ *
152
+ * @param stream - Output stream
153
+ * @param env - Environment to read
154
+ * @returns 1, 4, 8 or 24 bits; 1 when the stream is not a terminal or TERM is dumb
155
+ */
156
+ function colorDepth(stream, env) {
157
+ if (!stream.isTTY || env.TERM === "dumb")
158
+ return 1;
159
+ const copy = { ...env };
160
+ const forced = copy.FORCE_COLOR !== undefined && copy.FORCE_COLOR !== "0";
161
+ if (copy.NO_COLOR === "" || forced)
162
+ delete copy.NO_COLOR;
163
+ if (forced && ["", "1", "true"].includes(copy.FORCE_COLOR ?? ""))
164
+ delete copy.FORCE_COLOR;
165
+ let depth = stream.getColorDepth?.(copy) ?? 1;
166
+ if (copy.NO_COLOR !== undefined && !forced)
167
+ return depth;
168
+ if (/-256colou?r$/.test(env.TERM ?? ""))
169
+ depth = Math.max(depth, 8);
170
+ if (env.TERM || forced)
171
+ depth = Math.max(depth, 4);
172
+ return depth;
173
+ }
174
+ /**
175
+ * Tells whether the terminal can draw the Unicode glyphs.
176
+ *
177
+ * @param env - Environment to read
178
+ * @returns False on the Linux console, with CCLEANUP_ASCII set, or without a UTF-8 locale
179
+ */
180
+ function supportsUnicode(env) {
181
+ if (env.CCLEANUP_ASCII || env.TERM === "linux")
182
+ return false;
183
+ if (process.platform === "win32")
184
+ return Boolean(env.WT_SESSION || env.TERM_PROGRAM);
185
+ const locale = env.LC_ALL || env.LC_CTYPE || env.LANG || "";
186
+ return /utf-?8/i.test(locale) || Boolean(env.TERM_PROGRAM);
187
+ }
188
+ /**
189
+ * Reads the background of the terminal from COLORFGBG, set by rxvt, Konsole and others.
190
+ *
191
+ * @param env - Environment to read
192
+ * @returns True for a dark background, false for a light one, undefined when unknown
193
+ */
194
+ export function darkFromEnv(env = process.env) {
195
+ const parts = env.COLORFGBG?.split(";");
196
+ const bg = Number(parts?.[parts.length - 1]);
197
+ if (!parts || Number.isNaN(bg))
198
+ return undefined;
199
+ return bg < 7 || bg === 8;
200
+ }
201
+ /**
202
+ * Reads a background color reply (OSC 11).
203
+ *
204
+ * @param reply - Raw bytes received from the terminal
205
+ * @returns True when the luminance of the color is under one half, undefined without a reply
206
+ */
207
+ function parseOsc11(reply) {
208
+ const match = OSC11_REPLY.exec(reply);
209
+ if (!match)
210
+ return undefined;
211
+ const [r, g, b] = match.slice(1, 4).map((hex) => parseInt(hex, 16) / (16 ** hex.length - 1));
212
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b < 0.5;
213
+ }
214
+ /**
215
+ * Asks the terminal for its background color.
216
+ *
217
+ * The OSC 11 query is followed by a device attributes query, which every terminal
218
+ * answers in order: its reply marks the end, so a terminal without OSC 11 costs no wait.
219
+ *
220
+ * @param input - Terminal input, switched to raw mode for the exchange then restored
221
+ * @param output - Terminal output
222
+ * @param timeoutMs - Longest wait for a silent terminal
223
+ * @returns True for a dark background, false for a light one, undefined when unknown
224
+ */
225
+ export function probeDark(input, output, timeoutMs = 250) {
226
+ const term = process.env.TERM ?? "";
227
+ if (!input.isTTY || !output.isTTY || term === "dumb" || term === "linux") {
228
+ return Promise.resolve(undefined);
229
+ }
230
+ return new Promise((resolve) => {
231
+ let reply = "";
232
+ const wasRaw = input.isRaw;
233
+ const done = (value) => {
234
+ clearTimeout(timer);
235
+ input.removeListener("data", onData);
236
+ input.setRawMode(wasRaw);
237
+ input.pause();
238
+ resolve(value);
239
+ };
240
+ const onData = (chunk) => {
241
+ reply += chunk.toString("latin1");
242
+ if (DA1_REPLY.test(reply))
243
+ done(parseOsc11(reply));
244
+ };
245
+ const timer = setTimeout(() => done(parseOsc11(reply)), timeoutMs);
246
+ input.setRawMode(true);
247
+ input.on("data", onData);
248
+ input.resume();
249
+ output.write(`${ESC}]11;?${BEL}${ESC}[c`);
250
+ });
251
+ }
252
+ /**
253
+ * Builds the theme of an output stream.
254
+ *
255
+ * @param stream - Where the interface is written; a non-terminal output gets plain text
256
+ * @param options - Known background (else COLORFGBG, else dark) and environment to read
257
+ * @returns Capabilities, glyph set and a painter that degrades colors to what the terminal supports
258
+ */
259
+ export function createTheme(stream, options = {}) {
260
+ const env = options.env ?? process.env;
261
+ const enabled = Boolean(stream.isTTY);
262
+ const depth = colorDepth(stream, env);
263
+ const dark = options.dark ?? darkFromEnv(env) ?? true;
264
+ const unicode = supportsUnicode(env);
265
+ const palette = dark ? DARK : LIGHT;
266
+ const color = (rgb, basic, layer) => {
267
+ if (depth >= 24)
268
+ return `${layer};2;${rgb.join(";")}`;
269
+ if (depth >= 8)
270
+ return `${layer};5;${to256(rgb)}`;
271
+ if (depth >= 4)
272
+ return String(layer === 48 ? basic + 10 : basic);
273
+ return "";
274
+ };
275
+ const paint = (text, style = {}) => {
276
+ if (!enabled || text === "")
277
+ return text;
278
+ const codes = [];
279
+ if (style.bold)
280
+ codes.push("1");
281
+ if (style.dim)
282
+ codes.push("2");
283
+ if (style.strike)
284
+ codes.push("9");
285
+ if (style.inverse)
286
+ codes.push("7");
287
+ if (style.rgb)
288
+ codes.push(color(style.rgb, BASIC.accent, 38));
289
+ else if (style.fg)
290
+ codes.push(color(palette[style.fg], BASIC[style.fg], 38));
291
+ if (style.bgRgb)
292
+ codes.push(color(style.bgRgb, BASIC.accent, 48));
293
+ else if (style.bg)
294
+ codes.push(color(palette[style.bg], BASIC[style.bg], 48));
295
+ const open = codes.filter(Boolean).join(";");
296
+ return open ? `${ESC}[${open}m${text}${ESC}[0m` : text;
297
+ };
298
+ return {
299
+ enabled,
300
+ depth,
301
+ dark,
302
+ unicode,
303
+ glyphs: unicode ? UNICODE_GLYPHS : ASCII_GLYPHS,
304
+ paint,
305
+ rgb: (tone) => palette[tone],
306
+ };
307
+ }