ansi-quantone 0.0.0-stage → 0.9.1
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.
- package/CHANGELOG.md +22 -0
- package/README.md +48 -2
- package/dst/ansi-quantone-api-color.d.ts +10 -0
- package/dst/ansi-quantone-api-color.js +44 -0
- package/dst/ansi-quantone-api-debug.d.ts +26 -0
- package/dst/ansi-quantone-api-debug.js +279 -0
- package/dst/ansi-quantone-api-mapping.d.ts +32 -0
- package/dst/ansi-quantone-api-mapping.js +55 -0
- package/dst/ansi-quantone-api-sgr.d.ts +30 -0
- package/dst/ansi-quantone-api-sgr.js +150 -0
- package/dst/ansi-quantone-api-stream.d.ts +7 -0
- package/dst/ansi-quantone-api-stream.js +194 -0
- package/dst/ansi-quantone-api-terminal.d.ts +14 -0
- package/dst/ansi-quantone-api-terminal.js +142 -0
- package/dst/ansi-quantone-api-types.d.ts +28 -0
- package/dst/ansi-quantone-api-types.js +6 -0
- package/dst/ansi-quantone-api.3 +87 -0
- package/dst/ansi-quantone-api.d.ts +11 -0
- package/dst/ansi-quantone-api.js +196 -0
- package/dst/ansi-quantone-cli.d.ts +7 -0
- package/dst/ansi-quantone-cli.js +256 -0
- package/dst/ansi-quantone.1 +123 -0
- package/etc/ansi-quantone.yaml +39 -0
- package/etc/eslint.mjs +81 -0
- package/etc/stx.conf +40 -0
- package/etc/tsc.json +25 -0
- package/package.json +57 -5
- package/src/ansi-quantone-api-color.ts +48 -0
- package/src/ansi-quantone-api-debug.ts +300 -0
- package/src/ansi-quantone-api-mapping.ts +77 -0
- package/src/ansi-quantone-api-sgr.ts +183 -0
- package/src/ansi-quantone-api-stream.ts +207 -0
- package/src/ansi-quantone-api-terminal.ts +156 -0
- package/src/ansi-quantone-api-types.ts +40 -0
- package/src/ansi-quantone-api.md +185 -0
- package/src/ansi-quantone-api.ts +223 -0
- package/src/ansi-quantone-cli.md +212 -0
- package/src/ansi-quantone-cli.ts +259 -0
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
** ansi-quantone -- Recolor ANSI Color Sequences of CLI Commands onto a Toned Palette
|
|
3
|
+
** Copyright (c) 2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
|
|
4
|
+
** Licensed under MIT license
|
|
5
|
+
*/
|
|
6
|
+
import { quantone } from "quantone";
|
|
7
|
+
import { classifyColor, rgbToOKLab } from "./ansi-quantone-api-color.js";
|
|
8
|
+
/* map a color onto the palette and return its truecolor SGR parameters */
|
|
9
|
+
export const mapColor = (options, color, kind) => {
|
|
10
|
+
const n = parseInt(quantone(options, color).substring(1), 16);
|
|
11
|
+
return [kind === "fg" ? 38 : 48, 2, (n >> 16) & 0xFF, (n >> 8) & 0xFF, n & 0xFF];
|
|
12
|
+
};
|
|
13
|
+
/* reduce an RGB color onto the perceptually nearest ANSI color index */
|
|
14
|
+
const reduceColor = (rc, lab, rgb) => {
|
|
15
|
+
let index = rc.reduced.get(rgb);
|
|
16
|
+
if (index === undefined) {
|
|
17
|
+
const [L, A, B] = rgbToOKLab(rgb);
|
|
18
|
+
let best = Infinity;
|
|
19
|
+
index = 0;
|
|
20
|
+
for (let i = 0; i < lab.length; i++) {
|
|
21
|
+
const d = (L - lab[i][0]) ** 2 + (A - lab[i][1]) ** 2 + (B - lab[i][2]) ** 2;
|
|
22
|
+
if (d < best) {
|
|
23
|
+
best = d;
|
|
24
|
+
index = i;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
if (rc.reduced.size >= 4096)
|
|
28
|
+
rc.reduced.clear();
|
|
29
|
+
rc.reduced.set(rgb, index);
|
|
30
|
+
}
|
|
31
|
+
return index;
|
|
32
|
+
};
|
|
33
|
+
/* check whether a color of a mapping rule matches an input color */
|
|
34
|
+
const matchColor = (rc, spec, color) => {
|
|
35
|
+
switch (spec.type) {
|
|
36
|
+
case "wildcard": return true;
|
|
37
|
+
case "default": return color.type === "default";
|
|
38
|
+
case "index": return color.type === "index" && color.index === spec.index;
|
|
39
|
+
case "rgb": return color.type === "rgb" && color.rgb === spec.rgb;
|
|
40
|
+
case "range": return color.type === "index" && color.index >= spec.from && color.index <= spec.to;
|
|
41
|
+
case "class": {
|
|
42
|
+
if (color.type === "default")
|
|
43
|
+
return false;
|
|
44
|
+
const cls = classifyColor(color.type === "index" ? parseInt(rc.ansi[color.index].substring(1), 16) : color.rgb);
|
|
45
|
+
return (spec.family === null || spec.family === cls.family)
|
|
46
|
+
&& (spec.tone === null || spec.tone === cls.tone);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
/* check whether two input colors are the same */
|
|
51
|
+
const sameColor = (a, b) => (a.type === "default" && b.type === "default")
|
|
52
|
+
|| (a.type === "index" && b.type === "index" && a.index === b.index)
|
|
53
|
+
|| (a.type === "rgb" && b.type === "rgb" && a.rgb === b.rgb);
|
|
54
|
+
/* map an input color onto the palette and return its SGR parameters
|
|
55
|
+
(where the default foreground gets the mapped default foreground, if any) */
|
|
56
|
+
const colorSGR = (rc, color, kind) => {
|
|
57
|
+
if (color.type === "default")
|
|
58
|
+
return kind === "fg" ? (rc.fgSGR ?? [39]) : [49];
|
|
59
|
+
const hex = color.type === "index" ? rc.ansi[color.index] : "#" + color.rgb.toString(16).padStart(6, "0");
|
|
60
|
+
return mapColor(rc.options, hex, kind);
|
|
61
|
+
};
|
|
62
|
+
/* reset the current source and target colors to the terminal default colors */
|
|
63
|
+
export const resetColors = (rc) => {
|
|
64
|
+
rc.src = { fg: { type: "default" }, bg: { type: "default" } };
|
|
65
|
+
rc.dst = { fg: { type: "default" }, bg: { type: "default" } };
|
|
66
|
+
};
|
|
67
|
+
/* transform an SGR parameter sequence, rewriting all colors onto the palette:
|
|
68
|
+
track the current source colors (with RGB colors optionally reduced onto ANSI colors),
|
|
69
|
+
apply the mapping rules (last match wins), and emit the target colors after all
|
|
70
|
+
non-color attributes (which are passed through unchanged) -- the colors set by
|
|
71
|
+
the sequence always, the other ones only if their mapping changed */
|
|
72
|
+
export const transformSGR = (params, rc) => {
|
|
73
|
+
const result = [];
|
|
74
|
+
const set = { fg: false, bg: false };
|
|
75
|
+
let changed = false;
|
|
76
|
+
const setColor = (kind, color) => {
|
|
77
|
+
rc.src[kind] = color;
|
|
78
|
+
set[kind] = true;
|
|
79
|
+
changed = true;
|
|
80
|
+
};
|
|
81
|
+
let i = 0;
|
|
82
|
+
while (i < params.length) {
|
|
83
|
+
const p = params[i];
|
|
84
|
+
if (p === 0) {
|
|
85
|
+
/* reset: re-establish the mapped default foreground, if any */
|
|
86
|
+
result.push(0);
|
|
87
|
+
resetColors(rc);
|
|
88
|
+
set.fg = rc.fgSGR !== null;
|
|
89
|
+
set.bg = false;
|
|
90
|
+
changed = true;
|
|
91
|
+
i++;
|
|
92
|
+
}
|
|
93
|
+
else if (p === 39 || p === 49) {
|
|
94
|
+
/* default color */
|
|
95
|
+
setColor(p === 39 ? "fg" : "bg", { type: "default" });
|
|
96
|
+
i++;
|
|
97
|
+
}
|
|
98
|
+
else if ((p >= 30 && p <= 37) || (p >= 40 && p <= 47)) {
|
|
99
|
+
/* basic color: ANSI color index 0-7 */
|
|
100
|
+
setColor(p < 40 ? "fg" : "bg", { type: "index", index: p % 10 });
|
|
101
|
+
i++;
|
|
102
|
+
}
|
|
103
|
+
else if ((p >= 90 && p <= 97) || (p >= 100 && p <= 107)) {
|
|
104
|
+
/* bright color: ANSI color index 8-15 */
|
|
105
|
+
setColor(p < 100 ? "fg" : "bg", { type: "index", index: p % 10 + 8 });
|
|
106
|
+
i++;
|
|
107
|
+
}
|
|
108
|
+
else if ((p === 38 || p === 48) && params[i + 1] === 5
|
|
109
|
+
&& i + 2 < params.length && params[i + 2] <= 255) {
|
|
110
|
+
/* 256-color: ANSI color index 0-255 */
|
|
111
|
+
setColor(p === 38 ? "fg" : "bg", { type: "index", index: params[i + 2] });
|
|
112
|
+
i += 3;
|
|
113
|
+
}
|
|
114
|
+
else if ((p === 38 || p === 48) && params[i + 1] === 2
|
|
115
|
+
&& i + 4 < params.length && params[i + 2] <= 255 && params[i + 3] <= 255 && params[i + 4] <= 255) {
|
|
116
|
+
/* RGB/truecolor (optionally reduced onto the nearest ANSI color) */
|
|
117
|
+
const rgb = (params[i + 2] << 16) | (params[i + 3] << 8) | params[i + 4];
|
|
118
|
+
setColor(p === 38 ? "fg" : "bg", rc.lab !== null ?
|
|
119
|
+
{ type: "index", index: reduceColor(rc, rc.lab, rgb) } : { type: "rgb", rgb });
|
|
120
|
+
i += 5;
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
/* non-color attribute or malformed extended color */
|
|
124
|
+
result.push(p);
|
|
125
|
+
i++;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (!changed)
|
|
129
|
+
return result;
|
|
130
|
+
/* apply the mapping rules (all matching ones in order, so the last match wins) */
|
|
131
|
+
let { fg, bg } = rc.src;
|
|
132
|
+
for (const rule of rc.mappings) {
|
|
133
|
+
if (matchColor(rc, rule.fromFg, rc.src.fg) && matchColor(rc, rule.fromBg, rc.src.bg)) {
|
|
134
|
+
if (rule.toFg.type !== "wildcard")
|
|
135
|
+
fg = rule.toFg;
|
|
136
|
+
if (rule.toBg.type !== "wildcard")
|
|
137
|
+
bg = rule.toBg;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/* emit the target colors */
|
|
141
|
+
for (const [kind, color] of [["fg", fg], ["bg", bg]]) {
|
|
142
|
+
if (set[kind] || !sameColor(color, rc.dst[kind])) {
|
|
143
|
+
result.push(...colorSGR(rc, color, kind));
|
|
144
|
+
rc.dst[kind] = color;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return result;
|
|
148
|
+
};
|
|
149
|
+
/* determine whether a string command sets (OSC 11) or resets (OSC 111) the default background */
|
|
150
|
+
export const isBgChange = (seq) => /^\x1b\](?:11;(?!\?)|111(?:;|\x07|\x1b))/.test(seq.toString("latin1"));
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
** ansi-quantone -- Recolor ANSI Color Sequences of CLI Commands onto a Toned Palette
|
|
3
|
+
** Copyright (c) 2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
|
|
4
|
+
** Licensed under MIT license
|
|
5
|
+
*/
|
|
6
|
+
import { type Recolor } from "./ansi-quantone-api-sgr.js";
|
|
7
|
+
export declare const processChunk: (chunk: Buffer, rc: Recolor) => Buffer;
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
** ansi-quantone -- Recolor ANSI Color Sequences of CLI Commands onto a Toned Palette
|
|
3
|
+
** Copyright (c) 2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
|
|
4
|
+
** Licensed under MIT license
|
|
5
|
+
*/
|
|
6
|
+
import { transformSGR, resetColors, isBgChange } from "./ansi-quantone-api-sgr.js";
|
|
7
|
+
/* ==== stream processing with partial sequence buffering ==== */
|
|
8
|
+
/* parser states for the escape sequence state machine */
|
|
9
|
+
const S_NORMAL = 0; /* plain text, scanning for ESC */
|
|
10
|
+
const S_ESC = 1; /* just saw ESC, determining sequence type */
|
|
11
|
+
const S_ESC_INTER = 2; /* ESC + intermediate bytes (nF sequence) */
|
|
12
|
+
const S_CSI_PARAM = 3; /* CSI parameter bytes */
|
|
13
|
+
const S_CSI_INTER = 4; /* CSI intermediate bytes */
|
|
14
|
+
const S_STR_BODY = 5; /* string command body (OSC/DCS/APC/PM/SOS) */
|
|
15
|
+
const S_STR_ESC = 6; /* ESC inside string command (potential ST) */
|
|
16
|
+
/* process a raw byte chunk through the escape sequence state machine
|
|
17
|
+
(operates on raw bytes so UTF-8 multi-byte sequences are never decoded/buffered;
|
|
18
|
+
ESC and all escape sequence bytes are in the ASCII range 0x00-0x7F which never
|
|
19
|
+
overlaps with UTF-8 continuation bytes 0x80-0xBF, so raw scanning is safe) */
|
|
20
|
+
export const processChunk = (chunk, rc) => {
|
|
21
|
+
const buf = rc.buf.length === 0 ? chunk : Buffer.concat([rc.buf, chunk]);
|
|
22
|
+
const out = [];
|
|
23
|
+
let i = 0;
|
|
24
|
+
let seqStart = -1;
|
|
25
|
+
let state = S_NORMAL;
|
|
26
|
+
while (i < buf.length) {
|
|
27
|
+
const ch = buf[i];
|
|
28
|
+
switch (state) {
|
|
29
|
+
case S_NORMAL: {
|
|
30
|
+
/* fast-scan for next ESC byte */
|
|
31
|
+
const escIdx = buf.indexOf(0x1B, i);
|
|
32
|
+
if (escIdx === -1) {
|
|
33
|
+
out.push(buf.subarray(i));
|
|
34
|
+
i = buf.length;
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
if (escIdx > i)
|
|
38
|
+
out.push(buf.subarray(i, escIdx));
|
|
39
|
+
seqStart = escIdx;
|
|
40
|
+
state = S_ESC;
|
|
41
|
+
i = escIdx + 1;
|
|
42
|
+
}
|
|
43
|
+
break;
|
|
44
|
+
}
|
|
45
|
+
case S_ESC:
|
|
46
|
+
if (ch === 0x5B) {
|
|
47
|
+
/* "[" → CSI sequence */
|
|
48
|
+
state = S_CSI_PARAM;
|
|
49
|
+
i++;
|
|
50
|
+
}
|
|
51
|
+
else if (ch === 0x5D || ch === 0x50 || ch === 0x5F
|
|
52
|
+
|| ch === 0x5E || ch === 0x58) {
|
|
53
|
+
/* "]" / "P" / "_" / "^" / "X" → string command */
|
|
54
|
+
state = S_STR_BODY;
|
|
55
|
+
i++;
|
|
56
|
+
}
|
|
57
|
+
else if (ch >= 0x20 && ch <= 0x2F) {
|
|
58
|
+
/* intermediate byte → nF escape sequence */
|
|
59
|
+
state = S_ESC_INTER;
|
|
60
|
+
i++;
|
|
61
|
+
}
|
|
62
|
+
else if (ch >= 0x30 && ch <= 0x7E) {
|
|
63
|
+
/* final byte → simple two-byte ESC sequence
|
|
64
|
+
(after "c" (RIS) re-establish the mapped default colors) */
|
|
65
|
+
out.push(buf.subarray(seqStart, i + 1));
|
|
66
|
+
if (ch === 0x63) {
|
|
67
|
+
out.push(rc.defaults);
|
|
68
|
+
resetColors(rc);
|
|
69
|
+
}
|
|
70
|
+
state = S_NORMAL;
|
|
71
|
+
i++;
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
/* unexpected byte → flush ESC and re-process */
|
|
75
|
+
out.push(buf.subarray(seqStart, seqStart + 1));
|
|
76
|
+
state = S_NORMAL;
|
|
77
|
+
i = seqStart + 1;
|
|
78
|
+
}
|
|
79
|
+
break;
|
|
80
|
+
case S_ESC_INTER:
|
|
81
|
+
if (ch >= 0x20 && ch <= 0x2F) {
|
|
82
|
+
/* more intermediate bytes */
|
|
83
|
+
i++;
|
|
84
|
+
}
|
|
85
|
+
else if (ch >= 0x30 && ch <= 0x7E) {
|
|
86
|
+
/* final byte → complete nF sequence */
|
|
87
|
+
out.push(buf.subarray(seqStart, i + 1));
|
|
88
|
+
state = S_NORMAL;
|
|
89
|
+
i++;
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
/* unexpected → flush and re-process */
|
|
93
|
+
out.push(buf.subarray(seqStart, i));
|
|
94
|
+
state = S_NORMAL;
|
|
95
|
+
}
|
|
96
|
+
break;
|
|
97
|
+
case S_CSI_PARAM:
|
|
98
|
+
if (ch >= 0x30 && ch <= 0x3F) {
|
|
99
|
+
/* parameter byte (digits, ";", "?", ">", etc.) */
|
|
100
|
+
i++;
|
|
101
|
+
}
|
|
102
|
+
else if (ch >= 0x20 && ch <= 0x2F) {
|
|
103
|
+
/* intermediate byte */
|
|
104
|
+
state = S_CSI_INTER;
|
|
105
|
+
i++;
|
|
106
|
+
}
|
|
107
|
+
else if (ch >= 0x40 && ch <= 0x7E) {
|
|
108
|
+
/* final byte → CSI sequence complete */
|
|
109
|
+
if (ch === 0x6D) {
|
|
110
|
+
/* "m" → SGR: transform colors */
|
|
111
|
+
const paramStr = buf.subarray(seqStart + 2, i).toString("ascii");
|
|
112
|
+
if (/^[0-9;]*$/.test(paramStr)) {
|
|
113
|
+
const params = paramStr === "" ? [0] : paramStr.split(";").map(Number);
|
|
114
|
+
const mapped = transformSGR(params, rc);
|
|
115
|
+
out.push(Buffer.from(`\x1b[${mapped.join(";")}m`));
|
|
116
|
+
}
|
|
117
|
+
else
|
|
118
|
+
out.push(buf.subarray(seqStart, i + 1));
|
|
119
|
+
}
|
|
120
|
+
else
|
|
121
|
+
out.push(buf.subarray(seqStart, i + 1));
|
|
122
|
+
state = S_NORMAL;
|
|
123
|
+
i++;
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
/* unexpected → flush and re-process */
|
|
127
|
+
out.push(buf.subarray(seqStart, i));
|
|
128
|
+
state = S_NORMAL;
|
|
129
|
+
}
|
|
130
|
+
break;
|
|
131
|
+
case S_CSI_INTER:
|
|
132
|
+
if (ch >= 0x20 && ch <= 0x2F) {
|
|
133
|
+
/* more intermediate bytes */
|
|
134
|
+
i++;
|
|
135
|
+
}
|
|
136
|
+
else if (ch >= 0x40 && ch <= 0x7E) {
|
|
137
|
+
/* final byte → CSI sequence complete (non-SGR)
|
|
138
|
+
(after "CSI ! p" (DECSTR) re-establish the mapped default colors) */
|
|
139
|
+
out.push(buf.subarray(seqStart, i + 1));
|
|
140
|
+
if (ch === 0x70 && buf.subarray(seqStart + 2, i).toString("ascii") === "!") {
|
|
141
|
+
out.push(rc.defaults);
|
|
142
|
+
resetColors(rc);
|
|
143
|
+
}
|
|
144
|
+
state = S_NORMAL;
|
|
145
|
+
i++;
|
|
146
|
+
}
|
|
147
|
+
else {
|
|
148
|
+
/* unexpected → flush and re-process */
|
|
149
|
+
out.push(buf.subarray(seqStart, i));
|
|
150
|
+
state = S_NORMAL;
|
|
151
|
+
}
|
|
152
|
+
break;
|
|
153
|
+
case S_STR_BODY:
|
|
154
|
+
if (ch === 0x1B) {
|
|
155
|
+
/* ESC inside string command → potential ST */
|
|
156
|
+
state = S_STR_ESC;
|
|
157
|
+
i++;
|
|
158
|
+
}
|
|
159
|
+
else if (ch === 0x07) {
|
|
160
|
+
/* BEL terminates string commands (at least OSC)
|
|
161
|
+
(suppress default background changes while it is mapped) */
|
|
162
|
+
if (rc.bgOSC === null || !isBgChange(buf.subarray(seqStart, i + 1)))
|
|
163
|
+
out.push(buf.subarray(seqStart, i + 1));
|
|
164
|
+
state = S_NORMAL;
|
|
165
|
+
i++;
|
|
166
|
+
}
|
|
167
|
+
else
|
|
168
|
+
i++;
|
|
169
|
+
break;
|
|
170
|
+
case S_STR_ESC:
|
|
171
|
+
if (ch === 0x5C) {
|
|
172
|
+
/* "\" → ST (String Terminator) → string command complete
|
|
173
|
+
(suppress default background changes while it is mapped) */
|
|
174
|
+
if (rc.bgOSC === null || !isBgChange(buf.subarray(seqStart, i + 1)))
|
|
175
|
+
out.push(buf.subarray(seqStart, i + 1));
|
|
176
|
+
state = S_NORMAL;
|
|
177
|
+
i++;
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
/* not ST → ESC starts a new sequence (malformed input) */
|
|
181
|
+
out.push(buf.subarray(seqStart, i - 1));
|
|
182
|
+
seqStart = i - 1;
|
|
183
|
+
state = S_ESC;
|
|
184
|
+
}
|
|
185
|
+
break;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/* keep any incomplete escape sequence in the buffer */
|
|
189
|
+
if (state !== S_NORMAL)
|
|
190
|
+
rc.buf = Buffer.from(buf.subarray(seqStart));
|
|
191
|
+
else
|
|
192
|
+
rc.buf = Buffer.alloc(0);
|
|
193
|
+
return Buffer.concat(out);
|
|
194
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
** ansi-quantone -- Recolor ANSI Color Sequences of CLI Commands onto a Toned Palette
|
|
3
|
+
** Copyright (c) 2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
|
|
4
|
+
** Licensed under MIT license
|
|
5
|
+
*/
|
|
6
|
+
import type { TerminalIO } from "./ansi-quantone-api-types.js";
|
|
7
|
+
export declare const xtermColors: string[];
|
|
8
|
+
export declare const queryColors: (terminal: TerminalIO, codes: string[]) => Promise<{
|
|
9
|
+
colors: Map<string, string>;
|
|
10
|
+
rest: Buffer;
|
|
11
|
+
}>;
|
|
12
|
+
export declare const loadColors: (file: string) => Map<string, string>;
|
|
13
|
+
export declare const saveColors: (file: string, colors: Map<string, string>) => void;
|
|
14
|
+
export declare const stdioTerminal: () => TerminalIO;
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
** ansi-quantone -- Recolor ANSI Color Sequences of CLI Commands onto a Toned Palette
|
|
3
|
+
** Copyright (c) 2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
|
|
4
|
+
** Licensed under MIT license
|
|
5
|
+
*/
|
|
6
|
+
import process from "node:process";
|
|
7
|
+
import crypto from "node:crypto";
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
import os from "node:os";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { spawnSync } from "node:child_process";
|
|
12
|
+
import ttyAttr from "tty-attr";
|
|
13
|
+
/* ==== terminal color query ==== */
|
|
14
|
+
/* the canonical xterm RGB values of the ANSI colors 0-255
|
|
15
|
+
(the fallbacks for the colors not reported by the terminal) */
|
|
16
|
+
export const xtermColors = Array.from({ length: 256 }, (_, i) => {
|
|
17
|
+
const level = (v) => v === 0 ? 0 : 55 + 40 * v;
|
|
18
|
+
let n;
|
|
19
|
+
if (i < 16)
|
|
20
|
+
n = [0x000000, 0xcd0000, 0x00cd00, 0xcdcd00, 0x0000ee, 0xcd00cd, 0x00cdcd, 0xe5e5e5,
|
|
21
|
+
0x7f7f7f, 0xff0000, 0x00ff00, 0xffff00, 0x5c5cff, 0xff00ff, 0x00ffff, 0xffffff][i];
|
|
22
|
+
else if (i < 232)
|
|
23
|
+
n = (level(Math.floor((i - 16) / 36)) << 16) | (level(Math.floor((i - 16) / 6) % 6) << 8) | level((i - 16) % 6);
|
|
24
|
+
else
|
|
25
|
+
n = (8 + 10 * (i - 232)) * 0x010101;
|
|
26
|
+
return "#" + n.toString(16).padStart(6, "0");
|
|
27
|
+
});
|
|
28
|
+
/* query the terminal colors via OSC 4 (ANSI color "4;<n>"), OSC 10 (default foreground
|
|
29
|
+
"10"), and OSC 11 (default background "11"), terminated by a DA1 query which every
|
|
30
|
+
terminal answers, and return the received colors plus all other received input bytes */
|
|
31
|
+
export const queryColors = (terminal, codes) => {
|
|
32
|
+
return new Promise((resolve) => {
|
|
33
|
+
let data = "";
|
|
34
|
+
const finish = () => {
|
|
35
|
+
clearTimeout(timer);
|
|
36
|
+
offData();
|
|
37
|
+
const colors = new Map();
|
|
38
|
+
const re = /\x1b\]((?:4;)?\d+);rgb:([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})\/([0-9a-fA-F]{1,4})(?:\x07|\x1b\\)/g;
|
|
39
|
+
for (const m of data.matchAll(re)) {
|
|
40
|
+
/* scale each 1-4 digit hex channel onto 8 bits */
|
|
41
|
+
const hex = m.slice(2, 5).map((c) => Math.round(parseInt(c, 16) / (16 ** c.length - 1) * 255).toString(16).padStart(2, "0"));
|
|
42
|
+
colors.set(m[1], "#" + hex.join(""));
|
|
43
|
+
}
|
|
44
|
+
const rest = data.replace(re, "").replace(/\x1b\[\?[0-9;]*c/, "");
|
|
45
|
+
resolve({ colors, rest: Buffer.from(rest, "latin1") });
|
|
46
|
+
};
|
|
47
|
+
const onData = (chunk) => {
|
|
48
|
+
data += chunk.toString("latin1");
|
|
49
|
+
if (/\x1b\[\?[0-9;]*c/.test(data))
|
|
50
|
+
finish();
|
|
51
|
+
};
|
|
52
|
+
const timer = setTimeout(finish, 1000);
|
|
53
|
+
const offData = terminal.onData(onData);
|
|
54
|
+
terminal.write(codes.map((code) => `\x1b]${code};?\x1b\\`).join("") + "\x1b[c");
|
|
55
|
+
});
|
|
56
|
+
};
|
|
57
|
+
/* load the cached terminal colors (or none on a missing or broken cache file) */
|
|
58
|
+
export const loadColors = (file) => {
|
|
59
|
+
try {
|
|
60
|
+
const data = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
61
|
+
if (typeof data !== "object" || data === null || Array.isArray(data))
|
|
62
|
+
return new Map();
|
|
63
|
+
return new Map(Object.entries(data).filter((entry) => typeof entry[1] === "string" && /^#[0-9a-f]{6}$/.test(entry[1])));
|
|
64
|
+
}
|
|
65
|
+
catch (_err) {
|
|
66
|
+
return new Map();
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
/* save the queried terminal colors over the cached ones (ignoring any failures),
|
|
70
|
+
atomically via a temporary file, so concurrent runs never read a partial file */
|
|
71
|
+
export const saveColors = (file, colors) => {
|
|
72
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
73
|
+
try {
|
|
74
|
+
const merged = new Map([...loadColors(file), ...colors]);
|
|
75
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
76
|
+
fs.writeFileSync(temp, JSON.stringify(Object.fromEntries(merged)) + "\n", { mode: 0o600 });
|
|
77
|
+
fs.renameSync(temp, file);
|
|
78
|
+
}
|
|
79
|
+
catch (_err) {
|
|
80
|
+
try {
|
|
81
|
+
fs.unlinkSync(temp);
|
|
82
|
+
}
|
|
83
|
+
catch (_err2) { /* ignore */ }
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
/* ==== process stdio terminal ==== */
|
|
87
|
+
/* determine the cache file of the queried colors of the process stdio terminal: only within
|
|
88
|
+
tmux, where e.g. popups do not answer color queries, and per tmux client (as identified by
|
|
89
|
+
the server socket and the client PID), as each client can be a different terminal */
|
|
90
|
+
const cacheFile = () => {
|
|
91
|
+
const tmux = process.env.TMUX ?? "";
|
|
92
|
+
if (tmux === "")
|
|
93
|
+
return undefined;
|
|
94
|
+
const result = spawnSync("tmux", ["display-message", "-p", "#{client_pid}"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 2000 });
|
|
95
|
+
const client = result.status === 0 ? result.stdout.trim() : "";
|
|
96
|
+
if (!/^\d+$/.test(client))
|
|
97
|
+
return undefined;
|
|
98
|
+
const socket = tmux.replace(/,\d+,\d+$/, "");
|
|
99
|
+
const dir = path.join(process.env.XDG_CACHE_HOME ?? path.join(os.homedir(), ".cache"), "ansi-quantone");
|
|
100
|
+
const key = crypto.createHash("sha1").update(`${socket}:${client}`).digest("hex").substring(0, 16);
|
|
101
|
+
return path.join(dir, `colors-tmux-${key}.json`);
|
|
102
|
+
};
|
|
103
|
+
/* the terminal I/O of the process stdio (the default terminal of a recoloring run) */
|
|
104
|
+
export const stdioTerminal = () => ({
|
|
105
|
+
query: process.stdin.isTTY === true,
|
|
106
|
+
cache: cacheFile(),
|
|
107
|
+
columns: () => process.stdout.columns ?? 80,
|
|
108
|
+
rows: () => process.stdout.rows ?? 24,
|
|
109
|
+
write: (data, cb) => process.stdout.write(data, cb),
|
|
110
|
+
onDrain: (cb) => { process.stdout.once("drain", cb); },
|
|
111
|
+
onData: (cb) => {
|
|
112
|
+
process.stdin.on("data", cb);
|
|
113
|
+
process.stdin.resume();
|
|
114
|
+
return () => {
|
|
115
|
+
process.stdin.off("data", cb);
|
|
116
|
+
process.stdin.pause();
|
|
117
|
+
};
|
|
118
|
+
},
|
|
119
|
+
onResize: (cb) => {
|
|
120
|
+
process.stdout.on("resize", cb);
|
|
121
|
+
return () => { process.stdout.off("resize", cb); };
|
|
122
|
+
},
|
|
123
|
+
onSignal: (cb) => {
|
|
124
|
+
const handlers = ["SIGTERM", "SIGHUP"].map((signal) => [signal, () => { cb(signal); }]);
|
|
125
|
+
for (const [signal, handler] of handlers)
|
|
126
|
+
process.on(signal, handler);
|
|
127
|
+
return () => {
|
|
128
|
+
for (const [signal, handler] of handlers)
|
|
129
|
+
process.off(signal, handler);
|
|
130
|
+
};
|
|
131
|
+
},
|
|
132
|
+
setup: () => {
|
|
133
|
+
if (process.stdin.isTTY) {
|
|
134
|
+
ttyAttr.preserveAttr();
|
|
135
|
+
ttyAttr.setRawMode();
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
restore: () => {
|
|
139
|
+
if (process.stdin.isTTY)
|
|
140
|
+
ttyAttr.restoreAttr();
|
|
141
|
+
}
|
|
142
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
** ansi-quantone -- Recolor ANSI Color Sequences of CLI Commands onto a Toned Palette
|
|
3
|
+
** Copyright (c) 2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
|
|
4
|
+
** Licensed under MIT license
|
|
5
|
+
*/
|
|
6
|
+
import type { QuantoneOptions, QuantoneColor } from "quantone";
|
|
7
|
+
export type DefaultColor = QuantoneColor | "auto" | "none";
|
|
8
|
+
export type Config = {
|
|
9
|
+
palette: QuantoneOptions;
|
|
10
|
+
foreground: DefaultColor;
|
|
11
|
+
background: DefaultColor;
|
|
12
|
+
reduce: boolean;
|
|
13
|
+
mappings: string[];
|
|
14
|
+
debug: boolean;
|
|
15
|
+
};
|
|
16
|
+
export type TerminalIO = {
|
|
17
|
+
query: boolean;
|
|
18
|
+
cache?: string;
|
|
19
|
+
columns: () => number;
|
|
20
|
+
rows: () => number;
|
|
21
|
+
write: (data: Buffer | string, cb?: () => void) => boolean;
|
|
22
|
+
onDrain: (cb: () => void) => void;
|
|
23
|
+
onData: (cb: (data: Buffer) => void) => () => void;
|
|
24
|
+
onResize: (cb: () => void) => () => void;
|
|
25
|
+
onSignal: (cb: (signal: "SIGTERM" | "SIGHUP") => void) => () => void;
|
|
26
|
+
setup: () => void;
|
|
27
|
+
restore: () => void;
|
|
28
|
+
};
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
.TH "ANSI-QUANTONE-API" "3" "December 2026" "" ""
|
|
2
|
+
.SH "NAME"
|
|
3
|
+
\fBansi-quantone-api\fR - Recolor ANSI Color Sequences of CLI Commands onto a Toned Palette
|
|
4
|
+
.SH "SYNOPSIS"
|
|
5
|
+
.P
|
|
6
|
+
.RS 2
|
|
7
|
+
.nf
|
|
8
|
+
import { run, stdioTerminal, type Config, type TerminalIO } from "ansi-quantone"
|
|
9
|
+
|
|
10
|
+
run(config: Config, command: string, args?: string\[lB]\[rB], terminal?: TerminalIO): Promise<number>
|
|
11
|
+
stdioTerminal(): TerminalIO
|
|
12
|
+
.fi
|
|
13
|
+
.RE
|
|
14
|
+
.SH "DESCRIPTION"
|
|
15
|
+
.P
|
|
16
|
+
\fBansi-quantone-api\fR, the API of \fIRecolor ANSI Color Sequences of CLI Commands onto a Toned Palette\fR, runs an arbitrary command-line or Terminal User Interface (TUI) application inside a Pseudo-Terminal (PTY) on a terminal, intercepts the ANSI Select Graphic Rendition (SGR) color escape sequences of its output, and maps every foreground and background color onto a toned palette with the color quantizer \fBQuantone\fR. It is used by the command-line tool \fBansi-quantone\fR(1).
|
|
17
|
+
.P
|
|
18
|
+
All explicit colors are recolored: the ANSI basic 8 colors, the bright 8 colors, the 256-color palette, and RGB/truecolor. The RGB values of the ANSI colors are queried from the terminal (via \fBOSC 4\fR), so the actual color theme of the terminal is honored, with the canonical \fBxterm\fR RGB values as the fallback for all colors not reported. The recolored colors are always emitted as RGB/truecolor.
|
|
19
|
+
.P
|
|
20
|
+
The terminal default colors carry no color value of their own. Hence, their input colors are either given explicitly or queried from the terminal (via \fBOSC 10\fR / \fBOSC 11\fR), and then mapped onto the palette as well. The default foreground is established as an explicit foreground color at startup and after every SGR 39 (default foreground), SGR 0 (reset), RIS (full reset), and DECSTR (soft reset). The default background instead is changed in the terminal itself (via \fBOSC 11\fR), as only this also covers all never written screen cells. On exit, it is restored to its originally queried color (via \fBOSC 11\fR) and then reset (via \fBOSC 111\fR), and any default background changes of the \fIcommand\fR itself are suppressed meanwhile.
|
|
21
|
+
.P
|
|
22
|
+
If the terminal has a cache file, all answered colors are stored there (atomically, over the previously cached ones), and if it answers no color queries at all (e.g. a \fBtmux\fR popup), the cached colors are used instead of the fallbacks.
|
|
23
|
+
.SH "API"
|
|
24
|
+
.RS 0
|
|
25
|
+
.IP \(bu 4
|
|
26
|
+
\fBrun(\fR\fIconfig\fR\fB,\fR \fIcommand\fR\fB,\fR \fIargs\fR\fB,\fR \fIterminal\fR\fB)\fR: Spawns the \fIcommand\fR with its arguments \fIargs\fR (default: none) in a PTY, with the current working directory and environment of the process, and recolors its output onto the \fIterminal\fR (default: \fBstdioTerminal()\fR) according to the \fIconfig\fR. It resolves to the exit code of the \fIcommand\fR, once it exited and the \fIterminal\fR is restored again. It rejects with an \fBError\fR on an invalid \fIconfig\fR or if the \fIcommand\fR cannot be spawned.
|
|
27
|
+
.IP \(bu 4
|
|
28
|
+
\fBstdioTerminal()\fR: Returns the terminal I/O of the process stdio: output is written to standard output, input is read from standard input, which is switched into raw mode, and the signals \fBSIGTERM\fR and \fBSIGHUP\fR are forwarded to the \fIcommand\fR. Within \fBtmux\fR only, its cache file is \fB$XDG_CACHE_HOME/ansi-quantone/colors-tmux-\fR\fIkey\fR\fB.json\fR (default \fB$XDG_CACHE_HOME\fR: \fB~/.cache\fR), where \fIkey\fR is derived from the \fBtmux\fR server socket and client PID, as each client can be a different terminal with different colors.
|
|
29
|
+
.IP \(bu 4
|
|
30
|
+
\fBConfig\fR: The configuration of \fBrun()\fR, with the following fields: \fBpalette\fR (the palette options \fBneutral\fR, \fBaccent\fR, \fBshades\fR, \fBchromatic\fR, \fBfloor\fR, \fBceiling\fR, \fBthreshold\fR, and \fBshift\fR of \fBQuantone\fR), \fBforeground\fR and \fBbackground\fR (the input colors of the terminal default colors: a color, \fB"auto"\fR to query them from the terminal, falling back to ANSI color \fB7\fR resp. \fB0\fR, or \fB"none"\fR to not recolor them), \fBreduce\fR (whether to reduce RGB/truecolor input colors onto the perceptually nearest, by \fBOKLab\fR distance, of the 256 ANSI colors before the color mappings), \fBmappings\fR (the list of color mapping rules, see \fBCOLOR MAPPINGS\fR), and \fBdebug\fR (whether to enable the debug mode, see \fBDEBUG MODE\fR).
|
|
31
|
+
.IP \(bu 4
|
|
32
|
+
\fBTerminalIO\fR: The terminal I/O of a run, e.g. the process stdio or a bridge to the terminal of a Web UI, with the following fields: \fBquery\fR (whether the terminal answers color queries), \fBcache\fR (the optional path of the cache file of the queried colors), \fBcolumns()\fR and \fBrows()\fR (its current size), \fBwrite(\fR\fIdata\fR\fB,\fR \fIcb\fR\fB)\fR (write output, returning \fBfalse\fR on back-pressure), \fBonDrain(\fR\fIcb\fR\fB)\fR (once the output is drained again), \fBonData(\fR\fIcb\fR\fB)\fR (on input data), \fBonResize(\fR\fIcb\fR\fB)\fR (on size changes), \fBonSignal(\fR\fIcb\fR\fB)\fR (on the termination requests \fBSIGTERM\fR and \fBSIGHUP\fR), \fBsetup()\fR (switch into raw mode), and \fBrestore()\fR (restore the original mode). The \fBonData\fR, \fBonResize\fR, and \fBonSignal\fR functions return a function to unregister the callback again.
|
|
33
|
+
.RE 0
|
|
34
|
+
|
|
35
|
+
.P
|
|
36
|
+
A \fIcolor\fR is given in the hex notation \fB#RRGGBB\fR or \fB#RGB\fR, as an ANSI color index \fB0\fR-\fB255\fR, or as an ANSI color name like \fBblue\fR or \fBbrightBlue\fR. All palette options not given take the defaults of \fBQuantone\fR.
|
|
37
|
+
.SH "COLOR MAPPINGS"
|
|
38
|
+
.P
|
|
39
|
+
A color mapping rule has the form \fB<fg>/<bg> : <fg>/<bg>\fR, where the left side is the source foreground/background color pair to match and the right side is the replacement color pair. The colors are tracked across all SGR sequences, so a rule always matches the current color pair. The replacement colors are still mapped onto the palette. All matching rules are applied in order, so later rules override earlier ones. The processing order is: reducing (\fBreduce\fR), mapping, and palette mapping.
|
|
40
|
+
.P
|
|
41
|
+
A color of a rule is one of the following:
|
|
42
|
+
.RS 0
|
|
43
|
+
.IP \(bu 4
|
|
44
|
+
\fB*\fR: On the source side, matches any color. On the target side, keeps the current color.
|
|
45
|
+
.IP \(bu 4
|
|
46
|
+
\fBdefault\fR: The terminal default color (SGR 39 / SGR 49).
|
|
47
|
+
.IP \(bu 4
|
|
48
|
+
An ANSI color index \fB0\fR-\fB255\fR or an ANSI color name like \fBblue\fR or \fBbrightBlue\fR. It matches the ANSI color in all its forms, i.e., \fBblue\fR, \fB4\fR, SGR 34, and SGR 38;5;4 are the same color.
|
|
49
|
+
.IP \(bu 4
|
|
50
|
+
A hex color \fB#RRGGBB\fR or \fB#RGB\fR. It matches RGB/truecolor input colors with exactly this value only.
|
|
51
|
+
.IP \(bu 4
|
|
52
|
+
A range \fB<from>..<to>\fR of ANSI color indices (e.g. \fB232..243\fR). Allowed on the source side only.
|
|
53
|
+
.IP \(bu 4
|
|
54
|
+
A class \fB@<family>\fR, \fB@<tone>\fR, or \fB@<family>.<tone>\fR (e.g. \fB@warm\fR, \fB@light\fR, or \fB@cool.dark\fR), matching all colors except \fBdefault\fR by their RGB value (for ANSI colors, as queried from the terminal). The family is \fBgrey\fR (alias \fBgray\fR) for colors with a chroma (max minus min channel) below 48, \fBwarm\fR for the hues from 280\[de] to 60\[de], and \fBcool\fR for the hues from 60\[de] to 280\[de]. The tone is \fBdark\fR for a luma (Rec. 709) below 64, \fBlight\fR for one above 180, and \fBmid\fR otherwise. Allowed on the source side only.
|
|
55
|
+
.RE 0
|
|
56
|
+
|
|
57
|
+
.SH "DEBUG MODE"
|
|
58
|
+
.P
|
|
59
|
+
In debug mode (\fBdebug\fR), the source and target output are additionally emulated on two virtual screens. The key sequence \fBCTRL+a d\fR toggles a debug overlay, consisting of a debug cursor and an info box. The debug cursor is a red 3x3 frame with rounded corners around the observed character, initially in the center of the screen.
|
|
60
|
+
.P
|
|
61
|
+
The info box in the top-right corner (or in the top-left corner, if the debug cursor is in the upper-right quadrant of the screen) shows the position and code point of the observed character, plus its source and target foreground and background colors, each with a color swatch. For a source ANSI color, its RGB value as the input of the recoloring is shown, too.
|
|
62
|
+
.P
|
|
63
|
+
While the overlay is displayed, the cursor keys move the debug cursor, a left mouse click positions it, and all other input is discarded. For this, the mouse click reporting of the terminal is enabled meanwhile, and the mouse modes of the \fIcommand\fR are restored afterwards. The key sequences \fBCTRL+a a\fR and \fBCTRL+a CTRL+a\fR send a literal \fBCTRL+a\fR to the \fIcommand\fR.
|
|
64
|
+
.P
|
|
65
|
+
The keys are recognized in their legacy encoding as well as in the encodings of the xterm \fImodifyOtherKeys\fR and the \fIkitty keyboard protocol\fR, as enabled by some applications. Inside \fBtmux\fR(1) or \fBscreen\fR(1) with \fBCTRL+a\fR as their prefix key, press \fBCTRL+a a d\fR.
|
|
66
|
+
.SH "EXAMPLE"
|
|
67
|
+
.P
|
|
68
|
+
.RS 2
|
|
69
|
+
.nf
|
|
70
|
+
import { run } from "ansi-quantone"
|
|
71
|
+
|
|
72
|
+
const exitCode = await run({
|
|
73
|
+
palette: { neutral: "#999999", accent: "#336699", shades: 16 },
|
|
74
|
+
foreground: "auto",
|
|
75
|
+
background: "none",
|
|
76
|
+
reduce: true,
|
|
77
|
+
mappings: \[lB] "*/blue : */black" \[rB],
|
|
78
|
+
debug: false
|
|
79
|
+
}, "htop")
|
|
80
|
+
.fi
|
|
81
|
+
.RE
|
|
82
|
+
.SH "SEE ALSO"
|
|
83
|
+
.P
|
|
84
|
+
\fBansi-quantone\fR(1), \fBquantone\fR(1), \fBansi-recolor\fR(1)
|
|
85
|
+
.SH "AUTHOR"
|
|
86
|
+
.P
|
|
87
|
+
Dr. Ralf S. Engelschall \fI\(larse@engelschall.com\(ra\fR
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
** ansi-quantone -- Recolor ANSI Color Sequences of CLI Commands onto a Toned Palette
|
|
3
|
+
** Copyright (c) 2026 Dr. Ralf S. Engelschall <rse@engelschall.com>
|
|
4
|
+
** Licensed under MIT license
|
|
5
|
+
*/
|
|
6
|
+
import { type QuantoneOptions, type QuantoneColor } from "quantone";
|
|
7
|
+
import type { DefaultColor, Config, TerminalIO } from "./ansi-quantone-api-types.js";
|
|
8
|
+
import { stdioTerminal } from "./ansi-quantone-api-terminal.js";
|
|
9
|
+
export type { QuantoneOptions, QuantoneColor, DefaultColor, Config, TerminalIO };
|
|
10
|
+
export { stdioTerminal };
|
|
11
|
+
export declare const run: (config: Config, command: string, args?: string[], terminal?: TerminalIO) => Promise<number>;
|