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