Debian Codegraph @

node/colorjs.io/dist/color.legacy.js

raw
1 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
2
3 var esnext_iterator_map = {};
4
5 var es_iterator_map = {};
6
7 var globalThis_1;
8 var hasRequiredGlobalThis;
9
10 function requireGlobalThis () {
11 if (hasRequiredGlobalThis) return globalThis_1;
12 hasRequiredGlobalThis = 1;
13 var check = function (it) {
14 return it && it.Math === Math && it;
15 };
16
17 // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
18 globalThis_1 =
19 // eslint-disable-next-line es/no-global-this -- safe
20 check(typeof globalThis == 'object' && globalThis) ||
21 check(typeof window == 'object' && window) ||
22 // eslint-disable-next-line no-restricted-globals -- safe
23 check(typeof self == 'object' && self) ||
24 check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
25 check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
26 // eslint-disable-next-line no-new-func -- fallback
27 (function () { return this; })() || Function('return this')();
28 return globalThis_1;
29 }
30
31 var objectGetOwnPropertyDescriptor = {};
32
33 var fails;
34 var hasRequiredFails;
35
36 function requireFails () {
37 if (hasRequiredFails) return fails;
38 hasRequiredFails = 1;
39 fails = function (exec) {
40 try {
41 return !!exec();
42 } catch (error) {
43 return true;
44 }
45 };
46 return fails;
47 }
48
49 var descriptors;
50 var hasRequiredDescriptors;
51
52 function requireDescriptors () {
53 if (hasRequiredDescriptors) return descriptors;
54 hasRequiredDescriptors = 1;
55 var fails = requireFails();
56
57 // Detect IE8's incomplete defineProperty implementation
58 descriptors = !fails(function () {
59 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
60 return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] !== 7;
61 });
62 return descriptors;
63 }
64
65 var functionBindNative;
66 var hasRequiredFunctionBindNative;
67
68 function requireFunctionBindNative () {
69 if (hasRequiredFunctionBindNative) return functionBindNative;
70 hasRequiredFunctionBindNative = 1;
71 var fails = requireFails();
72
73 functionBindNative = !fails(function () {
74 // eslint-disable-next-line es/no-function-prototype-bind -- safe
75 var test = (function () { /* empty */ }).bind();
76 // eslint-disable-next-line no-prototype-builtins -- safe
77 return typeof test != 'function' || test.hasOwnProperty('prototype');
78 });
79 return functionBindNative;
80 }
81
82 var functionCall;
83 var hasRequiredFunctionCall;
84
85 function requireFunctionCall () {
86 if (hasRequiredFunctionCall) return functionCall;
87 hasRequiredFunctionCall = 1;
88 var NATIVE_BIND = requireFunctionBindNative();
89
90 var call = Function.prototype.call;
91
92 functionCall = NATIVE_BIND ? call.bind(call) : function () {
93 return call.apply(call, arguments);
94 };
95 return functionCall;
96 }
97
98 var objectPropertyIsEnumerable = {};
99
100 var hasRequiredObjectPropertyIsEnumerable;
101
102 function requireObjectPropertyIsEnumerable () {
103 if (hasRequiredObjectPropertyIsEnumerable) return objectPropertyIsEnumerable;
104 hasRequiredObjectPropertyIsEnumerable = 1;
105 var $propertyIsEnumerable = {}.propertyIsEnumerable;
106 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
107 var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
108
109 // Nashorn ~ JDK8 bug
110 var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1);
111
112 // `Object.prototype.propertyIsEnumerable` method implementation
113 // https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
114 objectPropertyIsEnumerable.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
115 var descriptor = getOwnPropertyDescriptor(this, V);
116 return !!descriptor && descriptor.enumerable;
117 } : $propertyIsEnumerable;
118 return objectPropertyIsEnumerable;
119 }
120
121 var createPropertyDescriptor;
122 var hasRequiredCreatePropertyDescriptor;
123
124 function requireCreatePropertyDescriptor () {
125 if (hasRequiredCreatePropertyDescriptor) return createPropertyDescriptor;
126 hasRequiredCreatePropertyDescriptor = 1;
127 createPropertyDescriptor = function (bitmap, value) {
128 return {
129 enumerable: !(bitmap & 1),
130 configurable: !(bitmap & 2),
131 writable: !(bitmap & 4),
132 value: value
133 };
134 };
135 return createPropertyDescriptor;
136 }
137
138 var functionUncurryThis;
139 var hasRequiredFunctionUncurryThis;
140
141 function requireFunctionUncurryThis () {
142 if (hasRequiredFunctionUncurryThis) return functionUncurryThis;
143 hasRequiredFunctionUncurryThis = 1;
144 var NATIVE_BIND = requireFunctionBindNative();
145
146 var FunctionPrototype = Function.prototype;
147 var call = FunctionPrototype.call;
148 var uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call);
149
150 functionUncurryThis = NATIVE_BIND ? uncurryThisWithBind : function (fn) {
151 return function () {
152 return call.apply(fn, arguments);
153 };
154 };
155 return functionUncurryThis;
156 }
157
158 var classofRaw;
159 var hasRequiredClassofRaw;
160
161 function requireClassofRaw () {
162 if (hasRequiredClassofRaw) return classofRaw;
163 hasRequiredClassofRaw = 1;
164 var uncurryThis = requireFunctionUncurryThis();
165
166 var toString = uncurryThis({}.toString);
167 var stringSlice = uncurryThis(''.slice);
168
169 classofRaw = function (it) {
170 return stringSlice(toString(it), 8, -1);
171 };
172 return classofRaw;
173 }
174
175 var indexedObject;
176 var hasRequiredIndexedObject;
177
178 function requireIndexedObject () {
179 if (hasRequiredIndexedObject) return indexedObject;
180 hasRequiredIndexedObject = 1;
181 var uncurryThis = requireFunctionUncurryThis();
182 var fails = requireFails();
183 var classof = requireClassofRaw();
184
185 var $Object = Object;
186 var split = uncurryThis(''.split);
187
188 // fallback for non-array-like ES3 and non-enumerable old V8 strings
189 indexedObject = fails(function () {
190 // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
191 // eslint-disable-next-line no-prototype-builtins -- safe
192 return !$Object('z').propertyIsEnumerable(0);
193 }) ? function (it) {
194 return classof(it) === 'String' ? split(it, '') : $Object(it);
195 } : $Object;
196 return indexedObject;
197 }
198
199 var isNullOrUndefined;
200 var hasRequiredIsNullOrUndefined;
201
202 function requireIsNullOrUndefined () {
203 if (hasRequiredIsNullOrUndefined) return isNullOrUndefined;
204 hasRequiredIsNullOrUndefined = 1;
205 // we can't use just `it == null` since of `document.all` special case
206 // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
207 isNullOrUndefined = function (it) {
208 return it === null || it === undefined;
209 };
210 return isNullOrUndefined;
211 }
212
213 var requireObjectCoercible;
214 var hasRequiredRequireObjectCoercible;
215
216 function requireRequireObjectCoercible () {
217 if (hasRequiredRequireObjectCoercible) return requireObjectCoercible;
218 hasRequiredRequireObjectCoercible = 1;
219 var isNullOrUndefined = requireIsNullOrUndefined();
220
221 var $TypeError = TypeError;
222
223 // `RequireObjectCoercible` abstract operation
224 // https://tc39.es/ecma262/#sec-requireobjectcoercible
225 requireObjectCoercible = function (it) {
226 if (isNullOrUndefined(it)) throw new $TypeError("Can't call method on " + it);
227 return it;
228 };
229 return requireObjectCoercible;
230 }
231
232 var toIndexedObject;
233 var hasRequiredToIndexedObject;
234
235 function requireToIndexedObject () {
236 if (hasRequiredToIndexedObject) return toIndexedObject;
237 hasRequiredToIndexedObject = 1;
238 // toObject with fallback for non-array-like ES3 strings
239 var IndexedObject = requireIndexedObject();
240 var requireObjectCoercible = requireRequireObjectCoercible();
241
242 toIndexedObject = function (it) {
243 return IndexedObject(requireObjectCoercible(it));
244 };
245 return toIndexedObject;
246 }
247
248 var isCallable;
249 var hasRequiredIsCallable;
250
251 function requireIsCallable () {
252 if (hasRequiredIsCallable) return isCallable;
253 hasRequiredIsCallable = 1;
254 // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
255 var documentAll = typeof document == 'object' && document.all;
256
257 // `IsCallable` abstract operation
258 // https://tc39.es/ecma262/#sec-iscallable
259 // eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing
260 isCallable = typeof documentAll == 'undefined' && documentAll !== undefined ? function (argument) {
261 return typeof argument == 'function' || argument === documentAll;
262 } : function (argument) {
263 return typeof argument == 'function';
264 };
265 return isCallable;
266 }
267
268 var isObject;
269 var hasRequiredIsObject;
270
271 function requireIsObject () {
272 if (hasRequiredIsObject) return isObject;
273 hasRequiredIsObject = 1;
274 var isCallable = requireIsCallable();
275
276 isObject = function (it) {
277 return typeof it == 'object' ? it !== null : isCallable(it);
278 };
279 return isObject;
280 }
281
282 var getBuiltIn;
283 var hasRequiredGetBuiltIn;
284
285 function requireGetBuiltIn () {
286 if (hasRequiredGetBuiltIn) return getBuiltIn;
287 hasRequiredGetBuiltIn = 1;
288 var globalThis = requireGlobalThis();
289 var isCallable = requireIsCallable();
290
291 var aFunction = function (argument) {
292 return isCallable(argument) ? argument : undefined;
293 };
294
295 getBuiltIn = function (namespace, method) {
296 return arguments.length < 2 ? aFunction(globalThis[namespace]) : globalThis[namespace] && globalThis[namespace][method];
297 };
298 return getBuiltIn;
299 }
300
301 var objectIsPrototypeOf;
302 var hasRequiredObjectIsPrototypeOf;
303
304 function requireObjectIsPrototypeOf () {
305 if (hasRequiredObjectIsPrototypeOf) return objectIsPrototypeOf;
306 hasRequiredObjectIsPrototypeOf = 1;
307 var uncurryThis = requireFunctionUncurryThis();
308
309 objectIsPrototypeOf = uncurryThis({}.isPrototypeOf);
310 return objectIsPrototypeOf;
311 }
312
313 var environmentUserAgent;
314 var hasRequiredEnvironmentUserAgent;
315
316 function requireEnvironmentUserAgent () {
317 if (hasRequiredEnvironmentUserAgent) return environmentUserAgent;
318 hasRequiredEnvironmentUserAgent = 1;
319 var globalThis = requireGlobalThis();
320
321 var navigator = globalThis.navigator;
322 var userAgent = navigator && navigator.userAgent;
323
324 environmentUserAgent = userAgent ? String(userAgent) : '';
325 return environmentUserAgent;
326 }
327
328 var environmentV8Version;
329 var hasRequiredEnvironmentV8Version;
330
331 function requireEnvironmentV8Version () {
332 if (hasRequiredEnvironmentV8Version) return environmentV8Version;
333 hasRequiredEnvironmentV8Version = 1;
334 var globalThis = requireGlobalThis();
335 var userAgent = requireEnvironmentUserAgent();
336
337 var process = globalThis.process;
338 var Deno = globalThis.Deno;
339 var versions = process && process.versions || Deno && Deno.version;
340 var v8 = versions && versions.v8;
341 var match, version;
342
343 if (v8) {
344 match = v8.split('.');
345 // in old Chrome, versions of V8 isn't V8 = Chrome / 10
346 // but their correct versions are not interesting for us
347 version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
348 }
349
350 // BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
351 // so check `userAgent` even if `.v8` exists, but 0
352 if (!version && userAgent) {
353 match = userAgent.match(/Edge\/(\d+)/);
354 if (!match || match[1] >= 74) {
355 match = userAgent.match(/Chrome\/(\d+)/);
356 if (match) version = +match[1];
357 }
358 }
359
360 environmentV8Version = version;
361 return environmentV8Version;
362 }
363
364 var symbolConstructorDetection;
365 var hasRequiredSymbolConstructorDetection;
366
367 function requireSymbolConstructorDetection () {
368 if (hasRequiredSymbolConstructorDetection) return symbolConstructorDetection;
369 hasRequiredSymbolConstructorDetection = 1;
370 /* eslint-disable es/no-symbol -- required for testing */
371 var V8_VERSION = requireEnvironmentV8Version();
372 var fails = requireFails();
373 var globalThis = requireGlobalThis();
374
375 var $String = globalThis.String;
376
377 // eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
378 symbolConstructorDetection = !!Object.getOwnPropertySymbols && !fails(function () {
379 var symbol = Symbol('symbol detection');
380 // Chrome 38 Symbol has incorrect toString conversion
381 // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
382 // nb: Do not call `String` directly to avoid this being optimized out to `symbol+''` which will,
383 // of course, fail.
384 return !$String(symbol) || !(Object(symbol) instanceof Symbol) ||
385 // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
386 !Symbol.sham && V8_VERSION && V8_VERSION < 41;
387 });
388 return symbolConstructorDetection;
389 }
390
391 var useSymbolAsUid;
392 var hasRequiredUseSymbolAsUid;
393
394 function requireUseSymbolAsUid () {
395 if (hasRequiredUseSymbolAsUid) return useSymbolAsUid;
396 hasRequiredUseSymbolAsUid = 1;
397 /* eslint-disable es/no-symbol -- required for testing */
398 var NATIVE_SYMBOL = requireSymbolConstructorDetection();
399
400 useSymbolAsUid = NATIVE_SYMBOL &&
401 !Symbol.sham &&
402 typeof Symbol.iterator == 'symbol';
403 return useSymbolAsUid;
404 }
405
406 var isSymbol;
407 var hasRequiredIsSymbol;
408
409 function requireIsSymbol () {
410 if (hasRequiredIsSymbol) return isSymbol;
411 hasRequiredIsSymbol = 1;
412 var getBuiltIn = requireGetBuiltIn();
413 var isCallable = requireIsCallable();
414 var isPrototypeOf = requireObjectIsPrototypeOf();
415 var USE_SYMBOL_AS_UID = requireUseSymbolAsUid();
416
417 var $Object = Object;
418
419 isSymbol = USE_SYMBOL_AS_UID ? function (it) {
420 return typeof it == 'symbol';
421 } : function (it) {
422 var $Symbol = getBuiltIn('Symbol');
423 return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it));
424 };
425 return isSymbol;
426 }
427
428 var tryToString;
429 var hasRequiredTryToString;
430
431 function requireTryToString () {
432 if (hasRequiredTryToString) return tryToString;
433 hasRequiredTryToString = 1;
434 var $String = String;
435
436 tryToString = function (argument) {
437 try {
438 return $String(argument);
439 } catch (error) {
440 return 'Object';
441 }
442 };
443 return tryToString;
444 }
445
446 var aCallable;
447 var hasRequiredACallable;
448
449 function requireACallable () {
450 if (hasRequiredACallable) return aCallable;
451 hasRequiredACallable = 1;
452 var isCallable = requireIsCallable();
453 var tryToString = requireTryToString();
454
455 var $TypeError = TypeError;
456
457 // `Assert: IsCallable(argument) is true`
458 aCallable = function (argument) {
459 if (isCallable(argument)) return argument;
460 throw new $TypeError(tryToString(argument) + ' is not a function');
461 };
462 return aCallable;
463 }
464
465 var getMethod;
466 var hasRequiredGetMethod;
467
468 function requireGetMethod () {
469 if (hasRequiredGetMethod) return getMethod;
470 hasRequiredGetMethod = 1;
471 var aCallable = requireACallable();
472 var isNullOrUndefined = requireIsNullOrUndefined();
473
474 // `GetMethod` abstract operation
475 // https://tc39.es/ecma262/#sec-getmethod
476 getMethod = function (V, P) {
477 var func = V[P];
478 return isNullOrUndefined(func) ? undefined : aCallable(func);
479 };
480 return getMethod;
481 }
482
483 var ordinaryToPrimitive;
484 var hasRequiredOrdinaryToPrimitive;
485
486 function requireOrdinaryToPrimitive () {
487 if (hasRequiredOrdinaryToPrimitive) return ordinaryToPrimitive;
488 hasRequiredOrdinaryToPrimitive = 1;
489 var call = requireFunctionCall();
490 var isCallable = requireIsCallable();
491 var isObject = requireIsObject();
492
493 var $TypeError = TypeError;
494
495 // `OrdinaryToPrimitive` abstract operation
496 // https://tc39.es/ecma262/#sec-ordinarytoprimitive
497 ordinaryToPrimitive = function (input, pref) {
498 var fn, val;
499 if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
500 if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val;
501 if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
502 throw new $TypeError("Can't convert object to primitive value");
503 };
504 return ordinaryToPrimitive;
505 }
506
507 var sharedStore = {exports: {}};
508
509 var isPure;
510 var hasRequiredIsPure;
511
512 function requireIsPure () {
513 if (hasRequiredIsPure) return isPure;
514 hasRequiredIsPure = 1;
515 isPure = false;
516 return isPure;
517 }
518
519 var defineGlobalProperty;
520 var hasRequiredDefineGlobalProperty;
521
522 function requireDefineGlobalProperty () {
523 if (hasRequiredDefineGlobalProperty) return defineGlobalProperty;
524 hasRequiredDefineGlobalProperty = 1;
525 var globalThis = requireGlobalThis();
526
527 // eslint-disable-next-line es/no-object-defineproperty -- safe
528 var defineProperty = Object.defineProperty;
529
530 defineGlobalProperty = function (key, value) {
531 try {
532 defineProperty(globalThis, key, { value: value, configurable: true, writable: true });
533 } catch (error) {
534 globalThis[key] = value;
535 } return value;
536 };
537 return defineGlobalProperty;
538 }
539
540 var hasRequiredSharedStore;
541
542 function requireSharedStore () {
543 if (hasRequiredSharedStore) return sharedStore.exports;
544 hasRequiredSharedStore = 1;
545 var IS_PURE = requireIsPure();
546 var globalThis = requireGlobalThis();
547 var defineGlobalProperty = requireDefineGlobalProperty();
548
549 var SHARED = '__core-js_shared__';
550 var store = sharedStore.exports = globalThis[SHARED] || defineGlobalProperty(SHARED, {});
551
552 (store.versions || (store.versions = [])).push({
553 version: '3.39.0',
554 mode: IS_PURE ? 'pure' : 'global',
555 copyright: '© 2014-2024 Denis Pushkarev (zloirock.ru)',
556 license: 'https://github.com/zloirock/core-js/blob/v3.39.0/LICENSE',
557 source: 'https://github.com/zloirock/core-js'
558 });
559 return sharedStore.exports;
560 }
561
562 var shared;
563 var hasRequiredShared;
564
565 function requireShared () {
566 if (hasRequiredShared) return shared;
567 hasRequiredShared = 1;
568 var store = requireSharedStore();
569
570 shared = function (key, value) {
571 return store[key] || (store[key] = value || {});
572 };
573 return shared;
574 }
575
576 var toObject;
577 var hasRequiredToObject;
578
579 function requireToObject () {
580 if (hasRequiredToObject) return toObject;
581 hasRequiredToObject = 1;
582 var requireObjectCoercible = requireRequireObjectCoercible();
583
584 var $Object = Object;
585
586 // `ToObject` abstract operation
587 // https://tc39.es/ecma262/#sec-toobject
588 toObject = function (argument) {
589 return $Object(requireObjectCoercible(argument));
590 };
591 return toObject;
592 }
593
594 var hasOwnProperty_1;
595 var hasRequiredHasOwnProperty;
596
597 function requireHasOwnProperty () {
598 if (hasRequiredHasOwnProperty) return hasOwnProperty_1;
599 hasRequiredHasOwnProperty = 1;
600 var uncurryThis = requireFunctionUncurryThis();
601 var toObject = requireToObject();
602
603 var hasOwnProperty = uncurryThis({}.hasOwnProperty);
604
605 // `HasOwnProperty` abstract operation
606 // https://tc39.es/ecma262/#sec-hasownproperty
607 // eslint-disable-next-line es/no-object-hasown -- safe
608 hasOwnProperty_1 = Object.hasOwn || function hasOwn(it, key) {
609 return hasOwnProperty(toObject(it), key);
610 };
611 return hasOwnProperty_1;
612 }
613
614 var uid;
615 var hasRequiredUid;
616
617 function requireUid () {
618 if (hasRequiredUid) return uid;
619 hasRequiredUid = 1;
620 var uncurryThis = requireFunctionUncurryThis();
621
622 var id = 0;
623 var postfix = Math.random();
624 var toString = uncurryThis(1.0.toString);
625
626 uid = function (key) {
627 return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36);
628 };
629 return uid;
630 }
631
632 var wellKnownSymbol;
633 var hasRequiredWellKnownSymbol;
634
635 function requireWellKnownSymbol () {
636 if (hasRequiredWellKnownSymbol) return wellKnownSymbol;
637 hasRequiredWellKnownSymbol = 1;
638 var globalThis = requireGlobalThis();
639 var shared = requireShared();
640 var hasOwn = requireHasOwnProperty();
641 var uid = requireUid();
642 var NATIVE_SYMBOL = requireSymbolConstructorDetection();
643 var USE_SYMBOL_AS_UID = requireUseSymbolAsUid();
644
645 var Symbol = globalThis.Symbol;
646 var WellKnownSymbolsStore = shared('wks');
647 var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol['for'] || Symbol : Symbol && Symbol.withoutSetter || uid;
648
649 wellKnownSymbol = function (name) {
650 if (!hasOwn(WellKnownSymbolsStore, name)) {
651 WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn(Symbol, name)
652 ? Symbol[name]
653 : createWellKnownSymbol('Symbol.' + name);
654 } return WellKnownSymbolsStore[name];
655 };
656 return wellKnownSymbol;
657 }
658
659 var toPrimitive;
660 var hasRequiredToPrimitive;
661
662 function requireToPrimitive () {
663 if (hasRequiredToPrimitive) return toPrimitive;
664 hasRequiredToPrimitive = 1;
665 var call = requireFunctionCall();
666 var isObject = requireIsObject();
667 var isSymbol = requireIsSymbol();
668 var getMethod = requireGetMethod();
669 var ordinaryToPrimitive = requireOrdinaryToPrimitive();
670 var wellKnownSymbol = requireWellKnownSymbol();
671
672 var $TypeError = TypeError;
673 var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
674
675 // `ToPrimitive` abstract operation
676 // https://tc39.es/ecma262/#sec-toprimitive
677 toPrimitive = function (input, pref) {
678 if (!isObject(input) || isSymbol(input)) return input;
679 var exoticToPrim = getMethod(input, TO_PRIMITIVE);
680 var result;
681 if (exoticToPrim) {
682 if (pref === undefined) pref = 'default';
683 result = call(exoticToPrim, input, pref);
684 if (!isObject(result) || isSymbol(result)) return result;
685 throw new $TypeError("Can't convert object to primitive value");
686 }
687 if (pref === undefined) pref = 'number';
688 return ordinaryToPrimitive(input, pref);
689 };
690 return toPrimitive;
691 }
692
693 var toPropertyKey;
694 var hasRequiredToPropertyKey;
695
696 function requireToPropertyKey () {
697 if (hasRequiredToPropertyKey) return toPropertyKey;
698 hasRequiredToPropertyKey = 1;
699 var toPrimitive = requireToPrimitive();
700 var isSymbol = requireIsSymbol();
701
702 // `ToPropertyKey` abstract operation
703 // https://tc39.es/ecma262/#sec-topropertykey
704 toPropertyKey = function (argument) {
705 var key = toPrimitive(argument, 'string');
706 return isSymbol(key) ? key : key + '';
707 };
708 return toPropertyKey;
709 }
710
711 var documentCreateElement;
712 var hasRequiredDocumentCreateElement;
713
714 function requireDocumentCreateElement () {
715 if (hasRequiredDocumentCreateElement) return documentCreateElement;
716 hasRequiredDocumentCreateElement = 1;
717 var globalThis = requireGlobalThis();
718 var isObject = requireIsObject();
719
720 var document = globalThis.document;
721 // typeof document.createElement is 'object' in old IE
722 var EXISTS = isObject(document) && isObject(document.createElement);
723
724 documentCreateElement = function (it) {
725 return EXISTS ? document.createElement(it) : {};
726 };
727 return documentCreateElement;
728 }
729
730 var ie8DomDefine;
731 var hasRequiredIe8DomDefine;
732
733 function requireIe8DomDefine () {
734 if (hasRequiredIe8DomDefine) return ie8DomDefine;
735 hasRequiredIe8DomDefine = 1;
736 var DESCRIPTORS = requireDescriptors();
737 var fails = requireFails();
738 var createElement = requireDocumentCreateElement();
739
740 // Thanks to IE8 for its funny defineProperty
741 ie8DomDefine = !DESCRIPTORS && !fails(function () {
742 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
743 return Object.defineProperty(createElement('div'), 'a', {
744 get: function () { return 7; }
745 }).a !== 7;
746 });
747 return ie8DomDefine;
748 }
749
750 var hasRequiredObjectGetOwnPropertyDescriptor;
751
752 function requireObjectGetOwnPropertyDescriptor () {
753 if (hasRequiredObjectGetOwnPropertyDescriptor) return objectGetOwnPropertyDescriptor;
754 hasRequiredObjectGetOwnPropertyDescriptor = 1;
755 var DESCRIPTORS = requireDescriptors();
756 var call = requireFunctionCall();
757 var propertyIsEnumerableModule = requireObjectPropertyIsEnumerable();
758 var createPropertyDescriptor = requireCreatePropertyDescriptor();
759 var toIndexedObject = requireToIndexedObject();
760 var toPropertyKey = requireToPropertyKey();
761 var hasOwn = requireHasOwnProperty();
762 var IE8_DOM_DEFINE = requireIe8DomDefine();
763
764 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
765 var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
766
767 // `Object.getOwnPropertyDescriptor` method
768 // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
769 objectGetOwnPropertyDescriptor.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
770 O = toIndexedObject(O);
771 P = toPropertyKey(P);
772 if (IE8_DOM_DEFINE) try {
773 return $getOwnPropertyDescriptor(O, P);
774 } catch (error) { /* empty */ }
775 if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]);
776 };
777 return objectGetOwnPropertyDescriptor;
778 }
779
780 var objectDefineProperty = {};
781
782 var v8PrototypeDefineBug;
783 var hasRequiredV8PrototypeDefineBug;
784
785 function requireV8PrototypeDefineBug () {
786 if (hasRequiredV8PrototypeDefineBug) return v8PrototypeDefineBug;
787 hasRequiredV8PrototypeDefineBug = 1;
788 var DESCRIPTORS = requireDescriptors();
789 var fails = requireFails();
790
791 // V8 ~ Chrome 36-
792 // https://bugs.chromium.org/p/v8/issues/detail?id=3334
793 v8PrototypeDefineBug = DESCRIPTORS && fails(function () {
794 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
795 return Object.defineProperty(function () { /* empty */ }, 'prototype', {
796 value: 42,
797 writable: false
798 }).prototype !== 42;
799 });
800 return v8PrototypeDefineBug;
801 }
802
803 var anObject;
804 var hasRequiredAnObject;
805
806 function requireAnObject () {
807 if (hasRequiredAnObject) return anObject;
808 hasRequiredAnObject = 1;
809 var isObject = requireIsObject();
810
811 var $String = String;
812 var $TypeError = TypeError;
813
814 // `Assert: Type(argument) is Object`
815 anObject = function (argument) {
816 if (isObject(argument)) return argument;
817 throw new $TypeError($String(argument) + ' is not an object');
818 };
819 return anObject;
820 }
821
822 var hasRequiredObjectDefineProperty;
823
824 function requireObjectDefineProperty () {
825 if (hasRequiredObjectDefineProperty) return objectDefineProperty;
826 hasRequiredObjectDefineProperty = 1;
827 var DESCRIPTORS = requireDescriptors();
828 var IE8_DOM_DEFINE = requireIe8DomDefine();
829 var V8_PROTOTYPE_DEFINE_BUG = requireV8PrototypeDefineBug();
830 var anObject = requireAnObject();
831 var toPropertyKey = requireToPropertyKey();
832
833 var $TypeError = TypeError;
834 // eslint-disable-next-line es/no-object-defineproperty -- safe
835 var $defineProperty = Object.defineProperty;
836 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
837 var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
838 var ENUMERABLE = 'enumerable';
839 var CONFIGURABLE = 'configurable';
840 var WRITABLE = 'writable';
841
842 // `Object.defineProperty` method
843 // https://tc39.es/ecma262/#sec-object.defineproperty
844 objectDefineProperty.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) {
845 anObject(O);
846 P = toPropertyKey(P);
847 anObject(Attributes);
848 if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {
849 var current = $getOwnPropertyDescriptor(O, P);
850 if (current && current[WRITABLE]) {
851 O[P] = Attributes.value;
852 Attributes = {
853 configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE],
854 enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],
855 writable: false
856 };
857 }
858 } return $defineProperty(O, P, Attributes);
859 } : $defineProperty : function defineProperty(O, P, Attributes) {
860 anObject(O);
861 P = toPropertyKey(P);
862 anObject(Attributes);
863 if (IE8_DOM_DEFINE) try {
864 return $defineProperty(O, P, Attributes);
865 } catch (error) { /* empty */ }
866 if ('get' in Attributes || 'set' in Attributes) throw new $TypeError('Accessors not supported');
867 if ('value' in Attributes) O[P] = Attributes.value;
868 return O;
869 };
870 return objectDefineProperty;
871 }
872
873 var createNonEnumerableProperty;
874 var hasRequiredCreateNonEnumerableProperty;
875
876 function requireCreateNonEnumerableProperty () {
877 if (hasRequiredCreateNonEnumerableProperty) return createNonEnumerableProperty;
878 hasRequiredCreateNonEnumerableProperty = 1;
879 var DESCRIPTORS = requireDescriptors();
880 var definePropertyModule = requireObjectDefineProperty();
881 var createPropertyDescriptor = requireCreatePropertyDescriptor();
882
883 createNonEnumerableProperty = DESCRIPTORS ? function (object, key, value) {
884 return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
885 } : function (object, key, value) {
886 object[key] = value;
887 return object;
888 };
889 return createNonEnumerableProperty;
890 }
891
892 var makeBuiltIn = {exports: {}};
893
894 var functionName;
895 var hasRequiredFunctionName;
896
897 function requireFunctionName () {
898 if (hasRequiredFunctionName) return functionName;
899 hasRequiredFunctionName = 1;
900 var DESCRIPTORS = requireDescriptors();
901 var hasOwn = requireHasOwnProperty();
902
903 var FunctionPrototype = Function.prototype;
904 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
905 var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor;
906
907 var EXISTS = hasOwn(FunctionPrototype, 'name');
908 // additional protection from minified / mangled / dropped function names
909 var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something';
910 var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable));
911
912 functionName = {
913 EXISTS: EXISTS,
914 PROPER: PROPER,
915 CONFIGURABLE: CONFIGURABLE
916 };
917 return functionName;
918 }
919
920 var inspectSource;
921 var hasRequiredInspectSource;
922
923 function requireInspectSource () {
924 if (hasRequiredInspectSource) return inspectSource;
925 hasRequiredInspectSource = 1;
926 var uncurryThis = requireFunctionUncurryThis();
927 var isCallable = requireIsCallable();
928 var store = requireSharedStore();
929
930 var functionToString = uncurryThis(Function.toString);
931
932 // this helper broken in `[email protected]`, so we can't use `shared` helper
933 if (!isCallable(store.inspectSource)) {
934 store.inspectSource = function (it) {
935 return functionToString(it);
936 };
937 }
938
939 inspectSource = store.inspectSource;
940 return inspectSource;
941 }
942
943 var weakMapBasicDetection;
944 var hasRequiredWeakMapBasicDetection;
945
946 function requireWeakMapBasicDetection () {
947 if (hasRequiredWeakMapBasicDetection) return weakMapBasicDetection;
948 hasRequiredWeakMapBasicDetection = 1;
949 var globalThis = requireGlobalThis();
950 var isCallable = requireIsCallable();
951
952 var WeakMap = globalThis.WeakMap;
953
954 weakMapBasicDetection = isCallable(WeakMap) && /native code/.test(String(WeakMap));
955 return weakMapBasicDetection;
956 }
957
958 var sharedKey;
959 var hasRequiredSharedKey;
960
961 function requireSharedKey () {
962 if (hasRequiredSharedKey) return sharedKey;
963 hasRequiredSharedKey = 1;
964 var shared = requireShared();
965 var uid = requireUid();
966
967 var keys = shared('keys');
968
969 sharedKey = function (key) {
970 return keys[key] || (keys[key] = uid(key));
971 };
972 return sharedKey;
973 }
974
975 var hiddenKeys;
976 var hasRequiredHiddenKeys;
977
978 function requireHiddenKeys () {
979 if (hasRequiredHiddenKeys) return hiddenKeys;
980 hasRequiredHiddenKeys = 1;
981 hiddenKeys = {};
982 return hiddenKeys;
983 }
984
985 var internalState;
986 var hasRequiredInternalState;
987
988 function requireInternalState () {
989 if (hasRequiredInternalState) return internalState;
990 hasRequiredInternalState = 1;
991 var NATIVE_WEAK_MAP = requireWeakMapBasicDetection();
992 var globalThis = requireGlobalThis();
993 var isObject = requireIsObject();
994 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
995 var hasOwn = requireHasOwnProperty();
996 var shared = requireSharedStore();
997 var sharedKey = requireSharedKey();
998 var hiddenKeys = requireHiddenKeys();
999
1000 var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
1001 var TypeError = globalThis.TypeError;
1002 var WeakMap = globalThis.WeakMap;
1003 var set, get, has;
1004
1005 var enforce = function (it) {
1006 return has(it) ? get(it) : set(it, {});
1007 };
1008
1009 var getterFor = function (TYPE) {
1010 return function (it) {
1011 var state;
1012 if (!isObject(it) || (state = get(it)).type !== TYPE) {
1013 throw new TypeError('Incompatible receiver, ' + TYPE + ' required');
1014 } return state;
1015 };
1016 };
1017
1018 if (NATIVE_WEAK_MAP || shared.state) {
1019 var store = shared.state || (shared.state = new WeakMap());
1020 /* eslint-disable no-self-assign -- prototype methods protection */
1021 store.get = store.get;
1022 store.has = store.has;
1023 store.set = store.set;
1024 /* eslint-enable no-self-assign -- prototype methods protection */
1025 set = function (it, metadata) {
1026 if (store.has(it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
1027 metadata.facade = it;
1028 store.set(it, metadata);
1029 return metadata;
1030 };
1031 get = function (it) {
1032 return store.get(it) || {};
1033 };
1034 has = function (it) {
1035 return store.has(it);
1036 };
1037 } else {
1038 var STATE = sharedKey('state');
1039 hiddenKeys[STATE] = true;
1040 set = function (it, metadata) {
1041 if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
1042 metadata.facade = it;
1043 createNonEnumerableProperty(it, STATE, metadata);
1044 return metadata;
1045 };
1046 get = function (it) {
1047 return hasOwn(it, STATE) ? it[STATE] : {};
1048 };
1049 has = function (it) {
1050 return hasOwn(it, STATE);
1051 };
1052 }
1053
1054 internalState = {
1055 set: set,
1056 get: get,
1057 has: has,
1058 enforce: enforce,
1059 getterFor: getterFor
1060 };
1061 return internalState;
1062 }
1063
1064 var hasRequiredMakeBuiltIn;
1065
1066 function requireMakeBuiltIn () {
1067 if (hasRequiredMakeBuiltIn) return makeBuiltIn.exports;
1068 hasRequiredMakeBuiltIn = 1;
1069 var uncurryThis = requireFunctionUncurryThis();
1070 var fails = requireFails();
1071 var isCallable = requireIsCallable();
1072 var hasOwn = requireHasOwnProperty();
1073 var DESCRIPTORS = requireDescriptors();
1074 var CONFIGURABLE_FUNCTION_NAME = requireFunctionName().CONFIGURABLE;
1075 var inspectSource = requireInspectSource();
1076 var InternalStateModule = requireInternalState();
1077
1078 var enforceInternalState = InternalStateModule.enforce;
1079 var getInternalState = InternalStateModule.get;
1080 var $String = String;
1081 // eslint-disable-next-line es/no-object-defineproperty -- safe
1082 var defineProperty = Object.defineProperty;
1083 var stringSlice = uncurryThis(''.slice);
1084 var replace = uncurryThis(''.replace);
1085 var join = uncurryThis([].join);
1086
1087 var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function () {
1088 return defineProperty(function () { /* empty */ }, 'length', { value: 8 }).length !== 8;
1089 });
1090
1091 var TEMPLATE = String(String).split('String');
1092
1093 var makeBuiltIn$1 = makeBuiltIn.exports = function (value, name, options) {
1094 if (stringSlice($String(name), 0, 7) === 'Symbol(') {
1095 name = '[' + replace($String(name), /^Symbol\(([^)]*)\).*$/, '$1') + ']';
1096 }
1097 if (options && options.getter) name = 'get ' + name;
1098 if (options && options.setter) name = 'set ' + name;
1099 if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) {
1100 if (DESCRIPTORS) defineProperty(value, 'name', { value: name, configurable: true });
1101 else value.name = name;
1102 }
1103 if (CONFIGURABLE_LENGTH && options && hasOwn(options, 'arity') && value.length !== options.arity) {
1104 defineProperty(value, 'length', { value: options.arity });
1105 }
1106 try {
1107 if (options && hasOwn(options, 'constructor') && options.constructor) {
1108 if (DESCRIPTORS) defineProperty(value, 'prototype', { writable: false });
1109 // in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable
1110 } else if (value.prototype) value.prototype = undefined;
1111 } catch (error) { /* empty */ }
1112 var state = enforceInternalState(value);
1113 if (!hasOwn(state, 'source')) {
1114 state.source = join(TEMPLATE, typeof name == 'string' ? name : '');
1115 } return value;
1116 };
1117
1118 // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
1119 // eslint-disable-next-line no-extend-native -- required
1120 Function.prototype.toString = makeBuiltIn$1(function toString() {
1121 return isCallable(this) && getInternalState(this).source || inspectSource(this);
1122 }, 'toString');
1123 return makeBuiltIn.exports;
1124 }
1125
1126 var defineBuiltIn;
1127 var hasRequiredDefineBuiltIn;
1128
1129 function requireDefineBuiltIn () {
1130 if (hasRequiredDefineBuiltIn) return defineBuiltIn;
1131 hasRequiredDefineBuiltIn = 1;
1132 var isCallable = requireIsCallable();
1133 var definePropertyModule = requireObjectDefineProperty();
1134 var makeBuiltIn = requireMakeBuiltIn();
1135 var defineGlobalProperty = requireDefineGlobalProperty();
1136
1137 defineBuiltIn = function (O, key, value, options) {
1138 if (!options) options = {};
1139 var simple = options.enumerable;
1140 var name = options.name !== undefined ? options.name : key;
1141 if (isCallable(value)) makeBuiltIn(value, name, options);
1142 if (options.global) {
1143 if (simple) O[key] = value;
1144 else defineGlobalProperty(key, value);
1145 } else {
1146 try {
1147 if (!options.unsafe) delete O[key];
1148 else if (O[key]) simple = true;
1149 } catch (error) { /* empty */ }
1150 if (simple) O[key] = value;
1151 else definePropertyModule.f(O, key, {
1152 value: value,
1153 enumerable: false,
1154 configurable: !options.nonConfigurable,
1155 writable: !options.nonWritable
1156 });
1157 } return O;
1158 };
1159 return defineBuiltIn;
1160 }
1161
1162 var objectGetOwnPropertyNames = {};
1163
1164 var mathTrunc;
1165 var hasRequiredMathTrunc;
1166
1167 function requireMathTrunc () {
1168 if (hasRequiredMathTrunc) return mathTrunc;
1169 hasRequiredMathTrunc = 1;
1170 var ceil = Math.ceil;
1171 var floor = Math.floor;
1172
1173 // `Math.trunc` method
1174 // https://tc39.es/ecma262/#sec-math.trunc
1175 // eslint-disable-next-line es/no-math-trunc -- safe
1176 mathTrunc = Math.trunc || function trunc(x) {
1177 var n = +x;
1178 return (n > 0 ? floor : ceil)(n);
1179 };
1180 return mathTrunc;
1181 }
1182
1183 var toIntegerOrInfinity;
1184 var hasRequiredToIntegerOrInfinity;
1185
1186 function requireToIntegerOrInfinity () {
1187 if (hasRequiredToIntegerOrInfinity) return toIntegerOrInfinity;
1188 hasRequiredToIntegerOrInfinity = 1;
1189 var trunc = requireMathTrunc();
1190
1191 // `ToIntegerOrInfinity` abstract operation
1192 // https://tc39.es/ecma262/#sec-tointegerorinfinity
1193 toIntegerOrInfinity = function (argument) {
1194 var number = +argument;
1195 // eslint-disable-next-line no-self-compare -- NaN check
1196 return number !== number || number === 0 ? 0 : trunc(number);
1197 };
1198 return toIntegerOrInfinity;
1199 }
1200
1201 var toAbsoluteIndex;
1202 var hasRequiredToAbsoluteIndex;
1203
1204 function requireToAbsoluteIndex () {
1205 if (hasRequiredToAbsoluteIndex) return toAbsoluteIndex;
1206 hasRequiredToAbsoluteIndex = 1;
1207 var toIntegerOrInfinity = requireToIntegerOrInfinity();
1208
1209 var max = Math.max;
1210 var min = Math.min;
1211
1212 // Helper for a popular repeating case of the spec:
1213 // Let integer be ? ToInteger(index).
1214 // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
1215 toAbsoluteIndex = function (index, length) {
1216 var integer = toIntegerOrInfinity(index);
1217 return integer < 0 ? max(integer + length, 0) : min(integer, length);
1218 };
1219 return toAbsoluteIndex;
1220 }
1221
1222 var toLength;
1223 var hasRequiredToLength;
1224
1225 function requireToLength () {
1226 if (hasRequiredToLength) return toLength;
1227 hasRequiredToLength = 1;
1228 var toIntegerOrInfinity = requireToIntegerOrInfinity();
1229
1230 var min = Math.min;
1231
1232 // `ToLength` abstract operation
1233 // https://tc39.es/ecma262/#sec-tolength
1234 toLength = function (argument) {
1235 var len = toIntegerOrInfinity(argument);
1236 return len > 0 ? min(len, 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
1237 };
1238 return toLength;
1239 }
1240
1241 var lengthOfArrayLike;
1242 var hasRequiredLengthOfArrayLike;
1243
1244 function requireLengthOfArrayLike () {
1245 if (hasRequiredLengthOfArrayLike) return lengthOfArrayLike;
1246 hasRequiredLengthOfArrayLike = 1;
1247 var toLength = requireToLength();
1248
1249 // `LengthOfArrayLike` abstract operation
1250 // https://tc39.es/ecma262/#sec-lengthofarraylike
1251 lengthOfArrayLike = function (obj) {
1252 return toLength(obj.length);
1253 };
1254 return lengthOfArrayLike;
1255 }
1256
1257 var arrayIncludes;
1258 var hasRequiredArrayIncludes;
1259
1260 function requireArrayIncludes () {
1261 if (hasRequiredArrayIncludes) return arrayIncludes;
1262 hasRequiredArrayIncludes = 1;
1263 var toIndexedObject = requireToIndexedObject();
1264 var toAbsoluteIndex = requireToAbsoluteIndex();
1265 var lengthOfArrayLike = requireLengthOfArrayLike();
1266
1267 // `Array.prototype.{ indexOf, includes }` methods implementation
1268 var createMethod = function (IS_INCLUDES) {
1269 return function ($this, el, fromIndex) {
1270 var O = toIndexedObject($this);
1271 var length = lengthOfArrayLike(O);
1272 if (length === 0) return !IS_INCLUDES && -1;
1273 var index = toAbsoluteIndex(fromIndex, length);
1274 var value;
1275 // Array#includes uses SameValueZero equality algorithm
1276 // eslint-disable-next-line no-self-compare -- NaN check
1277 if (IS_INCLUDES && el !== el) while (length > index) {
1278 value = O[index++];
1279 // eslint-disable-next-line no-self-compare -- NaN check
1280 if (value !== value) return true;
1281 // Array#indexOf ignores holes, Array#includes - not
1282 } else for (;length > index; index++) {
1283 if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
1284 } return !IS_INCLUDES && -1;
1285 };
1286 };
1287
1288 arrayIncludes = {
1289 // `Array.prototype.includes` method
1290 // https://tc39.es/ecma262/#sec-array.prototype.includes
1291 includes: createMethod(true),
1292 // `Array.prototype.indexOf` method
1293 // https://tc39.es/ecma262/#sec-array.prototype.indexof
1294 indexOf: createMethod(false)
1295 };
1296 return arrayIncludes;
1297 }
1298
1299 var objectKeysInternal;
1300 var hasRequiredObjectKeysInternal;
1301
1302 function requireObjectKeysInternal () {
1303 if (hasRequiredObjectKeysInternal) return objectKeysInternal;
1304 hasRequiredObjectKeysInternal = 1;
1305 var uncurryThis = requireFunctionUncurryThis();
1306 var hasOwn = requireHasOwnProperty();
1307 var toIndexedObject = requireToIndexedObject();
1308 var indexOf = requireArrayIncludes().indexOf;
1309 var hiddenKeys = requireHiddenKeys();
1310
1311 var push = uncurryThis([].push);
1312
1313 objectKeysInternal = function (object, names) {
1314 var O = toIndexedObject(object);
1315 var i = 0;
1316 var result = [];
1317 var key;
1318 for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key);
1319 // Don't enum bug & hidden keys
1320 while (names.length > i) if (hasOwn(O, key = names[i++])) {
1321 ~indexOf(result, key) || push(result, key);
1322 }
1323 return result;
1324 };
1325 return objectKeysInternal;
1326 }
1327
1328 var enumBugKeys;
1329 var hasRequiredEnumBugKeys;
1330
1331 function requireEnumBugKeys () {
1332 if (hasRequiredEnumBugKeys) return enumBugKeys;
1333 hasRequiredEnumBugKeys = 1;
1334 // IE8- don't enum bug keys
1335 enumBugKeys = [
1336 'constructor',
1337 'hasOwnProperty',
1338 'isPrototypeOf',
1339 'propertyIsEnumerable',
1340 'toLocaleString',
1341 'toString',
1342 'valueOf'
1343 ];
1344 return enumBugKeys;
1345 }
1346
1347 var hasRequiredObjectGetOwnPropertyNames;
1348
1349 function requireObjectGetOwnPropertyNames () {
1350 if (hasRequiredObjectGetOwnPropertyNames) return objectGetOwnPropertyNames;
1351 hasRequiredObjectGetOwnPropertyNames = 1;
1352 var internalObjectKeys = requireObjectKeysInternal();
1353 var enumBugKeys = requireEnumBugKeys();
1354
1355 var hiddenKeys = enumBugKeys.concat('length', 'prototype');
1356
1357 // `Object.getOwnPropertyNames` method
1358 // https://tc39.es/ecma262/#sec-object.getownpropertynames
1359 // eslint-disable-next-line es/no-object-getownpropertynames -- safe
1360 objectGetOwnPropertyNames.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
1361 return internalObjectKeys(O, hiddenKeys);
1362 };
1363 return objectGetOwnPropertyNames;
1364 }
1365
1366 var objectGetOwnPropertySymbols = {};
1367
1368 var hasRequiredObjectGetOwnPropertySymbols;
1369
1370 function requireObjectGetOwnPropertySymbols () {
1371 if (hasRequiredObjectGetOwnPropertySymbols) return objectGetOwnPropertySymbols;
1372 hasRequiredObjectGetOwnPropertySymbols = 1;
1373 // eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
1374 objectGetOwnPropertySymbols.f = Object.getOwnPropertySymbols;
1375 return objectGetOwnPropertySymbols;
1376 }
1377
1378 var ownKeys;
1379 var hasRequiredOwnKeys;
1380
1381 function requireOwnKeys () {
1382 if (hasRequiredOwnKeys) return ownKeys;
1383 hasRequiredOwnKeys = 1;
1384 var getBuiltIn = requireGetBuiltIn();
1385 var uncurryThis = requireFunctionUncurryThis();
1386 var getOwnPropertyNamesModule = requireObjectGetOwnPropertyNames();
1387 var getOwnPropertySymbolsModule = requireObjectGetOwnPropertySymbols();
1388 var anObject = requireAnObject();
1389
1390 var concat = uncurryThis([].concat);
1391
1392 // all object keys, includes non-enumerable and symbols
1393 ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
1394 var keys = getOwnPropertyNamesModule.f(anObject(it));
1395 var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
1396 return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys;
1397 };
1398 return ownKeys;
1399 }
1400
1401 var copyConstructorProperties;
1402 var hasRequiredCopyConstructorProperties;
1403
1404 function requireCopyConstructorProperties () {
1405 if (hasRequiredCopyConstructorProperties) return copyConstructorProperties;
1406 hasRequiredCopyConstructorProperties = 1;
1407 var hasOwn = requireHasOwnProperty();
1408 var ownKeys = requireOwnKeys();
1409 var getOwnPropertyDescriptorModule = requireObjectGetOwnPropertyDescriptor();
1410 var definePropertyModule = requireObjectDefineProperty();
1411
1412 copyConstructorProperties = function (target, source, exceptions) {
1413 var keys = ownKeys(source);
1414 var defineProperty = definePropertyModule.f;
1415 var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
1416 for (var i = 0; i < keys.length; i++) {
1417 var key = keys[i];
1418 if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) {
1419 defineProperty(target, key, getOwnPropertyDescriptor(source, key));
1420 }
1421 }
1422 };
1423 return copyConstructorProperties;
1424 }
1425
1426 var isForced_1;
1427 var hasRequiredIsForced;
1428
1429 function requireIsForced () {
1430 if (hasRequiredIsForced) return isForced_1;
1431 hasRequiredIsForced = 1;
1432 var fails = requireFails();
1433 var isCallable = requireIsCallable();
1434
1435 var replacement = /#|\.prototype\./;
1436
1437 var isForced = function (feature, detection) {
1438 var value = data[normalize(feature)];
1439 return value === POLYFILL ? true
1440 : value === NATIVE ? false
1441 : isCallable(detection) ? fails(detection)
1442 : !!detection;
1443 };
1444
1445 var normalize = isForced.normalize = function (string) {
1446 return String(string).replace(replacement, '.').toLowerCase();
1447 };
1448
1449 var data = isForced.data = {};
1450 var NATIVE = isForced.NATIVE = 'N';
1451 var POLYFILL = isForced.POLYFILL = 'P';
1452
1453 isForced_1 = isForced;
1454 return isForced_1;
1455 }
1456
1457 var _export;
1458 var hasRequired_export;
1459
1460 function require_export () {
1461 if (hasRequired_export) return _export;
1462 hasRequired_export = 1;
1463 var globalThis = requireGlobalThis();
1464 var getOwnPropertyDescriptor = requireObjectGetOwnPropertyDescriptor().f;
1465 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
1466 var defineBuiltIn = requireDefineBuiltIn();
1467 var defineGlobalProperty = requireDefineGlobalProperty();
1468 var copyConstructorProperties = requireCopyConstructorProperties();
1469 var isForced = requireIsForced();
1470
1471 /*
1472 options.target - name of the target object
1473 options.global - target is the global object
1474 options.stat - export as static methods of target
1475 options.proto - export as prototype methods of target
1476 options.real - real prototype method for the `pure` version
1477 options.forced - export even if the native feature is available
1478 options.bind - bind methods to the target, required for the `pure` version
1479 options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
1480 options.unsafe - use the simple assignment of property instead of delete + defineProperty
1481 options.sham - add a flag to not completely full polyfills
1482 options.enumerable - export as enumerable property
1483 options.dontCallGetSet - prevent calling a getter on target
1484 options.name - the .name of the function if it does not match the key
1485 */
1486 _export = function (options, source) {
1487 var TARGET = options.target;
1488 var GLOBAL = options.global;
1489 var STATIC = options.stat;
1490 var FORCED, target, key, targetProperty, sourceProperty, descriptor;
1491 if (GLOBAL) {
1492 target = globalThis;
1493 } else if (STATIC) {
1494 target = globalThis[TARGET] || defineGlobalProperty(TARGET, {});
1495 } else {
1496 target = globalThis[TARGET] && globalThis[TARGET].prototype;
1497 }
1498 if (target) for (key in source) {
1499 sourceProperty = source[key];
1500 if (options.dontCallGetSet) {
1501 descriptor = getOwnPropertyDescriptor(target, key);
1502 targetProperty = descriptor && descriptor.value;
1503 } else targetProperty = target[key];
1504 FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
1505 // contained in target
1506 if (!FORCED && targetProperty !== undefined) {
1507 if (typeof sourceProperty == typeof targetProperty) continue;
1508 copyConstructorProperties(sourceProperty, targetProperty);
1509 }
1510 // add a flag to not completely full polyfills
1511 if (options.sham || (targetProperty && targetProperty.sham)) {
1512 createNonEnumerableProperty(sourceProperty, 'sham', true);
1513 }
1514 defineBuiltIn(target, key, sourceProperty, options);
1515 }
1516 };
1517 return _export;
1518 }
1519
1520 var getIteratorDirect;
1521 var hasRequiredGetIteratorDirect;
1522
1523 function requireGetIteratorDirect () {
1524 if (hasRequiredGetIteratorDirect) return getIteratorDirect;
1525 hasRequiredGetIteratorDirect = 1;
1526 // `GetIteratorDirect(obj)` abstract operation
1527 // https://tc39.es/proposal-iterator-helpers/#sec-getiteratordirect
1528 getIteratorDirect = function (obj) {
1529 return {
1530 iterator: obj,
1531 next: obj.next,
1532 done: false
1533 };
1534 };
1535 return getIteratorDirect;
1536 }
1537
1538 var objectDefineProperties = {};
1539
1540 var objectKeys;
1541 var hasRequiredObjectKeys;
1542
1543 function requireObjectKeys () {
1544 if (hasRequiredObjectKeys) return objectKeys;
1545 hasRequiredObjectKeys = 1;
1546 var internalObjectKeys = requireObjectKeysInternal();
1547 var enumBugKeys = requireEnumBugKeys();
1548
1549 // `Object.keys` method
1550 // https://tc39.es/ecma262/#sec-object.keys
1551 // eslint-disable-next-line es/no-object-keys -- safe
1552 objectKeys = Object.keys || function keys(O) {
1553 return internalObjectKeys(O, enumBugKeys);
1554 };
1555 return objectKeys;
1556 }
1557
1558 var hasRequiredObjectDefineProperties;
1559
1560 function requireObjectDefineProperties () {
1561 if (hasRequiredObjectDefineProperties) return objectDefineProperties;
1562 hasRequiredObjectDefineProperties = 1;
1563 var DESCRIPTORS = requireDescriptors();
1564 var V8_PROTOTYPE_DEFINE_BUG = requireV8PrototypeDefineBug();
1565 var definePropertyModule = requireObjectDefineProperty();
1566 var anObject = requireAnObject();
1567 var toIndexedObject = requireToIndexedObject();
1568 var objectKeys = requireObjectKeys();
1569
1570 // `Object.defineProperties` method
1571 // https://tc39.es/ecma262/#sec-object.defineproperties
1572 // eslint-disable-next-line es/no-object-defineproperties -- safe
1573 objectDefineProperties.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) {
1574 anObject(O);
1575 var props = toIndexedObject(Properties);
1576 var keys = objectKeys(Properties);
1577 var length = keys.length;
1578 var index = 0;
1579 var key;
1580 while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]);
1581 return O;
1582 };
1583 return objectDefineProperties;
1584 }
1585
1586 var html;
1587 var hasRequiredHtml;
1588
1589 function requireHtml () {
1590 if (hasRequiredHtml) return html;
1591 hasRequiredHtml = 1;
1592 var getBuiltIn = requireGetBuiltIn();
1593
1594 html = getBuiltIn('document', 'documentElement');
1595 return html;
1596 }
1597
1598 var objectCreate;
1599 var hasRequiredObjectCreate;
1600
1601 function requireObjectCreate () {
1602 if (hasRequiredObjectCreate) return objectCreate;
1603 hasRequiredObjectCreate = 1;
1604 /* global ActiveXObject -- old IE, WSH */
1605 var anObject = requireAnObject();
1606 var definePropertiesModule = requireObjectDefineProperties();
1607 var enumBugKeys = requireEnumBugKeys();
1608 var hiddenKeys = requireHiddenKeys();
1609 var html = requireHtml();
1610 var documentCreateElement = requireDocumentCreateElement();
1611 var sharedKey = requireSharedKey();
1612
1613 var GT = '>';
1614 var LT = '<';
1615 var PROTOTYPE = 'prototype';
1616 var SCRIPT = 'script';
1617 var IE_PROTO = sharedKey('IE_PROTO');
1618
1619 var EmptyConstructor = function () { /* empty */ };
1620
1621 var scriptTag = function (content) {
1622 return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
1623 };
1624
1625 // Create object with fake `null` prototype: use ActiveX Object with cleared prototype
1626 var NullProtoObjectViaActiveX = function (activeXDocument) {
1627 activeXDocument.write(scriptTag(''));
1628 activeXDocument.close();
1629 var temp = activeXDocument.parentWindow.Object;
1630 // eslint-disable-next-line no-useless-assignment -- avoid memory leak
1631 activeXDocument = null;
1632 return temp;
1633 };
1634
1635 // Create object with fake `null` prototype: use iframe Object with cleared prototype
1636 var NullProtoObjectViaIFrame = function () {
1637 // Thrash, waste and sodomy: IE GC bug
1638 var iframe = documentCreateElement('iframe');
1639 var JS = 'java' + SCRIPT + ':';
1640 var iframeDocument;
1641 iframe.style.display = 'none';
1642 html.appendChild(iframe);
1643 // https://github.com/zloirock/core-js/issues/475
1644 iframe.src = String(JS);
1645 iframeDocument = iframe.contentWindow.document;
1646 iframeDocument.open();
1647 iframeDocument.write(scriptTag('document.F=Object'));
1648 iframeDocument.close();
1649 return iframeDocument.F;
1650 };
1651
1652 // Check for document.domain and active x support
1653 // No need to use active x approach when document.domain is not set
1654 // see https://github.com/es-shims/es5-shim/issues/150
1655 // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
1656 // avoid IE GC bug
1657 var activeXDocument;
1658 var NullProtoObject = function () {
1659 try {
1660 activeXDocument = new ActiveXObject('htmlfile');
1661 } catch (error) { /* ignore */ }
1662 NullProtoObject = typeof document != 'undefined'
1663 ? document.domain && activeXDocument
1664 ? NullProtoObjectViaActiveX(activeXDocument) // old IE
1665 : NullProtoObjectViaIFrame()
1666 : NullProtoObjectViaActiveX(activeXDocument); // WSH
1667 var length = enumBugKeys.length;
1668 while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
1669 return NullProtoObject();
1670 };
1671
1672 hiddenKeys[IE_PROTO] = true;
1673
1674 // `Object.create` method
1675 // https://tc39.es/ecma262/#sec-object.create
1676 // eslint-disable-next-line es/no-object-create -- safe
1677 objectCreate = Object.create || function create(O, Properties) {
1678 var result;
1679 if (O !== null) {
1680 EmptyConstructor[PROTOTYPE] = anObject(O);
1681 result = new EmptyConstructor();
1682 EmptyConstructor[PROTOTYPE] = null;
1683 // add "__proto__" for Object.getPrototypeOf polyfill
1684 result[IE_PROTO] = O;
1685 } else result = NullProtoObject();
1686 return Properties === undefined ? result : definePropertiesModule.f(result, Properties);
1687 };
1688 return objectCreate;
1689 }
1690
1691 var defineBuiltIns;
1692 var hasRequiredDefineBuiltIns;
1693
1694 function requireDefineBuiltIns () {
1695 if (hasRequiredDefineBuiltIns) return defineBuiltIns;
1696 hasRequiredDefineBuiltIns = 1;
1697 var defineBuiltIn = requireDefineBuiltIn();
1698
1699 defineBuiltIns = function (target, src, options) {
1700 for (var key in src) defineBuiltIn(target, key, src[key], options);
1701 return target;
1702 };
1703 return defineBuiltIns;
1704 }
1705
1706 var correctPrototypeGetter;
1707 var hasRequiredCorrectPrototypeGetter;
1708
1709 function requireCorrectPrototypeGetter () {
1710 if (hasRequiredCorrectPrototypeGetter) return correctPrototypeGetter;
1711 hasRequiredCorrectPrototypeGetter = 1;
1712 var fails = requireFails();
1713
1714 correctPrototypeGetter = !fails(function () {
1715 function F() { /* empty */ }
1716 F.prototype.constructor = null;
1717 // eslint-disable-next-line es/no-object-getprototypeof -- required for testing
1718 return Object.getPrototypeOf(new F()) !== F.prototype;
1719 });
1720 return correctPrototypeGetter;
1721 }
1722
1723 var objectGetPrototypeOf;
1724 var hasRequiredObjectGetPrototypeOf;
1725
1726 function requireObjectGetPrototypeOf () {
1727 if (hasRequiredObjectGetPrototypeOf) return objectGetPrototypeOf;
1728 hasRequiredObjectGetPrototypeOf = 1;
1729 var hasOwn = requireHasOwnProperty();
1730 var isCallable = requireIsCallable();
1731 var toObject = requireToObject();
1732 var sharedKey = requireSharedKey();
1733 var CORRECT_PROTOTYPE_GETTER = requireCorrectPrototypeGetter();
1734
1735 var IE_PROTO = sharedKey('IE_PROTO');
1736 var $Object = Object;
1737 var ObjectPrototype = $Object.prototype;
1738
1739 // `Object.getPrototypeOf` method
1740 // https://tc39.es/ecma262/#sec-object.getprototypeof
1741 // eslint-disable-next-line es/no-object-getprototypeof -- safe
1742 objectGetPrototypeOf = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function (O) {
1743 var object = toObject(O);
1744 if (hasOwn(object, IE_PROTO)) return object[IE_PROTO];
1745 var constructor = object.constructor;
1746 if (isCallable(constructor) && object instanceof constructor) {
1747 return constructor.prototype;
1748 } return object instanceof $Object ? ObjectPrototype : null;
1749 };
1750 return objectGetPrototypeOf;
1751 }
1752
1753 var iteratorsCore;
1754 var hasRequiredIteratorsCore;
1755
1756 function requireIteratorsCore () {
1757 if (hasRequiredIteratorsCore) return iteratorsCore;
1758 hasRequiredIteratorsCore = 1;
1759 var fails = requireFails();
1760 var isCallable = requireIsCallable();
1761 var isObject = requireIsObject();
1762 var create = requireObjectCreate();
1763 var getPrototypeOf = requireObjectGetPrototypeOf();
1764 var defineBuiltIn = requireDefineBuiltIn();
1765 var wellKnownSymbol = requireWellKnownSymbol();
1766 var IS_PURE = requireIsPure();
1767
1768 var ITERATOR = wellKnownSymbol('iterator');
1769 var BUGGY_SAFARI_ITERATORS = false;
1770
1771 // `%IteratorPrototype%` object
1772 // https://tc39.es/ecma262/#sec-%iteratorprototype%-object
1773 var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
1774
1775 /* eslint-disable es/no-array-prototype-keys -- safe */
1776 if ([].keys) {
1777 arrayIterator = [].keys();
1778 // Safari 8 has buggy iterators w/o `next`
1779 if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
1780 else {
1781 PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));
1782 if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
1783 }
1784 }
1785
1786 var NEW_ITERATOR_PROTOTYPE = !isObject(IteratorPrototype) || fails(function () {
1787 var test = {};
1788 // FF44- legacy iterators case
1789 return IteratorPrototype[ITERATOR].call(test) !== test;
1790 });
1791
1792 if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {};
1793 else if (IS_PURE) IteratorPrototype = create(IteratorPrototype);
1794
1795 // `%IteratorPrototype%[@@iterator]()` method
1796 // https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator
1797 if (!isCallable(IteratorPrototype[ITERATOR])) {
1798 defineBuiltIn(IteratorPrototype, ITERATOR, function () {
1799 return this;
1800 });
1801 }
1802
1803 iteratorsCore = {
1804 IteratorPrototype: IteratorPrototype,
1805 BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
1806 };
1807 return iteratorsCore;
1808 }
1809
1810 var createIterResultObject;
1811 var hasRequiredCreateIterResultObject;
1812
1813 function requireCreateIterResultObject () {
1814 if (hasRequiredCreateIterResultObject) return createIterResultObject;
1815 hasRequiredCreateIterResultObject = 1;
1816 // `CreateIterResultObject` abstract operation
1817 // https://tc39.es/ecma262/#sec-createiterresultobject
1818 createIterResultObject = function (value, done) {
1819 return { value: value, done: done };
1820 };
1821 return createIterResultObject;
1822 }
1823
1824 var iteratorClose;
1825 var hasRequiredIteratorClose;
1826
1827 function requireIteratorClose () {
1828 if (hasRequiredIteratorClose) return iteratorClose;
1829 hasRequiredIteratorClose = 1;
1830 var call = requireFunctionCall();
1831 var anObject = requireAnObject();
1832 var getMethod = requireGetMethod();
1833
1834 iteratorClose = function (iterator, kind, value) {
1835 var innerResult, innerError;
1836 anObject(iterator);
1837 try {
1838 innerResult = getMethod(iterator, 'return');
1839 if (!innerResult) {
1840 if (kind === 'throw') throw value;
1841 return value;
1842 }
1843 innerResult = call(innerResult, iterator);
1844 } catch (error) {
1845 innerError = true;
1846 innerResult = error;
1847 }
1848 if (kind === 'throw') throw value;
1849 if (innerError) throw innerResult;
1850 anObject(innerResult);
1851 return value;
1852 };
1853 return iteratorClose;
1854 }
1855
1856 var iteratorCreateProxy;
1857 var hasRequiredIteratorCreateProxy;
1858
1859 function requireIteratorCreateProxy () {
1860 if (hasRequiredIteratorCreateProxy) return iteratorCreateProxy;
1861 hasRequiredIteratorCreateProxy = 1;
1862 var call = requireFunctionCall();
1863 var create = requireObjectCreate();
1864 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
1865 var defineBuiltIns = requireDefineBuiltIns();
1866 var wellKnownSymbol = requireWellKnownSymbol();
1867 var InternalStateModule = requireInternalState();
1868 var getMethod = requireGetMethod();
1869 var IteratorPrototype = requireIteratorsCore().IteratorPrototype;
1870 var createIterResultObject = requireCreateIterResultObject();
1871 var iteratorClose = requireIteratorClose();
1872
1873 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
1874 var ITERATOR_HELPER = 'IteratorHelper';
1875 var WRAP_FOR_VALID_ITERATOR = 'WrapForValidIterator';
1876 var setInternalState = InternalStateModule.set;
1877
1878 var createIteratorProxyPrototype = function (IS_ITERATOR) {
1879 var getInternalState = InternalStateModule.getterFor(IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER);
1880
1881 return defineBuiltIns(create(IteratorPrototype), {
1882 next: function next() {
1883 var state = getInternalState(this);
1884 // for simplification:
1885 // for `%WrapForValidIteratorPrototype%.next` our `nextHandler` returns `IterResultObject`
1886 // for `%IteratorHelperPrototype%.next` - just a value
1887 if (IS_ITERATOR) return state.nextHandler();
1888 try {
1889 var result = state.done ? undefined : state.nextHandler();
1890 return createIterResultObject(result, state.done);
1891 } catch (error) {
1892 state.done = true;
1893 throw error;
1894 }
1895 },
1896 'return': function () {
1897 var state = getInternalState(this);
1898 var iterator = state.iterator;
1899 state.done = true;
1900 if (IS_ITERATOR) {
1901 var returnMethod = getMethod(iterator, 'return');
1902 return returnMethod ? call(returnMethod, iterator) : createIterResultObject(undefined, true);
1903 }
1904 if (state.inner) try {
1905 iteratorClose(state.inner.iterator, 'normal');
1906 } catch (error) {
1907 return iteratorClose(iterator, 'throw', error);
1908 }
1909 if (iterator) iteratorClose(iterator, 'normal');
1910 return createIterResultObject(undefined, true);
1911 }
1912 });
1913 };
1914
1915 var WrapForValidIteratorPrototype = createIteratorProxyPrototype(true);
1916 var IteratorHelperPrototype = createIteratorProxyPrototype(false);
1917
1918 createNonEnumerableProperty(IteratorHelperPrototype, TO_STRING_TAG, 'Iterator Helper');
1919
1920 iteratorCreateProxy = function (nextHandler, IS_ITERATOR) {
1921 var IteratorProxy = function Iterator(record, state) {
1922 if (state) {
1923 state.iterator = record.iterator;
1924 state.next = record.next;
1925 } else state = record;
1926 state.type = IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER;
1927 state.nextHandler = nextHandler;
1928 state.counter = 0;
1929 state.done = false;
1930 setInternalState(this, state);
1931 };
1932
1933 IteratorProxy.prototype = IS_ITERATOR ? WrapForValidIteratorPrototype : IteratorHelperPrototype;
1934
1935 return IteratorProxy;
1936 };
1937 return iteratorCreateProxy;
1938 }
1939
1940 var callWithSafeIterationClosing;
1941 var hasRequiredCallWithSafeIterationClosing;
1942
1943 function requireCallWithSafeIterationClosing () {
1944 if (hasRequiredCallWithSafeIterationClosing) return callWithSafeIterationClosing;
1945 hasRequiredCallWithSafeIterationClosing = 1;
1946 var anObject = requireAnObject();
1947 var iteratorClose = requireIteratorClose();
1948
1949 // call something on iterator step with safe closing on error
1950 callWithSafeIterationClosing = function (iterator, fn, value, ENTRIES) {
1951 try {
1952 return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
1953 } catch (error) {
1954 iteratorClose(iterator, 'throw', error);
1955 }
1956 };
1957 return callWithSafeIterationClosing;
1958 }
1959
1960 var iteratorMap;
1961 var hasRequiredIteratorMap;
1962
1963 function requireIteratorMap () {
1964 if (hasRequiredIteratorMap) return iteratorMap;
1965 hasRequiredIteratorMap = 1;
1966 var call = requireFunctionCall();
1967 var aCallable = requireACallable();
1968 var anObject = requireAnObject();
1969 var getIteratorDirect = requireGetIteratorDirect();
1970 var createIteratorProxy = requireIteratorCreateProxy();
1971 var callWithSafeIterationClosing = requireCallWithSafeIterationClosing();
1972
1973 var IteratorProxy = createIteratorProxy(function () {
1974 var iterator = this.iterator;
1975 var result = anObject(call(this.next, iterator));
1976 var done = this.done = !!result.done;
1977 if (!done) return callWithSafeIterationClosing(iterator, this.mapper, [result.value, this.counter++], true);
1978 });
1979
1980 // `Iterator.prototype.map` method
1981 // https://github.com/tc39/proposal-iterator-helpers
1982 iteratorMap = function map(mapper) {
1983 anObject(this);
1984 aCallable(mapper);
1985 return new IteratorProxy(getIteratorDirect(this), {
1986 mapper: mapper
1987 });
1988 };
1989 return iteratorMap;
1990 }
1991
1992 var hasRequiredEs_iterator_map;
1993
1994 function requireEs_iterator_map () {
1995 if (hasRequiredEs_iterator_map) return es_iterator_map;
1996 hasRequiredEs_iterator_map = 1;
1997 var $ = require_export();
1998 var map = requireIteratorMap();
1999 var IS_PURE = requireIsPure();
2000
2001 // `Iterator.prototype.map` method
2002 // https://tc39.es/ecma262/#sec-iterator.prototype.map
2003 $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
2004 map: map
2005 });
2006 return es_iterator_map;
2007 }
2008
2009 var hasRequiredEsnext_iterator_map;
2010
2011 function requireEsnext_iterator_map () {
2012 if (hasRequiredEsnext_iterator_map) return esnext_iterator_map;
2013 hasRequiredEsnext_iterator_map = 1;
2014 // TODO: Remove from `core-js@4`
2015 requireEs_iterator_map();
2016 return esnext_iterator_map;
2017 }
2018
2019 requireEsnext_iterator_map();
2020
2021 /** @import { Matrix3x3, Vector3 } from "./types.js" */
2022
2023 /**
2024 * A is m x n. B is n x p. product is m x p.
2025 *
2026 * Array arguments are treated like vectors:
2027 * - A becomes 1 x n
2028 * - B becomes n x 1
2029 *
2030 * Returns Matrix m x p or equivalent array or number
2031 *
2032 * @overload
2033 * @param {number[]} A Vector 1 x n
2034 * @param {number[]} B Vector n x 1
2035 * @returns {number} Scalar number
2036 *
2037 * @overload
2038 * @param {number[][]} A Matrix m x n
2039 * @param {number[]} B Vector n x 1
2040 * @returns {number[]} Array with length m
2041 *
2042 * @overload
2043 * @param {number[]} A Vector 1 x n
2044 * @param {number[][]} B Matrix n x p
2045 * @returns {number[]} Array with length p
2046 *
2047 * @overload
2048 * @param {number[][]} A Matrix m x n
2049 * @param {number[][]} B Matrix n x p
2050 * @returns {number[][]} Matrix m x p
2051 *
2052 * @param {number[] | number[][]} A Matrix m x n or a vector
2053 * @param {number[] | number[][]} B Matrix n x p or a vector
2054 * @returns {number | number[] | number[][]} Matrix m x p or equivalent array or number
2055 */
2056 function multiplyMatrices(A, B) {
2057 let m = A.length;
2058 /** @type {number[][]} */
2059 let AM;
2060 /** @type {number[][]} */
2061 let BM;
2062 let aVec = false;
2063 let bVec = false;
2064 if (!Array.isArray(A[0])) {
2065 // A is vector, convert to [[a, b, c, ...]]
2066 AM = [(/** @type {number[]} */A)];
2067 m = AM.length;
2068 aVec = true;
2069 } else {
2070 AM = /** @type {number[][]} */A;
2071 }
2072 if (!Array.isArray(B[0])) {
2073 // B is vector, convert to [[a], [b], [c], ...]]
2074 BM = B.length > 0 ? B.map(x => [x]) : [[]]; // Avoid mapping empty array
2075 bVec = true;
2076 } else {
2077 BM = /** @type {number[][]} */B;
2078 }
2079 let p = BM[0].length;
2080 let BM_cols = BM[0].map((_, i) => BM.map(x => x[i])); // transpose B
2081 /** @type {number[] | number[][]} */
2082 let product = AM.map(row => BM_cols.map(col => {
2083 let ret = 0;
2084 if (!Array.isArray(row)) {
2085 for (let c of col) {
2086 ret += row * c;
2087 }
2088 return ret;
2089 }
2090 for (let i = 0; i < row.length; i++) {
2091 ret += row[i] * (col[i] || 0);
2092 }
2093 return ret;
2094 }));
2095 if (m === 1 && aVec) {
2096 product = product[0]; // Avoid [[a, b, c, ...]]
2097 }
2098 if (p === 1 && bVec) {
2099 if (m === 1 && aVec) {
2100 return product[0]; // Avoid [[a]], return a number
2101 } else {
2102 return product.map(x => x[0]); // Avoid [[a], [b], [c], ...]]
2103 }
2104 }
2105 return product;
2106 }
2107
2108 // dot3 and transform functions adapted from https://github.com/texel-org/color/blob/9793c7d4d02b51f068e0f3fd37131129a4270396/src/core.js
2109 //
2110 // The MIT License (MIT)
2111 // Copyright (c) 2024 Matt DesLauriers
2112
2113 // Permission is hereby granted, free of charge, to any person obtaining a copy
2114 // of this software and associated documentation files (the "Software"), to deal
2115 // in the Software without restriction, including without limitation the rights
2116 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
2117 // copies of the Software, and to permit persons to whom the Software is
2118 // furnished to do so, subject to the following conditions:
2119
2120 // The above copyright notice and this permission notice shall be included in all
2121 // copies or substantial portions of the Software.
2122
2123 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2124 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2125 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
2126 // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
2127 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
2128 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
2129 // OR OTHER DEALINGS IN THE SOFTWARE.
2130
2131 /**
2132 * Returns the dot product of two vectors each with a length of 3.
2133 *
2134 * @param {Vector3} a
2135 * @param {Vector3} b
2136 * @returns {number}
2137 */
2138 function dot3(a, b) {
2139 return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
2140 }
2141
2142 /**
2143 * Transforms a vector of length 3 by a 3x3 matrix. Specify the same input and output
2144 * vector to transform in place.
2145 *
2146 * @param {Vector3} input
2147 * @param {Matrix3x3} matrix
2148 * @param {Vector3} [out]
2149 * @returns {Vector3}
2150 */
2151 function multiply_v3_m3x3(input, matrix, out = [0, 0, 0]) {
2152 const x = dot3(input, matrix[0]);
2153 const y = dot3(input, matrix[1]);
2154 const z = dot3(input, matrix[2]);
2155 out[0] = x;
2156 out[1] = y;
2157 out[2] = z;
2158 return out;
2159 }
2160
2161 /**
2162 * Various utility functions
2163 */
2164
2165
2166 /**
2167 * Check if a value is a string (including a String object)
2168 * @param {any} str - Value to check
2169 * @returns {str is string}
2170 */
2171 function isString(str) {
2172 return type(str) === "string";
2173 }
2174
2175 /**
2176 * Determine the internal JavaScript [[Class]] of an object.
2177 * @param {any} o - Value to check
2178 * @returns {string}
2179 */
2180 function type(o) {
2181 let str = Object.prototype.toString.call(o);
2182 return (str.match(/^\[object\s+(.*?)\]$/)[1] || "").toLowerCase();
2183 }
2184
2185 /**
2186 * @param {number} n
2187 * @param {{ precision?: number | undefined, unit?: string | undefined }} options
2188 * @returns {string}
2189 */
2190 function serializeNumber(n, {
2191 precision = 16,
2192 unit
2193 }) {
2194 if (isNone(n)) {
2195 return "none";
2196 }
2197 n = +toPrecision(n, precision);
2198 return n + (unit !== null && unit !== void 0 ? unit : "");
2199 }
2200
2201 /**
2202 * Check if a value corresponds to a none argument
2203 * @param {any} n - Value to check
2204 * @returns {n is null}
2205 */
2206 function isNone(n) {
2207 return n === null;
2208 }
2209
2210 /**
2211 * Replace none values with 0
2212 * @param {number | null} n
2213 * @returns {number}
2214 */
2215 function skipNone(n) {
2216 return isNone(n) ? 0 : n;
2217 }
2218
2219 /**
2220 * Round a number to a certain number of significant digits
2221 * @param {number} n - The number to round
2222 * @param {number} precision - Number of significant digits
2223 */
2224 function toPrecision(n, precision) {
2225 if (n === 0) {
2226 return 0;
2227 }
2228 let integer = ~~n;
2229 let digits = 0;
2230 if (integer && precision) {
2231 digits = ~~Math.log10(Math.abs(integer)) + 1;
2232 }
2233 const multiplier = 10.0 ** (precision - digits);
2234 return Math.floor(n * multiplier + 0.5) / multiplier;
2235 }
2236
2237 /**
2238 * @param {number} start
2239 * @param {number} end
2240 * @param {number} p
2241 */
2242 function interpolate(start, end, p) {
2243 if (isNaN(start)) {
2244 return end;
2245 }
2246 if (isNaN(end)) {
2247 return start;
2248 }
2249 return start + (end - start) * p;
2250 }
2251
2252 /**
2253 * @param {number} start
2254 * @param {number} end
2255 * @param {number} value
2256 */
2257 function interpolateInv(start, end, value) {
2258 return (value - start) / (end - start);
2259 }
2260
2261 /**
2262 * @param {[number, number]} from
2263 * @param {[number, number]} to
2264 * @param {number} value
2265 */
2266 function mapRange(from, to, value) {
2267 if (!from || !to || from === to || from[0] === to[0] && from[1] === to[1] || isNaN(value) || value === null) {
2268 // Ranges missing or the same
2269 return value;
2270 }
2271 return interpolate(to[0], to[1], interpolateInv(from[0], from[1], value));
2272 }
2273
2274 /**
2275 * Clamp value between the minimum and maximum
2276 * @param {number} min minimum value to return
2277 * @param {number} val the value to return if it is between min and max
2278 * @param {number} max maximum value to return
2279 */
2280 function clamp(min, val, max) {
2281 return Math.max(Math.min(max, val), min);
2282 }
2283
2284 /**
2285 * Copy sign of one value to another.
2286 * @param {number} to - Number to copy sign to
2287 * @param {number} from - Number to copy sign from
2288 */
2289 function copySign(to, from) {
2290 return Math.sign(to) === Math.sign(from) ? to : -to;
2291 }
2292
2293 /**
2294 * Perform pow on a signed number and copy sign to result
2295 * @param {number} base The base number
2296 * @param {number} exp The exponent
2297 */
2298 function spow(base, exp) {
2299 return copySign(Math.abs(base) ** exp, base);
2300 }
2301
2302 /**
2303 * Perform a divide, but return zero if the denominator is zero
2304 * @param {number} n The numerator
2305 * @param {number} d The denominator
2306 */
2307 function zdiv(n, d) {
2308 return d === 0 ? 0 : n / d;
2309 }
2310
2311 /**
2312 * Perform a bisect on a sorted list and locate the insertion point for
2313 * a value in arr to maintain sorted order.
2314 * @param {number[]} arr - array of sorted numbers
2315 * @param {number} value - value to find insertion point for
2316 * @param {number} lo - used to specify a the low end of a subset of the list
2317 * @param {number} hi - used to specify a the high end of a subset of the list
2318 */
2319 function bisectLeft(arr, value, lo = 0, hi = arr.length) {
2320 while (lo < hi) {
2321 const mid = lo + hi >> 1;
2322 if (arr[mid] < value) {
2323 lo = mid + 1;
2324 } else {
2325 hi = mid;
2326 }
2327 }
2328 return lo;
2329 }
2330
2331 /**
2332 * Determines whether an argument is an instance of a constructor, including subclasses.
2333 * This is done by first just checking `instanceof`,
2334 * and then comparing the string names of the constructors if that fails.
2335 * @param {any} arg
2336 * @param {C} constructor
2337 * @template {new (...args: any) => any} C
2338 * @returns {arg is InstanceType<C>}
2339 */
2340 function isInstance(arg, constructor) {
2341 if (arg instanceof constructor) {
2342 return true;
2343 }
2344 const targetName = constructor.name;
2345 while (arg) {
2346 var _proto$constructor;
2347 const proto = Object.getPrototypeOf(arg);
2348 const constructorName = proto === null || proto === void 0 || (_proto$constructor = proto.constructor) === null || _proto$constructor === void 0 ? void 0 : _proto$constructor.name;
2349 if (constructorName === targetName) {
2350 return true;
2351 }
2352 if (!constructorName || constructorName === "Object") {
2353 return false;
2354 }
2355 arg = proto;
2356 }
2357 return false;
2358 }
2359
2360 var util = /*#__PURE__*/Object.freeze({
2361 __proto__: null,
2362 bisectLeft: bisectLeft,
2363 clamp: clamp,
2364 copySign: copySign,
2365 interpolate: interpolate,
2366 interpolateInv: interpolateInv,
2367 isInstance: isInstance,
2368 isNone: isNone,
2369 isString: isString,
2370 mapRange: mapRange,
2371 multiplyMatrices: multiplyMatrices,
2372 multiply_v3_m3x3: multiply_v3_m3x3,
2373 serializeNumber: serializeNumber,
2374 skipNone: skipNone,
2375 spow: spow,
2376 toPrecision: toPrecision,
2377 type: type,
2378 zdiv: zdiv
2379 });
2380
2381 var esnext_iterator_constructor = {};
2382
2383 var es_iterator_constructor = {};
2384
2385 var anInstance;
2386 var hasRequiredAnInstance;
2387
2388 function requireAnInstance () {
2389 if (hasRequiredAnInstance) return anInstance;
2390 hasRequiredAnInstance = 1;
2391 var isPrototypeOf = requireObjectIsPrototypeOf();
2392
2393 var $TypeError = TypeError;
2394
2395 anInstance = function (it, Prototype) {
2396 if (isPrototypeOf(Prototype, it)) return it;
2397 throw new $TypeError('Incorrect invocation');
2398 };
2399 return anInstance;
2400 }
2401
2402 var defineBuiltInAccessor;
2403 var hasRequiredDefineBuiltInAccessor;
2404
2405 function requireDefineBuiltInAccessor () {
2406 if (hasRequiredDefineBuiltInAccessor) return defineBuiltInAccessor;
2407 hasRequiredDefineBuiltInAccessor = 1;
2408 var makeBuiltIn = requireMakeBuiltIn();
2409 var defineProperty = requireObjectDefineProperty();
2410
2411 defineBuiltInAccessor = function (target, name, descriptor) {
2412 if (descriptor.get) makeBuiltIn(descriptor.get, name, { getter: true });
2413 if (descriptor.set) makeBuiltIn(descriptor.set, name, { setter: true });
2414 return defineProperty.f(target, name, descriptor);
2415 };
2416 return defineBuiltInAccessor;
2417 }
2418
2419 var createProperty;
2420 var hasRequiredCreateProperty;
2421
2422 function requireCreateProperty () {
2423 if (hasRequiredCreateProperty) return createProperty;
2424 hasRequiredCreateProperty = 1;
2425 var DESCRIPTORS = requireDescriptors();
2426 var definePropertyModule = requireObjectDefineProperty();
2427 var createPropertyDescriptor = requireCreatePropertyDescriptor();
2428
2429 createProperty = function (object, key, value) {
2430 if (DESCRIPTORS) definePropertyModule.f(object, key, createPropertyDescriptor(0, value));
2431 else object[key] = value;
2432 };
2433 return createProperty;
2434 }
2435
2436 var hasRequiredEs_iterator_constructor;
2437
2438 function requireEs_iterator_constructor () {
2439 if (hasRequiredEs_iterator_constructor) return es_iterator_constructor;
2440 hasRequiredEs_iterator_constructor = 1;
2441 var $ = require_export();
2442 var globalThis = requireGlobalThis();
2443 var anInstance = requireAnInstance();
2444 var anObject = requireAnObject();
2445 var isCallable = requireIsCallable();
2446 var getPrototypeOf = requireObjectGetPrototypeOf();
2447 var defineBuiltInAccessor = requireDefineBuiltInAccessor();
2448 var createProperty = requireCreateProperty();
2449 var fails = requireFails();
2450 var hasOwn = requireHasOwnProperty();
2451 var wellKnownSymbol = requireWellKnownSymbol();
2452 var IteratorPrototype = requireIteratorsCore().IteratorPrototype;
2453 var DESCRIPTORS = requireDescriptors();
2454 var IS_PURE = requireIsPure();
2455
2456 var CONSTRUCTOR = 'constructor';
2457 var ITERATOR = 'Iterator';
2458 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
2459
2460 var $TypeError = TypeError;
2461 var NativeIterator = globalThis[ITERATOR];
2462
2463 // FF56- have non-standard global helper `Iterator`
2464 var FORCED = IS_PURE
2465 || !isCallable(NativeIterator)
2466 || NativeIterator.prototype !== IteratorPrototype
2467 // FF44- non-standard `Iterator` passes previous tests
2468 || !fails(function () { NativeIterator({}); });
2469
2470 var IteratorConstructor = function Iterator() {
2471 anInstance(this, IteratorPrototype);
2472 if (getPrototypeOf(this) === IteratorPrototype) throw new $TypeError('Abstract class Iterator not directly constructable');
2473 };
2474
2475 var defineIteratorPrototypeAccessor = function (key, value) {
2476 if (DESCRIPTORS) {
2477 defineBuiltInAccessor(IteratorPrototype, key, {
2478 configurable: true,
2479 get: function () {
2480 return value;
2481 },
2482 set: function (replacement) {
2483 anObject(this);
2484 if (this === IteratorPrototype) throw new $TypeError("You can't redefine this property");
2485 if (hasOwn(this, key)) this[key] = replacement;
2486 else createProperty(this, key, replacement);
2487 }
2488 });
2489 } else IteratorPrototype[key] = value;
2490 };
2491
2492 if (!hasOwn(IteratorPrototype, TO_STRING_TAG)) defineIteratorPrototypeAccessor(TO_STRING_TAG, ITERATOR);
2493
2494 if (FORCED || !hasOwn(IteratorPrototype, CONSTRUCTOR) || IteratorPrototype[CONSTRUCTOR] === Object) {
2495 defineIteratorPrototypeAccessor(CONSTRUCTOR, IteratorConstructor);
2496 }
2497
2498 IteratorConstructor.prototype = IteratorPrototype;
2499
2500 // `Iterator` constructor
2501 // https://tc39.es/ecma262/#sec-iterator
2502 $({ global: true, constructor: true, forced: FORCED }, {
2503 Iterator: IteratorConstructor
2504 });
2505 return es_iterator_constructor;
2506 }
2507
2508 var hasRequiredEsnext_iterator_constructor;
2509
2510 function requireEsnext_iterator_constructor () {
2511 if (hasRequiredEsnext_iterator_constructor) return esnext_iterator_constructor;
2512 hasRequiredEsnext_iterator_constructor = 1;
2513 // TODO: Remove from `core-js@4`
2514 requireEs_iterator_constructor();
2515 return esnext_iterator_constructor;
2516 }
2517
2518 requireEsnext_iterator_constructor();
2519
2520 var esnext_iterator_forEach = {};
2521
2522 var es_iterator_forEach = {};
2523
2524 var functionUncurryThisClause;
2525 var hasRequiredFunctionUncurryThisClause;
2526
2527 function requireFunctionUncurryThisClause () {
2528 if (hasRequiredFunctionUncurryThisClause) return functionUncurryThisClause;
2529 hasRequiredFunctionUncurryThisClause = 1;
2530 var classofRaw = requireClassofRaw();
2531 var uncurryThis = requireFunctionUncurryThis();
2532
2533 functionUncurryThisClause = function (fn) {
2534 // Nashorn bug:
2535 // https://github.com/zloirock/core-js/issues/1128
2536 // https://github.com/zloirock/core-js/issues/1130
2537 if (classofRaw(fn) === 'Function') return uncurryThis(fn);
2538 };
2539 return functionUncurryThisClause;
2540 }
2541
2542 var functionBindContext;
2543 var hasRequiredFunctionBindContext;
2544
2545 function requireFunctionBindContext () {
2546 if (hasRequiredFunctionBindContext) return functionBindContext;
2547 hasRequiredFunctionBindContext = 1;
2548 var uncurryThis = requireFunctionUncurryThisClause();
2549 var aCallable = requireACallable();
2550 var NATIVE_BIND = requireFunctionBindNative();
2551
2552 var bind = uncurryThis(uncurryThis.bind);
2553
2554 // optional / simple context binding
2555 functionBindContext = function (fn, that) {
2556 aCallable(fn);
2557 return that === undefined ? fn : NATIVE_BIND ? bind(fn, that) : function (/* ...args */) {
2558 return fn.apply(that, arguments);
2559 };
2560 };
2561 return functionBindContext;
2562 }
2563
2564 var iterators;
2565 var hasRequiredIterators;
2566
2567 function requireIterators () {
2568 if (hasRequiredIterators) return iterators;
2569 hasRequiredIterators = 1;
2570 iterators = {};
2571 return iterators;
2572 }
2573
2574 var isArrayIteratorMethod;
2575 var hasRequiredIsArrayIteratorMethod;
2576
2577 function requireIsArrayIteratorMethod () {
2578 if (hasRequiredIsArrayIteratorMethod) return isArrayIteratorMethod;
2579 hasRequiredIsArrayIteratorMethod = 1;
2580 var wellKnownSymbol = requireWellKnownSymbol();
2581 var Iterators = requireIterators();
2582
2583 var ITERATOR = wellKnownSymbol('iterator');
2584 var ArrayPrototype = Array.prototype;
2585
2586 // check on default Array iterator
2587 isArrayIteratorMethod = function (it) {
2588 return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);
2589 };
2590 return isArrayIteratorMethod;
2591 }
2592
2593 var toStringTagSupport;
2594 var hasRequiredToStringTagSupport;
2595
2596 function requireToStringTagSupport () {
2597 if (hasRequiredToStringTagSupport) return toStringTagSupport;
2598 hasRequiredToStringTagSupport = 1;
2599 var wellKnownSymbol = requireWellKnownSymbol();
2600
2601 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
2602 var test = {};
2603
2604 test[TO_STRING_TAG] = 'z';
2605
2606 toStringTagSupport = String(test) === '[object z]';
2607 return toStringTagSupport;
2608 }
2609
2610 var classof;
2611 var hasRequiredClassof;
2612
2613 function requireClassof () {
2614 if (hasRequiredClassof) return classof;
2615 hasRequiredClassof = 1;
2616 var TO_STRING_TAG_SUPPORT = requireToStringTagSupport();
2617 var isCallable = requireIsCallable();
2618 var classofRaw = requireClassofRaw();
2619 var wellKnownSymbol = requireWellKnownSymbol();
2620
2621 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
2622 var $Object = Object;
2623
2624 // ES3 wrong here
2625 var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) === 'Arguments';
2626
2627 // fallback for IE11 Script Access Denied error
2628 var tryGet = function (it, key) {
2629 try {
2630 return it[key];
2631 } catch (error) { /* empty */ }
2632 };
2633
2634 // getting tag from ES6+ `Object.prototype.toString`
2635 classof = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {
2636 var O, tag, result;
2637 return it === undefined ? 'Undefined' : it === null ? 'Null'
2638 // @@toStringTag case
2639 : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == 'string' ? tag
2640 // builtinTag case
2641 : CORRECT_ARGUMENTS ? classofRaw(O)
2642 // ES3 arguments fallback
2643 : (result = classofRaw(O)) === 'Object' && isCallable(O.callee) ? 'Arguments' : result;
2644 };
2645 return classof;
2646 }
2647
2648 var getIteratorMethod;
2649 var hasRequiredGetIteratorMethod;
2650
2651 function requireGetIteratorMethod () {
2652 if (hasRequiredGetIteratorMethod) return getIteratorMethod;
2653 hasRequiredGetIteratorMethod = 1;
2654 var classof = requireClassof();
2655 var getMethod = requireGetMethod();
2656 var isNullOrUndefined = requireIsNullOrUndefined();
2657 var Iterators = requireIterators();
2658 var wellKnownSymbol = requireWellKnownSymbol();
2659
2660 var ITERATOR = wellKnownSymbol('iterator');
2661
2662 getIteratorMethod = function (it) {
2663 if (!isNullOrUndefined(it)) return getMethod(it, ITERATOR)
2664 || getMethod(it, '@@iterator')
2665 || Iterators[classof(it)];
2666 };
2667 return getIteratorMethod;
2668 }
2669
2670 var getIterator;
2671 var hasRequiredGetIterator;
2672
2673 function requireGetIterator () {
2674 if (hasRequiredGetIterator) return getIterator;
2675 hasRequiredGetIterator = 1;
2676 var call = requireFunctionCall();
2677 var aCallable = requireACallable();
2678 var anObject = requireAnObject();
2679 var tryToString = requireTryToString();
2680 var getIteratorMethod = requireGetIteratorMethod();
2681
2682 var $TypeError = TypeError;
2683
2684 getIterator = function (argument, usingIterator) {
2685 var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator;
2686 if (aCallable(iteratorMethod)) return anObject(call(iteratorMethod, argument));
2687 throw new $TypeError(tryToString(argument) + ' is not iterable');
2688 };
2689 return getIterator;
2690 }
2691
2692 var iterate;
2693 var hasRequiredIterate;
2694
2695 function requireIterate () {
2696 if (hasRequiredIterate) return iterate;
2697 hasRequiredIterate = 1;
2698 var bind = requireFunctionBindContext();
2699 var call = requireFunctionCall();
2700 var anObject = requireAnObject();
2701 var tryToString = requireTryToString();
2702 var isArrayIteratorMethod = requireIsArrayIteratorMethod();
2703 var lengthOfArrayLike = requireLengthOfArrayLike();
2704 var isPrototypeOf = requireObjectIsPrototypeOf();
2705 var getIterator = requireGetIterator();
2706 var getIteratorMethod = requireGetIteratorMethod();
2707 var iteratorClose = requireIteratorClose();
2708
2709 var $TypeError = TypeError;
2710
2711 var Result = function (stopped, result) {
2712 this.stopped = stopped;
2713 this.result = result;
2714 };
2715
2716 var ResultPrototype = Result.prototype;
2717
2718 iterate = function (iterable, unboundFunction, options) {
2719 var that = options && options.that;
2720 var AS_ENTRIES = !!(options && options.AS_ENTRIES);
2721 var IS_RECORD = !!(options && options.IS_RECORD);
2722 var IS_ITERATOR = !!(options && options.IS_ITERATOR);
2723 var INTERRUPTED = !!(options && options.INTERRUPTED);
2724 var fn = bind(unboundFunction, that);
2725 var iterator, iterFn, index, length, result, next, step;
2726
2727 var stop = function (condition) {
2728 if (iterator) iteratorClose(iterator, 'normal', condition);
2729 return new Result(true, condition);
2730 };
2731
2732 var callFn = function (value) {
2733 if (AS_ENTRIES) {
2734 anObject(value);
2735 return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
2736 } return INTERRUPTED ? fn(value, stop) : fn(value);
2737 };
2738
2739 if (IS_RECORD) {
2740 iterator = iterable.iterator;
2741 } else if (IS_ITERATOR) {
2742 iterator = iterable;
2743 } else {
2744 iterFn = getIteratorMethod(iterable);
2745 if (!iterFn) throw new $TypeError(tryToString(iterable) + ' is not iterable');
2746 // optimisation for array iterators
2747 if (isArrayIteratorMethod(iterFn)) {
2748 for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) {
2749 result = callFn(iterable[index]);
2750 if (result && isPrototypeOf(ResultPrototype, result)) return result;
2751 } return new Result(false);
2752 }
2753 iterator = getIterator(iterable, iterFn);
2754 }
2755
2756 next = IS_RECORD ? iterable.next : iterator.next;
2757 while (!(step = call(next, iterator)).done) {
2758 try {
2759 result = callFn(step.value);
2760 } catch (error) {
2761 iteratorClose(iterator, 'throw', error);
2762 }
2763 if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result;
2764 } return new Result(false);
2765 };
2766 return iterate;
2767 }
2768
2769 var hasRequiredEs_iterator_forEach;
2770
2771 function requireEs_iterator_forEach () {
2772 if (hasRequiredEs_iterator_forEach) return es_iterator_forEach;
2773 hasRequiredEs_iterator_forEach = 1;
2774 var $ = require_export();
2775 var iterate = requireIterate();
2776 var aCallable = requireACallable();
2777 var anObject = requireAnObject();
2778 var getIteratorDirect = requireGetIteratorDirect();
2779
2780 // `Iterator.prototype.forEach` method
2781 // https://tc39.es/ecma262/#sec-iterator.prototype.foreach
2782 $({ target: 'Iterator', proto: true, real: true }, {
2783 forEach: function forEach(fn) {
2784 anObject(this);
2785 aCallable(fn);
2786 var record = getIteratorDirect(this);
2787 var counter = 0;
2788 iterate(record, function (value) {
2789 fn(value, counter++);
2790 }, { IS_RECORD: true });
2791 }
2792 });
2793 return es_iterator_forEach;
2794 }
2795
2796 var hasRequiredEsnext_iterator_forEach;
2797
2798 function requireEsnext_iterator_forEach () {
2799 if (hasRequiredEsnext_iterator_forEach) return esnext_iterator_forEach;
2800 hasRequiredEsnext_iterator_forEach = 1;
2801 // TODO: Remove from `core-js@4`
2802 requireEs_iterator_forEach();
2803 return esnext_iterator_forEach;
2804 }
2805
2806 requireEsnext_iterator_forEach();
2807
2808 /**
2809 * A class for adding deep extensibility to any piece of JS code
2810 */
2811 class Hooks {
2812 add(name, callback, first) {
2813 if (typeof arguments[0] != "string") {
2814 // Multiple hooks
2815 for (var name in arguments[0]) {
2816 this.add(name, arguments[0][name], arguments[1]);
2817 }
2818 return;
2819 }
2820 (Array.isArray(name) ? name : [name]).forEach(function (name) {
2821 this[name] = this[name] || [];
2822 if (callback) {
2823 this[name][first ? "unshift" : "push"](callback);
2824 }
2825 }, this);
2826 }
2827 run(name, env) {
2828 this[name] = this[name] || [];
2829 this[name].forEach(function (callback) {
2830 callback.call(env && env.context ? env.context : env, env);
2831 });
2832 }
2833 }
2834
2835 /**
2836 * The instance of {@link Hooks} used throughout Color.js
2837 */
2838 const hooks = new Hooks();
2839
2840 var _globalThis$process;
2841 // Global defaults one may want to configure
2842 var defaults = {
2843 gamut_mapping: "css",
2844 precision: 5,
2845 deltaE: "76",
2846 // Default deltaE method
2847 verbose: (globalThis === null || globalThis === void 0 || (_globalThis$process = globalThis.process) === null || _globalThis$process === void 0 || (_globalThis$process = _globalThis$process.env) === null || _globalThis$process === void 0 || (_globalThis$process = _globalThis$process.NODE_ENV) === null || _globalThis$process === void 0 ? void 0 : _globalThis$process.toLowerCase()) !== "test",
2848 warn: function warn(msg) {
2849 if (this.verbose) {
2850 var _globalThis$console, _globalThis$console$w;
2851 globalThis === null || globalThis === void 0 || (_globalThis$console = globalThis.console) === null || _globalThis$console === void 0 || (_globalThis$console$w = _globalThis$console.warn) === null || _globalThis$console$w === void 0 || _globalThis$console$w.call(_globalThis$console, msg);
2852 }
2853 }
2854 };
2855
2856 var es_error_cause = {};
2857
2858 var functionApply;
2859 var hasRequiredFunctionApply;
2860
2861 function requireFunctionApply () {
2862 if (hasRequiredFunctionApply) return functionApply;
2863 hasRequiredFunctionApply = 1;
2864 var NATIVE_BIND = requireFunctionBindNative();
2865
2866 var FunctionPrototype = Function.prototype;
2867 var apply = FunctionPrototype.apply;
2868 var call = FunctionPrototype.call;
2869
2870 // eslint-disable-next-line es/no-reflect -- safe
2871 functionApply = typeof Reflect == 'object' && Reflect.apply || (NATIVE_BIND ? call.bind(apply) : function () {
2872 return call.apply(apply, arguments);
2873 });
2874 return functionApply;
2875 }
2876
2877 var functionUncurryThisAccessor;
2878 var hasRequiredFunctionUncurryThisAccessor;
2879
2880 function requireFunctionUncurryThisAccessor () {
2881 if (hasRequiredFunctionUncurryThisAccessor) return functionUncurryThisAccessor;
2882 hasRequiredFunctionUncurryThisAccessor = 1;
2883 var uncurryThis = requireFunctionUncurryThis();
2884 var aCallable = requireACallable();
2885
2886 functionUncurryThisAccessor = function (object, key, method) {
2887 try {
2888 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
2889 return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object, key)[method]));
2890 } catch (error) { /* empty */ }
2891 };
2892 return functionUncurryThisAccessor;
2893 }
2894
2895 var isPossiblePrototype;
2896 var hasRequiredIsPossiblePrototype;
2897
2898 function requireIsPossiblePrototype () {
2899 if (hasRequiredIsPossiblePrototype) return isPossiblePrototype;
2900 hasRequiredIsPossiblePrototype = 1;
2901 var isObject = requireIsObject();
2902
2903 isPossiblePrototype = function (argument) {
2904 return isObject(argument) || argument === null;
2905 };
2906 return isPossiblePrototype;
2907 }
2908
2909 var aPossiblePrototype;
2910 var hasRequiredAPossiblePrototype;
2911
2912 function requireAPossiblePrototype () {
2913 if (hasRequiredAPossiblePrototype) return aPossiblePrototype;
2914 hasRequiredAPossiblePrototype = 1;
2915 var isPossiblePrototype = requireIsPossiblePrototype();
2916
2917 var $String = String;
2918 var $TypeError = TypeError;
2919
2920 aPossiblePrototype = function (argument) {
2921 if (isPossiblePrototype(argument)) return argument;
2922 throw new $TypeError("Can't set " + $String(argument) + ' as a prototype');
2923 };
2924 return aPossiblePrototype;
2925 }
2926
2927 var objectSetPrototypeOf;
2928 var hasRequiredObjectSetPrototypeOf;
2929
2930 function requireObjectSetPrototypeOf () {
2931 if (hasRequiredObjectSetPrototypeOf) return objectSetPrototypeOf;
2932 hasRequiredObjectSetPrototypeOf = 1;
2933 /* eslint-disable no-proto -- safe */
2934 var uncurryThisAccessor = requireFunctionUncurryThisAccessor();
2935 var isObject = requireIsObject();
2936 var requireObjectCoercible = requireRequireObjectCoercible();
2937 var aPossiblePrototype = requireAPossiblePrototype();
2938
2939 // `Object.setPrototypeOf` method
2940 // https://tc39.es/ecma262/#sec-object.setprototypeof
2941 // Works with __proto__ only. Old v8 can't work with null proto objects.
2942 // eslint-disable-next-line es/no-object-setprototypeof -- safe
2943 objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () {
2944 var CORRECT_SETTER = false;
2945 var test = {};
2946 var setter;
2947 try {
2948 setter = uncurryThisAccessor(Object.prototype, '__proto__', 'set');
2949 setter(test, []);
2950 CORRECT_SETTER = test instanceof Array;
2951 } catch (error) { /* empty */ }
2952 return function setPrototypeOf(O, proto) {
2953 requireObjectCoercible(O);
2954 aPossiblePrototype(proto);
2955 if (!isObject(O)) return O;
2956 if (CORRECT_SETTER) setter(O, proto);
2957 else O.__proto__ = proto;
2958 return O;
2959 };
2960 }() : undefined);
2961 return objectSetPrototypeOf;
2962 }
2963
2964 var proxyAccessor;
2965 var hasRequiredProxyAccessor;
2966
2967 function requireProxyAccessor () {
2968 if (hasRequiredProxyAccessor) return proxyAccessor;
2969 hasRequiredProxyAccessor = 1;
2970 var defineProperty = requireObjectDefineProperty().f;
2971
2972 proxyAccessor = function (Target, Source, key) {
2973 key in Target || defineProperty(Target, key, {
2974 configurable: true,
2975 get: function () { return Source[key]; },
2976 set: function (it) { Source[key] = it; }
2977 });
2978 };
2979 return proxyAccessor;
2980 }
2981
2982 var inheritIfRequired;
2983 var hasRequiredInheritIfRequired;
2984
2985 function requireInheritIfRequired () {
2986 if (hasRequiredInheritIfRequired) return inheritIfRequired;
2987 hasRequiredInheritIfRequired = 1;
2988 var isCallable = requireIsCallable();
2989 var isObject = requireIsObject();
2990 var setPrototypeOf = requireObjectSetPrototypeOf();
2991
2992 // makes subclassing work correct for wrapped built-ins
2993 inheritIfRequired = function ($this, dummy, Wrapper) {
2994 var NewTarget, NewTargetPrototype;
2995 if (
2996 // it can work only with native `setPrototypeOf`
2997 setPrototypeOf &&
2998 // we haven't completely correct pre-ES6 way for getting `new.target`, so use this
2999 isCallable(NewTarget = dummy.constructor) &&
3000 NewTarget !== Wrapper &&
3001 isObject(NewTargetPrototype = NewTarget.prototype) &&
3002 NewTargetPrototype !== Wrapper.prototype
3003 ) setPrototypeOf($this, NewTargetPrototype);
3004 return $this;
3005 };
3006 return inheritIfRequired;
3007 }
3008
3009 var toString;
3010 var hasRequiredToString;
3011
3012 function requireToString () {
3013 if (hasRequiredToString) return toString;
3014 hasRequiredToString = 1;
3015 var classof = requireClassof();
3016
3017 var $String = String;
3018
3019 toString = function (argument) {
3020 if (classof(argument) === 'Symbol') throw new TypeError('Cannot convert a Symbol value to a string');
3021 return $String(argument);
3022 };
3023 return toString;
3024 }
3025
3026 var normalizeStringArgument;
3027 var hasRequiredNormalizeStringArgument;
3028
3029 function requireNormalizeStringArgument () {
3030 if (hasRequiredNormalizeStringArgument) return normalizeStringArgument;
3031 hasRequiredNormalizeStringArgument = 1;
3032 var toString = requireToString();
3033
3034 normalizeStringArgument = function (argument, $default) {
3035 return argument === undefined ? arguments.length < 2 ? '' : $default : toString(argument);
3036 };
3037 return normalizeStringArgument;
3038 }
3039
3040 var installErrorCause;
3041 var hasRequiredInstallErrorCause;
3042
3043 function requireInstallErrorCause () {
3044 if (hasRequiredInstallErrorCause) return installErrorCause;
3045 hasRequiredInstallErrorCause = 1;
3046 var isObject = requireIsObject();
3047 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
3048
3049 // `InstallErrorCause` abstract operation
3050 // https://tc39.es/proposal-error-cause/#sec-errorobjects-install-error-cause
3051 installErrorCause = function (O, options) {
3052 if (isObject(options) && 'cause' in options) {
3053 createNonEnumerableProperty(O, 'cause', options.cause);
3054 }
3055 };
3056 return installErrorCause;
3057 }
3058
3059 var errorStackClear;
3060 var hasRequiredErrorStackClear;
3061
3062 function requireErrorStackClear () {
3063 if (hasRequiredErrorStackClear) return errorStackClear;
3064 hasRequiredErrorStackClear = 1;
3065 var uncurryThis = requireFunctionUncurryThis();
3066
3067 var $Error = Error;
3068 var replace = uncurryThis(''.replace);
3069
3070 var TEST = (function (arg) { return String(new $Error(arg).stack); })('zxcasd');
3071 // eslint-disable-next-line redos/no-vulnerable, sonarjs/slow-regex -- safe
3072 var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/;
3073 var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST);
3074
3075 errorStackClear = function (stack, dropEntries) {
3076 if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) {
3077 while (dropEntries--) stack = replace(stack, V8_OR_CHAKRA_STACK_ENTRY, '');
3078 } return stack;
3079 };
3080 return errorStackClear;
3081 }
3082
3083 var errorStackInstallable;
3084 var hasRequiredErrorStackInstallable;
3085
3086 function requireErrorStackInstallable () {
3087 if (hasRequiredErrorStackInstallable) return errorStackInstallable;
3088 hasRequiredErrorStackInstallable = 1;
3089 var fails = requireFails();
3090 var createPropertyDescriptor = requireCreatePropertyDescriptor();
3091
3092 errorStackInstallable = !fails(function () {
3093 var error = new Error('a');
3094 if (!('stack' in error)) return true;
3095 // eslint-disable-next-line es/no-object-defineproperty -- safe
3096 Object.defineProperty(error, 'stack', createPropertyDescriptor(1, 7));
3097 return error.stack !== 7;
3098 });
3099 return errorStackInstallable;
3100 }
3101
3102 var errorStackInstall;
3103 var hasRequiredErrorStackInstall;
3104
3105 function requireErrorStackInstall () {
3106 if (hasRequiredErrorStackInstall) return errorStackInstall;
3107 hasRequiredErrorStackInstall = 1;
3108 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
3109 var clearErrorStack = requireErrorStackClear();
3110 var ERROR_STACK_INSTALLABLE = requireErrorStackInstallable();
3111
3112 // non-standard V8
3113 var captureStackTrace = Error.captureStackTrace;
3114
3115 errorStackInstall = function (error, C, stack, dropEntries) {
3116 if (ERROR_STACK_INSTALLABLE) {
3117 if (captureStackTrace) captureStackTrace(error, C);
3118 else createNonEnumerableProperty(error, 'stack', clearErrorStack(stack, dropEntries));
3119 }
3120 };
3121 return errorStackInstall;
3122 }
3123
3124 var wrapErrorConstructorWithCause;
3125 var hasRequiredWrapErrorConstructorWithCause;
3126
3127 function requireWrapErrorConstructorWithCause () {
3128 if (hasRequiredWrapErrorConstructorWithCause) return wrapErrorConstructorWithCause;
3129 hasRequiredWrapErrorConstructorWithCause = 1;
3130 var getBuiltIn = requireGetBuiltIn();
3131 var hasOwn = requireHasOwnProperty();
3132 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
3133 var isPrototypeOf = requireObjectIsPrototypeOf();
3134 var setPrototypeOf = requireObjectSetPrototypeOf();
3135 var copyConstructorProperties = requireCopyConstructorProperties();
3136 var proxyAccessor = requireProxyAccessor();
3137 var inheritIfRequired = requireInheritIfRequired();
3138 var normalizeStringArgument = requireNormalizeStringArgument();
3139 var installErrorCause = requireInstallErrorCause();
3140 var installErrorStack = requireErrorStackInstall();
3141 var DESCRIPTORS = requireDescriptors();
3142 var IS_PURE = requireIsPure();
3143
3144 wrapErrorConstructorWithCause = function (FULL_NAME, wrapper, FORCED, IS_AGGREGATE_ERROR) {
3145 var STACK_TRACE_LIMIT = 'stackTraceLimit';
3146 var OPTIONS_POSITION = IS_AGGREGATE_ERROR ? 2 : 1;
3147 var path = FULL_NAME.split('.');
3148 var ERROR_NAME = path[path.length - 1];
3149 var OriginalError = getBuiltIn.apply(null, path);
3150
3151 if (!OriginalError) return;
3152
3153 var OriginalErrorPrototype = OriginalError.prototype;
3154
3155 // V8 9.3- bug https://bugs.chromium.org/p/v8/issues/detail?id=12006
3156 if (!IS_PURE && hasOwn(OriginalErrorPrototype, 'cause')) delete OriginalErrorPrototype.cause;
3157
3158 if (!FORCED) return OriginalError;
3159
3160 var BaseError = getBuiltIn('Error');
3161
3162 var WrappedError = wrapper(function (a, b) {
3163 var message = normalizeStringArgument(IS_AGGREGATE_ERROR ? b : a, undefined);
3164 var result = IS_AGGREGATE_ERROR ? new OriginalError(a) : new OriginalError();
3165 if (message !== undefined) createNonEnumerableProperty(result, 'message', message);
3166 installErrorStack(result, WrappedError, result.stack, 2);
3167 if (this && isPrototypeOf(OriginalErrorPrototype, this)) inheritIfRequired(result, this, WrappedError);
3168 if (arguments.length > OPTIONS_POSITION) installErrorCause(result, arguments[OPTIONS_POSITION]);
3169 return result;
3170 });
3171
3172 WrappedError.prototype = OriginalErrorPrototype;
3173
3174 if (ERROR_NAME !== 'Error') {
3175 if (setPrototypeOf) setPrototypeOf(WrappedError, BaseError);
3176 else copyConstructorProperties(WrappedError, BaseError, { name: true });
3177 } else if (DESCRIPTORS && STACK_TRACE_LIMIT in OriginalError) {
3178 proxyAccessor(WrappedError, OriginalError, STACK_TRACE_LIMIT);
3179 proxyAccessor(WrappedError, OriginalError, 'prepareStackTrace');
3180 }
3181
3182 copyConstructorProperties(WrappedError, OriginalError);
3183
3184 if (!IS_PURE) try {
3185 // Safari 13- bug: WebAssembly errors does not have a proper `.name`
3186 if (OriginalErrorPrototype.name !== ERROR_NAME) {
3187 createNonEnumerableProperty(OriginalErrorPrototype, 'name', ERROR_NAME);
3188 }
3189 OriginalErrorPrototype.constructor = WrappedError;
3190 } catch (error) { /* empty */ }
3191
3192 return WrappedError;
3193 };
3194 return wrapErrorConstructorWithCause;
3195 }
3196
3197 var hasRequiredEs_error_cause;
3198
3199 function requireEs_error_cause () {
3200 if (hasRequiredEs_error_cause) return es_error_cause;
3201 hasRequiredEs_error_cause = 1;
3202 /* eslint-disable no-unused-vars -- required for functions `.length` */
3203 var $ = require_export();
3204 var globalThis = requireGlobalThis();
3205 var apply = requireFunctionApply();
3206 var wrapErrorConstructorWithCause = requireWrapErrorConstructorWithCause();
3207
3208 var WEB_ASSEMBLY = 'WebAssembly';
3209 var WebAssembly = globalThis[WEB_ASSEMBLY];
3210
3211 // eslint-disable-next-line es/no-error-cause -- feature detection
3212 var FORCED = new Error('e', { cause: 7 }).cause !== 7;
3213
3214 var exportGlobalErrorCauseWrapper = function (ERROR_NAME, wrapper) {
3215 var O = {};
3216 O[ERROR_NAME] = wrapErrorConstructorWithCause(ERROR_NAME, wrapper, FORCED);
3217 $({ global: true, constructor: true, arity: 1, forced: FORCED }, O);
3218 };
3219
3220 var exportWebAssemblyErrorCauseWrapper = function (ERROR_NAME, wrapper) {
3221 if (WebAssembly && WebAssembly[ERROR_NAME]) {
3222 var O = {};
3223 O[ERROR_NAME] = wrapErrorConstructorWithCause(WEB_ASSEMBLY + '.' + ERROR_NAME, wrapper, FORCED);
3224 $({ target: WEB_ASSEMBLY, stat: true, constructor: true, arity: 1, forced: FORCED }, O);
3225 }
3226 };
3227
3228 // https://tc39.es/ecma262/#sec-nativeerror
3229 exportGlobalErrorCauseWrapper('Error', function (init) {
3230 return function Error(message) { return apply(init, this, arguments); };
3231 });
3232 exportGlobalErrorCauseWrapper('EvalError', function (init) {
3233 return function EvalError(message) { return apply(init, this, arguments); };
3234 });
3235 exportGlobalErrorCauseWrapper('RangeError', function (init) {
3236 return function RangeError(message) { return apply(init, this, arguments); };
3237 });
3238 exportGlobalErrorCauseWrapper('ReferenceError', function (init) {
3239 return function ReferenceError(message) { return apply(init, this, arguments); };
3240 });
3241 exportGlobalErrorCauseWrapper('SyntaxError', function (init) {
3242 return function SyntaxError(message) { return apply(init, this, arguments); };
3243 });
3244 exportGlobalErrorCauseWrapper('TypeError', function (init) {
3245 return function TypeError(message) { return apply(init, this, arguments); };
3246 });
3247 exportGlobalErrorCauseWrapper('URIError', function (init) {
3248 return function URIError(message) { return apply(init, this, arguments); };
3249 });
3250 exportWebAssemblyErrorCauseWrapper('CompileError', function (init) {
3251 return function CompileError(message) { return apply(init, this, arguments); };
3252 });
3253 exportWebAssemblyErrorCauseWrapper('LinkError', function (init) {
3254 return function LinkError(message) { return apply(init, this, arguments); };
3255 });
3256 exportWebAssemblyErrorCauseWrapper('RuntimeError', function (init) {
3257 return function RuntimeError(message) { return apply(init, this, arguments); };
3258 });
3259 return es_error_cause;
3260 }
3261
3262 requireEs_error_cause();
3263
3264 var es_array_push = {};
3265
3266 var isArray;
3267 var hasRequiredIsArray;
3268
3269 function requireIsArray () {
3270 if (hasRequiredIsArray) return isArray;
3271 hasRequiredIsArray = 1;
3272 var classof = requireClassofRaw();
3273
3274 // `IsArray` abstract operation
3275 // https://tc39.es/ecma262/#sec-isarray
3276 // eslint-disable-next-line es/no-array-isarray -- safe
3277 isArray = Array.isArray || function isArray(argument) {
3278 return classof(argument) === 'Array';
3279 };
3280 return isArray;
3281 }
3282
3283 var arraySetLength;
3284 var hasRequiredArraySetLength;
3285
3286 function requireArraySetLength () {
3287 if (hasRequiredArraySetLength) return arraySetLength;
3288 hasRequiredArraySetLength = 1;
3289 var DESCRIPTORS = requireDescriptors();
3290 var isArray = requireIsArray();
3291
3292 var $TypeError = TypeError;
3293 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
3294 var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
3295
3296 // Safari < 13 does not throw an error in this case
3297 var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS && !function () {
3298 // makes no sense without proper strict mode support
3299 if (this !== undefined) return true;
3300 try {
3301 // eslint-disable-next-line es/no-object-defineproperty -- safe
3302 Object.defineProperty([], 'length', { writable: false }).length = 1;
3303 } catch (error) {
3304 return error instanceof TypeError;
3305 }
3306 }();
3307
3308 arraySetLength = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) {
3309 if (isArray(O) && !getOwnPropertyDescriptor(O, 'length').writable) {
3310 throw new $TypeError('Cannot set read only .length');
3311 } return O.length = length;
3312 } : function (O, length) {
3313 return O.length = length;
3314 };
3315 return arraySetLength;
3316 }
3317
3318 var doesNotExceedSafeInteger;
3319 var hasRequiredDoesNotExceedSafeInteger;
3320
3321 function requireDoesNotExceedSafeInteger () {
3322 if (hasRequiredDoesNotExceedSafeInteger) return doesNotExceedSafeInteger;
3323 hasRequiredDoesNotExceedSafeInteger = 1;
3324 var $TypeError = TypeError;
3325 var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991
3326
3327 doesNotExceedSafeInteger = function (it) {
3328 if (it > MAX_SAFE_INTEGER) throw $TypeError('Maximum allowed index exceeded');
3329 return it;
3330 };
3331 return doesNotExceedSafeInteger;
3332 }
3333
3334 var hasRequiredEs_array_push;
3335
3336 function requireEs_array_push () {
3337 if (hasRequiredEs_array_push) return es_array_push;
3338 hasRequiredEs_array_push = 1;
3339 var $ = require_export();
3340 var toObject = requireToObject();
3341 var lengthOfArrayLike = requireLengthOfArrayLike();
3342 var setArrayLength = requireArraySetLength();
3343 var doesNotExceedSafeInteger = requireDoesNotExceedSafeInteger();
3344 var fails = requireFails();
3345
3346 var INCORRECT_TO_LENGTH = fails(function () {
3347 return [].push.call({ length: 0x100000000 }, 1) !== 4294967297;
3348 });
3349
3350 // V8 <= 121 and Safari <= 15.4; FF < 23 throws InternalError
3351 // https://bugs.chromium.org/p/v8/issues/detail?id=12681
3352 var properErrorOnNonWritableLength = function () {
3353 try {
3354 // eslint-disable-next-line es/no-object-defineproperty -- safe
3355 Object.defineProperty([], 'length', { writable: false }).push();
3356 } catch (error) {
3357 return error instanceof TypeError;
3358 }
3359 };
3360
3361 var FORCED = INCORRECT_TO_LENGTH || !properErrorOnNonWritableLength();
3362
3363 // `Array.prototype.push` method
3364 // https://tc39.es/ecma262/#sec-array.prototype.push
3365 $({ target: 'Array', proto: true, arity: 1, forced: FORCED }, {
3366 // eslint-disable-next-line no-unused-vars -- required for `.length`
3367 push: function push(item) {
3368 var O = toObject(this);
3369 var len = lengthOfArrayLike(O);
3370 var argCount = arguments.length;
3371 doesNotExceedSafeInteger(len + argCount);
3372 for (var i = 0; i < argCount; i++) {
3373 O[len] = arguments[i];
3374 len++;
3375 }
3376 setArrayLength(O, len);
3377 return len;
3378 }
3379 });
3380 return es_array_push;
3381 }
3382
3383 requireEs_array_push();
3384
3385 var esnext_iterator_every = {};
3386
3387 var es_iterator_every = {};
3388
3389 var hasRequiredEs_iterator_every;
3390
3391 function requireEs_iterator_every () {
3392 if (hasRequiredEs_iterator_every) return es_iterator_every;
3393 hasRequiredEs_iterator_every = 1;
3394 var $ = require_export();
3395 var iterate = requireIterate();
3396 var aCallable = requireACallable();
3397 var anObject = requireAnObject();
3398 var getIteratorDirect = requireGetIteratorDirect();
3399
3400 // `Iterator.prototype.every` method
3401 // https://tc39.es/ecma262/#sec-iterator.prototype.every
3402 $({ target: 'Iterator', proto: true, real: true }, {
3403 every: function every(predicate) {
3404 anObject(this);
3405 aCallable(predicate);
3406 var record = getIteratorDirect(this);
3407 var counter = 0;
3408 return !iterate(record, function (value, stop) {
3409 if (!predicate(value, counter++)) return stop();
3410 }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
3411 }
3412 });
3413 return es_iterator_every;
3414 }
3415
3416 var hasRequiredEsnext_iterator_every;
3417
3418 function requireEsnext_iterator_every () {
3419 if (hasRequiredEsnext_iterator_every) return esnext_iterator_every;
3420 hasRequiredEsnext_iterator_every = 1;
3421 // TODO: Remove from `core-js@4`
3422 requireEs_iterator_every();
3423 return esnext_iterator_every;
3424 }
3425
3426 requireEsnext_iterator_every();
3427
3428 var esnext_iterator_some = {};
3429
3430 var es_iterator_some = {};
3431
3432 var hasRequiredEs_iterator_some;
3433
3434 function requireEs_iterator_some () {
3435 if (hasRequiredEs_iterator_some) return es_iterator_some;
3436 hasRequiredEs_iterator_some = 1;
3437 var $ = require_export();
3438 var iterate = requireIterate();
3439 var aCallable = requireACallable();
3440 var anObject = requireAnObject();
3441 var getIteratorDirect = requireGetIteratorDirect();
3442
3443 // `Iterator.prototype.some` method
3444 // https://tc39.es/ecma262/#sec-iterator.prototype.some
3445 $({ target: 'Iterator', proto: true, real: true }, {
3446 some: function some(predicate) {
3447 anObject(this);
3448 aCallable(predicate);
3449 var record = getIteratorDirect(this);
3450 var counter = 0;
3451 return iterate(record, function (value, stop) {
3452 if (predicate(value, counter++)) return stop();
3453 }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
3454 }
3455 });
3456 return es_iterator_some;
3457 }
3458
3459 var hasRequiredEsnext_iterator_some;
3460
3461 function requireEsnext_iterator_some () {
3462 if (hasRequiredEsnext_iterator_some) return esnext_iterator_some;
3463 hasRequiredEsnext_iterator_some = 1;
3464 // TODO: Remove from `core-js@4`
3465 requireEs_iterator_some();
3466 return esnext_iterator_some;
3467 }
3468
3469 requireEsnext_iterator_some();
3470
3471 var esnext_set_difference_v2 = {};
3472
3473 var es_set_difference_v2 = {};
3474
3475 var setHelpers;
3476 var hasRequiredSetHelpers;
3477
3478 function requireSetHelpers () {
3479 if (hasRequiredSetHelpers) return setHelpers;
3480 hasRequiredSetHelpers = 1;
3481 var uncurryThis = requireFunctionUncurryThis();
3482
3483 // eslint-disable-next-line es/no-set -- safe
3484 var SetPrototype = Set.prototype;
3485
3486 setHelpers = {
3487 // eslint-disable-next-line es/no-set -- safe
3488 Set: Set,
3489 add: uncurryThis(SetPrototype.add),
3490 has: uncurryThis(SetPrototype.has),
3491 remove: uncurryThis(SetPrototype['delete']),
3492 proto: SetPrototype
3493 };
3494 return setHelpers;
3495 }
3496
3497 var aSet;
3498 var hasRequiredASet;
3499
3500 function requireASet () {
3501 if (hasRequiredASet) return aSet;
3502 hasRequiredASet = 1;
3503 var has = requireSetHelpers().has;
3504
3505 // Perform ? RequireInternalSlot(M, [[SetData]])
3506 aSet = function (it) {
3507 has(it);
3508 return it;
3509 };
3510 return aSet;
3511 }
3512
3513 var iterateSimple;
3514 var hasRequiredIterateSimple;
3515
3516 function requireIterateSimple () {
3517 if (hasRequiredIterateSimple) return iterateSimple;
3518 hasRequiredIterateSimple = 1;
3519 var call = requireFunctionCall();
3520
3521 iterateSimple = function (record, fn, ITERATOR_INSTEAD_OF_RECORD) {
3522 var iterator = ITERATOR_INSTEAD_OF_RECORD ? record : record.iterator;
3523 var next = record.next;
3524 var step, result;
3525 while (!(step = call(next, iterator)).done) {
3526 result = fn(step.value);
3527 if (result !== undefined) return result;
3528 }
3529 };
3530 return iterateSimple;
3531 }
3532
3533 var setIterate;
3534 var hasRequiredSetIterate;
3535
3536 function requireSetIterate () {
3537 if (hasRequiredSetIterate) return setIterate;
3538 hasRequiredSetIterate = 1;
3539 var uncurryThis = requireFunctionUncurryThis();
3540 var iterateSimple = requireIterateSimple();
3541 var SetHelpers = requireSetHelpers();
3542
3543 var Set = SetHelpers.Set;
3544 var SetPrototype = SetHelpers.proto;
3545 var forEach = uncurryThis(SetPrototype.forEach);
3546 var keys = uncurryThis(SetPrototype.keys);
3547 var next = keys(new Set()).next;
3548
3549 setIterate = function (set, fn, interruptible) {
3550 return interruptible ? iterateSimple({ iterator: keys(set), next: next }, fn) : forEach(set, fn);
3551 };
3552 return setIterate;
3553 }
3554
3555 var setClone;
3556 var hasRequiredSetClone;
3557
3558 function requireSetClone () {
3559 if (hasRequiredSetClone) return setClone;
3560 hasRequiredSetClone = 1;
3561 var SetHelpers = requireSetHelpers();
3562 var iterate = requireSetIterate();
3563
3564 var Set = SetHelpers.Set;
3565 var add = SetHelpers.add;
3566
3567 setClone = function (set) {
3568 var result = new Set();
3569 iterate(set, function (it) {
3570 add(result, it);
3571 });
3572 return result;
3573 };
3574 return setClone;
3575 }
3576
3577 var setSize;
3578 var hasRequiredSetSize;
3579
3580 function requireSetSize () {
3581 if (hasRequiredSetSize) return setSize;
3582 hasRequiredSetSize = 1;
3583 var uncurryThisAccessor = requireFunctionUncurryThisAccessor();
3584 var SetHelpers = requireSetHelpers();
3585
3586 setSize = uncurryThisAccessor(SetHelpers.proto, 'size', 'get') || function (set) {
3587 return set.size;
3588 };
3589 return setSize;
3590 }
3591
3592 var getSetRecord;
3593 var hasRequiredGetSetRecord;
3594
3595 function requireGetSetRecord () {
3596 if (hasRequiredGetSetRecord) return getSetRecord;
3597 hasRequiredGetSetRecord = 1;
3598 var aCallable = requireACallable();
3599 var anObject = requireAnObject();
3600 var call = requireFunctionCall();
3601 var toIntegerOrInfinity = requireToIntegerOrInfinity();
3602 var getIteratorDirect = requireGetIteratorDirect();
3603
3604 var INVALID_SIZE = 'Invalid size';
3605 var $RangeError = RangeError;
3606 var $TypeError = TypeError;
3607 var max = Math.max;
3608
3609 var SetRecord = function (set, intSize) {
3610 this.set = set;
3611 this.size = max(intSize, 0);
3612 this.has = aCallable(set.has);
3613 this.keys = aCallable(set.keys);
3614 };
3615
3616 SetRecord.prototype = {
3617 getIterator: function () {
3618 return getIteratorDirect(anObject(call(this.keys, this.set)));
3619 },
3620 includes: function (it) {
3621 return call(this.has, this.set, it);
3622 }
3623 };
3624
3625 // `GetSetRecord` abstract operation
3626 // https://tc39.es/proposal-set-methods/#sec-getsetrecord
3627 getSetRecord = function (obj) {
3628 anObject(obj);
3629 var numSize = +obj.size;
3630 // NOTE: If size is undefined, then numSize will be NaN
3631 // eslint-disable-next-line no-self-compare -- NaN check
3632 if (numSize !== numSize) throw new $TypeError(INVALID_SIZE);
3633 var intSize = toIntegerOrInfinity(numSize);
3634 if (intSize < 0) throw new $RangeError(INVALID_SIZE);
3635 return new SetRecord(obj, intSize);
3636 };
3637 return getSetRecord;
3638 }
3639
3640 var setDifference;
3641 var hasRequiredSetDifference;
3642
3643 function requireSetDifference () {
3644 if (hasRequiredSetDifference) return setDifference;
3645 hasRequiredSetDifference = 1;
3646 var aSet = requireASet();
3647 var SetHelpers = requireSetHelpers();
3648 var clone = requireSetClone();
3649 var size = requireSetSize();
3650 var getSetRecord = requireGetSetRecord();
3651 var iterateSet = requireSetIterate();
3652 var iterateSimple = requireIterateSimple();
3653
3654 var has = SetHelpers.has;
3655 var remove = SetHelpers.remove;
3656
3657 // `Set.prototype.difference` method
3658 // https://github.com/tc39/proposal-set-methods
3659 setDifference = function difference(other) {
3660 var O = aSet(this);
3661 var otherRec = getSetRecord(other);
3662 var result = clone(O);
3663 if (size(O) <= otherRec.size) iterateSet(O, function (e) {
3664 if (otherRec.includes(e)) remove(result, e);
3665 });
3666 else iterateSimple(otherRec.getIterator(), function (e) {
3667 if (has(O, e)) remove(result, e);
3668 });
3669 return result;
3670 };
3671 return setDifference;
3672 }
3673
3674 var setMethodAcceptSetLike;
3675 var hasRequiredSetMethodAcceptSetLike;
3676
3677 function requireSetMethodAcceptSetLike () {
3678 if (hasRequiredSetMethodAcceptSetLike) return setMethodAcceptSetLike;
3679 hasRequiredSetMethodAcceptSetLike = 1;
3680 var getBuiltIn = requireGetBuiltIn();
3681
3682 var createSetLike = function (size) {
3683 return {
3684 size: size,
3685 has: function () {
3686 return false;
3687 },
3688 keys: function () {
3689 return {
3690 next: function () {
3691 return { done: true };
3692 }
3693 };
3694 }
3695 };
3696 };
3697
3698 setMethodAcceptSetLike = function (name) {
3699 var Set = getBuiltIn('Set');
3700 try {
3701 new Set()[name](createSetLike(0));
3702 try {
3703 // late spec change, early WebKit ~ Safari 17.0 beta implementation does not pass it
3704 // https://github.com/tc39/proposal-set-methods/pull/88
3705 new Set()[name](createSetLike(-1));
3706 return false;
3707 } catch (error2) {
3708 return true;
3709 }
3710 } catch (error) {
3711 return false;
3712 }
3713 };
3714 return setMethodAcceptSetLike;
3715 }
3716
3717 var hasRequiredEs_set_difference_v2;
3718
3719 function requireEs_set_difference_v2 () {
3720 if (hasRequiredEs_set_difference_v2) return es_set_difference_v2;
3721 hasRequiredEs_set_difference_v2 = 1;
3722 var $ = require_export();
3723 var difference = requireSetDifference();
3724 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3725
3726 // `Set.prototype.difference` method
3727 // https://tc39.es/ecma262/#sec-set.prototype.difference
3728 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('difference') }, {
3729 difference: difference
3730 });
3731 return es_set_difference_v2;
3732 }
3733
3734 var hasRequiredEsnext_set_difference_v2;
3735
3736 function requireEsnext_set_difference_v2 () {
3737 if (hasRequiredEsnext_set_difference_v2) return esnext_set_difference_v2;
3738 hasRequiredEsnext_set_difference_v2 = 1;
3739 // TODO: Remove from `core-js@4`
3740 requireEs_set_difference_v2();
3741 return esnext_set_difference_v2;
3742 }
3743
3744 requireEsnext_set_difference_v2();
3745
3746 var esnext_set_intersection_v2 = {};
3747
3748 var es_set_intersection_v2 = {};
3749
3750 var setIntersection;
3751 var hasRequiredSetIntersection;
3752
3753 function requireSetIntersection () {
3754 if (hasRequiredSetIntersection) return setIntersection;
3755 hasRequiredSetIntersection = 1;
3756 var aSet = requireASet();
3757 var SetHelpers = requireSetHelpers();
3758 var size = requireSetSize();
3759 var getSetRecord = requireGetSetRecord();
3760 var iterateSet = requireSetIterate();
3761 var iterateSimple = requireIterateSimple();
3762
3763 var Set = SetHelpers.Set;
3764 var add = SetHelpers.add;
3765 var has = SetHelpers.has;
3766
3767 // `Set.prototype.intersection` method
3768 // https://github.com/tc39/proposal-set-methods
3769 setIntersection = function intersection(other) {
3770 var O = aSet(this);
3771 var otherRec = getSetRecord(other);
3772 var result = new Set();
3773
3774 if (size(O) > otherRec.size) {
3775 iterateSimple(otherRec.getIterator(), function (e) {
3776 if (has(O, e)) add(result, e);
3777 });
3778 } else {
3779 iterateSet(O, function (e) {
3780 if (otherRec.includes(e)) add(result, e);
3781 });
3782 }
3783
3784 return result;
3785 };
3786 return setIntersection;
3787 }
3788
3789 var hasRequiredEs_set_intersection_v2;
3790
3791 function requireEs_set_intersection_v2 () {
3792 if (hasRequiredEs_set_intersection_v2) return es_set_intersection_v2;
3793 hasRequiredEs_set_intersection_v2 = 1;
3794 var $ = require_export();
3795 var fails = requireFails();
3796 var intersection = requireSetIntersection();
3797 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3798
3799 var INCORRECT = !setMethodAcceptSetLike('intersection') || fails(function () {
3800 // eslint-disable-next-line es/no-array-from, es/no-set -- testing
3801 return String(Array.from(new Set([1, 2, 3]).intersection(new Set([3, 2])))) !== '3,2';
3802 });
3803
3804 // `Set.prototype.intersection` method
3805 // https://tc39.es/ecma262/#sec-set.prototype.intersection
3806 $({ target: 'Set', proto: true, real: true, forced: INCORRECT }, {
3807 intersection: intersection
3808 });
3809 return es_set_intersection_v2;
3810 }
3811
3812 var hasRequiredEsnext_set_intersection_v2;
3813
3814 function requireEsnext_set_intersection_v2 () {
3815 if (hasRequiredEsnext_set_intersection_v2) return esnext_set_intersection_v2;
3816 hasRequiredEsnext_set_intersection_v2 = 1;
3817 // TODO: Remove from `core-js@4`
3818 requireEs_set_intersection_v2();
3819 return esnext_set_intersection_v2;
3820 }
3821
3822 requireEsnext_set_intersection_v2();
3823
3824 var esnext_set_isDisjointFrom_v2 = {};
3825
3826 var es_set_isDisjointFrom_v2 = {};
3827
3828 var setIsDisjointFrom;
3829 var hasRequiredSetIsDisjointFrom;
3830
3831 function requireSetIsDisjointFrom () {
3832 if (hasRequiredSetIsDisjointFrom) return setIsDisjointFrom;
3833 hasRequiredSetIsDisjointFrom = 1;
3834 var aSet = requireASet();
3835 var has = requireSetHelpers().has;
3836 var size = requireSetSize();
3837 var getSetRecord = requireGetSetRecord();
3838 var iterateSet = requireSetIterate();
3839 var iterateSimple = requireIterateSimple();
3840 var iteratorClose = requireIteratorClose();
3841
3842 // `Set.prototype.isDisjointFrom` method
3843 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isDisjointFrom
3844 setIsDisjointFrom = function isDisjointFrom(other) {
3845 var O = aSet(this);
3846 var otherRec = getSetRecord(other);
3847 if (size(O) <= otherRec.size) return iterateSet(O, function (e) {
3848 if (otherRec.includes(e)) return false;
3849 }, true) !== false;
3850 var iterator = otherRec.getIterator();
3851 return iterateSimple(iterator, function (e) {
3852 if (has(O, e)) return iteratorClose(iterator, 'normal', false);
3853 }) !== false;
3854 };
3855 return setIsDisjointFrom;
3856 }
3857
3858 var hasRequiredEs_set_isDisjointFrom_v2;
3859
3860 function requireEs_set_isDisjointFrom_v2 () {
3861 if (hasRequiredEs_set_isDisjointFrom_v2) return es_set_isDisjointFrom_v2;
3862 hasRequiredEs_set_isDisjointFrom_v2 = 1;
3863 var $ = require_export();
3864 var isDisjointFrom = requireSetIsDisjointFrom();
3865 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3866
3867 // `Set.prototype.isDisjointFrom` method
3868 // https://tc39.es/ecma262/#sec-set.prototype.isdisjointfrom
3869 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isDisjointFrom') }, {
3870 isDisjointFrom: isDisjointFrom
3871 });
3872 return es_set_isDisjointFrom_v2;
3873 }
3874
3875 var hasRequiredEsnext_set_isDisjointFrom_v2;
3876
3877 function requireEsnext_set_isDisjointFrom_v2 () {
3878 if (hasRequiredEsnext_set_isDisjointFrom_v2) return esnext_set_isDisjointFrom_v2;
3879 hasRequiredEsnext_set_isDisjointFrom_v2 = 1;
3880 // TODO: Remove from `core-js@4`
3881 requireEs_set_isDisjointFrom_v2();
3882 return esnext_set_isDisjointFrom_v2;
3883 }
3884
3885 requireEsnext_set_isDisjointFrom_v2();
3886
3887 var esnext_set_isSubsetOf_v2 = {};
3888
3889 var es_set_isSubsetOf_v2 = {};
3890
3891 var setIsSubsetOf;
3892 var hasRequiredSetIsSubsetOf;
3893
3894 function requireSetIsSubsetOf () {
3895 if (hasRequiredSetIsSubsetOf) return setIsSubsetOf;
3896 hasRequiredSetIsSubsetOf = 1;
3897 var aSet = requireASet();
3898 var size = requireSetSize();
3899 var iterate = requireSetIterate();
3900 var getSetRecord = requireGetSetRecord();
3901
3902 // `Set.prototype.isSubsetOf` method
3903 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSubsetOf
3904 setIsSubsetOf = function isSubsetOf(other) {
3905 var O = aSet(this);
3906 var otherRec = getSetRecord(other);
3907 if (size(O) > otherRec.size) return false;
3908 return iterate(O, function (e) {
3909 if (!otherRec.includes(e)) return false;
3910 }, true) !== false;
3911 };
3912 return setIsSubsetOf;
3913 }
3914
3915 var hasRequiredEs_set_isSubsetOf_v2;
3916
3917 function requireEs_set_isSubsetOf_v2 () {
3918 if (hasRequiredEs_set_isSubsetOf_v2) return es_set_isSubsetOf_v2;
3919 hasRequiredEs_set_isSubsetOf_v2 = 1;
3920 var $ = require_export();
3921 var isSubsetOf = requireSetIsSubsetOf();
3922 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3923
3924 // `Set.prototype.isSubsetOf` method
3925 // https://tc39.es/ecma262/#sec-set.prototype.issubsetof
3926 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isSubsetOf') }, {
3927 isSubsetOf: isSubsetOf
3928 });
3929 return es_set_isSubsetOf_v2;
3930 }
3931
3932 var hasRequiredEsnext_set_isSubsetOf_v2;
3933
3934 function requireEsnext_set_isSubsetOf_v2 () {
3935 if (hasRequiredEsnext_set_isSubsetOf_v2) return esnext_set_isSubsetOf_v2;
3936 hasRequiredEsnext_set_isSubsetOf_v2 = 1;
3937 // TODO: Remove from `core-js@4`
3938 requireEs_set_isSubsetOf_v2();
3939 return esnext_set_isSubsetOf_v2;
3940 }
3941
3942 requireEsnext_set_isSubsetOf_v2();
3943
3944 var esnext_set_isSupersetOf_v2 = {};
3945
3946 var es_set_isSupersetOf_v2 = {};
3947
3948 var setIsSupersetOf;
3949 var hasRequiredSetIsSupersetOf;
3950
3951 function requireSetIsSupersetOf () {
3952 if (hasRequiredSetIsSupersetOf) return setIsSupersetOf;
3953 hasRequiredSetIsSupersetOf = 1;
3954 var aSet = requireASet();
3955 var has = requireSetHelpers().has;
3956 var size = requireSetSize();
3957 var getSetRecord = requireGetSetRecord();
3958 var iterateSimple = requireIterateSimple();
3959 var iteratorClose = requireIteratorClose();
3960
3961 // `Set.prototype.isSupersetOf` method
3962 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSupersetOf
3963 setIsSupersetOf = function isSupersetOf(other) {
3964 var O = aSet(this);
3965 var otherRec = getSetRecord(other);
3966 if (size(O) < otherRec.size) return false;
3967 var iterator = otherRec.getIterator();
3968 return iterateSimple(iterator, function (e) {
3969 if (!has(O, e)) return iteratorClose(iterator, 'normal', false);
3970 }) !== false;
3971 };
3972 return setIsSupersetOf;
3973 }
3974
3975 var hasRequiredEs_set_isSupersetOf_v2;
3976
3977 function requireEs_set_isSupersetOf_v2 () {
3978 if (hasRequiredEs_set_isSupersetOf_v2) return es_set_isSupersetOf_v2;
3979 hasRequiredEs_set_isSupersetOf_v2 = 1;
3980 var $ = require_export();
3981 var isSupersetOf = requireSetIsSupersetOf();
3982 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
3983
3984 // `Set.prototype.isSupersetOf` method
3985 // https://tc39.es/ecma262/#sec-set.prototype.issupersetof
3986 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isSupersetOf') }, {
3987 isSupersetOf: isSupersetOf
3988 });
3989 return es_set_isSupersetOf_v2;
3990 }
3991
3992 var hasRequiredEsnext_set_isSupersetOf_v2;
3993
3994 function requireEsnext_set_isSupersetOf_v2 () {
3995 if (hasRequiredEsnext_set_isSupersetOf_v2) return esnext_set_isSupersetOf_v2;
3996 hasRequiredEsnext_set_isSupersetOf_v2 = 1;
3997 // TODO: Remove from `core-js@4`
3998 requireEs_set_isSupersetOf_v2();
3999 return esnext_set_isSupersetOf_v2;
4000 }
4001
4002 requireEsnext_set_isSupersetOf_v2();
4003
4004 var esnext_set_symmetricDifference_v2 = {};
4005
4006 var es_set_symmetricDifference_v2 = {};
4007
4008 var setSymmetricDifference;
4009 var hasRequiredSetSymmetricDifference;
4010
4011 function requireSetSymmetricDifference () {
4012 if (hasRequiredSetSymmetricDifference) return setSymmetricDifference;
4013 hasRequiredSetSymmetricDifference = 1;
4014 var aSet = requireASet();
4015 var SetHelpers = requireSetHelpers();
4016 var clone = requireSetClone();
4017 var getSetRecord = requireGetSetRecord();
4018 var iterateSimple = requireIterateSimple();
4019
4020 var add = SetHelpers.add;
4021 var has = SetHelpers.has;
4022 var remove = SetHelpers.remove;
4023
4024 // `Set.prototype.symmetricDifference` method
4025 // https://github.com/tc39/proposal-set-methods
4026 setSymmetricDifference = function symmetricDifference(other) {
4027 var O = aSet(this);
4028 var keysIter = getSetRecord(other).getIterator();
4029 var result = clone(O);
4030 iterateSimple(keysIter, function (e) {
4031 if (has(O, e)) remove(result, e);
4032 else add(result, e);
4033 });
4034 return result;
4035 };
4036 return setSymmetricDifference;
4037 }
4038
4039 var hasRequiredEs_set_symmetricDifference_v2;
4040
4041 function requireEs_set_symmetricDifference_v2 () {
4042 if (hasRequiredEs_set_symmetricDifference_v2) return es_set_symmetricDifference_v2;
4043 hasRequiredEs_set_symmetricDifference_v2 = 1;
4044 var $ = require_export();
4045 var symmetricDifference = requireSetSymmetricDifference();
4046 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
4047
4048 // `Set.prototype.symmetricDifference` method
4049 // https://tc39.es/ecma262/#sec-set.prototype.symmetricdifference
4050 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('symmetricDifference') }, {
4051 symmetricDifference: symmetricDifference
4052 });
4053 return es_set_symmetricDifference_v2;
4054 }
4055
4056 var hasRequiredEsnext_set_symmetricDifference_v2;
4057
4058 function requireEsnext_set_symmetricDifference_v2 () {
4059 if (hasRequiredEsnext_set_symmetricDifference_v2) return esnext_set_symmetricDifference_v2;
4060 hasRequiredEsnext_set_symmetricDifference_v2 = 1;
4061 // TODO: Remove from `core-js@4`
4062 requireEs_set_symmetricDifference_v2();
4063 return esnext_set_symmetricDifference_v2;
4064 }
4065
4066 requireEsnext_set_symmetricDifference_v2();
4067
4068 var esnext_set_union_v2 = {};
4069
4070 var es_set_union_v2 = {};
4071
4072 var setUnion;
4073 var hasRequiredSetUnion;
4074
4075 function requireSetUnion () {
4076 if (hasRequiredSetUnion) return setUnion;
4077 hasRequiredSetUnion = 1;
4078 var aSet = requireASet();
4079 var add = requireSetHelpers().add;
4080 var clone = requireSetClone();
4081 var getSetRecord = requireGetSetRecord();
4082 var iterateSimple = requireIterateSimple();
4083
4084 // `Set.prototype.union` method
4085 // https://github.com/tc39/proposal-set-methods
4086 setUnion = function union(other) {
4087 var O = aSet(this);
4088 var keysIter = getSetRecord(other).getIterator();
4089 var result = clone(O);
4090 iterateSimple(keysIter, function (it) {
4091 add(result, it);
4092 });
4093 return result;
4094 };
4095 return setUnion;
4096 }
4097
4098 var hasRequiredEs_set_union_v2;
4099
4100 function requireEs_set_union_v2 () {
4101 if (hasRequiredEs_set_union_v2) return es_set_union_v2;
4102 hasRequiredEs_set_union_v2 = 1;
4103 var $ = require_export();
4104 var union = requireSetUnion();
4105 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
4106
4107 // `Set.prototype.union` method
4108 // https://tc39.es/ecma262/#sec-set.prototype.union
4109 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('union') }, {
4110 union: union
4111 });
4112 return es_set_union_v2;
4113 }
4114
4115 var hasRequiredEsnext_set_union_v2;
4116
4117 function requireEsnext_set_union_v2 () {
4118 if (hasRequiredEsnext_set_union_v2) return esnext_set_union_v2;
4119 hasRequiredEsnext_set_union_v2 = 1;
4120 // TODO: Remove from `core-js@4`
4121 requireEs_set_union_v2();
4122 return esnext_set_union_v2;
4123 }
4124
4125 requireEsnext_set_union_v2();
4126
4127 var esnext_iterator_find = {};
4128
4129 var es_iterator_find = {};
4130
4131 var hasRequiredEs_iterator_find;
4132
4133 function requireEs_iterator_find () {
4134 if (hasRequiredEs_iterator_find) return es_iterator_find;
4135 hasRequiredEs_iterator_find = 1;
4136 var $ = require_export();
4137 var iterate = requireIterate();
4138 var aCallable = requireACallable();
4139 var anObject = requireAnObject();
4140 var getIteratorDirect = requireGetIteratorDirect();
4141
4142 // `Iterator.prototype.find` method
4143 // https://tc39.es/ecma262/#sec-iterator.prototype.find
4144 $({ target: 'Iterator', proto: true, real: true }, {
4145 find: function find(predicate) {
4146 anObject(this);
4147 aCallable(predicate);
4148 var record = getIteratorDirect(this);
4149 var counter = 0;
4150 return iterate(record, function (value, stop) {
4151 if (predicate(value, counter++)) return stop(value);
4152 }, { IS_RECORD: true, INTERRUPTED: true }).result;
4153 }
4154 });
4155 return es_iterator_find;
4156 }
4157
4158 var hasRequiredEsnext_iterator_find;
4159
4160 function requireEsnext_iterator_find () {
4161 if (hasRequiredEsnext_iterator_find) return esnext_iterator_find;
4162 hasRequiredEsnext_iterator_find = 1;
4163 // TODO: Remove from `core-js@4`
4164 requireEs_iterator_find();
4165 return esnext_iterator_find;
4166 }
4167
4168 requireEsnext_iterator_find();
4169
4170 class Type {
4171 // Class properties - declared here so that type inference works
4172 type;
4173 coordMeta;
4174 coordRange;
4175 /** @type {[number, number]} */
4176 range;
4177
4178 /**
4179 * @param {any} type
4180 * @param {import("./types.js").CoordMeta} coordMeta
4181 */
4182 constructor(type, coordMeta) {
4183 if (typeof type === "object") {
4184 this.coordMeta = type;
4185 }
4186 if (coordMeta) {
4187 var _coordMeta$range;
4188 this.coordMeta = coordMeta;
4189 this.coordRange = (_coordMeta$range = coordMeta.range) !== null && _coordMeta$range !== void 0 ? _coordMeta$range : coordMeta.refRange;
4190 }
4191 if (typeof type === "string") {
4192 let params = type.trim().match(/^(?<type><[a-z]+>)(\[(?<min>-?[.\d]+),\s*(?<max>-?[.\d]+)\])?$/);
4193 if (!params) {
4194 throw new TypeError(`Cannot parse ${type} as a type definition.`);
4195 }
4196 this.type = params.groups.type;
4197 let {
4198 min,
4199 max
4200 } = params.groups;
4201 if (min || max) {
4202 this.range = [+min, +max];
4203 }
4204 }
4205 }
4206
4207 /** @returns {[number, number]} */
4208 get computedRange() {
4209 if (this.range) {
4210 return this.range;
4211 }
4212 if (this.type === "<percentage>") {
4213 return this.percentageRange();
4214 } else if (this.type === "<angle>") {
4215 return [0, 360];
4216 }
4217 return null;
4218 }
4219 get unit() {
4220 if (this.type === "<percentage>") {
4221 return "%";
4222 } else if (this.type === "<angle>") {
4223 return "deg";
4224 }
4225 return "";
4226 }
4227
4228 /**
4229 * Map a number to the internal representation
4230 * @param {number} number
4231 */
4232 resolve(number) {
4233 if (this.type === "<angle>") {
4234 return number;
4235 }
4236 let fromRange = this.computedRange;
4237 let toRange = this.coordRange;
4238 if (this.type === "<percentage>") {
4239 var _toRange;
4240 (_toRange = toRange) !== null && _toRange !== void 0 ? _toRange : toRange = this.percentageRange();
4241 }
4242 return mapRange(fromRange, toRange, number);
4243 }
4244
4245 /**
4246 * Serialize a number from the internal representation to a string
4247 * @param {number} number
4248 * @param {number} [precision]
4249 */
4250 serialize(number, precision) {
4251 let toRange = this.type === "<percentage>" ? this.percentageRange(100) : this.computedRange;
4252 let unit = this.unit;
4253 number = mapRange(this.coordRange, toRange, number);
4254 return serializeNumber(number, {
4255 unit,
4256 precision
4257 });
4258 }
4259 toString() {
4260 let ret = this.type;
4261 if (this.range) {
4262 let [min = "", max = ""] = this.range;
4263 ret += `[${min},${max}]`;
4264 }
4265 return ret;
4266 }
4267
4268 /**
4269 * Returns a percentage range for values of this type
4270 * @param {number} scale
4271 * @returns {[number, number]}
4272 */
4273 percentageRange(scale = 1) {
4274 let range;
4275 if (this.coordMeta && this.coordMeta.range || this.coordRange && this.coordRange[0] >= 0) {
4276 range = [0, 1];
4277 } else {
4278 range = [-1, 1];
4279 }
4280 return [range[0] * scale, range[1] * scale];
4281 }
4282 static get(type, coordMeta) {
4283 if (isInstance(type, this)) {
4284 return type;
4285 }
4286 return new this(type, coordMeta);
4287 }
4288 }
4289
4290 /** @import { ColorSpace, Coords } from "./types.js" */
4291
4292 // Type re-exports
4293 /** @typedef {import("./types.js").Format} FormatInterface */
4294
4295 /**
4296 * @internal
4297 * Used to index {@link FormatInterface Format} objects and store an instance.
4298 * Not meant for external use
4299 */
4300 const instance = Symbol("instance");
4301
4302 /**
4303 * Remove the first element of an array type
4304 * @template {any[]} T
4305 * @typedef {T extends [any, ...infer R] ? R : T[number][]} RemoveFirstElement
4306 */
4307
4308 /**
4309 * @class Format
4310 * @implements {Omit<FormatInterface, "coords" | "serializeCoords">}
4311 * Class to hold a color serialization format
4312 */
4313 class Format {
4314 // Class properties - declared here so that type inference works
4315 type;
4316 name;
4317 spaceCoords;
4318 /** @type {Type[][]} */
4319 coords;
4320 /** @type {string | undefined} */
4321 id;
4322 /** @type {boolean | undefined} */
4323 alpha;
4324
4325 /**
4326 * @param {FormatInterface} format
4327 * @param {ColorSpace} space
4328 */
4329 constructor(format, space = format.space) {
4330 format[instance] = this;
4331 this.type = "function";
4332 this.name = "color";
4333 Object.assign(this, format);
4334 this.space = space;
4335 if (this.type === "custom") {
4336 // Nothing else to do here
4337 return;
4338 }
4339 this.spaceCoords = Object.values(space.coords);
4340 if (!this.coords) {
4341 // @ts-expect-error Strings are converted to the correct type later
4342 this.coords = this.spaceCoords.map(coordMeta => {
4343 let ret = ["<number>", "<percentage>"];
4344 if (coordMeta.type === "angle") {
4345 ret.push("<angle>");
4346 }
4347 return ret;
4348 });
4349 }
4350 this.coords = this.coords.map(/** @param {string | string[] | Type[]} types */(types, i) => {
4351 let coordMeta = this.spaceCoords[i];
4352 if (typeof types === "string") {
4353 types = types.trim().split(/\s*\|\s*/);
4354 }
4355 return types.map(type => Type.get(type, coordMeta));
4356 });
4357 }
4358
4359 /**
4360 * @param {Coords} coords
4361 * @param {number} precision
4362 * @param {Type[]} types
4363 */
4364 serializeCoords(coords, precision, types) {
4365 types = coords.map((_, i) => {
4366 var _types$i, _types;
4367 return Type.get((_types$i = (_types = types) === null || _types === void 0 ? void 0 : _types[i]) !== null && _types$i !== void 0 ? _types$i : this.coords[i][0], this.spaceCoords[i]);
4368 });
4369 return coords.map((c, i) => types[i].serialize(c, precision));
4370 }
4371
4372 /**
4373 * Validates the coordinates of a color against a format's coord grammar and
4374 * maps the coordinates to the range or refRange of the coordinates.
4375 * @param {Coords} coords
4376 * @param {[string, string, string]} types
4377 */
4378 coerceCoords(coords, types) {
4379 return Object.entries(this.space.coords).map(([id, coordMeta], i) => {
4380 let arg = coords[i];
4381 if (isNone(arg) || isNaN(arg)) {
4382 // Nothing to do here
4383 return arg;
4384 }
4385
4386 // Find grammar alternative that matches the provided type
4387 // Non-strict equals is intentional because we are comparing w/ string objects
4388 let providedType = types[i];
4389 let type = this.coords[i].find(c => c.type == providedType);
4390
4391 // Check that each coord conforms to its grammar
4392 if (!type) {
4393 var _ref, _arg;
4394 // Type does not exist in the grammar, throw
4395 let coordName = coordMeta.name || id;
4396 throw new TypeError(`${(_ref = providedType !== null && providedType !== void 0 ? providedType : /** @type {any} */(_arg = arg) === null || _arg === void 0 ? void 0 : _arg.raw) !== null && _ref !== void 0 ? _ref : arg} not allowed for ${coordName} in ${this.name}()`);
4397 }
4398 arg = type.resolve(arg);
4399 if (type.range) {
4400 // Adjust type to include range
4401 types[i] = type.toString();
4402 }
4403 return arg;
4404 });
4405 }
4406
4407 /**
4408 * @returns {boolean | Required<FormatInterface>["serialize"]}
4409 */
4410 canSerialize() {
4411 return this.type === "function" || /** @type {any} */this.serialize;
4412 }
4413
4414 /**
4415 * @param {string} str
4416 * @returns {(import("./types.js").ColorConstructor) | undefined | null}
4417 */
4418 parse(str) {
4419 return null;
4420 }
4421
4422 /**
4423 * @param {Format | FormatInterface} format
4424 * @param {RemoveFirstElement<ConstructorParameters<typeof Format>>} args
4425 * @returns {Format}
4426 */
4427 static get(format, ...args) {
4428 if (!format || isInstance(format, this)) {
4429 return /** @type {Format} */format;
4430 }
4431 if (format[instance]) {
4432 return format[instance];
4433 }
4434 return new Format(format, ...args);
4435 }
4436 }
4437
4438 // Type re-exports
4439 /** @typedef {import("./types.js").White} White */
4440
4441 /** @type {Record<string, White>} */
4442 // prettier-ignore
4443 const WHITES = {
4444 // for compatibility, the four-digit chromaticity-derived ones everyone else uses
4445 D50: [0.3457 / 0.3585, 1.00000, (1.0 - 0.3457 - 0.3585) / 0.3585],
4446 D65: [0.3127 / 0.3290, 1.00000, (1.0 - 0.3127 - 0.3290) / 0.3290]
4447 };
4448
4449 /**
4450 *
4451 * @param {string | White} name
4452 * @returns {White}
4453 */
4454 function getWhite(name) {
4455 if (Array.isArray(name)) {
4456 return name;
4457 }
4458 return WHITES[name];
4459 }
4460
4461 /**
4462 * Adapt XYZ from white point W1 to W2
4463 * @param {White | string} W1
4464 * @param {White | string} W2
4465 * @param {[number, number, number]} XYZ
4466 * @param {{ method?: string | undefined }} options
4467 * @returns {[number, number, number]}
4468 */
4469 function adapt$2(W1, W2, XYZ, options = {}) {
4470 W1 = getWhite(W1);
4471 W2 = getWhite(W2);
4472 if (!W1 || !W2) {
4473 throw new TypeError(`Missing white point to convert ${!W1 ? "from" : ""}${!W1 && !W2 ? "/" : ""}${!W2 ? "to" : ""}`);
4474 }
4475 if (W1 === W2) {
4476 // Same whitepoints, no conversion needed
4477 return XYZ;
4478 }
4479 let env = {
4480 W1,
4481 W2,
4482 XYZ,
4483 options
4484 };
4485 hooks.run("chromatic-adaptation-start", env);
4486 if (!env.M) {
4487 if (env.W1 === WHITES.D65 && env.W2 === WHITES.D50) {
4488 // prettier-ignore
4489 env.M = [[1.0479297925449969, 0.022946870601609652, -0.05019226628920524], [0.02962780877005599, 0.9904344267538799, -0.017073799063418826], [-0.009243040646204504, 0.015055191490298152, 0.7518742814281371]];
4490 } else if (env.W1 === WHITES.D50 && env.W2 === WHITES.D65) {
4491 // prettier-ignore
4492 env.M = [[0.955473421488075, -0.02309845494876471, 0.06325924320057072], [-0.0283697093338637, 1.0099953980813041, 0.021041441191917323], [0.012314014864481998, -0.020507649298898964, 1.330365926242124]];
4493 }
4494 }
4495 hooks.run("chromatic-adaptation-end", env);
4496 if (env.M) {
4497 return multiply_v3_m3x3(env.XYZ, env.M);
4498 } else {
4499 throw new TypeError("Only Bradford CAT with white points D50 and D65 supported for now.");
4500 }
4501 }
4502
4503 /** @import { ColorConstructor } from "./types.js" */
4504
4505 // Type re-exports
4506 /** @typedef {import("./types.js").ArgumentMeta} ArgumentMeta */
4507 /** @typedef {import("./types.js").ParseFunctionReturn} ParseFunctionReturn */
4508 /** @typedef {import("./types.js").ParseOptions} ParseOptions */
4509
4510 /**
4511 * Convert a CSS Color string to a color object
4512 * @param {string} str
4513 * @param {ParseOptions} [options]
4514 * @returns {ColorConstructor}
4515 */
4516 function parse(str, options) {
4517 var _String, _env$options$parseMet;
4518 let env = {
4519 str: (_String = String(str)) === null || _String === void 0 ? void 0 : _String.trim(),
4520 options
4521 };
4522 hooks.run("parse-start", env);
4523 if (env.color) {
4524 return env.color;
4525 }
4526 env.parsed = parseFunction(env.str);
4527 let ret;
4528 let meta = env.options ? (_env$options$parseMet = env.options.parseMeta) !== null && _env$options$parseMet !== void 0 ? _env$options$parseMet : env.options.meta : null;
4529 if (env.parsed) {
4530 // Is a functional syntax
4531 let name = env.parsed.name;
4532 let format;
4533 let space;
4534 let coords = env.parsed.args;
4535 let types = coords.map((c, i) => {
4536 var _env$parsed$argMeta$i;
4537 return (_env$parsed$argMeta$i = env.parsed.argMeta[i]) === null || _env$parsed$argMeta$i === void 0 ? void 0 : _env$parsed$argMeta$i.type;
4538 });
4539 if (name === "color") {
4540 // color() function
4541 let id = coords.shift();
4542 types.shift();
4543 // Check against both <dashed-ident> and <ident> versions
4544 let alternateId = id.startsWith("--") ? id.substring(2) : `--${id}`;
4545 let ids = [id, alternateId];
4546 format = ColorSpace.findFormat({
4547 name,
4548 id: ids,
4549 type: "function"
4550 });
4551 if (!format) {
4552 var _didYouMean;
4553 // Not found
4554 let didYouMean;
4555 let registryId = id in ColorSpace.registry ? id : alternateId;
4556 if (registryId in ColorSpace.registry) {
4557 var _ColorSpace$registry$;
4558 // Used color space id instead of color() id, these are often different
4559 let cssId = (_ColorSpace$registry$ = ColorSpace.registry[registryId].formats) === null || _ColorSpace$registry$ === void 0 || (_ColorSpace$registry$ = _ColorSpace$registry$.color) === null || _ColorSpace$registry$ === void 0 ? void 0 : _ColorSpace$registry$.id;
4560 if (cssId) {
4561 let altColor = str.replace("color(" + id, "color(" + cssId);
4562 didYouMean = `Did you mean ${altColor}?`;
4563 }
4564 }
4565 throw new TypeError(`Cannot parse ${env.str}. ` + ((_didYouMean = didYouMean) !== null && _didYouMean !== void 0 ? _didYouMean : "Missing a plugin?"));
4566 }
4567 space = format.space;
4568 if (format.id.startsWith("--") && !id.startsWith("--")) {
4569 defaults.warn(`${space.name} is a non-standard space and not currently supported in the CSS spec. ` + `Use prefixed color(${format.id}) instead of color(${id}).`);
4570 }
4571 if (id.startsWith("--") && !format.id.startsWith("--")) {
4572 defaults.warn(`${space.name} is a standard space and supported in the CSS spec. ` + `Use color(${format.id}) instead of prefixed color(${id}).`);
4573 }
4574 } else {
4575 format = ColorSpace.findFormat({
4576 name,
4577 type: "function"
4578 });
4579 space = format.space;
4580 }
4581 if (meta) {
4582 Object.assign(meta, {
4583 format,
4584 formatId: format.name,
4585 types,
4586 commas: env.parsed.commas
4587 });
4588 }
4589 let alpha = 1;
4590 if (env.parsed.lastAlpha) {
4591 alpha = env.parsed.args.pop();
4592 if (meta) {
4593 meta.alphaType = types.pop();
4594 }
4595 }
4596 let coordCount = format.coords.length;
4597 if (coords.length !== coordCount) {
4598 throw new TypeError(`Expected ${coordCount} coordinates for ${space.id} in ${env.str}), got ${coords.length}`);
4599 }
4600 coords = format.coerceCoords(coords, types);
4601 ret = {
4602 spaceId: space.id,
4603 coords,
4604 alpha
4605 };
4606 } else {
4607 // Custom, colorspace-specific format
4608 spaceloop: for (let space of ColorSpace.all) {
4609 for (let formatId in space.formats) {
4610 let format = space.formats[formatId];
4611 if (format.type !== "custom") {
4612 continue;
4613 }
4614 if (format.test && !format.test(env.str)) {
4615 continue;
4616 }
4617
4618 // Convert to Format object
4619 let formatObject = space.getFormat(format);
4620 let color = formatObject.parse(env.str);
4621 if (color) {
4622 if (meta) {
4623 Object.assign(meta, {
4624 format: formatObject,
4625 formatId
4626 });
4627 }
4628 ret = color;
4629 break spaceloop;
4630 }
4631 }
4632 }
4633 }
4634 if (!ret) {
4635 // If we're here, we couldn't parse
4636 throw new TypeError(`Could not parse ${str} as a color. Missing a plugin?`);
4637 }
4638
4639 // Clamp alpha to [0, 1]
4640 ret.alpha = isNone(ret.alpha) ? ret.alpha : ret.alpha === undefined ? 1 : clamp(0, ret.alpha, 1);
4641 return ret;
4642 }
4643
4644 /**
4645 * Units and multiplication factors for the internally stored numbers
4646 */
4647 const units = {
4648 "%": 0.01,
4649 deg: 1,
4650 grad: 0.9,
4651 rad: 180 / Math.PI,
4652 turn: 360
4653 };
4654 const regex = {
4655 // Need to list calc(NaN) explicitly as otherwise its ending paren would terminate the function call
4656 function: /^([a-z]+)\(((?:calc\(NaN\)|.)+?)\)$/i,
4657 number: /^([-+]?(?:[0-9]*\.)?[0-9]+(e[-+]?[0-9]+)?)$/i,
4658 unitValue: RegExp(`(${Object.keys(units).join("|")})$`),
4659 // NOTE The -+ are not just for prefix, but also for idents, and e+N notation!
4660 singleArgument: /\/?\s*(none|NaN|calc\(NaN\)|[-+\w.]+(?:%|deg|g?rad|turn)?)/g
4661 };
4662
4663 /**
4664 * Parse a single function argument
4665 * @param {string} rawArg
4666 * @returns {{value: number, meta: ArgumentMeta}}
4667 */
4668 function parseArgument(rawArg) {
4669 var _rawArg$match;
4670 /** @type {Partial<ArgumentMeta>} */
4671 let meta = {};
4672 let unit = (_rawArg$match = rawArg.match(regex.unitValue)) === null || _rawArg$match === void 0 ? void 0 : _rawArg$match[0];
4673 /** @type {string | number} */
4674 let value = meta.raw = rawArg;
4675 if (unit) {
4676 // It’s a dimension token
4677 meta.type = unit === "%" ? "<percentage>" : "<angle>";
4678 meta.unit = unit;
4679 meta.unitless = Number(value.slice(0, -unit.length)); // unitless number
4680
4681 value = meta.unitless * units[unit];
4682 } else if (regex.number.test(value)) {
4683 // It's a number
4684 // Convert numerical args to numbers
4685 value = Number(value);
4686 meta.type = "<number>";
4687 } else if (value === "none") {
4688 value = null;
4689 } else if (value === "NaN" || value === "calc(NaN)") {
4690 value = NaN;
4691 meta.type = "<number>";
4692 } else {
4693 meta.type = "<ident>";
4694 }
4695 return {
4696 value: (/** @type {number} */value),
4697 meta: (/** @type {ArgumentMeta} */meta)
4698 };
4699 }
4700
4701 /**
4702 * Parse a CSS function, regardless of its name and arguments
4703 * @param {string} str String to parse
4704 * @return {ParseFunctionReturn | void}
4705 */
4706 function parseFunction(str) {
4707 if (!str) {
4708 return;
4709 }
4710 str = str.trim();
4711 let parts = str.match(regex.function);
4712 if (parts) {
4713 // It is a function, parse args
4714 let args = [];
4715 let argMeta = [];
4716 let lastAlpha = false;
4717 let name = parts[1].toLowerCase();
4718 let separators = parts[2].replace(regex.singleArgument, ($0, rawArg) => {
4719 let {
4720 value,
4721 meta
4722 } = parseArgument(rawArg);
4723 if (
4724 // If there's a slash here, it's modern syntax
4725 $0.startsWith("/") ||
4726 // If there's still elements to process after there's already 3 in `args` (and the we're not dealing with "color()"), it's likely to be a legacy color like "hsl(0, 0%, 0%, 0.5)"
4727 name !== "color" && args.length === 3) {
4728 // It's alpha
4729 lastAlpha = true;
4730 }
4731 args.push(value);
4732 argMeta.push(meta);
4733 return "";
4734 });
4735 return {
4736 name,
4737 args,
4738 argMeta,
4739 lastAlpha,
4740 commas: separators.includes(","),
4741 rawName: parts[1],
4742 rawArgs: parts[2]
4743 };
4744 }
4745 }
4746
4747 /** @import { ColorTypes, ParseOptions as GetColorOptions, PlainColorObject } from "./types.js" */
4748
4749 /**
4750 * Resolves a color reference (object or string) to a plain color object
4751 * @overload
4752 * @param {ColorTypes} color
4753 * @param {GetColorOptions} [options]
4754 * @returns {PlainColorObject}
4755 */
4756 /**
4757 * @overload
4758 * @param {ColorTypes[]} color
4759 * @param {GetColorOptions} [options]
4760 * @returns {PlainColorObject[]}
4761 */
4762 function getColor(color, options) {
4763 if (Array.isArray(color)) {
4764 return color.map(c => getColor(c, options));
4765 }
4766 if (!color) {
4767 throw new TypeError("Empty color reference");
4768 }
4769 if (isString(color)) {
4770 color = parse(color, options);
4771 }
4772
4773 // Object fixup
4774 let space = color.space || color.spaceId;
4775 if (typeof space === "string") {
4776 // Convert string id to color space object
4777 color.space = ColorSpace.get(space);
4778 }
4779 if (color.alpha === undefined) {
4780 color.alpha = 1;
4781 }
4782 return color;
4783 }
4784
4785 const ε$7 = 0.000075;
4786
4787 /**
4788 * Class to represent a color space
4789 */
4790 class ColorSpace {
4791 constructor(options) {
4792 var _options$displaySpace, _options$coords, _ref, _options$white, _options$formats, _this$formats$color;
4793 this.id = options.id;
4794 this.name = options.name;
4795 this.base = options.base ? ColorSpace.get(options.base) : null;
4796 this.aliases = options.aliases;
4797 this.displaySpaces = (_options$displaySpace = options.displaySpaces) === null || _options$displaySpace === void 0 ? void 0 : _options$displaySpace.map(space => ColorSpace.get(space));
4798
4799 // This space's ancestors, closest first (immediate base → root), excluding the space itself.
4800 this.bases = [];
4801 for (let base = this.base; base; base = base.base) {
4802 this.bases.push(base);
4803 }
4804 if (options.rgbGamut) {
4805 this.rgbGamut = options.rgbGamut;
4806 }
4807 if (options.linearGamut) {
4808 this.linearGamut = options.linearGamut;
4809 }
4810 if (this.base) {
4811 this.fromBase = options.fromBase;
4812 this.toBase = options.toBase;
4813 }
4814
4815 // Coordinate metadata
4816
4817 let coords = (_options$coords = options.coords) !== null && _options$coords !== void 0 ? _options$coords : this.base.coords;
4818 for (let name in coords) {
4819 if (!("name" in coords[name])) {
4820 coords[name].name = name;
4821 }
4822 }
4823 this.coords = coords;
4824
4825 // White point
4826
4827 let white = (_ref = (_options$white = options.white) !== null && _options$white !== void 0 ? _options$white : this.base.white) !== null && _ref !== void 0 ? _ref : "D65";
4828 this.white = getWhite(white);
4829
4830 // Sort out formats
4831
4832 this.formats = (_options$formats = options.formats) !== null && _options$formats !== void 0 ? _options$formats : {};
4833 for (let name in this.formats) {
4834 let format = this.formats[name];
4835 format.type || (format.type = "function");
4836 format.name || (format.name = name);
4837 }
4838 if (!((_this$formats$color = this.formats.color) !== null && _this$formats$color !== void 0 && _this$formats$color.id)) {
4839 var _this$formats$color2;
4840 this.formats.color = {
4841 ...((_this$formats$color2 = this.formats.color) !== null && _this$formats$color2 !== void 0 ? _this$formats$color2 : {}),
4842 id: options.cssId || this.id
4843 };
4844 }
4845
4846 // Gamut space
4847
4848 if (options.gamutSpace) {
4849 // Gamut space explicitly specified
4850 this.gamutSpace = options.gamutSpace === "self" ? this : ColorSpace.get(options.gamutSpace);
4851 } else {
4852 // No gamut space specified, calculate a sensible default
4853 if (this.isPolar) {
4854 // Do not check gamut through polar coordinates
4855 this.gamutSpace = this.base;
4856 } else {
4857 this.gamutSpace = this;
4858 }
4859 }
4860
4861 // Optimize inGamut for unbounded spaces
4862 if (this.gamutSpace.isUnbounded) {
4863 this.inGamut = (coords, options) => {
4864 return true;
4865 };
4866 }
4867
4868 // Other stuff
4869 this.referred = options.referred;
4870
4871 // Compute ancestors and store them, since they will never change
4872 Object.defineProperty(this, "path", {
4873 value: getPath(this).reverse(),
4874 writable: false,
4875 enumerable: true,
4876 configurable: true
4877 });
4878 hooks.run("colorspace-init-end", this);
4879 }
4880 inGamut(coords, {
4881 epsilon = ε$7
4882 } = {}) {
4883 if (!this.equals(this.gamutSpace)) {
4884 coords = this.to(this.gamutSpace, coords);
4885 return this.gamutSpace.inGamut(coords, {
4886 epsilon
4887 });
4888 }
4889 let coordMeta = Object.values(this.coords);
4890 return coords.every((c, i) => {
4891 let meta = coordMeta[i];
4892 if (meta.type !== "angle" && meta.range) {
4893 if (isNone(c)) {
4894 // NaN is always in gamut
4895 return true;
4896 }
4897 let [min, max] = meta.range;
4898 return (min === undefined || c >= min - epsilon) && (max === undefined || c <= max + epsilon);
4899 }
4900 return true;
4901 });
4902 }
4903 get isUnbounded() {
4904 return Object.values(this.coords).every(coord => !("range" in coord));
4905 }
4906 get cssId() {
4907 var _this$formats;
4908 return ((_this$formats = this.formats) === null || _this$formats === void 0 || (_this$formats = _this$formats.color) === null || _this$formats === void 0 ? void 0 : _this$formats.id) || this.id;
4909 }
4910 get isPolar() {
4911 for (let id in this.coords) {
4912 if (this.coords[id].type === "angle") {
4913 return true;
4914 }
4915 }
4916 return false;
4917 }
4918
4919 /**
4920 * Lookup a format in this color space
4921 * @param {string | object | Format} format - Format id if string. If object, it's converted to a `Format` object and returned.
4922 * @returns {Format}
4923 */
4924 getFormat(format) {
4925 if (!format) {
4926 return null;
4927 }
4928 if (format === "default") {
4929 format = Object.values(this.formats)[0];
4930 } else if (typeof format === "string") {
4931 format = this.formats[format];
4932 }
4933 let ret = Format.get(format, this);
4934 if (ret !== format && format.name in this.formats) {
4935 // Update the format we have on file so we can find it more quickly next time
4936 this.formats[format.name] = ret;
4937 }
4938 return ret;
4939 }
4940
4941 /**
4942 * Check if this color space is the same as another color space reference.
4943 * Allows proxying color space objects and comparing color spaces with ids.
4944 * @param {string | ColorSpace} space ColorSpace object or id to compare to
4945 * @returns {boolean}
4946 */
4947 equals(space) {
4948 if (!space) {
4949 return false;
4950 }
4951 return this === space || this.id === space || this.id === space.id;
4952 }
4953 to(space, coords) {
4954 if (arguments.length === 1) {
4955 const color = getColor(space);
4956 [space, coords] = [color.space, color.coords];
4957 }
4958 space = ColorSpace.get(space);
4959 if (this.equals(space)) {
4960 // Same space, no change needed
4961 return coords;
4962 }
4963
4964 // Convert NaN to 0, which seems to be valid in every coordinate of every color space
4965 coords = coords.map(c => isNone(c) ? 0 : c);
4966
4967 // Find connection space = lowest common ancestor in the base tree
4968 let myPath = this.path;
4969 let otherPath = space.path;
4970 let connectionSpace, connectionSpaceIndex;
4971 for (let i = 0; i < myPath.length; i++) {
4972 if (myPath[i].equals(otherPath[i])) {
4973 connectionSpace = myPath[i];
4974 connectionSpaceIndex = i;
4975 } else {
4976 break;
4977 }
4978 }
4979 if (!connectionSpace) {
4980 // This should never happen
4981 throw new Error(`Cannot convert between color spaces ${this} and ${space}: no connection space was found`);
4982 }
4983
4984 // Go up from current space to connection space
4985 for (let i = myPath.length - 1; i > connectionSpaceIndex; i--) {
4986 coords = myPath[i].toBase(coords);
4987 }
4988
4989 // Go down from connection space to target space
4990 for (let i = connectionSpaceIndex + 1; i < otherPath.length; i++) {
4991 coords = otherPath[i].fromBase(coords);
4992 }
4993 return coords;
4994 }
4995 from(space, coords) {
4996 if (arguments.length === 1) {
4997 const color = getColor(space);
4998 [space, coords] = [color.space, color.coords];
4999 }
5000 space = ColorSpace.get(space);
5001 return space.to(this, coords);
5002 }
5003 toString() {
5004 return `${this.name} (${this.id})`;
5005 }
5006 getMinCoords() {
5007 let ret = [];
5008 for (let id in this.coords) {
5009 var _range$min;
5010 let meta = this.coords[id];
5011 let range = meta.range || meta.refRange;
5012 ret.push((_range$min = range === null || range === void 0 ? void 0 : range.min) !== null && _range$min !== void 0 ? _range$min : 0);
5013 }
5014 return ret;
5015 }
5016 static registry = {};
5017
5018 // Returns array of unique color spaces
5019 static get all() {
5020 return [...new Set(Object.values(ColorSpace.registry))];
5021 }
5022 static register(id, space) {
5023 if (arguments.length === 1) {
5024 space = arguments[0];
5025 id = space.id;
5026 }
5027 space = this.get(space);
5028 if (this.registry[id] && this.registry[id] !== space) {
5029 throw new Error(`Duplicate color space registration: '${id}'`);
5030 }
5031 this.registry[id] = space;
5032
5033 // Register aliases when called without an explicit ID.
5034 if (arguments.length === 1 && space.aliases) {
5035 for (let alias of space.aliases) {
5036 this.register(alias, space);
5037 }
5038 }
5039 return space;
5040 }
5041
5042 /**
5043 * Lookup ColorSpace object by name
5044 * @param {ColorSpace | string} name
5045 */
5046 static get(space, ...alternatives) {
5047 if (!space || isInstance(space, this)) {
5048 return space;
5049 }
5050 let argType = type(space);
5051 if (argType === "string") {
5052 // It's a color space id
5053 let ret = ColorSpace.registry[space.toLowerCase()];
5054 if (!ret) {
5055 throw new TypeError(`No color space found with id = "${space}"`);
5056 }
5057 return ret;
5058 }
5059 if (alternatives.length) {
5060 return ColorSpace.get(...alternatives);
5061 }
5062 throw new TypeError(`${space} is not a valid color space`);
5063 }
5064
5065 /**
5066 * Look up all color spaces for a format that matches certain criteria
5067 * @param {object | string} filters
5068 * @param {Array<ColorSpace>} [spaces=ColorSpace.all]
5069 * @returns {Format | null}
5070 */
5071 static findFormat(filters, spaces = ColorSpace.all) {
5072 if (!filters) {
5073 return null;
5074 }
5075 if (typeof filters === "string") {
5076 filters = {
5077 name: filters
5078 };
5079 }
5080 for (let space of spaces) {
5081 for (let [name, format] of Object.entries(space.formats)) {
5082 var _format$name, _format$type;
5083 (_format$name = format.name) !== null && _format$name !== void 0 ? _format$name : format.name = name;
5084 (_format$type = format.type) !== null && _format$type !== void 0 ? _format$type : format.type = "function";
5085 let matches = (!filters.name || format.name === filters.name) && (!filters.type || format.type === filters.type);
5086 if (filters.id) {
5087 let ids = format.ids || [format.id];
5088 let filterIds = Array.isArray(filters.id) ? filters.id : [filters.id];
5089 matches && (matches = filterIds.some(id => ids.includes(id)));
5090 }
5091 if (matches) {
5092 let ret = Format.get(format, space);
5093 if (ret !== format) {
5094 space.formats[format.name] = ret;
5095 }
5096 return ret;
5097 }
5098 }
5099 }
5100 return null;
5101 }
5102
5103 /**
5104 * Get metadata about a coordinate of a color space
5105 *
5106 * @static
5107 * @param {Array | string} ref
5108 * @param {ColorSpace | string} [workingSpace]
5109 * @return {Object}
5110 */
5111 static resolveCoord(ref, workingSpace) {
5112 let coordType = type(ref);
5113 let space, coord;
5114 if (coordType === "string") {
5115 if (ref.includes(".")) {
5116 // Absolute coordinate
5117 [space, coord] = ref.split(".");
5118 } else {
5119 // Relative coordinate
5120 [space, coord] = [, ref];
5121 }
5122 } else if (Array.isArray(ref)) {
5123 [space, coord] = ref;
5124 } else {
5125 // Object
5126 space = ref.space;
5127 coord = ref.coordId;
5128 }
5129 space = ColorSpace.get(space);
5130 if (!space) {
5131 space = workingSpace;
5132 }
5133 if (!space) {
5134 throw new TypeError(`Cannot resolve coordinate reference ${ref}: No color space specified and relative references are not allowed here`);
5135 }
5136 coordType = type(coord);
5137 if (coordType === "number" || coordType === "string" && coord >= 0) {
5138 // Resolve numerical coord
5139 let meta = Object.entries(space.coords)[coord];
5140 if (meta) {
5141 return {
5142 space,
5143 id: meta[0],
5144 index: coord,
5145 ...meta[1]
5146 };
5147 }
5148 }
5149 space = ColorSpace.get(space);
5150 let normalizedCoord = coord.toLowerCase();
5151 let i = 0;
5152 for (let id in space.coords) {
5153 var _meta$name;
5154 let meta = space.coords[id];
5155 if (id.toLowerCase() === normalizedCoord || ((_meta$name = meta.name) === null || _meta$name === void 0 ? void 0 : _meta$name.toLowerCase()) === normalizedCoord) {
5156 return {
5157 space,
5158 id,
5159 index: i,
5160 ...meta
5161 };
5162 }
5163 i++;
5164 }
5165 throw new TypeError(`No "${coord}" coordinate found in ${space.name}. Its coordinates are: ${Object.keys(space.coords).join(", ")}`);
5166 }
5167 static DEFAULT_FORMAT = {
5168 type: "functions",
5169 name: "color"
5170 };
5171 }
5172 function getPath(space) {
5173 let ret = [space];
5174 for (let s = space; s = s.base;) {
5175 ret.push(s);
5176 }
5177 return ret;
5178 }
5179
5180 var XYZ_D65 = new ColorSpace({
5181 id: "xyz-d65",
5182 name: "XYZ D65",
5183 coords: {
5184 x: {
5185 refRange: [0, 1],
5186 name: "X"
5187 },
5188 y: {
5189 refRange: [0, 1],
5190 name: "Y"
5191 },
5192 z: {
5193 refRange: [0, 1],
5194 name: "Z"
5195 }
5196 },
5197 white: "D65",
5198 formats: {
5199 color: {
5200 ids: ["xyz-d65", "xyz"]
5201 }
5202 },
5203 aliases: ["xyz"]
5204 });
5205
5206 // Type re-exports
5207 /** @typedef {import("./types.js").RGBOptions} RGBOptions */
5208
5209 /** Convenience class for RGB color spaces */
5210 class RGBColorSpace extends ColorSpace {
5211 /**
5212 * Creates a new RGB ColorSpace.
5213 * If coords are not specified, they will use the default RGB coords.
5214 * Instead of `fromBase()` and `toBase()` functions,
5215 * you can specify to/from XYZ matrices and have `toBase()` and `fromBase()` automatically generated.
5216 * @param {RGBOptions} options
5217 */
5218 constructor(options) {
5219 var _options$referred;
5220 if (!options.coords) {
5221 options.coords = {
5222 r: {
5223 range: [0, 1],
5224 name: "Red"
5225 },
5226 g: {
5227 range: [0, 1],
5228 name: "Green"
5229 },
5230 b: {
5231 range: [0, 1],
5232 name: "Blue"
5233 }
5234 };
5235 }
5236 if (!options.base) {
5237 options.base = XYZ_D65;
5238 }
5239 if (options.toXYZ_M && options.fromXYZ_M) {
5240 var _options$toBase, _options$fromBase;
5241 (_options$toBase = options.toBase) !== null && _options$toBase !== void 0 ? _options$toBase : options.toBase = rgb => {
5242 let xyz = multiply_v3_m3x3(rgb, options.toXYZ_M);
5243 if (this.white !== this.base.white) {
5244 // Perform chromatic adaptation
5245 xyz = adapt$2(this.white, this.base.white, xyz);
5246 }
5247 return xyz;
5248 };
5249 (_options$fromBase = options.fromBase) !== null && _options$fromBase !== void 0 ? _options$fromBase : options.fromBase = xyz => {
5250 xyz = adapt$2(this.base.white, this.white, xyz);
5251 return multiply_v3_m3x3(xyz, options.fromXYZ_M);
5252 };
5253 }
5254 (_options$referred = options.referred) !== null && _options$referred !== void 0 ? _options$referred : options.referred = "display";
5255 super(options);
5256 }
5257 }
5258
5259 /** @import { ColorTypes, PlainColorObject } from "./types.js" */
5260
5261 // Type re-exports
5262 /** @typedef {import("./types.js").TryColorOptions} TryColorOptions */
5263
5264 /**
5265 * Resolves a color reference (object or string) to a plain color object, or `null` if resolution fails.
5266 * Can resolve more complex CSS colors (e.g. relative colors, `calc()`, CSS variables, `color-mix()`, etc.) through the DOM.
5267 *
5268 * @overload
5269 * @param {ColorTypes} color
5270 * @param {TryColorOptions} [options]
5271 * @returns {PlainColorObject | null}
5272 */
5273 /**
5274 * @overload
5275 * @param {ColorTypes[]} color
5276 * @param {TryColorOptions} [options]
5277 * @returns {(PlainColorObject | null)[]}
5278 */
5279 function tryColor(color, options = {}) {
5280 if (Array.isArray(color)) {
5281 return color.map(c => tryColor(c, options));
5282 }
5283 let {
5284 cssProperty = "background-color",
5285 element,
5286 ...getColorOptions
5287 } = options;
5288 let error = null;
5289 try {
5290 return getColor(color, getColorOptions);
5291 } catch (e) {
5292 error = e;
5293 }
5294 let {
5295 CSS,
5296 getComputedStyle
5297 } = globalThis;
5298 if (isString(color) && element && CSS && getComputedStyle) {
5299 // Try resolving the color using the DOM, if supported in CSS
5300 if (CSS.supports(cssProperty, color)) {
5301 let previousValue = element.style[cssProperty];
5302 if (color !== previousValue) {
5303 element.style[cssProperty] = color;
5304 }
5305 let computedColor = getComputedStyle(element).getPropertyValue(cssProperty);
5306 if (color !== previousValue) {
5307 element.style[cssProperty] = previousValue;
5308 }
5309 if (computedColor !== color) {
5310 // getComputedStyle() changed the color, try again
5311 try {
5312 return getColor(computedColor, getColorOptions);
5313 } catch (e) {
5314 error = e;
5315 }
5316 } else {
5317 // Still not resolved
5318 error = {
5319 message: "Color value is a valid CSS color, but it could not be resolved :("
5320 };
5321 }
5322 }
5323 }
5324
5325 // If we're here, we failed to resolve the color
5326 if (options.errorMeta) {
5327 options.errorMeta.error = error;
5328 }
5329 return null;
5330 }
5331
5332 /** @import { ColorTypes, Coords } from "./types.js" */
5333
5334 /**
5335 * Options for {@link getAll}
5336 * @typedef GetAllOptions
5337 * @property {string | ColorSpace | undefined} [space]
5338 * The color space to convert to. Defaults to the color's current space
5339 * @property {number | undefined} [precision]
5340 * The number of significant digits to round the coordinates to
5341 */
5342
5343 /**
5344 * Get the coordinates of a color in any color space
5345 * @overload
5346 * @param {ColorTypes} color
5347 * @param {string | ColorSpace} [options=color.space] The color space to convert to. Defaults to the color's current space
5348 * @returns {Coords} The color coordinates in the given color space
5349 */
5350 /**
5351 * @overload
5352 * @param {ColorTypes} color
5353 * @param {GetAllOptions} [options]
5354 * @returns {Coords} The color coordinates in the given color space
5355 */
5356 function getAll(color, options) {
5357 color = getColor(color);
5358 let space = ColorSpace.get(options, options === null || options === void 0 ? void 0 : options.space);
5359 let precision = options === null || options === void 0 ? void 0 : options.precision;
5360 let coords;
5361 if (!space || color.space.equals(space)) {
5362 // No conversion needed
5363 coords = color.coords.slice();
5364 } else {
5365 coords = space.from(color);
5366 }
5367 return precision === undefined ? coords : coords.map(coord => toPrecision(coord, precision));
5368 }
5369
5370 /** @import { ColorTypes, Ref } from "./types.js" */
5371
5372 /**
5373 * @param {ColorTypes} color
5374 * @param {Ref} prop
5375 * @returns {number}
5376 */
5377 function get(color, prop) {
5378 color = getColor(color);
5379 if (prop === "alpha") {
5380 var _color$alpha;
5381 return (_color$alpha = color.alpha) !== null && _color$alpha !== void 0 ? _color$alpha : 1;
5382 }
5383 let {
5384 space,
5385 index
5386 } = ColorSpace.resolveCoord(prop, color.space);
5387 let coords = getAll(color, space);
5388 return coords[index];
5389 }
5390
5391 /** @import { ColorTypes, Coords, PlainColorObject } from "./types.js" */
5392
5393 /**
5394 * Set all coordinates of a color at once, in its own color space or another.
5395 * Modifies the color in place.
5396 * @overload
5397 * @param {ColorTypes} color
5398 * @param {Coords} coords Array of coordinates
5399 * @param {number} [alpha]
5400 * @returns {PlainColorObject}
5401 */
5402 /**
5403 * @overload
5404 * @param {ColorTypes} color
5405 * @param {string | ColorSpace} space The color space of the provided coordinates.
5406 * @param {Coords} coords Array of coordinates
5407 * @param {number} [alpha]
5408 * @returns {PlainColorObject}
5409 */
5410 function setAll(color, space, coords, alpha) {
5411 color = getColor(color);
5412 if (Array.isArray(space)) {
5413 // Space is omitted
5414 [space, coords, alpha] = [color.space, space, coords];
5415 }
5416 space = ColorSpace.get(space); // Make sure we have a ColorSpace object
5417 color.coords = space === color.space ? coords.slice() : space.to(color.space, coords);
5418 if (alpha !== undefined) {
5419 color.alpha = alpha;
5420 }
5421 return color;
5422 }
5423
5424 /** @type {"color"} */
5425 setAll.returns = "color";
5426
5427 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
5428
5429 /**
5430 * Set properties and return current instance
5431 * @overload
5432 * @param {ColorTypes} color
5433 * @param {Ref} prop
5434 * @param {number | ((coord: number) => number)} value
5435 * @returns {PlainColorObject}
5436 */
5437 /**
5438 * @overload
5439 * @param {ColorTypes} color
5440 * @param {Record<string, number | ((coord: number) => number)>} props
5441 * @returns {PlainColorObject}
5442 */
5443 function set(color, prop, value) {
5444 color = getColor(color);
5445 if (arguments.length === 2 && type(arguments[1]) === "object") {
5446 // Argument is an object literal
5447 let object = arguments[1];
5448 for (let p in object) {
5449 set(color, p, object[p]);
5450 }
5451 } else {
5452 if (typeof value === "function") {
5453 value = value(get(color, prop));
5454 }
5455 if (prop === "alpha") {
5456 color.alpha = value;
5457 } else {
5458 let {
5459 space,
5460 index
5461 } = ColorSpace.resolveCoord(prop, color.space);
5462 let coords = getAll(color, space);
5463 coords[index] = value;
5464 setAll(color, space, coords);
5465 }
5466 }
5467 return color;
5468 }
5469
5470 /** @type {"color"} */
5471 set.returns = "color";
5472
5473 var XYZ_D50 = new ColorSpace({
5474 id: "xyz-d50",
5475 name: "XYZ D50",
5476 white: "D50",
5477 base: XYZ_D65,
5478 fromBase: coords => adapt$2(XYZ_D65.white, "D50", coords),
5479 toBase: coords => adapt$2("D50", XYZ_D65.white, coords)
5480 });
5481
5482 // κ * ε = 2^3 = 8
5483 const ε$6 = 216 / 24389; // 6^3/29^3 == (24/116)^3
5484 const ε3$1 = 24 / 116;
5485 const κ$4 = 24389 / 27; // 29^3/3^3
5486
5487 let white$4 = WHITES.D50;
5488 var lab = new ColorSpace({
5489 id: "lab",
5490 name: "Lab",
5491 coords: {
5492 l: {
5493 refRange: [0, 100],
5494 name: "Lightness"
5495 },
5496 a: {
5497 refRange: [-125, 125]
5498 },
5499 b: {
5500 refRange: [-125, 125]
5501 }
5502 },
5503 // Assuming XYZ is relative to D50, convert to CIE Lab
5504 // from CIE standard, which now defines these as a rational fraction
5505 white: white$4,
5506 base: XYZ_D50,
5507 // Convert D50-adapted XYX to Lab
5508 // CIE 15.3:2004 section 8.2.1.1
5509 fromBase(XYZ) {
5510 // XYZ scaled relative to reference white
5511 let xyz = XYZ.map((value, i) => value / white$4[i]);
5512 let f = xyz.map(value => value > ε$6 ? Math.cbrt(value) : (κ$4 * value + 16) / 116);
5513 let L = 116 * f[1] - 16;
5514 let a = 500 * (f[0] - f[1]);
5515 let b = 200 * (f[1] - f[2]);
5516 return [L, a, b];
5517 },
5518 // Convert Lab to D50-adapted XYZ
5519 // Same result as CIE 15.3:2004 Appendix D although the derivation is different
5520 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
5521 toBase(Lab) {
5522 // compute f, starting with the luminance-related term
5523 let [L, a, b] = Lab;
5524 let f = [];
5525 f[1] = (L + 16) / 116;
5526 f[0] = a / 500 + f[1];
5527 f[2] = f[1] - b / 200;
5528
5529 // compute xyz
5530 // prettier-ignore
5531 let xyz = [f[0] > ε3$1 ? Math.pow(f[0], 3) : (116 * f[0] - 16) / κ$4, Lab[0] > 8 ? Math.pow((Lab[0] + 16) / 116, 3) : Lab[0] / κ$4, f[2] > ε3$1 ? Math.pow(f[2], 3) : (116 * f[2] - 16) / κ$4];
5532
5533 // Compute XYZ by scaling xyz by reference white
5534 return xyz.map((value, i) => value * white$4[i]);
5535 },
5536 formats: {
5537 lab: {
5538 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
5539 }
5540 }
5541 });
5542
5543 /**
5544 * Constrain an angle to 360 degrees
5545 * @param {number} angle
5546 * @returns {number}
5547 */
5548 function constrain(angle) {
5549 if (typeof angle !== "number") {
5550 return angle;
5551 }
5552 return (angle % 360 + 360) % 360;
5553 }
5554
5555 /**
5556 * @param {"raw" | "increasing" | "decreasing" | "longer" | "shorter"} arc
5557 * @param {[number, number]} angles
5558 * @returns {[number, number]}
5559 */
5560 function adjust(arc, angles) {
5561 let [a1, a2] = angles;
5562 let none1 = isNone(a1);
5563 let none2 = isNone(a2);
5564 if (none1 && none2) {
5565 return [a1, a2];
5566 } else if (none1) {
5567 a1 = a2;
5568 } else if (none2) {
5569 a2 = a1;
5570 }
5571 if (arc === "raw") {
5572 return angles;
5573 }
5574 a1 = constrain(a1);
5575 a2 = constrain(a2);
5576 let angleDiff = a2 - a1;
5577 if (arc === "increasing") {
5578 if (angleDiff < 0) {
5579 a2 += 360;
5580 }
5581 } else if (arc === "decreasing") {
5582 if (angleDiff > 0) {
5583 a1 += 360;
5584 }
5585 } else if (arc === "longer") {
5586 if (-180 < angleDiff && angleDiff < 180) {
5587 if (angleDiff > 0) {
5588 a1 += 360;
5589 } else {
5590 a2 += 360;
5591 }
5592 }
5593 } else if (arc === "shorter") {
5594 if (angleDiff > 180) {
5595 a1 += 360;
5596 } else if (angleDiff < -180) {
5597 a2 += 360;
5598 }
5599 }
5600 return [a1, a2];
5601 }
5602
5603 var lch = new ColorSpace({
5604 id: "lch",
5605 name: "LCH",
5606 coords: {
5607 l: {
5608 refRange: [0, 100],
5609 name: "Lightness"
5610 },
5611 c: {
5612 refRange: [0, 150],
5613 name: "Chroma"
5614 },
5615 h: {
5616 refRange: [0, 360],
5617 type: "angle",
5618 name: "Hue"
5619 }
5620 },
5621 base: lab,
5622 fromBase(Lab) {
5623 // These methods are used for other polar forms as well, so we can't hardcode the ε
5624 if (this.ε === undefined) {
5625 // @ts-expect-error Property 'coords' does not exist on type 'string | ColorSpace'
5626 let range = Object.values(this.base.coords)[1].refRange;
5627 let extent = range[1] - range[0];
5628 this.ε = extent / 100000;
5629 }
5630
5631 // Convert to polar form
5632 let [L, a, b] = Lab;
5633 let isAchromatic = Math.abs(a) < this.ε && Math.abs(b) < this.ε;
5634 let h = isAchromatic ? null : constrain(Math.atan2(b, a) * 180 / Math.PI);
5635 let C = isAchromatic ? 0 : Math.sqrt(a ** 2 + b ** 2);
5636 return [L, C, h];
5637 },
5638 toBase(lch) {
5639 // Convert from polar form
5640 let [L, C, h] = lch;
5641 let a = null,
5642 b = null;
5643 if (!isNone(h)) {
5644 C = C < 0 ? 0 : C; // Clamp negative Chroma
5645 a = C * Math.cos(h * Math.PI / 180);
5646 b = C * Math.sin(h * Math.PI / 180);
5647 }
5648 return [L, a, b];
5649 },
5650 formats: {
5651 lch: {
5652 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"]
5653 }
5654 }
5655 });
5656
5657 // deltaE2000 is a statistically significant improvement
5658 // and is recommended by the CIE and Idealliance
5659 // especially for color differences less than 10 deltaE76
5660 // but is wicked complicated
5661 // and many implementations have small errors!
5662 // DeltaE2000 is also discontinuous; in case this
5663 // matters to you, use deltaECMC instead.
5664
5665 const Gfactor = 25 ** 7;
5666 const π$1 = Math.PI;
5667 const r2d = 180 / π$1;
5668 const d2r$1 = π$1 / 180;
5669 function pow7(x) {
5670 // Faster than x ** 7 or Math.pow(x, 7)
5671
5672 const x2 = x * x;
5673 const x7 = x2 * x2 * x2 * x;
5674 return x7;
5675 }
5676
5677 /**
5678 * @param {import("../types.js").ColorTypes} color
5679 * @param {import("../types.js").ColorTypes} sample
5680 * @param {{ kL?: number | undefined; kC?: number | undefined; kH?: number | undefined }} options
5681 * @returns {number}
5682 */
5683 function deltaE2000 (color, sample, {
5684 kL = 1,
5685 kC = 1,
5686 kH = 1
5687 } = {}) {
5688 [color, sample] = getColor([color, sample]);
5689
5690 // Given this color as the reference
5691 // and the function parameter as the sample,
5692 // calculate deltaE 2000.
5693
5694 // This implementation assumes the parametric
5695 // weighting factors kL, kC and kH
5696 // for the influence of viewing conditions
5697 // are all 1, as sadly seems typical.
5698 // kL should be increased for lightness texture or noise
5699 // and kC increased for chroma noise
5700
5701 let [L1, a1, b1] = lab.from(color);
5702 let C1 = lch.from(lab, [L1, a1, b1])[1];
5703 let [L2, a2, b2] = lab.from(sample);
5704 let C2 = lch.from(lab, [L2, a2, b2])[1];
5705
5706 // Check for negative Chroma,
5707 // which might happen through
5708 // direct user input of LCH values
5709
5710 if (C1 < 0) {
5711 C1 = 0;
5712 }
5713 if (C2 < 0) {
5714 C2 = 0;
5715 }
5716 let Cbar = (C1 + C2) / 2; // mean Chroma
5717
5718 // calculate a-axis asymmetry factor from mean Chroma
5719 // this turns JND ellipses for near-neutral colors back into circles
5720 let C7 = pow7(Cbar);
5721 let G = 0.5 * (1 - Math.sqrt(C7 / (C7 + Gfactor)));
5722
5723 // scale a axes by asymmetry factor
5724 // this by the way is why there is no Lab2000 colorspace
5725 let adash1 = (1 + G) * a1;
5726 let adash2 = (1 + G) * a2;
5727
5728 // calculate new Chroma from scaled a and original b axes
5729 let Cdash1 = Math.sqrt(adash1 ** 2 + b1 ** 2);
5730 let Cdash2 = Math.sqrt(adash2 ** 2 + b2 ** 2);
5731
5732 // calculate new hues, with zero hue for true neutrals
5733 // and in degrees, not radians
5734
5735 let h1 = adash1 === 0 && b1 === 0 ? 0 : Math.atan2(b1, adash1);
5736 let h2 = adash2 === 0 && b2 === 0 ? 0 : Math.atan2(b2, adash2);
5737 if (h1 < 0) {
5738 h1 += 2 * π$1;
5739 }
5740 if (h2 < 0) {
5741 h2 += 2 * π$1;
5742 }
5743 h1 *= r2d;
5744 h2 *= r2d;
5745
5746 // Lightness and Chroma differences; sign matters
5747 let ΔL = L2 - L1;
5748 let ΔC = Cdash2 - Cdash1;
5749
5750 // Hue difference, getting the sign correct
5751 let hdiff = h2 - h1;
5752 let hsum = h1 + h2;
5753 let habs = Math.abs(hdiff);
5754 let Δh;
5755 if (Cdash1 * Cdash2 === 0) {
5756 Δh = 0;
5757 } else if (habs <= 180) {
5758 Δh = hdiff;
5759 } else if (hdiff > 180) {
5760 Δh = hdiff - 360;
5761 } else if (hdiff < -180) {
5762 Δh = hdiff + 360;
5763 } else {
5764 defaults.warn("the unthinkable has happened");
5765 }
5766
5767 // weighted Hue difference, more for larger Chroma
5768 let ΔH = 2 * Math.sqrt(Cdash2 * Cdash1) * Math.sin(Δh * d2r$1 / 2);
5769
5770 // calculate mean Lightness and Chroma
5771 let Ldash = (L1 + L2) / 2;
5772 let Cdash = (Cdash1 + Cdash2) / 2;
5773 let Cdash7 = pow7(Cdash);
5774
5775 // Compensate for non-linearity in the blue region of Lab.
5776 // Four possibilities for hue weighting factor,
5777 // depending on the angles, to get the correct sign
5778 let hdash;
5779 if (Cdash1 * Cdash2 === 0) {
5780 hdash = hsum; // which should be zero
5781 } else if (habs <= 180) {
5782 hdash = hsum / 2;
5783 } else if (hsum < 360) {
5784 hdash = (hsum + 360) / 2;
5785 } else {
5786 hdash = (hsum - 360) / 2;
5787 }
5788
5789 // positional corrections to the lack of uniformity of CIELAB
5790 // These are all trying to make JND ellipsoids more like spheres
5791
5792 // SL Lightness crispening factor
5793 // a background with L=50 is assumed
5794 let lsq = (Ldash - 50) ** 2;
5795 let SL = 1 + 0.015 * lsq / Math.sqrt(20 + lsq);
5796
5797 // SC Chroma factor, similar to those in CMC and deltaE 94 formulae
5798 let SC = 1 + 0.045 * Cdash;
5799
5800 // Cross term T for blue non-linearity
5801 let T = 1;
5802 T -= 0.17 * Math.cos((hdash - 30) * d2r$1);
5803 T += 0.24 * Math.cos(2 * hdash * d2r$1);
5804 T += 0.32 * Math.cos((3 * hdash + 6) * d2r$1);
5805 T -= 0.2 * Math.cos((4 * hdash - 63) * d2r$1);
5806
5807 // SH Hue factor depends on Chroma,
5808 // as well as adjusted hue angle like deltaE94.
5809 let SH = 1 + 0.015 * Cdash * T;
5810
5811 // RT Hue rotation term compensates for rotation of JND ellipses
5812 // and Munsell constant hue lines
5813 // in the medium-high Chroma blue region
5814 // (Hue 225 to 315)
5815 let Δθ = 30 * Math.exp(-1 * ((hdash - 275) / 25) ** 2);
5816 let RC = 2 * Math.sqrt(Cdash7 / (Cdash7 + Gfactor));
5817 let RT = -1 * Math.sin(2 * Δθ * d2r$1) * RC;
5818
5819 // Finally calculate the deltaE, term by term as root sume of squares
5820 let dE = (ΔL / (kL * SL)) ** 2;
5821 dE += (ΔC / (kC * SC)) ** 2;
5822 dE += (ΔH / (kH * SH)) ** 2;
5823 dE += RT * (ΔC / (kC * SC)) * (ΔH / (kH * SH));
5824 return Math.sqrt(dE);
5825 // Yay!!!
5826 }
5827
5828 /** @import { Matrix3x3 } from "../types.js" */
5829
5830 // Recalculated for consistent reference white
5831 // see https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-943521484
5832 /** @type {Matrix3x3} */
5833 // prettier-ignore
5834 const XYZtoLMS_M$1 = [[0.8190224379967030, 0.3619062600528904, -0.1288737815209879], [0.0329836539323885, 0.9292868615863434, 0.0361446663506424], [0.0481771893596242, 0.2642395317527308, 0.6335478284694309]];
5835 // inverse of XYZtoLMS_M
5836 /** @type {Matrix3x3} */
5837 // prettier-ignore
5838 const LMStoXYZ_M$1 = [[1.2268798758459243, -0.5578149944602171, 0.2813910456659647], [-0.0405757452148008, 1.1122868032803170, -0.0717110580655164], [-0.0763729366746601, -0.4214933324022432, 1.5869240198367816]];
5839 /** @type {Matrix3x3} */
5840 // prettier-ignore
5841 const LMStoLab_M = [[0.2104542683093140, 0.7936177747023054, -0.0040720430116193], [1.9779985324311684, -2.4285922420485799, 0.4505937096174110], [0.0259040424655478, 0.7827717124575296, -0.8086757549230774]];
5842 // LMStoIab_M inverted
5843 /** @type {Matrix3x3} */
5844 // prettier-ignore
5845 const LabtoLMS_M = [[1.0000000000000000, 0.3963377773761749, 0.2158037573099136], [1.0000000000000000, -0.1055613458156586, -0.0638541728258133], [1.0000000000000000, -0.0894841775298119, -1.2914855480194092]];
5846 var Oklab = new ColorSpace({
5847 id: "oklab",
5848 name: "Oklab",
5849 coords: {
5850 l: {
5851 refRange: [0, 1],
5852 name: "Lightness"
5853 },
5854 a: {
5855 refRange: [-0.4, 0.4]
5856 },
5857 b: {
5858 refRange: [-0.4, 0.4]
5859 }
5860 },
5861 // Note that XYZ is relative to D65
5862 white: "D65",
5863 base: XYZ_D65,
5864 fromBase(XYZ) {
5865 // move to LMS cone domain
5866 let LMS = multiply_v3_m3x3(XYZ, XYZtoLMS_M$1);
5867
5868 // non-linearity
5869 LMS[0] = Math.cbrt(LMS[0]);
5870 LMS[1] = Math.cbrt(LMS[1]);
5871 LMS[2] = Math.cbrt(LMS[2]);
5872 return multiply_v3_m3x3(LMS, LMStoLab_M, LMS);
5873 },
5874 toBase(OKLab) {
5875 // move to LMS cone domain
5876 let LMSg = multiply_v3_m3x3(OKLab, LabtoLMS_M);
5877
5878 // restore linearity
5879 LMSg[0] = LMSg[0] ** 3;
5880 LMSg[1] = LMSg[1] ** 3;
5881 LMSg[2] = LMSg[2] ** 3;
5882 return multiply_v3_m3x3(LMSg, LMStoXYZ_M$1, LMSg);
5883 },
5884 formats: {
5885 oklab: {
5886 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
5887 }
5888 }
5889 });
5890
5891 /**
5892 * More accurate color-difference formulae
5893 * than the simple 1976 Euclidean distance in CIE Lab
5894 * @param {import("../types.js").ColorTypes} color
5895 * @param {import("../types.js").ColorTypes} sample
5896 * @returns {number}
5897 */
5898 function deltaEOK (color, sample) {
5899 [color, sample] = getColor([color, sample]);
5900
5901 // Given this color as the reference
5902 // and a sample,
5903 // calculate deltaEOK, term by term as root sum of squares
5904 let [L1, a1, b1] = Oklab.from(color);
5905 let [L2, a2, b2] = Oklab.from(sample);
5906 let ΔL = L1 - L2;
5907 let Δa = a1 - a2;
5908 let Δb = b1 - b2;
5909 return Math.sqrt(ΔL ** 2 + Δa ** 2 + Δb ** 2);
5910 }
5911
5912 /** @import { ColorTypes } from "./types.js" */
5913
5914 const ε$5 = 0.000075;
5915
5916 /**
5917 * Check if a color is in gamut of either its own or another color space
5918 * @param {ColorTypes} color
5919 * @param {string | ColorSpace} [space]
5920 * @param {{ epsilon?: number | undefined }} [param2]
5921 * @returns {boolean}
5922 */
5923 function inGamut(color, space, {
5924 epsilon = ε$5
5925 } = {}) {
5926 color = getColor(color);
5927 if (!space) {
5928 space = color.space;
5929 }
5930 space = ColorSpace.get(space);
5931 let coords = color.coords;
5932 if (space !== color.space) {
5933 coords = space.from(color);
5934 }
5935 return space.inGamut(coords, {
5936 epsilon
5937 });
5938 }
5939
5940 var OKLCH = new ColorSpace({
5941 id: "oklch",
5942 name: "OkLCh",
5943 coords: {
5944 l: {
5945 refRange: [0, 1],
5946 name: "Lightness"
5947 },
5948 c: {
5949 refRange: [0, 0.4],
5950 name: "Chroma"
5951 },
5952 h: {
5953 refRange: [0, 360],
5954 type: "angle",
5955 name: "Hue"
5956 }
5957 },
5958 white: "D65",
5959 base: Oklab,
5960 fromBase: lch.fromBase,
5961 toBase: lch.toBase,
5962 formats: {
5963 oklch: {
5964 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"]
5965 }
5966 }
5967 });
5968
5969 /** @import { Coords, PlainColorObject } from "./types.js" */
5970
5971 /**
5972 * @param {PlainColorObject} color
5973 * @returns {PlainColorObject}
5974 */
5975 function clone(color) {
5976 return {
5977 space: color.space,
5978 coords: (/** @type {Coords} */color.coords.slice()),
5979 alpha: color.alpha
5980 };
5981 }
5982
5983 var esnext_iterator_reduce = {};
5984
5985 var es_iterator_reduce = {};
5986
5987 var hasRequiredEs_iterator_reduce;
5988
5989 function requireEs_iterator_reduce () {
5990 if (hasRequiredEs_iterator_reduce) return es_iterator_reduce;
5991 hasRequiredEs_iterator_reduce = 1;
5992 var $ = require_export();
5993 var iterate = requireIterate();
5994 var aCallable = requireACallable();
5995 var anObject = requireAnObject();
5996 var getIteratorDirect = requireGetIteratorDirect();
5997
5998 var $TypeError = TypeError;
5999
6000 // `Iterator.prototype.reduce` method
6001 // https://tc39.es/ecma262/#sec-iterator.prototype.reduce
6002 $({ target: 'Iterator', proto: true, real: true }, {
6003 reduce: function reduce(reducer /* , initialValue */) {
6004 anObject(this);
6005 aCallable(reducer);
6006 var record = getIteratorDirect(this);
6007 var noInitial = arguments.length < 2;
6008 var accumulator = noInitial ? undefined : arguments[1];
6009 var counter = 0;
6010 iterate(record, function (value) {
6011 if (noInitial) {
6012 noInitial = false;
6013 accumulator = value;
6014 } else {
6015 accumulator = reducer(accumulator, value, counter);
6016 }
6017 counter++;
6018 }, { IS_RECORD: true });
6019 if (noInitial) throw new $TypeError('Reduce of empty iterator with no initial value');
6020 return accumulator;
6021 }
6022 });
6023 return es_iterator_reduce;
6024 }
6025
6026 var hasRequiredEsnext_iterator_reduce;
6027
6028 function requireEsnext_iterator_reduce () {
6029 if (hasRequiredEsnext_iterator_reduce) return esnext_iterator_reduce;
6030 hasRequiredEsnext_iterator_reduce = 1;
6031 // TODO: Remove from `core-js@4`
6032 requireEs_iterator_reduce();
6033 return esnext_iterator_reduce;
6034 }
6035
6036 requireEsnext_iterator_reduce();
6037
6038 /** @import { ColorTypes } from "./types.js" */
6039
6040 /**
6041 * Euclidean distance of colors in an arbitrary color space
6042 * @param {ColorTypes} color1
6043 * @param {ColorTypes} color2
6044 * @param {string | ColorSpace} space
6045 * @returns {number}
6046 */
6047 function distance(color1, color2, space = "lab") {
6048 space = ColorSpace.get(space);
6049
6050 // Assume getColor() is called on color in space.from()
6051 let coords1 = space.from(color1);
6052 let coords2 = space.from(color2);
6053 return Math.sqrt(coords1.reduce((acc, c1, i) => {
6054 let c2 = coords2[i];
6055 if (isNone(c1) || isNone(c2)) {
6056 return acc;
6057 }
6058 return acc + (c2 - c1) ** 2;
6059 }, 0));
6060 }
6061
6062 /**
6063 * @param {import("../types.js").ColorTypes} color
6064 * @param {import("../types.js").ColorTypes} sample
6065 * @returns {number}
6066 */
6067 function deltaE76(color, sample) {
6068 // Assume getColor() is called in the distance function
6069 return distance(color, sample, "lab");
6070 }
6071
6072 // More accurate color-difference formulae
6073 // than the simple 1976 Euclidean distance in Lab
6074
6075 // CMC by the Color Measurement Committee of the
6076 // Bradford Society of Dyeists and Colorsts, 1994.
6077 // Uses LCH rather than Lab,
6078 // with different weights for L, C and H differences
6079 // A nice increase in accuracy for modest increase in complexity
6080 const π = Math.PI;
6081 const d2r = π / 180;
6082
6083 /**
6084 * @param {import("../types.js").ColorTypes} color
6085 * @param {import("../types.js").ColorTypes} sample
6086 * @param {{ l?: number | undefined; c?: number | undefined }} options
6087 * @returns {number}
6088 */
6089 function deltaECMC (color, sample, {
6090 l = 2,
6091 c = 1
6092 } = {}) {
6093 [color, sample] = getColor([color, sample]);
6094
6095 // Given this color as the reference
6096 // and a sample,
6097 // calculate deltaE CMC.
6098
6099 // This implementation assumes the parametric
6100 // weighting factors l:c are 2:1
6101 // which is typical for non-textile uses.
6102
6103 let [L1, a1, b1] = lab.from(color);
6104 let [, C1, H1] = lch.from(lab, [L1, a1, b1]);
6105 let [L2, a2, b2] = lab.from(sample);
6106 let C2 = lch.from(lab, [L2, a2, b2])[1];
6107
6108 // let [L1, a1, b1] = color.getAll(lab);
6109 // let C1 = color.get("lch.c");
6110 // let H1 = color.get("lch.h");
6111 // let [L2, a2, b2] = sample.getAll(lab);
6112 // let C2 = sample.get("lch.c");
6113
6114 // Check for negative Chroma,
6115 // which might happen through
6116 // direct user input of LCH values
6117
6118 if (C1 < 0) {
6119 C1 = 0;
6120 }
6121 if (C2 < 0) {
6122 C2 = 0;
6123 }
6124
6125 // we don't need H2 as ΔH is calculated from Δa, Δb and ΔC
6126
6127 // Lightness and Chroma differences
6128 // These are (color - sample), unlike deltaE2000
6129 let ΔL = L1 - L2;
6130 let ΔC = C1 - C2;
6131 let Δa = a1 - a2;
6132 let Δb = b1 - b2;
6133
6134 // weighted Hue difference, less for larger Chroma difference
6135
6136 let H2 = Δa ** 2 + Δb ** 2 - ΔC ** 2;
6137 // due to roundoff error it is possible that, for zero a and b,
6138 // ΔC > Δa + Δb is 0, resulting in attempting
6139 // to take the square root of a negative number
6140
6141 // trying instead the equation from Industrial Color Physics
6142 // By Georg A. Klein
6143
6144 // let ΔH = ((a1 * b2) - (a2 * b1)) / Math.sqrt(0.5 * ((C2 * C1) + (a2 * a1) + (b2 * b1)));
6145 // console.log({ΔH});
6146 // This gives the same result to 12 decimal places
6147 // except it sometimes NaNs when trying to root a negative number
6148
6149 // let ΔH = Math.sqrt(H2); we never actually use the root, it gets squared again!!
6150
6151 // positional corrections to the lack of uniformity of CIELAB
6152 // These are all trying to make JND ellipsoids more like spheres
6153
6154 // SL Lightness crispening factor, depends entirely on L1 not L2
6155 let SL = 0.511; // linear portion of the Y to L transfer function
6156 if (L1 >= 16) {
6157 // cubic portion
6158 SL = 0.040975 * L1 / (1 + 0.01765 * L1);
6159 }
6160
6161 // SC Chroma factor
6162 let SC = 0.0638 * C1 / (1 + 0.0131 * C1) + 0.638;
6163
6164 // Cross term T for blue non-linearity
6165 let T;
6166 if (isNone(H1)) {
6167 H1 = 0;
6168 }
6169 if (H1 >= 164 && H1 <= 345) {
6170 T = 0.56 + Math.abs(0.2 * Math.cos((H1 + 168) * d2r));
6171 } else {
6172 T = 0.36 + Math.abs(0.4 * Math.cos((H1 + 35) * d2r));
6173 }
6174 // console.log({T});
6175
6176 // SH Hue factor also depends on C1,
6177 let C4 = Math.pow(C1, 4);
6178 let F = Math.sqrt(C4 / (C4 + 1900));
6179 let SH = SC * (F * T + 1 - F);
6180
6181 // Finally calculate the deltaE, term by term as root sume of squares
6182 let dE = (ΔL / (l * SL)) ** 2;
6183 dE += (ΔC / (c * SC)) ** 2;
6184 dE += H2 / SH ** 2;
6185 // dE += (ΔH / SH) ** 2;
6186 return Math.sqrt(dE);
6187 // Yay!!!
6188 }
6189
6190 const Yw$1 = 203; // absolute luminance of media white
6191
6192 var XYZ_Abs_D65 = new ColorSpace({
6193 // Absolute CIE XYZ, with a D65 whitepoint,
6194 // as used in most HDR colorspaces as a starting point.
6195 // SDR spaces are converted per BT.2048
6196 // so that diffuse, media white is 203 cd/m²
6197 id: "xyz-abs-d65",
6198 cssId: "--xyz-abs-d65",
6199 name: "Absolute XYZ D65",
6200 coords: {
6201 x: {
6202 refRange: [0, 9504.7],
6203 name: "Xa"
6204 },
6205 y: {
6206 refRange: [0, 10000],
6207 name: "Ya"
6208 },
6209 z: {
6210 refRange: [0, 10888.3],
6211 name: "Za"
6212 }
6213 },
6214 base: XYZ_D65,
6215 fromBase(XYZ) {
6216 // Make XYZ absolute, not relative to media white
6217 // Maximum luminance in PQ is 10,000 cd/m²
6218 // Relative XYZ has Y=1 for media white
6219 return XYZ.map(v => v * Yw$1);
6220 },
6221 toBase(AbsXYZ) {
6222 // Convert to media-white relative XYZ
6223 return AbsXYZ.map(v => v / Yw$1);
6224 }
6225 });
6226
6227 /** @import { Matrix3x3, Vector3 } from "../types.js" */
6228
6229 const b$1 = 1.15;
6230 const g = 0.66;
6231 const n$1 = 2610 / 2 ** 14;
6232 const ninv$1 = 2 ** 14 / 2610;
6233 const c1$2 = 3424 / 2 ** 12;
6234 const c2$2 = 2413 / 2 ** 7;
6235 const c3$2 = 2392 / 2 ** 7;
6236 const p$1 = 1.7 * 2523 / 2 ** 5;
6237 const pinv = 2 ** 5 / (1.7 * 2523);
6238 const d = -0.56;
6239 const d0 = 1.6295499532821566e-11;
6240
6241 /** @type {Matrix3x3} */
6242 // prettier-ignore
6243 const XYZtoCone_M = [[0.41478972, 0.579999, 0.0146480], [-0.2015100, 1.120649, 0.0531008], [-0.0166008, 0.264800, 0.6684799]];
6244 // XYZtoCone_M inverted
6245 /** @type {Matrix3x3} */
6246 // prettier-ignore
6247 const ConetoXYZ_M = [[1.9242264357876067, -1.0047923125953657, 0.037651404030618], [0.35031676209499907, 0.7264811939316552, -0.06538442294808501], [-0.09098281098284752, -0.3127282905230739, 1.5227665613052603]];
6248 /** @type {Matrix3x3} */
6249 // prettier-ignore
6250 const ConetoIab_M = [[0.5, 0.5, 0], [3.524000, -4.066708, 0.542708], [0.199076, 1.096799, -1.295875]];
6251 // ConetoIab_M inverted
6252 /** @type {Matrix3x3} */
6253 // prettier-ignore
6254 const IabtoCone_M = [[1, 0.13860504327153927, 0.05804731615611883], [1, -0.1386050432715393, -0.058047316156118904], [1, -0.09601924202631895, -0.81189189605603900]];
6255 var Jzazbz = new ColorSpace({
6256 id: "jzazbz",
6257 name: "Jzazbz",
6258 coords: {
6259 jz: {
6260 refRange: [0, 1],
6261 name: "Jz"
6262 },
6263 az: {
6264 refRange: [-0.21, 0.21]
6265 },
6266 bz: {
6267 refRange: [-0.21, 0.21]
6268 }
6269 },
6270 base: XYZ_Abs_D65,
6271 fromBase(XYZ) {
6272 // First make XYZ absolute, not relative to media white
6273 // Maximum luminance in PQ is 10,000 cd/m²
6274 // Relative XYZ has Y=1 for media white
6275 // BT.2048 says media white Y=203 at PQ 58
6276
6277 let [Xa, Ya, Za] = XYZ;
6278
6279 // modify X and Y to minimize blue curvature
6280 let Xm = b$1 * Xa - (b$1 - 1) * Za;
6281 let Ym = g * Ya - (g - 1) * Xa;
6282
6283 // move to LMS cone domain
6284 let LMS = multiply_v3_m3x3([Xm, Ym, Za], XYZtoCone_M);
6285
6286 // PQ-encode LMS
6287 let PQLMS = /** @type {Vector3} } */
6288 LMS.map(function (val) {
6289 let num = c1$2 + c2$2 * spow(val / 10000, n$1);
6290 let denom = 1 + c3$2 * spow(val / 10000, n$1);
6291 return spow(num / denom, p$1);
6292 });
6293
6294 // almost there, calculate Iz az bz
6295 let [Iz, az, bz] = multiply_v3_m3x3(PQLMS, ConetoIab_M);
6296 // console.log({Iz, az, bz});
6297
6298 let Jz = (1 + d) * Iz / (1 + d * Iz) - d0;
6299 return [Jz, az, bz];
6300 },
6301 toBase(Jzazbz) {
6302 let [Jz, az, bz] = Jzazbz;
6303 let Iz = (Jz + d0) / (1 + d - d * (Jz + d0));
6304
6305 // bring into LMS cone domain
6306 let PQLMS = multiply_v3_m3x3([Iz, az, bz], IabtoCone_M);
6307
6308 // convert from PQ-coded to linear-light
6309 let LMS = /** @type {Vector3} } */
6310 PQLMS.map(function (val) {
6311 let num = c1$2 - spow(val, pinv);
6312 let denom = c3$2 * spow(val, pinv) - c2$2;
6313 let x = 10000 * spow(num / denom, ninv$1);
6314 return x; // luminance relative to diffuse white, [0, 70 or so].
6315 });
6316
6317 // modified abs XYZ
6318 let [Xm, Ym, Za] = multiply_v3_m3x3(LMS, ConetoXYZ_M);
6319
6320 // un-modify X and Y to get D65 XYZ, relative to media white
6321 let Xa = (Xm + (b$1 - 1) * Za) / b$1;
6322 let Ya = (Ym + (g - 1) * Xa) / g;
6323 return [Xa, Ya, Za];
6324 },
6325 formats: {
6326 // https://drafts.csswg.org/css-color-hdr/#Jzazbz
6327 jzazbz: {
6328 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
6329 }
6330 }
6331 });
6332
6333 var jzczhz = new ColorSpace({
6334 id: "jzczhz",
6335 name: "JzCzHz",
6336 coords: {
6337 jz: {
6338 refRange: [0, 1],
6339 name: "Jz"
6340 },
6341 cz: {
6342 refRange: [0, 0.26],
6343 name: "Chroma"
6344 },
6345 hz: {
6346 refRange: [0, 360],
6347 type: "angle",
6348 name: "Hue"
6349 }
6350 },
6351 base: Jzazbz,
6352 fromBase: lch.fromBase,
6353 toBase: lch.toBase,
6354 formats: {
6355 // https://drafts.csswg.org/css-color-hdr/#JzCzhz
6356 jzczhz: {
6357 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"]
6358 }
6359 }
6360 });
6361
6362 /**
6363 * More accurate color-difference formulae
6364 * than the simple 1976 Euclidean distance in Lab
6365 *
6366 * Uses JzCzHz, which has improved perceptual uniformity
6367 * and thus a simple Euclidean root-sum of ΔL² ΔC² ΔH²
6368 * gives good results.
6369 * @param {import("../types.js").ColorTypes} color
6370 * @param {import("../types.js").ColorTypes} sample
6371 * @returns {number}
6372 */
6373 function deltaEJz (color, sample) {
6374 [color, sample] = getColor([color, sample]);
6375
6376 // Given this color as the reference
6377 // and a sample,
6378 // calculate deltaE in JzCzHz.
6379 let [Jz1, Cz1, Hz1] = jzczhz.from(color);
6380 let [Jz2, Cz2, Hz2] = jzczhz.from(sample);
6381
6382 // Lightness and Chroma differences
6383 // sign does not matter as they are squared.
6384 let ΔJ = Jz1 - Jz2;
6385 let ΔC = Cz1 - Cz2;
6386
6387 // length of chord for ΔH
6388 if (isNone(Hz1) && isNone(Hz2)) {
6389 // both undefined hues
6390 Hz1 = 0;
6391 Hz2 = 0;
6392 } else if (isNone(Hz1)) {
6393 // one undefined, set to the defined hue
6394 Hz1 = Hz2;
6395 } else if (isNone(Hz2)) {
6396 Hz2 = Hz1;
6397 }
6398 let Δh = Hz1 - Hz2;
6399 let ΔH = 2 * Math.sqrt(Cz1 * Cz2) * Math.sin(Δh / 2 * (Math.PI / 180));
6400 return Math.sqrt(ΔJ ** 2 + ΔC ** 2 + ΔH ** 2);
6401 }
6402
6403 /** @import { Matrix3x3, Vector3 } from "../types.js" */
6404
6405 const c1$1 = 3424 / 4096;
6406 const c2$1 = 2413 / 128;
6407 const c3$1 = 2392 / 128;
6408 const m1$1 = 2610 / 16384;
6409 const m2 = 2523 / 32;
6410 const im1 = 16384 / 2610;
6411 const im2 = 32 / 2523;
6412
6413 // The matrix below includes the 4% crosstalk components
6414 // and is from the Dolby "What is ICtCp" paper"
6415 /** @type {Matrix3x3} */
6416 // prettier-ignore
6417 const XYZtoLMS_M = [[0.3592832590121217, 0.6976051147779502, -0.0358915932320290], [-0.1920808463704993, 1.1004767970374321, 0.0753748658519118], [0.0070797844607479, 0.0748396662186362, 0.8433265453898765]];
6418 // linear-light Rec.2020 to LMS, again with crosstalk
6419 // rational terms from Jan Fröhlich,
6420 // Encoding High Dynamic Range andWide Color Gamut Imagery, p.97
6421 // and ITU-R BT.2124-0 p.2
6422 /*
6423 const Rec2020toLMS_M = [
6424 [ 1688 / 4096, 2146 / 4096, 262 / 4096 ],
6425 [ 683 / 4096, 2951 / 4096, 462 / 4096 ],
6426 [ 99 / 4096, 309 / 4096, 3688 / 4096 ]
6427 ];
6428 */
6429 // this includes the Ebner LMS coefficients,
6430 // the rotation, and the scaling to [-0.5,0.5] range
6431 // rational terms from Fröhlich p.97
6432 // and ITU-R BT.2124-0 pp.2-3
6433 /** @type {Matrix3x3} */
6434 // prettier-ignore
6435 const LMStoIPT_M = [[2048 / 4096, 2048 / 4096, 0], [6610 / 4096, -13613 / 4096, 7003 / 4096], [17933 / 4096, -17390 / 4096, -543 / 4096]];
6436
6437 // inverted matrices, calculated from the above
6438 /** @type {Matrix3x3} */
6439 // prettier-ignore
6440 const IPTtoLMS_M = [[0.9999999999999998, 0.0086090370379328, 0.1110296250030260], [0.9999999999999998, -0.0086090370379328, -0.1110296250030259], [0.9999999999999998, 0.5600313357106791, -0.3206271749873188]];
6441 /*
6442 // prettier-ignore
6443 const LMStoRec2020_M = [
6444 [ 3.4375568932814012112, -2.5072112125095058195, 0.069654319228104608382],
6445 [-0.79142868665644156125, 1.9838372198740089874, -0.19240853321756742626 ],
6446 [-0.025646662911506476363, -0.099240248643945566751, 1.1248869115554520431 ]
6447 ];
6448 */
6449 /** @type {Matrix3x3} */
6450 // prettier-ignore
6451 const LMStoXYZ_M = [[2.0701522183894223, -1.3263473389671563, 0.2066510476294053], [0.3647385209748072, 0.6805660249472273, -0.0453045459220347], [-0.0497472075358123, -0.0492609666966131, 1.1880659249923042]];
6452
6453 // Only the PQ form of ICtCp is implemented here. There is also an HLG form.
6454 // from Dolby, "WHAT IS ICTCP?"
6455 // https://professional.dolby.com/siteassets/pdfs/ictcp_dolbywhitepaper_v071.pdf
6456 // and
6457 // Dolby, "Perceptual Color Volume
6458 // Measuring the Distinguishable Colors of HDR and WCG Displays"
6459 // https://professional.dolby.com/siteassets/pdfs/dolby-vision-measuring-perceptual-color-volume-v7.1.pdf
6460 var ictcp = new ColorSpace({
6461 id: "ictcp",
6462 name: "ICTCP",
6463 // From BT.2100-2 page 7:
6464 // During production, signal values are expected to exceed the
6465 // range E′ = [0.0 : 1.0]. This provides processing headroom and avoids
6466 // signal degradation during cascaded processing. Such values of E′,
6467 // below 0.0 or exceeding 1.0, should not be clipped during production
6468 // and exchange.
6469 // Values below 0.0 should not be clipped in reference displays (even
6470 // though they represent “negative” light) to allow the black level of
6471 // the signal (LB) to be properly set using test signals known as “PLUGE”
6472 coords: {
6473 i: {
6474 refRange: [0, 1],
6475 // Constant luminance,
6476 name: "I"
6477 },
6478 ct: {
6479 refRange: [-0.5, 0.5],
6480 // Full BT.2020 gamut in range [-0.5, 0.5]
6481 name: "CT"
6482 },
6483 cp: {
6484 refRange: [-0.5, 0.5],
6485 name: "CP"
6486 }
6487 },
6488 base: XYZ_Abs_D65,
6489 fromBase(XYZ) {
6490 // move to LMS cone domain
6491 let LMS = multiply_v3_m3x3(XYZ, XYZtoLMS_M);
6492 return LMStoICtCp(LMS);
6493 },
6494 toBase(ICtCp) {
6495 let LMS = ICtCptoLMS(ICtCp);
6496 return multiply_v3_m3x3(LMS, LMStoXYZ_M);
6497 },
6498 formats: {
6499 ictcp: {
6500 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
6501 }
6502 }
6503 });
6504
6505 /**
6506 *
6507 * @param {Vector3} LMS
6508 * @returns {Vector3}
6509 */
6510 function LMStoICtCp(LMS) {
6511 // apply the PQ EOTF
6512 // we can't ever be dividing by zero because of the "1 +" in the denominator
6513 let PQLMS = /** @type {Vector3} */
6514 LMS.map(function (val) {
6515 let num = c1$1 + c2$1 * (val / 10000) ** m1$1;
6516 let denom = 1 + c3$1 * (val / 10000) ** m1$1;
6517 return (num / denom) ** m2;
6518 });
6519
6520 // LMS to IPT, with rotation for Y'C'bC'r compatibility
6521 return multiply_v3_m3x3(PQLMS, LMStoIPT_M);
6522 }
6523
6524 /**
6525 *
6526 * @param {Vector3} ICtCp
6527 * @returns {Vector3}
6528 */
6529 function ICtCptoLMS(ICtCp) {
6530 let PQLMS = multiply_v3_m3x3(ICtCp, IPTtoLMS_M);
6531
6532 // From BT.2124-0 Annex 2 Conversion 3
6533 let LMS = /** @type {Vector3} */
6534 PQLMS.map(function (val) {
6535 let num = Math.max(val ** im2 - c1$1, 0);
6536 let denom = c2$1 - c3$1 * val ** im2;
6537 return 10000 * (num / denom) ** im1;
6538 });
6539 return LMS;
6540 }
6541
6542 /**
6543 * Delta E in ICtCp space,
6544 * which the ITU calls Delta E ITP, which is shorter.
6545 * Formulae from ITU Rec. ITU-R BT.2124-0
6546 * @param {import("../types.js").ColorTypes} color
6547 * @param {import("../types.js").ColorTypes} sample
6548 * @returns {number}
6549 */
6550 function deltaEITP (color, sample) {
6551 [color, sample] = getColor([color, sample]);
6552
6553 // Given this color as the reference
6554 // and a sample,
6555 // calculate deltaE in ICtCp
6556 // which is simply the Euclidean distance
6557
6558 let [I1, T1, P1] = ictcp.from(color);
6559 let [I2, T2, P2] = ictcp.from(sample);
6560
6561 // the 0.25 factor is to undo the encoding scaling in Ct
6562 // the 720 is so that 1 deltaE = 1 JND
6563 // per ITU-R BT.2124-0 p.3
6564
6565 return 720 * Math.sqrt((I1 - I2) ** 2 + 0.25 * (T1 - T2) ** 2 + (P1 - P2) ** 2);
6566 }
6567
6568 /**
6569 * More accurate color-difference formulae
6570 * than the simple 1976 Euclidean distance in CIE Lab
6571 * The Oklab a and b axes are scaled relative to the L axis, for better uniformity
6572 * Björn Ottosson said:
6573 * "I've recently done some tests with color distance datasets as implemented
6574 * in Colorio and on both the Combvd dataset and the OSA-UCS dataset a
6575 * scale factor of slightly more than 2 for a and b would give the best results
6576 * (2.016 works best for Combvd and 2.045 for the OSA-UCS dataset)."
6577 * @see {@link <https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-945714988>}
6578 * @param {import("../types.js").ColorTypes} color
6579 * @param {import("../types.js").ColorTypes} sample
6580 * @returns {number}
6581 */
6582 function deltaEOK2 (color, sample) {
6583 [color, sample] = getColor([color, sample]);
6584
6585 // Given this color as the reference
6586 // and a sample,
6587 // calculate deltaEOK2, term by term as root sum of squares
6588 let abscale = 2;
6589 let [L1, a1, b1] = Oklab.from(color);
6590 let [L2, a2, b2] = Oklab.from(sample);
6591 let ΔL = L1 - L2;
6592 let Δa = abscale * (a1 - a2);
6593 let Δb = abscale * (b1 - b2);
6594 return Math.sqrt(ΔL ** 2 + Δa ** 2 + Δb ** 2);
6595 }
6596
6597 /** @import { Coords, Matrix3x3, Vector3 } from "../types.js" */
6598
6599 // Type re-exports
6600 /** @typedef {import("../types.js").Cam16Object} Cam16Object */
6601 /** @typedef {import("../types.js").Cam16Input} Cam16Input */
6602 /** @typedef {import("../types.js").Cam16Environment} Cam16Environment */
6603
6604 const white$3 = WHITES.D65;
6605 const adaptedCoef = 0.42;
6606 const adaptedCoefInv = 1 / adaptedCoef;
6607 const tau$1 = 2 * Math.PI;
6608
6609 /** @type {Matrix3x3} */
6610 // prettier-ignore
6611 const cat16 = [[0.401288, 0.650173, -0.051461], [-0.250268, 1.204414, 0.045854], [-0.002079, 0.048952, 0.953127]];
6612
6613 /** @type {Matrix3x3} */
6614 const cat16Inv = [[1.8620678550872327, -1.0112546305316843, 0.14918677544445175], [0.38752654323613717, 0.6214474419314753, -0.008973985167612518], [-0.015841498849333856, -0.03412293802851557, 1.0499644368778496]];
6615
6616 /** @type {Matrix3x3} */
6617 const m1 = [[460.0, 451.0, 288.0], [460.0, -891.0, -261.0], [460.0, -220.0, -6300.0]];
6618 const surroundMap = {
6619 dark: [0.8, 0.525, 0.8],
6620 dim: [0.9, 0.59, 0.9],
6621 average: [1, 0.69, 1]
6622 };
6623 const hueQuadMap = {
6624 // Red, Yellow, Green, Blue, Red
6625 h: [20.14, 90.0, 164.25, 237.53, 380.14],
6626 e: [0.8, 0.7, 1.0, 1.2, 0.8],
6627 H: [0.0, 100.0, 200.0, 300.0, 400.0]
6628 };
6629 const rad2deg = 180 / Math.PI;
6630 const deg2rad$1 = Math.PI / 180;
6631
6632 /**
6633 * @param {Coords} coords
6634 * @param {number} fl
6635 * @returns {[number, number, number]}
6636 */
6637 function adapt$1(coords, fl) {
6638 const temp = /** @type {[number, number, number]} */
6639 coords.map(c => {
6640 const x = spow(fl * Math.abs(c) * 0.01, adaptedCoef);
6641 return 400 * copySign(x, c) / (x + 27.13);
6642 });
6643 return temp;
6644 }
6645
6646 /**
6647 * @param {Coords} adapted
6648 * @param {number} fl
6649 * @returns {[number, number, number]}
6650 */
6651 function unadapt(adapted, fl) {
6652 const constant = 100 / fl * 27.13 ** adaptedCoefInv;
6653 return /** @type {[number, number, number]} */adapted.map(c => {
6654 const cabs = Math.abs(c);
6655 return copySign(constant * spow(cabs / (400 - cabs), adaptedCoefInv), c);
6656 });
6657 }
6658
6659 /**
6660 * @param {number} h
6661 */
6662 function hueQuadrature(h) {
6663 let hp = constrain(h);
6664 if (hp <= hueQuadMap.h[0]) {
6665 hp += 360;
6666 }
6667 const i = bisectLeft(hueQuadMap.h, hp) - 1;
6668 const [hi, hii] = hueQuadMap.h.slice(i, i + 2);
6669 const [ei, eii] = hueQuadMap.e.slice(i, i + 2);
6670 const Hi = hueQuadMap.H[i];
6671 const t = (hp - hi) / ei;
6672 return Hi + 100 * t / (t + (hii - hp) / eii);
6673 }
6674
6675 /**
6676 * @param {number} H
6677 */
6678 function invHueQuadrature(H) {
6679 let Hp = (H % 400 + 400) % 400;
6680 const i = Math.floor(0.01 * Hp);
6681 Hp = Hp % 100;
6682 const [hi, hii] = hueQuadMap.h.slice(i, i + 2);
6683 const [ei, eii] = hueQuadMap.e.slice(i, i + 2);
6684 return constrain((Hp * (eii * hi - ei * hii) - 100 * hi * eii) / (Hp * (eii - ei) - 100 * eii));
6685 }
6686
6687 /**
6688 * @param {[number, number, number]} refWhite
6689 * @param {number} adaptingLuminance
6690 * @param {number} backgroundLuminance
6691 * @param {keyof typeof surroundMap} surround
6692 * @param {boolean} discounting
6693 * @returns {Cam16Environment}
6694 */
6695 function environment(refWhite, adaptingLuminance, backgroundLuminance, surround, discounting) {
6696 const env = {};
6697 env.discounting = discounting;
6698 env.refWhite = refWhite;
6699 env.surround = surround;
6700 const xyzW = /** @type {Vector3} */
6701 refWhite.map(c => {
6702 return c * 100;
6703 });
6704
6705 // The average luminance of the environment in `cd/m^2cd/m` (a.k.a. nits)
6706 env.la = adaptingLuminance;
6707 // The relative luminance of the nearby background
6708 env.yb = backgroundLuminance;
6709 // Absolute luminance of the reference white.
6710 const yw = xyzW[1];
6711
6712 // Cone response for reference white
6713 const rgbW = multiply_v3_m3x3(xyzW, cat16);
6714
6715 // Surround: dark, dim, and average
6716 let values = surroundMap[env.surround];
6717 const f = values[0];
6718 env.c = values[1];
6719 env.nc = values[2];
6720 const k = 1 / (5 * env.la + 1);
6721 const k4 = k ** 4;
6722
6723 // Factor of luminance level adaptation
6724 env.fl = k4 * env.la + 0.1 * (1 - k4) * (1 - k4) * Math.cbrt(5 * env.la);
6725 env.flRoot = env.fl ** 0.25;
6726 env.n = env.yb / yw;
6727 env.z = 1.48 + Math.sqrt(env.n);
6728 env.nbb = 0.725 * env.n ** -0.2;
6729 env.ncb = env.nbb;
6730
6731 // Degree of adaptation calculating if not discounting
6732 // illuminant (assumed eye is fully adapted)
6733 const d = Math.max(Math.min(f * (1 - 1 / 3.6 * Math.exp((-env.la - 42) / 92)), 1), 0);
6734 env.dRgb = /** @type {[number, number, number]} */
6735 rgbW.map(c => {
6736 return interpolate(1, yw / c, d);
6737 });
6738 env.dRgbInv = /** @type {[number, number, number]} */
6739 env.dRgb.map(c => {
6740 return 1 / c;
6741 });
6742
6743 // Achromatic response
6744 const rgbCW = /** @type {[number, number, number]} */
6745 rgbW.map((c, i) => {
6746 return c * env.dRgb[i];
6747 });
6748 const rgbAW = adapt$1(rgbCW, env.fl);
6749 env.aW = env.nbb * (2 * rgbAW[0] + rgbAW[1] + 0.05 * rgbAW[2]);
6750
6751 // console.log(env);
6752
6753 return env;
6754 }
6755
6756 // Pre-calculate everything we can with the viewing conditions
6757 const viewingConditions$1 = environment(white$3, 64 / Math.PI * 0.2, 20, "average", false);
6758
6759 /**
6760 * @param {Cam16Input} cam16
6761 * @param {Cam16Environment} env
6762 * @returns {[number, number, number]}
6763 */
6764 function fromCam16(cam16, env) {
6765 // These check ensure one, and only one attribute for a
6766 // given category is provided.
6767 // @ts-expect-error The '^` operator is not allowed for boolean types
6768 if (!(cam16.J !== undefined ^ cam16.Q !== undefined)) {
6769 throw new Error("Conversion requires one and only one: 'J' or 'Q'");
6770 }
6771
6772 // @ts-expect-error - The '^` operator is not allowed for boolean types
6773 if (!(cam16.C !== undefined ^ cam16.M !== undefined ^ cam16.s !== undefined)) {
6774 throw new Error("Conversion requires one and only one: 'C', 'M' or 's'");
6775 }
6776
6777 // Hue is absolutely required
6778 // @ts-expect-error - The '^` operator is not allowed for boolean types
6779 if (!(cam16.h !== undefined ^ cam16.H !== undefined)) {
6780 throw new Error("Conversion requires one and only one: 'h' or 'H'");
6781 }
6782
6783 // Black
6784 if (cam16.J === 0.0 || cam16.Q === 0.0) {
6785 return [0.0, 0.0, 0.0];
6786 }
6787
6788 // Break hue into Cartesian components
6789 let hRad = 0.0;
6790 if (cam16.h !== undefined) {
6791 hRad = constrain(cam16.h) * deg2rad$1;
6792 } else {
6793 hRad = invHueQuadrature(cam16.H) * deg2rad$1;
6794 }
6795 const cosh = Math.cos(hRad);
6796 const sinh = Math.sin(hRad);
6797
6798 // Calculate `Jroot` from one of the lightness derived coordinates.
6799 let Jroot = 0.0;
6800 if (cam16.J !== undefined) {
6801 Jroot = spow(cam16.J, 1 / 2) * 0.1;
6802 } else if (cam16.Q !== undefined) {
6803 Jroot = 0.25 * env.c * cam16.Q / ((env.aW + 4) * env.flRoot);
6804 }
6805
6806 // Calculate the `t` value from one of the chroma derived coordinates
6807 let alpha = 0.0;
6808 if (cam16.C !== undefined) {
6809 alpha = cam16.C / Jroot;
6810 } else if (cam16.M !== undefined) {
6811 alpha = cam16.M / env.flRoot / Jroot;
6812 } else if (cam16.s !== undefined) {
6813 alpha = 0.0004 * cam16.s ** 2 * (env.aW + 4) / env.c;
6814 }
6815 const t = spow(alpha * Math.pow(1.64 - Math.pow(0.29, env.n), -0.73), 10 / 9);
6816
6817 // Eccentricity
6818 const et = 0.25 * (Math.cos(hRad + 2) + 3.8);
6819
6820 // Achromatic response
6821 const A = env.aW * spow(Jroot, 2 / env.c / env.z);
6822
6823 // Calculate red-green and yellow-blue components
6824 const p1 = 5e4 / 13 * env.nc * env.ncb * et;
6825 const p2 = A / env.nbb;
6826 const r = 23 * (p2 + 0.305) * zdiv(t, 23 * p1 + t * (11 * cosh + 108 * sinh));
6827 const a = r * cosh;
6828 const b = r * sinh;
6829
6830 // Calculate back from cone response to XYZ
6831 const rgb_c = unadapt(/** @type {Vector3} */
6832
6833 multiply_v3_m3x3([p2, a, b], m1).map(c => {
6834 return c * 1 / 1403;
6835 }), env.fl);
6836 return /** @type {Vector3} */multiply_v3_m3x3(/** @type {Vector3} */
6837 rgb_c.map((c, i) => {
6838 return c * env.dRgbInv[i];
6839 }), cat16Inv).map(c => {
6840 return c / 100;
6841 });
6842 }
6843
6844 /**
6845 * @param {[number, number, number]} xyzd65
6846 * @param {Cam16Environment} env
6847 * @returns {Cam16Object}
6848 */
6849 function toCam16(xyzd65, env) {
6850 // Cone response
6851 const xyz100 = /** @type {Vector3} */
6852 xyzd65.map(c => {
6853 return c * 100;
6854 });
6855 const rgbA = adapt$1(/** @type {[number, number, number]} */
6856
6857 multiply_v3_m3x3(xyz100, cat16).map((c, i) => {
6858 return c * env.dRgb[i];
6859 }), env.fl);
6860
6861 // Calculate hue from red-green and yellow-blue components
6862 const a = rgbA[0] + (-12 * rgbA[1] + rgbA[2]) / 11;
6863 const b = (rgbA[0] + rgbA[1] - 2 * rgbA[2]) / 9;
6864 const hRad = (Math.atan2(b, a) % tau$1 + tau$1) % tau$1;
6865
6866 // Eccentricity
6867 const et = 0.25 * (Math.cos(hRad + 2) + 3.8);
6868 const t = 5e4 / 13 * env.nc * env.ncb * zdiv(et * Math.sqrt(a ** 2 + b ** 2), rgbA[0] + rgbA[1] + 1.05 * rgbA[2] + 0.305);
6869 const alpha = spow(t, 0.9) * Math.pow(1.64 - Math.pow(0.29, env.n), 0.73);
6870
6871 // Achromatic response
6872 const A = env.nbb * (2 * rgbA[0] + rgbA[1] + 0.05 * rgbA[2]);
6873 const Jroot = spow(A / env.aW, 0.5 * env.c * env.z);
6874
6875 // Lightness
6876 const J = 100 * spow(Jroot, 2);
6877
6878 // Brightness
6879 const Q = 4 / env.c * Jroot * (env.aW + 4) * env.flRoot;
6880
6881 // Chroma
6882 const C = alpha * Jroot;
6883
6884 // Colorfulness
6885 const M = C * env.flRoot;
6886
6887 // Hue
6888 const h = constrain(hRad * rad2deg);
6889
6890 // Hue quadrature
6891 const H = hueQuadrature(h);
6892
6893 // Saturation
6894 const s = 50 * spow(env.c * alpha / (env.aW + 4), 1 / 2);
6895
6896 // console.log({J: J, C: C, h: h, s: s, Q: Q, M: M, H: H});
6897
6898 return {
6899 J: J,
6900 C: C,
6901 h: h,
6902 s: s,
6903 Q: Q,
6904 M: M,
6905 H: H
6906 };
6907 }
6908
6909 // Provided as a way to directly evaluate the CAM16 model
6910 // https://observablehq.com/@jrus/cam16: reference implementation
6911 // https://arxiv.org/pdf/1802.06067.pdf: Nico Schlömer
6912 // https://onlinelibrary.wiley.com/doi/pdf/10.1002/col.22324: hue quadrature
6913 // https://www.researchgate.net/publication/318152296_Comprehensive_color_solutions_CAM16_CAT16_and_CAM16-UCS
6914 // Results compared against: https://github.com/colour-science/colour
6915 var cam16 = new ColorSpace({
6916 id: "cam16-jmh",
6917 cssId: "--cam16-jmh",
6918 name: "CAM16-JMh",
6919 coords: {
6920 j: {
6921 refRange: [0, 100],
6922 name: "J"
6923 },
6924 m: {
6925 refRange: [0, 105.0],
6926 name: "Colorfulness"
6927 },
6928 h: {
6929 refRange: [0, 360],
6930 type: "angle",
6931 name: "Hue"
6932 }
6933 },
6934 base: XYZ_D65,
6935 fromBase(xyz) {
6936 // If another derivation is created, ε could vary, so we can't hardcode
6937 if (this.ε === undefined) {
6938 this.ε = Object.values(this.coords)[1].refRange[1] / 100000;
6939 }
6940 const cam16 = toCam16(xyz, viewingConditions$1);
6941 const isAchromatic = Math.abs(cam16.M) < this.ε;
6942 return [cam16.J, isAchromatic ? 0 : cam16.M, isAchromatic ? null : cam16.h];
6943 },
6944 toBase(cam16) {
6945 return fromCam16({
6946 J: cam16[0],
6947 M: cam16[1],
6948 h: cam16[2]
6949 }, viewingConditions$1);
6950 }
6951 });
6952
6953 const white$2 = WHITES.D65;
6954 const ε$4 = 216 / 24389; // 6^3/29^3 == (24/116)^3
6955 const κ$3 = 24389 / 27; // 29^3/3^3
6956
6957 function toLstar(y) {
6958 // Convert XYZ Y to L*
6959
6960 const fy = y > ε$4 ? Math.cbrt(y) : (κ$3 * y + 16) / 116;
6961 return 116.0 * fy - 16.0;
6962 }
6963 function fromLstar(lstar) {
6964 // Convert L* back to XYZ Y
6965
6966 return lstar > 8 ? Math.pow((lstar + 16) / 116, 3) : lstar / κ$3;
6967 }
6968 function fromHct(coords, env) {
6969 // Use Newton's method to try and converge as quick as possible or
6970 // converge as close as we can. While the requested precision is achieved
6971 // most of the time, it may not always be achievable. Especially past the
6972 // visible spectrum, the algorithm will likely struggle to get the same
6973 // precision. If, for whatever reason, we cannot achieve the accuracy we
6974 // seek in the allotted iterations, just return the closest we were able to
6975 // get.
6976
6977 let [h, c, t] = coords;
6978 let xyz = [];
6979 let j = 0;
6980
6981 // Shortcut out for black
6982 if (t === 0) {
6983 return [0.0, 0.0, 0.0];
6984 }
6985
6986 // Calculate the Y we need to target
6987 let y = fromLstar(t);
6988
6989 // A better initial guess yields better results. Polynomials come from
6990 // curve fitting the T vs J response.
6991 if (t > 0) {
6992 j = 0.00379058511492914 * t ** 2 + 0.608983189401032 * t + 0.9155088574762233;
6993 } else {
6994 j = 9.514440756550361e-6 * t ** 2 + 0.08693057439788597 * t - 21.928975842194614;
6995 }
6996
6997 // Threshold of how close is close enough, and max number of attempts.
6998 // More precision and more attempts means more time spent iterating. Higher
6999 // required precision gives more accuracy but also increases the chance of
7000 // not hitting the goal. 2e-12 allows us to convert round trip with
7001 // reasonable accuracy of six decimal places or more.
7002 const threshold = 2e-12;
7003 const max_attempts = 15;
7004 let attempt = 0;
7005 let last = Infinity;
7006 let best = [0, 0, 0];
7007
7008 // Try to find a J such that the returned y matches the returned y of the L*
7009 while (attempt <= max_attempts) {
7010 xyz = fromCam16({
7011 J: j,
7012 C: c,
7013 h: h
7014 }, env);
7015
7016 // If we are within range, return XYZ
7017 // If we are closer than last time, save the values
7018 const delta = Math.abs(xyz[1] - y);
7019 if (delta < last) {
7020 if (delta <= threshold) {
7021 return xyz;
7022 }
7023 best = xyz;
7024 last = delta;
7025 }
7026
7027 // f(j_root) = (j ** (1 / 2)) * 0.1
7028 // f(j) = ((f(j_root) * 100) ** 2) / j - 1 = 0
7029 // f(j_root) = Y = y / 100
7030 // f(j) = (y ** 2) / j - 1
7031 // f'(j) = (2 * y) / j
7032 j = j - (xyz[1] - y) * j / (2 * xyz[1]);
7033 attempt += 1;
7034 }
7035
7036 // We could not acquire the precision we desired,
7037 // return our closest attempt.
7038 return best;
7039 }
7040 function toHct(xyz, env) {
7041 // Calculate HCT by taking the L* of CIE LCh D65 and CAM16 chroma and hue.
7042
7043 const t = toLstar(xyz[1]);
7044 if (t === 0.0) {
7045 return [0.0, 0.0, 0.0];
7046 }
7047 const cam16 = toCam16(xyz, viewingConditions);
7048 return [constrain(cam16.h), cam16.C, t];
7049 }
7050
7051 // Pre-calculate everything we can with the viewing conditions
7052 const viewingConditions = environment(white$2, 200 / Math.PI * fromLstar(50.0), fromLstar(50.0) * 100, "average", false);
7053
7054 // https://material.io/blog/science-of-color-design
7055 // This is not a port of the material-color-utilities,
7056 // but instead implements the full color space as described,
7057 // combining CAM16 JCh and Lab D65. This does not clamp conversion
7058 // to HCT to specific chroma bands and provides support for wider
7059 // gamuts than Google currently supports and does so at a greater
7060 // precision (> 8 bits back to sRGB).
7061 // This implementation comes from https://github.com/facelessuser/coloraide
7062 // which is licensed under MIT.
7063 var hct = new ColorSpace({
7064 id: "hct",
7065 name: "HCT",
7066 coords: {
7067 h: {
7068 refRange: [0, 360],
7069 type: "angle",
7070 name: "Hue"
7071 },
7072 c: {
7073 refRange: [0, 145],
7074 name: "Colorfulness"
7075 },
7076 t: {
7077 refRange: [0, 100],
7078 name: "Tone"
7079 }
7080 },
7081 base: XYZ_D65,
7082 fromBase(xyz) {
7083 if (this.ε === undefined) {
7084 this.ε = Object.values(this.coords)[1].refRange[1] / 100000;
7085 }
7086 let hct = toHct(xyz);
7087 if (hct[1] < this.ε) {
7088 hct[1] = 0.0;
7089 hct[0] = null;
7090 }
7091 return hct;
7092 },
7093 toBase(hct) {
7094 return fromHct(hct, viewingConditions);
7095 },
7096 formats: {
7097 color: {
7098 id: "--hct",
7099 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
7100 }
7101 }
7102 });
7103
7104 const deg2rad = Math.PI / 180;
7105 const ucsCoeff = [1.0, 0.007, 0.0228];
7106
7107 /**
7108 * Convert HCT chroma and hue (CAM16 JMh colorfulness and hue) using UCS logic for a and b.
7109 * @param {Coords} coords - HCT coordinates.
7110 * @return {number[]}
7111 */
7112 function convertUcsAb(coords) {
7113 // We want the distance between the actual color.
7114 // If chroma is negative, it will throw off our calculations.
7115 // Normally, converting back to the base and forward will correct it.
7116 // If we have a negative chroma after this, then we have a color that
7117 // cannot resolve to positive chroma.
7118 if (coords[1] < 0) {
7119 coords = hct.fromBase(hct.toBase(coords));
7120 }
7121
7122 // Only in extreme cases (usually outside the visible spectrum)
7123 // can the input value for log become negative.
7124 // Avoid domain error by forcing a zero result via "max" if necessary.
7125 const M = Math.log(Math.max(1 + ucsCoeff[2] * coords[1] * viewingConditions.flRoot, 1.0)) / ucsCoeff[2];
7126 const hrad = coords[0] * deg2rad;
7127 const a = M * Math.cos(hrad);
7128 const b = M * Math.sin(hrad);
7129 return [coords[2], a, b];
7130 }
7131
7132 /**
7133 * Color distance using HCT.
7134 * @param {import("../types.js").ColorTypes} color
7135 * @param {import("../types.js").ColorTypes} sample
7136 * @returns {number}
7137 */
7138 function deltaEHCT (color, sample) {
7139 [color, sample] = getColor([color, sample]);
7140 let [t1, a1, b1] = convertUcsAb(hct.from(color));
7141 let [t2, a2, b2] = convertUcsAb(hct.from(sample));
7142
7143 // Use simple euclidean distance with a and b using UCS conversion
7144 // and LCh lightness (HCT tone).
7145 return Math.sqrt((t1 - t2) ** 2 + (a1 - a2) ** 2 + (b1 - b2) ** 2);
7146 }
7147
7148 /**
7149 * Helmlab MetricSpace — 13-stage perceptual color space.
7150 *
7151 * A data-driven analytical color space fit on COMBVD (3,813 paired human
7152 * color-difference judgments aggregating BFD-P, Witt 1999, RIT-DuPont, and
7153 * Leeds). Used internally by `deltaEHelmlab` and exposed as the CSS
7154 * color space `helmlab-metric` for inspectability. Its coordinate system
7155 * (asymmetric ab plane, L > 1 from H-K modeling, achromatic axis offset
7156 * from origin) is shaped for ΔE accuracy rather than author-facing
7157 * coordinates — for general CSS authoring use HelmGen (`helmgen`).
7158 *
7159 * Measured in this branch: ~24% lower STRESS than CIEDE2000 on COMBVD.
7160 *
7161 * Pipeline: XYZ → M1 → γ → M2 → hue correction → H-K → cubic L → dark L
7162 * → hue-dep chroma scale → chroma power → L-dep chroma scale
7163 * → HLC interaction → hue-dep lightness → rotation
7164 *
7165 * Reference: arXiv:2602.23010
7166 * @see https://github.com/Grkmyldz148/helmlab
7167 */
7168
7169 /** @import { Matrix3x3 } from "../types.js" */
7170
7171 const {
7172 cos,
7173 sin,
7174 sqrt,
7175 atan2,
7176 exp,
7177 abs,
7178 pow,
7179 PI
7180 } = Math;
7181
7182 /** Bradford CAT: Color.js D65 → Helmlab D65 (apply in fromBase before M1) */
7183 /** @type {Matrix3x3} */
7184 // prettier-ignore
7185 const CAT_TO_HELM = [[1.000042977349746, 2.0718877053183e-05, -4.361018085669474e-05], [2.6946201090235744e-05, 0.9999906145080147, -1.4898828405401079e-05], [-7.941753620756204e-06, 1.2875204405137254e-05, 0.9997859822609763]];
7186
7187 /** Bradford CAT: Helmlab D65 → Color.js D65 (apply in toBase after M1_INV) */
7188 /** @type {Matrix3x3} */
7189 // prettier-ignore
7190 const CAT_FROM_HELM = [[0.9999570254019492, -2.071874272730964e-05, 4.361733292468361e-05], [-2.694517763358666e-05, 1.000009385946497, 1.490098223546482e-05], [7.943459292954202e-06, -1.287824596735154e-05, 1.000214063706999]];
7191
7192 // ── Utility functions ──────────────────────────────────────────────
7193
7194 // ── Core parameters (v21, 72 params) ──────────────────────────────
7195
7196 /** @type {Matrix3x3} */
7197 // prettier-ignore
7198 const M1$1 = [[0.72129864331134985189, 0.45344826541531813024, -0.19288975751942616377], [-0.78821186949557897616, 1.79524137675723594043, 0.08761724511817850503], [-0.09177005999121559676, 0.45765588659459255361, 1.29220455139176770842]];
7199 /** @type {Matrix3x3} */
7200 // prettier-ignore
7201 const M1_INV$1 = [[1.06510729580885898926, -0.31500440753011210715, 0.18034923817410389302], [0.47211077138377960383, 0.42719957659624552271, 0.04150680489380984689], [-0.09156391926309541407, -0.17367093631949789834, 0.77197903825582936399]];
7202 const GAMMA = [0.47229813098762524, 0.5149184096354483, 0.5113233386366979];
7203 const INV_GAMMA = [2.1173067060606283, 1.9420552485353544, 1.9557096741686448];
7204
7205 /** @type {Matrix3x3} */
7206 // prettier-ignore
7207 const M2$1 = [[-0.26355622180094095963, 0.41683228837031738312, 0.49267631416564028335], [1.88975705087773215851, -3.12122320342057735232, 1.04216669210603840590], [0.35851086179620561545, 1.76940281937903676202, -1.41206260676953720967]];
7208 /** @type {Matrix3x3} */
7209 // prettier-ignore
7210 const M2_INV$1 = [[0.91838978228150214278, 0.52320512370886662623, 0.70658045980908557038], [1.08990905744330257576, 0.07005324849041903723, 0.43197768747870440853], [1.59889572926420897581, 0.22061850068770233468, 0.01250603735522095097]];
7211
7212 // Enrichment parameters
7213 const hue_cos1 = -0.02833024015436984,
7214 hue_sin1 = -0.21131429516166544;
7215 const hue_cos2 = 0.2189784817615645,
7216 hue_sin2 = -0.06871898981942523;
7217 const hue_cos3 = 0.005506053349515315,
7218 hue_sin3 = -0.0641329861299175;
7219 const hue_cos4 = -0.053592461436994296,
7220 hue_sin4 = -0.00954137464208059;
7221 const hk_weight = 0.2676231133101982,
7222 hk_power = 0.8934892185255707;
7223 const hk_hue_mod = 0.7173169828841472;
7224 const hk_sin1 = 0.6915224124600773,
7225 hk_cos2 = 0.48647127559605596,
7226 hk_sin2 = 0.9853124591201782;
7227 const L_corr_p1 = 0.5385456675962418,
7228 L_corr_p2 = 0.12508858146241716,
7229 L_corr_p3 = 0.6768950256217603;
7230 const Lh_cos1 = -0.4963251525324449,
7231 Lh_sin1 = -0.09564696283240552;
7232 const lp_dark = -0.029053748937210654,
7233 lp_dark_hcos = 1.3346761652952872,
7234 lp_dark_hsin = -0.1698908144723919;
7235 const cs_cos1 = -0.195370576218515,
7236 cs_sin1 = 0.5330819227283227;
7237 const cs_cos2 = 0.08863325582067766,
7238 cs_sin2 = 0.9365540137751136;
7239 const cs_cos3 = 0.13789738139719568,
7240 cs_sin3 = 0.061650260197979936;
7241 const cs_cos4 = 0.0641970862504494,
7242 cs_sin4 = -0.027401052793571013;
7243 const cp_cos1 = -0.09900209889026965,
7244 cp_sin1 = 0.059635520647228726;
7245 const cp_cos2 = -0.013586499967803128,
7246 cp_sin2 = 0.2253393118474472;
7247 const lc1 = -1.5239477450767043,
7248 lc2 = -1.751157310240011;
7249 const hlc_cos1 = -0.43576378069144767,
7250 hlc_sin1 = 1.060094063845983;
7251 const hlc_cos2 = 0.47931193034584496,
7252 hlc_sin2 = -0.2622579649434462;
7253 const hl_cos1 = 0.13610794232685908,
7254 hl_sin1 = 0.1168702235362288;
7255 const hl_cos2 = -0.01617739641422492,
7256 hl_sin2 = 0.038145638815030566;
7257
7258 // Rigid rotation φ = −28.2°
7259 const PHI = -28.2 * PI / 180;
7260 const ROT_COS = cos(PHI);
7261 const ROT_SIN = sin(PHI);
7262
7263 // ── Pipeline helper functions ──────────────────────────────────────
7264
7265 function hueDelta(h) {
7266 return hue_cos1 * cos(h) + hue_sin1 * sin(h) + hue_cos2 * cos(2 * h) + hue_sin2 * sin(2 * h) + hue_cos3 * cos(3 * h) + hue_sin3 * sin(3 * h) + hue_cos4 * cos(4 * h) + hue_sin4 * sin(4 * h);
7267 }
7268 function hueDeltaDeriv(h) {
7269 return -hue_cos1 * sin(h) + hue_sin1 * cos(h) + -2 * hue_cos2 * sin(2 * h) + 2 * hue_sin2 * cos(2 * h) + -3 * hue_cos3 * sin(3 * h) + 3 * hue_sin3 * cos(3 * h) + -4 * hue_cos4 * sin(4 * h) + 4 * hue_sin4 * cos(4 * h);
7270 }
7271 function chromaScaleH(h) {
7272 let logS = cs_cos1 * cos(h) + cs_sin1 * sin(h) + cs_cos2 * cos(2 * h) + cs_sin2 * sin(2 * h) + cs_cos3 * cos(3 * h) + cs_sin3 * sin(3 * h) + cs_cos4 * cos(4 * h) + cs_sin4 * sin(4 * h);
7273 return exp(logS);
7274 }
7275 function lChromaScale(L) {
7276 let dL = L - 0.5;
7277 return exp(clamp(-30, lc1 * dL + lc2 * dL * dL, 30));
7278 }
7279 function hlcScale(h, L) {
7280 let hueFactor = hlc_cos1 * cos(h) + hlc_sin1 * sin(h) + hlc_cos2 * cos(2 * h) + hlc_sin2 * sin(2 * h);
7281 return exp(clamp(-30, (L - 0.5) * hueFactor, 30));
7282 }
7283 function hueLightnessScale(h) {
7284 let logS = hl_cos1 * cos(h) + hl_sin1 * sin(h) + hl_cos2 * cos(2 * h) + hl_sin2 * sin(2 * h);
7285 return exp(logS);
7286 }
7287 function chromaPowerH(h) {
7288 return 1 + cp_cos1 * cos(h) + cp_sin1 * sin(h) + cp_cos2 * cos(2 * h) + cp_sin2 * sin(2 * h);
7289 }
7290 function lCorrectFwd(L, h) {
7291 let t = L * (1 - L);
7292 let result = L + L_corr_p1 * t + L_corr_p2 * t * (0.5 - L) + L_corr_p3 * t * t;
7293 result += t * (Lh_cos1 * cos(h) + Lh_sin1 * sin(h));
7294 return result;
7295 }
7296 function lCorrectInv(L1, h) {
7297 let Lh = Lh_cos1 * cos(h) + Lh_sin1 * sin(h);
7298 let L = L1;
7299 for (let i = 0; i < 15; i++) {
7300 let t = L * (1 - L);
7301 let dt = 1 - 2 * L;
7302 let f = L + (L_corr_p1 + Lh) * t + L_corr_p2 * t * (0.5 - L) + L_corr_p3 * t * t - L1;
7303 let dfdL = 1 + (L_corr_p1 + Lh) * dt + L_corr_p2 * (dt * (0.5 - L) - t) + L_corr_p3 * 2 * t * dt;
7304 if (abs(dfdL) < 1e-10) {
7305 dfdL = 1;
7306 }
7307 L -= f / dfdL;
7308 }
7309 return L;
7310 }
7311 function darkLFwd(L, h) {
7312 let coeff = lp_dark + lp_dark_hcos * cos(h) + lp_dark_hsin * sin(h);
7313 let oml = L < 1 ? 1 - L : 0; // clamp at L=1: identity for L≥1
7314 let g = coeff * L * oml * oml;
7315 return L * exp(clamp(-30, g, 30));
7316 }
7317 function darkLInv(Ln, h) {
7318 let coeff = lp_dark + lp_dark_hcos * cos(h) + lp_dark_hsin * sin(h);
7319 let L = Ln;
7320 for (let i = 0; i < 12; i++) {
7321 let oml = L < 1 ? 1 - L : 0;
7322 let g = coeff * L * oml * oml;
7323 let eg = exp(clamp(-30, g, 30));
7324 let f = L * eg - Ln;
7325 let gp = coeff * oml * (1 - 3 * L);
7326 let fp = eg * (1 + L * gp);
7327 if (abs(fp) < 1e-10) {
7328 fp = 1;
7329 }
7330 L -= f / fp;
7331 }
7332 return L;
7333 }
7334
7335 // ── Color space definition ─────────────────────────────────────────
7336 // Helmlab MetricSpace is the perceptual forward space behind `deltaEHelmlab`.
7337 // Its coordinate system is shaped to maximize ΔE prediction accuracy on
7338 // visual-difference datasets (COMBVD: BFD-P, Witt 1999, RIT-DuPont, Leeds),
7339 // not author convenience. As a result:
7340 // - the ab plane is asymmetric (the metric was fit to directionally
7341 // asymmetric human discrimination thresholds);
7342 // - the L axis exceeds 1 for highly chromatic colors because the
7343 // Helmholtz–Kohlrausch boost is modeled explicitly (high-chroma colors
7344 // appear brighter than equiluminant neutrals);
7345 // - the achromatic axis is not pinned to (0, 0) — the gray axis sits
7346 // slightly off-origin in this coordinate system. Distance is
7347 // translation-invariant, so this does not affect ΔE quality.
7348 //
7349 // For CSS-author-facing color authoring (palettes, gradients, gamut
7350 // mapping), use HelmGen (`helmgen`) instead. This space (`helmlab-metric`)
7351 // is exposed primarily so the metric forward is inspectable for
7352 // debugging, color-science exploration, and as the internal forward used
7353 // by `deltaEHelmlab`.
7354
7355 const fromXYZ = function (xyz) {
7356 // Stage 0: Chromatic adaptation (Color.js D65 → Helmlab D65)
7357 let adapted = multiply_v3_m3x3(xyz, CAT_TO_HELM);
7358
7359 // Stage 1: XYZ → LMS (M1)
7360 let [lms0, lms1, lms2] = multiply_v3_m3x3(adapted, M1$1);
7361
7362 // Stage 2: Power compression (signed)
7363 let c0 = spow(lms0, GAMMA[0]);
7364 let c1 = spow(lms1, GAMMA[1]);
7365 let c2 = spow(lms2, GAMMA[2]);
7366
7367 // Stage 3: LMS_c → Lab_raw (M2)
7368 let [L, a, b] = multiply_v3_m3x3([c0, c1, c2], M2$1);
7369
7370 // Stage 3.5: Hue correction (4-harmonic Fourier)
7371 let h = atan2(b, a);
7372 let C = sqrt(a * a + b * b);
7373 let delta = hueDelta(h);
7374 let hNew = h + delta;
7375 a = C * cos(hNew);
7376 b = C * sin(hNew);
7377
7378 // Stage 3.7: Helmholtz-Kohlrausch correction
7379 let Cr = sqrt(a * a + b * b);
7380 let hkBoost = hk_weight * pow(Cr, clamp(0.01, hk_power, 10));
7381 let hr = atan2(b, a);
7382 let factor = 1 + hk_hue_mod * cos(hr) + hk_sin1 * sin(hr) + hk_cos2 * cos(2 * hr) + hk_sin2 * sin(2 * hr);
7383 L += hkBoost * factor;
7384
7385 // Stage 4: Cubic L correction (with hue modulation)
7386 h = atan2(b, a);
7387 L = lCorrectFwd(L, h);
7388
7389 // Stage 4.5: Dark L compression
7390 h = atan2(b, a);
7391 L = darkLFwd(L, h);
7392
7393 // Stage 5: Hue-dependent chroma scaling
7394 h = atan2(b, a);
7395 let cs = chromaScaleH(h);
7396 a *= cs;
7397 b *= cs;
7398
7399 // Stage 5.5: Nonlinear chroma power
7400 h = atan2(b, a);
7401 C = sqrt(a * a + b * b);
7402 let p = chromaPowerH(h);
7403 let Cn = C > 0 ? pow(C, p) : 0;
7404 a = Cn * cos(h);
7405 b = Cn * sin(h);
7406
7407 // Stage 6: L-dependent chroma scaling
7408 let T = lChromaScale(L);
7409 a *= T;
7410 b *= T;
7411
7412 // Stage 6.5: HLC interaction
7413 h = atan2(b, a);
7414 let hlcS = hlcScale(h, L);
7415 a *= hlcS;
7416 b *= hlcS;
7417
7418 // Stage 8: Hue-dependent lightness scaling
7419 h = atan2(b, a);
7420 L *= hueLightnessScale(h);
7421
7422 // Stage 11: Rigid rotation (φ = −28.2°)
7423 let aRot = a * ROT_COS - b * ROT_SIN;
7424 let bRot = a * ROT_SIN + b * ROT_COS;
7425 return [L, aRot, bRot];
7426 };
7427 const toXYZ = function (lab) {
7428 let [L, a, b] = lab;
7429
7430 // Undo Stage 11: rotation
7431 let aUn = a * ROT_COS + b * ROT_SIN;
7432 let bUn = -a * ROT_SIN + b * ROT_COS;
7433 a = aUn;
7434 b = bUn;
7435
7436 // Undo Stage 8: hue-dep lightness
7437 let h = atan2(b, a);
7438 L /= hueLightnessScale(h);
7439
7440 // Undo Stage 6.5: HLC
7441 h = atan2(b, a);
7442 let hlcS = hlcScale(h, L);
7443 a /= hlcS;
7444 b /= hlcS;
7445
7446 // Undo Stage 6: L-dep chroma
7447 let T = lChromaScale(L);
7448 a /= T;
7449 b /= T;
7450
7451 // Undo Stage 5.5: chroma power
7452 h = atan2(b, a);
7453 let C = sqrt(a * a + b * b);
7454 let p = chromaPowerH(h);
7455 let Co = C > 0 ? pow(C, 1 / p) : 0;
7456 a = Co * cos(h);
7457 b = Co * sin(h);
7458
7459 // Undo Stage 5: chroma scaling
7460 h = atan2(b, a);
7461 let cs = chromaScaleH(h);
7462 a /= cs;
7463 b /= cs;
7464
7465 // Undo Stage 4.5: dark L
7466 h = atan2(b, a);
7467 L = darkLInv(L, h);
7468
7469 // Undo Stage 4: cubic L
7470 h = atan2(b, a);
7471 L = lCorrectInv(L, h);
7472
7473 // Undo Stage 3.7: H-K
7474 let Cr = sqrt(a * a + b * b);
7475 let hkBoost = hk_weight * pow(Cr, clamp(0.01, hk_power, 10));
7476 let hr = atan2(b, a);
7477 let factor = 1 + hk_hue_mod * cos(hr) + hk_sin1 * sin(hr) + hk_cos2 * cos(2 * hr) + hk_sin2 * sin(2 * hr);
7478 L -= hkBoost * factor;
7479
7480 // Undo Stage 3.5: hue correction (Newton iteration)
7481 let hOut = atan2(b, a);
7482 C = sqrt(a * a + b * b);
7483 let hRaw = hOut;
7484 for (let i = 0; i < 8; i++) {
7485 let f = hRaw + hueDelta(hRaw) - hOut;
7486 let fp = 1 + hueDeltaDeriv(hRaw);
7487 if (abs(fp) < 1e-10) {
7488 fp = 1;
7489 }
7490 hRaw -= f / fp;
7491 }
7492 a = C * cos(hRaw);
7493 b = C * sin(hRaw);
7494
7495 // Undo Stage 3: Lab → LMS_c (M2_inv)
7496 let [lc0, lc1, lc2] = multiply_v3_m3x3([L, a, b], M2_INV$1);
7497
7498 // Undo Stage 2: power compression
7499 let l0 = spow(lc0, INV_GAMMA[0]);
7500 let l1 = spow(lc1, INV_GAMMA[1]);
7501 let l2 = spow(lc2, INV_GAMMA[2]);
7502
7503 // Undo Stage 1: LMS → XYZ (M1_inv)
7504 let xyz = multiply_v3_m3x3([l0, l1, l2], M1_INV$1);
7505
7506 // Undo Stage 0: Chromatic adaptation (Helmlab D65 → Color.js D65)
7507 return multiply_v3_m3x3(xyz, CAT_FROM_HELM);
7508 };
7509 var helmlab = new ColorSpace({
7510 id: "helmlab-metric",
7511 name: "Helmlab MetricSpace",
7512 cssId: "--helmlab-metric",
7513 coords: {
7514 l: {
7515 refRange: [0, 1.6],
7516 name: "Lightness"
7517 },
7518 a: {
7519 refRange: [-1.5, 1.5]
7520 },
7521 b: {
7522 refRange: [-1.5, 1.5]
7523 }
7524 },
7525 white: "D65",
7526 base: XYZ_D65,
7527 fromBase(xyz) {
7528 return fromXYZ(xyz);
7529 },
7530 toBase(lab) {
7531 return toXYZ(lab);
7532 }
7533 });
7534
7535 // Helmlab MetricSpace weighted distance (v21, 72 params).
7536 // Optimized on COMBVD human color-difference judgments.
7537 //
7538 // Formula:
7539 // SL = 1 + sl * (L_avg - 0.5)²
7540 // SC = 1 + sc * C_avg
7541 // raw = (ΔL²/SL² + wC * Δab²/SC²) ^ (p/2)
7542 // compressed = raw / (1 + c * raw)
7543 // ΔE = compressed ^ q
7544
7545 const sl = -0.9155125151657894;
7546 const sc = 2.9268353744941558;
7547 const wC = 3.966003089807536;
7548 const p = 1.9737081170404969;
7549 const compress = 52.473130649294724;
7550 const q = 0.47897301074925214;
7551
7552 /**
7553 * @param {import("../types.js").ColorTypes} color
7554 * @param {import("../types.js").ColorTypes} sample
7555 * @returns {number}
7556 */
7557 function deltaEHelmlab (color, sample) {
7558 [color, sample] = getColor([color, sample]);
7559 let [L1, a1, b1] = helmlab.from(color);
7560 let [L2, a2, b2] = helmlab.from(sample);
7561 let ΔL = L1 - L2;
7562 let Δa = a1 - a2;
7563 let Δb = b1 - b2;
7564
7565 // Pair-dependent weighting
7566 let Lavg = (L1 + L2) * 0.5;
7567 let SL = 1 + sl * (Lavg - 0.5) ** 2;
7568 let C1 = Math.sqrt(a1 ** 2 + b1 ** 2);
7569 let C2 = Math.sqrt(a2 ** 2 + b2 ** 2);
7570 let Cavg = (C1 + C2) * 0.5;
7571 let SC = 1 + sc * Cavg;
7572
7573 // Weighted Minkowski distance
7574 let raw = (ΔL ** 2 / SL ** 2 + wC * (Δa ** 2 + Δb ** 2) / SC ** 2) ** (p / 2);
7575
7576 // Monotonic compression
7577 let compressed = raw / (1 + compress * raw);
7578 return compressed ** q;
7579 }
7580
7581 /**
7582 * @packageDocumentation
7583 * This module defines all the builtin deltaE methods.
7584 */
7585 var deltaEMethods = {
7586 deltaE76,
7587 deltaECMC,
7588 deltaE2000,
7589 deltaEJz,
7590 deltaEITP,
7591 deltaEOK,
7592 deltaEOK2,
7593 deltaEHCT,
7594 deltaEHelmlab
7595 };
7596
7597 /** @typedef {keyof typeof import("./index.js").default extends `deltaE${infer Method}` ? Method : string} Methods */
7598
7599 /** @import { ColorTypes, PlainColorObject } from "./types.js" */
7600
7601 // Type re-exports
7602 /** @typedef {import("./types.js").ToGamutOptions} ToGamutOptions */
7603
7604 /**
7605 * Calculate the epsilon to 2 degrees smaller than the specified JND.
7606 * @param {number} jnd The target "just noticeable difference".
7607 * @returns {number}
7608 */
7609 function calcEpsilon(jnd) {
7610 // Calculate the epsilon to 2 degrees smaller than the specified JND.
7611
7612 const order = !jnd ? 0 : Math.floor(Math.log10(Math.abs(jnd)));
7613 // Limit to an arbitrary value to ensure value is never too small and causes infinite loops.
7614 return Math.max(parseFloat(`1e${order - 2}`), 1e-6);
7615 }
7616 const GMAPPRESET = {
7617 hct: {
7618 method: "hct.c",
7619 jnd: 2,
7620 deltaEMethod: "hct",
7621 blackWhiteClamp: {}
7622 },
7623 "hct-tonal": {
7624 method: "hct.c",
7625 jnd: 0,
7626 deltaEMethod: "hct",
7627 blackWhiteClamp: {
7628 channel: "hct.t",
7629 min: 0,
7630 max: 100
7631 }
7632 }
7633 };
7634
7635 /**
7636 * Force coordinates to be in gamut of a certain color space.
7637 * Mutates the color it is passed.
7638 * @overload
7639 * @param {ColorTypes} color
7640 * @param {ToGamutOptions} [options]
7641 * @returns {PlainColorObject}
7642 */
7643 /**
7644 * @overload
7645 * @param {ColorTypes} color
7646 * @param {string} [space]
7647 * @returns {PlainColorObject}
7648 */
7649 /**
7650 * @param {ColorTypes} color
7651 * @param {string & Partial<ToGamutOptions> | ToGamutOptions} [space]
7652 * @returns {PlainColorObject}
7653 */
7654 function toGamut(color, {
7655 method = defaults.gamut_mapping,
7656 space = undefined,
7657 deltaEMethod = "",
7658 jnd = 2,
7659 blackWhiteClamp = undefined,
7660 min = undefined,
7661 max = undefined
7662 } = {}) {
7663 color = getColor(color);
7664 if (isString(arguments[1])) {
7665 space = arguments[1];
7666 } else if (!space) {
7667 space = color.space;
7668 }
7669 space = ColorSpace.get(space);
7670
7671 // 3 spaces:
7672 // color.space: current color space
7673 // space: space whose gamut we are mapping to
7674 // mapSpace: space with the coord we're reducing
7675
7676 if (inGamut(color, space, {
7677 epsilon: 0
7678 })) {
7679 return /** @type {PlainColorObject} */color;
7680 }
7681 let spaceColor;
7682 if (method === "css") {
7683 spaceColor = toGamutCSS(color, {
7684 space
7685 });
7686 } else if (method === "raytrace") {
7687 spaceColor = toGamutRayTrace(color, {
7688 space
7689 });
7690 } else {
7691 if (method !== "clip") {
7692 if (Object.prototype.hasOwnProperty.call(GMAPPRESET, method)) {
7693 ({
7694 method,
7695 jnd,
7696 deltaEMethod,
7697 blackWhiteClamp
7698 } = GMAPPRESET[method]);
7699 }
7700
7701 // Get the correct delta E method
7702 let de = deltaE2000;
7703 if (deltaEMethod !== "") {
7704 for (let m in deltaEMethods) {
7705 if ("deltae" + deltaEMethod.toLowerCase() === m.toLowerCase()) {
7706 de = deltaEMethods[m];
7707 break;
7708 }
7709 }
7710 }
7711 if (jnd === 0) {
7712 jnd = 1e-16;
7713 }
7714 let clipped = toGamut(to(color, space), {
7715 method: "clip",
7716 space
7717 });
7718 if (de(color, clipped) > jnd) {
7719 var _min;
7720 // Clamp to SDR white and black if required
7721 if (blackWhiteClamp && Object.keys(blackWhiteClamp).length === 3) {
7722 let channelMeta = ColorSpace.resolveCoord(blackWhiteClamp.channel);
7723 let channel = get(to(color, channelMeta.space), channelMeta.id);
7724 if (isNone(channel)) {
7725 channel = 0;
7726 }
7727 if (channel >= blackWhiteClamp.max) {
7728 return to({
7729 space: "xyz-d65",
7730 coords: WHITES["D65"]
7731 }, color.space);
7732 } else if (channel <= blackWhiteClamp.min) {
7733 return to({
7734 space: "xyz-d65",
7735 coords: [0, 0, 0]
7736 }, color.space);
7737 }
7738 }
7739
7740 // Reduce a coordinate of a certain color space until the color is in gamut
7741 let coordMeta = ColorSpace.resolveCoord(method);
7742 let mapSpace = coordMeta.space;
7743 let coordId = coordMeta.id;
7744 let mappedColor = to(color, mapSpace);
7745 // If we were already in the mapped color space, we need to resolve undefined channels
7746 mappedColor.coords.forEach((c, i) => {
7747 if (isNone(c)) {
7748 mappedColor.coords[i] = 0;
7749 }
7750 });
7751 let bounds = coordMeta.range || coordMeta.refRange;
7752 (_min = min) !== null && _min !== void 0 ? _min : min = bounds[0];
7753 let ε = calcEpsilon(jnd);
7754 let low = min;
7755 let high = Math.min(get(mappedColor, coordId), max !== null && max !== void 0 ? max : Infinity);
7756 set(mappedColor, coordId, high);
7757 while (high - low > ε) {
7758 let clipped = clone(mappedColor);
7759 clipped = toGamut(clipped, {
7760 space,
7761 method: "clip"
7762 });
7763 let deltaE = de(mappedColor, clipped);
7764 if (deltaE - jnd < ε) {
7765 low = get(mappedColor, coordId);
7766 } else {
7767 high = get(mappedColor, coordId);
7768 }
7769 set(mappedColor, coordId, (low + high) / 2);
7770 }
7771 spaceColor = to(mappedColor, space);
7772 } else {
7773 spaceColor = clipped;
7774 }
7775 } else {
7776 spaceColor = to(color, space);
7777 }
7778 if (method === "clip" ||
7779 // Dumb coord clipping
7780 // finish off smarter gamut mapping with clip to get rid of ε, see #17
7781 !inGamut(spaceColor, space, {
7782 epsilon: 0
7783 })) {
7784 let bounds = Object.values(space.coords).map(c => c.range || []);
7785 spaceColor.coords = /** @type {[number, number, number]} */
7786 spaceColor.coords.map((c, i) => {
7787 let [min, max] = bounds[i];
7788 if (min !== undefined) {
7789 c = Math.max(min, c);
7790 }
7791 if (max !== undefined) {
7792 c = Math.min(c, max);
7793 }
7794 return c;
7795 });
7796 }
7797 }
7798 if (space !== color.space) {
7799 spaceColor = to(spaceColor, color.space);
7800 }
7801 color.coords = spaceColor.coords;
7802 return /** @type {PlainColorObject} */color;
7803 }
7804
7805 /** @type {"color"} */
7806 toGamut.returns = "color";
7807
7808 /**
7809 * The reference colors to be used if lightness is out of the range 0-1 in the
7810 * `Oklch` space. These are created in the `Oklab` space, as it is used by the
7811 * DeltaEOK calculation, so it is guaranteed to be imported.
7812 * @satisfies {Record<string, ColorTypes>}
7813 */
7814 const COLORS = {
7815 WHITE: {
7816 space: Oklab,
7817 coords: [1, 0, 0],
7818 alpha: 1
7819 },
7820 BLACK: {
7821 space: Oklab,
7822 coords: [0, 0, 0],
7823 alpha: 1
7824 }
7825 };
7826
7827 /**
7828 * Given a color `origin`, returns a new color that is in gamut using
7829 * the CSS Gamut Mapping Algorithm. If `space` is specified, it will be in gamut
7830 * in `space`, and returned in `space`. Otherwise, it will be in gamut and
7831 * returned in the color space of `origin`.
7832 * @param {ColorTypes} origin
7833 * @param {{ space?: string | ColorSpace | undefined }} options
7834 * @returns {PlainColorObject}
7835 */
7836 function toGamutCSS(origin, {
7837 space
7838 } = {}) {
7839 const JND = 0.02;
7840 const ε = 0.0001;
7841 origin = getColor(origin);
7842 if (!space) {
7843 space = origin.space;
7844 }
7845 space = ColorSpace.get(space);
7846 if (space.isUnbounded) {
7847 return to(origin, space);
7848 }
7849 const origin_OKLCH = to(origin, OKLCH);
7850 let L = origin_OKLCH.coords[0];
7851
7852 // return media white or black, if lightness is out of range
7853 if (L >= 1) {
7854 const white = to(COLORS.WHITE, space);
7855 white.alpha = origin.alpha;
7856 return to(white, space);
7857 }
7858 if (L <= 0) {
7859 const black = to(COLORS.BLACK, space);
7860 black.alpha = origin.alpha;
7861 return to(black, space);
7862 }
7863 if (inGamut(origin_OKLCH, space, {
7864 epsilon: 0
7865 })) {
7866 return to(origin_OKLCH, space);
7867 }
7868 function clip(_color) {
7869 const destColor = to(_color, space);
7870 const spaceCoords = Object.values(/** @type {ColorSpace} */space.coords);
7871 destColor.coords = /** @type {[number, number, number]} */
7872 destColor.coords.map((coord, index) => {
7873 if ("range" in spaceCoords[index]) {
7874 const [min, max] = spaceCoords[index].range;
7875 return clamp(min, coord, max);
7876 }
7877 return coord;
7878 });
7879 return destColor;
7880 }
7881 let min = 0;
7882 let max = origin_OKLCH.coords[1];
7883 let min_inGamut = true;
7884 let current = clone(origin_OKLCH);
7885 let clipped = clip(current);
7886 let E = deltaEOK(clipped, current);
7887 if (E < JND) {
7888 return clipped;
7889 }
7890 while (max - min > ε) {
7891 const chroma = (min + max) / 2;
7892 current.coords[1] = chroma;
7893 if (min_inGamut && inGamut(current, space, {
7894 epsilon: 0
7895 })) {
7896 min = chroma;
7897 } else {
7898 clipped = clip(current);
7899 E = deltaEOK(clipped, current);
7900 if (E < JND) {
7901 if (JND - E < ε) {
7902 break;
7903 } else {
7904 min_inGamut = false;
7905 min = chroma;
7906 }
7907 } else {
7908 max = chroma;
7909 }
7910 }
7911 }
7912 return clipped;
7913 }
7914
7915 /**
7916 * Given `start` and `end` coordinates of a 3D ray and a `bmin` and `bmax` bounding box,
7917 * find the intersection of the ray and box. Return an empty list if no intersect is found.`
7918 * @param {[number, number, number]} start
7919 * @param {[number, number, number]} end
7920 * @param {[number, number, number]} bmin
7921 * @param {[number, number, number]} bmax
7922 * @returns {[number, number, number] | []}
7923 */
7924 function raytrace_box(start, end, bmin = [0, 0, 0], bmax = [1, 1, 1]) {
7925 // Use slab method to detect intersection of ray and box and return intersect.
7926 // https://en.wikipedia.org/wiki/Slab_method
7927
7928 // Calculate whether there was a hit
7929 let tfar = Infinity;
7930 let tnear = -Infinity;
7931 let direction = [];
7932 for (let i = 0; i < 3; i++) {
7933 const a = start[i];
7934 const b = end[i];
7935 const d = b - a;
7936 const bn = bmin[i];
7937 const bx = bmax[i];
7938 direction.push(d);
7939
7940 // Non parallel cases
7941 if (Math.abs(d) > 1e-12) {
7942 const inv_d = 1 / d;
7943 const t1 = (bn - a) * inv_d;
7944 const t2 = (bx - a) * inv_d;
7945 tnear = Math.max(Math.min(t1, t2), tnear);
7946 tfar = Math.min(Math.max(t1, t2), tfar);
7947 }
7948
7949 // Impossible parallel case
7950 else if (a < bn || a > bx) {
7951 return [];
7952 }
7953 }
7954
7955 // No hit
7956 if (tnear > tfar || tfar < 0) {
7957 return [];
7958 }
7959
7960 // Favor the intersection first in the direction start -> end
7961 if (tnear < 0) {
7962 tnear = tfar;
7963 }
7964
7965 // A point, or something approaching a single point where start and end are the same.
7966 if (!isFinite(tnear)) {
7967 return [];
7968 }
7969
7970 // Calculate nearest intersection via interpolation
7971 return [start[0] + direction[0] * tnear, start[1] + direction[1] * tnear, start[2] + direction[2] * tnear];
7972 }
7973
7974 /**
7975 * Given a color `origin`, returns a new color that is in gamut using
7976 * the CSS Ray Trace Gamut Mapping Algorithm. If `space` is specified,
7977 * it will be in gamut `space`, and returned in `space`. Otherwise,
7978 * it will be in gamut and returned in the color space of `origin`.
7979 * @param {ColorTypes} origin
7980 * @param {{ space?: string | ColorSpace | undefined }} options
7981 * @returns {PlainColorObject}
7982 */
7983 function toGamutRayTrace(origin, {
7984 space
7985 } = {}) {
7986 origin = getColor(origin);
7987 if (!space) {
7988 space = origin.space;
7989 }
7990 space = ColorSpace.get(space);
7991
7992 // If the space is already in gamut, stop.
7993 if (space.isUnbounded) {
7994 return to(origin, space);
7995 }
7996
7997 // Get the OkLCh coordinates.
7998 let oklchOrigin = to(origin, OKLCH);
7999 let [lightness, chroma, hue] = oklchOrigin.coords;
8000
8001 // Return white or black if color's lightness exceeds the SDR range.
8002 if (lightness >= 1) {
8003 const white = to(COLORS.WHITE, space);
8004 white.alpha = origin.alpha;
8005 return to(white, space);
8006 } else if (lightness <= 0) {
8007 const black = to(COLORS.BLACK, space);
8008 black.alpha = origin.alpha;
8009 return to(black, space);
8010 }
8011
8012 // Get a copy of the origin color as the RGB target space.
8013 const originSpace = space;
8014 const rGamut = space.rgbGamut;
8015 if (rGamut !== undefined) {
8016 space = rGamut;
8017 }
8018 if (!isInstance(space, RGBColorSpace)) {
8019 throw Error("An RGB gamut is required");
8020 }
8021
8022 // Get SDR bounds. Some HDR spaces have headroom, so reduce max to SDR range.
8023 let [mn, mx] = Object.values(space.coords)[0].range;
8024 let max = /** @type {[number, number, number]} */[mx, mx, mx];
8025
8026 // See if we have a linear version of the color space
8027 const lGamut = space.linearGamut;
8028 if (lGamut !== undefined) {
8029 // Recalculate minimum and maximum relative to the linear space
8030 let temp = to({
8031 space: space,
8032 coords: max,
8033 alpha: origin.alpha
8034 }, lGamut);
8035 mx = temp.coords[0];
8036 max = /** @type {[number, number, number]} */[mx, mx, mx];
8037 space = lGamut;
8038 mn = Object.values(space.coords)[0].range[0];
8039 }
8040 let min = /** @type {[number, number, number]} */[mn, mn, mn];
8041 let rgbOrigin = to(oklchOrigin, space);
8042 if (!rgbOrigin.coords.every(x => mn <= x && x <= mx)) {
8043 // If this were performed within a perceptual space like CAM16, which has achromatics that do not align
8044 // with the RGB achromatic line, projecting the color onto the RGB achromatic line may be preferable,
8045 // but since OkLCh's achromatics align with all CSS RGB spaces, just set chroma to zero.
8046 let anchor = to({
8047 space: OKLCH,
8048 coords: [lightness, 0, hue]
8049 }, space).coords;
8050
8051 // Calculate bounds to adjust the anchor closer to the gamut surface.
8052 // We don't want to make the ray too short, so offset some amount from the low and high range.
8053 const low = mn + 1e-6;
8054 const high = mx - 1e-6;
8055
8056 // Cast a ray from the zero chroma color to the target color.
8057 // Trace the line to the RGB cube edge and find where it intersects.
8058 // Correct L and h within the perceptual OkLCh after each attempt.
8059 let last = rgbOrigin.coords;
8060 for (let i = 0; i < 4; i++) {
8061 if (i) {
8062 // For constant luminance, we correct the color by simply setting lightness and hue to
8063 // match the original color. In a non constant luminance reduction, it is better to
8064 // project the color onto the reduction path vector.
8065 const oklchColor = to(rgbOrigin, OKLCH);
8066 oklchColor.coords[0] = lightness;
8067 oklchColor.coords[2] = hue;
8068 rgbOrigin = to(oklchColor, space);
8069 }
8070 // Cast a ray from the achromatic anchor to the RGB target and find the gamut intersection.
8071 const intersection = raytrace_box(anchor, rgbOrigin.coords, min, max);
8072
8073 // If we cannot find an intersection, reset to last successful iteration of the color.
8074 // In OkLCh, this is only likely to happen if our ray gets too small, in that case, it is time to stop.
8075 if (intersection.length === 0) {
8076 rgbOrigin.coords = [...last];
8077 break;
8078 }
8079
8080 // Adjust anchor point closer to surface, when possible, to improve results for some spaces.
8081 if (i && rgbOrigin.coords.every(x => low < x && x < high)) {
8082 anchor = [...rgbOrigin.coords];
8083 }
8084
8085 // If we have an intersection, update the color.
8086 last = /** @type {[number, number, number]} */intersection;
8087 rgbOrigin.coords = [...intersection];
8088 }
8089 }
8090
8091 // Convert to the original, specified gamut
8092 rgbOrigin = to(rgbOrigin, originSpace);
8093 const spaceCoords = Object.values(/** @type {ColorSpace} */originSpace.coords);
8094
8095 // Remove noise from floating point math by clipping
8096 rgbOrigin.coords = /** @type {[number, number, number]} */
8097 rgbOrigin.coords.map((coord, index) => {
8098 if ("range" in spaceCoords[index]) {
8099 const [lower, upper] = spaceCoords[index].range;
8100 return clamp(lower, coord, upper);
8101 }
8102 return coord;
8103 });
8104 return rgbOrigin;
8105 }
8106
8107 /** @import { ColorTypes, PlainColorObject, ToGamutOptions } from "./types.js" */
8108
8109 /**
8110 * Convert to color space and return a new color
8111 * @param {ColorTypes} color
8112 * @param {string | ColorSpace} space
8113 * @param {{ inGamut?: boolean | ToGamutOptions | undefined }} options
8114 * @returns {PlainColorObject}
8115 */
8116 function to(color, space, {
8117 inGamut
8118 } = {}) {
8119 color = getColor(color);
8120 space = ColorSpace.get(space);
8121 let coords = space.from(color);
8122 let ret = {
8123 space,
8124 coords,
8125 alpha: color.alpha
8126 };
8127 if (inGamut) {
8128 ret = toGamut(ret, inGamut === true ? undefined : inGamut);
8129 }
8130 return ret;
8131 }
8132
8133 /** @type {"color"} */
8134 to.returns = "color";
8135
8136 /** @import { ColorTypes, ParseOptions, PlainColorObject } from "./types.js" */
8137
8138 // Type re-exports
8139 /** @typedef {import("./types.js").SerializeOptions} SerializeOptions */
8140
8141 /**
8142 * Generic toString() method, outputs a color(spaceId ...coords) function, a functional syntax, or custom formats defined by the color space
8143 * @param {ColorTypes} color
8144 * @param {SerializeOptions & Record<string, any>} options
8145 * @returns {string}
8146 */
8147 function serialize(color, options = {}) {
8148 let {
8149 precision = defaults.precision,
8150 format,
8151 inGamut: inGamut$1 = true,
8152 coords: coordFormat,
8153 alpha: alphaFormat,
8154 commas
8155 } = options;
8156 let ret;
8157 let colorWithMeta = /** @type {PlainColorObject & ParseOptions} */getColor(color);
8158 let formatId = format;
8159 let parseMeta = colorWithMeta.parseMeta;
8160 if (parseMeta && !format) {
8161 var _coordFormat, _alphaFormat, _commas;
8162 if (parseMeta.format.canSerialize()) {
8163 format = parseMeta.format;
8164 formatId = parseMeta.formatId;
8165 }
8166 (_coordFormat = coordFormat) !== null && _coordFormat !== void 0 ? _coordFormat : coordFormat = parseMeta.types;
8167 (_alphaFormat = alphaFormat) !== null && _alphaFormat !== void 0 ? _alphaFormat : alphaFormat = parseMeta.alphaType;
8168 (_commas = commas) !== null && _commas !== void 0 ? _commas : commas = parseMeta.commas;
8169 }
8170 if (formatId) {
8171 var _colorWithMeta$space$;
8172 // A format is explicitly specified
8173 format = (_colorWithMeta$space$ = colorWithMeta.space.getFormat(format)) !== null && _colorWithMeta$space$ !== void 0 ? _colorWithMeta$space$ : ColorSpace.findFormat(formatId);
8174 }
8175 if (!format) {
8176 var _colorWithMeta$space$2;
8177 // No format specified, or format not found
8178 format = (_colorWithMeta$space$2 = colorWithMeta.space.getFormat("default")) !== null && _colorWithMeta$space$2 !== void 0 ? _colorWithMeta$space$2 : ColorSpace.DEFAULT_FORMAT;
8179 formatId = format.name;
8180 }
8181 if (format && format.space && format.space !== colorWithMeta.space) {
8182 // Format specified belongs to a different color space,
8183 // need to convert to it first
8184 colorWithMeta = to(colorWithMeta, format.space);
8185 }
8186
8187 // The assignment to coords and inGamut needs to stay in the order they are now
8188 // The order of the assignment was changed as a workaround for a bug in Next.js
8189 // See this issue for details: https://github.com/color-js/color.js/issues/260
8190
8191 let coords = colorWithMeta.coords.slice(); // clone so we can manipulate it
8192
8193 inGamut$1 || (inGamut$1 = format.toGamut);
8194 if (inGamut$1 && !inGamut(colorWithMeta)) {
8195 // FIXME what happens if the color contains none values?
8196 coords = toGamut(clone(colorWithMeta), inGamut$1 === true ? undefined : inGamut$1).coords;
8197 }
8198 if (format.type === "custom") {
8199 if (format.serialize) {
8200 ret = format.serialize(coords, colorWithMeta.alpha, options);
8201 } else {
8202 throw new TypeError(`format ${formatId} can only be used to parse colors, not for serialization`);
8203 }
8204 } else {
8205 var _alphaFormat$type, _alphaFormat2, _alphaFormat3, _alphaFormat4, _commas2;
8206 // Functional syntax
8207 let name = format.name || "color";
8208 let args = format.serializeCoords(coords, precision, coordFormat);
8209 if (name === "color") {
8210 var _format$ids;
8211 // If output is a color() function, add colorspace id as first argument
8212 let cssId = format.id || ((_format$ids = format.ids) === null || _format$ids === void 0 ? void 0 : _format$ids[0]) || colorWithMeta.space.cssId || colorWithMeta.space.id;
8213 args.unshift(cssId);
8214 }
8215
8216 // Serialize alpha?
8217 /** @type {string | number} */
8218 let alpha = colorWithMeta.alpha;
8219 if (alphaFormat !== undefined && !(typeof alphaFormat === "object")) {
8220 alphaFormat = typeof alphaFormat === "string" ? {
8221 type: alphaFormat
8222 } : {
8223 include: alphaFormat
8224 };
8225 }
8226 let alphaType = (_alphaFormat$type = (_alphaFormat2 = alphaFormat) === null || _alphaFormat2 === void 0 ? void 0 : _alphaFormat2.type) !== null && _alphaFormat$type !== void 0 ? _alphaFormat$type : "<number>";
8227 let serializeAlpha = ((_alphaFormat3 = alphaFormat) === null || _alphaFormat3 === void 0 ? void 0 : _alphaFormat3.include) === true || format.alpha === true || ((_alphaFormat4 = alphaFormat) === null || _alphaFormat4 === void 0 ? void 0 : _alphaFormat4.include) !== false && format.alpha !== false && alpha < 1;
8228 let strAlpha = "";
8229 (_commas2 = commas) !== null && _commas2 !== void 0 ? _commas2 : commas = format.commas;
8230 if (serializeAlpha) {
8231 if (precision !== null) {
8232 let unit;
8233 if (alphaType === "<percentage>") {
8234 unit = "%";
8235 alpha *= 100;
8236 }
8237 alpha = serializeNumber(alpha, {
8238 precision,
8239 unit
8240 });
8241 }
8242 strAlpha = `${commas ? "," : " /"} ${alpha}`;
8243 }
8244 ret = `${name}(${args.join(commas ? ", " : " ")}${strAlpha})`;
8245 }
8246 return ret;
8247 }
8248
8249 var esnext_iterator_filter = {};
8250
8251 var es_iterator_filter = {};
8252
8253 var hasRequiredEs_iterator_filter;
8254
8255 function requireEs_iterator_filter () {
8256 if (hasRequiredEs_iterator_filter) return es_iterator_filter;
8257 hasRequiredEs_iterator_filter = 1;
8258 var $ = require_export();
8259 var call = requireFunctionCall();
8260 var aCallable = requireACallable();
8261 var anObject = requireAnObject();
8262 var getIteratorDirect = requireGetIteratorDirect();
8263 var createIteratorProxy = requireIteratorCreateProxy();
8264 var callWithSafeIterationClosing = requireCallWithSafeIterationClosing();
8265 var IS_PURE = requireIsPure();
8266
8267 var IteratorProxy = createIteratorProxy(function () {
8268 var iterator = this.iterator;
8269 var predicate = this.predicate;
8270 var next = this.next;
8271 var result, done, value;
8272 while (true) {
8273 result = anObject(call(next, iterator));
8274 done = this.done = !!result.done;
8275 if (done) return;
8276 value = result.value;
8277 if (callWithSafeIterationClosing(iterator, predicate, [value, this.counter++], true)) return value;
8278 }
8279 });
8280
8281 // `Iterator.prototype.filter` method
8282 // https://tc39.es/ecma262/#sec-iterator.prototype.filter
8283 $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
8284 filter: function filter(predicate) {
8285 anObject(this);
8286 aCallable(predicate);
8287 return new IteratorProxy(getIteratorDirect(this), {
8288 predicate: predicate
8289 });
8290 }
8291 });
8292 return es_iterator_filter;
8293 }
8294
8295 var hasRequiredEsnext_iterator_filter;
8296
8297 function requireEsnext_iterator_filter () {
8298 if (hasRequiredEsnext_iterator_filter) return esnext_iterator_filter;
8299 hasRequiredEsnext_iterator_filter = 1;
8300 // TODO: Remove from `core-js@4`
8301 requireEs_iterator_filter();
8302 return esnext_iterator_filter;
8303 }
8304
8305 requireEsnext_iterator_filter();
8306
8307 /** @import { Matrix3x3 } from "../types.js" */
8308
8309 // convert an array of linear-light rec2020 values to CIE XYZ
8310 // using D65 (no chromatic adaptation)
8311 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
8312 // 0 is actually calculated as 4.994106574466076e-17
8313 /** @type {Matrix3x3} */
8314 // prettier-ignore
8315 const toXYZ_M$5 = [[0.6369580483012914, 0.14461690358620832, 0.1688809751641721], [0.2627002120112671, 0.6779980715188708, 0.05930171646986196], [0.000000000000000, 0.028072693049087428, 1.060985057710791]];
8316
8317 // from ITU-R BT.2124-0 Annex 2 p.3
8318 /** @type {Matrix3x3} */
8319 // prettier-ignore
8320 const fromXYZ_M$5 = [[1.716651187971268, -0.355670783776392, -0.253366281373660], [-0.666684351832489, 1.616481236634939, 0.0157685458139111], [0.017639857445311, -0.042770613257809, 0.942103121235474]];
8321 var REC_2020_Linear = new RGBColorSpace({
8322 id: "rec2020-linear",
8323 cssId: "--rec2020-linear",
8324 name: "Linear REC.2020",
8325 white: "D65",
8326 toXYZ_M: toXYZ_M$5,
8327 fromXYZ_M: fromXYZ_M$5
8328 });
8329
8330 // import sRGB from "./srgb.js";
8331
8332 var REC2020 = new RGBColorSpace({
8333 id: "rec2020",
8334 name: "REC.2020",
8335 base: REC_2020_Linear,
8336 linearGamut: REC_2020_Linear,
8337 // Reference electro-optical transfer function from Rec. ITU-R BT.1886 Annex 1
8338 // with b (black lift) = 0 and a (user gain) = 1
8339 // defined over the extended range, not clamped
8340 toBase(RGB) {
8341 return RGB.map(function (val) {
8342 let sign = val < 0 ? -1 : 1;
8343 let abs = val * sign;
8344 return sign * Math.pow(abs, 2.4);
8345 });
8346 },
8347 fromBase(RGB) {
8348 return RGB.map(function (val) {
8349 let sign = val < 0 ? -1 : 1;
8350 let abs = val * sign;
8351 return sign * Math.pow(abs, 1 / 2.4);
8352 });
8353 }
8354 });
8355
8356 /** @import { Matrix3x3 } from "../types.js" */
8357
8358 /** @type {Matrix3x3} */
8359 // prettier-ignore
8360 const toXYZ_M$4 = [[0.4865709486482162, 0.26566769316909306, 0.1982172852343625], [0.2289745640697488, 0.6917385218365064, 0.079286914093745], [0.0000000000000000, 0.04511338185890264, 1.043944368900976]];
8361
8362 /** @type {Matrix3x3} */
8363 // prettier-ignore
8364 const fromXYZ_M$4 = [[2.493496911941425, -0.9313836179191239, -0.40271078445071684], [-0.8294889695615747, 1.7626640603183463, 0.023624685841943577], [0.03584583024378447, -0.07617238926804182, 0.9568845240076872]];
8365 var P3Linear = new RGBColorSpace({
8366 id: "p3-linear",
8367 cssId: "display-p3-linear",
8368 name: "Linear P3",
8369 white: "D65",
8370 toXYZ_M: toXYZ_M$4,
8371 fromXYZ_M: fromXYZ_M$4
8372 });
8373
8374 /** @import { Matrix3x3 } from "../types.js" */
8375
8376 // This is the linear-light version of sRGB
8377 // as used for example in SVG filters
8378 // or in Canvas
8379
8380 // This matrix was calculated directly from the RGB and white chromaticities
8381 // when rounded to 8 decimal places, it agrees completely with the official matrix
8382 // see https://github.com/w3c/csswg-drafts/issues/5922
8383 /** @type {Matrix3x3} */
8384 // prettier-ignore
8385 const toXYZ_M$3 = [[0.41239079926595934, 0.357584339383878, 0.1804807884018343], [0.21263900587151027, 0.715168678767756, 0.07219231536073371], [0.01933081871559182, 0.11919477979462598, 0.9505321522496607]];
8386
8387 // This matrix is the inverse of the above;
8388 // again it agrees with the official definition when rounded to 8 decimal places
8389 /** @type {Matrix3x3} */
8390 // prettier-ignore
8391 const fromXYZ_M$3 = [[3.2409699419045226, -1.537383177570094, -0.4986107602930034], [-0.9692436362808796, 1.8759675015077202, 0.04155505740717559], [0.05563007969699366, -0.20397695888897652, 1.0569715142428786]];
8392 var sRGBLinear = new RGBColorSpace({
8393 id: "srgb-linear",
8394 name: "Linear sRGB",
8395 white: "D65",
8396 toXYZ_M: toXYZ_M$3,
8397 fromXYZ_M: fromXYZ_M$3
8398 });
8399
8400 // To produce: Visit https://www.w3.org/TR/css-color-4/#named-colors
8401 // and run in the console:
8402 // copy($$("tr", $(".named-color-table tbody")).map(tr => `"${tr.cells[2].textContent.trim()}": [${tr.cells[4].textContent.trim().split(/\s+/).map(c => c === "0"? "0" : c === "255"? "1" : c + " / 255").join(", ")}]`).join(",\n"))
8403
8404 /** List of CSS color keywords
8405 * Note that this does not include currentColor, transparent,
8406 * or system colors
8407 *
8408 * @type {Record<string, [number, number, number]>}
8409 */
8410 var KEYWORDS = {
8411 aliceblue: [240 / 255, 248 / 255, 1],
8412 antiquewhite: [250 / 255, 235 / 255, 215 / 255],
8413 aqua: [0, 1, 1],
8414 aquamarine: [127 / 255, 1, 212 / 255],
8415 azure: [240 / 255, 1, 1],
8416 beige: [245 / 255, 245 / 255, 220 / 255],
8417 bisque: [1, 228 / 255, 196 / 255],
8418 black: [0, 0, 0],
8419 blanchedalmond: [1, 235 / 255, 205 / 255],
8420 blue: [0, 0, 1],
8421 blueviolet: [138 / 255, 43 / 255, 226 / 255],
8422 brown: [165 / 255, 42 / 255, 42 / 255],
8423 burlywood: [222 / 255, 184 / 255, 135 / 255],
8424 cadetblue: [95 / 255, 158 / 255, 160 / 255],
8425 chartreuse: [127 / 255, 1, 0],
8426 chocolate: [210 / 255, 105 / 255, 30 / 255],
8427 coral: [1, 127 / 255, 80 / 255],
8428 cornflowerblue: [100 / 255, 149 / 255, 237 / 255],
8429 cornsilk: [1, 248 / 255, 220 / 255],
8430 crimson: [220 / 255, 20 / 255, 60 / 255],
8431 cyan: [0, 1, 1],
8432 darkblue: [0, 0, 139 / 255],
8433 darkcyan: [0, 139 / 255, 139 / 255],
8434 darkgoldenrod: [184 / 255, 134 / 255, 11 / 255],
8435 darkgray: [169 / 255, 169 / 255, 169 / 255],
8436 darkgreen: [0, 100 / 255, 0],
8437 darkgrey: [169 / 255, 169 / 255, 169 / 255],
8438 darkkhaki: [189 / 255, 183 / 255, 107 / 255],
8439 darkmagenta: [139 / 255, 0, 139 / 255],
8440 darkolivegreen: [85 / 255, 107 / 255, 47 / 255],
8441 darkorange: [1, 140 / 255, 0],
8442 darkorchid: [153 / 255, 50 / 255, 204 / 255],
8443 darkred: [139 / 255, 0, 0],
8444 darksalmon: [233 / 255, 150 / 255, 122 / 255],
8445 darkseagreen: [143 / 255, 188 / 255, 143 / 255],
8446 darkslateblue: [72 / 255, 61 / 255, 139 / 255],
8447 darkslategray: [47 / 255, 79 / 255, 79 / 255],
8448 darkslategrey: [47 / 255, 79 / 255, 79 / 255],
8449 darkturquoise: [0, 206 / 255, 209 / 255],
8450 darkviolet: [148 / 255, 0, 211 / 255],
8451 deeppink: [1, 20 / 255, 147 / 255],
8452 deepskyblue: [0, 191 / 255, 1],
8453 dimgray: [105 / 255, 105 / 255, 105 / 255],
8454 dimgrey: [105 / 255, 105 / 255, 105 / 255],
8455 dodgerblue: [30 / 255, 144 / 255, 1],
8456 firebrick: [178 / 255, 34 / 255, 34 / 255],
8457 floralwhite: [1, 250 / 255, 240 / 255],
8458 forestgreen: [34 / 255, 139 / 255, 34 / 255],
8459 fuchsia: [1, 0, 1],
8460 gainsboro: [220 / 255, 220 / 255, 220 / 255],
8461 ghostwhite: [248 / 255, 248 / 255, 1],
8462 gold: [1, 215 / 255, 0],
8463 goldenrod: [218 / 255, 165 / 255, 32 / 255],
8464 gray: [128 / 255, 128 / 255, 128 / 255],
8465 green: [0, 128 / 255, 0],
8466 greenyellow: [173 / 255, 1, 47 / 255],
8467 grey: [128 / 255, 128 / 255, 128 / 255],
8468 honeydew: [240 / 255, 1, 240 / 255],
8469 hotpink: [1, 105 / 255, 180 / 255],
8470 indianred: [205 / 255, 92 / 255, 92 / 255],
8471 indigo: [75 / 255, 0, 130 / 255],
8472 ivory: [1, 1, 240 / 255],
8473 khaki: [240 / 255, 230 / 255, 140 / 255],
8474 lavender: [230 / 255, 230 / 255, 250 / 255],
8475 lavenderblush: [1, 240 / 255, 245 / 255],
8476 lawngreen: [124 / 255, 252 / 255, 0],
8477 lemonchiffon: [1, 250 / 255, 205 / 255],
8478 lightblue: [173 / 255, 216 / 255, 230 / 255],
8479 lightcoral: [240 / 255, 128 / 255, 128 / 255],
8480 lightcyan: [224 / 255, 1, 1],
8481 lightgoldenrodyellow: [250 / 255, 250 / 255, 210 / 255],
8482 lightgray: [211 / 255, 211 / 255, 211 / 255],
8483 lightgreen: [144 / 255, 238 / 255, 144 / 255],
8484 lightgrey: [211 / 255, 211 / 255, 211 / 255],
8485 lightpink: [1, 182 / 255, 193 / 255],
8486 lightsalmon: [1, 160 / 255, 122 / 255],
8487 lightseagreen: [32 / 255, 178 / 255, 170 / 255],
8488 lightskyblue: [135 / 255, 206 / 255, 250 / 255],
8489 lightslategray: [119 / 255, 136 / 255, 153 / 255],
8490 lightslategrey: [119 / 255, 136 / 255, 153 / 255],
8491 lightsteelblue: [176 / 255, 196 / 255, 222 / 255],
8492 lightyellow: [1, 1, 224 / 255],
8493 lime: [0, 1, 0],
8494 limegreen: [50 / 255, 205 / 255, 50 / 255],
8495 linen: [250 / 255, 240 / 255, 230 / 255],
8496 magenta: [1, 0, 1],
8497 maroon: [128 / 255, 0, 0],
8498 mediumaquamarine: [102 / 255, 205 / 255, 170 / 255],
8499 mediumblue: [0, 0, 205 / 255],
8500 mediumorchid: [186 / 255, 85 / 255, 211 / 255],
8501 mediumpurple: [147 / 255, 112 / 255, 219 / 255],
8502 mediumseagreen: [60 / 255, 179 / 255, 113 / 255],
8503 mediumslateblue: [123 / 255, 104 / 255, 238 / 255],
8504 mediumspringgreen: [0, 250 / 255, 154 / 255],
8505 mediumturquoise: [72 / 255, 209 / 255, 204 / 255],
8506 mediumvioletred: [199 / 255, 21 / 255, 133 / 255],
8507 midnightblue: [25 / 255, 25 / 255, 112 / 255],
8508 mintcream: [245 / 255, 1, 250 / 255],
8509 mistyrose: [1, 228 / 255, 225 / 255],
8510 moccasin: [1, 228 / 255, 181 / 255],
8511 navajowhite: [1, 222 / 255, 173 / 255],
8512 navy: [0, 0, 128 / 255],
8513 oldlace: [253 / 255, 245 / 255, 230 / 255],
8514 olive: [128 / 255, 128 / 255, 0],
8515 olivedrab: [107 / 255, 142 / 255, 35 / 255],
8516 orange: [1, 165 / 255, 0],
8517 orangered: [1, 69 / 255, 0],
8518 orchid: [218 / 255, 112 / 255, 214 / 255],
8519 palegoldenrod: [238 / 255, 232 / 255, 170 / 255],
8520 palegreen: [152 / 255, 251 / 255, 152 / 255],
8521 paleturquoise: [175 / 255, 238 / 255, 238 / 255],
8522 palevioletred: [219 / 255, 112 / 255, 147 / 255],
8523 papayawhip: [1, 239 / 255, 213 / 255],
8524 peachpuff: [1, 218 / 255, 185 / 255],
8525 peru: [205 / 255, 133 / 255, 63 / 255],
8526 pink: [1, 192 / 255, 203 / 255],
8527 plum: [221 / 255, 160 / 255, 221 / 255],
8528 powderblue: [176 / 255, 224 / 255, 230 / 255],
8529 purple: [128 / 255, 0, 128 / 255],
8530 rebeccapurple: [102 / 255, 51 / 255, 153 / 255],
8531 red: [1, 0, 0],
8532 rosybrown: [188 / 255, 143 / 255, 143 / 255],
8533 royalblue: [65 / 255, 105 / 255, 225 / 255],
8534 saddlebrown: [139 / 255, 69 / 255, 19 / 255],
8535 salmon: [250 / 255, 128 / 255, 114 / 255],
8536 sandybrown: [244 / 255, 164 / 255, 96 / 255],
8537 seagreen: [46 / 255, 139 / 255, 87 / 255],
8538 seashell: [1, 245 / 255, 238 / 255],
8539 sienna: [160 / 255, 82 / 255, 45 / 255],
8540 silver: [192 / 255, 192 / 255, 192 / 255],
8541 skyblue: [135 / 255, 206 / 255, 235 / 255],
8542 slateblue: [106 / 255, 90 / 255, 205 / 255],
8543 slategray: [112 / 255, 128 / 255, 144 / 255],
8544 slategrey: [112 / 255, 128 / 255, 144 / 255],
8545 snow: [1, 250 / 255, 250 / 255],
8546 springgreen: [0, 1, 127 / 255],
8547 steelblue: [70 / 255, 130 / 255, 180 / 255],
8548 tan: [210 / 255, 180 / 255, 140 / 255],
8549 teal: [0, 128 / 255, 128 / 255],
8550 thistle: [216 / 255, 191 / 255, 216 / 255],
8551 tomato: [1, 99 / 255, 71 / 255],
8552 turquoise: [64 / 255, 224 / 255, 208 / 255],
8553 violet: [238 / 255, 130 / 255, 238 / 255],
8554 wheat: [245 / 255, 222 / 255, 179 / 255],
8555 white: [1, 1, 1],
8556 whitesmoke: [245 / 255, 245 / 255, 245 / 255],
8557 yellow: [1, 1, 0],
8558 yellowgreen: [154 / 255, 205 / 255, 50 / 255]
8559 };
8560
8561 /** @import { Coords } from "../types.js" */
8562
8563 let coordGrammar = Array(3).fill("<percentage> | <number>[0, 255]");
8564 let coordGrammarNumber = Array(3).fill("<number>[0, 255]");
8565 var sRGB = new RGBColorSpace({
8566 id: "srgb",
8567 name: "sRGB",
8568 base: sRGBLinear,
8569 linearGamut: sRGBLinear,
8570 fromBase: rgb => {
8571 // convert an array of linear-light sRGB values in the range 0.0-1.0
8572 // to gamma corrected form
8573 // https://en.wikipedia.org/wiki/SRGB
8574 return rgb.map(val => {
8575 let sign = val < 0 ? -1 : 1;
8576 let abs = val * sign;
8577 if (abs > 0.0031308) {
8578 return sign * (1.055 * abs ** (1 / 2.4) - 0.055);
8579 }
8580 return 12.92 * val;
8581 });
8582 },
8583 toBase: rgb => {
8584 // convert an array of sRGB values in the range 0.0 - 1.0
8585 // to linear light (un-companded) form.
8586 // https://en.wikipedia.org/wiki/SRGB
8587 return rgb.map(val => {
8588 let sign = val < 0 ? -1 : 1;
8589 let abs = val * sign;
8590 if (abs <= 0.04045) {
8591 return val / 12.92;
8592 }
8593 return sign * ((abs + 0.055) / 1.055) ** 2.4;
8594 });
8595 },
8596 formats: {
8597 rgb: {
8598 coords: coordGrammar
8599 },
8600 rgb_number: {
8601 name: "rgb",
8602 commas: true,
8603 coords: coordGrammarNumber,
8604 alpha: false
8605 },
8606 color: {
8607 /* use defaults */
8608 },
8609 rgba: {
8610 coords: coordGrammar,
8611 commas: true,
8612 alpha: true
8613 },
8614 rgba_number: {
8615 name: "rgba",
8616 commas: true,
8617 coords: coordGrammarNumber
8618 },
8619 hex: {
8620 type: "custom",
8621 toGamut: true,
8622 test: str => /^#(([a-f0-9]{2}){3,4}|[a-f0-9]{3,4})$/i.test(str),
8623 parse(str) {
8624 if (str.length <= 5) {
8625 // #rgb or #rgba, duplicate digits
8626 str = str.replace(/[a-f0-9]/gi, "$&$&");
8627 }
8628
8629 /** @type {number[]} */
8630 let rgba = [];
8631 // @ts-expect-error Type 'void' is not assignable to type 'string'
8632 str.replace(/[a-f0-9]{2}/gi, component => {
8633 rgba.push(parseInt(component, 16) / 255);
8634 });
8635 return {
8636 spaceId: "srgb",
8637 coords: (/** @type {Coords} */rgba.slice(0, 3)),
8638 alpha: (/** @type {number} */rgba.slice(3)[0])
8639 };
8640 },
8641 serialize: (coords, alpha, {
8642 collapse = true,
8643 // collapse to 3-4 digit hex when possible?
8644 alpha: alphaFormat
8645 } = {}) => {
8646 if (alphaFormat !== false && alpha < 1 || alphaFormat === true) {
8647 coords.push(alpha);
8648 }
8649 coords = /** @type {[number, number, number]} */
8650 coords.map(c => Math.round(c * 255));
8651 let collapsible = collapse && coords.every(c => c % 17 === 0);
8652 let hex = coords.map(c => {
8653 if (collapsible) {
8654 return (c / 17).toString(16);
8655 }
8656 return c.toString(16).padStart(2, "0");
8657 }).join("");
8658 return "#" + hex;
8659 }
8660 },
8661 keyword: {
8662 type: "custom",
8663 test: str => /^[a-z]+$/i.test(str),
8664 parse(str) {
8665 str = str.toLowerCase();
8666 let ret = {
8667 spaceId: "srgb",
8668 coords: null,
8669 alpha: 1
8670 };
8671 if (str === "transparent") {
8672 ret.coords = KEYWORDS.black;
8673 ret.alpha = 0;
8674 } else {
8675 ret.coords = KEYWORDS[str];
8676 }
8677 if (ret.coords) {
8678 return ret;
8679 }
8680 }
8681 }
8682 }
8683 });
8684
8685 var P3 = new RGBColorSpace({
8686 id: "p3",
8687 cssId: "display-p3",
8688 name: "P3",
8689 base: P3Linear,
8690 linearGamut: P3Linear,
8691 // Gamma encoding/decoding is the same as sRGB
8692 fromBase: sRGB.fromBase,
8693 toBase: sRGB.toBase
8694 });
8695
8696 /** @import ColorSpace from "./ColorSpace.js" */
8697 /** @import { ColorTypes, PlainColorObject, DisplayOptions } from "./types.js" */
8698
8699 // Type re-exports
8700 /** @typedef {import("./types.js").Display} Display */
8701
8702 // Default space for CSS output. Code in Color.js makes this wider if there's a DOM available
8703 defaults.display_space = sRGB;
8704 let supportsNone;
8705 if (typeof CSS !== "undefined" && CSS.supports) {
8706 // Find widest supported color space for CSS
8707 for (let space of [lab, REC2020, P3]) {
8708 let coords = space.getMinCoords();
8709 let color = {
8710 space,
8711 coords,
8712 alpha: 1
8713 };
8714 let str = serialize(color);
8715 if (CSS.supports("color", str)) {
8716 defaults.display_space = space;
8717 break;
8718 }
8719 }
8720 }
8721
8722 /**
8723 * Returns a serialization of the color that can actually be displayed in the browser.
8724 * If the default serialization can be displayed, it is returned.
8725 * Otherwise, if a `space` is given, the color is converted directly to it.
8726 * If not, the color is converted to the first supported of its space's `displaySpaces` (if any),
8727 * else the closest supported space in its base color space chain (which preserves its gamut),
8728 * else the default fallback space (Lab, REC2020, or P3, whichever is the widest supported).
8729 * In Node.js, this is basically equivalent to `serialize()` but returns a `String` object instead.
8730 * @param {ColorTypes} color
8731 * @param {DisplayOptions} [options] Options. Any properties beyond `space` and `supports` are passed to `serialize()`.
8732 * @returns {Display} String object containing the serialized color
8733 * with a color property containing the converted color (or the original, if no conversion was necessary)
8734 */
8735 function display(color, {
8736 space,
8737 supports = (_globalThis$CSS => (_globalThis$CSS = globalThis.CSS) === null || _globalThis$CSS === void 0 ? void 0 : _globalThis$CSS.supports)(),
8738 ...options
8739 } = {}) {
8740 color = getColor(color);
8741 let ret = /** @type {Display} */serialize(color, options);
8742 if (!supports || supports("color", /** @type {string} */ret) || !defaults.display_space) {
8743 ret = /** @type {Display} */new String(ret);
8744 ret.color = /** @type {PlainColorObject} */color;
8745 } else {
8746 // If we're here, what we were about to output is not supported
8747 let fallbackColor = /** @type {PlainColorObject} */color;
8748
8749 // First, check if the culprit is none values
8750 let hasNone = color.coords.some(isNone) || isNone(color.alpha);
8751 if (hasNone) {
8752 var _supportsNone;
8753 // Does the browser support none values?
8754 if (!((_supportsNone = supportsNone) !== null && _supportsNone !== void 0 ? _supportsNone : supportsNone = supports("color", "hsl(none 50% 50%)"))) {
8755 // Nope, try again without none
8756 fallbackColor = clone(/** @type {PlainColorObject} */color);
8757 fallbackColor.coords = /** @type {[number, number, number]} */
8758 fallbackColor.coords.map(skipNone);
8759 fallbackColor.alpha = skipNone(fallbackColor.alpha);
8760
8761 // @ts-expect-error This is set to the correct type later
8762 ret = serialize(fallbackColor, options);
8763 if (supports("color", /** @type {string} */ret)) {
8764 // We're done, now it's supported
8765 ret = /** @type {Display} */new String(ret);
8766 ret.color = fallbackColor;
8767 return ret;
8768 }
8769 }
8770 }
8771
8772 // If we're here, the color function is not supported.
8773 // With no explicit space, try the color's own `displaySpaces`, or else walk up its base
8774 // color space chain (closest first, skipping XYZ connection spaces), and use the first
8775 // space the browser supports, before falling back to the default space.
8776 if (space === undefined) {
8777 var _space$displaySpaces;
8778 space = fallbackColor.space;
8779 let candidates = (_space$displaySpaces = space.displaySpaces) !== null && _space$displaySpaces !== void 0 ? _space$displaySpaces : space.bases;
8780
8781 // Skip XYZ connection spaces (unless the space itself is one, so it still has a fallback).
8782 if (!space.displaySpaces && !space.id.startsWith("xyz-")) {
8783 candidates = candidates.filter(space => !space.id.startsWith("xyz-"));
8784 }
8785 for (let candidate of candidates) {
8786 let candidateColor = to(fallbackColor, candidate);
8787 let str = serialize(candidateColor, options);
8788 if (supports("color", /** @type {string} */str)) {
8789 ret = /** @type {Display} */new String(str);
8790 ret.color = candidateColor;
8791 return ret;
8792 }
8793 }
8794 space = defaults.display_space;
8795 }
8796
8797 // Fall back to fallback space
8798 fallbackColor = to(fallbackColor, /** @type {string | ColorSpace} */space);
8799 ret = /** @type {Display} */new String(serialize(fallbackColor, options));
8800 ret.color = fallbackColor;
8801 }
8802 return ret;
8803 }
8804
8805 /** @import { ColorSpace as ColorSpaceType } from "./types.js" */
8806
8807 // Cell count per coordinate: each keyed coordinate's range is divided into this many cells.
8808 // Calibrated so a cell spans < 1e-4 of chroma for OKLCh + P3 (slopes measured by
8809 // scripts/oklch-gamut-bounds.js); finer precision would not change the result.
8810 const STEPS = 1e6;
8811
8812 // A specialized, memoized maxChroma function per (reduce space, gamut), built lazily on first use
8813 // and keyed by their ids. Each closes over a two-layer digit trie of cached results: the lightness
8814 // key descends the outer trie to a node whose `.h` holds a hue trie, descended in turn to a
8815 // `.value` holding the max chroma. Each key drops its trailing zeros, so a round l or h costs no levels.
8816 /** @typedef {Array<any> & { value?: number }} HueTrie A digit indexes into the next level; `.value` is the max chroma */
8817 /** @typedef {Array<any> & { h?: HueTrie }} LightnessTrie A digit indexes into the next level; `.h` is the hue trie at this lightness */
8818 /** @type {Record<string, Record<string, (l: number, h: number) => number>>} */
8819 const cache = {};
8820
8821 // Significant digits of a ≤ 6-digit integer key (trailing zeros omitted, so round numbers stay shallow)
8822 function digitsOf(n) {
8823 let digits = [];
8824 for (let div = STEPS / 10; n; div /= 10) {
8825 digits.push(Math.floor(n / div));
8826 n %= div;
8827 }
8828 return digits;
8829 }
8830
8831 /**
8832 * Maximum chroma within an RGB gamut for a given lightness and hue, in a polar space's chroma units.
8833 * @param {number} l Lightness, in the reduce space's units
8834 * @param {number} h Hue angle, in degrees
8835 * @param {{ space: string | ColorSpaceType, gamut: string | ColorSpaceType }} options
8836 * `space` is the polar space whose chroma is reduced; `gamut` is the RGB gamut to fit.
8837 * @returns {number}
8838 */
8839 function maxChroma(l, h, {
8840 space,
8841 gamut
8842 }) {
8843 var _cache$space$id, _gamut$id, _cache$space$id$_gamu, _space$id, _cache$_space$id;
8844 space = ColorSpace.get(space);
8845 gamut = ColorSpace.get(gamut);
8846 let fn = (_cache$space$id$_gamu = (_cache$space$id = (_cache$_space$id = cache[_space$id = space.id]) !== null && _cache$_space$id !== void 0 ? _cache$_space$id : cache[_space$id] = {})[_gamut$id = gamut.id]) !== null && _cache$space$id$_gamu !== void 0 ? _cache$space$id$_gamu : _cache$space$id[_gamut$id] = makeMaxChroma(space, gamut);
8847 return fn(l, h);
8848 }
8849
8850 /**
8851 * Build the specialized maxChroma function for one (space, gamut) pair, doing the per-pair setup
8852 * (validation, role identification, ranges) once and capturing it in the returned closure.
8853 * @param {ColorSpaceType} space Resolved polar space whose chroma is reduced
8854 * @param {ColorSpaceType} gamut Resolved RGB gamut to fit
8855 * @returns {(l: number, h: number) => number}
8856 */
8857 function makeMaxChroma(space, gamut) {
8858 if (!space.isPolar || !("c" in space.coords)) {
8859 throw new TypeError(`maxChroma() needs a polar space with a "c" coordinate, got ${space.id}`);
8860 }
8861
8862 // Identify coordinates by role
8863 let ids = Object.keys(space.coords);
8864 let hueId = ids.find(id => space.coords[id].type === "angle");
8865 let lightnessId = ids.find(id => id !== "c" && id !== hueId);
8866 let range = id => {
8867 var _space$coords$id$rang;
8868 return (_space$coords$id$rang = space.coords[id].range) !== null && _space$coords$id$rang !== void 0 ? _space$coords$id$rang : space.coords[id].refRange;
8869 };
8870 let [lMin, lMax] = range(lightnessId);
8871 let [hMin, hMax] = range(hueId);
8872 let cMax = range("c")[1];
8873 let cIndex = ids.indexOf("c");
8874 let method = `${space.id}.c`;
8875 let root = /** @type {LightnessTrie} */[];
8876 return function (l, h) {
8877 var _lNode2, _lNode2$h, _hNode2, _hNode2$value;
8878 if (l <= lMin || l >= lMax) {
8879 return 0;
8880 }
8881 let lNode = root;
8882 for (let d of digitsOf(Math.floor((l - lMin) / (lMax - lMin) * STEPS))) {
8883 var _lNode, _lNode$d;
8884 lNode = (_lNode$d = (_lNode = lNode)[d]) !== null && _lNode$d !== void 0 ? _lNode$d : _lNode[d] = [];
8885 }
8886 let hNode = (_lNode2$h = (_lNode2 = lNode).h) !== null && _lNode2$h !== void 0 ? _lNode2$h : _lNode2.h = [];
8887 for (let d of digitsOf(Math.floor((constrain(h) - hMin) / (hMax - hMin) * STEPS))) {
8888 var _hNode, _hNode$d;
8889 hNode = (_hNode$d = (_hNode = hNode)[d]) !== null && _hNode$d !== void 0 ? _hNode$d : _hNode[d] = [];
8890 }
8891 let coords = /** @type {[number, number, number]} */
8892 ids.map(id => id === "c" ? cMax : id === hueId ? h : l);
8893 return (_hNode2$value = (_hNode2 = hNode).value) !== null && _hNode2$value !== void 0 ? _hNode2$value : _hNode2.value = toGamut({
8894 space,
8895 coords
8896 },
8897 // deltaE OK stays sensitive near black, where deltaE 2000 is too forgiving of excess chroma
8898 {
8899 space: gamut,
8900 method,
8901 deltaEMethod: "OK",
8902 jnd: 0
8903 }).coords[cIndex];
8904 };
8905 }
8906
8907 /** @import { ColorTypes } from "./types.js" */
8908
8909 // Type re-exports
8910 /** @typedef {import("./types.js").DeltasReturn} DeltasReturn */
8911
8912 /**
8913 * Get color differences per-component, on any color space
8914 * @param {ColorTypes} c1
8915 * @param {ColorTypes} c2
8916 * @param {object} options
8917 * @param {string | ColorSpace} [options.space=c1.space] - The color space to use for the delta calculation. Defaults to the color space of the first color.
8918 * @param {Parameters<typeof adjust>[0]} [options.hue="shorter"] - How to handle hue differences. Same as hue interpolation option.
8919 * @returns {DeltasReturn}
8920 */
8921 function deltas(c1, c2, {
8922 space,
8923 hue = "shorter"
8924 } = {}) {
8925 c1 = getColor(c1);
8926 space || (space = c1.space);
8927 space = ColorSpace.get(space);
8928 let spaceCoords = Object.values(space.coords);
8929 [c1, c2] = [c1, c2].map(c => to(c, space));
8930 let [coords1, coords2] = [c1, c2].map(c => c.coords);
8931 let coords = /** @type {[number, number, number]} */
8932 coords1.map((coord1, i) => {
8933 let coordMeta = spaceCoords[i];
8934 let coord2 = coords2[i];
8935 if (coordMeta.type === "angle") {
8936 [coord1, coord2] = adjust(hue, [coord1, coord2]);
8937 }
8938 return subtractCoords(coord1, coord2);
8939 });
8940 let alpha = subtractCoords(c1.alpha, c2.alpha);
8941 return {
8942 space: (/** @type {ColorSpace} */space),
8943 coords,
8944 alpha
8945 };
8946 }
8947 function subtractCoords(c1, c2) {
8948 if (isNone(c1) || isNone(c2)) {
8949 return c1 === c2 ? null : 0;
8950 }
8951 return c1 - c2;
8952 }
8953
8954 /** @import { ColorTypes } from "./types.js" */
8955
8956 /**
8957 * @param {ColorTypes} color1
8958 * @param {ColorTypes} color2
8959 * @returns {boolean}
8960 */
8961 function equals(color1, color2) {
8962 color1 = getColor(color1);
8963 color2 = getColor(color2);
8964 return color1.space === color2.space && color1.alpha === color2.alpha && color1.coords.every((c, i) => c === color2.coords[i]);
8965 }
8966
8967 /**
8968 * Relative luminance
8969 */
8970
8971 /** @import { ColorTypes } from "./types.js" */
8972
8973 /**
8974 *
8975 * @param {ColorTypes} color
8976 * @returns {number}
8977 */
8978 function getLuminance(color) {
8979 // Assume getColor() is called on color in get()
8980 return get(color, [XYZ_D65, "y"]);
8981 }
8982
8983 /**
8984 * @param {ColorTypes} color
8985 * @param {number | ((coord: number) => number)} value
8986 */
8987 function setLuminance(color, value) {
8988 // Assume getColor() is called on color in set()
8989 set(color, [XYZ_D65, "y"], value);
8990 }
8991
8992 /**
8993 * @param {typeof import("./color.js").default} Color
8994 */
8995 function register$2(Color) {
8996 Object.defineProperty(Color.prototype, "luminance", {
8997 get() {
8998 return getLuminance(this);
8999 },
9000 set(value) {
9001 setLuminance(this, value);
9002 }
9003 });
9004 }
9005
9006 var luminance = /*#__PURE__*/Object.freeze({
9007 __proto__: null,
9008 getLuminance: getLuminance,
9009 register: register$2,
9010 setLuminance: setLuminance
9011 });
9012
9013 // WCAG 2.0 contrast https://www.w3.org/TR/WCAG20-TECHS/G18.html
9014 // Simple contrast, with fixed 5% viewing flare contribution
9015 // Symmetric, does not matter which is foreground and which is background
9016
9017
9018 /**
9019 * @param {import("../types.js").ColorTypes} color1
9020 * @param {import("../types.js").ColorTypes} color2
9021 * @returns {number}
9022 */
9023 function contrastWCAG21(color1, color2) {
9024 color1 = getColor(color1);
9025 color2 = getColor(color2);
9026 let Y1 = Math.max(getLuminance(color1), 0);
9027 let Y2 = Math.max(getLuminance(color2), 0);
9028 if (Y2 > Y1) {
9029 [Y1, Y2] = [Y2, Y1];
9030 }
9031 return (Y1 + 0.05) / (Y2 + 0.05);
9032 }
9033
9034 // exponents
9035 const normBG = 0.56;
9036 const normTXT = 0.57;
9037 const revTXT = 0.62;
9038 const revBG = 0.65;
9039
9040 // clamps
9041 const blkThrs = 0.022;
9042 const blkClmp = 1.414;
9043 const loClip = 0.1;
9044 const deltaYmin = 0.0005;
9045
9046 // scalers
9047 // see https://github.com/w3c/silver/issues/645
9048 const scaleBoW = 1.14;
9049 const loBoWoffset = 0.027;
9050 const scaleWoB = 1.14;
9051 function fclamp(Y) {
9052 if (Y >= blkThrs) {
9053 return Y;
9054 }
9055 return Y + (blkThrs - Y) ** blkClmp;
9056 }
9057 function linearize(val) {
9058 let sign = val < 0 ? -1 : 1;
9059 let abs = Math.abs(val);
9060 return sign * Math.pow(abs, 2.4);
9061 }
9062
9063 /**
9064 * Not symmetric, requires a foreground (text) color, and a background color
9065 * @param {import("../types.js").ColorTypes} background
9066 * @param {import("../types.js").ColorTypes} foreground
9067 * @returns {number}
9068 */
9069 function contrastAPCA(background, foreground) {
9070 foreground = getColor(foreground);
9071 background = getColor(background);
9072 let S;
9073 let C;
9074 let Sapc;
9075
9076 // Myndex as-published, assumes sRGB inputs
9077 let R, G, B;
9078 foreground = to(foreground, "srgb");
9079 // Should these be clamped to in-gamut values?
9080
9081 // Calculates "screen luminance" with non-standard simple gamma EOTF
9082 // weights should be from CSS Color 4, not the ones here which are via Myndex and copied from Lindbloom
9083 [R, G, B] = foreground.coords.map(c => {
9084 return isNone(c) ? 0 : c;
9085 });
9086 let lumTxt = linearize(R) * 0.2126729 + linearize(G) * 0.7151522 + linearize(B) * 0.072175;
9087 background = to(background, "srgb");
9088 [R, G, B] = background.coords.map(c => {
9089 return isNone(c) ? 0 : c;
9090 });
9091 let lumBg = linearize(R) * 0.2126729 + linearize(G) * 0.7151522 + linearize(B) * 0.072175;
9092
9093 // toe clamping of very dark values to account for flare
9094 let Ytxt = fclamp(lumTxt);
9095 let Ybg = fclamp(lumBg);
9096
9097 // are we "Black on White" (dark on light), or light on dark?
9098 let BoW = Ybg > Ytxt;
9099
9100 // why is this a delta, when Y is not perceptually uniform?
9101 // Answer: it is a noise gate, see
9102 // https://github.com/LeaVerou/color.js/issues/208
9103 if (Math.abs(Ybg - Ytxt) < deltaYmin) {
9104 C = 0;
9105 } else {
9106 if (BoW) {
9107 // dark text on light background
9108 S = Ybg ** normBG - Ytxt ** normTXT;
9109 C = S * scaleBoW;
9110 } else {
9111 // light text on dark background
9112 S = Ybg ** revBG - Ytxt ** revTXT;
9113 C = S * scaleWoB;
9114 }
9115 }
9116 if (Math.abs(C) < loClip) {
9117 Sapc = 0;
9118 } else if (C > 0) {
9119 // not clear whether Woffset is loBoWoffset or loWoBoffset
9120 // but they have the same value
9121 Sapc = C - loBoWoffset;
9122 } else {
9123 Sapc = C + loBoWoffset;
9124 }
9125 return Sapc * 100;
9126 }
9127
9128 // Michelson luminance contrast
9129 // the relation between the spread and the sum of the two luminances
9130 // Symmetric, does not matter which is foreground and which is background
9131 // No black level compensation for flare.
9132
9133
9134 /**
9135 * @param {import("../types.js").ColorTypes} color1
9136 * @param {import("../types.js").ColorTypes} color2
9137 * @returns {number}
9138 */
9139 function contrastMichelson(color1, color2) {
9140 color1 = getColor(color1);
9141 color2 = getColor(color2);
9142 let Y1 = Math.max(getLuminance(color1), 0);
9143 let Y2 = Math.max(getLuminance(color2), 0);
9144 if (Y2 > Y1) {
9145 [Y1, Y2] = [Y2, Y1];
9146 }
9147 let denom = Y1 + Y2;
9148 return denom === 0 ? 0 : (Y1 - Y2) / denom;
9149 }
9150
9151 // Weber luminance contrast
9152 // The difference between the two luminances divided by the lower luminance
9153 // Symmetric, does not matter which is foreground and which is background
9154 // No black level compensation for flare.
9155
9156
9157 // the darkest sRGB color above black is #000001 and this produces
9158 // a plain Weber contrast of ~45647.
9159 // So, setting the divide-by-zero result at 50000 is a reasonable
9160 // max clamp for the plain Weber
9161 const max = 50000;
9162
9163 /**
9164 * @param {import("../types.js").ColorTypes} color1
9165 * @param {import("../types.js").ColorTypes} color2
9166 * @returns {number}
9167 */
9168 function contrastWeber(color1, color2) {
9169 color1 = getColor(color1);
9170 color2 = getColor(color2);
9171 let Y1 = Math.max(getLuminance(color1), 0);
9172 let Y2 = Math.max(getLuminance(color2), 0);
9173 if (Y2 > Y1) {
9174 [Y1, Y2] = [Y2, Y1];
9175 }
9176 return Y2 === 0 ? max : (Y1 - Y2) / Y2;
9177 }
9178
9179 // CIE Lightness difference, as used by Google Material Design
9180 // Google HCT Tone is the same as CIE Lightness
9181 // https://material.io/blog/science-of-color-design
9182
9183
9184 /**
9185 * @param {import("../types.js").ColorTypes} color1
9186 * @param {import("../types.js").ColorTypes} color2
9187 * @returns {number}
9188 */
9189 function contrastLstar(color1, color2) {
9190 color1 = getColor(color1);
9191 color2 = getColor(color2);
9192 let L1 = get(color1, [lab, "l"]);
9193 let L2 = get(color2, [lab, "l"]);
9194 return Math.abs(L1 - L2);
9195 }
9196
9197 // κ * ε = 2^3 = 8
9198 const ε$3 = 216 / 24389; // 6^3/29^3 == (24/116)^3
9199 const ε3 = 24 / 116;
9200 const κ$2 = 24389 / 27; // 29^3/3^3
9201
9202 let white$1 = WHITES.D65;
9203 var lab_d65 = new ColorSpace({
9204 id: "lab-d65",
9205 name: "Lab D65",
9206 coords: {
9207 l: {
9208 refRange: [0, 100],
9209 name: "Lightness"
9210 },
9211 a: {
9212 refRange: [-125, 125]
9213 },
9214 b: {
9215 refRange: [-125, 125]
9216 }
9217 },
9218 // Assuming XYZ is relative to D65, convert to CIE Lab
9219 // from CIE standard, which now defines these as a rational fraction
9220 white: white$1,
9221 base: XYZ_D65,
9222 // Convert D65-adapted XYZ to Lab
9223 // CIE 15.3:2004 section 8.2.1.1
9224 fromBase(XYZ) {
9225 // compute xyz, which is XYZ scaled relative to reference white
9226 let xyz = XYZ.map((value, i) => value / white$1[i]);
9227
9228 // now compute f
9229 let f = xyz.map(value => value > ε$3 ? Math.cbrt(value) : (κ$2 * value + 16) / 116);
9230 return [116 * f[1] - 16,
9231 // L
9232 500 * (f[0] - f[1]),
9233 // a
9234 200 * (f[1] - f[2]) // b
9235 ];
9236 },
9237 // Convert Lab to D65-adapted XYZ
9238 // Same result as CIE 15.3:2004 Appendix D although the derivation is different
9239 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
9240 toBase(Lab) {
9241 // compute f, starting with the luminance-related term
9242 let f = [];
9243 f[1] = (Lab[0] + 16) / 116;
9244 f[0] = Lab[1] / 500 + f[1];
9245 f[2] = f[1] - Lab[2] / 200;
9246
9247 // compute xyz
9248 let xyz = [f[0] > ε3 ? Math.pow(f[0], 3) : (116 * f[0] - 16) / κ$2, Lab[0] > 8 ? Math.pow((Lab[0] + 16) / 116, 3) : Lab[0] / κ$2, f[2] > ε3 ? Math.pow(f[2], 3) : (116 * f[2] - 16) / κ$2];
9249
9250 // Compute XYZ by scaling xyz by reference white
9251 return xyz.map((value, i) => value * white$1[i]);
9252 },
9253 formats: {
9254 "lab-d65": {
9255 coords: ["<number> | <percentage>", "<number> | <percentage>", "<number> | <percentage>"]
9256 }
9257 }
9258 });
9259
9260 // Delta Phi Star perceptual lightness contrast
9261 // See https://github.com/Myndex/deltaphistar
9262 // The (difference between two Lstars each raised to phi) raised to (1/phi)
9263 // Symmetric, does not matter which is foreground and which is background
9264
9265 const phi = Math.pow(5, 0.5) * 0.5 + 0.5; // Math.phi can be used if Math.js
9266
9267 /**
9268 * @param {import("../types.js").ColorTypes} color1
9269 * @param {import("../types.js").ColorTypes} color2
9270 * @returns {number}
9271 */
9272 function contrastDeltaPhi(color1, color2) {
9273 color1 = getColor(color1);
9274 color2 = getColor(color2);
9275 let Lstr1 = get(color1, [lab_d65, "l"]);
9276 let Lstr2 = get(color2, [lab_d65, "l"]);
9277 let deltaPhiStar = Math.abs(Math.pow(Lstr1, phi) - Math.pow(Lstr2, phi));
9278 let contrast = Math.pow(deltaPhiStar, 1 / phi) * Math.SQRT2 - 40;
9279 return contrast < 7.5 ? 0.0 : contrast;
9280 }
9281
9282 /** @typedef {keyof typeof import("./index.js") extends `contrast${infer Alg}` ? Alg : string} Algorithms */
9283
9284 var contrastMethods = /*#__PURE__*/Object.freeze({
9285 __proto__: null,
9286 contrastAPCA: contrastAPCA,
9287 contrastDeltaPhi: contrastDeltaPhi,
9288 contrastLstar: contrastLstar,
9289 contrastMichelson: contrastMichelson,
9290 contrastWCAG21: contrastWCAG21,
9291 contrastWeber: contrastWeber
9292 });
9293
9294 /** @import { ColorTypes } from "./types.js" */
9295
9296 // Type re-exports
9297 /** @typedef {import("./types.js").Algorithms} Algorithms */
9298
9299 /**
9300 *
9301 * @param {ColorTypes} background
9302 * @param {ColorTypes} foreground
9303 * @param {Algorithms | ({ algorithm: Algorithms } & Record<string, any>)} o
9304 * Algorithm to use as well as any other options to pass to the contrast function
9305 * @returns {number}
9306 * @throws {TypeError} Unknown or unspecified algorithm
9307 */
9308 function contrast(background, foreground, o) {
9309 if (isString(o)) {
9310 o = {
9311 algorithm: o
9312 };
9313 }
9314 let {
9315 algorithm,
9316 ...rest
9317 } = o || {};
9318 if (!algorithm) {
9319 let algorithms = Object.keys(contrastMethods).map(a => a.replace(/^contrast/, "")).join(", ");
9320 throw new TypeError(`contrast() function needs a contrast algorithm. Please specify one of: ${algorithms}`);
9321 }
9322 background = getColor(background);
9323 foreground = getColor(foreground);
9324 for (let a in contrastMethods) {
9325 if ("contrast" + algorithm.toLowerCase() === a.toLowerCase()) {
9326 return contrastMethods[a](background, foreground, rest);
9327 }
9328 }
9329 throw new TypeError(`Unknown contrast algorithm: ${algorithm}`);
9330 }
9331
9332 /** @import Color, { ColorTypes } from "./color.js" */
9333
9334 // Chromaticity coordinates
9335 /**
9336 * @param {ColorTypes} color
9337 * @returns {[number, number]}
9338 */
9339 function uv(color) {
9340 // Assumes getAll() calls getColor() on color
9341 let [X, Y, Z] = getAll(color, XYZ_D65);
9342 let denom = X + 15 * Y + 3 * Z;
9343 return [4 * X / denom, 9 * Y / denom];
9344 }
9345
9346 /**
9347 * @param {ColorTypes} color
9348 * @returns {[number, number]}
9349 */
9350 function xy(color) {
9351 // Assumes getAll() calls getColor() on color
9352 let [X, Y, Z] = getAll(color, XYZ_D65);
9353 let sum = X + Y + Z;
9354 return [X / sum, Y / sum];
9355 }
9356
9357 /**
9358 * @param {typeof Color} Color
9359 */
9360 function register$1(Color) {
9361 // no setters, as lightness information is lost
9362 // when converting color to chromaticity
9363 Object.defineProperty(Color.prototype, "uv", {
9364 get() {
9365 return uv(this);
9366 }
9367 });
9368 Object.defineProperty(Color.prototype, "xy", {
9369 get() {
9370 return xy(this);
9371 }
9372 });
9373 }
9374
9375 var chromaticity = /*#__PURE__*/Object.freeze({
9376 __proto__: null,
9377 register: register$1,
9378 uv: uv,
9379 xy: xy
9380 });
9381
9382 /** @import { ColorTypes } from "./types.js" */
9383
9384 // Type re-exports
9385 /** @typedef {import("./types.js").Methods} Methods */
9386
9387 /**
9388 *
9389 * @param {ColorTypes} c1
9390 * @param {ColorTypes} c2
9391 * @param {Methods | ({ method?: Methods | undefined } & Record<string, any>)} [o]
9392 * deltaE method to use as well as any other options to pass to the deltaE function
9393 * @returns {number}
9394 * @throws {TypeError} Unknown or unspecified method
9395 */
9396 function deltaE(c1, c2, o = {}) {
9397 if (isString(o)) {
9398 o = {
9399 method: o
9400 };
9401 }
9402 let {
9403 method = defaults.deltaE,
9404 ...rest
9405 } = o;
9406 for (let m in deltaEMethods) {
9407 if ("deltae" + method.toLowerCase() === m.toLowerCase()) {
9408 return deltaEMethods[m](c1, c2, rest);
9409 }
9410 }
9411 throw new TypeError(`Unknown deltaE method: ${method}`);
9412 }
9413
9414 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
9415
9416 /**
9417 * @param {ColorTypes} color
9418 * @param {number} amount
9419 * @returns {PlainColorObject}
9420 */
9421 function lighten(color, amount = 0.25) {
9422 let space = ColorSpace.get("oklch", "lch");
9423 let /** @type {Ref} */lightness = [space, "l"];
9424 return set(color, lightness, l => l * (1 + amount));
9425 }
9426
9427 /**
9428 * @param {ColorTypes} color
9429 * @param {number} amount
9430 * @returns {PlainColorObject}
9431 */
9432 function darken(color, amount = 0.25) {
9433 let space = ColorSpace.get("oklch", "lch");
9434 let /** @type {Ref} */lightness = [space, "l"];
9435 return set(color, lightness, l => l * (1 - amount));
9436 }
9437
9438 /** @type {"color"} */
9439 lighten.returns = "color";
9440
9441 /** @type {"color"} */
9442 darken.returns = "color";
9443
9444 var variations = /*#__PURE__*/Object.freeze({
9445 __proto__: null,
9446 darken: darken,
9447 lighten: lighten
9448 });
9449
9450 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
9451
9452 // Type re-exports
9453 /** @typedef {import("./types.js").MixOptions} MixOptions */
9454 /** @typedef {import("./types.js").Range} Range */
9455 /** @typedef {import("./types.js").RangeOptions} RangeOptions */
9456 /** @typedef {import("./types.js").StepsOptions} StepsOptions */
9457
9458 /**
9459 * Return an intermediate color between two colors
9460 * @overload
9461 * @param {ColorTypes} c1
9462 * @param {ColorTypes} c2
9463 * @param {MixOptions} [options]
9464 * @returns {PlainColorObject}
9465 */
9466 /**
9467 * @overload
9468 * @param {ColorTypes} c1
9469 * @param {ColorTypes} c2
9470 * @param {number} [p=0.5]
9471 * @param {MixOptions} [options]
9472 * @returns {PlainColorObject}
9473 */
9474 function mix(c1, c2, p, o = {}) {
9475 var _p;
9476 [c1, c2] = [getColor(c1), getColor(c2)];
9477 if (type(p) === "object") {
9478 [p, o] = [0.5, p];
9479 }
9480 let r = range(c1, c2, o);
9481 return r((_p = p) !== null && _p !== void 0 ? _p : 0.5); // why not give p a default value like we do for options? Overloading doesn't work, and TS complains
9482 }
9483
9484 /**
9485 * Get an array of discrete steps
9486 * @overload
9487 * @param {ColorTypes} c1
9488 * @param {ColorTypes} c2
9489 * @param {StepsOptions} [options]
9490 * @returns {PlainColorObject[]}
9491 */
9492 /**
9493 * @overload
9494 * @param {Range} range
9495 * @param {StepsOptions} [options]
9496 * @returns {PlainColorObject[]}
9497 */
9498 function steps(c1, c2, options = {}) {
9499 let colorRange;
9500 if (isRange(c1)) {
9501 // Tweaking existing range
9502 [colorRange, options] = [c1, c2];
9503 [c1, c2] = colorRange.rangeArgs.colors;
9504 }
9505 let {
9506 maxDeltaE,
9507 deltaEMethod,
9508 steps = 2,
9509 maxSteps = 1000,
9510 ...rangeOptions
9511 } = options;
9512 if (!colorRange) {
9513 [c1, c2] = [getColor(c1), getColor(c2)];
9514 colorRange = range(c1, c2, rangeOptions);
9515 }
9516 let totalDelta = deltaE(c1, c2);
9517 let actualSteps = maxDeltaE > 0 ? Math.max(steps, Math.ceil(totalDelta / maxDeltaE) + 1) : steps;
9518 let ret = [];
9519 if (maxSteps !== undefined) {
9520 actualSteps = Math.min(actualSteps, maxSteps);
9521 }
9522 if (actualSteps === 1) {
9523 ret = [{
9524 p: 0.5,
9525 color: colorRange(0.5)
9526 }];
9527 } else {
9528 let step = 1 / (actualSteps - 1);
9529 ret = Array.from({
9530 length: actualSteps
9531 }, (_, i) => {
9532 let p = i * step;
9533 return {
9534 p,
9535 color: colorRange(p)
9536 };
9537 });
9538 }
9539 if (maxDeltaE > 0) {
9540 // Iterate over all stops and find max deltaE
9541 let maxDelta = ret.reduce((acc, cur, i) => {
9542 if (i === 0) {
9543 return 0;
9544 }
9545 let ΔΕ = deltaE(cur.color, ret[i - 1].color, deltaEMethod);
9546 return Math.max(acc, ΔΕ);
9547 }, 0);
9548 while (maxDelta > maxDeltaE) {
9549 // Insert intermediate stops and measure maxDelta again
9550 // We need to do this for all pairs, otherwise the midpoint shifts
9551 maxDelta = 0;
9552 for (let i = 1; i < ret.length && ret.length < maxSteps; i++) {
9553 let prev = ret[i - 1];
9554 let cur = ret[i];
9555 let p = (cur.p + prev.p) / 2;
9556 let color = colorRange(p);
9557 maxDelta = Math.max(maxDelta, deltaE(color, prev.color), deltaE(color, cur.color));
9558 ret.splice(i, 0, {
9559 p,
9560 color: colorRange(p)
9561 });
9562 i++;
9563 }
9564 }
9565 }
9566 ret = ret.map(a => a.color);
9567 return ret;
9568 }
9569
9570 /**
9571 * Creates a function that accepts a number and returns a color.
9572 * For numbers in the range 0 to 1, the function interpolates;
9573 * for numbers outside that range, the function extrapolates
9574 * (and thus may not return the results you expect)
9575 * @overload
9576 * @param {Range} range
9577 * @param {RangeOptions} [options]
9578 * @returns {Range}
9579 */
9580 /**
9581 * @overload
9582 * @param {ColorTypes} color1
9583 * @param {ColorTypes} color2
9584 * @param {RangeOptions & Record<string, any>} [options]
9585 * @returns {Range}
9586 */
9587 function range(color1, color2, options = {}) {
9588 if (isRange(color1)) {
9589 // Tweaking existing range
9590 let [r, options] = [color1, color2];
9591 return range(...r.rangeArgs.colors, {
9592 ...r.rangeArgs.options,
9593 ...options
9594 });
9595 }
9596 let {
9597 space,
9598 outputSpace,
9599 progression,
9600 premultiplied
9601 } = options;
9602 color1 = getColor(color1);
9603 color2 = getColor(color2);
9604
9605 // Make sure we're working on copies of these colors
9606 color1 = clone(color1);
9607 color2 = clone(color2);
9608 let rangeArgs = {
9609 colors: [color1, color2],
9610 options
9611 };
9612 if (space) {
9613 space = ColorSpace.get(space);
9614 } else {
9615 space = ColorSpace.registry[defaults.interpolationSpace] || color1.space;
9616 }
9617 outputSpace = outputSpace ? ColorSpace.get(outputSpace) : space;
9618 color1 = to(color1, space);
9619 color2 = to(color2, space);
9620
9621 // Gamut map to avoid areas of flat color
9622 color1 = toGamut(color1);
9623 color2 = toGamut(color2);
9624
9625 // Handle hue interpolation
9626 // See https://github.com/w3c/csswg-drafts/issues/4735#issuecomment-635741840
9627 if (space.coords.h && space.coords.h.type === "angle") {
9628 let arc = options.hue = options.hue || "shorter";
9629 let /** @type {Ref} */hue = [space, "h"];
9630 let [θ1, θ2] = [get(color1, hue), get(color2, hue)];
9631 // Undefined hues must be evaluated before hue fix-up to properly
9632 // calculate hue arcs between undefined and defined hues.
9633 // See https://github.com/w3c/csswg-drafts/issues/9436#issuecomment-1746957545
9634 if (isNone(θ1) && !isNone(θ2)) {
9635 θ1 = θ2;
9636 } else if (isNone(θ2) && !isNone(θ1)) {
9637 θ2 = θ1;
9638 }
9639 [θ1, θ2] = adjust(arc, [θ1, θ2]);
9640 set(color1, hue, θ1);
9641 set(color2, hue, θ2);
9642 }
9643 if (premultiplied) {
9644 // not coping with polar spaces yet
9645 color1.coords = /** @type {[number, number, number]} */
9646 color1.coords.map(c => c * color1.alpha);
9647 color2.coords = /** @type {[number, number, number]} */
9648 color2.coords.map(c => c * color2.alpha);
9649 }
9650 return Object.assign(p => {
9651 p = progression ? progression(p) : p;
9652 let coords = color1.coords.map((start, i) => {
9653 let end = color2.coords[i];
9654 return interpolate(start, end, p);
9655 });
9656 let alpha = interpolate(color1.alpha, color2.alpha, p);
9657 let ret = {
9658 space,
9659 coords,
9660 alpha
9661 };
9662 if (premultiplied) {
9663 // undo premultiplication
9664 ret.coords = ret.coords.map(c => c / alpha);
9665 }
9666 if (outputSpace !== space) {
9667 ret = to(ret, outputSpace);
9668 }
9669 return ret;
9670 }, {
9671 rangeArgs
9672 });
9673 }
9674
9675 /**
9676 * @param {any} val
9677 * @returns {val is Range}
9678 */
9679 function isRange(val) {
9680 return type(val) === "function" && !!val.rangeArgs;
9681 }
9682 defaults.interpolationSpace = "lab";
9683
9684 /**
9685 * @param {typeof import("./color.js").default} Color
9686 */
9687 function register(Color) {
9688 Color.defineFunction("mix", mix, {
9689 returns: "color"
9690 });
9691 Color.defineFunction("range", range, {
9692 returns: "function<color>"
9693 });
9694 Color.defineFunction("steps", steps, {
9695 returns: "array<color>"
9696 });
9697 }
9698
9699 var interpolation = /*#__PURE__*/Object.freeze({
9700 __proto__: null,
9701 isRange: isRange,
9702 mix: mix,
9703 range: range,
9704 register: register,
9705 steps: steps
9706 });
9707
9708 var HSL = new ColorSpace({
9709 id: "hsl",
9710 name: "HSL",
9711 coords: {
9712 h: {
9713 refRange: [0, 360],
9714 type: "angle",
9715 name: "Hue"
9716 },
9717 s: {
9718 range: [0, 100],
9719 name: "Saturation"
9720 },
9721 l: {
9722 range: [0, 100],
9723 name: "Lightness"
9724 }
9725 },
9726 base: sRGB,
9727 rgbGamut: sRGB,
9728 // Adapted from https://drafts.csswg.org/css-color-4/better-rgbToHsl.js
9729 fromBase: rgb => {
9730 let max = Math.max(...rgb);
9731 let min = Math.min(...rgb);
9732 let [r, g, b] = rgb;
9733 let [h, s, l] = [null, 0, (min + max) / 2];
9734 let d = max - min;
9735 if (d !== 0) {
9736 s = l === 0 || l === 1 ? 0 : (max - l) / Math.min(l, 1 - l);
9737 switch (max) {
9738 case r:
9739 h = (g - b) / d + (g < b ? 6 : 0);
9740 break;
9741 case g:
9742 h = (b - r) / d + 2;
9743 break;
9744 case b:
9745 h = (r - g) / d + 4;
9746 }
9747 h = h * 60;
9748 }
9749
9750 // Very out of gamut colors can produce negative saturation
9751 // If so, just rotate the hue by 180 and use a positive saturation
9752 // see https://github.com/w3c/csswg-drafts/issues/9222
9753 if (s < 0) {
9754 h += 180;
9755 s = Math.abs(s);
9756 }
9757 if (h >= 360) {
9758 h -= 360;
9759 }
9760 return [h, s * 100, l * 100];
9761 },
9762 // Adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB_alternative
9763 toBase: hsl => {
9764 let [h, s, l] = hsl;
9765 h = h % 360;
9766 if (h < 0) {
9767 h += 360;
9768 }
9769 s /= 100;
9770 l /= 100;
9771 function f(n) {
9772 let k = (n + h / 30) % 12;
9773 let a = s * Math.min(l, 1 - l);
9774 return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));
9775 }
9776 return [f(0), f(8), f(4)];
9777 },
9778 formats: {
9779 hsl: {
9780 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
9781 },
9782 hsla: {
9783 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"],
9784 commas: true,
9785 alpha: true
9786 }
9787 }
9788 });
9789
9790 var hslP3 = new ColorSpace({
9791 id: "hsl-p3",
9792 cssId: "--hsl-p3",
9793 name: "HSL P3",
9794 coords: {
9795 h: {
9796 refRange: [0, 360],
9797 type: "angle",
9798 name: "Hue"
9799 },
9800 s: {
9801 range: [0, 100],
9802 name: "Saturation"
9803 },
9804 l: {
9805 range: [0, 100],
9806 name: "Lightness"
9807 }
9808 },
9809 base: P3,
9810 rgbGamut: P3,
9811 fromBase: HSL.fromBase,
9812 toBase: HSL.toBase
9813 });
9814
9815 var hslRec2020 = new ColorSpace({
9816 id: "hsl-rec2020",
9817 cssId: "--hsl-rec2020",
9818 name: "HSL Rec.2020",
9819 coords: {
9820 h: {
9821 refRange: [0, 360],
9822 type: "angle",
9823 name: "Hue"
9824 },
9825 s: {
9826 range: [0, 100],
9827 name: "Saturation"
9828 },
9829 l: {
9830 range: [0, 100],
9831 name: "Lightness"
9832 }
9833 },
9834 base: REC2020,
9835 rgbGamut: REC2020,
9836 fromBase: HSL.fromBase,
9837 toBase: HSL.toBase
9838 });
9839
9840 // Note that, like HSL, calculations are done directly on
9841 // gamma-corrected sRGB values rather than linearising them first.
9842
9843 var HSV = new ColorSpace({
9844 id: "hsv",
9845 name: "HSV",
9846 coords: {
9847 h: {
9848 refRange: [0, 360],
9849 type: "angle",
9850 name: "Hue"
9851 },
9852 s: {
9853 range: [0, 100],
9854 name: "Saturation"
9855 },
9856 v: {
9857 range: [0, 100],
9858 name: "Value"
9859 }
9860 },
9861 base: sRGB,
9862 rgbGamut: sRGB,
9863 // https://en.wikipedia.org/wiki/HSL_and_HSV#Formal_derivation
9864 fromBase(rgb) {
9865 let max = Math.max(...rgb);
9866 let min = Math.min(...rgb);
9867 let [r, g, b] = rgb;
9868 let [h, s, v] = [null, 0, max];
9869 let d = max - min;
9870 if (d !== 0) {
9871 switch (max) {
9872 case r:
9873 h = (g - b) / d + (g < b ? 6 : 0);
9874 break;
9875 case g:
9876 h = (b - r) / d + 2;
9877 break;
9878 case b:
9879 h = (r - g) / d + 4;
9880 }
9881 h = h * 60;
9882 }
9883 if (v) {
9884 s = d / v;
9885 }
9886 if (h >= 360) {
9887 h -= 360;
9888 }
9889 return [h, s * 100, v * 100];
9890 },
9891 // Adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_RGB_alternative
9892 toBase(hsv) {
9893 let [h, s, v] = hsv;
9894 h = h % 360;
9895 if (h < 0) {
9896 h += 360;
9897 }
9898 s /= 100;
9899 v /= 100;
9900 function f(n) {
9901 let k = (n + h / 60) % 6;
9902 return v - v * s * Math.max(0, Math.min(k, 4 - k, 1));
9903 }
9904 return [f(5), f(3), f(1)];
9905 },
9906 formats: {
9907 color: {
9908 id: "--hsv",
9909 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
9910 }
9911 }
9912 });
9913
9914 // The Hue, Whiteness Blackness (HWB) colorspace
9915 // See https://drafts.csswg.org/css-color-4/#the-hwb-notation
9916 // Note that, like HSL, calculations are done directly on
9917 // gamma-corrected sRGB values rather than linearising them first.
9918
9919 var hwb = new ColorSpace({
9920 id: "hwb",
9921 name: "HWB",
9922 coords: {
9923 h: {
9924 refRange: [0, 360],
9925 type: "angle",
9926 name: "Hue"
9927 },
9928 w: {
9929 range: [0, 100],
9930 name: "Whiteness"
9931 },
9932 b: {
9933 range: [0, 100],
9934 name: "Blackness"
9935 }
9936 },
9937 base: HSV,
9938 rgbGamut: sRGB,
9939 fromBase(hsv) {
9940 let [h, s, v] = hsv;
9941 return [h, v * (100 - s) / 100, 100 - v];
9942 },
9943 toBase(hwb) {
9944 let [h, w, b] = hwb;
9945
9946 // Now convert percentages to [0..1]
9947 w /= 100;
9948 b /= 100;
9949
9950 // Achromatic check (white plus black >= 1)
9951 let sum = w + b;
9952 if (sum >= 1) {
9953 let gray = w / sum;
9954 return [h, 0, gray * 100];
9955 }
9956 let v = 1 - b;
9957 let s = v === 0 ? 0 : 1 - w / v;
9958 return [h, s * 100, v * 100];
9959 },
9960 formats: {
9961 hwb: {
9962 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
9963 }
9964 }
9965 });
9966
9967 /** @import { Matrix3x3 } from "../types.js" */
9968
9969 // convert an array of linear-light a98-rgb values to CIE XYZ
9970 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
9971 // has greater numerical precision than section 4.3.5.3 of
9972 // https://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf
9973 // but the values below were calculated from first principles
9974 // from the chromaticity coordinates of R G B W
9975
9976 /** @type {Matrix3x3} */
9977 // prettier-ignore
9978 const toXYZ_M$2 = [[0.5766690429101305, 0.1855582379065463, 0.1882286462349947], [0.29734497525053605, 0.6273635662554661, 0.07529145849399788], [0.02703136138641234, 0.07068885253582723, 0.9913375368376388]];
9979
9980 /** @type {Matrix3x3} */
9981 // prettier-ignore
9982 const fromXYZ_M$2 = [[2.0415879038107465, -0.5650069742788596, -0.34473135077832956], [-0.9692436362808795, 1.8759675015077202, 0.04155505740717557], [0.013444280632031142, -0.11836239223101838, 1.0151749943912054]];
9983 var A98Linear = new RGBColorSpace({
9984 id: "a98rgb-linear",
9985 cssId: "--a98-rgb-linear",
9986 name: "Linear Adobe® 98 RGB compatible",
9987 white: "D65",
9988 toXYZ_M: toXYZ_M$2,
9989 fromXYZ_M: fromXYZ_M$2
9990 });
9991
9992 var a98rgb = new RGBColorSpace({
9993 id: "a98rgb",
9994 cssId: "a98-rgb",
9995 name: "Adobe® 98 RGB compatible",
9996 base: A98Linear,
9997 linearGamut: A98Linear,
9998 toBase: RGB => RGB.map(val => Math.pow(Math.abs(val), 563 / 256) * Math.sign(val)),
9999 fromBase: RGB => RGB.map(val => Math.pow(Math.abs(val), 256 / 563) * Math.sign(val))
10000 });
10001
10002 /** @import { Matrix3x3 } from "../types.js" */
10003
10004 // convert an array of prophoto-rgb values to CIE XYZ
10005 // using D50 (so no chromatic adaptation needed afterwards)
10006 // matrix cannot be expressed in rational form, but is calculated to 64 bit accuracy
10007 // see https://github.com/w3c/csswg-drafts/issues/7675
10008 /** @type {Matrix3x3} */
10009 // prettier-ignore
10010 const toXYZ_M$1 = [[0.79776664490064230, 0.13518129740053308, 0.03134773412839220], [0.28807482881940130, 0.71183523424187300, 0.00008993693872564], [0.00000000000000000, 0.00000000000000000, 0.82510460251046020]];
10011
10012 /** @type {Matrix3x3} */
10013 // prettier-ignore
10014 const fromXYZ_M$1 = [[1.34578688164715830, -0.25557208737979464, -0.05110186497554526], [-0.54463070512490190, 1.50824774284514680, 0.02052744743642139], [0.00000000000000000, 0.00000000000000000, 1.21196754563894520]];
10015 var ProPhotoLinear = new RGBColorSpace({
10016 id: "prophoto-linear",
10017 cssId: "--prophoto-rgb-linear",
10018 name: "Linear ProPhoto",
10019 white: "D50",
10020 base: XYZ_D50,
10021 toXYZ_M: toXYZ_M$1,
10022 fromXYZ_M: fromXYZ_M$1
10023 });
10024
10025 const Et = 1 / 512;
10026 const Et2 = 16 / 512;
10027 var prophoto = new RGBColorSpace({
10028 id: "prophoto",
10029 cssId: "prophoto-rgb",
10030 name: "ProPhoto",
10031 base: ProPhotoLinear,
10032 linearGamut: ProPhotoLinear,
10033 toBase(RGB) {
10034 // Transfer curve is gamma 1.8 with a small linear portion
10035 return RGB.map(v => {
10036 let sign = v < 0 ? -1 : 1;
10037 let abs = v * sign;
10038 if (abs < Et2) {
10039 return v / 16;
10040 }
10041 return sign * abs ** 1.8;
10042 });
10043 },
10044 fromBase(RGB) {
10045 return RGB.map(v => {
10046 let sign = v < 0 ? -1 : 1;
10047 let abs = v * sign;
10048 if (abs >= Et) {
10049 return sign * abs ** (1 / 1.8);
10050 }
10051 return 16 * v;
10052 });
10053 }
10054 });
10055
10056 // import sRGB from "./srgb.js";
10057
10058 const α = 1.09929682680944;
10059 const β = 0.018053968510807;
10060 var rec2020Oetf = new RGBColorSpace({
10061 id: "--rec2020-oetf",
10062 name: "REC.2020_Scene_Referred",
10063 base: REC_2020_Linear,
10064 linearGamut: REC_2020_Linear,
10065 referred: "scene",
10066 // Non-linear transfer function from Rec. ITU-R BT.2020-2 table 4
10067 toBase(RGB) {
10068 return RGB.map(function (val) {
10069 let sign = val < 0 ? -1 : 1;
10070 let abs = val * sign;
10071 if (abs < β * 4.5) {
10072 return val / 4.5;
10073 }
10074 return sign * Math.pow((abs + α - 1) / α, 1 / 0.45);
10075 });
10076 },
10077 fromBase(RGB) {
10078 return RGB.map(function (val) {
10079 let sign = val < 0 ? -1 : 1;
10080 let abs = val * sign;
10081 if (abs >= β) {
10082 return sign * (α * Math.pow(abs, 0.45) - (α - 1));
10083 }
10084 return 4.5 * val;
10085 });
10086 }
10087 });
10088
10089 var oklchP3 = new ColorSpace({
10090 id: "oklch-p3",
10091 name: "OKLCh P3",
10092 coords: {
10093 l: {
10094 refRange: [0, 1],
10095 name: "Lightness"
10096 },
10097 c: {
10098 range: [0, 1],
10099 name: "Chroma"
10100 },
10101 h: {
10102 refRange: [0, 360],
10103 type: "angle",
10104 name: "Hue"
10105 }
10106 },
10107 white: "D65",
10108 base: OKLCH,
10109 toBase([l, c, h]) {
10110 if (![l, c, h].some(isNone)) {
10111 c *= maxChroma(l, h, {
10112 space: OKLCH,
10113 gamut: "p3"
10114 });
10115 }
10116 return [l, c, h];
10117 },
10118 fromBase([l, c, h]) {
10119 if (![l, c, h].some(isNone)) {
10120 let cMax = maxChroma(l, h, {
10121 space: OKLCH,
10122 gamut: "p3"
10123 });
10124 c = cMax ? c / cMax : 0;
10125 }
10126 return [l, c, h];
10127 },
10128 formats: {
10129 color: {
10130 id: "--oklch-p3",
10131 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"]
10132 }
10133 }
10134 });
10135
10136 /** @import { Matrix3x3, Vector3 } from "../types.js" */
10137
10138 // Type re-exports
10139 /** @typedef {import("../types.js").OKCoeff} OKCoeff */
10140
10141 const tau = 2 * Math.PI;
10142
10143 /** @type {Matrix3x3} */
10144 // prettier-ignore
10145 const toSRGBLinear = [[4.0767416360759583, -3.3077115392580629, 0.2309699031821043], [-1.2684379732850315, 2.6097573492876882, -0.3413193760026570], [-0.0041960761386756, -0.7034186179359362, 1.7076146940746117]];
10146
10147 /** @type {OKCoeff} */
10148 const RGBCoeff = [
10149 // Red
10150 [
10151 // Limit
10152 [-1.8817031, -0.80936501],
10153 // `Kn` coefficients
10154 [1.19086277, 1.76576728, 0.59662641, 0.75515197, 0.56771245]],
10155 // Green
10156 [
10157 // Limit
10158 [1.8144408, -1.19445267],
10159 // `Kn` coefficients
10160 [0.73956515, -0.45954404, 0.08285427, 0.12541073, -0.14503204]],
10161 // Blue
10162 [
10163 // Limit
10164 [0.13110758, 1.81333971],
10165 // `Kn` coefficients
10166 [1.35733652, -0.00915799, -1.1513021, -0.50559606, 0.00692167]]];
10167 const floatMax = Number.MAX_VALUE;
10168 const K1 = 0.206;
10169 const K2 = 0.03;
10170 const K3 = (1.0 + K1) / (1.0 + K2);
10171 function vdot(a, b) {
10172 // Dot two vectors
10173
10174 let l = a.length;
10175 if (l !== b.length) {
10176 throw new Error(`Vectors of size ${l} and ${b.length} are not aligned`);
10177 }
10178 let s = 0.0;
10179 a.forEach((c, i) => {
10180 s += c * b[i];
10181 });
10182 return s;
10183 }
10184
10185 /**
10186 * Toe function for L_r
10187 * @param {number} x
10188 */
10189 function toe(x) {
10190 return 0.5 * (K3 * x - K1 + Math.sqrt((K3 * x - K1) * (K3 * x - K1) + 4 * K2 * K3 * x));
10191 }
10192
10193 /**
10194 * Inverse toe function for L_r
10195 * @param {number} x
10196 */
10197 function toeInv(x) {
10198 return (x ** 2 + K1 * x) / (K3 * (x + K2));
10199 }
10200
10201 /**
10202 * @param {readonly [number, number]} cusp
10203 * @returns {[number, number]}
10204 */
10205 function toSt(cusp) {
10206 // To ST.
10207
10208 let [l, c] = cusp;
10209 return [c / l, c / (1 - l)];
10210 }
10211 function getStMid(a, b) {
10212 // Returns a smooth approximation of the location of the cusp.
10213 //
10214 // This polynomial was created by an optimization process.
10215 // It has been designed so that S_mid < S_max and T_mid < T_max.
10216
10217 // prettier-ignore
10218 let s = 0.11516993 + 1.0 / (7.44778970 + 4.15901240 * b + a * (-2.19557347 + 1.75198401 * b + a * (-2.13704948 - 10.02301043 * b + a * (-4.24894561 + 5.38770819 * b + 4.69891013 * a))));
10219
10220 // prettier-ignore
10221 let t = 0.11239642 + 1.0 / (1.61320320 - 0.68124379 * b + a * (0.40370612 + 0.90148123 * b + a * (-0.27087943 + 0.61223990 * b + a * (0.00299215 - 0.45399568 * b - 0.14661872 * a))));
10222 return [s, t];
10223 }
10224
10225 /**
10226 * @param {Vector3} lab
10227 * @param {Matrix3x3} lmsToRgb
10228 */
10229 function oklabToLinearRGB(lab, lmsToRgb) {
10230 // Convert from Oklab to linear RGB.
10231 //
10232 // Can be any gamut as long as `lmsToRgb` is a matrix
10233 // that transform the LMS values to the linear RGB space.
10234
10235 let lms = multiply_v3_m3x3(lab, LabtoLMS_M);
10236 lms[0] = lms[0] ** 3;
10237 lms[1] = lms[1] ** 3;
10238 lms[2] = lms[2] ** 3;
10239 return multiply_v3_m3x3(lms, lmsToRgb, lms);
10240 }
10241
10242 /**
10243 * @param {number} a
10244 * @param {number} b
10245 * @param {Matrix3x3} lmsToRgb
10246 * @param {OKCoeff} okCoeff
10247 * @returns {[number, number]}
10248 * @todo Could probably make these types more specific/better-documented if desired
10249 */
10250 function findCusp(a, b, lmsToRgb, okCoeff) {
10251 // Finds L_cusp and C_cusp for a given hue.
10252 //
10253 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
10254
10255 // First, find the maximum saturation (saturation `S = C/L`)
10256 let sCusp = computeMaxSaturation(a, b, lmsToRgb, okCoeff);
10257
10258 // Convert to linear RGB to find the first point where at least one of r, g or b >= 1:
10259 let rgb = oklabToLinearRGB([1, sCusp * a, sCusp * b], lmsToRgb);
10260 let lCusp = spow(1.0 / Math.max(...rgb), 1 / 3);
10261 let cCusp = lCusp * sCusp;
10262 return [lCusp, cCusp];
10263 }
10264
10265 /**
10266 * @param {number} a
10267 * @param {number} b
10268 * @param {number} l1
10269 * @param {number} c1
10270 * @param {number} l0
10271 * @param {Matrix3x3} lmsToRgb
10272 * @param {OKCoeff} okCoeff
10273 * @param {[number, number]} cusp
10274 * @returns {Number}
10275 * @todo Could probably make these types more specific/better-documented if desired
10276 */
10277 function findGamutIntersection(a, b, l1, c1, l0, lmsToRgb, okCoeff, cusp) {
10278 // Finds intersection of the line.
10279 //
10280 // Defined by the following:
10281 //
10282 // ```
10283 // L = L0 * (1 - t) + t * L1
10284 // C = t * C1
10285 // ```
10286 //
10287 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
10288
10289 let t;
10290 if (cusp === undefined) {
10291 cusp = findCusp(a, b, lmsToRgb, okCoeff);
10292 }
10293
10294 // Find the intersection for upper and lower half separately
10295 if ((l1 - l0) * cusp[1] - (cusp[0] - l0) * c1 <= 0.0) {
10296 // Lower half
10297 t = cusp[1] * l0 / (c1 * cusp[0] + cusp[1] * (l0 - l1));
10298 } else {
10299 // Upper half
10300
10301 // First intersect with triangle
10302 t = cusp[1] * (l0 - 1.0) / (c1 * (cusp[0] - 1.0) + cusp[1] * (l0 - l1));
10303
10304 // Then one step Halley's method
10305 let dl = l1 - l0;
10306 let dc = c1;
10307 let kl = vdot(LabtoLMS_M[0].slice(1), [a, b]);
10308 let km = vdot(LabtoLMS_M[1].slice(1), [a, b]);
10309 let ks = vdot(LabtoLMS_M[2].slice(1), [a, b]);
10310 let ldt_ = dl + dc * kl;
10311 let mdt_ = dl + dc * km;
10312 let sdt_ = dl + dc * ks;
10313
10314 // If higher accuracy is required, 2 or 3 iterations of the following block can be used:
10315 let L = l0 * (1.0 - t) + t * l1;
10316 let C = t * c1;
10317 let l_ = L + C * kl;
10318 let m_ = L + C * km;
10319 let s_ = L + C * ks;
10320 let l = l_ ** 3;
10321 let m = m_ ** 3;
10322 let s = s_ ** 3;
10323 let ldt = 3 * ldt_ * l_ ** 2;
10324 let mdt = 3 * mdt_ * m_ ** 2;
10325 let sdt = 3 * sdt_ * s_ ** 2;
10326 let ldt2 = 6 * ldt_ ** 2 * l_;
10327 let mdt2 = 6 * mdt_ ** 2 * m_;
10328 let sdt2 = 6 * sdt_ ** 2 * s_;
10329 let r_ = vdot(lmsToRgb[0], [l, m, s]) - 1;
10330 let r1 = vdot(lmsToRgb[0], [ldt, mdt, sdt]);
10331 let r2 = vdot(lmsToRgb[0], [ldt2, mdt2, sdt2]);
10332 let ur = r1 / (r1 * r1 - 0.5 * r_ * r2);
10333 let tr = -r_ * ur;
10334 let g_ = vdot(lmsToRgb[1], [l, m, s]) - 1;
10335 let g1 = vdot(lmsToRgb[1], [ldt, mdt, sdt]);
10336 let g2 = vdot(lmsToRgb[1], [ldt2, mdt2, sdt2]);
10337 let ug = g1 / (g1 * g1 - 0.5 * g_ * g2);
10338 let tg = -g_ * ug;
10339 let b_ = vdot(lmsToRgb[2], [l, m, s]) - 1;
10340 let b1 = vdot(lmsToRgb[2], [ldt, mdt, sdt]);
10341 let b2 = vdot(lmsToRgb[2], [ldt2, mdt2, sdt2]);
10342 let ub = b1 / (b1 * b1 - 0.5 * b_ * b2);
10343 let tb = -b_ * ub;
10344 tr = ur >= 0.0 ? tr : floatMax;
10345 tg = ug >= 0.0 ? tg : floatMax;
10346 tb = ub >= 0.0 ? tb : floatMax;
10347 t += Math.min(tr, Math.min(tg, tb));
10348 }
10349 return t;
10350 }
10351 function getCs(lab, lmsToRgb, okCoeff) {
10352 // Get Cs
10353
10354 let [l, a, b] = lab;
10355 let cusp = findCusp(a, b, lmsToRgb, okCoeff);
10356 let cMax = findGamutIntersection(a, b, l, 1, l, lmsToRgb, okCoeff, cusp);
10357 let stMax = toSt(cusp);
10358
10359 // Scale factor to compensate for the curved part of gamut shape:
10360 let k = cMax / Math.min(l * stMax[0], (1 - l) * stMax[1]);
10361 let stMid = getStMid(a, b);
10362
10363 // Use a soft minimum function, instead of a sharp triangle shape to get a smooth value for chroma.
10364 let ca = l * stMid[0];
10365 let cb = (1.0 - l) * stMid[1];
10366 let cMid = 0.9 * k * Math.sqrt(Math.sqrt(1.0 / (1.0 / ca ** 4 + 1.0 / cb ** 4)));
10367
10368 // For `C_0`, the shape is independent of hue, so `ST` are constant.
10369 // Values picked to roughly be the average values of `ST`.
10370 ca = l * 0.4;
10371 cb = (1.0 - l) * 0.8;
10372
10373 // Use a soft minimum function, instead of a sharp triangle shape to get a smooth value for chroma.
10374 let c0 = Math.sqrt(1.0 / (1.0 / ca ** 2 + 1.0 / cb ** 2));
10375 return [c0, cMid, cMax];
10376 }
10377 function computeMaxSaturation(a, b, lmsToRgb, okCoeff) {
10378 // Finds the maximum saturation possible for a given hue that fits in RGB.
10379 //
10380 // Saturation here is defined as `S = C/L`.
10381 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
10382
10383 // Max saturation will be when one of r, g or b goes below zero.
10384
10385 // Select different coefficients depending on which component goes below zero first.
10386
10387 let k0, k1, k2, k3, k4, wl, wm, ws;
10388 if (vdot(okCoeff[0][0], [a, b]) > 1) {
10389 // Red component
10390 [k0, k1, k2, k3, k4] = okCoeff[0][1];
10391 [wl, wm, ws] = lmsToRgb[0];
10392 } else if (vdot(okCoeff[1][0], [a, b]) > 1) {
10393 // Green component
10394 [k0, k1, k2, k3, k4] = okCoeff[1][1];
10395 [wl, wm, ws] = lmsToRgb[1];
10396 } else {
10397 // Blue component
10398 [k0, k1, k2, k3, k4] = okCoeff[2][1];
10399 [wl, wm, ws] = lmsToRgb[2];
10400 }
10401
10402 // Approximate max saturation using a polynomial:
10403 let sat = k0 + k1 * a + k2 * b + k3 * a ** 2 + k4 * a * b;
10404
10405 // Do one step Halley's method to get closer.
10406 // This gives an error less than 10e6, except for some blue hues where the `dS/dh` is close to infinite.
10407 // This should be sufficient for most applications, otherwise do two/three steps.
10408
10409 let kl = vdot(LabtoLMS_M[0].slice(1), [a, b]);
10410 let km = vdot(LabtoLMS_M[1].slice(1), [a, b]);
10411 let ks = vdot(LabtoLMS_M[2].slice(1), [a, b]);
10412 let l_ = 1.0 + sat * kl;
10413 let m_ = 1.0 + sat * km;
10414 let s_ = 1.0 + sat * ks;
10415 let l = l_ ** 3;
10416 let m = m_ ** 3;
10417 let s = s_ ** 3;
10418 let lds = 3.0 * kl * l_ ** 2;
10419 let mds = 3.0 * km * m_ ** 2;
10420 let sds = 3.0 * ks * s_ ** 2;
10421 let lds2 = 6.0 * kl ** 2 * l_;
10422 let mds2 = 6.0 * km ** 2 * m_;
10423 let sds2 = 6.0 * ks ** 2 * s_;
10424 let f = wl * l + wm * m + ws * s;
10425 let f1 = wl * lds + wm * mds + ws * sds;
10426 let f2 = wl * lds2 + wm * mds2 + ws * sds2;
10427 sat = sat - f * f1 / (f1 ** 2 - 0.5 * f * f2);
10428 return sat;
10429 }
10430 function okhslToOklab(hsl, lmsToRgb, okCoeff) {
10431 // Convert Okhsl to Oklab.
10432
10433 let [h, s, l] = hsl;
10434 let L = toeInv(l);
10435 let a = null;
10436 let b = null;
10437 h = constrain(h) / 360.0;
10438 if (L !== 0.0 && L !== 1.0 && s !== 0) {
10439 let a_ = Math.cos(tau * h);
10440 let b_ = Math.sin(tau * h);
10441 let [c0, cMid, cMax] = getCs([L, a_, b_], lmsToRgb, okCoeff);
10442
10443 // Interpolate the three values for C so that:
10444 // ```
10445 // At s=0: dC/ds = C_0, C=0
10446 // At s=0.8: C=C_mid
10447 // At s=1.0: C=C_max
10448 // ```
10449
10450 let mid = 0.8;
10451 let midInv = 1.25;
10452 let t, k0, k1, k2;
10453 if (s < mid) {
10454 t = midInv * s;
10455 k0 = 0.0;
10456 k1 = mid * c0;
10457 k2 = 1.0 - k1 / cMid;
10458 } else {
10459 t = 5 * (s - 0.8);
10460 k0 = cMid;
10461 k1 = 0.2 * cMid ** 2 * 1.25 ** 2 / c0;
10462 k2 = 1.0 - k1 / (cMax - cMid);
10463 }
10464 let c = k0 + t * k1 / (1.0 - k2 * t);
10465 a = c * a_;
10466 b = c * b_;
10467 }
10468 return [L, a, b];
10469 }
10470 function oklabToOkhsl(lab, lmsToRgb, okCoeff) {
10471 // Oklab to Okhsl.
10472
10473 // Epsilon for lightness should approach close to 32 bit lightness
10474 // Epsilon for saturation just needs to be sufficiently close when denoting achromatic
10475 let εL = 1e-7;
10476 let εS = 1e-4;
10477 let L = lab[0];
10478 let s = 0.0;
10479 let l = toe(L);
10480 let c = Math.sqrt(lab[1] ** 2 + lab[2] ** 2);
10481 let h = 0.5 + Math.atan2(-lab[2], -lab[1]) / tau;
10482 if (l !== 0.0 && l !== 1.0 && c !== 0) {
10483 let a_ = lab[1] / c;
10484 let b_ = lab[2] / c;
10485 let [c0, cMid, cMax] = getCs([L, a_, b_], lmsToRgb, okCoeff);
10486 let mid = 0.8;
10487 let midInv = 1.25;
10488 let k0, k1, k2, t;
10489 if (c < cMid) {
10490 k1 = mid * c0;
10491 k2 = 1.0 - k1 / cMid;
10492 t = c / (k1 + k2 * c);
10493 s = t * mid;
10494 } else {
10495 k0 = cMid;
10496 k1 = 0.2 * cMid ** 2 * midInv ** 2 / c0;
10497 k2 = 1.0 - k1 / (cMax - cMid);
10498 t = (c - k0) / (k1 + k2 * (c - k0));
10499 s = mid + 0.2 * t;
10500 }
10501 }
10502 const achromatic = Math.abs(s) < εS;
10503 if (achromatic || l === 0.0 || Math.abs(1 - l) < εL) {
10504 h = null;
10505 // Due to floating point imprecision near lightness of 1, we can end up
10506 // with really high around white, this is to provide consistency as
10507 // saturation can be really high for white due this imprecision.
10508 if (!achromatic) {
10509 s = 0.0;
10510 }
10511 } else {
10512 h = constrain(h * 360);
10513 }
10514 return [h, s, l];
10515 }
10516 const Okhsl = new ColorSpace({
10517 id: "okhsl",
10518 name: "Okhsl",
10519 coords: {
10520 h: {
10521 refRange: [0, 360],
10522 type: "angle",
10523 name: "Hue"
10524 },
10525 s: {
10526 range: [0, 1],
10527 name: "Saturation"
10528 },
10529 l: {
10530 range: [0, 1],
10531 name: "Lightness"
10532 }
10533 },
10534 base: Oklab,
10535 gamutSpace: "self",
10536 // Convert Oklab to Okhsl
10537 fromBase(lab) {
10538 return oklabToOkhsl(lab, toSRGBLinear, RGBCoeff);
10539 },
10540 // Convert Okhsl to Oklab
10541 toBase(hsl) {
10542 return okhslToOklab(hsl, toSRGBLinear, RGBCoeff);
10543 },
10544 formats: {
10545 color: {
10546 id: "--okhsl",
10547 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
10548 }
10549 }
10550 });
10551 Okhsl.rgbGamut = new RGBColorSpace({
10552 id: "okhsl-prism",
10553 cssId: "--okhsl-prism",
10554 name: "Okhsl Prism",
10555 base: Okhsl,
10556 fromBase(hsl) {
10557 return HSL.toBase([hsl[0], hsl[1] * 100, hsl[2] * 100]);
10558 },
10559 toBase(rgb) {
10560 const hsl = HSL.fromBase(rgb);
10561 hsl[1] /= 100;
10562 hsl[2] /= 100;
10563 return hsl;
10564 }
10565 });
10566
10567 var OKLrab = new ColorSpace({
10568 id: "oklrab",
10569 name: "Oklrab",
10570 coords: {
10571 l: {
10572 refRange: [0, 1],
10573 name: "Lightness"
10574 },
10575 a: {
10576 refRange: [-0.4, 0.4]
10577 },
10578 b: {
10579 refRange: [-0.4, 0.4]
10580 }
10581 },
10582 // Note that XYZ is relative to D65
10583 white: "D65",
10584 base: Oklab,
10585 fromBase(oklab) {
10586 return [toe(oklab[0]), oklab[1], oklab[2]];
10587 },
10588 toBase(oklrab) {
10589 return [toeInv(oklrab[0]), oklrab[1], oklrab[2]];
10590 },
10591 formats: {
10592 color: {
10593 coords: ["<percentage> | <number>", "<number> | <percentage>[-1,1]", "<number> | <percentage>[-1,1]"]
10594 }
10595 }
10596 });
10597
10598 var oklrch = new ColorSpace({
10599 id: "oklrch",
10600 name: "Oklrch",
10601 coords: {
10602 l: {
10603 refRange: [0, 1],
10604 name: "Lightness"
10605 },
10606 c: {
10607 refRange: [0, 0.4],
10608 name: "Chroma"
10609 },
10610 h: {
10611 refRange: [0, 360],
10612 type: "angle",
10613 name: "Hue"
10614 }
10615 },
10616 white: "D65",
10617 base: OKLrab,
10618 fromBase: lch.fromBase,
10619 toBase: lch.toBase,
10620 formats: {
10621 color: {
10622 coords: ["<percentage> | <number>", "<number> | <percentage>[0,1]", "<number> | <angle>"]
10623 }
10624 }
10625 });
10626
10627 // Okhsv class.
10628 //
10629 // ---- License ----
10630 //
10631 // Copyright (c) 2021 Björn Ottosson
10632 //
10633 // Permission is hereby granted, free of charge, to any person obtaining a copy of
10634 // this software and associated documentation files (the "Software"), to deal in
10635 // the Software without restriction, including without limitation the rights to
10636 // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10637 // of the Software, and to permit persons to whom the Software is furnished to do
10638 // so, subject to the following conditions:
10639 //
10640 // The above copyright notice and this permission notice shall be included in all
10641 // copies or substantial portions of the Software.
10642 //
10643 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
10644 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
10645 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
10646 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
10647 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
10648 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
10649 // SOFTWARE.
10650
10651 /** @import { Coords, Matrix3x3, OKCoeff, Vector3 } from "../types.js" */
10652
10653 /**
10654 *
10655 * @param {Vector3} hsv
10656 * @param {Matrix3x3} lmsToRgb
10657 * @param {OKCoeff} okCoeff
10658 * @returns {Coords}
10659 */
10660 function okhsvToOklab(hsv, lmsToRgb, okCoeff) {
10661 // Convert from Okhsv to Oklab."""
10662
10663 let [h, s, v] = hsv;
10664 h = constrain(h) / 360.0;
10665 let l = toeInv(v);
10666 let a = null;
10667 let b = null;
10668
10669 // Avoid processing gray or colors with undefined hues
10670 if (l !== 0.0 && s !== 0.0) {
10671 let a_ = Math.cos(tau * h);
10672 let b_ = Math.sin(tau * h);
10673 let cusp = findCusp(a_, b_, lmsToRgb, okCoeff);
10674 let [sMax, tMax] = toSt(cusp);
10675 let s0 = 0.5;
10676 let k = 1 - s0 / sMax;
10677
10678 // first we compute L and V as if the gamut is a perfect triangle:
10679
10680 // L, C when v==1:
10681 let lv = 1 - s * s0 / (s0 + tMax - tMax * k * s);
10682 let cv = s * tMax * s0 / (s0 + tMax - tMax * k * s);
10683 l = v * lv;
10684 let c = v * cv;
10685
10686 // then we compensate for both toe and the curved top part of the triangle:
10687 let lvt = toeInv(lv);
10688 let cvt = cv * lvt / lv;
10689 let lNew = toeInv(l);
10690 c = c * lNew / l;
10691 l = lNew;
10692
10693 // RGB scale
10694 let [rs, gs, bs] = oklabToLinearRGB([lvt, a_ * cvt, b_ * cvt], lmsToRgb);
10695 let scaleL = spow(1.0 / Math.max(Math.max(rs, gs), Math.max(bs, 0.0)), 1 / 3);
10696 l = l * scaleL;
10697 c = c * scaleL;
10698 a = c * a_;
10699 b = c * b_;
10700 }
10701 return [l, a, b];
10702 }
10703
10704 /**
10705 *
10706 * @param {Vector3} lab
10707 * @param {Matrix3x3} lmsToRgb
10708 * @param {OKCoeff} okCoeff
10709 * @returns {Coords}
10710 */
10711 function oklabToOkhsv(lab, lmsToRgb, okCoeff) {
10712 // Oklab to Okhsv.
10713
10714 // Epsilon for saturation just needs to be sufficiently close when denoting achromatic
10715 let ε = 1e-4;
10716 let l = lab[0];
10717 let s = 0.0;
10718 let v = toe(l);
10719 let c = Math.sqrt(lab[1] ** 2 + lab[2] ** 2);
10720 let h = 0.5 + Math.atan2(-lab[2], -lab[1]) / tau;
10721 if (l !== 0.0 && l !== 1 && c !== 0.0) {
10722 let a_ = lab[1] / c;
10723 let b_ = lab[2] / c;
10724 let cusp = findCusp(a_, b_, lmsToRgb, okCoeff);
10725 let [sMax, tMax] = toSt(cusp);
10726 let s0 = 0.5;
10727 let k = 1 - s0 / sMax;
10728
10729 // first we find `L_v`, `C_v`, `L_vt` and `C_vt`
10730 let t = tMax / (c + l * tMax);
10731 let lv = t * l;
10732 let cv = t * c;
10733 let lvt = toeInv(lv);
10734 let cvt = cv * lvt / lv;
10735
10736 // we can then use these to invert the step that compensates
10737 // for the toe and the curved top part of the triangle:
10738 let [rs, gs, bs] = oklabToLinearRGB([lvt, a_ * cvt, b_ * cvt], lmsToRgb);
10739 let scaleL = spow(1.0 / Math.max(Math.max(rs, gs), Math.max(bs, 0.0)), 1 / 3);
10740 l = l / scaleL;
10741 c = c / scaleL;
10742 c = c * toe(l) / l;
10743 l = toe(l);
10744
10745 // we can now compute v and s:
10746 v = l / lv;
10747 s = (s0 + tMax) * cv / (tMax * s0 + tMax * k * cv);
10748 }
10749 if (Math.abs(s) < ε || v === 0.0) {
10750 h = null;
10751 } else {
10752 h = constrain(h * 360);
10753 }
10754 return [h, s, v];
10755 }
10756 const Okhsv = new ColorSpace({
10757 id: "okhsv",
10758 name: "Okhsv",
10759 coords: {
10760 h: {
10761 refRange: [0, 360],
10762 type: "angle",
10763 name: "Hue"
10764 },
10765 s: {
10766 range: [0, 1],
10767 name: "Saturation"
10768 },
10769 v: {
10770 range: [0, 1],
10771 name: "Value"
10772 }
10773 },
10774 base: Oklab,
10775 gamutSpace: "self",
10776 // Convert Oklab to Okhsl
10777 fromBase(lab) {
10778 return oklabToOkhsv(lab, toSRGBLinear, RGBCoeff);
10779 },
10780 // Convert Okhsl to Oklab
10781 toBase(hsl) {
10782 return okhsvToOklab(hsl, toSRGBLinear, RGBCoeff);
10783 },
10784 formats: {
10785 color: {
10786 id: "--okhsv",
10787 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
10788 }
10789 }
10790 });
10791 Okhsv.rgbGamut = new RGBColorSpace({
10792 id: "okhsv-prism",
10793 cssId: "--okhsv-prism",
10794 name: "Okhsv Prism",
10795 base: Okhsv,
10796 fromBase(hsl) {
10797 return HSL.toBase([hsl[0], hsl[1] * 100, hsl[2] * 100]);
10798 },
10799 toBase(rgb) {
10800 const hsl = HSL.fromBase(rgb);
10801 hsl[1] /= 100;
10802 hsl[2] /= 100;
10803 return hsl;
10804 }
10805 });
10806
10807 let white = WHITES.D65;
10808 const ε$2 = 216 / 24389; // 6^3/29^3 == (24/116)^3
10809 const κ$1 = 24389 / 27; // 29^3/3^3
10810 const [U_PRIME_WHITE, V_PRIME_WHITE] = uv({
10811 space: XYZ_D65,
10812 coords: white
10813 });
10814 var Luv = new ColorSpace({
10815 id: "luv",
10816 name: "Luv",
10817 coords: {
10818 l: {
10819 refRange: [0, 100],
10820 name: "Lightness"
10821 },
10822 // Reference ranges from https://facelessuser.github.io/coloraide/colors/luv/
10823 u: {
10824 refRange: [-215, 215]
10825 },
10826 v: {
10827 refRange: [-215, 215]
10828 }
10829 },
10830 white: white,
10831 base: XYZ_D65,
10832 // Convert D65-adapted XYZ to Luv
10833 // https://en.wikipedia.org/wiki/CIELUV#The_forward_transformation
10834 fromBase(XYZ) {
10835 let xyz = /** @type {[number, number, number]} */[skipNone(XYZ[0]), skipNone(XYZ[1]), skipNone(XYZ[2])];
10836 let y = xyz[1];
10837 let [up, vp] = uv({
10838 space: XYZ_D65,
10839 coords: xyz
10840 });
10841
10842 // Protect against XYZ of [0, 0, 0]
10843 if (!Number.isFinite(up) || !Number.isFinite(vp)) {
10844 return [0, 0, 0];
10845 }
10846 let L = y <= ε$2 ? κ$1 * y : 116 * Math.cbrt(y) - 16;
10847 return [L, 13 * L * (up - U_PRIME_WHITE), 13 * L * (vp - V_PRIME_WHITE)];
10848 },
10849 // Convert Luv to D65-adapted XYZ
10850 // https://en.wikipedia.org/wiki/CIELUV#The_reverse_transformation
10851 toBase(Luv) {
10852 let [L, u, v] = Luv;
10853
10854 // Protect against division by zero and none Lightness
10855 if (L === 0 || isNone(L)) {
10856 return [0, 0, 0];
10857 }
10858 u = skipNone(u);
10859 v = skipNone(v);
10860 let up = u / (13 * L) + U_PRIME_WHITE;
10861 let vp = v / (13 * L) + V_PRIME_WHITE;
10862 let y = L <= 8 ? L / κ$1 : Math.pow((L + 16) / 116, 3);
10863 return [y * (9 * up / (4 * vp)), y, y * ((12 - 3 * up - 20 * vp) / (4 * vp))];
10864 },
10865 formats: {
10866 color: {
10867 id: "--luv",
10868 coords: ["<number> | <percentage>", "<number> | <percentage>", "<number> | <percentage>"]
10869 }
10870 }
10871 });
10872
10873 var LCHuv = new ColorSpace({
10874 id: "lchuv",
10875 name: "LChuv",
10876 coords: {
10877 l: {
10878 refRange: [0, 100],
10879 name: "Lightness"
10880 },
10881 c: {
10882 refRange: [0, 220],
10883 name: "Chroma"
10884 },
10885 h: {
10886 refRange: [0, 360],
10887 type: "angle",
10888 name: "Hue"
10889 }
10890 },
10891 base: Luv,
10892 fromBase: lch.fromBase,
10893 toBase: lch.toBase,
10894 formats: {
10895 color: {
10896 id: "--lchuv",
10897 coords: ["<number> | <percentage>", "<number> | <percentage>", "<number> | <angle>"]
10898 }
10899 }
10900 });
10901
10902 /*
10903 Adapted from: https://github.com/hsluv/hsluv-javascript/blob/14b49e6cf9a9137916096b8487a5372626b57ba4/src/hsluv.ts
10904
10905 Copyright (c) 2012-2022 Alexei Boronine
10906
10907 Permission is hereby granted, free of charge, to any person obtaining a copy
10908 of this software and associated documentation files (the "Software"), to deal
10909 in the Software without restriction, including without limitation the rights
10910 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10911 copies of the Software, and to permit persons to whom the Software is
10912 furnished to do so, subject to the following conditions:
10913
10914 The above copyright notice and this permission notice shall be included in all
10915 copies or substantial portions of the Software.
10916
10917 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
10918 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
10919 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
10920 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
10921 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
10922 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
10923 SOFTWARE.
10924 */
10925
10926 const ε$1 = 216 / 24389; // 6^3/29^3 == (24/116)^3
10927 const κ = 24389 / 27; // 29^3/3^3
10928
10929 const m_r0 = fromXYZ_M$3[0][0];
10930 const m_r1 = fromXYZ_M$3[0][1];
10931 const m_r2 = fromXYZ_M$3[0][2];
10932 const m_g0 = fromXYZ_M$3[1][0];
10933 const m_g1 = fromXYZ_M$3[1][1];
10934 const m_g2 = fromXYZ_M$3[1][2];
10935 const m_b0 = fromXYZ_M$3[2][0];
10936 const m_b1 = fromXYZ_M$3[2][1];
10937 const m_b2 = fromXYZ_M$3[2][2];
10938 function distanceFromOriginAngle(slope, intercept, angle) {
10939 const d = intercept / (Math.sin(angle) - slope * Math.cos(angle));
10940 return d < 0 ? Infinity : d;
10941 }
10942
10943 /**
10944 * @param {number} l
10945 */
10946 function calculateBoundingLines(l) {
10947 const sub1 = Math.pow(l + 16, 3) / 1560896;
10948 const sub2 = sub1 > ε$1 ? sub1 : l / κ;
10949 const s1r = sub2 * (284517 * m_r0 - 94839 * m_r2);
10950 const s2r = sub2 * (838422 * m_r2 + 769860 * m_r1 + 731718 * m_r0);
10951 const s3r = sub2 * (632260 * m_r2 - 126452 * m_r1);
10952 const s1g = sub2 * (284517 * m_g0 - 94839 * m_g2);
10953 const s2g = sub2 * (838422 * m_g2 + 769860 * m_g1 + 731718 * m_g0);
10954 const s3g = sub2 * (632260 * m_g2 - 126452 * m_g1);
10955 const s1b = sub2 * (284517 * m_b0 - 94839 * m_b2);
10956 const s2b = sub2 * (838422 * m_b2 + 769860 * m_b1 + 731718 * m_b0);
10957 const s3b = sub2 * (632260 * m_b2 - 126452 * m_b1);
10958 return {
10959 r0s: s1r / s3r,
10960 r0i: s2r * l / s3r,
10961 r1s: s1r / (s3r + 126452),
10962 r1i: (s2r - 769860) * l / (s3r + 126452),
10963 g0s: s1g / s3g,
10964 g0i: s2g * l / s3g,
10965 g1s: s1g / (s3g + 126452),
10966 g1i: (s2g - 769860) * l / (s3g + 126452),
10967 b0s: s1b / s3b,
10968 b0i: s2b * l / s3b,
10969 b1s: s1b / (s3b + 126452),
10970 b1i: (s2b - 769860) * l / (s3b + 126452)
10971 };
10972 }
10973 function calcMaxChromaHsluv(lines, h) {
10974 const hueRad = h / 360 * Math.PI * 2;
10975 const r0 = distanceFromOriginAngle(lines.r0s, lines.r0i, hueRad);
10976 const r1 = distanceFromOriginAngle(lines.r1s, lines.r1i, hueRad);
10977 const g0 = distanceFromOriginAngle(lines.g0s, lines.g0i, hueRad);
10978 const g1 = distanceFromOriginAngle(lines.g1s, lines.g1i, hueRad);
10979 const b0 = distanceFromOriginAngle(lines.b0s, lines.b0i, hueRad);
10980 const b1 = distanceFromOriginAngle(lines.b1s, lines.b1i, hueRad);
10981 return Math.min(r0, r1, g0, g1, b0, b1);
10982 }
10983 var hsluv = new ColorSpace({
10984 id: "hsluv",
10985 name: "HSLuv",
10986 coords: {
10987 h: {
10988 refRange: [0, 360],
10989 type: "angle",
10990 name: "Hue"
10991 },
10992 s: {
10993 range: [0, 100],
10994 name: "Saturation"
10995 },
10996 l: {
10997 range: [0, 100],
10998 name: "Lightness"
10999 }
11000 },
11001 base: LCHuv,
11002 gamutSpace: sRGB,
11003 rgbGamut: sRGB,
11004 // Convert LCHuv to HSLuv
11005 fromBase(lch) {
11006 let [l, c, h] = [skipNone(lch[0]), skipNone(lch[1]), skipNone(lch[2])];
11007 let s;
11008 if (l > 99.9999999) {
11009 s = 0;
11010 l = 100;
11011 } else if (l < 0.00000001) {
11012 s = 0;
11013 l = 0;
11014 } else {
11015 let lines = calculateBoundingLines(l);
11016 let max = calcMaxChromaHsluv(lines, h);
11017 s = c / max * 100;
11018 }
11019 return [h, s, l];
11020 },
11021 // Convert HSLuv to LCHuv
11022 toBase(hsl) {
11023 let [h, s, l] = [skipNone(hsl[0]), skipNone(hsl[1]), skipNone(hsl[2])];
11024 let c;
11025 if (l > 99.9999999) {
11026 l = 100;
11027 c = 0;
11028 } else if (l < 0.00000001) {
11029 l = 0;
11030 c = 0;
11031 } else {
11032 let lines = calculateBoundingLines(l);
11033 let max = calcMaxChromaHsluv(lines, h);
11034 c = max / 100 * s;
11035 }
11036 return [l, c, h];
11037 },
11038 formats: {
11039 color: {
11040 id: "--hsluv",
11041 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
11042 }
11043 }
11044 });
11045
11046 /*
11047 Adapted from: https://github.com/hsluv/hsluv-javascript/blob/14b49e6cf9a9137916096b8487a5372626b57ba4/src/hsluv.ts
11048
11049 Copyright (c) 2012-2022 Alexei Boronine
11050
11051 Permission is hereby granted, free of charge, to any person obtaining a copy
11052 of this software and associated documentation files (the "Software"), to deal
11053 in the Software without restriction, including without limitation the rights
11054 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11055 copies of the Software, and to permit persons to whom the Software is
11056 furnished to do so, subject to the following conditions:
11057
11058 The above copyright notice and this permission notice shall be included in all
11059 copies or substantial portions of the Software.
11060
11061 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11062 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
11063 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
11064 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
11065 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
11066 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
11067 SOFTWARE.
11068 */
11069
11070
11071 fromXYZ_M$3[0][0];
11072 fromXYZ_M$3[0][1];
11073 fromXYZ_M$3[0][2];
11074 fromXYZ_M$3[1][0];
11075 fromXYZ_M$3[1][1];
11076 fromXYZ_M$3[1][2];
11077 fromXYZ_M$3[2][0];
11078 fromXYZ_M$3[2][1];
11079 fromXYZ_M$3[2][2];
11080 function distanceFromOrigin(slope, intercept) {
11081 return Math.abs(intercept) / Math.sqrt(Math.pow(slope, 2) + 1);
11082 }
11083 function calcMaxChromaHpluv(lines) {
11084 let r0 = distanceFromOrigin(lines.r0s, lines.r0i);
11085 let r1 = distanceFromOrigin(lines.r1s, lines.r1i);
11086 let g0 = distanceFromOrigin(lines.g0s, lines.g0i);
11087 let g1 = distanceFromOrigin(lines.g1s, lines.g1i);
11088 let b0 = distanceFromOrigin(lines.b0s, lines.b0i);
11089 let b1 = distanceFromOrigin(lines.b1s, lines.b1i);
11090 return Math.min(r0, r1, g0, g1, b0, b1);
11091 }
11092 const HPLuv = new ColorSpace({
11093 id: "hpluv",
11094 name: "HPLuv",
11095 coords: {
11096 h: {
11097 refRange: [0, 360],
11098 type: "angle",
11099 name: "Hue"
11100 },
11101 s: {
11102 range: [0, 100],
11103 name: "Saturation"
11104 },
11105 l: {
11106 range: [0, 100],
11107 name: "Lightness"
11108 }
11109 },
11110 base: LCHuv,
11111 gamutSpace: "self",
11112 // Convert LCHuv to HPLuv
11113 fromBase(lch) {
11114 let [l, c, h] = [skipNone(lch[0]), skipNone(lch[1]), skipNone(lch[2])];
11115 let s;
11116 if (l > 99.9999999) {
11117 s = 0;
11118 l = 100;
11119 } else if (l < 0.00000001) {
11120 s = 0;
11121 l = 0;
11122 } else {
11123 let lines = calculateBoundingLines(l);
11124 let max = calcMaxChromaHpluv(lines);
11125 s = c / max * 100;
11126 }
11127 return [h, s, l];
11128 },
11129 // Convert HPLuv to LCHuv
11130 toBase(hsl) {
11131 let [h, s, l] = [skipNone(hsl[0]), skipNone(hsl[1]), skipNone(hsl[2])];
11132 let c;
11133 if (l > 99.9999999) {
11134 l = 100;
11135 c = 0;
11136 } else if (l < 0.00000001) {
11137 l = 0;
11138 c = 0;
11139 } else {
11140 let lines = calculateBoundingLines(l);
11141 let max = calcMaxChromaHpluv(lines);
11142 c = max / 100 * s;
11143 }
11144 return [l, c, h];
11145 },
11146 formats: {
11147 color: {
11148 id: "--hpluv",
11149 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
11150 }
11151 }
11152 });
11153 HPLuv.rgbGamut = new RGBColorSpace({
11154 id: "hpluv-prism",
11155 cssId: "--hpluv-prism",
11156 name: "HPLuv Prism",
11157 base: HPLuv,
11158 fromBase(hsl) {
11159 return HSL.toBase(hsl);
11160 },
11161 toBase(rgb) {
11162 return HSL.fromBase(rgb);
11163 }
11164 });
11165
11166 /**
11167 * Helmlab GenSpace — generation-optimized color space for interpolation.
11168 *
11169 * Pipeline (v0.11.1, depressed cubic + chroma power + L-gated enrichment):
11170 * XYZ → M1 → depcubic(α=0.021) → M2 → chroma_power(0.978) →
11171 * PW_L → L-gated hue enrichment → Lab
11172 *
11173 * Optimized for perceptually uniform gradients, palette generation,
11174 * and color-mix. 59-8 vs OKLab in head-to-head benchmarks (83 metrics,
11175 * 3038 gradient pairs, sRGB/P3/Rec.2020). 360/360/360 cusps.
11176 *
11177 * Key properties:
11178 * - Depressed cubic: y³ + αy = x, finite derivative at zero
11179 * - Chroma power (0.978): improves gradient CV uniformity
11180 * - L-gated hue enrichment: fixes blue→white purple shift
11181 * - Structurally achromatic: a=b≈0 for all grays
11182 *
11183 * Note on blue-region gamut fold:
11184 * All M1→f→M2 spaces (OKLab, IPT, HelmGen) exhibit a tiny non-contiguous
11185 * gamut region near h≈260° in sRGB. This is a mathematical consequence of
11186 * mixing LMS channels before applying a power-like transfer: the inverse
11187 * creates a cubic polynomial that can have two positive roots in the blue
11188 * region. OKLab has 46 such holes; HelmGen has 5, each ~0.001 chroma wide
11189 * (sub-pixel, invisible). See: color.js#81, csswg-drafts#7071.
11190 *
11191 * Reference: arXiv:2602.23010
11192 * @see https://github.com/Grkmyldz148/helmlab
11193 */
11194
11195 /** @import { Matrix3x3 } from "../types.js" */
11196
11197 // ── Depressed cubic parameter ──────────────────────────────────────
11198 const ALPHA = 0.021;
11199 const S = Math.sqrt(ALPHA / 3);
11200 const S3 = S * S * S;
11201
11202 // ── Chroma power ───────────────────────────────────────────────────
11203 const CP = 0.978;
11204
11205 // ── L-gated hue enrichment parameters ──────────────────────────────
11206 const ENR_AMP = 0.058;
11207 const ENR_CENTER = 264.5 * Math.PI / 180; // radians
11208 const ENR_SIGMA = 0.7;
11209 const ENR_LLO = 0.37;
11210 const ENR_LHI = 1.0;
11211
11212 // ── Core matrices (v0.11.1) ────────────────────────────────────────
11213
11214 /** @type {Matrix3x3} */
11215 // prettier-ignore
11216 // M1 = M1_orig @ CAT_TO_HELM (Bradford CAT baked in: Color.js D65 → Helmlab D65 → LMS)
11217 const M1 = [[8.1548321559412884e-01, 3.6033406153856506e-01, -1.2434135574228214e-01], [3.3010083527450780e-02, 9.2928650570661686e-01, 3.6121927165754429e-02], [4.8188273564568611e-02, 2.6428415753384238e-01, 6.3349717841955344e-01]];
11218 /** @type {Matrix3x3} */
11219 // prettier-ignore
11220 const M1_INV = [[1.2325947975032656e+00, -5.5575902392875232e-01, 2.7362015347715829e-01], [-4.0801327874216024e-02, 1.1122288637386530e+00, -7.1427535864437813e-02], [-7.6738259283377658e-02, -4.2172784577108585e-01, 1.5875238558143416e+00]];
11221
11222 /** @type {Matrix3x3} */
11223 // prettier-ignore
11224 const M2 = [[0.21193779684470104, 0.7992121834263127, -0.00410075161564345], [2.4672018828033475, -2.9877348024830788, 0.520532919679731], [-0.11390787868068575, 1.3932982808117473, -1.279390402131062]];
11225 /** @type {Matrix3x3} */
11226 // prettier-ignore
11227 const M2_INV = [[0.9930001151336143, 0.32599327253052285, 0.12945085631713921], [0.9930001151336139, -0.08708353111074627, -0.03861361743004929], [0.9930001151336136, -0.12386097008215022, -0.8351991365871061]];
11228
11229 // ── Piecewise-linear L correction (21 breakpoints, v0.11.1) ───────
11230 // prettier-ignore
11231 const PW_L_IN = [0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0];
11232 // prettier-ignore
11233 const PW_L_OUT = [0, 0.009494013522189627, 0.02564569838030986, 0.055259661658689105, 0.10574901531227408, 0.16055853320726027, 0.21405964892993756, 0.26786230508811226, 0.3220435246104499, 0.3739052098520243, 0.43020997780918835, 0.4835465162128873, 0.5399824670411353, 0.5956710081330342, 0.6542161666450478, 0.7115380216519989, 0.7702762412711669, 0.8293313467712837, 0.889406386197059, 0.9462829573474728, 1.0];
11234 const PW_N = PW_L_IN.length;
11235
11236 // ── Depressed cubic: y³ + αy = x ──────────────────────────────────
11237
11238 function depcubicFwd(x) {
11239 let t = x / (2 * S3);
11240 let y = 2 * S * Math.sinh(Math.asinh(t) / 3);
11241 // Halley refinement
11242 let f = y * y * y + ALPHA * y - x;
11243 let fp = 3 * y * y + ALPHA;
11244 let fpp = 6 * y;
11245 let denom = 2 * fp * fp - f * fpp;
11246 if (Math.abs(denom) > 1e-30) {
11247 y -= 2 * f * fp / denom;
11248 }
11249 return y;
11250 }
11251 function depcubicInv(y) {
11252 return y * y * y + ALPHA * y;
11253 }
11254
11255 // ── L-gated hue enrichment ─────────────────────────────────────────
11256
11257 function enrichGate(L) {
11258 let t = Math.max(0, Math.min(1, (L - ENR_LLO) / (ENR_LHI - ENR_LLO)));
11259 return Math.sin(Math.PI * t) ** 2;
11260 }
11261 function enrichFwd(L, a, b) {
11262 let C = Math.sqrt(a * a + b * b);
11263 if (C < 1e-12) {
11264 return [a, b];
11265 }
11266 let gate = enrichGate(L);
11267 if (gate < 1e-12) {
11268 return [a, b];
11269 }
11270 let h = Math.atan2(b, a);
11271 let dh = h - ENR_CENTER;
11272 dh = dh - Math.round(dh / (2 * Math.PI)) * 2 * Math.PI;
11273 let gauss = Math.exp(-0.5 * (dh / ENR_SIGMA) ** 2);
11274 let hNew = h + ENR_AMP * gate * gauss;
11275 return [C * Math.cos(hNew), C * Math.sin(hNew)];
11276 }
11277 function enrichInv(L, a, b) {
11278 let C = Math.sqrt(a * a + b * b);
11279 if (C < 1e-12) {
11280 return [a, b];
11281 }
11282 let gate = enrichGate(L);
11283 if (gate < 1e-12) {
11284 return [a, b];
11285 }
11286 let hTarget = Math.atan2(b, a);
11287 let sig2 = ENR_SIGMA * ENR_SIGMA;
11288 let ag = ENR_AMP * gate;
11289 let h = hTarget;
11290 for (let i = 0; i < 8; i++) {
11291 let dh = h - ENR_CENTER;
11292 dh = dh - Math.round(dh / (2 * Math.PI)) * 2 * Math.PI;
11293 let gauss = Math.exp(-0.5 * dh * dh / sig2);
11294 let F = h + ag * gauss - hTarget;
11295 let Fp = 1 + ag * gauss * (-dh / sig2);
11296 let Fpp = ag * gauss * (-1 / sig2 + dh * dh / (sig2 * sig2));
11297 let den = 2 * Fp * Fp - F * Fpp;
11298 if (Math.abs(den) > 1e-30) {
11299 h -= 2 * F * Fp / den;
11300 }
11301 }
11302 return [C * Math.cos(h), C * Math.sin(h)];
11303 }
11304
11305 // ── PW L correction ───────────────────────────────────────────────
11306
11307 function pwLForward(L) {
11308 if (L <= 0 || L >= 1) {
11309 return L;
11310 }
11311 let lo = 0,
11312 hi = PW_N - 1;
11313 while (hi - lo > 1) {
11314 let mid = lo + hi >> 1;
11315 if (PW_L_IN[mid] <= L) {
11316 lo = mid;
11317 } else {
11318 hi = mid;
11319 }
11320 }
11321 let t = (L - PW_L_IN[lo]) / (PW_L_IN[hi] - PW_L_IN[lo]);
11322 return PW_L_OUT[lo] + t * (PW_L_OUT[hi] - PW_L_OUT[lo]);
11323 }
11324 function pwLInverse(L) {
11325 if (L <= PW_L_OUT[0] || L >= PW_L_OUT[PW_N - 1]) {
11326 return L;
11327 }
11328 let lo = 0,
11329 hi = PW_N - 1;
11330 while (hi - lo > 1) {
11331 let mid = lo + hi >> 1;
11332 if (PW_L_OUT[mid] <= L) {
11333 lo = mid;
11334 } else {
11335 hi = mid;
11336 }
11337 }
11338 let t = (L - PW_L_OUT[lo]) / (PW_L_OUT[hi] - PW_L_OUT[lo]);
11339 return PW_L_IN[lo] + t * (PW_L_IN[hi] - PW_L_IN[lo]);
11340 }
11341
11342 // ── Color space definition ─────────────────────────────────────────
11343
11344 var HelmGen = new ColorSpace({
11345 id: "helmgen",
11346 name: "HelmGen",
11347 cssId: "--helmgen",
11348 coords: {
11349 l: {
11350 refRange: [0, 1],
11351 name: "Lightness"
11352 },
11353 a: {
11354 refRange: [-0.6, 0.6]
11355 },
11356 b: {
11357 refRange: [-0.6, 0.6]
11358 }
11359 },
11360 white: "D65",
11361 base: XYZ_D65,
11362 fromBase(xyz) {
11363 // Stage 1: XYZ → LMS (M1)
11364 let lms = multiply_v3_m3x3(xyz, M1);
11365
11366 // Stage 2: Depressed cubic transfer (y³ + αy = x)
11367 let c0 = depcubicFwd(Math.max(lms[0], 0));
11368 let c1 = depcubicFwd(Math.max(lms[1], 0));
11369 let c2 = depcubicFwd(Math.max(lms[2], 0));
11370
11371 // Stage 2.5: Smooth neutral blend (C∞ correction for achromatic precision)
11372 {
11373 let mean = (c0 + c1 + c2) / 3;
11374 let mx = Math.max(c0, c1, c2);
11375 let mn = Math.min(c0, c1, c2);
11376 let spread = (mx - mn) / Math.max(Math.abs(mean), 1e-30);
11377 let w = Math.exp(-((spread / 1e-5) ** 2));
11378 c0 += w * (mean - c0);
11379 c1 += w * (mean - c1);
11380 c2 += w * (mean - c2);
11381 }
11382
11383 // Stage 3: LMS_c → Lab (M2)
11384 let [L, a, b] = multiply_v3_m3x3([c0, c1, c2], M2);
11385
11386 // Stage 3.5: Chroma power (cp=0.978)
11387 {
11388 let C = Math.sqrt(a * a + b * b);
11389 if (C > 1e-12) {
11390 let Cnew = Math.pow(C, CP);
11391 let s = Cnew / C;
11392 a *= s;
11393 b *= s;
11394 }
11395 }
11396
11397 // Stage 4: Piecewise-linear L correction
11398 L = pwLForward(L);
11399
11400 // Stage 5: L-gated hue enrichment
11401 [a, b] = enrichFwd(L, a, b);
11402 return [L, a, b];
11403 },
11404 toBase(lab) {
11405 let [L, a, b] = lab;
11406
11407 // Undo Stage 5: L-gated hue enrichment
11408 [a, b] = enrichInv(L, a, b);
11409
11410 // Undo Stage 4: PW L correction
11411 L = pwLInverse(L);
11412
11413 // Undo Stage 3.5: Chroma power inverse (C^(1/cp))
11414 {
11415 let C = Math.sqrt(a * a + b * b);
11416 if (C > 1e-12) {
11417 let Corig = Math.pow(C, 1 / CP);
11418 let s = Corig / C;
11419 a *= s;
11420 b *= s;
11421 }
11422 }
11423
11424 // Undo Stage 3: Lab → LMS_c (M2_inv)
11425 let [lc0, lc1, lc2] = multiply_v3_m3x3([L, a, b], M2_INV);
11426
11427 // Undo Stage 2.5: Smooth neutral blend
11428 {
11429 let mean = (lc0 + lc1 + lc2) / 3;
11430 let mx = Math.max(lc0, lc1, lc2);
11431 let mn = Math.min(lc0, lc1, lc2);
11432 let spread = (mx - mn) / Math.max(Math.abs(mean), 1e-30);
11433 let w = Math.exp(-((spread / 1e-5) ** 2));
11434 lc0 += w * (mean - lc0);
11435 lc1 += w * (mean - lc1);
11436 lc2 += w * (mean - lc2);
11437 }
11438
11439 // Undo Stage 2: Inverse depressed cubic (x = y³ + αy)
11440 let l0 = depcubicInv(lc0);
11441 let l1 = depcubicInv(lc1);
11442 let l2 = depcubicInv(lc2);
11443
11444 // Undo Stage 1: LMS → XYZ (M1_inv)
11445 return multiply_v3_m3x3([l0, l1, l2], M1_INV);
11446 }
11447 });
11448
11449 /**
11450 * HelmGenLCh — cylindrical form of Helmlab GenSpace.
11451 *
11452 * Converts GenSpace's rectangular (L, a, b) coordinates to
11453 * cylindrical (L, C, h). Ideal for CSS interpolation contexts
11454 * like gradients and color-mix where hue angle matters.
11455 *
11456 * @see https://github.com/Grkmyldz148/helmlab
11457 */
11458 var helmgenlch = new ColorSpace({
11459 id: "helmgenlch",
11460 name: "HelmGenLCh",
11461 coords: {
11462 l: {
11463 refRange: [0, 1],
11464 name: "Lightness"
11465 },
11466 c: {
11467 refRange: [0, 0.65],
11468 name: "Chroma"
11469 },
11470 h: {
11471 refRange: [0, 360],
11472 type: "angle",
11473 name: "Hue"
11474 }
11475 },
11476 white: "D65",
11477 base: HelmGen,
11478 fromBase: lch.fromBase,
11479 toBase: lch.toBase
11480 });
11481
11482 var REC_2100_Linear = new RGBColorSpace({
11483 id: "rec2100-linear",
11484 name: "Linear REC.2100",
11485 white: "D65",
11486 toBase: REC_2020_Linear.toBase,
11487 fromBase: REC_2020_Linear.fromBase
11488 });
11489
11490 const Yw = 203; // absolute luminance of media white, cd/m²
11491 const n = 2610 / 2 ** 14;
11492 const ninv = 2 ** 14 / 2610;
11493 const m = 2523 / 2 ** 5;
11494 const minv = 2 ** 5 / 2523;
11495 const c1 = 3424 / 2 ** 12;
11496 const c2 = 2413 / 2 ** 7;
11497 const c3 = 2392 / 2 ** 7;
11498 var rec2100Pq = new RGBColorSpace({
11499 id: "rec2100pq",
11500 cssId: "rec2100-pq",
11501 name: "REC.2100-PQ",
11502 base: REC_2100_Linear,
11503 linearGamut: REC_2100_Linear,
11504 toBase(RGB) {
11505 // given PQ encoded component in range [0, 1]
11506 // return media-white relative linear-light
11507 return RGB.map(function (val) {
11508 let x = (Math.max(val ** minv - c1, 0) / (c2 - c3 * val ** minv)) ** ninv;
11509 return x * 10000 / Yw; // luminance relative to diffuse white, [0, 70 or so].
11510 });
11511 },
11512 fromBase(RGB) {
11513 // given media-white relative linear-light
11514 // returnPQ encoded component in range [0, 1]
11515 return RGB.map(function (val) {
11516 let x = Math.max(val * Yw / 10000, 0); // absolute luminance of peak white is 10,000 cd/m².
11517 let num = c1 + c2 * x ** n;
11518 let denom = 1 + c3 * x ** n;
11519 return (num / denom) ** m;
11520 });
11521 }
11522 });
11523
11524 const a = 0.17883277;
11525 const b = 0.28466892; // 1 - (4 * a)
11526 const c = 0.55991073; // 0.5 - a * Math.log(4 *a)
11527
11528 const scale = 3.7743; // Place 18% grey at HLG 0.38, so media white at 0.75
11529
11530 var rec2100Hlg = new RGBColorSpace({
11531 id: "rec2100hlg",
11532 cssId: "rec2100-hlg",
11533 name: "REC.2100-HLG",
11534 referred: "scene",
11535 base: REC_2100_Linear,
11536 linearGamut: REC_2100_Linear,
11537 toBase(RGB) {
11538 // given HLG encoded component in range [0, 1]
11539 // return media-white relative linear-light
11540 return RGB.map(function (val) {
11541 // first the HLG EOTF
11542 // ITU-R BT.2390-10 p.30 section
11543 // 6.3 The hybrid log-gamma electro-optical transfer function (EOTF)
11544 // Then scale by 3 so media white is 1.0
11545 if (val <= 0.5) {
11546 return val ** 2 / 3 * scale;
11547 }
11548 return (Math.exp((val - c) / a) + b) / 12 * scale;
11549 });
11550 },
11551 fromBase(RGB) {
11552 // given media-white relative linear-light
11553 // where diffuse white is 1.0,
11554 // return HLG encoded component in range [0, 1]
11555 return RGB.map(function (val) {
11556 // first scale to put linear-light media white at 1/3
11557 val /= scale;
11558 // now the HLG OETF
11559 // ITU-R BT.2390-10 p.23
11560 // 6.1 The hybrid log-gamma opto-electronic transfer function (OETF)
11561 if (val <= 1 / 12) {
11562 return spow(3 * val, 0.5);
11563 }
11564 return a * Math.log(12 * val - b) + c;
11565 });
11566 }
11567 });
11568
11569 /** @import { White } from "./types.js" */
11570
11571 // Type re-exports
11572 /** @typedef {import("./types.js").CAT} CAT */
11573
11574 /** @type {Record<string, CAT>} */
11575 const CATs = {};
11576 hooks.add("chromatic-adaptation-start", env => {
11577 if (env.options.method) {
11578 env.M = adapt(env.W1, env.W2, env.options.method);
11579 }
11580 });
11581 hooks.add("chromatic-adaptation-end", env => {
11582 if (!env.M) {
11583 env.M = adapt(env.W1, env.W2, env.options.method);
11584 }
11585 });
11586 function defineCAT(/** @type {CAT} */{
11587 id,
11588 toCone_M,
11589 fromCone_M
11590 }) {
11591 // Use id, toCone_M, fromCone_M like variables
11592 CATs[id] = arguments[0];
11593 }
11594
11595 /**
11596 *
11597 * @param {White} W1
11598 * @param {White} W2
11599 * @param {string} id
11600 * @returns {number[][]}
11601 */
11602 function adapt(W1, W2, id = "Bradford") {
11603 // adapt from a source whitepoint or illuminant W1
11604 // to a destination whitepoint or illuminant W2,
11605 // using the given chromatic adaptation transform (CAT)
11606 // debugger;
11607 let method = CATs[id];
11608 let [ρs, γs, βs] = multiplyMatrices(method.toCone_M, W1);
11609 let [ρd, γd, βd] = multiplyMatrices(method.toCone_M, W2);
11610
11611 // all practical illuminants have non-zero XYZ so no division by zero can occur below
11612 // prettier-ignore
11613 let scale = [[ρd / ρs, 0, 0], [0, γd / γs, 0], [0, 0, βd / βs]];
11614 // console.log({scale});
11615
11616 let scaled_cone_M = multiplyMatrices(scale, method.toCone_M);
11617 let adapt_M = multiplyMatrices(method.fromCone_M, scaled_cone_M);
11618 // console.log({scaled_cone_M, adapt_M});
11619 return adapt_M;
11620 }
11621
11622 // prettier-ignore
11623 defineCAT({
11624 id: "von Kries",
11625 toCone_M: [[0.4002400, 0.7076000, -0.0808100], [-0.2263000, 1.1653200, 0.0457000], [0.0000000, 0.0000000, 0.9182200]],
11626 fromCone_M: [[1.8599363874558397, -1.1293816185800916, 0.21989740959619328], [0.3611914362417676, 0.6388124632850422, -0.000006370596838649899], [0, 0, 1.0890636230968613]]
11627 });
11628
11629 // prettier-ignore
11630 defineCAT({
11631 id: "Bradford",
11632 // Convert an array of XYZ values in the range 0.0 - 1.0
11633 // to cone fundamentals
11634 toCone_M: [[0.8951000, 0.2664000, -0.1614000], [-0.7502000, 1.7135000, 0.0367000], [0.0389000, -0.0685000, 1.0296000]],
11635 // and back
11636 fromCone_M: [[0.9869929054667121, -0.14705425642099013, 0.15996265166373122], [0.4323052697233945, 0.5183602715367774, 0.049291228212855594], [-0.00852866457517732, 0.04004282165408486, 0.96848669578755]]
11637 });
11638
11639 // prettier-ignore
11640 defineCAT({
11641 id: "CAT02",
11642 // with complete chromatic adaptation to W2, so D = 1.0
11643 toCone_M: [[0.7328000, 0.4296000, -0.1624000], [-0.7036000, 1.6975000, 0.0061000], [0.0030000, 0.0136000, 0.9834000]],
11644 fromCone_M: [[1.0961238208355142, -0.27886900021828726, 0.18274517938277307], [0.4543690419753592, 0.4735331543074117, 0.07209780371722911], [-0.009627608738429355, -0.00569803121611342, 1.0153256399545427]]
11645 });
11646
11647 // prettier-ignore
11648 defineCAT({
11649 id: "CAT16",
11650 toCone_M: [[0.401288, 0.650173, -0.051461], [-0.250268, 1.204414, 0.045854], [-0.002079, 0.048952, 0.953127]],
11651 // the extra precision is needed to avoid roundtripping errors
11652 fromCone_M: [[1.862067855087233, -1.0112546305316845, 0.14918677544445172], [0.3875265432361372, 0.6214474419314753, -0.008973985167612521], [-0.01584149884933386, -0.03412293802851557, 1.0499644368778496]]
11653 });
11654
11655 // prettier-ignore
11656 Object.assign(WHITES, {
11657 // whitepoint values from ASTM E308-01 with 10nm spacing, 1931 2 degree observer
11658 // all normalized to Y (luminance) = 1.00000
11659 // Illuminant A is a tungsten electric light, giving a very warm, orange light.
11660 A: [1.09850, 1.00000, 0.35585],
11661 // Illuminant C was an early approximation to daylight: illuminant A with a blue filter.
11662 C: [0.98074, 1.000000, 1.18232],
11663 // The daylight series of illuminants simulate natural daylight.
11664 // The color temperature (in degrees Kelvin/100) ranges from
11665 // cool, overcast daylight (D50) to bright, direct sunlight (D65).
11666 D55: [0.95682, 1.00000, 0.92149],
11667 D75: [0.94972, 1.00000, 1.22638],
11668 // Equal-energy illuminant, used in two-stage CAT16
11669 E: [1.00000, 1.00000, 1.00000],
11670 // The F series of illuminants represent fluorescent lights
11671 F2: [0.99186, 1.00000, 0.67393],
11672 F7: [0.95041, 1.00000, 1.08747],
11673 F11: [1.00962, 1.00000, 0.64350]
11674 });
11675
11676 /** @import { Matrix3x3 } from "../types.js" */
11677
11678 // The ACES whitepoint
11679 // see TB-2018-001 Derivation of the ACES White Point CIE Chromaticity Coordinates
11680 // also https://github.com/ampas/aces-dev/blob/master/documents/python/TB-2018-001/aces_wp.py
11681 // Similar to D60
11682 WHITES.ACES = [0.32168 / 0.33767, 1.0, (1.0 - 0.32168 - 0.33767) / 0.33767];
11683
11684 // convert an array of linear-light ACEScc values to CIE XYZ
11685 /** @type {Matrix3x3} */
11686 // prettier-ignore
11687 const toXYZ_M = [[0.6624541811085053, 0.13400420645643313, 0.1561876870049078], [0.27222871678091454, 0.6740817658111484, 0.05368951740793705], [-0.005574649490394108, 0.004060733528982826, 1.0103391003129971]];
11688 /** @type {Matrix3x3} */
11689 // prettier-ignore
11690 const fromXYZ_M = [[1.6410233796943257, -0.32480329418479, -0.23642469523761225], [-0.6636628587229829, 1.6153315916573379, 0.016756347685530137], [0.011721894328375376, -0.008284441996237409, 0.9883948585390215]];
11691 var ACEScg = new RGBColorSpace({
11692 id: "acescg",
11693 cssId: "--acescg",
11694 name: "ACEScg",
11695 // ACEScg – A scene-referred, linear-light encoding of ACES Data
11696 // https://docs.acescentral.com/specifications/acescg/
11697 // uses the AP1 primaries, see section 4.3.1 Color primaries
11698 coords: {
11699 r: {
11700 range: [0, 65504],
11701 name: "Red"
11702 },
11703 g: {
11704 range: [0, 65504],
11705 name: "Green"
11706 },
11707 b: {
11708 range: [0, 65504],
11709 name: "Blue"
11710 }
11711 },
11712 referred: "scene",
11713 white: WHITES.ACES,
11714 toXYZ_M,
11715 fromXYZ_M
11716 });
11717
11718 // export default Color;
11719
11720 const ε = 2 ** -16;
11721
11722 // the smallest value which, in the 32bit IEEE 754 float encoding,
11723 // decodes as a non-negative value
11724 const ACES_min_nonzero = -0.35828683;
11725
11726 // brightest encoded value, decodes to 65504
11727 const ACES_cc_max = (Math.log2(65504) + 9.72) / 17.52; // 1.468
11728
11729 var acescc = new RGBColorSpace({
11730 id: "acescc",
11731 cssId: "--acescc",
11732 name: "ACEScc",
11733 // see S-2014-003 ACEScc – A Logarithmic Encoding of ACES Data
11734 // https://docs.acescentral.com/specifications/acescc/
11735 // uses the AP1 primaries, see section 4.3.1 Color primaries
11736
11737 // Appendix A: "Very small ACES scene referred values below 7 1/4 stops
11738 // below 18% middle gray are encoded as negative ACEScc values.
11739 // These values should be preserved per the encoding in Section 4.4
11740 // so that all positive ACES values are maintained."
11741 coords: {
11742 r: {
11743 range: [ACES_min_nonzero, ACES_cc_max],
11744 name: "Red"
11745 },
11746 g: {
11747 range: [ACES_min_nonzero, ACES_cc_max],
11748 name: "Green"
11749 },
11750 b: {
11751 range: [ACES_min_nonzero, ACES_cc_max],
11752 name: "Blue"
11753 }
11754 },
11755 referred: "scene",
11756 base: ACEScg,
11757 linearGamut: ACEScg,
11758 // from section 4.4.2 Decoding Function
11759 toBase(RGB) {
11760 const low = (9.72 - 15) / 17.52; // -0.3014
11761
11762 return RGB.map(function (val) {
11763 if (val <= low) {
11764 return (2 ** (val * 17.52 - 9.72) - ε) * 2; // very low values, below -0.3014
11765 } else if (val < ACES_cc_max) {
11766 return 2 ** (val * 17.52 - 9.72);
11767 } else {
11768 // val >= ACES_cc_max
11769 return 65504;
11770 }
11771 });
11772 },
11773 // Non-linear encoding function from S-2014-003, section 4.4.1 Encoding Function
11774 fromBase(RGB) {
11775 return RGB.map(function (val) {
11776 if (val <= 0) {
11777 return (Math.log2(ε) + 9.72) / 17.52; // -0.3584
11778 } else if (val < ε) {
11779 return (Math.log2(ε + val * 0.5) + 9.72) / 17.52;
11780 } else {
11781 // val >= ε
11782 return (Math.log2(val) + 9.72) / 17.52;
11783 }
11784 });
11785 }
11786 // encoded media white (rgb 1,1,1) => linear [ 222.861, 222.861, 222.861 ]
11787 // encoded media black (rgb 0,0,0) => linear [ 0.0011857, 0.0011857, 0.0011857]
11788 });
11789
11790 /**
11791 * @packageDocumentation
11792 * Re-exports all the spaces built into Color.js.
11793 */
11794
11795 var spaces = /*#__PURE__*/Object.freeze({
11796 __proto__: null,
11797 A98RGB: a98rgb,
11798 A98RGB_Linear: A98Linear,
11799 ACEScc: acescc,
11800 ACEScg: ACEScg,
11801 CAM16_JMh: cam16,
11802 HCT: hct,
11803 HPLuv: HPLuv,
11804 HSL: HSL,
11805 HSL_P3: hslP3,
11806 HSL_REC2020: hslRec2020,
11807 HSLuv: hsluv,
11808 HSV: HSV,
11809 HWB: hwb,
11810 HelmGen: HelmGen,
11811 HelmGenLCh: helmgenlch,
11812 Helmlab: helmlab,
11813 ICTCP: ictcp,
11814 JzCzHz: jzczhz,
11815 Jzazbz: Jzazbz,
11816 LCH: lch,
11817 LCHuv: LCHuv,
11818 Lab: lab,
11819 Lab_D65: lab_d65,
11820 Luv: Luv,
11821 OKLCH: OKLCH,
11822 OKLCH_P3: oklchP3,
11823 OKLab: Oklab,
11824 OKLrCH: oklrch,
11825 OKLrab: OKLrab,
11826 Okhsl: Okhsl,
11827 Okhsv: Okhsv,
11828 P3: P3,
11829 P3_Linear: P3Linear,
11830 ProPhoto: prophoto,
11831 ProPhoto_Linear: ProPhotoLinear,
11832 REC_2020: REC2020,
11833 REC_2020_Linear: REC_2020_Linear,
11834 REC_2020_Scene_Referred: rec2020Oetf,
11835 REC_2100_HLG: rec2100Hlg,
11836 REC_2100_Linear: REC_2100_Linear,
11837 REC_2100_PQ: rec2100Pq,
11838 XYZ_ABS_D65: XYZ_Abs_D65,
11839 XYZ_D50: XYZ_D50,
11840 XYZ_D65: XYZ_D65,
11841 sRGB: sRGB,
11842 sRGB_Linear: sRGBLinear
11843 });
11844
11845 class Color {
11846 /**
11847 * Creates an instance of Color.
11848 * Signatures:
11849 * - `new Color(stringToParse)`
11850 * - `new Color(otherColor)`
11851 * - `new Color({space, coords, alpha})`
11852 * - `new Color(space, coords, alpha)`
11853 * - `new Color(spaceId, coords, alpha)`
11854 */
11855 constructor(...args) {
11856 let color;
11857 if (args.length === 1) {
11858 let parseMeta = {};
11859 // Clone simple objects to avoid mutating original in getColor
11860 if (typeof args[0] === "object" && Object.getPrototypeOf(args[0]).constructor === Object) {
11861 args[0] = {
11862 ...args[0]
11863 };
11864 }
11865 color = getColor(args[0], {
11866 parseMeta
11867 });
11868 if (parseMeta.format) {
11869 // Color actually came from a string
11870 this.parseMeta = parseMeta;
11871 }
11872 }
11873 let space, coords, alpha;
11874 if (color) {
11875 space = color.space || color.spaceId;
11876 coords = color.coords;
11877 alpha = color.alpha;
11878 } else {
11879 // default signature new Color(ColorSpace, array [, alpha])
11880 [space, coords, alpha] = args;
11881 }
11882 Object.defineProperty(this, "space", {
11883 value: ColorSpace.get(space),
11884 writable: false,
11885 enumerable: true,
11886 configurable: true // see note in https://262.ecma-international.org/8.0/#sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver
11887 });
11888 this.coords = coords ? coords.slice() : [0, 0, 0];
11889
11890 // Clamp alpha to [0, 1]
11891 this.alpha = isNone(alpha) ? alpha : alpha === undefined ? 1 : clamp(0, alpha, 1);
11892
11893 // Define getters and setters for each coordinate
11894 for (let id in this.space.coords) {
11895 Object.defineProperty(this, id, {
11896 get: () => this.get(id),
11897 set: value => this.set(id, value)
11898 });
11899 }
11900 }
11901 get spaceId() {
11902 return this.space.id;
11903 }
11904 clone() {
11905 return new Color(this.space, this.coords, this.alpha);
11906 }
11907 toJSON() {
11908 return {
11909 spaceId: this.spaceId,
11910 coords: this.coords,
11911 alpha: this.alpha
11912 };
11913 }
11914 display(...args) {
11915 let ret = display(this, ...args);
11916
11917 // Convert color object to Color instance
11918 ret.color = new Color(ret.color);
11919 return ret;
11920 }
11921
11922 /**
11923 * Get a color from the argument(s) passed
11924 * Basically gets us the same result as new Color(color) but doesn't clone an existing color object
11925 */
11926 static get(color, ...args) {
11927 if (isInstance(color, this)) {
11928 return color;
11929 }
11930 return new Color(color, ...args);
11931 }
11932
11933 /**
11934 * Get a color instance from the argument passed or `null` if resolution fails (instead of throwing an error).
11935 * Additionally, it supports passing an element to resolve complex CSS colors through the DOM (slow).
11936 * @see {@link tryColor} for more details
11937 */
11938 static try(color, options) {
11939 if (isInstance(color, this)) {
11940 return color;
11941 }
11942 let ret = tryColor(color, options);
11943 if (ret) {
11944 return new Color(ret);
11945 }
11946 return null;
11947 }
11948 static defineFunction(name, code, o = code) {
11949 let {
11950 instance = true,
11951 returns
11952 } = o;
11953 let func = function (...args) {
11954 let ret = code(...args);
11955 if (returns === "color") {
11956 ret = Color.get(ret);
11957 } else if (returns === "function<color>") {
11958 let f = ret;
11959 ret = function (...args) {
11960 let ret = f(...args);
11961 return Color.get(ret);
11962 };
11963 // Copy any function metadata
11964 Object.assign(ret, f);
11965 } else if (returns === "array<color>") {
11966 ret = ret.map(c => Color.get(c));
11967 }
11968 return ret;
11969 };
11970 if (!(name in Color)) {
11971 Color[name] = func;
11972 }
11973 if (instance) {
11974 Color.prototype[name] = function (...args) {
11975 return func(this, ...args);
11976 };
11977 }
11978 }
11979 static defineFunctions(o) {
11980 for (let name in o) {
11981 Color.defineFunction(name, o[name], o[name]);
11982 }
11983 }
11984 static extend(exports) {
11985 if (exports.register) {
11986 exports.register(Color);
11987 } else {
11988 // No register method, just add the module's functions
11989 for (let name in exports) {
11990 Color.defineFunction(name, exports[name]);
11991 }
11992 }
11993 }
11994 }
11995 Color.defineFunctions({
11996 get,
11997 getAll,
11998 set,
11999 setAll,
12000 to,
12001 equals,
12002 inGamut,
12003 toGamut,
12004 distance,
12005 deltas,
12006 toString: serialize
12007 });
12008 Object.assign(Color, {
12009 util,
12010 hooks,
12011 WHITES,
12012 Space: ColorSpace,
12013 spaces: ColorSpace.registry,
12014 parse,
12015 // Global defaults one may want to configure
12016 defaults
12017 });
12018
12019 /**
12020 * @packageDocumentation
12021 * This module contains {@link spaces a namespace} with all the spaces built into Color.js.
12022 */
12023 for (let key of Object.keys(spaces)) {
12024 ColorSpace.register(spaces[key]);
12025 }
12026
12027 // Add space accessors to existing color spaces
12028 for (let id in ColorSpace.registry) {
12029 addSpaceAccessors(id, ColorSpace.registry[id]);
12030 }
12031
12032 // Add space accessors to color spaces not yet created
12033 hooks.add("colorspace-init-end", space => {
12034 var _space$aliases;
12035 addSpaceAccessors(space.id, space);
12036 (_space$aliases = space.aliases) === null || _space$aliases === void 0 || _space$aliases.forEach(alias => {
12037 addSpaceAccessors(alias, space);
12038 });
12039 });
12040 function addSpaceAccessors(id, space) {
12041 let propId = id.replace(/-/g, "_");
12042 Object.defineProperty(Color.prototype, propId, {
12043 // Convert coords to coords in another colorspace and return them
12044 // Source colorspace: this.spaceId
12045 // Target colorspace: id
12046 get() {
12047 let ret = this.getAll(id);
12048 if (typeof Proxy === "undefined") {
12049 // If proxies are not supported, just return a static array
12050 return ret;
12051 }
12052
12053 // Enable color.spaceId.coordName syntax
12054 let proxy = new Proxy(ret, {
12055 has: /** @param {string} property */(obj, property) => {
12056 try {
12057 ColorSpace.resolveCoord([space, property]);
12058 return true;
12059 } catch (e) {}
12060 return Reflect.has(obj, property);
12061 },
12062 get: (obj, property, receiver) => {
12063 if (property && typeof property !== "symbol" && !(property in obj) && property in proxy) {
12064 let {
12065 index
12066 } = ColorSpace.resolveCoord([space, property]);
12067 if (index >= 0) {
12068 return obj[index];
12069 }
12070 }
12071 return Reflect.get(obj, property, receiver);
12072 },
12073 set: (obj, property, value, receiver) => {
12074 if (property && typeof property !== "symbol" && !(property in obj) || Number(property) >= 0) {
12075 let {
12076 index
12077 } = ColorSpace.resolveCoord([space, (/** @type {string} */property)]);
12078 if (index >= 0) {
12079 obj[index] = value;
12080
12081 // Update color.coords
12082 this.setAll(id, obj);
12083 return true;
12084 }
12085 }
12086 return Reflect.set(obj, property, value, receiver);
12087 }
12088 });
12089 return proxy;
12090 },
12091 // Convert coords in another colorspace to internal coords and set them
12092 // Target colorspace: this.spaceId
12093 // Source colorspace: id
12094 set(coords) {
12095 this.setAll(id, coords);
12096 },
12097 configurable: true,
12098 enumerable: true
12099 });
12100 }
12101
12102 /**
12103 * Entry point for the OOP flavor of the API
12104 * Import as `colorjs.io`
12105 */
12106 Color.extend(deltaEMethods);
12107 Color.extend({
12108 deltaE
12109 });
12110 Object.assign(Color, {
12111 deltaEMethods
12112 });
12113 Color.extend(variations);
12114 Color.extend({
12115 contrast
12116 });
12117 Color.extend(chromaticity);
12118 Color.extend(luminance);
12119 Color.extend(interpolation);
12120 Color.extend(contrastMethods);
12121
12122 export { Color as default };
12123 //# sourceMappingURL=color.legacy.js.map