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