colorino 0.13.1 → 0.14.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.
@@ -1,1011 +0,0 @@
1
- function hexToRgb(hex) {
2
- const match = hex.toString().match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
3
- if (!match) {
4
- return [0, 0, 0];
5
- }
6
- let colorString = match[0];
7
- if (match[0].length === 3) {
8
- colorString = [...colorString].map((char) => char + char).join("");
9
- }
10
- const integer = parseInt(colorString, 16);
11
- const r = integer >> 16 & 255;
12
- const g = integer >> 8 & 255;
13
- const b = integer & 255;
14
- return [r, g, b];
15
- }
16
- function rgbToAnsi256(rgb) {
17
- const [r, g, b] = rgb;
18
- if (r === g && g === b) {
19
- if (r < 8) return 16;
20
- if (r > 248) return 231;
21
- return Math.round((r - 8) / 247 * 24) + 232;
22
- }
23
- return 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
24
- }
25
- function rgbToHsvValue(rgb) {
26
- const r = rgb[0] / 255;
27
- const g = rgb[1] / 255;
28
- const b = rgb[2] / 255;
29
- const v = Math.max(r, g, b);
30
- return v * 100;
31
- }
32
- function rgbToAnsi16(rgb) {
33
- const [r, g, b] = rgb;
34
- const value = rgbToHsvValue(rgb);
35
- const roundedValue = Math.round(value / 50);
36
- if (roundedValue === 0) {
37
- return 30;
38
- }
39
- let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
40
- if (roundedValue === 2) {
41
- ansi += 60;
42
- }
43
- return ansi;
44
- }
45
- const colorConverter = {
46
- hex: {
47
- toRgb: hexToRgb,
48
- toAnsi16: (hex) => rgbToAnsi16(hexToRgb(hex)),
49
- toAnsi256: (hex) => rgbToAnsi256(hexToRgb(hex))
50
- }};
51
-
52
- var ColorLevel = /* @__PURE__ */ ((ColorLevel2) => {
53
- ColorLevel2[ColorLevel2["NO_COLOR"] = 0] = "NO_COLOR";
54
- ColorLevel2[ColorLevel2["ANSI"] = 1] = "ANSI";
55
- ColorLevel2[ColorLevel2["ANSI256"] = 2] = "ANSI256";
56
- ColorLevel2[ColorLevel2["TRUECOLOR"] = 3] = "TRUECOLOR";
57
- return ColorLevel2;
58
- })(ColorLevel || {});
59
-
60
- function isConsoleMethod(level) {
61
- return ["log", "info", "warn", "error", "trace", "debug"].includes(level);
62
- }
63
- const ColorinoBrowserColorized = Symbol("colorino.browserColorized");
64
- const ColorinoBrowserObject = Symbol("colorino.browserObject");
65
-
66
- const catppuccinMochaPalette = {
67
- log: "#cdd6f4",
68
- // Text
69
- info: "#89b4fa",
70
- // Blue
71
- warn: "#f9e2af",
72
- // Yellow
73
- error: "#f38ba8",
74
- // Red
75
- debug: "#a6adc8",
76
- // Subtext0
77
- trace: "#9399b2"
78
- // Subtext1
79
- };
80
- const catppuccinLattePalette = {
81
- log: "#4c4f69",
82
- // Text
83
- info: "#1e66f5",
84
- // Blue
85
- warn: "#df8e1d",
86
- // Yellow
87
- error: "#d20f39",
88
- // Red
89
- debug: "#7c7f93",
90
- // Subtext0
91
- trace: "#8c8fa1"
92
- // Subtext1
93
- };
94
- const draculaPalette = {
95
- log: "#f8f8f2",
96
- // Foreground
97
- info: "#8be9fd",
98
- // Cyan
99
- warn: "#f1fa8c",
100
- // Yellow
101
- error: "#ff5555",
102
- // Red
103
- debug: "#bd93f9",
104
- // Purple
105
- trace: "#6272a4"
106
- // Comment
107
- };
108
- const githubLightPalette = {
109
- log: "#24292e",
110
- // Text
111
- info: "#0366d6",
112
- // Blue
113
- warn: "#f9a002",
114
- // Yellow
115
- error: "#d73a49",
116
- // Red
117
- debug: "#586069",
118
- // Gray
119
- trace: "#6a737d"
120
- // Gray-light
121
- };
122
-
123
- const themePalettes = {
124
- "catppuccin-mocha": catppuccinMochaPalette,
125
- "catppuccin-latte": catppuccinLattePalette,
126
- dracula: draculaPalette,
127
- "github-light": githubLightPalette
128
- };
129
- const defaultDarkTheme = "dracula";
130
- const defaultLightTheme = "github-light";
131
- function isThemeName(theme) {
132
- return theme in themePalettes;
133
- }
134
-
135
- function determineBaseTheme(themeOpt, detectedBrowserTheme) {
136
- let baseThemeName;
137
- if (isThemeName(themeOpt)) {
138
- baseThemeName = themeOpt;
139
- } else if (themeOpt === "light") {
140
- baseThemeName = defaultLightTheme;
141
- } else if (themeOpt === "dark") {
142
- baseThemeName = defaultDarkTheme;
143
- } else {
144
- baseThemeName = detectedBrowserTheme === "light" ? defaultLightTheme : defaultDarkTheme;
145
- }
146
- return baseThemeName;
147
- }
148
-
149
- class TypeValidator {
150
- static isNull(value) {
151
- return value === null;
152
- }
153
- static isObject(value) {
154
- return typeof value === "object" && value !== null;
155
- }
156
- static isString(value) {
157
- return typeof value === "string";
158
- }
159
- static isError(value) {
160
- return value instanceof Error;
161
- }
162
- static isBrowserColorizedArg(value) {
163
- return typeof value === "object" && value !== null && ColorinoBrowserColorized in value;
164
- }
165
- static isBrowserObjectArg(value) {
166
- return typeof value === "object" && value !== null && ColorinoBrowserObject in value;
167
- }
168
- static isAnsiColoredString(value) {
169
- return TypeValidator.isString(value) && /\x1b\[[0-9;]*m/.test(value);
170
- }
171
- static isFormattableObject(value) {
172
- return TypeValidator.isObject(value) && !TypeValidator.isError(value) && !TypeValidator.isBrowserColorizedArg(value);
173
- }
174
- }
175
-
176
- class MyColorino {
177
- constructor(initialPalette, _userPalette, _validator, _browserColorSupportDetector, _nodeColorSupportDetector, _options = {}) {
178
- this._userPalette = _userPalette;
179
- this._validator = _validator;
180
- this._browserColorSupportDetector = _browserColorSupportDetector;
181
- this._nodeColorSupportDetector = _nodeColorSupportDetector;
182
- this._options = _options;
183
- this._palette = initialPalette;
184
- this.isBrowser = !!this._browserColorSupportDetector;
185
- this._colorLevel = this._detectColorSupport();
186
- const validatePaletteResult = this._validator.validatePalette(this._palette);
187
- if (validatePaletteResult.isErr()) throw validatePaletteResult.error;
188
- if (this._colorLevel !== ColorLevel.NO_COLOR && !this._options.disableWarnings && this._colorLevel === "UnknownEnv") {
189
- this._maybeWarnUser();
190
- }
191
- const themeOpt = this._options.theme ?? "auto";
192
- if (themeOpt === "auto" && this._nodeColorSupportDetector) {
193
- this._nodeColorSupportDetector.onTheme((resolvedTheme) => {
194
- this._applyResolvedTheme(resolvedTheme);
195
- });
196
- }
197
- }
198
- _alreadyWarned = false;
199
- _colorLevel;
200
- isBrowser;
201
- _palette;
202
- log(...args) {
203
- this._out("log", args);
204
- }
205
- info(...args) {
206
- this._out("info", args);
207
- }
208
- warn(...args) {
209
- this._out("warn", args);
210
- }
211
- error(...args) {
212
- this._out("error", args);
213
- }
214
- trace(...args) {
215
- this._out("trace", args);
216
- }
217
- debug(...args) {
218
- this._out("debug", args);
219
- }
220
- colorize(text, hex) {
221
- if (this._colorLevel === ColorLevel.NO_COLOR || this._colorLevel === "UnknownEnv") {
222
- return text;
223
- }
224
- if (this.isBrowser) {
225
- return {
226
- [ColorinoBrowserColorized]: true,
227
- text,
228
- hex
229
- };
230
- }
231
- const ansiPrefix = this._toAnsiPrefix(hex);
232
- if (!ansiPrefix) {
233
- return text;
234
- }
235
- return `${ansiPrefix}${text}\x1B[0m`;
236
- }
237
- _isAnsiColoredString(value) {
238
- return typeof value === "string" && /\x1b\[[0-9;]*m/.test(value);
239
- }
240
- _applyResolvedTheme(resolvedTheme) {
241
- const themeOpt = this._options.theme ?? "auto";
242
- const baseThemeName = determineBaseTheme(themeOpt, resolvedTheme);
243
- const basePalette = themePalettes[baseThemeName];
244
- this._palette = { ...basePalette, ...this._userPalette };
245
- }
246
- _detectColorSupport() {
247
- if (this.isBrowser) {
248
- return this._browserColorSupportDetector?.getColorLevel() ?? "UnknownEnv";
249
- }
250
- if (this._nodeColorSupportDetector?.isNodeEnv()) {
251
- return this._nodeColorSupportDetector?.getColorLevel() ?? "UnknownEnv";
252
- }
253
- return "UnknownEnv";
254
- }
255
- _maybeWarnUser() {
256
- if (this._alreadyWarned) return;
257
- this._alreadyWarned = true;
258
- console.warn(
259
- "No ANSI color support detected in this terminal. See [https://github.com/chalk/supports-color#support-matrix](https://github.com/chalk/supports-color#support-matrix) to learn how to enable terminal color."
260
- );
261
- }
262
- _formatValue(value, maxDepth = this._options.maxDepth ?? 5) {
263
- const seen = /* @__PURE__ */ new WeakSet();
264
- const sanitize = (val, currentDepth) => {
265
- if (val == null || typeof val !== "object") return val;
266
- if (seen.has(val)) return "[Circular]";
267
- seen.add(val);
268
- if (currentDepth >= maxDepth) return "[Object]";
269
- if (Array.isArray(val)) {
270
- return val.map((item) => sanitize(item, currentDepth + 1));
271
- }
272
- const result = {};
273
- for (const key in val) {
274
- result[key] = sanitize(
275
- val[key],
276
- currentDepth + 1
277
- );
278
- }
279
- return result;
280
- };
281
- return JSON.stringify(sanitize(value, 0), null, 2);
282
- }
283
- _normalizeString(value) {
284
- if (value instanceof String) return value.valueOf();
285
- return value;
286
- }
287
- _processArgs(args) {
288
- const processedArgs = [];
289
- let previousWasObject = false;
290
- for (const rawArg of args) {
291
- const arg = this._normalizeString(rawArg);
292
- if (TypeValidator.isBrowserColorizedArg(arg)) {
293
- processedArgs.push(arg);
294
- previousWasObject = false;
295
- continue;
296
- }
297
- if (TypeValidator.isFormattableObject(arg)) {
298
- if (this.isBrowser) {
299
- processedArgs.push({
300
- [ColorinoBrowserObject]: true,
301
- value: arg
302
- });
303
- } else {
304
- processedArgs.push(`
305
- ${this._formatValue(arg)}`);
306
- }
307
- previousWasObject = true;
308
- } else if (TypeValidator.isError(arg)) {
309
- processedArgs.push("\n", this._cleanErrorStack(arg));
310
- previousWasObject = true;
311
- } else {
312
- if (TypeValidator.isString(arg) && previousWasObject) {
313
- processedArgs.push(`
314
- ${arg}`);
315
- } else {
316
- processedArgs.push(arg);
317
- }
318
- previousWasObject = false;
319
- }
320
- }
321
- return processedArgs;
322
- }
323
- _applyBrowserColors(consoleMethod, args) {
324
- const formatParts = [];
325
- const cssArgs = [];
326
- const otherArgs = [];
327
- const paletteHex = this._palette[consoleMethod];
328
- for (const rawArg of args) {
329
- const arg = this._normalizeString(rawArg);
330
- if (TypeValidator.isBrowserColorizedArg(arg)) {
331
- formatParts.push(`%c${arg.text}`);
332
- cssArgs.push(`color:${arg.hex}`);
333
- continue;
334
- }
335
- if (TypeValidator.isBrowserObjectArg(arg)) {
336
- formatParts.push("%o");
337
- otherArgs.push(arg.value);
338
- continue;
339
- }
340
- if (TypeValidator.isString(arg)) {
341
- formatParts.push(`%c${arg}`);
342
- cssArgs.push(`color:${paletteHex}`);
343
- continue;
344
- }
345
- formatParts.push("%o");
346
- otherArgs.push(arg);
347
- }
348
- if (formatParts.length === 0) {
349
- return args;
350
- }
351
- return [formatParts.join(""), ...cssArgs, ...otherArgs];
352
- }
353
- _toAnsiPrefix(hex) {
354
- if (this._colorLevel === ColorLevel.NO_COLOR || this._colorLevel === "UnknownEnv") {
355
- return "";
356
- }
357
- switch (this._colorLevel) {
358
- case ColorLevel.TRUECOLOR: {
359
- const [r, g, b] = colorConverter.hex.toRgb(hex);
360
- return `\x1B[38;2;${r};${g};${b}m`;
361
- }
362
- case ColorLevel.ANSI256: {
363
- const code = colorConverter.hex.toAnsi256(hex);
364
- return `\x1B[38;5;${code}m`;
365
- }
366
- case ColorLevel.ANSI:
367
- default: {
368
- const code = colorConverter.hex.toAnsi16(hex);
369
- return `\x1B[${code}m`;
370
- }
371
- }
372
- }
373
- _applyNodeColors(consoleMethod, args) {
374
- const coloredArgs = [...args];
375
- const firstStringIndex = coloredArgs.findIndex(
376
- (arg) => typeof arg === "string"
377
- );
378
- if (firstStringIndex === -1) {
379
- return coloredArgs;
380
- }
381
- const first = coloredArgs[firstStringIndex];
382
- if (this._isAnsiColoredString(first)) {
383
- return coloredArgs;
384
- }
385
- const hex = this._palette[consoleMethod];
386
- const ansiPrefix = this._toAnsiPrefix(hex);
387
- if (!ansiPrefix) {
388
- return coloredArgs;
389
- }
390
- coloredArgs[firstStringIndex] = `${ansiPrefix}${String(first)}\x1B[0m`;
391
- return coloredArgs;
392
- }
393
- _output(consoleMethod, args) {
394
- if (consoleMethod === "trace") this._printCleanTrace(args);
395
- else console[consoleMethod](...args);
396
- }
397
- _out(level, args) {
398
- const consoleMethod = isConsoleMethod(level) ? level : "log";
399
- const processedArgs = this._processArgs(args);
400
- if (this._colorLevel === ColorLevel.NO_COLOR || this._colorLevel === "UnknownEnv") {
401
- this._output(consoleMethod, processedArgs);
402
- return;
403
- }
404
- if (this.isBrowser) {
405
- const coloredArgs2 = this._applyBrowserColors(consoleMethod, processedArgs);
406
- this._output(consoleMethod, coloredArgs2);
407
- return;
408
- }
409
- const coloredArgs = this._applyNodeColors(consoleMethod, processedArgs);
410
- this._output(consoleMethod, coloredArgs);
411
- }
412
- _filterStack(stack) {
413
- return stack.split("\n").filter((line) => !line.match(/.*colorino.*/gi)).join("\n");
414
- }
415
- _cleanErrorStack(error) {
416
- if (!error.stack) return error;
417
- const cleanStack = this._filterStack(error.stack);
418
- const cloned = Object.create(Object.getPrototypeOf(error));
419
- Object.assign(cloned, error);
420
- cloned.stack = cleanStack;
421
- return cloned;
422
- }
423
- _printCleanTrace(args) {
424
- const error = new Error();
425
- if (error.stack) {
426
- const cleanStack = this._filterStack(error.stack);
427
- console.log(...args, `
428
- ${cleanStack}`);
429
- } else {
430
- console.log(...args);
431
- }
432
- }
433
- }
434
-
435
- const defaultErrorConfig = {
436
- withStackTrace: false,
437
- };
438
- // Custom error object
439
- // Context / discussion: https://github.com/supermacro/neverthrow/pull/215
440
- const createNeverThrowError = (message, result, config = defaultErrorConfig) => {
441
- const data = result.isOk()
442
- ? { type: 'Ok', value: result.value }
443
- : { type: 'Err', value: result.error };
444
- const maybeStack = config.withStackTrace ? new Error().stack : undefined;
445
- return {
446
- data,
447
- message,
448
- stack: maybeStack,
449
- };
450
- };
451
-
452
- /******************************************************************************
453
- Copyright (c) Microsoft Corporation.
454
-
455
- Permission to use, copy, modify, and/or distribute this software for any
456
- purpose with or without fee is hereby granted.
457
-
458
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
459
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
460
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
461
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
462
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
463
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
464
- PERFORMANCE OF THIS SOFTWARE.
465
- ***************************************************************************** */
466
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
467
-
468
-
469
- function __awaiter(thisArg, _arguments, P, generator) {
470
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
471
- return new (P || (P = Promise))(function (resolve, reject) {
472
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
473
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
474
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
475
- step((generator = generator.apply(thisArg, [])).next());
476
- });
477
- }
478
-
479
- function __values(o) {
480
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
481
- if (m) return m.call(o);
482
- if (o && typeof o.length === "number") return {
483
- next: function () {
484
- if (o && i >= o.length) o = void 0;
485
- return { value: o && o[i++], done: !o };
486
- }
487
- };
488
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
489
- }
490
-
491
- function __await(v) {
492
- return this instanceof __await ? (this.v = v, this) : new __await(v);
493
- }
494
-
495
- function __asyncGenerator(thisArg, _arguments, generator) {
496
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
497
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
498
- return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
499
- function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
500
- function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
501
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
502
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
503
- function fulfill(value) { resume("next", value); }
504
- function reject(value) { resume("throw", value); }
505
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
506
- }
507
-
508
- function __asyncDelegator(o) {
509
- var i, p;
510
- return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
511
- function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
512
- }
513
-
514
- function __asyncValues(o) {
515
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
516
- var m = o[Symbol.asyncIterator], i;
517
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
518
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
519
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
520
- }
521
-
522
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
523
- var e = new Error(message);
524
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
525
- };
526
-
527
- class ResultAsync {
528
- constructor(res) {
529
- this._promise = res;
530
- }
531
- static fromSafePromise(promise) {
532
- const newPromise = promise.then((value) => new Ok(value));
533
- return new ResultAsync(newPromise);
534
- }
535
- static fromPromise(promise, errorFn) {
536
- const newPromise = promise
537
- .then((value) => new Ok(value))
538
- .catch((e) => new Err(errorFn(e)));
539
- return new ResultAsync(newPromise);
540
- }
541
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
542
- static fromThrowable(fn, errorFn) {
543
- return (...args) => {
544
- return new ResultAsync((() => __awaiter(this, void 0, void 0, function* () {
545
- try {
546
- return new Ok(yield fn(...args));
547
- }
548
- catch (error) {
549
- return new Err(errorFn ? errorFn(error) : error);
550
- }
551
- }))());
552
- };
553
- }
554
- static combine(asyncResultList) {
555
- return combineResultAsyncList(asyncResultList);
556
- }
557
- static combineWithAllErrors(asyncResultList) {
558
- return combineResultAsyncListWithAllErrors(asyncResultList);
559
- }
560
- map(f) {
561
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
562
- if (res.isErr()) {
563
- return new Err(res.error);
564
- }
565
- return new Ok(yield f(res.value));
566
- })));
567
- }
568
- andThrough(f) {
569
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
570
- if (res.isErr()) {
571
- return new Err(res.error);
572
- }
573
- const newRes = yield f(res.value);
574
- if (newRes.isErr()) {
575
- return new Err(newRes.error);
576
- }
577
- return new Ok(res.value);
578
- })));
579
- }
580
- andTee(f) {
581
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
582
- if (res.isErr()) {
583
- return new Err(res.error);
584
- }
585
- try {
586
- yield f(res.value);
587
- }
588
- catch (e) {
589
- // Tee does not care about the error
590
- }
591
- return new Ok(res.value);
592
- })));
593
- }
594
- orTee(f) {
595
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
596
- if (res.isOk()) {
597
- return new Ok(res.value);
598
- }
599
- try {
600
- yield f(res.error);
601
- }
602
- catch (e) {
603
- // Tee does not care about the error
604
- }
605
- return new Err(res.error);
606
- })));
607
- }
608
- mapErr(f) {
609
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
610
- if (res.isOk()) {
611
- return new Ok(res.value);
612
- }
613
- return new Err(yield f(res.error));
614
- })));
615
- }
616
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
617
- andThen(f) {
618
- return new ResultAsync(this._promise.then((res) => {
619
- if (res.isErr()) {
620
- return new Err(res.error);
621
- }
622
- const newValue = f(res.value);
623
- return newValue instanceof ResultAsync ? newValue._promise : newValue;
624
- }));
625
- }
626
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
627
- orElse(f) {
628
- return new ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
629
- if (res.isErr()) {
630
- return f(res.error);
631
- }
632
- return new Ok(res.value);
633
- })));
634
- }
635
- match(ok, _err) {
636
- return this._promise.then((res) => res.match(ok, _err));
637
- }
638
- unwrapOr(t) {
639
- return this._promise.then((res) => res.unwrapOr(t));
640
- }
641
- /**
642
- * @deprecated will be removed in 9.0.0.
643
- *
644
- * You can use `safeTry` without this method.
645
- * @example
646
- * ```typescript
647
- * safeTry(async function* () {
648
- * const okValue = yield* yourResult
649
- * })
650
- * ```
651
- * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
652
- */
653
- safeUnwrap() {
654
- return __asyncGenerator(this, arguments, function* safeUnwrap_1() {
655
- return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(yield __await(this._promise.then((res) => res.safeUnwrap()))))));
656
- });
657
- }
658
- // Makes ResultAsync implement PromiseLike<Result>
659
- then(successCallback, failureCallback) {
660
- return this._promise.then(successCallback, failureCallback);
661
- }
662
- [Symbol.asyncIterator]() {
663
- return __asyncGenerator(this, arguments, function* _a() {
664
- const result = yield __await(this._promise);
665
- if (result.isErr()) {
666
- // @ts-expect-error -- This is structurally equivalent and safe
667
- yield yield __await(errAsync(result.error));
668
- }
669
- // @ts-expect-error -- This is structurally equivalent and safe
670
- return yield __await(result.value);
671
- });
672
- }
673
- }
674
- function errAsync(err) {
675
- return new ResultAsync(Promise.resolve(new Err(err)));
676
- }
677
-
678
- /**
679
- * Short circuits on the FIRST Err value that we find
680
- */
681
- const combineResultList = (resultList) => {
682
- let acc = ok([]);
683
- for (const result of resultList) {
684
- if (result.isErr()) {
685
- acc = err(result.error);
686
- break;
687
- }
688
- else {
689
- acc.map((list) => list.push(result.value));
690
- }
691
- }
692
- return acc;
693
- };
694
- /* This is the typesafe version of Promise.all
695
- *
696
- * Takes a list of ResultAsync<T, E> and success if all inner results are Ok values
697
- * or fails if one (or more) of the inner results are Err values
698
- */
699
- const combineResultAsyncList = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultList);
700
- /**
701
- * Give a list of all the errors we find
702
- */
703
- const combineResultListWithAllErrors = (resultList) => {
704
- let acc = ok([]);
705
- for (const result of resultList) {
706
- if (result.isErr() && acc.isErr()) {
707
- acc.error.push(result.error);
708
- }
709
- else if (result.isErr() && acc.isOk()) {
710
- acc = err([result.error]);
711
- }
712
- else if (result.isOk() && acc.isOk()) {
713
- acc.value.push(result.value);
714
- }
715
- // do nothing when result.isOk() && acc.isErr()
716
- }
717
- return acc;
718
- };
719
- const combineResultAsyncListWithAllErrors = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultListWithAllErrors);
720
-
721
- // eslint-disable-next-line @typescript-eslint/no-namespace
722
- var Result;
723
- (function (Result) {
724
- /**
725
- * Wraps a function with a try catch, creating a new function with the same
726
- * arguments but returning `Ok` if successful, `Err` if the function throws
727
- *
728
- * @param fn function to wrap with ok on success or err on failure
729
- * @param errorFn when an error is thrown, this will wrap the error result if provided
730
- */
731
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
732
- function fromThrowable(fn, errorFn) {
733
- return (...args) => {
734
- try {
735
- const result = fn(...args);
736
- return ok(result);
737
- }
738
- catch (e) {
739
- return err(errorFn ? errorFn(e) : e);
740
- }
741
- };
742
- }
743
- Result.fromThrowable = fromThrowable;
744
- function combine(resultList) {
745
- return combineResultList(resultList);
746
- }
747
- Result.combine = combine;
748
- function combineWithAllErrors(resultList) {
749
- return combineResultListWithAllErrors(resultList);
750
- }
751
- Result.combineWithAllErrors = combineWithAllErrors;
752
- })(Result || (Result = {}));
753
- function ok(value) {
754
- return new Ok(value);
755
- }
756
- function err(err) {
757
- return new Err(err);
758
- }
759
- class Ok {
760
- constructor(value) {
761
- this.value = value;
762
- }
763
- isOk() {
764
- return true;
765
- }
766
- isErr() {
767
- return !this.isOk();
768
- }
769
- map(f) {
770
- return ok(f(this.value));
771
- }
772
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
773
- mapErr(_f) {
774
- return ok(this.value);
775
- }
776
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
777
- andThen(f) {
778
- return f(this.value);
779
- }
780
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
781
- andThrough(f) {
782
- return f(this.value).map((_value) => this.value);
783
- }
784
- andTee(f) {
785
- try {
786
- f(this.value);
787
- }
788
- catch (e) {
789
- // Tee doesn't care about the error
790
- }
791
- return ok(this.value);
792
- }
793
- orTee(_f) {
794
- return ok(this.value);
795
- }
796
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
797
- orElse(_f) {
798
- return ok(this.value);
799
- }
800
- asyncAndThen(f) {
801
- return f(this.value);
802
- }
803
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
804
- asyncAndThrough(f) {
805
- return f(this.value).map(() => this.value);
806
- }
807
- asyncMap(f) {
808
- return ResultAsync.fromSafePromise(f(this.value));
809
- }
810
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
811
- unwrapOr(_v) {
812
- return this.value;
813
- }
814
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
815
- match(ok, _err) {
816
- return ok(this.value);
817
- }
818
- safeUnwrap() {
819
- const value = this.value;
820
- /* eslint-disable-next-line require-yield */
821
- return (function* () {
822
- return value;
823
- })();
824
- }
825
- _unsafeUnwrap(_) {
826
- return this.value;
827
- }
828
- _unsafeUnwrapErr(config) {
829
- throw createNeverThrowError('Called `_unsafeUnwrapErr` on an Ok', this, config);
830
- }
831
- // eslint-disable-next-line @typescript-eslint/no-this-alias, require-yield
832
- *[Symbol.iterator]() {
833
- return this.value;
834
- }
835
- }
836
- class Err {
837
- constructor(error) {
838
- this.error = error;
839
- }
840
- isOk() {
841
- return false;
842
- }
843
- isErr() {
844
- return !this.isOk();
845
- }
846
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
847
- map(_f) {
848
- return err(this.error);
849
- }
850
- mapErr(f) {
851
- return err(f(this.error));
852
- }
853
- andThrough(_f) {
854
- return err(this.error);
855
- }
856
- andTee(_f) {
857
- return err(this.error);
858
- }
859
- orTee(f) {
860
- try {
861
- f(this.error);
862
- }
863
- catch (e) {
864
- // Tee doesn't care about the error
865
- }
866
- return err(this.error);
867
- }
868
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
869
- andThen(_f) {
870
- return err(this.error);
871
- }
872
- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
873
- orElse(f) {
874
- return f(this.error);
875
- }
876
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
877
- asyncAndThen(_f) {
878
- return errAsync(this.error);
879
- }
880
- asyncAndThrough(_f) {
881
- return errAsync(this.error);
882
- }
883
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
884
- asyncMap(_f) {
885
- return errAsync(this.error);
886
- }
887
- unwrapOr(v) {
888
- return v;
889
- }
890
- match(_ok, err) {
891
- return err(this.error);
892
- }
893
- safeUnwrap() {
894
- const error = this.error;
895
- return (function* () {
896
- yield err(error);
897
- throw new Error('Do not use this generator out of `safeTry`');
898
- })();
899
- }
900
- _unsafeUnwrap(config) {
901
- throw createNeverThrowError('Called `_unsafeUnwrap` on an Err', this, config);
902
- }
903
- _unsafeUnwrapErr(_) {
904
- return this.error;
905
- }
906
- *[Symbol.iterator]() {
907
- // eslint-disable-next-line @typescript-eslint/no-this-alias
908
- const self = this;
909
- // @ts-expect-error -- This is structurally equivalent and safe
910
- yield self;
911
- // @ts-expect-error -- This is structurally equivalent and safe
912
- return self;
913
- }
914
- }
915
- Result.fromThrowable;
916
-
917
- class InputValidationError extends Error {
918
- constructor(message) {
919
- super(message);
920
- this.name = "InputValidationError";
921
- Object.setPrototypeOf(this, InputValidationError.prototype);
922
- }
923
- }
924
-
925
- class InputValidator {
926
- validateHex(hex) {
927
- const trimmedHex = hex.trim();
928
- const isHexValid = /^#[0-9A-F]{6}$/i.test(trimmedHex);
929
- if (!isHexValid) {
930
- return err(new InputValidationError(`Invalid hex color: '${hex}'`));
931
- }
932
- return ok(true);
933
- }
934
- validatePalette(palette) {
935
- for (const level in palette) {
936
- const hex = palette[level];
937
- const result = this.validateHex(hex);
938
- if (result.isErr()) {
939
- return err(result.error);
940
- }
941
- }
942
- return ok(true);
943
- }
944
- }
945
-
946
- class BrowserColorSupportDetector {
947
- constructor(_window, _navigator, _overrideTheme) {
948
- this._window = _window;
949
- this._navigator = _navigator;
950
- this._overrideTheme = _overrideTheme;
951
- }
952
- isBrowserEnv() {
953
- return !!this._window && !!this._navigator?.userAgent;
954
- }
955
- getColorLevel() {
956
- if (!this.isBrowserEnv()) {
957
- return ColorLevel.NO_COLOR;
958
- }
959
- const userAgent = this._navigator.userAgent.toLowerCase();
960
- if (userAgent.includes("chrome")) return ColorLevel.ANSI256;
961
- if (userAgent.includes("firefox")) return ColorLevel.ANSI256;
962
- return ColorLevel.ANSI256;
963
- }
964
- getTheme() {
965
- if (this._overrideTheme) {
966
- return this._overrideTheme;
967
- }
968
- if (!this.isBrowserEnv() || typeof this._window.matchMedia !== "function") {
969
- return "unknown";
970
- }
971
- if (this._window.matchMedia("(prefers-color-scheme: dark)").matches) {
972
- return "dark";
973
- }
974
- if (this._window.matchMedia("(prefers-color-scheme: light)").matches) {
975
- return "light";
976
- }
977
- return "unknown";
978
- }
979
- }
980
-
981
- function createColorino(userPalette = {}, options = {}) {
982
- const validator = new InputValidator();
983
- let detectorThemeOverride;
984
- if (options.theme === "dark" || options.theme === "light") {
985
- detectorThemeOverride = options.theme;
986
- }
987
- const browserDetector = new BrowserColorSupportDetector(
988
- window,
989
- navigator,
990
- detectorThemeOverride
991
- );
992
- const detectedBrowserTheme = browserDetector.getTheme();
993
- const themeOpt = options.theme ?? "auto";
994
- const baseThemeName = determineBaseTheme(
995
- themeOpt,
996
- detectedBrowserTheme
997
- );
998
- const basePalette = themePalettes[baseThemeName];
999
- const finalPalette = { ...basePalette, ...userPalette };
1000
- return new MyColorino(
1001
- finalPalette,
1002
- userPalette,
1003
- validator,
1004
- browserDetector,
1005
- void 0,
1006
- options
1007
- );
1008
- }
1009
- const colorino = createColorino();
1010
-
1011
- export { colorino, createColorino, themePalettes };