@reliverse/relico 1.3.2 → 1.3.4

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,47 @@
1
+ //#region src/mod.d.ts
2
+ type ColorLevel = 0 | 1 | 2 | 3;
3
+ interface Rgb {
4
+ r: number;
5
+ g: number;
6
+ b: number;
7
+ }
8
+ type SgrOp = {
9
+ kind: "style";
10
+ open: number[];
11
+ } | {
12
+ kind: "fg-basic";
13
+ idx: number;
14
+ bright: boolean;
15
+ } | {
16
+ kind: "bg-basic";
17
+ idx: number;
18
+ bright: boolean;
19
+ } | {
20
+ kind: "fg-256";
21
+ code: number;
22
+ } | {
23
+ kind: "bg-256";
24
+ code: number;
25
+ } | {
26
+ kind: "fg-true";
27
+ rgb: Rgb;
28
+ } | {
29
+ kind: "bg-true";
30
+ rgb: Rgb;
31
+ };
32
+ type ApplyInput = string | number;
33
+ type FormatCallable = ((input: ApplyInput) => string) & {
34
+ readonly [OP_SYMBOL]: SgrOp[];
35
+ };
36
+ type BaseColorName = "black" | "red" | "green" | "yellow" | "blue" | "magenta" | "cyan" | "white" | "gray" | "orange" | "pink" | "purple" | "teal" | "lime" | "brown" | "navy" | "maroon" | "olive" | "silver";
37
+ type ColorName = BaseColorName | BrightColorName | BgColorName;
38
+ type BrightColorName = "blackBright" | "redBright" | "greenBright" | "yellowBright" | "blueBright" | "magentaBright" | "cyanBright" | "whiteBright" | "orangeBright" | "pinkBright" | "purpleBright" | "tealBright" | "limeBright" | "brownBright" | "navyBright" | "maroonBright" | "oliveBright" | "silverBright";
39
+ type BgColorName = `bg${Capitalize<BaseColorName>}` | `bg${Capitalize<BrightColorName>}`;
40
+ type ReStyleKey = "reset" | "bold" | "dim" | "italic" | "underline" | "inverse" | "hidden" | "strikethrough";
41
+ type Re = FormatCallable & { readonly [K in ReStyleKey]: Re } & { readonly [K in ColorName]: Re } & { readonly [K in BgColorName]: Re };
42
+ declare const OP_SYMBOL: unique symbol;
43
+ declare const setColorLevel: (level: ColorLevel) => void;
44
+ declare const re: Re;
45
+ declare const chain: (...parts: FormatCallable[]) => Re;
46
+ //#endregion
47
+ export { chain, re, setColorLevel };
@@ -0,0 +1,356 @@
1
+ //#region src/mod.ts
2
+ const ESC = "\x1B[";
3
+ const RESET = `${ESC}0m`;
4
+ const OP_SYMBOL = Symbol("re.ops");
5
+ const COLOR_LEVEL_OFF = 0;
6
+ const COLOR_LEVEL_BASIC = 1;
7
+ const COLOR_LEVEL_256 = 2;
8
+ const COLOR_LEVEL_TRUECOLOR = 3;
9
+ const MIN_BYTE = 0;
10
+ const MAX_BYTE = 255;
11
+ const WHITE_RGB = 255;
12
+ const ANSI_256_GRAYSCALE_MIN = 8;
13
+ const ANSI_256_GRAYSCALE_MAX = 248;
14
+ const ANSI_256_BASE_OFFSET = 16;
15
+ const ANSI_256_GRAYSCALE_BASE = 232;
16
+ const ANSI_256_GRAYSCALE_RANGE = 247;
17
+ const ANSI_256_GRAYSCALE_STEPS = 24;
18
+ const ANSI_256_BRIGHT_THRESHOLD = 231;
19
+ const ANSI_256_RGB_LEVELS = 5;
20
+ const ANSI_256_RGB_RED_MULTIPLIER = 36;
21
+ const ANSI_256_RGB_GREEN_MULTIPLIER = 6;
22
+ const SGR_FG_BASE = 30;
23
+ const SGR_BG_BASE = 40;
24
+ const SGR_FG_BRIGHT_BASE = 90;
25
+ const SGR_BG_BRIGHT_BASE = 100;
26
+ const SGR_RESET = 0;
27
+ const SGR_BOLD = 1;
28
+ const SGR_DIM = 2;
29
+ const SGR_ITALIC = 3;
30
+ const SGR_UNDERLINE = 4;
31
+ const SGR_INVERSE = 7;
32
+ const SGR_HIDDEN = 8;
33
+ const SGR_STRIKETHROUGH = 9;
34
+ const HEX_BYTE_LENGTH = 2;
35
+ const HEX_RED_START = 0;
36
+ const HEX_GREEN_START = 2;
37
+ const HEX_BLUE_START = 4;
38
+ const HEX_BLUE_END = 6;
39
+ const HEX_RADIX = 16;
40
+ const BRIGHT_SUFFIX_LENGTH = 6;
41
+ const BG_PREFIX_LENGTH = 2;
42
+ const BG_COLOR_START = 3;
43
+ const BRIGHT_MIX_FACTOR = .25;
44
+ const BRIGHT_SUFFIX_REGEX = /Bright$/u;
45
+ let CURRENT_LEVEL = COLOR_LEVEL_TRUECOLOR;
46
+ const setColorLevel = (level) => {
47
+ if (level !== COLOR_LEVEL_OFF && level !== COLOR_LEVEL_BASIC && level !== COLOR_LEVEL_256 && level !== COLOR_LEVEL_TRUECOLOR) throw new Error("Invalid color level");
48
+ CURRENT_LEVEL = level;
49
+ };
50
+ const clampByte = (n) => {
51
+ if (!Number.isFinite(n)) return MIN_BYTE;
52
+ if (n < MIN_BYTE) return MIN_BYTE;
53
+ if (n > MAX_BYTE) return MAX_BYTE;
54
+ return Math.round(n);
55
+ };
56
+ const BASIC8 = [
57
+ {
58
+ r: 0,
59
+ g: 0,
60
+ b: 0
61
+ },
62
+ {
63
+ r: 205,
64
+ g: 0,
65
+ b: 0
66
+ },
67
+ {
68
+ r: 0,
69
+ g: 205,
70
+ b: 0
71
+ },
72
+ {
73
+ r: 205,
74
+ g: 205,
75
+ b: 0
76
+ },
77
+ {
78
+ r: 0,
79
+ g: 0,
80
+ b: 238
81
+ },
82
+ {
83
+ r: 205,
84
+ g: 0,
85
+ b: 205
86
+ },
87
+ {
88
+ r: 0,
89
+ g: 205,
90
+ b: 205
91
+ },
92
+ {
93
+ r: 229,
94
+ g: 229,
95
+ b: 229
96
+ }
97
+ ];
98
+ const sgr = (codes) => `${ESC}${codes.join(";")}m`;
99
+ const nearestBasicIndex = (rgb) => {
100
+ let best = 0;
101
+ let bestDist = Number.POSITIVE_INFINITY;
102
+ for (let i = 0; i < BASIC8.length; i++) {
103
+ const c = BASIC8[i];
104
+ const dr = c.r - rgb.r;
105
+ const dg = c.g - rgb.g;
106
+ const db = c.b - rgb.b;
107
+ const d = dr * dr + dg * dg + db * db;
108
+ if (d < bestDist) {
109
+ bestDist = d;
110
+ best = i;
111
+ }
112
+ }
113
+ return best;
114
+ };
115
+ const rgbToAnsi256 = (rgb) => {
116
+ if (rgb.r === rgb.g && rgb.g === rgb.b) {
117
+ if (rgb.r < ANSI_256_GRAYSCALE_MIN) return ANSI_256_BASE_OFFSET;
118
+ if (rgb.r > ANSI_256_GRAYSCALE_MAX) return ANSI_256_BRIGHT_THRESHOLD;
119
+ const step = Math.round((rgb.r - ANSI_256_GRAYSCALE_MIN) / ANSI_256_GRAYSCALE_RANGE * ANSI_256_GRAYSCALE_STEPS);
120
+ return ANSI_256_GRAYSCALE_BASE + step;
121
+ }
122
+ const r = Math.round(rgb.r / MAX_BYTE * ANSI_256_RGB_LEVELS);
123
+ const g = Math.round(rgb.g / MAX_BYTE * ANSI_256_RGB_LEVELS);
124
+ const b = Math.round(rgb.b / MAX_BYTE * ANSI_256_RGB_LEVELS);
125
+ return ANSI_256_BASE_OFFSET + ANSI_256_RGB_RED_MULTIPLIER * r + ANSI_256_RGB_GREEN_MULTIPLIER * g + b;
126
+ };
127
+ const NAMED_COLORS = {
128
+ black: "#000000",
129
+ red: "#ff0000",
130
+ green: "#00ff00",
131
+ yellow: "#ffff00",
132
+ blue: "#0000ff",
133
+ magenta: "#ff00ff",
134
+ cyan: "#00ffff",
135
+ white: "#ffffff",
136
+ gray: "#808080",
137
+ orange: "#ffa500",
138
+ pink: "#ffc0cb",
139
+ purple: "#800080",
140
+ teal: "#008080",
141
+ lime: "#00ff00",
142
+ brown: "#a52a2a",
143
+ navy: "#000080",
144
+ maroon: "#800000",
145
+ olive: "#808000",
146
+ silver: "#c0c0c0"
147
+ };
148
+ const mixWithWhite = (rgb, factor) => {
149
+ const t = factor;
150
+ return {
151
+ r: clampByte(rgb.r * (1 - t) + WHITE_RGB * t),
152
+ g: clampByte(rgb.g * (1 - t) + WHITE_RGB * t),
153
+ b: clampByte(rgb.b * (1 - t) + WHITE_RGB * t)
154
+ };
155
+ };
156
+ const fromNamed = (name) => {
157
+ const hex = NAMED_COLORS[name];
158
+ const clean = hex.startsWith("#") ? hex.slice(1) : hex;
159
+ const r = Number.parseInt(clean.slice(HEX_RED_START, HEX_BYTE_LENGTH), HEX_RADIX);
160
+ const g = Number.parseInt(clean.slice(HEX_GREEN_START, HEX_BLUE_START), HEX_RADIX);
161
+ const b = Number.parseInt(clean.slice(HEX_BLUE_START, HEX_BLUE_END), HEX_RADIX);
162
+ return {
163
+ r,
164
+ g,
165
+ b
166
+ };
167
+ };
168
+ const toBaseName = (compound) => {
169
+ const base = compound.replace(BRIGHT_SUFFIX_REGEX, "");
170
+ const key = base.charAt(0).toLowerCase() + base.slice(1);
171
+ return key;
172
+ };
173
+ const parseColorName = (name) => {
174
+ if (name.endsWith("Bright")) {
175
+ const base = toBaseName(name);
176
+ const rgb = fromNamed(base);
177
+ const rgbAdj = mixWithWhite(rgb, BRIGHT_MIX_FACTOR);
178
+ return {
179
+ rgb: rgbAdj,
180
+ wantBright: true
181
+ };
182
+ }
183
+ return {
184
+ rgb: fromNamed(name),
185
+ wantBright: false
186
+ };
187
+ };
188
+ const openForOp = (op) => {
189
+ if (CURRENT_LEVEL === COLOR_LEVEL_OFF) return "";
190
+ switch (op.kind) {
191
+ case "style": return sgr(op.open);
192
+ case "fg-basic": return sgr([(op.bright ? SGR_FG_BRIGHT_BASE : SGR_FG_BASE) + op.idx]);
193
+ case "bg-basic": return sgr([(op.bright ? SGR_BG_BRIGHT_BASE : SGR_BG_BASE) + op.idx]);
194
+ case "fg-256": return `${ESC}38;5;${op.code}m`;
195
+ case "bg-256": return `${ESC}48;5;${op.code}m`;
196
+ case "fg-true": return `${ESC}38;2;${op.rgb.r};${op.rgb.g};${op.rgb.b}m`;
197
+ case "bg-true": return `${ESC}48;2;${op.rgb.r};${op.rgb.g};${op.rgb.b}m`;
198
+ default: return "";
199
+ }
200
+ };
201
+ const opsToOpen = (ops) => {
202
+ if (CURRENT_LEVEL === COLOR_LEVEL_OFF) return "";
203
+ let out = "";
204
+ for (const op of ops) out += openForOp(op);
205
+ return out;
206
+ };
207
+ const applyOpsToText = (ops, input) => {
208
+ const text = String(input);
209
+ if (CURRENT_LEVEL === COLOR_LEVEL_OFF || ops.length === 0 || text.length === 0) return text;
210
+ const open = opsToOpen(ops);
211
+ if (!text.includes("\n")) return `${open}${text}${RESET}`;
212
+ const lines = text.split("\n");
213
+ const result = new Array(lines.length);
214
+ for (let i = 0; i < lines.length; i++) {
215
+ const line = lines[i];
216
+ if (line.endsWith("\r")) result[i] = `${open}${line.slice(0, -1)}\r${RESET}`;
217
+ else result[i] = `${open}${line}${RESET}`;
218
+ }
219
+ return result.join("\n");
220
+ };
221
+ const mkFgOpsFromRgb = (rgb, wantBright = false) => {
222
+ if (CURRENT_LEVEL === COLOR_LEVEL_BASIC) {
223
+ const idx = nearestBasicIndex(rgb);
224
+ return [{
225
+ kind: "fg-basic",
226
+ idx,
227
+ bright: wantBright
228
+ }];
229
+ }
230
+ if (CURRENT_LEVEL === COLOR_LEVEL_256) return [{
231
+ kind: "fg-256",
232
+ code: rgbToAnsi256(rgb)
233
+ }];
234
+ return [{
235
+ kind: "fg-true",
236
+ rgb
237
+ }];
238
+ };
239
+ const mkBgOpsFromRgb = (rgb, wantBright = false) => {
240
+ if (CURRENT_LEVEL === COLOR_LEVEL_BASIC) {
241
+ const idx = nearestBasicIndex(rgb);
242
+ return [{
243
+ kind: "bg-basic",
244
+ idx,
245
+ bright: wantBright
246
+ }];
247
+ }
248
+ if (CURRENT_LEVEL === COLOR_LEVEL_256) return [{
249
+ kind: "bg-256",
250
+ code: rgbToAnsi256(rgb)
251
+ }];
252
+ return [{
253
+ kind: "bg-true",
254
+ rgb
255
+ }];
256
+ };
257
+ const STYLE_TABLE = {
258
+ reset: {
259
+ kind: "style",
260
+ open: [SGR_RESET]
261
+ },
262
+ bold: {
263
+ kind: "style",
264
+ open: [SGR_BOLD]
265
+ },
266
+ dim: {
267
+ kind: "style",
268
+ open: [SGR_DIM]
269
+ },
270
+ italic: {
271
+ kind: "style",
272
+ open: [SGR_ITALIC]
273
+ },
274
+ underline: {
275
+ kind: "style",
276
+ open: [SGR_UNDERLINE]
277
+ },
278
+ inverse: {
279
+ kind: "style",
280
+ open: [SGR_INVERSE]
281
+ },
282
+ hidden: {
283
+ kind: "style",
284
+ open: [SGR_HIDDEN]
285
+ },
286
+ strikethrough: {
287
+ kind: "style",
288
+ open: [SGR_STRIKETHROUGH]
289
+ }
290
+ };
291
+ const STYLE_KEYS = new Set([
292
+ "reset",
293
+ "bold",
294
+ "dim",
295
+ "italic",
296
+ "underline",
297
+ "inverse",
298
+ "hidden",
299
+ "strikethrough"
300
+ ]);
301
+ const isColorKey = (key) => {
302
+ if (key in NAMED_COLORS) return true;
303
+ if (key.endsWith("Bright") && isColorKey(key.slice(0, -BRIGHT_SUFFIX_LENGTH))) return true;
304
+ return false;
305
+ };
306
+ const isBgKey = (key) => {
307
+ if (!key.startsWith("bg") || key.length <= BG_PREFIX_LENGTH) return false;
308
+ const colorPart = key.charAt(BG_PREFIX_LENGTH).toLowerCase() + key.slice(BG_COLOR_START);
309
+ return isColorKey(colorPart);
310
+ };
311
+ const callableProxy = (ops) => {
312
+ const base = (input) => applyOpsToText(ops, input);
313
+ Object.defineProperty(base, OP_SYMBOL, {
314
+ value: ops,
315
+ enumerable: false,
316
+ configurable: false,
317
+ writable: false
318
+ });
319
+ return new Proxy(base, {
320
+ apply(_target, _thisArg, argArray) {
321
+ const [input] = argArray;
322
+ return applyOpsToText(ops, input);
323
+ },
324
+ get(_target, prop) {
325
+ const key = String(prop);
326
+ if (prop === OP_SYMBOL) return ops;
327
+ if (STYLE_KEYS.has(key)) {
328
+ const op = STYLE_TABLE[key];
329
+ return callableProxy([...ops, op]);
330
+ }
331
+ if (isBgKey(key)) {
332
+ const raw = key.slice(BG_PREFIX_LENGTH);
333
+ const colorName = raw.charAt(0).toLowerCase() + raw.slice(1);
334
+ const { rgb, wantBright } = parseColorName(colorName);
335
+ return callableProxy([...ops, ...mkBgOpsFromRgb(rgb, wantBright)]);
336
+ }
337
+ if (isColorKey(key)) {
338
+ const { rgb, wantBright } = parseColorName(key);
339
+ return callableProxy([...ops, ...mkFgOpsFromRgb(rgb, wantBright)]);
340
+ }
341
+ return callableProxy(ops);
342
+ }
343
+ });
344
+ };
345
+ const re = callableProxy([]);
346
+ const chain = (...parts) => {
347
+ const collected = [];
348
+ for (const p of parts) {
349
+ const ops = p[OP_SYMBOL];
350
+ if (ops && ops.length > 0) for (const op of ops) collected.push(op);
351
+ }
352
+ return callableProxy(collected);
353
+ };
354
+
355
+ //#endregion
356
+ export { chain, re, setColorLevel };
package/package.json CHANGED
@@ -1,11 +1,15 @@
1
1
  {
2
2
  "name": "@reliverse/relico",
3
3
  "author": "reliverse",
4
- "version": "1.3.2",
4
+ "version": "1.3.4",
5
5
  "type": "module",
6
6
  "description": "@reliverse/relico is a themeable, chainable, typed, truecolor-powered, modern terminal styling toolkit. Designed to make your CLI output colorful, accessible, and human-friendly. It gives you a flexible way to apply colors and styles — with reliability and a smart developer experience baked in. Built for humans, not just terminals.",
7
7
  "exports": {
8
- ".": "./src/mod.ts"
8
+ ".": {
9
+ "types": "./dist-npm/bin/mod.d.mts",
10
+ "import": "./dist-npm/bin/mod.mjs",
11
+ "default": "./dist-npm/bin/mod.mjs"
12
+ }
9
13
  },
10
14
  "publishConfig": {
11
15
  "access": "public"
@@ -14,10 +18,11 @@
14
18
  "package.json",
15
19
  "README.md",
16
20
  "LICENSE",
17
- "src"
21
+ "dist-npm/bin"
18
22
  ],
19
23
  "scripts": {
20
- "pub": "dler pub",
24
+ "pub": "bun run build && bun publish",
25
+ "build": "bun obuild",
21
26
  "dev": "bun examples/core.ts",
22
27
  "latest": "bun update --latest && bun check",
23
28
  "check": "tsc --noEmit && biome check --fix --unsafe",
@@ -32,6 +37,7 @@
32
37
  "@total-typescript/ts-reset": "^0.6.1",
33
38
  "@types/bun": "^1.2.20",
34
39
  "@types/node": "^24.3.0",
40
+ "obuild": "^0.2.1",
35
41
  "typescript": "^5.9.2",
36
42
  "ultracite": "^5.1.5"
37
43
  }
package/src/mod.ts DELETED
@@ -1,492 +0,0 @@
1
- /* @reliverse/relico - Tiny, type-safe terminal color library with chainable API
2
- - Levels: 0 (off), 1 (ANSI 8/bright), 2 (ANSI 256), 3 (Truecolor)
3
- - Named palettes (std, web, grayscale), Bright & Pastel variants, bg-variants
4
- - Chainable: re.bold.red.underline("text"), chain(re.bold, re.red)("text")
5
- - Multiline-safe: styles applied per line with reset to prevent bleed
6
- */
7
-
8
- type ColorLevel = 0 | 1 | 2 | 3;
9
-
10
- interface Rgb {
11
- r: number;
12
- g: number;
13
- b: number;
14
- }
15
-
16
- type SgrOp =
17
- | { kind: "style"; open: number[] } // closed by global reset at line end
18
- | { kind: "fg-basic"; idx: number; bright: boolean }
19
- | { kind: "bg-basic"; idx: number; bright: boolean }
20
- | { kind: "fg-256"; code: number }
21
- | { kind: "bg-256"; code: number }
22
- | { kind: "fg-true"; rgb: Rgb }
23
- | { kind: "bg-true"; rgb: Rgb };
24
-
25
- type ApplyInput = string | number;
26
-
27
- type FormatCallable = ((input: ApplyInput) => string) & { readonly [OP_SYMBOL]: SgrOp[] };
28
-
29
- type BaseColorName =
30
- | "black"
31
- | "red"
32
- | "green"
33
- | "yellow"
34
- | "blue"
35
- | "magenta"
36
- | "cyan"
37
- | "white"
38
- | "gray"
39
- | "orange"
40
- | "pink"
41
- | "purple"
42
- | "teal"
43
- | "lime"
44
- | "brown"
45
- | "navy"
46
- | "maroon"
47
- | "olive"
48
- | "silver";
49
-
50
- type ColorName = BaseColorName | BrightColorName | BgColorName;
51
-
52
- type BrightColorName =
53
- | "blackBright"
54
- | "redBright"
55
- | "greenBright"
56
- | "yellowBright"
57
- | "blueBright"
58
- | "magentaBright"
59
- | "cyanBright"
60
- | "whiteBright"
61
- | "orangeBright"
62
- | "pinkBright"
63
- | "purpleBright"
64
- | "tealBright"
65
- | "limeBright"
66
- | "brownBright"
67
- | "navyBright"
68
- | "maroonBright"
69
- | "oliveBright"
70
- | "silverBright";
71
-
72
- type BgColorName = `bg${Capitalize<BaseColorName>}` | `bg${Capitalize<BrightColorName>}`;
73
-
74
- type ReStyleKey =
75
- | "reset"
76
- | "bold"
77
- | "dim"
78
- | "italic"
79
- | "underline"
80
- | "inverse"
81
- | "hidden"
82
- | "strikethrough";
83
-
84
- type Re = FormatCallable & {
85
- readonly [K in ReStyleKey]: Re;
86
- } & {
87
- readonly [K in ColorName]: Re;
88
- } & {
89
- readonly [K in BgColorName]: Re;
90
- };
91
-
92
- const ESC = "\x1B[";
93
- const RESET = `${ESC}0m`;
94
- const OP_SYMBOL: unique symbol = Symbol("re.ops");
95
-
96
- // Color level constants
97
- const COLOR_LEVEL_OFF = 0;
98
- const COLOR_LEVEL_BASIC = 1;
99
- const COLOR_LEVEL_256 = 2;
100
- const COLOR_LEVEL_TRUECOLOR = 3;
101
-
102
- // RGB and byte constants
103
- const MIN_BYTE = 0;
104
- const MAX_BYTE = 255;
105
- const WHITE_RGB = 255;
106
-
107
- // ANSI 256 color constants
108
- const ANSI_256_GRAYSCALE_MIN = 8;
109
- const ANSI_256_GRAYSCALE_MAX = 248;
110
- const ANSI_256_BASE_OFFSET = 16;
111
- const ANSI_256_GRAYSCALE_BASE = 232;
112
- const ANSI_256_GRAYSCALE_RANGE = 247;
113
- const ANSI_256_GRAYSCALE_STEPS = 24;
114
- const ANSI_256_BRIGHT_THRESHOLD = 231;
115
- const ANSI_256_RGB_LEVELS = 5;
116
- const ANSI_256_RGB_RED_MULTIPLIER = 36;
117
- const ANSI_256_RGB_GREEN_MULTIPLIER = 6;
118
-
119
- // SGR code constants
120
- const SGR_FG_BASE = 30;
121
- const SGR_BG_BASE = 40;
122
- const SGR_FG_BRIGHT_BASE = 90;
123
- const SGR_BG_BRIGHT_BASE = 100;
124
-
125
- // Style SGR codes
126
- const SGR_RESET = 0;
127
- const SGR_BOLD = 1;
128
- const SGR_DIM = 2;
129
- const SGR_ITALIC = 3;
130
- const SGR_UNDERLINE = 4;
131
- const SGR_INVERSE = 7;
132
- const SGR_HIDDEN = 8;
133
- const SGR_STRIKETHROUGH = 9;
134
-
135
- // Hex parsing constants
136
- const HEX_BYTE_LENGTH = 2;
137
- const HEX_RED_START = 0;
138
- const HEX_GREEN_START = 2;
139
- const HEX_BLUE_START = 4;
140
- const HEX_BLUE_END = 6;
141
- const HEX_RADIX = 16;
142
-
143
- // String processing constants
144
- const BRIGHT_SUFFIX_LENGTH = 6;
145
- const BG_PREFIX_LENGTH = 2;
146
- const BG_COLOR_START = 3;
147
-
148
- // Color mixing constants
149
- const BRIGHT_MIX_FACTOR = 0.25;
150
-
151
- // Regex constants
152
- const BRIGHT_SUFFIX_REGEX = /Bright$/u;
153
-
154
- let CURRENT_LEVEL: ColorLevel = COLOR_LEVEL_TRUECOLOR;
155
-
156
- export const setColorLevel = (level: ColorLevel): void => {
157
- if (
158
- level !== COLOR_LEVEL_OFF &&
159
- level !== COLOR_LEVEL_BASIC &&
160
- level !== COLOR_LEVEL_256 &&
161
- level !== COLOR_LEVEL_TRUECOLOR
162
- ) {
163
- throw new Error("Invalid color level");
164
- }
165
- CURRENT_LEVEL = level;
166
- };
167
-
168
- const clampByte = (n: number): number => {
169
- if (!Number.isFinite(n)) {
170
- return MIN_BYTE;
171
- }
172
- if (n < MIN_BYTE) {
173
- return MIN_BYTE;
174
- }
175
- if (n > MAX_BYTE) {
176
- return MAX_BYTE;
177
- }
178
- return Math.round(n);
179
- };
180
-
181
- // Base 8-color RGB anchors (non-bright)
182
- const BASIC8: Rgb[] = [
183
- { r: 0, g: 0, b: 0 }, // black
184
- { r: 205, g: 0, b: 0 }, // red
185
- { r: 0, g: 205, b: 0 }, // green
186
- { r: 205, g: 205, b: 0 }, // yellow
187
- { r: 0, g: 0, b: 238 }, // blue
188
- { r: 205, g: 0, b: 205 }, // magenta
189
- { r: 0, g: 205, b: 205 }, // cyan
190
- { r: 229, g: 229, b: 229 }, // white (light gray)
191
- ];
192
-
193
- // SGR code builders
194
- const sgr = (codes: number[]): string => `${ESC}${codes.join(";")}m`;
195
-
196
- // RGB → closest of BASIC8 index (0..7)
197
- const nearestBasicIndex = (rgb: Rgb): number => {
198
- let best = 0;
199
- let bestDist = Number.POSITIVE_INFINITY;
200
- for (let i = 0; i < BASIC8.length; i++) {
201
- const c = BASIC8[i];
202
- const dr = c.r - rgb.r;
203
- const dg = c.g - rgb.g;
204
- const db = c.b - rgb.b;
205
- const d = dr * dr + dg * dg + db * db;
206
- if (d < bestDist) {
207
- bestDist = d;
208
- best = i;
209
- }
210
- }
211
- return best;
212
- };
213
-
214
- // RGB → ANSI 256 index
215
- const rgbToAnsi256 = (rgb: Rgb): number => {
216
- // Try grayscale if r≈g≈b
217
- if (rgb.r === rgb.g && rgb.g === rgb.b) {
218
- if (rgb.r < ANSI_256_GRAYSCALE_MIN) {
219
- return ANSI_256_BASE_OFFSET;
220
- }
221
- if (rgb.r > ANSI_256_GRAYSCALE_MAX) {
222
- return ANSI_256_BRIGHT_THRESHOLD;
223
- }
224
- const step = Math.round(
225
- ((rgb.r - ANSI_256_GRAYSCALE_MIN) / ANSI_256_GRAYSCALE_RANGE) * ANSI_256_GRAYSCALE_STEPS,
226
- );
227
- return ANSI_256_GRAYSCALE_BASE + step;
228
- }
229
- const r = Math.round((rgb.r / MAX_BYTE) * ANSI_256_RGB_LEVELS);
230
- const g = Math.round((rgb.g / MAX_BYTE) * ANSI_256_RGB_LEVELS);
231
- const b = Math.round((rgb.b / MAX_BYTE) * ANSI_256_RGB_LEVELS);
232
- return (
233
- ANSI_256_BASE_OFFSET + ANSI_256_RGB_RED_MULTIPLIER * r + ANSI_256_RGB_GREEN_MULTIPLIER * g + b
234
- );
235
- };
236
-
237
- // Color data
238
- const NAMED_COLORS: Record<BaseColorName, string> = {
239
- black: "#000000",
240
- red: "#ff0000",
241
- green: "#00ff00",
242
- yellow: "#ffff00",
243
- blue: "#0000ff",
244
- magenta: "#ff00ff",
245
- cyan: "#00ffff",
246
- white: "#ffffff",
247
- gray: "#808080",
248
- orange: "#ffa500",
249
- pink: "#ffc0cb",
250
- purple: "#800080",
251
- teal: "#008080",
252
- lime: "#00ff00",
253
- brown: "#a52a2a",
254
- navy: "#000080",
255
- maroon: "#800000",
256
- olive: "#808000",
257
- silver: "#c0c0c0",
258
- };
259
-
260
- const mixWithWhite = (rgb: Rgb, factor: number): Rgb => {
261
- const t = factor;
262
- return {
263
- r: clampByte(rgb.r * (1 - t) + WHITE_RGB * t),
264
- g: clampByte(rgb.g * (1 - t) + WHITE_RGB * t),
265
- b: clampByte(rgb.b * (1 - t) + WHITE_RGB * t),
266
- };
267
- };
268
-
269
- const fromNamed = (name: BaseColorName): Rgb => {
270
- const hex = NAMED_COLORS[name];
271
- // Simple hex to RGB conversion for named colors only
272
- const clean = hex.startsWith("#") ? hex.slice(1) : hex;
273
- const r = Number.parseInt(clean.slice(HEX_RED_START, HEX_BYTE_LENGTH), HEX_RADIX);
274
- const g = Number.parseInt(clean.slice(HEX_GREEN_START, HEX_BLUE_START), HEX_RADIX);
275
- const b = Number.parseInt(clean.slice(HEX_BLUE_START, HEX_BLUE_END), HEX_RADIX);
276
- return { r, g, b };
277
- };
278
-
279
- const toBaseName = (compound: BrightColorName): BaseColorName => {
280
- const base = compound.replace(BRIGHT_SUFFIX_REGEX, "");
281
- const key = base.charAt(0).toLowerCase() + base.slice(1);
282
- return key as BaseColorName;
283
- };
284
-
285
- const parseColorName = (name: ColorName): { rgb: Rgb; wantBright: boolean } => {
286
- if ((name as string).endsWith("Bright")) {
287
- const base = toBaseName(name as BrightColorName);
288
- const rgb = fromNamed(base);
289
- // Lighten a bit in high levels; level 1 will use bright SGR
290
- const rgbAdj = mixWithWhite(rgb, BRIGHT_MIX_FACTOR);
291
- return { rgb: rgbAdj, wantBright: true };
292
- }
293
- return { rgb: fromNamed(name as BaseColorName), wantBright: false };
294
- };
295
-
296
- const openForOp = (op: SgrOp): string => {
297
- if (CURRENT_LEVEL === COLOR_LEVEL_OFF) {
298
- return "";
299
- }
300
- switch (op.kind) {
301
- case "style":
302
- return sgr(op.open);
303
- case "fg-basic":
304
- return sgr([(op.bright ? SGR_FG_BRIGHT_BASE : SGR_FG_BASE) + op.idx]);
305
- case "bg-basic":
306
- return sgr([(op.bright ? SGR_BG_BRIGHT_BASE : SGR_BG_BASE) + op.idx]);
307
- case "fg-256":
308
- return `${ESC}38;5;${op.code}m`;
309
- case "bg-256":
310
- return `${ESC}48;5;${op.code}m`;
311
- case "fg-true":
312
- return `${ESC}38;2;${op.rgb.r};${op.rgb.g};${op.rgb.b}m`;
313
- case "bg-true":
314
- return `${ESC}48;2;${op.rgb.r};${op.rgb.g};${op.rgb.b}m`;
315
- default:
316
- return "";
317
- }
318
- };
319
-
320
- const opsToOpen = (ops: SgrOp[]): string => {
321
- if (CURRENT_LEVEL === COLOR_LEVEL_OFF) {
322
- return "";
323
- }
324
- let out = "";
325
- for (const op of ops) {
326
- out += openForOp(op);
327
- }
328
- return out;
329
- };
330
-
331
- // Optimized multiline processing with fewer allocations and branches
332
- const applyOpsToText = (ops: SgrOp[], input: ApplyInput): string => {
333
- const text = String(input);
334
- if (CURRENT_LEVEL === COLOR_LEVEL_OFF || ops.length === 0 || text.length === 0) {
335
- return text;
336
- }
337
-
338
- const open = opsToOpen(ops);
339
-
340
- // Fast path for single-line text (most common case)
341
- if (!text.includes("\n")) {
342
- return `${open}${text}${RESET}`;
343
- }
344
-
345
- // Optimized multiline handling with pre-calculated string lengths
346
- const lines = text.split("\n");
347
- const result = new Array(lines.length);
348
-
349
- for (let i = 0; i < lines.length; i++) {
350
- const line = lines[i];
351
- if (line.endsWith("\r")) {
352
- result[i] = `${open}${line.slice(0, -1)}\r${RESET}`;
353
- } else {
354
- result[i] = `${open}${line}${RESET}`;
355
- }
356
- }
357
-
358
- return result.join("\n");
359
- };
360
-
361
- // Build operations for a color request according to CURRENT_LEVEL
362
- const mkFgOpsFromRgb = (rgb: Rgb, wantBright = false): SgrOp[] => {
363
- if (CURRENT_LEVEL === COLOR_LEVEL_BASIC) {
364
- const idx = nearestBasicIndex(rgb);
365
- return [{ kind: "fg-basic", idx, bright: wantBright }];
366
- }
367
- if (CURRENT_LEVEL === COLOR_LEVEL_256) {
368
- return [{ kind: "fg-256", code: rgbToAnsi256(rgb) }];
369
- }
370
- return [{ kind: "fg-true", rgb }];
371
- };
372
-
373
- const mkBgOpsFromRgb = (rgb: Rgb, wantBright = false): SgrOp[] => {
374
- if (CURRENT_LEVEL === COLOR_LEVEL_BASIC) {
375
- const idx = nearestBasicIndex(rgb);
376
- return [{ kind: "bg-basic", idx, bright: wantBright }];
377
- }
378
- if (CURRENT_LEVEL === COLOR_LEVEL_256) {
379
- return [{ kind: "bg-256", code: rgbToAnsi256(rgb) }];
380
- }
381
- return [{ kind: "bg-true", rgb }];
382
- };
383
-
384
- // Style ops
385
- const STYLE_TABLE: Record<ReStyleKey, SgrOp> = {
386
- reset: { kind: "style", open: [SGR_RESET] },
387
- bold: { kind: "style", open: [SGR_BOLD] },
388
- dim: { kind: "style", open: [SGR_DIM] },
389
- italic: { kind: "style", open: [SGR_ITALIC] },
390
- underline: { kind: "style", open: [SGR_UNDERLINE] },
391
- inverse: { kind: "style", open: [SGR_INVERSE] },
392
- hidden: { kind: "style", open: [SGR_HIDDEN] },
393
- strikethrough: { kind: "style", open: [SGR_STRIKETHROUGH] },
394
- };
395
-
396
- // Lookup maps
397
- const STYLE_KEYS = new Set([
398
- "reset",
399
- "bold",
400
- "dim",
401
- "italic",
402
- "underline",
403
- "inverse",
404
- "hidden",
405
- "strikethrough",
406
- ]);
407
-
408
- // Direct color/bg key checks
409
- const isColorKey = (key: string): boolean => {
410
- // Base colors and extended colors
411
- if (key in NAMED_COLORS) {
412
- return true;
413
- }
414
- // Bright variants
415
- if (key.endsWith("Bright") && isColorKey(key.slice(0, -BRIGHT_SUFFIX_LENGTH))) {
416
- return true;
417
- }
418
- return false;
419
- };
420
-
421
- const isBgKey = (key: string): boolean => {
422
- if (!key.startsWith("bg") || key.length <= BG_PREFIX_LENGTH) {
423
- return false;
424
- }
425
- const colorPart = key.charAt(BG_PREFIX_LENGTH).toLowerCase() + key.slice(BG_COLOR_START);
426
- return isColorKey(colorPart);
427
- };
428
-
429
- // Proxy with performance through pre-computed lookups
430
- const callableProxy = (ops: SgrOp[]): Re => {
431
- const base = ((input: ApplyInput) => applyOpsToText(ops, input)) as FormatCallable;
432
- Object.defineProperty(base, OP_SYMBOL, {
433
- value: ops,
434
- enumerable: false,
435
- configurable: false,
436
- writable: false,
437
- });
438
-
439
- return new Proxy(base as unknown as Re, {
440
- apply(_target, _thisArg, argArray) {
441
- const [input] = argArray as [ApplyInput];
442
- return applyOpsToText(ops, input);
443
- },
444
- get(_target, prop) {
445
- const key = String(prop);
446
-
447
- // Ops extractor for chain()
448
- if (prop === OP_SYMBOL) {
449
- return ops;
450
- }
451
-
452
- // Fast path for styles using Set lookup
453
- if (STYLE_KEYS.has(key)) {
454
- const op = STYLE_TABLE[key as ReStyleKey];
455
- return callableProxy([...ops, op]);
456
- }
457
-
458
- // Fast path for colors
459
- if (isBgKey(key)) {
460
- const raw = key.slice(BG_PREFIX_LENGTH); // remove 'bg'
461
- const colorName = raw.charAt(0).toLowerCase() + raw.slice(1);
462
- const { rgb, wantBright } = parseColorName(colorName as ColorName);
463
- return callableProxy([...ops, ...mkBgOpsFromRgb(rgb, wantBright)]);
464
- }
465
-
466
- if (isColorKey(key)) {
467
- const { rgb, wantBright } = parseColorName(key as ColorName);
468
- return callableProxy([...ops, ...mkFgOpsFromRgb(rgb, wantBright)]);
469
- }
470
-
471
- // Unknown key → return self (no-op), keeps chain resilient
472
- return callableProxy(ops);
473
- },
474
- });
475
- };
476
-
477
- // Public root
478
- export const re: Re = callableProxy([]);
479
-
480
- // chain(re.bold, re.red, re.underline)("text")
481
- export const chain = (...parts: FormatCallable[]): Re => {
482
- const collected: SgrOp[] = [];
483
- for (const p of parts) {
484
- const ops = (p as FormatCallable)[OP_SYMBOL] as SgrOp[] | undefined;
485
- if (ops && ops.length > 0) {
486
- for (const op of ops) {
487
- collected.push(op);
488
- }
489
- }
490
- }
491
- return callableProxy(collected);
492
- };