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