colorino 0.9.0 → 0.10.0

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