Debian Codegraph @

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

raw
1 var Color = (function () {
2 'use strict';
3
4 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
5
6 var esnext_iterator_map = {};
7
8 var es_iterator_map = {};
9
10 var globalThis_1;
11 var hasRequiredGlobalThis;
12
13 function requireGlobalThis () {
14 if (hasRequiredGlobalThis) return globalThis_1;
15 hasRequiredGlobalThis = 1;
16 var check = function (it) {
17 return it && it.Math === Math && it;
18 };
19
20 // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
21 globalThis_1 =
22 // eslint-disable-next-line es/no-global-this -- safe
23 check(typeof globalThis == 'object' && globalThis) ||
24 check(typeof window == 'object' && window) ||
25 // eslint-disable-next-line no-restricted-globals -- safe
26 check(typeof self == 'object' && self) ||
27 check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
28 check(typeof commonjsGlobal == 'object' && commonjsGlobal) ||
29 // eslint-disable-next-line no-new-func -- fallback
30 (function () { return this; })() || Function('return this')();
31 return globalThis_1;
32 }
33
34 var objectGetOwnPropertyDescriptor = {};
35
36 var fails;
37 var hasRequiredFails;
38
39 function requireFails () {
40 if (hasRequiredFails) return fails;
41 hasRequiredFails = 1;
42 fails = function (exec) {
43 try {
44 return !!exec();
45 } catch (error) {
46 return true;
47 }
48 };
49 return fails;
50 }
51
52 var descriptors;
53 var hasRequiredDescriptors;
54
55 function requireDescriptors () {
56 if (hasRequiredDescriptors) return descriptors;
57 hasRequiredDescriptors = 1;
58 var fails = requireFails();
59
60 // Detect IE8's incomplete defineProperty implementation
61 descriptors = !fails(function () {
62 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
63 return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] !== 7;
64 });
65 return descriptors;
66 }
67
68 var functionBindNative;
69 var hasRequiredFunctionBindNative;
70
71 function requireFunctionBindNative () {
72 if (hasRequiredFunctionBindNative) return functionBindNative;
73 hasRequiredFunctionBindNative = 1;
74 var fails = requireFails();
75
76 functionBindNative = !fails(function () {
77 // eslint-disable-next-line es/no-function-prototype-bind -- safe
78 var test = (function () { /* empty */ }).bind();
79 // eslint-disable-next-line no-prototype-builtins -- safe
80 return typeof test != 'function' || test.hasOwnProperty('prototype');
81 });
82 return functionBindNative;
83 }
84
85 var functionCall;
86 var hasRequiredFunctionCall;
87
88 function requireFunctionCall () {
89 if (hasRequiredFunctionCall) return functionCall;
90 hasRequiredFunctionCall = 1;
91 var NATIVE_BIND = requireFunctionBindNative();
92
93 var call = Function.prototype.call;
94
95 functionCall = NATIVE_BIND ? call.bind(call) : function () {
96 return call.apply(call, arguments);
97 };
98 return functionCall;
99 }
100
101 var objectPropertyIsEnumerable = {};
102
103 var hasRequiredObjectPropertyIsEnumerable;
104
105 function requireObjectPropertyIsEnumerable () {
106 if (hasRequiredObjectPropertyIsEnumerable) return objectPropertyIsEnumerable;
107 hasRequiredObjectPropertyIsEnumerable = 1;
108 var $propertyIsEnumerable = {}.propertyIsEnumerable;
109 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
110 var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
111
112 // Nashorn ~ JDK8 bug
113 var NASHORN_BUG = getOwnPropertyDescriptor && !$propertyIsEnumerable.call({ 1: 2 }, 1);
114
115 // `Object.prototype.propertyIsEnumerable` method implementation
116 // https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable
117 objectPropertyIsEnumerable.f = NASHORN_BUG ? function propertyIsEnumerable(V) {
118 var descriptor = getOwnPropertyDescriptor(this, V);
119 return !!descriptor && descriptor.enumerable;
120 } : $propertyIsEnumerable;
121 return objectPropertyIsEnumerable;
122 }
123
124 var createPropertyDescriptor;
125 var hasRequiredCreatePropertyDescriptor;
126
127 function requireCreatePropertyDescriptor () {
128 if (hasRequiredCreatePropertyDescriptor) return createPropertyDescriptor;
129 hasRequiredCreatePropertyDescriptor = 1;
130 createPropertyDescriptor = function (bitmap, value) {
131 return {
132 enumerable: !(bitmap & 1),
133 configurable: !(bitmap & 2),
134 writable: !(bitmap & 4),
135 value: value
136 };
137 };
138 return createPropertyDescriptor;
139 }
140
141 var functionUncurryThis;
142 var hasRequiredFunctionUncurryThis;
143
144 function requireFunctionUncurryThis () {
145 if (hasRequiredFunctionUncurryThis) return functionUncurryThis;
146 hasRequiredFunctionUncurryThis = 1;
147 var NATIVE_BIND = requireFunctionBindNative();
148
149 var FunctionPrototype = Function.prototype;
150 var call = FunctionPrototype.call;
151 var uncurryThisWithBind = NATIVE_BIND && FunctionPrototype.bind.bind(call, call);
152
153 functionUncurryThis = NATIVE_BIND ? uncurryThisWithBind : function (fn) {
154 return function () {
155 return call.apply(fn, arguments);
156 };
157 };
158 return functionUncurryThis;
159 }
160
161 var classofRaw;
162 var hasRequiredClassofRaw;
163
164 function requireClassofRaw () {
165 if (hasRequiredClassofRaw) return classofRaw;
166 hasRequiredClassofRaw = 1;
167 var uncurryThis = requireFunctionUncurryThis();
168
169 var toString = uncurryThis({}.toString);
170 var stringSlice = uncurryThis(''.slice);
171
172 classofRaw = function (it) {
173 return stringSlice(toString(it), 8, -1);
174 };
175 return classofRaw;
176 }
177
178 var indexedObject;
179 var hasRequiredIndexedObject;
180
181 function requireIndexedObject () {
182 if (hasRequiredIndexedObject) return indexedObject;
183 hasRequiredIndexedObject = 1;
184 var uncurryThis = requireFunctionUncurryThis();
185 var fails = requireFails();
186 var classof = requireClassofRaw();
187
188 var $Object = Object;
189 var split = uncurryThis(''.split);
190
191 // fallback for non-array-like ES3 and non-enumerable old V8 strings
192 indexedObject = fails(function () {
193 // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
194 // eslint-disable-next-line no-prototype-builtins -- safe
195 return !$Object('z').propertyIsEnumerable(0);
196 }) ? function (it) {
197 return classof(it) === 'String' ? split(it, '') : $Object(it);
198 } : $Object;
199 return indexedObject;
200 }
201
202 var isNullOrUndefined;
203 var hasRequiredIsNullOrUndefined;
204
205 function requireIsNullOrUndefined () {
206 if (hasRequiredIsNullOrUndefined) return isNullOrUndefined;
207 hasRequiredIsNullOrUndefined = 1;
208 // we can't use just `it == null` since of `document.all` special case
209 // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot-aec
210 isNullOrUndefined = function (it) {
211 return it === null || it === undefined;
212 };
213 return isNullOrUndefined;
214 }
215
216 var requireObjectCoercible;
217 var hasRequiredRequireObjectCoercible;
218
219 function requireRequireObjectCoercible () {
220 if (hasRequiredRequireObjectCoercible) return requireObjectCoercible;
221 hasRequiredRequireObjectCoercible = 1;
222 var isNullOrUndefined = requireIsNullOrUndefined();
223
224 var $TypeError = TypeError;
225
226 // `RequireObjectCoercible` abstract operation
227 // https://tc39.es/ecma262/#sec-requireobjectcoercible
228 requireObjectCoercible = function (it) {
229 if (isNullOrUndefined(it)) throw new $TypeError("Can't call method on " + it);
230 return it;
231 };
232 return requireObjectCoercible;
233 }
234
235 var toIndexedObject;
236 var hasRequiredToIndexedObject;
237
238 function requireToIndexedObject () {
239 if (hasRequiredToIndexedObject) return toIndexedObject;
240 hasRequiredToIndexedObject = 1;
241 // toObject with fallback for non-array-like ES3 strings
242 var IndexedObject = requireIndexedObject();
243 var requireObjectCoercible = requireRequireObjectCoercible();
244
245 toIndexedObject = function (it) {
246 return IndexedObject(requireObjectCoercible(it));
247 };
248 return toIndexedObject;
249 }
250
251 var isCallable;
252 var hasRequiredIsCallable;
253
254 function requireIsCallable () {
255 if (hasRequiredIsCallable) return isCallable;
256 hasRequiredIsCallable = 1;
257 // https://tc39.es/ecma262/#sec-IsHTMLDDA-internal-slot
258 var documentAll = typeof document == 'object' && document.all;
259
260 // `IsCallable` abstract operation
261 // https://tc39.es/ecma262/#sec-iscallable
262 // eslint-disable-next-line unicorn/no-typeof-undefined -- required for testing
263 isCallable = typeof documentAll == 'undefined' && documentAll !== undefined ? function (argument) {
264 return typeof argument == 'function' || argument === documentAll;
265 } : function (argument) {
266 return typeof argument == 'function';
267 };
268 return isCallable;
269 }
270
271 var isObject;
272 var hasRequiredIsObject;
273
274 function requireIsObject () {
275 if (hasRequiredIsObject) return isObject;
276 hasRequiredIsObject = 1;
277 var isCallable = requireIsCallable();
278
279 isObject = function (it) {
280 return typeof it == 'object' ? it !== null : isCallable(it);
281 };
282 return isObject;
283 }
284
285 var getBuiltIn;
286 var hasRequiredGetBuiltIn;
287
288 function requireGetBuiltIn () {
289 if (hasRequiredGetBuiltIn) return getBuiltIn;
290 hasRequiredGetBuiltIn = 1;
291 var globalThis = requireGlobalThis();
292 var isCallable = requireIsCallable();
293
294 var aFunction = function (argument) {
295 return isCallable(argument) ? argument : undefined;
296 };
297
298 getBuiltIn = function (namespace, method) {
299 return arguments.length < 2 ? aFunction(globalThis[namespace]) : globalThis[namespace] && globalThis[namespace][method];
300 };
301 return getBuiltIn;
302 }
303
304 var objectIsPrototypeOf;
305 var hasRequiredObjectIsPrototypeOf;
306
307 function requireObjectIsPrototypeOf () {
308 if (hasRequiredObjectIsPrototypeOf) return objectIsPrototypeOf;
309 hasRequiredObjectIsPrototypeOf = 1;
310 var uncurryThis = requireFunctionUncurryThis();
311
312 objectIsPrototypeOf = uncurryThis({}.isPrototypeOf);
313 return objectIsPrototypeOf;
314 }
315
316 var environmentUserAgent;
317 var hasRequiredEnvironmentUserAgent;
318
319 function requireEnvironmentUserAgent () {
320 if (hasRequiredEnvironmentUserAgent) return environmentUserAgent;
321 hasRequiredEnvironmentUserAgent = 1;
322 var globalThis = requireGlobalThis();
323
324 var navigator = globalThis.navigator;
325 var userAgent = navigator && navigator.userAgent;
326
327 environmentUserAgent = userAgent ? String(userAgent) : '';
328 return environmentUserAgent;
329 }
330
331 var environmentV8Version;
332 var hasRequiredEnvironmentV8Version;
333
334 function requireEnvironmentV8Version () {
335 if (hasRequiredEnvironmentV8Version) return environmentV8Version;
336 hasRequiredEnvironmentV8Version = 1;
337 var globalThis = requireGlobalThis();
338 var userAgent = requireEnvironmentUserAgent();
339
340 var process = globalThis.process;
341 var Deno = globalThis.Deno;
342 var versions = process && process.versions || Deno && Deno.version;
343 var v8 = versions && versions.v8;
344 var match, version;
345
346 if (v8) {
347 match = v8.split('.');
348 // in old Chrome, versions of V8 isn't V8 = Chrome / 10
349 // but their correct versions are not interesting for us
350 version = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
351 }
352
353 // BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
354 // so check `userAgent` even if `.v8` exists, but 0
355 if (!version && userAgent) {
356 match = userAgent.match(/Edge\/(\d+)/);
357 if (!match || match[1] >= 74) {
358 match = userAgent.match(/Chrome\/(\d+)/);
359 if (match) version = +match[1];
360 }
361 }
362
363 environmentV8Version = version;
364 return environmentV8Version;
365 }
366
367 var symbolConstructorDetection;
368 var hasRequiredSymbolConstructorDetection;
369
370 function requireSymbolConstructorDetection () {
371 if (hasRequiredSymbolConstructorDetection) return symbolConstructorDetection;
372 hasRequiredSymbolConstructorDetection = 1;
373 /* eslint-disable es/no-symbol -- required for testing */
374 var V8_VERSION = requireEnvironmentV8Version();
375 var fails = requireFails();
376 var globalThis = requireGlobalThis();
377
378 var $String = globalThis.String;
379
380 // eslint-disable-next-line es/no-object-getownpropertysymbols -- required for testing
381 symbolConstructorDetection = !!Object.getOwnPropertySymbols && !fails(function () {
382 var symbol = Symbol('symbol detection');
383 // Chrome 38 Symbol has incorrect toString conversion
384 // `get-own-property-symbols` polyfill symbols converted to object are not Symbol instances
385 // nb: Do not call `String` directly to avoid this being optimized out to `symbol+''` which will,
386 // of course, fail.
387 return !$String(symbol) || !(Object(symbol) instanceof Symbol) ||
388 // Chrome 38-40 symbols are not inherited from DOM collections prototypes to instances
389 !Symbol.sham && V8_VERSION && V8_VERSION < 41;
390 });
391 return symbolConstructorDetection;
392 }
393
394 var useSymbolAsUid;
395 var hasRequiredUseSymbolAsUid;
396
397 function requireUseSymbolAsUid () {
398 if (hasRequiredUseSymbolAsUid) return useSymbolAsUid;
399 hasRequiredUseSymbolAsUid = 1;
400 /* eslint-disable es/no-symbol -- required for testing */
401 var NATIVE_SYMBOL = requireSymbolConstructorDetection();
402
403 useSymbolAsUid = NATIVE_SYMBOL &&
404 !Symbol.sham &&
405 typeof Symbol.iterator == 'symbol';
406 return useSymbolAsUid;
407 }
408
409 var isSymbol;
410 var hasRequiredIsSymbol;
411
412 function requireIsSymbol () {
413 if (hasRequiredIsSymbol) return isSymbol;
414 hasRequiredIsSymbol = 1;
415 var getBuiltIn = requireGetBuiltIn();
416 var isCallable = requireIsCallable();
417 var isPrototypeOf = requireObjectIsPrototypeOf();
418 var USE_SYMBOL_AS_UID = requireUseSymbolAsUid();
419
420 var $Object = Object;
421
422 isSymbol = USE_SYMBOL_AS_UID ? function (it) {
423 return typeof it == 'symbol';
424 } : function (it) {
425 var $Symbol = getBuiltIn('Symbol');
426 return isCallable($Symbol) && isPrototypeOf($Symbol.prototype, $Object(it));
427 };
428 return isSymbol;
429 }
430
431 var tryToString;
432 var hasRequiredTryToString;
433
434 function requireTryToString () {
435 if (hasRequiredTryToString) return tryToString;
436 hasRequiredTryToString = 1;
437 var $String = String;
438
439 tryToString = function (argument) {
440 try {
441 return $String(argument);
442 } catch (error) {
443 return 'Object';
444 }
445 };
446 return tryToString;
447 }
448
449 var aCallable;
450 var hasRequiredACallable;
451
452 function requireACallable () {
453 if (hasRequiredACallable) return aCallable;
454 hasRequiredACallable = 1;
455 var isCallable = requireIsCallable();
456 var tryToString = requireTryToString();
457
458 var $TypeError = TypeError;
459
460 // `Assert: IsCallable(argument) is true`
461 aCallable = function (argument) {
462 if (isCallable(argument)) return argument;
463 throw new $TypeError(tryToString(argument) + ' is not a function');
464 };
465 return aCallable;
466 }
467
468 var getMethod;
469 var hasRequiredGetMethod;
470
471 function requireGetMethod () {
472 if (hasRequiredGetMethod) return getMethod;
473 hasRequiredGetMethod = 1;
474 var aCallable = requireACallable();
475 var isNullOrUndefined = requireIsNullOrUndefined();
476
477 // `GetMethod` abstract operation
478 // https://tc39.es/ecma262/#sec-getmethod
479 getMethod = function (V, P) {
480 var func = V[P];
481 return isNullOrUndefined(func) ? undefined : aCallable(func);
482 };
483 return getMethod;
484 }
485
486 var ordinaryToPrimitive;
487 var hasRequiredOrdinaryToPrimitive;
488
489 function requireOrdinaryToPrimitive () {
490 if (hasRequiredOrdinaryToPrimitive) return ordinaryToPrimitive;
491 hasRequiredOrdinaryToPrimitive = 1;
492 var call = requireFunctionCall();
493 var isCallable = requireIsCallable();
494 var isObject = requireIsObject();
495
496 var $TypeError = TypeError;
497
498 // `OrdinaryToPrimitive` abstract operation
499 // https://tc39.es/ecma262/#sec-ordinarytoprimitive
500 ordinaryToPrimitive = function (input, pref) {
501 var fn, val;
502 if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
503 if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val;
504 if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
505 throw new $TypeError("Can't convert object to primitive value");
506 };
507 return ordinaryToPrimitive;
508 }
509
510 var sharedStore = {exports: {}};
511
512 var isPure;
513 var hasRequiredIsPure;
514
515 function requireIsPure () {
516 if (hasRequiredIsPure) return isPure;
517 hasRequiredIsPure = 1;
518 isPure = false;
519 return isPure;
520 }
521
522 var defineGlobalProperty;
523 var hasRequiredDefineGlobalProperty;
524
525 function requireDefineGlobalProperty () {
526 if (hasRequiredDefineGlobalProperty) return defineGlobalProperty;
527 hasRequiredDefineGlobalProperty = 1;
528 var globalThis = requireGlobalThis();
529
530 // eslint-disable-next-line es/no-object-defineproperty -- safe
531 var defineProperty = Object.defineProperty;
532
533 defineGlobalProperty = function (key, value) {
534 try {
535 defineProperty(globalThis, key, { value: value, configurable: true, writable: true });
536 } catch (error) {
537 globalThis[key] = value;
538 } return value;
539 };
540 return defineGlobalProperty;
541 }
542
543 var hasRequiredSharedStore;
544
545 function requireSharedStore () {
546 if (hasRequiredSharedStore) return sharedStore.exports;
547 hasRequiredSharedStore = 1;
548 var IS_PURE = requireIsPure();
549 var globalThis = requireGlobalThis();
550 var defineGlobalProperty = requireDefineGlobalProperty();
551
552 var SHARED = '__core-js_shared__';
553 var store = sharedStore.exports = globalThis[SHARED] || defineGlobalProperty(SHARED, {});
554
555 (store.versions || (store.versions = [])).push({
556 version: '3.39.0',
557 mode: IS_PURE ? 'pure' : 'global',
558 copyright: '© 2014-2024 Denis Pushkarev (zloirock.ru)',
559 license: 'https://github.com/zloirock/core-js/blob/v3.39.0/LICENSE',
560 source: 'https://github.com/zloirock/core-js'
561 });
562 return sharedStore.exports;
563 }
564
565 var shared;
566 var hasRequiredShared;
567
568 function requireShared () {
569 if (hasRequiredShared) return shared;
570 hasRequiredShared = 1;
571 var store = requireSharedStore();
572
573 shared = function (key, value) {
574 return store[key] || (store[key] = value || {});
575 };
576 return shared;
577 }
578
579 var toObject;
580 var hasRequiredToObject;
581
582 function requireToObject () {
583 if (hasRequiredToObject) return toObject;
584 hasRequiredToObject = 1;
585 var requireObjectCoercible = requireRequireObjectCoercible();
586
587 var $Object = Object;
588
589 // `ToObject` abstract operation
590 // https://tc39.es/ecma262/#sec-toobject
591 toObject = function (argument) {
592 return $Object(requireObjectCoercible(argument));
593 };
594 return toObject;
595 }
596
597 var hasOwnProperty_1;
598 var hasRequiredHasOwnProperty;
599
600 function requireHasOwnProperty () {
601 if (hasRequiredHasOwnProperty) return hasOwnProperty_1;
602 hasRequiredHasOwnProperty = 1;
603 var uncurryThis = requireFunctionUncurryThis();
604 var toObject = requireToObject();
605
606 var hasOwnProperty = uncurryThis({}.hasOwnProperty);
607
608 // `HasOwnProperty` abstract operation
609 // https://tc39.es/ecma262/#sec-hasownproperty
610 // eslint-disable-next-line es/no-object-hasown -- safe
611 hasOwnProperty_1 = Object.hasOwn || function hasOwn(it, key) {
612 return hasOwnProperty(toObject(it), key);
613 };
614 return hasOwnProperty_1;
615 }
616
617 var uid;
618 var hasRequiredUid;
619
620 function requireUid () {
621 if (hasRequiredUid) return uid;
622 hasRequiredUid = 1;
623 var uncurryThis = requireFunctionUncurryThis();
624
625 var id = 0;
626 var postfix = Math.random();
627 var toString = uncurryThis(1.0.toString);
628
629 uid = function (key) {
630 return 'Symbol(' + (key === undefined ? '' : key) + ')_' + toString(++id + postfix, 36);
631 };
632 return uid;
633 }
634
635 var wellKnownSymbol;
636 var hasRequiredWellKnownSymbol;
637
638 function requireWellKnownSymbol () {
639 if (hasRequiredWellKnownSymbol) return wellKnownSymbol;
640 hasRequiredWellKnownSymbol = 1;
641 var globalThis = requireGlobalThis();
642 var shared = requireShared();
643 var hasOwn = requireHasOwnProperty();
644 var uid = requireUid();
645 var NATIVE_SYMBOL = requireSymbolConstructorDetection();
646 var USE_SYMBOL_AS_UID = requireUseSymbolAsUid();
647
648 var Symbol = globalThis.Symbol;
649 var WellKnownSymbolsStore = shared('wks');
650 var createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol['for'] || Symbol : Symbol && Symbol.withoutSetter || uid;
651
652 wellKnownSymbol = function (name) {
653 if (!hasOwn(WellKnownSymbolsStore, name)) {
654 WellKnownSymbolsStore[name] = NATIVE_SYMBOL && hasOwn(Symbol, name)
655 ? Symbol[name]
656 : createWellKnownSymbol('Symbol.' + name);
657 } return WellKnownSymbolsStore[name];
658 };
659 return wellKnownSymbol;
660 }
661
662 var toPrimitive;
663 var hasRequiredToPrimitive;
664
665 function requireToPrimitive () {
666 if (hasRequiredToPrimitive) return toPrimitive;
667 hasRequiredToPrimitive = 1;
668 var call = requireFunctionCall();
669 var isObject = requireIsObject();
670 var isSymbol = requireIsSymbol();
671 var getMethod = requireGetMethod();
672 var ordinaryToPrimitive = requireOrdinaryToPrimitive();
673 var wellKnownSymbol = requireWellKnownSymbol();
674
675 var $TypeError = TypeError;
676 var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
677
678 // `ToPrimitive` abstract operation
679 // https://tc39.es/ecma262/#sec-toprimitive
680 toPrimitive = function (input, pref) {
681 if (!isObject(input) || isSymbol(input)) return input;
682 var exoticToPrim = getMethod(input, TO_PRIMITIVE);
683 var result;
684 if (exoticToPrim) {
685 if (pref === undefined) pref = 'default';
686 result = call(exoticToPrim, input, pref);
687 if (!isObject(result) || isSymbol(result)) return result;
688 throw new $TypeError("Can't convert object to primitive value");
689 }
690 if (pref === undefined) pref = 'number';
691 return ordinaryToPrimitive(input, pref);
692 };
693 return toPrimitive;
694 }
695
696 var toPropertyKey;
697 var hasRequiredToPropertyKey;
698
699 function requireToPropertyKey () {
700 if (hasRequiredToPropertyKey) return toPropertyKey;
701 hasRequiredToPropertyKey = 1;
702 var toPrimitive = requireToPrimitive();
703 var isSymbol = requireIsSymbol();
704
705 // `ToPropertyKey` abstract operation
706 // https://tc39.es/ecma262/#sec-topropertykey
707 toPropertyKey = function (argument) {
708 var key = toPrimitive(argument, 'string');
709 return isSymbol(key) ? key : key + '';
710 };
711 return toPropertyKey;
712 }
713
714 var documentCreateElement;
715 var hasRequiredDocumentCreateElement;
716
717 function requireDocumentCreateElement () {
718 if (hasRequiredDocumentCreateElement) return documentCreateElement;
719 hasRequiredDocumentCreateElement = 1;
720 var globalThis = requireGlobalThis();
721 var isObject = requireIsObject();
722
723 var document = globalThis.document;
724 // typeof document.createElement is 'object' in old IE
725 var EXISTS = isObject(document) && isObject(document.createElement);
726
727 documentCreateElement = function (it) {
728 return EXISTS ? document.createElement(it) : {};
729 };
730 return documentCreateElement;
731 }
732
733 var ie8DomDefine;
734 var hasRequiredIe8DomDefine;
735
736 function requireIe8DomDefine () {
737 if (hasRequiredIe8DomDefine) return ie8DomDefine;
738 hasRequiredIe8DomDefine = 1;
739 var DESCRIPTORS = requireDescriptors();
740 var fails = requireFails();
741 var createElement = requireDocumentCreateElement();
742
743 // Thanks to IE8 for its funny defineProperty
744 ie8DomDefine = !DESCRIPTORS && !fails(function () {
745 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
746 return Object.defineProperty(createElement('div'), 'a', {
747 get: function () { return 7; }
748 }).a !== 7;
749 });
750 return ie8DomDefine;
751 }
752
753 var hasRequiredObjectGetOwnPropertyDescriptor;
754
755 function requireObjectGetOwnPropertyDescriptor () {
756 if (hasRequiredObjectGetOwnPropertyDescriptor) return objectGetOwnPropertyDescriptor;
757 hasRequiredObjectGetOwnPropertyDescriptor = 1;
758 var DESCRIPTORS = requireDescriptors();
759 var call = requireFunctionCall();
760 var propertyIsEnumerableModule = requireObjectPropertyIsEnumerable();
761 var createPropertyDescriptor = requireCreatePropertyDescriptor();
762 var toIndexedObject = requireToIndexedObject();
763 var toPropertyKey = requireToPropertyKey();
764 var hasOwn = requireHasOwnProperty();
765 var IE8_DOM_DEFINE = requireIe8DomDefine();
766
767 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
768 var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
769
770 // `Object.getOwnPropertyDescriptor` method
771 // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor
772 objectGetOwnPropertyDescriptor.f = DESCRIPTORS ? $getOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
773 O = toIndexedObject(O);
774 P = toPropertyKey(P);
775 if (IE8_DOM_DEFINE) try {
776 return $getOwnPropertyDescriptor(O, P);
777 } catch (error) { /* empty */ }
778 if (hasOwn(O, P)) return createPropertyDescriptor(!call(propertyIsEnumerableModule.f, O, P), O[P]);
779 };
780 return objectGetOwnPropertyDescriptor;
781 }
782
783 var objectDefineProperty = {};
784
785 var v8PrototypeDefineBug;
786 var hasRequiredV8PrototypeDefineBug;
787
788 function requireV8PrototypeDefineBug () {
789 if (hasRequiredV8PrototypeDefineBug) return v8PrototypeDefineBug;
790 hasRequiredV8PrototypeDefineBug = 1;
791 var DESCRIPTORS = requireDescriptors();
792 var fails = requireFails();
793
794 // V8 ~ Chrome 36-
795 // https://bugs.chromium.org/p/v8/issues/detail?id=3334
796 v8PrototypeDefineBug = DESCRIPTORS && fails(function () {
797 // eslint-disable-next-line es/no-object-defineproperty -- required for testing
798 return Object.defineProperty(function () { /* empty */ }, 'prototype', {
799 value: 42,
800 writable: false
801 }).prototype !== 42;
802 });
803 return v8PrototypeDefineBug;
804 }
805
806 var anObject;
807 var hasRequiredAnObject;
808
809 function requireAnObject () {
810 if (hasRequiredAnObject) return anObject;
811 hasRequiredAnObject = 1;
812 var isObject = requireIsObject();
813
814 var $String = String;
815 var $TypeError = TypeError;
816
817 // `Assert: Type(argument) is Object`
818 anObject = function (argument) {
819 if (isObject(argument)) return argument;
820 throw new $TypeError($String(argument) + ' is not an object');
821 };
822 return anObject;
823 }
824
825 var hasRequiredObjectDefineProperty;
826
827 function requireObjectDefineProperty () {
828 if (hasRequiredObjectDefineProperty) return objectDefineProperty;
829 hasRequiredObjectDefineProperty = 1;
830 var DESCRIPTORS = requireDescriptors();
831 var IE8_DOM_DEFINE = requireIe8DomDefine();
832 var V8_PROTOTYPE_DEFINE_BUG = requireV8PrototypeDefineBug();
833 var anObject = requireAnObject();
834 var toPropertyKey = requireToPropertyKey();
835
836 var $TypeError = TypeError;
837 // eslint-disable-next-line es/no-object-defineproperty -- safe
838 var $defineProperty = Object.defineProperty;
839 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
840 var $getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
841 var ENUMERABLE = 'enumerable';
842 var CONFIGURABLE = 'configurable';
843 var WRITABLE = 'writable';
844
845 // `Object.defineProperty` method
846 // https://tc39.es/ecma262/#sec-object.defineproperty
847 objectDefineProperty.f = DESCRIPTORS ? V8_PROTOTYPE_DEFINE_BUG ? function defineProperty(O, P, Attributes) {
848 anObject(O);
849 P = toPropertyKey(P);
850 anObject(Attributes);
851 if (typeof O === 'function' && P === 'prototype' && 'value' in Attributes && WRITABLE in Attributes && !Attributes[WRITABLE]) {
852 var current = $getOwnPropertyDescriptor(O, P);
853 if (current && current[WRITABLE]) {
854 O[P] = Attributes.value;
855 Attributes = {
856 configurable: CONFIGURABLE in Attributes ? Attributes[CONFIGURABLE] : current[CONFIGURABLE],
857 enumerable: ENUMERABLE in Attributes ? Attributes[ENUMERABLE] : current[ENUMERABLE],
858 writable: false
859 };
860 }
861 } return $defineProperty(O, P, Attributes);
862 } : $defineProperty : function defineProperty(O, P, Attributes) {
863 anObject(O);
864 P = toPropertyKey(P);
865 anObject(Attributes);
866 if (IE8_DOM_DEFINE) try {
867 return $defineProperty(O, P, Attributes);
868 } catch (error) { /* empty */ }
869 if ('get' in Attributes || 'set' in Attributes) throw new $TypeError('Accessors not supported');
870 if ('value' in Attributes) O[P] = Attributes.value;
871 return O;
872 };
873 return objectDefineProperty;
874 }
875
876 var createNonEnumerableProperty;
877 var hasRequiredCreateNonEnumerableProperty;
878
879 function requireCreateNonEnumerableProperty () {
880 if (hasRequiredCreateNonEnumerableProperty) return createNonEnumerableProperty;
881 hasRequiredCreateNonEnumerableProperty = 1;
882 var DESCRIPTORS = requireDescriptors();
883 var definePropertyModule = requireObjectDefineProperty();
884 var createPropertyDescriptor = requireCreatePropertyDescriptor();
885
886 createNonEnumerableProperty = DESCRIPTORS ? function (object, key, value) {
887 return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));
888 } : function (object, key, value) {
889 object[key] = value;
890 return object;
891 };
892 return createNonEnumerableProperty;
893 }
894
895 var makeBuiltIn = {exports: {}};
896
897 var functionName;
898 var hasRequiredFunctionName;
899
900 function requireFunctionName () {
901 if (hasRequiredFunctionName) return functionName;
902 hasRequiredFunctionName = 1;
903 var DESCRIPTORS = requireDescriptors();
904 var hasOwn = requireHasOwnProperty();
905
906 var FunctionPrototype = Function.prototype;
907 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
908 var getDescriptor = DESCRIPTORS && Object.getOwnPropertyDescriptor;
909
910 var EXISTS = hasOwn(FunctionPrototype, 'name');
911 // additional protection from minified / mangled / dropped function names
912 var PROPER = EXISTS && (function something() { /* empty */ }).name === 'something';
913 var CONFIGURABLE = EXISTS && (!DESCRIPTORS || (DESCRIPTORS && getDescriptor(FunctionPrototype, 'name').configurable));
914
915 functionName = {
916 EXISTS: EXISTS,
917 PROPER: PROPER,
918 CONFIGURABLE: CONFIGURABLE
919 };
920 return functionName;
921 }
922
923 var inspectSource;
924 var hasRequiredInspectSource;
925
926 function requireInspectSource () {
927 if (hasRequiredInspectSource) return inspectSource;
928 hasRequiredInspectSource = 1;
929 var uncurryThis = requireFunctionUncurryThis();
930 var isCallable = requireIsCallable();
931 var store = requireSharedStore();
932
933 var functionToString = uncurryThis(Function.toString);
934
935 // this helper broken in `[email protected]`, so we can't use `shared` helper
936 if (!isCallable(store.inspectSource)) {
937 store.inspectSource = function (it) {
938 return functionToString(it);
939 };
940 }
941
942 inspectSource = store.inspectSource;
943 return inspectSource;
944 }
945
946 var weakMapBasicDetection;
947 var hasRequiredWeakMapBasicDetection;
948
949 function requireWeakMapBasicDetection () {
950 if (hasRequiredWeakMapBasicDetection) return weakMapBasicDetection;
951 hasRequiredWeakMapBasicDetection = 1;
952 var globalThis = requireGlobalThis();
953 var isCallable = requireIsCallable();
954
955 var WeakMap = globalThis.WeakMap;
956
957 weakMapBasicDetection = isCallable(WeakMap) && /native code/.test(String(WeakMap));
958 return weakMapBasicDetection;
959 }
960
961 var sharedKey;
962 var hasRequiredSharedKey;
963
964 function requireSharedKey () {
965 if (hasRequiredSharedKey) return sharedKey;
966 hasRequiredSharedKey = 1;
967 var shared = requireShared();
968 var uid = requireUid();
969
970 var keys = shared('keys');
971
972 sharedKey = function (key) {
973 return keys[key] || (keys[key] = uid(key));
974 };
975 return sharedKey;
976 }
977
978 var hiddenKeys;
979 var hasRequiredHiddenKeys;
980
981 function requireHiddenKeys () {
982 if (hasRequiredHiddenKeys) return hiddenKeys;
983 hasRequiredHiddenKeys = 1;
984 hiddenKeys = {};
985 return hiddenKeys;
986 }
987
988 var internalState;
989 var hasRequiredInternalState;
990
991 function requireInternalState () {
992 if (hasRequiredInternalState) return internalState;
993 hasRequiredInternalState = 1;
994 var NATIVE_WEAK_MAP = requireWeakMapBasicDetection();
995 var globalThis = requireGlobalThis();
996 var isObject = requireIsObject();
997 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
998 var hasOwn = requireHasOwnProperty();
999 var shared = requireSharedStore();
1000 var sharedKey = requireSharedKey();
1001 var hiddenKeys = requireHiddenKeys();
1002
1003 var OBJECT_ALREADY_INITIALIZED = 'Object already initialized';
1004 var TypeError = globalThis.TypeError;
1005 var WeakMap = globalThis.WeakMap;
1006 var set, get, has;
1007
1008 var enforce = function (it) {
1009 return has(it) ? get(it) : set(it, {});
1010 };
1011
1012 var getterFor = function (TYPE) {
1013 return function (it) {
1014 var state;
1015 if (!isObject(it) || (state = get(it)).type !== TYPE) {
1016 throw new TypeError('Incompatible receiver, ' + TYPE + ' required');
1017 } return state;
1018 };
1019 };
1020
1021 if (NATIVE_WEAK_MAP || shared.state) {
1022 var store = shared.state || (shared.state = new WeakMap());
1023 /* eslint-disable no-self-assign -- prototype methods protection */
1024 store.get = store.get;
1025 store.has = store.has;
1026 store.set = store.set;
1027 /* eslint-enable no-self-assign -- prototype methods protection */
1028 set = function (it, metadata) {
1029 if (store.has(it)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
1030 metadata.facade = it;
1031 store.set(it, metadata);
1032 return metadata;
1033 };
1034 get = function (it) {
1035 return store.get(it) || {};
1036 };
1037 has = function (it) {
1038 return store.has(it);
1039 };
1040 } else {
1041 var STATE = sharedKey('state');
1042 hiddenKeys[STATE] = true;
1043 set = function (it, metadata) {
1044 if (hasOwn(it, STATE)) throw new TypeError(OBJECT_ALREADY_INITIALIZED);
1045 metadata.facade = it;
1046 createNonEnumerableProperty(it, STATE, metadata);
1047 return metadata;
1048 };
1049 get = function (it) {
1050 return hasOwn(it, STATE) ? it[STATE] : {};
1051 };
1052 has = function (it) {
1053 return hasOwn(it, STATE);
1054 };
1055 }
1056
1057 internalState = {
1058 set: set,
1059 get: get,
1060 has: has,
1061 enforce: enforce,
1062 getterFor: getterFor
1063 };
1064 return internalState;
1065 }
1066
1067 var hasRequiredMakeBuiltIn;
1068
1069 function requireMakeBuiltIn () {
1070 if (hasRequiredMakeBuiltIn) return makeBuiltIn.exports;
1071 hasRequiredMakeBuiltIn = 1;
1072 var uncurryThis = requireFunctionUncurryThis();
1073 var fails = requireFails();
1074 var isCallable = requireIsCallable();
1075 var hasOwn = requireHasOwnProperty();
1076 var DESCRIPTORS = requireDescriptors();
1077 var CONFIGURABLE_FUNCTION_NAME = requireFunctionName().CONFIGURABLE;
1078 var inspectSource = requireInspectSource();
1079 var InternalStateModule = requireInternalState();
1080
1081 var enforceInternalState = InternalStateModule.enforce;
1082 var getInternalState = InternalStateModule.get;
1083 var $String = String;
1084 // eslint-disable-next-line es/no-object-defineproperty -- safe
1085 var defineProperty = Object.defineProperty;
1086 var stringSlice = uncurryThis(''.slice);
1087 var replace = uncurryThis(''.replace);
1088 var join = uncurryThis([].join);
1089
1090 var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function () {
1091 return defineProperty(function () { /* empty */ }, 'length', { value: 8 }).length !== 8;
1092 });
1093
1094 var TEMPLATE = String(String).split('String');
1095
1096 var makeBuiltIn$1 = makeBuiltIn.exports = function (value, name, options) {
1097 if (stringSlice($String(name), 0, 7) === 'Symbol(') {
1098 name = '[' + replace($String(name), /^Symbol\(([^)]*)\).*$/, '$1') + ']';
1099 }
1100 if (options && options.getter) name = 'get ' + name;
1101 if (options && options.setter) name = 'set ' + name;
1102 if (!hasOwn(value, 'name') || (CONFIGURABLE_FUNCTION_NAME && value.name !== name)) {
1103 if (DESCRIPTORS) defineProperty(value, 'name', { value: name, configurable: true });
1104 else value.name = name;
1105 }
1106 if (CONFIGURABLE_LENGTH && options && hasOwn(options, 'arity') && value.length !== options.arity) {
1107 defineProperty(value, 'length', { value: options.arity });
1108 }
1109 try {
1110 if (options && hasOwn(options, 'constructor') && options.constructor) {
1111 if (DESCRIPTORS) defineProperty(value, 'prototype', { writable: false });
1112 // in V8 ~ Chrome 53, prototypes of some methods, like `Array.prototype.values`, are non-writable
1113 } else if (value.prototype) value.prototype = undefined;
1114 } catch (error) { /* empty */ }
1115 var state = enforceInternalState(value);
1116 if (!hasOwn(state, 'source')) {
1117 state.source = join(TEMPLATE, typeof name == 'string' ? name : '');
1118 } return value;
1119 };
1120
1121 // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
1122 // eslint-disable-next-line no-extend-native -- required
1123 Function.prototype.toString = makeBuiltIn$1(function toString() {
1124 return isCallable(this) && getInternalState(this).source || inspectSource(this);
1125 }, 'toString');
1126 return makeBuiltIn.exports;
1127 }
1128
1129 var defineBuiltIn;
1130 var hasRequiredDefineBuiltIn;
1131
1132 function requireDefineBuiltIn () {
1133 if (hasRequiredDefineBuiltIn) return defineBuiltIn;
1134 hasRequiredDefineBuiltIn = 1;
1135 var isCallable = requireIsCallable();
1136 var definePropertyModule = requireObjectDefineProperty();
1137 var makeBuiltIn = requireMakeBuiltIn();
1138 var defineGlobalProperty = requireDefineGlobalProperty();
1139
1140 defineBuiltIn = function (O, key, value, options) {
1141 if (!options) options = {};
1142 var simple = options.enumerable;
1143 var name = options.name !== undefined ? options.name : key;
1144 if (isCallable(value)) makeBuiltIn(value, name, options);
1145 if (options.global) {
1146 if (simple) O[key] = value;
1147 else defineGlobalProperty(key, value);
1148 } else {
1149 try {
1150 if (!options.unsafe) delete O[key];
1151 else if (O[key]) simple = true;
1152 } catch (error) { /* empty */ }
1153 if (simple) O[key] = value;
1154 else definePropertyModule.f(O, key, {
1155 value: value,
1156 enumerable: false,
1157 configurable: !options.nonConfigurable,
1158 writable: !options.nonWritable
1159 });
1160 } return O;
1161 };
1162 return defineBuiltIn;
1163 }
1164
1165 var objectGetOwnPropertyNames = {};
1166
1167 var mathTrunc;
1168 var hasRequiredMathTrunc;
1169
1170 function requireMathTrunc () {
1171 if (hasRequiredMathTrunc) return mathTrunc;
1172 hasRequiredMathTrunc = 1;
1173 var ceil = Math.ceil;
1174 var floor = Math.floor;
1175
1176 // `Math.trunc` method
1177 // https://tc39.es/ecma262/#sec-math.trunc
1178 // eslint-disable-next-line es/no-math-trunc -- safe
1179 mathTrunc = Math.trunc || function trunc(x) {
1180 var n = +x;
1181 return (n > 0 ? floor : ceil)(n);
1182 };
1183 return mathTrunc;
1184 }
1185
1186 var toIntegerOrInfinity;
1187 var hasRequiredToIntegerOrInfinity;
1188
1189 function requireToIntegerOrInfinity () {
1190 if (hasRequiredToIntegerOrInfinity) return toIntegerOrInfinity;
1191 hasRequiredToIntegerOrInfinity = 1;
1192 var trunc = requireMathTrunc();
1193
1194 // `ToIntegerOrInfinity` abstract operation
1195 // https://tc39.es/ecma262/#sec-tointegerorinfinity
1196 toIntegerOrInfinity = function (argument) {
1197 var number = +argument;
1198 // eslint-disable-next-line no-self-compare -- NaN check
1199 return number !== number || number === 0 ? 0 : trunc(number);
1200 };
1201 return toIntegerOrInfinity;
1202 }
1203
1204 var toAbsoluteIndex;
1205 var hasRequiredToAbsoluteIndex;
1206
1207 function requireToAbsoluteIndex () {
1208 if (hasRequiredToAbsoluteIndex) return toAbsoluteIndex;
1209 hasRequiredToAbsoluteIndex = 1;
1210 var toIntegerOrInfinity = requireToIntegerOrInfinity();
1211
1212 var max = Math.max;
1213 var min = Math.min;
1214
1215 // Helper for a popular repeating case of the spec:
1216 // Let integer be ? ToInteger(index).
1217 // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).
1218 toAbsoluteIndex = function (index, length) {
1219 var integer = toIntegerOrInfinity(index);
1220 return integer < 0 ? max(integer + length, 0) : min(integer, length);
1221 };
1222 return toAbsoluteIndex;
1223 }
1224
1225 var toLength;
1226 var hasRequiredToLength;
1227
1228 function requireToLength () {
1229 if (hasRequiredToLength) return toLength;
1230 hasRequiredToLength = 1;
1231 var toIntegerOrInfinity = requireToIntegerOrInfinity();
1232
1233 var min = Math.min;
1234
1235 // `ToLength` abstract operation
1236 // https://tc39.es/ecma262/#sec-tolength
1237 toLength = function (argument) {
1238 var len = toIntegerOrInfinity(argument);
1239 return len > 0 ? min(len, 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
1240 };
1241 return toLength;
1242 }
1243
1244 var lengthOfArrayLike;
1245 var hasRequiredLengthOfArrayLike;
1246
1247 function requireLengthOfArrayLike () {
1248 if (hasRequiredLengthOfArrayLike) return lengthOfArrayLike;
1249 hasRequiredLengthOfArrayLike = 1;
1250 var toLength = requireToLength();
1251
1252 // `LengthOfArrayLike` abstract operation
1253 // https://tc39.es/ecma262/#sec-lengthofarraylike
1254 lengthOfArrayLike = function (obj) {
1255 return toLength(obj.length);
1256 };
1257 return lengthOfArrayLike;
1258 }
1259
1260 var arrayIncludes;
1261 var hasRequiredArrayIncludes;
1262
1263 function requireArrayIncludes () {
1264 if (hasRequiredArrayIncludes) return arrayIncludes;
1265 hasRequiredArrayIncludes = 1;
1266 var toIndexedObject = requireToIndexedObject();
1267 var toAbsoluteIndex = requireToAbsoluteIndex();
1268 var lengthOfArrayLike = requireLengthOfArrayLike();
1269
1270 // `Array.prototype.{ indexOf, includes }` methods implementation
1271 var createMethod = function (IS_INCLUDES) {
1272 return function ($this, el, fromIndex) {
1273 var O = toIndexedObject($this);
1274 var length = lengthOfArrayLike(O);
1275 if (length === 0) return !IS_INCLUDES && -1;
1276 var index = toAbsoluteIndex(fromIndex, length);
1277 var value;
1278 // Array#includes uses SameValueZero equality algorithm
1279 // eslint-disable-next-line no-self-compare -- NaN check
1280 if (IS_INCLUDES && el !== el) while (length > index) {
1281 value = O[index++];
1282 // eslint-disable-next-line no-self-compare -- NaN check
1283 if (value !== value) return true;
1284 // Array#indexOf ignores holes, Array#includes - not
1285 } else for (;length > index; index++) {
1286 if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
1287 } return !IS_INCLUDES && -1;
1288 };
1289 };
1290
1291 arrayIncludes = {
1292 // `Array.prototype.includes` method
1293 // https://tc39.es/ecma262/#sec-array.prototype.includes
1294 includes: createMethod(true),
1295 // `Array.prototype.indexOf` method
1296 // https://tc39.es/ecma262/#sec-array.prototype.indexof
1297 indexOf: createMethod(false)
1298 };
1299 return arrayIncludes;
1300 }
1301
1302 var objectKeysInternal;
1303 var hasRequiredObjectKeysInternal;
1304
1305 function requireObjectKeysInternal () {
1306 if (hasRequiredObjectKeysInternal) return objectKeysInternal;
1307 hasRequiredObjectKeysInternal = 1;
1308 var uncurryThis = requireFunctionUncurryThis();
1309 var hasOwn = requireHasOwnProperty();
1310 var toIndexedObject = requireToIndexedObject();
1311 var indexOf = requireArrayIncludes().indexOf;
1312 var hiddenKeys = requireHiddenKeys();
1313
1314 var push = uncurryThis([].push);
1315
1316 objectKeysInternal = function (object, names) {
1317 var O = toIndexedObject(object);
1318 var i = 0;
1319 var result = [];
1320 var key;
1321 for (key in O) !hasOwn(hiddenKeys, key) && hasOwn(O, key) && push(result, key);
1322 // Don't enum bug & hidden keys
1323 while (names.length > i) if (hasOwn(O, key = names[i++])) {
1324 ~indexOf(result, key) || push(result, key);
1325 }
1326 return result;
1327 };
1328 return objectKeysInternal;
1329 }
1330
1331 var enumBugKeys;
1332 var hasRequiredEnumBugKeys;
1333
1334 function requireEnumBugKeys () {
1335 if (hasRequiredEnumBugKeys) return enumBugKeys;
1336 hasRequiredEnumBugKeys = 1;
1337 // IE8- don't enum bug keys
1338 enumBugKeys = [
1339 'constructor',
1340 'hasOwnProperty',
1341 'isPrototypeOf',
1342 'propertyIsEnumerable',
1343 'toLocaleString',
1344 'toString',
1345 'valueOf'
1346 ];
1347 return enumBugKeys;
1348 }
1349
1350 var hasRequiredObjectGetOwnPropertyNames;
1351
1352 function requireObjectGetOwnPropertyNames () {
1353 if (hasRequiredObjectGetOwnPropertyNames) return objectGetOwnPropertyNames;
1354 hasRequiredObjectGetOwnPropertyNames = 1;
1355 var internalObjectKeys = requireObjectKeysInternal();
1356 var enumBugKeys = requireEnumBugKeys();
1357
1358 var hiddenKeys = enumBugKeys.concat('length', 'prototype');
1359
1360 // `Object.getOwnPropertyNames` method
1361 // https://tc39.es/ecma262/#sec-object.getownpropertynames
1362 // eslint-disable-next-line es/no-object-getownpropertynames -- safe
1363 objectGetOwnPropertyNames.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
1364 return internalObjectKeys(O, hiddenKeys);
1365 };
1366 return objectGetOwnPropertyNames;
1367 }
1368
1369 var objectGetOwnPropertySymbols = {};
1370
1371 var hasRequiredObjectGetOwnPropertySymbols;
1372
1373 function requireObjectGetOwnPropertySymbols () {
1374 if (hasRequiredObjectGetOwnPropertySymbols) return objectGetOwnPropertySymbols;
1375 hasRequiredObjectGetOwnPropertySymbols = 1;
1376 // eslint-disable-next-line es/no-object-getownpropertysymbols -- safe
1377 objectGetOwnPropertySymbols.f = Object.getOwnPropertySymbols;
1378 return objectGetOwnPropertySymbols;
1379 }
1380
1381 var ownKeys;
1382 var hasRequiredOwnKeys;
1383
1384 function requireOwnKeys () {
1385 if (hasRequiredOwnKeys) return ownKeys;
1386 hasRequiredOwnKeys = 1;
1387 var getBuiltIn = requireGetBuiltIn();
1388 var uncurryThis = requireFunctionUncurryThis();
1389 var getOwnPropertyNamesModule = requireObjectGetOwnPropertyNames();
1390 var getOwnPropertySymbolsModule = requireObjectGetOwnPropertySymbols();
1391 var anObject = requireAnObject();
1392
1393 var concat = uncurryThis([].concat);
1394
1395 // all object keys, includes non-enumerable and symbols
1396 ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
1397 var keys = getOwnPropertyNamesModule.f(anObject(it));
1398 var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;
1399 return getOwnPropertySymbols ? concat(keys, getOwnPropertySymbols(it)) : keys;
1400 };
1401 return ownKeys;
1402 }
1403
1404 var copyConstructorProperties;
1405 var hasRequiredCopyConstructorProperties;
1406
1407 function requireCopyConstructorProperties () {
1408 if (hasRequiredCopyConstructorProperties) return copyConstructorProperties;
1409 hasRequiredCopyConstructorProperties = 1;
1410 var hasOwn = requireHasOwnProperty();
1411 var ownKeys = requireOwnKeys();
1412 var getOwnPropertyDescriptorModule = requireObjectGetOwnPropertyDescriptor();
1413 var definePropertyModule = requireObjectDefineProperty();
1414
1415 copyConstructorProperties = function (target, source, exceptions) {
1416 var keys = ownKeys(source);
1417 var defineProperty = definePropertyModule.f;
1418 var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;
1419 for (var i = 0; i < keys.length; i++) {
1420 var key = keys[i];
1421 if (!hasOwn(target, key) && !(exceptions && hasOwn(exceptions, key))) {
1422 defineProperty(target, key, getOwnPropertyDescriptor(source, key));
1423 }
1424 }
1425 };
1426 return copyConstructorProperties;
1427 }
1428
1429 var isForced_1;
1430 var hasRequiredIsForced;
1431
1432 function requireIsForced () {
1433 if (hasRequiredIsForced) return isForced_1;
1434 hasRequiredIsForced = 1;
1435 var fails = requireFails();
1436 var isCallable = requireIsCallable();
1437
1438 var replacement = /#|\.prototype\./;
1439
1440 var isForced = function (feature, detection) {
1441 var value = data[normalize(feature)];
1442 return value === POLYFILL ? true
1443 : value === NATIVE ? false
1444 : isCallable(detection) ? fails(detection)
1445 : !!detection;
1446 };
1447
1448 var normalize = isForced.normalize = function (string) {
1449 return String(string).replace(replacement, '.').toLowerCase();
1450 };
1451
1452 var data = isForced.data = {};
1453 var NATIVE = isForced.NATIVE = 'N';
1454 var POLYFILL = isForced.POLYFILL = 'P';
1455
1456 isForced_1 = isForced;
1457 return isForced_1;
1458 }
1459
1460 var _export;
1461 var hasRequired_export;
1462
1463 function require_export () {
1464 if (hasRequired_export) return _export;
1465 hasRequired_export = 1;
1466 var globalThis = requireGlobalThis();
1467 var getOwnPropertyDescriptor = requireObjectGetOwnPropertyDescriptor().f;
1468 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
1469 var defineBuiltIn = requireDefineBuiltIn();
1470 var defineGlobalProperty = requireDefineGlobalProperty();
1471 var copyConstructorProperties = requireCopyConstructorProperties();
1472 var isForced = requireIsForced();
1473
1474 /*
1475 options.target - name of the target object
1476 options.global - target is the global object
1477 options.stat - export as static methods of target
1478 options.proto - export as prototype methods of target
1479 options.real - real prototype method for the `pure` version
1480 options.forced - export even if the native feature is available
1481 options.bind - bind methods to the target, required for the `pure` version
1482 options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
1483 options.unsafe - use the simple assignment of property instead of delete + defineProperty
1484 options.sham - add a flag to not completely full polyfills
1485 options.enumerable - export as enumerable property
1486 options.dontCallGetSet - prevent calling a getter on target
1487 options.name - the .name of the function if it does not match the key
1488 */
1489 _export = function (options, source) {
1490 var TARGET = options.target;
1491 var GLOBAL = options.global;
1492 var STATIC = options.stat;
1493 var FORCED, target, key, targetProperty, sourceProperty, descriptor;
1494 if (GLOBAL) {
1495 target = globalThis;
1496 } else if (STATIC) {
1497 target = globalThis[TARGET] || defineGlobalProperty(TARGET, {});
1498 } else {
1499 target = globalThis[TARGET] && globalThis[TARGET].prototype;
1500 }
1501 if (target) for (key in source) {
1502 sourceProperty = source[key];
1503 if (options.dontCallGetSet) {
1504 descriptor = getOwnPropertyDescriptor(target, key);
1505 targetProperty = descriptor && descriptor.value;
1506 } else targetProperty = target[key];
1507 FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
1508 // contained in target
1509 if (!FORCED && targetProperty !== undefined) {
1510 if (typeof sourceProperty == typeof targetProperty) continue;
1511 copyConstructorProperties(sourceProperty, targetProperty);
1512 }
1513 // add a flag to not completely full polyfills
1514 if (options.sham || (targetProperty && targetProperty.sham)) {
1515 createNonEnumerableProperty(sourceProperty, 'sham', true);
1516 }
1517 defineBuiltIn(target, key, sourceProperty, options);
1518 }
1519 };
1520 return _export;
1521 }
1522
1523 var getIteratorDirect;
1524 var hasRequiredGetIteratorDirect;
1525
1526 function requireGetIteratorDirect () {
1527 if (hasRequiredGetIteratorDirect) return getIteratorDirect;
1528 hasRequiredGetIteratorDirect = 1;
1529 // `GetIteratorDirect(obj)` abstract operation
1530 // https://tc39.es/proposal-iterator-helpers/#sec-getiteratordirect
1531 getIteratorDirect = function (obj) {
1532 return {
1533 iterator: obj,
1534 next: obj.next,
1535 done: false
1536 };
1537 };
1538 return getIteratorDirect;
1539 }
1540
1541 var objectDefineProperties = {};
1542
1543 var objectKeys;
1544 var hasRequiredObjectKeys;
1545
1546 function requireObjectKeys () {
1547 if (hasRequiredObjectKeys) return objectKeys;
1548 hasRequiredObjectKeys = 1;
1549 var internalObjectKeys = requireObjectKeysInternal();
1550 var enumBugKeys = requireEnumBugKeys();
1551
1552 // `Object.keys` method
1553 // https://tc39.es/ecma262/#sec-object.keys
1554 // eslint-disable-next-line es/no-object-keys -- safe
1555 objectKeys = Object.keys || function keys(O) {
1556 return internalObjectKeys(O, enumBugKeys);
1557 };
1558 return objectKeys;
1559 }
1560
1561 var hasRequiredObjectDefineProperties;
1562
1563 function requireObjectDefineProperties () {
1564 if (hasRequiredObjectDefineProperties) return objectDefineProperties;
1565 hasRequiredObjectDefineProperties = 1;
1566 var DESCRIPTORS = requireDescriptors();
1567 var V8_PROTOTYPE_DEFINE_BUG = requireV8PrototypeDefineBug();
1568 var definePropertyModule = requireObjectDefineProperty();
1569 var anObject = requireAnObject();
1570 var toIndexedObject = requireToIndexedObject();
1571 var objectKeys = requireObjectKeys();
1572
1573 // `Object.defineProperties` method
1574 // https://tc39.es/ecma262/#sec-object.defineproperties
1575 // eslint-disable-next-line es/no-object-defineproperties -- safe
1576 objectDefineProperties.f = DESCRIPTORS && !V8_PROTOTYPE_DEFINE_BUG ? Object.defineProperties : function defineProperties(O, Properties) {
1577 anObject(O);
1578 var props = toIndexedObject(Properties);
1579 var keys = objectKeys(Properties);
1580 var length = keys.length;
1581 var index = 0;
1582 var key;
1583 while (length > index) definePropertyModule.f(O, key = keys[index++], props[key]);
1584 return O;
1585 };
1586 return objectDefineProperties;
1587 }
1588
1589 var html;
1590 var hasRequiredHtml;
1591
1592 function requireHtml () {
1593 if (hasRequiredHtml) return html;
1594 hasRequiredHtml = 1;
1595 var getBuiltIn = requireGetBuiltIn();
1596
1597 html = getBuiltIn('document', 'documentElement');
1598 return html;
1599 }
1600
1601 var objectCreate;
1602 var hasRequiredObjectCreate;
1603
1604 function requireObjectCreate () {
1605 if (hasRequiredObjectCreate) return objectCreate;
1606 hasRequiredObjectCreate = 1;
1607 /* global ActiveXObject -- old IE, WSH */
1608 var anObject = requireAnObject();
1609 var definePropertiesModule = requireObjectDefineProperties();
1610 var enumBugKeys = requireEnumBugKeys();
1611 var hiddenKeys = requireHiddenKeys();
1612 var html = requireHtml();
1613 var documentCreateElement = requireDocumentCreateElement();
1614 var sharedKey = requireSharedKey();
1615
1616 var GT = '>';
1617 var LT = '<';
1618 var PROTOTYPE = 'prototype';
1619 var SCRIPT = 'script';
1620 var IE_PROTO = sharedKey('IE_PROTO');
1621
1622 var EmptyConstructor = function () { /* empty */ };
1623
1624 var scriptTag = function (content) {
1625 return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;
1626 };
1627
1628 // Create object with fake `null` prototype: use ActiveX Object with cleared prototype
1629 var NullProtoObjectViaActiveX = function (activeXDocument) {
1630 activeXDocument.write(scriptTag(''));
1631 activeXDocument.close();
1632 var temp = activeXDocument.parentWindow.Object;
1633 // eslint-disable-next-line no-useless-assignment -- avoid memory leak
1634 activeXDocument = null;
1635 return temp;
1636 };
1637
1638 // Create object with fake `null` prototype: use iframe Object with cleared prototype
1639 var NullProtoObjectViaIFrame = function () {
1640 // Thrash, waste and sodomy: IE GC bug
1641 var iframe = documentCreateElement('iframe');
1642 var JS = 'java' + SCRIPT + ':';
1643 var iframeDocument;
1644 iframe.style.display = 'none';
1645 html.appendChild(iframe);
1646 // https://github.com/zloirock/core-js/issues/475
1647 iframe.src = String(JS);
1648 iframeDocument = iframe.contentWindow.document;
1649 iframeDocument.open();
1650 iframeDocument.write(scriptTag('document.F=Object'));
1651 iframeDocument.close();
1652 return iframeDocument.F;
1653 };
1654
1655 // Check for document.domain and active x support
1656 // No need to use active x approach when document.domain is not set
1657 // see https://github.com/es-shims/es5-shim/issues/150
1658 // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346
1659 // avoid IE GC bug
1660 var activeXDocument;
1661 var NullProtoObject = function () {
1662 try {
1663 activeXDocument = new ActiveXObject('htmlfile');
1664 } catch (error) { /* ignore */ }
1665 NullProtoObject = typeof document != 'undefined'
1666 ? document.domain && activeXDocument
1667 ? NullProtoObjectViaActiveX(activeXDocument) // old IE
1668 : NullProtoObjectViaIFrame()
1669 : NullProtoObjectViaActiveX(activeXDocument); // WSH
1670 var length = enumBugKeys.length;
1671 while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];
1672 return NullProtoObject();
1673 };
1674
1675 hiddenKeys[IE_PROTO] = true;
1676
1677 // `Object.create` method
1678 // https://tc39.es/ecma262/#sec-object.create
1679 // eslint-disable-next-line es/no-object-create -- safe
1680 objectCreate = Object.create || function create(O, Properties) {
1681 var result;
1682 if (O !== null) {
1683 EmptyConstructor[PROTOTYPE] = anObject(O);
1684 result = new EmptyConstructor();
1685 EmptyConstructor[PROTOTYPE] = null;
1686 // add "__proto__" for Object.getPrototypeOf polyfill
1687 result[IE_PROTO] = O;
1688 } else result = NullProtoObject();
1689 return Properties === undefined ? result : definePropertiesModule.f(result, Properties);
1690 };
1691 return objectCreate;
1692 }
1693
1694 var defineBuiltIns;
1695 var hasRequiredDefineBuiltIns;
1696
1697 function requireDefineBuiltIns () {
1698 if (hasRequiredDefineBuiltIns) return defineBuiltIns;
1699 hasRequiredDefineBuiltIns = 1;
1700 var defineBuiltIn = requireDefineBuiltIn();
1701
1702 defineBuiltIns = function (target, src, options) {
1703 for (var key in src) defineBuiltIn(target, key, src[key], options);
1704 return target;
1705 };
1706 return defineBuiltIns;
1707 }
1708
1709 var correctPrototypeGetter;
1710 var hasRequiredCorrectPrototypeGetter;
1711
1712 function requireCorrectPrototypeGetter () {
1713 if (hasRequiredCorrectPrototypeGetter) return correctPrototypeGetter;
1714 hasRequiredCorrectPrototypeGetter = 1;
1715 var fails = requireFails();
1716
1717 correctPrototypeGetter = !fails(function () {
1718 function F() { /* empty */ }
1719 F.prototype.constructor = null;
1720 // eslint-disable-next-line es/no-object-getprototypeof -- required for testing
1721 return Object.getPrototypeOf(new F()) !== F.prototype;
1722 });
1723 return correctPrototypeGetter;
1724 }
1725
1726 var objectGetPrototypeOf;
1727 var hasRequiredObjectGetPrototypeOf;
1728
1729 function requireObjectGetPrototypeOf () {
1730 if (hasRequiredObjectGetPrototypeOf) return objectGetPrototypeOf;
1731 hasRequiredObjectGetPrototypeOf = 1;
1732 var hasOwn = requireHasOwnProperty();
1733 var isCallable = requireIsCallable();
1734 var toObject = requireToObject();
1735 var sharedKey = requireSharedKey();
1736 var CORRECT_PROTOTYPE_GETTER = requireCorrectPrototypeGetter();
1737
1738 var IE_PROTO = sharedKey('IE_PROTO');
1739 var $Object = Object;
1740 var ObjectPrototype = $Object.prototype;
1741
1742 // `Object.getPrototypeOf` method
1743 // https://tc39.es/ecma262/#sec-object.getprototypeof
1744 // eslint-disable-next-line es/no-object-getprototypeof -- safe
1745 objectGetPrototypeOf = CORRECT_PROTOTYPE_GETTER ? $Object.getPrototypeOf : function (O) {
1746 var object = toObject(O);
1747 if (hasOwn(object, IE_PROTO)) return object[IE_PROTO];
1748 var constructor = object.constructor;
1749 if (isCallable(constructor) && object instanceof constructor) {
1750 return constructor.prototype;
1751 } return object instanceof $Object ? ObjectPrototype : null;
1752 };
1753 return objectGetPrototypeOf;
1754 }
1755
1756 var iteratorsCore;
1757 var hasRequiredIteratorsCore;
1758
1759 function requireIteratorsCore () {
1760 if (hasRequiredIteratorsCore) return iteratorsCore;
1761 hasRequiredIteratorsCore = 1;
1762 var fails = requireFails();
1763 var isCallable = requireIsCallable();
1764 var isObject = requireIsObject();
1765 var create = requireObjectCreate();
1766 var getPrototypeOf = requireObjectGetPrototypeOf();
1767 var defineBuiltIn = requireDefineBuiltIn();
1768 var wellKnownSymbol = requireWellKnownSymbol();
1769 var IS_PURE = requireIsPure();
1770
1771 var ITERATOR = wellKnownSymbol('iterator');
1772 var BUGGY_SAFARI_ITERATORS = false;
1773
1774 // `%IteratorPrototype%` object
1775 // https://tc39.es/ecma262/#sec-%iteratorprototype%-object
1776 var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
1777
1778 /* eslint-disable es/no-array-prototype-keys -- safe */
1779 if ([].keys) {
1780 arrayIterator = [].keys();
1781 // Safari 8 has buggy iterators w/o `next`
1782 if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
1783 else {
1784 PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));
1785 if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
1786 }
1787 }
1788
1789 var NEW_ITERATOR_PROTOTYPE = !isObject(IteratorPrototype) || fails(function () {
1790 var test = {};
1791 // FF44- legacy iterators case
1792 return IteratorPrototype[ITERATOR].call(test) !== test;
1793 });
1794
1795 if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {};
1796 else if (IS_PURE) IteratorPrototype = create(IteratorPrototype);
1797
1798 // `%IteratorPrototype%[@@iterator]()` method
1799 // https://tc39.es/ecma262/#sec-%iteratorprototype%-@@iterator
1800 if (!isCallable(IteratorPrototype[ITERATOR])) {
1801 defineBuiltIn(IteratorPrototype, ITERATOR, function () {
1802 return this;
1803 });
1804 }
1805
1806 iteratorsCore = {
1807 IteratorPrototype: IteratorPrototype,
1808 BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
1809 };
1810 return iteratorsCore;
1811 }
1812
1813 var createIterResultObject;
1814 var hasRequiredCreateIterResultObject;
1815
1816 function requireCreateIterResultObject () {
1817 if (hasRequiredCreateIterResultObject) return createIterResultObject;
1818 hasRequiredCreateIterResultObject = 1;
1819 // `CreateIterResultObject` abstract operation
1820 // https://tc39.es/ecma262/#sec-createiterresultobject
1821 createIterResultObject = function (value, done) {
1822 return { value: value, done: done };
1823 };
1824 return createIterResultObject;
1825 }
1826
1827 var iteratorClose;
1828 var hasRequiredIteratorClose;
1829
1830 function requireIteratorClose () {
1831 if (hasRequiredIteratorClose) return iteratorClose;
1832 hasRequiredIteratorClose = 1;
1833 var call = requireFunctionCall();
1834 var anObject = requireAnObject();
1835 var getMethod = requireGetMethod();
1836
1837 iteratorClose = function (iterator, kind, value) {
1838 var innerResult, innerError;
1839 anObject(iterator);
1840 try {
1841 innerResult = getMethod(iterator, 'return');
1842 if (!innerResult) {
1843 if (kind === 'throw') throw value;
1844 return value;
1845 }
1846 innerResult = call(innerResult, iterator);
1847 } catch (error) {
1848 innerError = true;
1849 innerResult = error;
1850 }
1851 if (kind === 'throw') throw value;
1852 if (innerError) throw innerResult;
1853 anObject(innerResult);
1854 return value;
1855 };
1856 return iteratorClose;
1857 }
1858
1859 var iteratorCreateProxy;
1860 var hasRequiredIteratorCreateProxy;
1861
1862 function requireIteratorCreateProxy () {
1863 if (hasRequiredIteratorCreateProxy) return iteratorCreateProxy;
1864 hasRequiredIteratorCreateProxy = 1;
1865 var call = requireFunctionCall();
1866 var create = requireObjectCreate();
1867 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
1868 var defineBuiltIns = requireDefineBuiltIns();
1869 var wellKnownSymbol = requireWellKnownSymbol();
1870 var InternalStateModule = requireInternalState();
1871 var getMethod = requireGetMethod();
1872 var IteratorPrototype = requireIteratorsCore().IteratorPrototype;
1873 var createIterResultObject = requireCreateIterResultObject();
1874 var iteratorClose = requireIteratorClose();
1875
1876 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
1877 var ITERATOR_HELPER = 'IteratorHelper';
1878 var WRAP_FOR_VALID_ITERATOR = 'WrapForValidIterator';
1879 var setInternalState = InternalStateModule.set;
1880
1881 var createIteratorProxyPrototype = function (IS_ITERATOR) {
1882 var getInternalState = InternalStateModule.getterFor(IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER);
1883
1884 return defineBuiltIns(create(IteratorPrototype), {
1885 next: function next() {
1886 var state = getInternalState(this);
1887 // for simplification:
1888 // for `%WrapForValidIteratorPrototype%.next` our `nextHandler` returns `IterResultObject`
1889 // for `%IteratorHelperPrototype%.next` - just a value
1890 if (IS_ITERATOR) return state.nextHandler();
1891 try {
1892 var result = state.done ? undefined : state.nextHandler();
1893 return createIterResultObject(result, state.done);
1894 } catch (error) {
1895 state.done = true;
1896 throw error;
1897 }
1898 },
1899 'return': function () {
1900 var state = getInternalState(this);
1901 var iterator = state.iterator;
1902 state.done = true;
1903 if (IS_ITERATOR) {
1904 var returnMethod = getMethod(iterator, 'return');
1905 return returnMethod ? call(returnMethod, iterator) : createIterResultObject(undefined, true);
1906 }
1907 if (state.inner) try {
1908 iteratorClose(state.inner.iterator, 'normal');
1909 } catch (error) {
1910 return iteratorClose(iterator, 'throw', error);
1911 }
1912 if (iterator) iteratorClose(iterator, 'normal');
1913 return createIterResultObject(undefined, true);
1914 }
1915 });
1916 };
1917
1918 var WrapForValidIteratorPrototype = createIteratorProxyPrototype(true);
1919 var IteratorHelperPrototype = createIteratorProxyPrototype(false);
1920
1921 createNonEnumerableProperty(IteratorHelperPrototype, TO_STRING_TAG, 'Iterator Helper');
1922
1923 iteratorCreateProxy = function (nextHandler, IS_ITERATOR) {
1924 var IteratorProxy = function Iterator(record, state) {
1925 if (state) {
1926 state.iterator = record.iterator;
1927 state.next = record.next;
1928 } else state = record;
1929 state.type = IS_ITERATOR ? WRAP_FOR_VALID_ITERATOR : ITERATOR_HELPER;
1930 state.nextHandler = nextHandler;
1931 state.counter = 0;
1932 state.done = false;
1933 setInternalState(this, state);
1934 };
1935
1936 IteratorProxy.prototype = IS_ITERATOR ? WrapForValidIteratorPrototype : IteratorHelperPrototype;
1937
1938 return IteratorProxy;
1939 };
1940 return iteratorCreateProxy;
1941 }
1942
1943 var callWithSafeIterationClosing;
1944 var hasRequiredCallWithSafeIterationClosing;
1945
1946 function requireCallWithSafeIterationClosing () {
1947 if (hasRequiredCallWithSafeIterationClosing) return callWithSafeIterationClosing;
1948 hasRequiredCallWithSafeIterationClosing = 1;
1949 var anObject = requireAnObject();
1950 var iteratorClose = requireIteratorClose();
1951
1952 // call something on iterator step with safe closing on error
1953 callWithSafeIterationClosing = function (iterator, fn, value, ENTRIES) {
1954 try {
1955 return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);
1956 } catch (error) {
1957 iteratorClose(iterator, 'throw', error);
1958 }
1959 };
1960 return callWithSafeIterationClosing;
1961 }
1962
1963 var iteratorMap;
1964 var hasRequiredIteratorMap;
1965
1966 function requireIteratorMap () {
1967 if (hasRequiredIteratorMap) return iteratorMap;
1968 hasRequiredIteratorMap = 1;
1969 var call = requireFunctionCall();
1970 var aCallable = requireACallable();
1971 var anObject = requireAnObject();
1972 var getIteratorDirect = requireGetIteratorDirect();
1973 var createIteratorProxy = requireIteratorCreateProxy();
1974 var callWithSafeIterationClosing = requireCallWithSafeIterationClosing();
1975
1976 var IteratorProxy = createIteratorProxy(function () {
1977 var iterator = this.iterator;
1978 var result = anObject(call(this.next, iterator));
1979 var done = this.done = !!result.done;
1980 if (!done) return callWithSafeIterationClosing(iterator, this.mapper, [result.value, this.counter++], true);
1981 });
1982
1983 // `Iterator.prototype.map` method
1984 // https://github.com/tc39/proposal-iterator-helpers
1985 iteratorMap = function map(mapper) {
1986 anObject(this);
1987 aCallable(mapper);
1988 return new IteratorProxy(getIteratorDirect(this), {
1989 mapper: mapper
1990 });
1991 };
1992 return iteratorMap;
1993 }
1994
1995 var hasRequiredEs_iterator_map;
1996
1997 function requireEs_iterator_map () {
1998 if (hasRequiredEs_iterator_map) return es_iterator_map;
1999 hasRequiredEs_iterator_map = 1;
2000 var $ = require_export();
2001 var map = requireIteratorMap();
2002 var IS_PURE = requireIsPure();
2003
2004 // `Iterator.prototype.map` method
2005 // https://tc39.es/ecma262/#sec-iterator.prototype.map
2006 $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
2007 map: map
2008 });
2009 return es_iterator_map;
2010 }
2011
2012 var hasRequiredEsnext_iterator_map;
2013
2014 function requireEsnext_iterator_map () {
2015 if (hasRequiredEsnext_iterator_map) return esnext_iterator_map;
2016 hasRequiredEsnext_iterator_map = 1;
2017 // TODO: Remove from `core-js@4`
2018 requireEs_iterator_map();
2019 return esnext_iterator_map;
2020 }
2021
2022 requireEsnext_iterator_map();
2023
2024 var es_error_cause = {};
2025
2026 var functionApply;
2027 var hasRequiredFunctionApply;
2028
2029 function requireFunctionApply () {
2030 if (hasRequiredFunctionApply) return functionApply;
2031 hasRequiredFunctionApply = 1;
2032 var NATIVE_BIND = requireFunctionBindNative();
2033
2034 var FunctionPrototype = Function.prototype;
2035 var apply = FunctionPrototype.apply;
2036 var call = FunctionPrototype.call;
2037
2038 // eslint-disable-next-line es/no-reflect -- safe
2039 functionApply = typeof Reflect == 'object' && Reflect.apply || (NATIVE_BIND ? call.bind(apply) : function () {
2040 return call.apply(apply, arguments);
2041 });
2042 return functionApply;
2043 }
2044
2045 var functionUncurryThisAccessor;
2046 var hasRequiredFunctionUncurryThisAccessor;
2047
2048 function requireFunctionUncurryThisAccessor () {
2049 if (hasRequiredFunctionUncurryThisAccessor) return functionUncurryThisAccessor;
2050 hasRequiredFunctionUncurryThisAccessor = 1;
2051 var uncurryThis = requireFunctionUncurryThis();
2052 var aCallable = requireACallable();
2053
2054 functionUncurryThisAccessor = function (object, key, method) {
2055 try {
2056 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
2057 return uncurryThis(aCallable(Object.getOwnPropertyDescriptor(object, key)[method]));
2058 } catch (error) { /* empty */ }
2059 };
2060 return functionUncurryThisAccessor;
2061 }
2062
2063 var isPossiblePrototype;
2064 var hasRequiredIsPossiblePrototype;
2065
2066 function requireIsPossiblePrototype () {
2067 if (hasRequiredIsPossiblePrototype) return isPossiblePrototype;
2068 hasRequiredIsPossiblePrototype = 1;
2069 var isObject = requireIsObject();
2070
2071 isPossiblePrototype = function (argument) {
2072 return isObject(argument) || argument === null;
2073 };
2074 return isPossiblePrototype;
2075 }
2076
2077 var aPossiblePrototype;
2078 var hasRequiredAPossiblePrototype;
2079
2080 function requireAPossiblePrototype () {
2081 if (hasRequiredAPossiblePrototype) return aPossiblePrototype;
2082 hasRequiredAPossiblePrototype = 1;
2083 var isPossiblePrototype = requireIsPossiblePrototype();
2084
2085 var $String = String;
2086 var $TypeError = TypeError;
2087
2088 aPossiblePrototype = function (argument) {
2089 if (isPossiblePrototype(argument)) return argument;
2090 throw new $TypeError("Can't set " + $String(argument) + ' as a prototype');
2091 };
2092 return aPossiblePrototype;
2093 }
2094
2095 var objectSetPrototypeOf;
2096 var hasRequiredObjectSetPrototypeOf;
2097
2098 function requireObjectSetPrototypeOf () {
2099 if (hasRequiredObjectSetPrototypeOf) return objectSetPrototypeOf;
2100 hasRequiredObjectSetPrototypeOf = 1;
2101 /* eslint-disable no-proto -- safe */
2102 var uncurryThisAccessor = requireFunctionUncurryThisAccessor();
2103 var isObject = requireIsObject();
2104 var requireObjectCoercible = requireRequireObjectCoercible();
2105 var aPossiblePrototype = requireAPossiblePrototype();
2106
2107 // `Object.setPrototypeOf` method
2108 // https://tc39.es/ecma262/#sec-object.setprototypeof
2109 // Works with __proto__ only. Old v8 can't work with null proto objects.
2110 // eslint-disable-next-line es/no-object-setprototypeof -- safe
2111 objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () {
2112 var CORRECT_SETTER = false;
2113 var test = {};
2114 var setter;
2115 try {
2116 setter = uncurryThisAccessor(Object.prototype, '__proto__', 'set');
2117 setter(test, []);
2118 CORRECT_SETTER = test instanceof Array;
2119 } catch (error) { /* empty */ }
2120 return function setPrototypeOf(O, proto) {
2121 requireObjectCoercible(O);
2122 aPossiblePrototype(proto);
2123 if (!isObject(O)) return O;
2124 if (CORRECT_SETTER) setter(O, proto);
2125 else O.__proto__ = proto;
2126 return O;
2127 };
2128 }() : undefined);
2129 return objectSetPrototypeOf;
2130 }
2131
2132 var proxyAccessor;
2133 var hasRequiredProxyAccessor;
2134
2135 function requireProxyAccessor () {
2136 if (hasRequiredProxyAccessor) return proxyAccessor;
2137 hasRequiredProxyAccessor = 1;
2138 var defineProperty = requireObjectDefineProperty().f;
2139
2140 proxyAccessor = function (Target, Source, key) {
2141 key in Target || defineProperty(Target, key, {
2142 configurable: true,
2143 get: function () { return Source[key]; },
2144 set: function (it) { Source[key] = it; }
2145 });
2146 };
2147 return proxyAccessor;
2148 }
2149
2150 var inheritIfRequired;
2151 var hasRequiredInheritIfRequired;
2152
2153 function requireInheritIfRequired () {
2154 if (hasRequiredInheritIfRequired) return inheritIfRequired;
2155 hasRequiredInheritIfRequired = 1;
2156 var isCallable = requireIsCallable();
2157 var isObject = requireIsObject();
2158 var setPrototypeOf = requireObjectSetPrototypeOf();
2159
2160 // makes subclassing work correct for wrapped built-ins
2161 inheritIfRequired = function ($this, dummy, Wrapper) {
2162 var NewTarget, NewTargetPrototype;
2163 if (
2164 // it can work only with native `setPrototypeOf`
2165 setPrototypeOf &&
2166 // we haven't completely correct pre-ES6 way for getting `new.target`, so use this
2167 isCallable(NewTarget = dummy.constructor) &&
2168 NewTarget !== Wrapper &&
2169 isObject(NewTargetPrototype = NewTarget.prototype) &&
2170 NewTargetPrototype !== Wrapper.prototype
2171 ) setPrototypeOf($this, NewTargetPrototype);
2172 return $this;
2173 };
2174 return inheritIfRequired;
2175 }
2176
2177 var toStringTagSupport;
2178 var hasRequiredToStringTagSupport;
2179
2180 function requireToStringTagSupport () {
2181 if (hasRequiredToStringTagSupport) return toStringTagSupport;
2182 hasRequiredToStringTagSupport = 1;
2183 var wellKnownSymbol = requireWellKnownSymbol();
2184
2185 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
2186 var test = {};
2187
2188 test[TO_STRING_TAG] = 'z';
2189
2190 toStringTagSupport = String(test) === '[object z]';
2191 return toStringTagSupport;
2192 }
2193
2194 var classof;
2195 var hasRequiredClassof;
2196
2197 function requireClassof () {
2198 if (hasRequiredClassof) return classof;
2199 hasRequiredClassof = 1;
2200 var TO_STRING_TAG_SUPPORT = requireToStringTagSupport();
2201 var isCallable = requireIsCallable();
2202 var classofRaw = requireClassofRaw();
2203 var wellKnownSymbol = requireWellKnownSymbol();
2204
2205 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
2206 var $Object = Object;
2207
2208 // ES3 wrong here
2209 var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) === 'Arguments';
2210
2211 // fallback for IE11 Script Access Denied error
2212 var tryGet = function (it, key) {
2213 try {
2214 return it[key];
2215 } catch (error) { /* empty */ }
2216 };
2217
2218 // getting tag from ES6+ `Object.prototype.toString`
2219 classof = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {
2220 var O, tag, result;
2221 return it === undefined ? 'Undefined' : it === null ? 'Null'
2222 // @@toStringTag case
2223 : typeof (tag = tryGet(O = $Object(it), TO_STRING_TAG)) == 'string' ? tag
2224 // builtinTag case
2225 : CORRECT_ARGUMENTS ? classofRaw(O)
2226 // ES3 arguments fallback
2227 : (result = classofRaw(O)) === 'Object' && isCallable(O.callee) ? 'Arguments' : result;
2228 };
2229 return classof;
2230 }
2231
2232 var toString;
2233 var hasRequiredToString;
2234
2235 function requireToString () {
2236 if (hasRequiredToString) return toString;
2237 hasRequiredToString = 1;
2238 var classof = requireClassof();
2239
2240 var $String = String;
2241
2242 toString = function (argument) {
2243 if (classof(argument) === 'Symbol') throw new TypeError('Cannot convert a Symbol value to a string');
2244 return $String(argument);
2245 };
2246 return toString;
2247 }
2248
2249 var normalizeStringArgument;
2250 var hasRequiredNormalizeStringArgument;
2251
2252 function requireNormalizeStringArgument () {
2253 if (hasRequiredNormalizeStringArgument) return normalizeStringArgument;
2254 hasRequiredNormalizeStringArgument = 1;
2255 var toString = requireToString();
2256
2257 normalizeStringArgument = function (argument, $default) {
2258 return argument === undefined ? arguments.length < 2 ? '' : $default : toString(argument);
2259 };
2260 return normalizeStringArgument;
2261 }
2262
2263 var installErrorCause;
2264 var hasRequiredInstallErrorCause;
2265
2266 function requireInstallErrorCause () {
2267 if (hasRequiredInstallErrorCause) return installErrorCause;
2268 hasRequiredInstallErrorCause = 1;
2269 var isObject = requireIsObject();
2270 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
2271
2272 // `InstallErrorCause` abstract operation
2273 // https://tc39.es/proposal-error-cause/#sec-errorobjects-install-error-cause
2274 installErrorCause = function (O, options) {
2275 if (isObject(options) && 'cause' in options) {
2276 createNonEnumerableProperty(O, 'cause', options.cause);
2277 }
2278 };
2279 return installErrorCause;
2280 }
2281
2282 var errorStackClear;
2283 var hasRequiredErrorStackClear;
2284
2285 function requireErrorStackClear () {
2286 if (hasRequiredErrorStackClear) return errorStackClear;
2287 hasRequiredErrorStackClear = 1;
2288 var uncurryThis = requireFunctionUncurryThis();
2289
2290 var $Error = Error;
2291 var replace = uncurryThis(''.replace);
2292
2293 var TEST = (function (arg) { return String(new $Error(arg).stack); })('zxcasd');
2294 // eslint-disable-next-line redos/no-vulnerable, sonarjs/slow-regex -- safe
2295 var V8_OR_CHAKRA_STACK_ENTRY = /\n\s*at [^:]*:[^\n]*/;
2296 var IS_V8_OR_CHAKRA_STACK = V8_OR_CHAKRA_STACK_ENTRY.test(TEST);
2297
2298 errorStackClear = function (stack, dropEntries) {
2299 if (IS_V8_OR_CHAKRA_STACK && typeof stack == 'string' && !$Error.prepareStackTrace) {
2300 while (dropEntries--) stack = replace(stack, V8_OR_CHAKRA_STACK_ENTRY, '');
2301 } return stack;
2302 };
2303 return errorStackClear;
2304 }
2305
2306 var errorStackInstallable;
2307 var hasRequiredErrorStackInstallable;
2308
2309 function requireErrorStackInstallable () {
2310 if (hasRequiredErrorStackInstallable) return errorStackInstallable;
2311 hasRequiredErrorStackInstallable = 1;
2312 var fails = requireFails();
2313 var createPropertyDescriptor = requireCreatePropertyDescriptor();
2314
2315 errorStackInstallable = !fails(function () {
2316 var error = new Error('a');
2317 if (!('stack' in error)) return true;
2318 // eslint-disable-next-line es/no-object-defineproperty -- safe
2319 Object.defineProperty(error, 'stack', createPropertyDescriptor(1, 7));
2320 return error.stack !== 7;
2321 });
2322 return errorStackInstallable;
2323 }
2324
2325 var errorStackInstall;
2326 var hasRequiredErrorStackInstall;
2327
2328 function requireErrorStackInstall () {
2329 if (hasRequiredErrorStackInstall) return errorStackInstall;
2330 hasRequiredErrorStackInstall = 1;
2331 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
2332 var clearErrorStack = requireErrorStackClear();
2333 var ERROR_STACK_INSTALLABLE = requireErrorStackInstallable();
2334
2335 // non-standard V8
2336 var captureStackTrace = Error.captureStackTrace;
2337
2338 errorStackInstall = function (error, C, stack, dropEntries) {
2339 if (ERROR_STACK_INSTALLABLE) {
2340 if (captureStackTrace) captureStackTrace(error, C);
2341 else createNonEnumerableProperty(error, 'stack', clearErrorStack(stack, dropEntries));
2342 }
2343 };
2344 return errorStackInstall;
2345 }
2346
2347 var wrapErrorConstructorWithCause;
2348 var hasRequiredWrapErrorConstructorWithCause;
2349
2350 function requireWrapErrorConstructorWithCause () {
2351 if (hasRequiredWrapErrorConstructorWithCause) return wrapErrorConstructorWithCause;
2352 hasRequiredWrapErrorConstructorWithCause = 1;
2353 var getBuiltIn = requireGetBuiltIn();
2354 var hasOwn = requireHasOwnProperty();
2355 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
2356 var isPrototypeOf = requireObjectIsPrototypeOf();
2357 var setPrototypeOf = requireObjectSetPrototypeOf();
2358 var copyConstructorProperties = requireCopyConstructorProperties();
2359 var proxyAccessor = requireProxyAccessor();
2360 var inheritIfRequired = requireInheritIfRequired();
2361 var normalizeStringArgument = requireNormalizeStringArgument();
2362 var installErrorCause = requireInstallErrorCause();
2363 var installErrorStack = requireErrorStackInstall();
2364 var DESCRIPTORS = requireDescriptors();
2365 var IS_PURE = requireIsPure();
2366
2367 wrapErrorConstructorWithCause = function (FULL_NAME, wrapper, FORCED, IS_AGGREGATE_ERROR) {
2368 var STACK_TRACE_LIMIT = 'stackTraceLimit';
2369 var OPTIONS_POSITION = IS_AGGREGATE_ERROR ? 2 : 1;
2370 var path = FULL_NAME.split('.');
2371 var ERROR_NAME = path[path.length - 1];
2372 var OriginalError = getBuiltIn.apply(null, path);
2373
2374 if (!OriginalError) return;
2375
2376 var OriginalErrorPrototype = OriginalError.prototype;
2377
2378 // V8 9.3- bug https://bugs.chromium.org/p/v8/issues/detail?id=12006
2379 if (!IS_PURE && hasOwn(OriginalErrorPrototype, 'cause')) delete OriginalErrorPrototype.cause;
2380
2381 if (!FORCED) return OriginalError;
2382
2383 var BaseError = getBuiltIn('Error');
2384
2385 var WrappedError = wrapper(function (a, b) {
2386 var message = normalizeStringArgument(IS_AGGREGATE_ERROR ? b : a, undefined);
2387 var result = IS_AGGREGATE_ERROR ? new OriginalError(a) : new OriginalError();
2388 if (message !== undefined) createNonEnumerableProperty(result, 'message', message);
2389 installErrorStack(result, WrappedError, result.stack, 2);
2390 if (this && isPrototypeOf(OriginalErrorPrototype, this)) inheritIfRequired(result, this, WrappedError);
2391 if (arguments.length > OPTIONS_POSITION) installErrorCause(result, arguments[OPTIONS_POSITION]);
2392 return result;
2393 });
2394
2395 WrappedError.prototype = OriginalErrorPrototype;
2396
2397 if (ERROR_NAME !== 'Error') {
2398 if (setPrototypeOf) setPrototypeOf(WrappedError, BaseError);
2399 else copyConstructorProperties(WrappedError, BaseError, { name: true });
2400 } else if (DESCRIPTORS && STACK_TRACE_LIMIT in OriginalError) {
2401 proxyAccessor(WrappedError, OriginalError, STACK_TRACE_LIMIT);
2402 proxyAccessor(WrappedError, OriginalError, 'prepareStackTrace');
2403 }
2404
2405 copyConstructorProperties(WrappedError, OriginalError);
2406
2407 if (!IS_PURE) try {
2408 // Safari 13- bug: WebAssembly errors does not have a proper `.name`
2409 if (OriginalErrorPrototype.name !== ERROR_NAME) {
2410 createNonEnumerableProperty(OriginalErrorPrototype, 'name', ERROR_NAME);
2411 }
2412 OriginalErrorPrototype.constructor = WrappedError;
2413 } catch (error) { /* empty */ }
2414
2415 return WrappedError;
2416 };
2417 return wrapErrorConstructorWithCause;
2418 }
2419
2420 var hasRequiredEs_error_cause;
2421
2422 function requireEs_error_cause () {
2423 if (hasRequiredEs_error_cause) return es_error_cause;
2424 hasRequiredEs_error_cause = 1;
2425 /* eslint-disable no-unused-vars -- required for functions `.length` */
2426 var $ = require_export();
2427 var globalThis = requireGlobalThis();
2428 var apply = requireFunctionApply();
2429 var wrapErrorConstructorWithCause = requireWrapErrorConstructorWithCause();
2430
2431 var WEB_ASSEMBLY = 'WebAssembly';
2432 var WebAssembly = globalThis[WEB_ASSEMBLY];
2433
2434 // eslint-disable-next-line es/no-error-cause -- feature detection
2435 var FORCED = new Error('e', { cause: 7 }).cause !== 7;
2436
2437 var exportGlobalErrorCauseWrapper = function (ERROR_NAME, wrapper) {
2438 var O = {};
2439 O[ERROR_NAME] = wrapErrorConstructorWithCause(ERROR_NAME, wrapper, FORCED);
2440 $({ global: true, constructor: true, arity: 1, forced: FORCED }, O);
2441 };
2442
2443 var exportWebAssemblyErrorCauseWrapper = function (ERROR_NAME, wrapper) {
2444 if (WebAssembly && WebAssembly[ERROR_NAME]) {
2445 var O = {};
2446 O[ERROR_NAME] = wrapErrorConstructorWithCause(WEB_ASSEMBLY + '.' + ERROR_NAME, wrapper, FORCED);
2447 $({ target: WEB_ASSEMBLY, stat: true, constructor: true, arity: 1, forced: FORCED }, O);
2448 }
2449 };
2450
2451 // https://tc39.es/ecma262/#sec-nativeerror
2452 exportGlobalErrorCauseWrapper('Error', function (init) {
2453 return function Error(message) { return apply(init, this, arguments); };
2454 });
2455 exportGlobalErrorCauseWrapper('EvalError', function (init) {
2456 return function EvalError(message) { return apply(init, this, arguments); };
2457 });
2458 exportGlobalErrorCauseWrapper('RangeError', function (init) {
2459 return function RangeError(message) { return apply(init, this, arguments); };
2460 });
2461 exportGlobalErrorCauseWrapper('ReferenceError', function (init) {
2462 return function ReferenceError(message) { return apply(init, this, arguments); };
2463 });
2464 exportGlobalErrorCauseWrapper('SyntaxError', function (init) {
2465 return function SyntaxError(message) { return apply(init, this, arguments); };
2466 });
2467 exportGlobalErrorCauseWrapper('TypeError', function (init) {
2468 return function TypeError(message) { return apply(init, this, arguments); };
2469 });
2470 exportGlobalErrorCauseWrapper('URIError', function (init) {
2471 return function URIError(message) { return apply(init, this, arguments); };
2472 });
2473 exportWebAssemblyErrorCauseWrapper('CompileError', function (init) {
2474 return function CompileError(message) { return apply(init, this, arguments); };
2475 });
2476 exportWebAssemblyErrorCauseWrapper('LinkError', function (init) {
2477 return function LinkError(message) { return apply(init, this, arguments); };
2478 });
2479 exportWebAssemblyErrorCauseWrapper('RuntimeError', function (init) {
2480 return function RuntimeError(message) { return apply(init, this, arguments); };
2481 });
2482 return es_error_cause;
2483 }
2484
2485 requireEs_error_cause();
2486
2487 var esnext_iterator_constructor = {};
2488
2489 var es_iterator_constructor = {};
2490
2491 var anInstance;
2492 var hasRequiredAnInstance;
2493
2494 function requireAnInstance () {
2495 if (hasRequiredAnInstance) return anInstance;
2496 hasRequiredAnInstance = 1;
2497 var isPrototypeOf = requireObjectIsPrototypeOf();
2498
2499 var $TypeError = TypeError;
2500
2501 anInstance = function (it, Prototype) {
2502 if (isPrototypeOf(Prototype, it)) return it;
2503 throw new $TypeError('Incorrect invocation');
2504 };
2505 return anInstance;
2506 }
2507
2508 var defineBuiltInAccessor;
2509 var hasRequiredDefineBuiltInAccessor;
2510
2511 function requireDefineBuiltInAccessor () {
2512 if (hasRequiredDefineBuiltInAccessor) return defineBuiltInAccessor;
2513 hasRequiredDefineBuiltInAccessor = 1;
2514 var makeBuiltIn = requireMakeBuiltIn();
2515 var defineProperty = requireObjectDefineProperty();
2516
2517 defineBuiltInAccessor = function (target, name, descriptor) {
2518 if (descriptor.get) makeBuiltIn(descriptor.get, name, { getter: true });
2519 if (descriptor.set) makeBuiltIn(descriptor.set, name, { setter: true });
2520 return defineProperty.f(target, name, descriptor);
2521 };
2522 return defineBuiltInAccessor;
2523 }
2524
2525 var createProperty;
2526 var hasRequiredCreateProperty;
2527
2528 function requireCreateProperty () {
2529 if (hasRequiredCreateProperty) return createProperty;
2530 hasRequiredCreateProperty = 1;
2531 var DESCRIPTORS = requireDescriptors();
2532 var definePropertyModule = requireObjectDefineProperty();
2533 var createPropertyDescriptor = requireCreatePropertyDescriptor();
2534
2535 createProperty = function (object, key, value) {
2536 if (DESCRIPTORS) definePropertyModule.f(object, key, createPropertyDescriptor(0, value));
2537 else object[key] = value;
2538 };
2539 return createProperty;
2540 }
2541
2542 var hasRequiredEs_iterator_constructor;
2543
2544 function requireEs_iterator_constructor () {
2545 if (hasRequiredEs_iterator_constructor) return es_iterator_constructor;
2546 hasRequiredEs_iterator_constructor = 1;
2547 var $ = require_export();
2548 var globalThis = requireGlobalThis();
2549 var anInstance = requireAnInstance();
2550 var anObject = requireAnObject();
2551 var isCallable = requireIsCallable();
2552 var getPrototypeOf = requireObjectGetPrototypeOf();
2553 var defineBuiltInAccessor = requireDefineBuiltInAccessor();
2554 var createProperty = requireCreateProperty();
2555 var fails = requireFails();
2556 var hasOwn = requireHasOwnProperty();
2557 var wellKnownSymbol = requireWellKnownSymbol();
2558 var IteratorPrototype = requireIteratorsCore().IteratorPrototype;
2559 var DESCRIPTORS = requireDescriptors();
2560 var IS_PURE = requireIsPure();
2561
2562 var CONSTRUCTOR = 'constructor';
2563 var ITERATOR = 'Iterator';
2564 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
2565
2566 var $TypeError = TypeError;
2567 var NativeIterator = globalThis[ITERATOR];
2568
2569 // FF56- have non-standard global helper `Iterator`
2570 var FORCED = IS_PURE
2571 || !isCallable(NativeIterator)
2572 || NativeIterator.prototype !== IteratorPrototype
2573 // FF44- non-standard `Iterator` passes previous tests
2574 || !fails(function () { NativeIterator({}); });
2575
2576 var IteratorConstructor = function Iterator() {
2577 anInstance(this, IteratorPrototype);
2578 if (getPrototypeOf(this) === IteratorPrototype) throw new $TypeError('Abstract class Iterator not directly constructable');
2579 };
2580
2581 var defineIteratorPrototypeAccessor = function (key, value) {
2582 if (DESCRIPTORS) {
2583 defineBuiltInAccessor(IteratorPrototype, key, {
2584 configurable: true,
2585 get: function () {
2586 return value;
2587 },
2588 set: function (replacement) {
2589 anObject(this);
2590 if (this === IteratorPrototype) throw new $TypeError("You can't redefine this property");
2591 if (hasOwn(this, key)) this[key] = replacement;
2592 else createProperty(this, key, replacement);
2593 }
2594 });
2595 } else IteratorPrototype[key] = value;
2596 };
2597
2598 if (!hasOwn(IteratorPrototype, TO_STRING_TAG)) defineIteratorPrototypeAccessor(TO_STRING_TAG, ITERATOR);
2599
2600 if (FORCED || !hasOwn(IteratorPrototype, CONSTRUCTOR) || IteratorPrototype[CONSTRUCTOR] === Object) {
2601 defineIteratorPrototypeAccessor(CONSTRUCTOR, IteratorConstructor);
2602 }
2603
2604 IteratorConstructor.prototype = IteratorPrototype;
2605
2606 // `Iterator` constructor
2607 // https://tc39.es/ecma262/#sec-iterator
2608 $({ global: true, constructor: true, forced: FORCED }, {
2609 Iterator: IteratorConstructor
2610 });
2611 return es_iterator_constructor;
2612 }
2613
2614 var hasRequiredEsnext_iterator_constructor;
2615
2616 function requireEsnext_iterator_constructor () {
2617 if (hasRequiredEsnext_iterator_constructor) return esnext_iterator_constructor;
2618 hasRequiredEsnext_iterator_constructor = 1;
2619 // TODO: Remove from `core-js@4`
2620 requireEs_iterator_constructor();
2621 return esnext_iterator_constructor;
2622 }
2623
2624 requireEsnext_iterator_constructor();
2625
2626 var esnext_iterator_reduce = {};
2627
2628 var es_iterator_reduce = {};
2629
2630 var functionUncurryThisClause;
2631 var hasRequiredFunctionUncurryThisClause;
2632
2633 function requireFunctionUncurryThisClause () {
2634 if (hasRequiredFunctionUncurryThisClause) return functionUncurryThisClause;
2635 hasRequiredFunctionUncurryThisClause = 1;
2636 var classofRaw = requireClassofRaw();
2637 var uncurryThis = requireFunctionUncurryThis();
2638
2639 functionUncurryThisClause = function (fn) {
2640 // Nashorn bug:
2641 // https://github.com/zloirock/core-js/issues/1128
2642 // https://github.com/zloirock/core-js/issues/1130
2643 if (classofRaw(fn) === 'Function') return uncurryThis(fn);
2644 };
2645 return functionUncurryThisClause;
2646 }
2647
2648 var functionBindContext;
2649 var hasRequiredFunctionBindContext;
2650
2651 function requireFunctionBindContext () {
2652 if (hasRequiredFunctionBindContext) return functionBindContext;
2653 hasRequiredFunctionBindContext = 1;
2654 var uncurryThis = requireFunctionUncurryThisClause();
2655 var aCallable = requireACallable();
2656 var NATIVE_BIND = requireFunctionBindNative();
2657
2658 var bind = uncurryThis(uncurryThis.bind);
2659
2660 // optional / simple context binding
2661 functionBindContext = function (fn, that) {
2662 aCallable(fn);
2663 return that === undefined ? fn : NATIVE_BIND ? bind(fn, that) : function (/* ...args */) {
2664 return fn.apply(that, arguments);
2665 };
2666 };
2667 return functionBindContext;
2668 }
2669
2670 var iterators;
2671 var hasRequiredIterators;
2672
2673 function requireIterators () {
2674 if (hasRequiredIterators) return iterators;
2675 hasRequiredIterators = 1;
2676 iterators = {};
2677 return iterators;
2678 }
2679
2680 var isArrayIteratorMethod;
2681 var hasRequiredIsArrayIteratorMethod;
2682
2683 function requireIsArrayIteratorMethod () {
2684 if (hasRequiredIsArrayIteratorMethod) return isArrayIteratorMethod;
2685 hasRequiredIsArrayIteratorMethod = 1;
2686 var wellKnownSymbol = requireWellKnownSymbol();
2687 var Iterators = requireIterators();
2688
2689 var ITERATOR = wellKnownSymbol('iterator');
2690 var ArrayPrototype = Array.prototype;
2691
2692 // check on default Array iterator
2693 isArrayIteratorMethod = function (it) {
2694 return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);
2695 };
2696 return isArrayIteratorMethod;
2697 }
2698
2699 var getIteratorMethod;
2700 var hasRequiredGetIteratorMethod;
2701
2702 function requireGetIteratorMethod () {
2703 if (hasRequiredGetIteratorMethod) return getIteratorMethod;
2704 hasRequiredGetIteratorMethod = 1;
2705 var classof = requireClassof();
2706 var getMethod = requireGetMethod();
2707 var isNullOrUndefined = requireIsNullOrUndefined();
2708 var Iterators = requireIterators();
2709 var wellKnownSymbol = requireWellKnownSymbol();
2710
2711 var ITERATOR = wellKnownSymbol('iterator');
2712
2713 getIteratorMethod = function (it) {
2714 if (!isNullOrUndefined(it)) return getMethod(it, ITERATOR)
2715 || getMethod(it, '@@iterator')
2716 || Iterators[classof(it)];
2717 };
2718 return getIteratorMethod;
2719 }
2720
2721 var getIterator;
2722 var hasRequiredGetIterator;
2723
2724 function requireGetIterator () {
2725 if (hasRequiredGetIterator) return getIterator;
2726 hasRequiredGetIterator = 1;
2727 var call = requireFunctionCall();
2728 var aCallable = requireACallable();
2729 var anObject = requireAnObject();
2730 var tryToString = requireTryToString();
2731 var getIteratorMethod = requireGetIteratorMethod();
2732
2733 var $TypeError = TypeError;
2734
2735 getIterator = function (argument, usingIterator) {
2736 var iteratorMethod = arguments.length < 2 ? getIteratorMethod(argument) : usingIterator;
2737 if (aCallable(iteratorMethod)) return anObject(call(iteratorMethod, argument));
2738 throw new $TypeError(tryToString(argument) + ' is not iterable');
2739 };
2740 return getIterator;
2741 }
2742
2743 var iterate;
2744 var hasRequiredIterate;
2745
2746 function requireIterate () {
2747 if (hasRequiredIterate) return iterate;
2748 hasRequiredIterate = 1;
2749 var bind = requireFunctionBindContext();
2750 var call = requireFunctionCall();
2751 var anObject = requireAnObject();
2752 var tryToString = requireTryToString();
2753 var isArrayIteratorMethod = requireIsArrayIteratorMethod();
2754 var lengthOfArrayLike = requireLengthOfArrayLike();
2755 var isPrototypeOf = requireObjectIsPrototypeOf();
2756 var getIterator = requireGetIterator();
2757 var getIteratorMethod = requireGetIteratorMethod();
2758 var iteratorClose = requireIteratorClose();
2759
2760 var $TypeError = TypeError;
2761
2762 var Result = function (stopped, result) {
2763 this.stopped = stopped;
2764 this.result = result;
2765 };
2766
2767 var ResultPrototype = Result.prototype;
2768
2769 iterate = function (iterable, unboundFunction, options) {
2770 var that = options && options.that;
2771 var AS_ENTRIES = !!(options && options.AS_ENTRIES);
2772 var IS_RECORD = !!(options && options.IS_RECORD);
2773 var IS_ITERATOR = !!(options && options.IS_ITERATOR);
2774 var INTERRUPTED = !!(options && options.INTERRUPTED);
2775 var fn = bind(unboundFunction, that);
2776 var iterator, iterFn, index, length, result, next, step;
2777
2778 var stop = function (condition) {
2779 if (iterator) iteratorClose(iterator, 'normal', condition);
2780 return new Result(true, condition);
2781 };
2782
2783 var callFn = function (value) {
2784 if (AS_ENTRIES) {
2785 anObject(value);
2786 return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
2787 } return INTERRUPTED ? fn(value, stop) : fn(value);
2788 };
2789
2790 if (IS_RECORD) {
2791 iterator = iterable.iterator;
2792 } else if (IS_ITERATOR) {
2793 iterator = iterable;
2794 } else {
2795 iterFn = getIteratorMethod(iterable);
2796 if (!iterFn) throw new $TypeError(tryToString(iterable) + ' is not iterable');
2797 // optimisation for array iterators
2798 if (isArrayIteratorMethod(iterFn)) {
2799 for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) {
2800 result = callFn(iterable[index]);
2801 if (result && isPrototypeOf(ResultPrototype, result)) return result;
2802 } return new Result(false);
2803 }
2804 iterator = getIterator(iterable, iterFn);
2805 }
2806
2807 next = IS_RECORD ? iterable.next : iterator.next;
2808 while (!(step = call(next, iterator)).done) {
2809 try {
2810 result = callFn(step.value);
2811 } catch (error) {
2812 iteratorClose(iterator, 'throw', error);
2813 }
2814 if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result;
2815 } return new Result(false);
2816 };
2817 return iterate;
2818 }
2819
2820 var hasRequiredEs_iterator_reduce;
2821
2822 function requireEs_iterator_reduce () {
2823 if (hasRequiredEs_iterator_reduce) return es_iterator_reduce;
2824 hasRequiredEs_iterator_reduce = 1;
2825 var $ = require_export();
2826 var iterate = requireIterate();
2827 var aCallable = requireACallable();
2828 var anObject = requireAnObject();
2829 var getIteratorDirect = requireGetIteratorDirect();
2830
2831 var $TypeError = TypeError;
2832
2833 // `Iterator.prototype.reduce` method
2834 // https://tc39.es/ecma262/#sec-iterator.prototype.reduce
2835 $({ target: 'Iterator', proto: true, real: true }, {
2836 reduce: function reduce(reducer /* , initialValue */) {
2837 anObject(this);
2838 aCallable(reducer);
2839 var record = getIteratorDirect(this);
2840 var noInitial = arguments.length < 2;
2841 var accumulator = noInitial ? undefined : arguments[1];
2842 var counter = 0;
2843 iterate(record, function (value) {
2844 if (noInitial) {
2845 noInitial = false;
2846 accumulator = value;
2847 } else {
2848 accumulator = reducer(accumulator, value, counter);
2849 }
2850 counter++;
2851 }, { IS_RECORD: true });
2852 if (noInitial) throw new $TypeError('Reduce of empty iterator with no initial value');
2853 return accumulator;
2854 }
2855 });
2856 return es_iterator_reduce;
2857 }
2858
2859 var hasRequiredEsnext_iterator_reduce;
2860
2861 function requireEsnext_iterator_reduce () {
2862 if (hasRequiredEsnext_iterator_reduce) return esnext_iterator_reduce;
2863 hasRequiredEsnext_iterator_reduce = 1;
2864 // TODO: Remove from `core-js@4`
2865 requireEs_iterator_reduce();
2866 return esnext_iterator_reduce;
2867 }
2868
2869 requireEsnext_iterator_reduce();
2870
2871 var web_domException_constructor = {};
2872
2873 var environment$1;
2874 var hasRequiredEnvironment;
2875
2876 function requireEnvironment () {
2877 if (hasRequiredEnvironment) return environment$1;
2878 hasRequiredEnvironment = 1;
2879 /* global Bun, Deno -- detection */
2880 var globalThis = requireGlobalThis();
2881 var userAgent = requireEnvironmentUserAgent();
2882 var classof = requireClassofRaw();
2883
2884 var userAgentStartsWith = function (string) {
2885 return userAgent.slice(0, string.length) === string;
2886 };
2887
2888 environment$1 = (function () {
2889 if (userAgentStartsWith('Bun/')) return 'BUN';
2890 if (userAgentStartsWith('Cloudflare-Workers')) return 'CLOUDFLARE';
2891 if (userAgentStartsWith('Deno/')) return 'DENO';
2892 if (userAgentStartsWith('Node.js/')) return 'NODE';
2893 if (globalThis.Bun && typeof Bun.version == 'string') return 'BUN';
2894 if (globalThis.Deno && typeof Deno.version == 'object') return 'DENO';
2895 if (classof(globalThis.process) === 'process') return 'NODE';
2896 if (globalThis.window && globalThis.document) return 'BROWSER';
2897 return 'REST';
2898 })();
2899 return environment$1;
2900 }
2901
2902 var environmentIsNode;
2903 var hasRequiredEnvironmentIsNode;
2904
2905 function requireEnvironmentIsNode () {
2906 if (hasRequiredEnvironmentIsNode) return environmentIsNode;
2907 hasRequiredEnvironmentIsNode = 1;
2908 var ENVIRONMENT = requireEnvironment();
2909
2910 environmentIsNode = ENVIRONMENT === 'NODE';
2911 return environmentIsNode;
2912 }
2913
2914 var getBuiltInNodeModule;
2915 var hasRequiredGetBuiltInNodeModule;
2916
2917 function requireGetBuiltInNodeModule () {
2918 if (hasRequiredGetBuiltInNodeModule) return getBuiltInNodeModule;
2919 hasRequiredGetBuiltInNodeModule = 1;
2920 var globalThis = requireGlobalThis();
2921 var IS_NODE = requireEnvironmentIsNode();
2922
2923 getBuiltInNodeModule = function (name) {
2924 if (IS_NODE) {
2925 try {
2926 return globalThis.process.getBuiltinModule(name);
2927 } catch (error) { /* empty */ }
2928 try {
2929 // eslint-disable-next-line no-new-func -- safe
2930 return Function('return require("' + name + '")')();
2931 } catch (error) { /* empty */ }
2932 }
2933 };
2934 return getBuiltInNodeModule;
2935 }
2936
2937 var errorToString;
2938 var hasRequiredErrorToString;
2939
2940 function requireErrorToString () {
2941 if (hasRequiredErrorToString) return errorToString;
2942 hasRequiredErrorToString = 1;
2943 var DESCRIPTORS = requireDescriptors();
2944 var fails = requireFails();
2945 var anObject = requireAnObject();
2946 var normalizeStringArgument = requireNormalizeStringArgument();
2947
2948 var nativeErrorToString = Error.prototype.toString;
2949
2950 var INCORRECT_TO_STRING = fails(function () {
2951 if (DESCRIPTORS) {
2952 // Chrome 32- incorrectly call accessor
2953 // eslint-disable-next-line es/no-object-create, es/no-object-defineproperty -- safe
2954 var object = Object.create(Object.defineProperty({}, 'name', { get: function () {
2955 return this === object;
2956 } }));
2957 if (nativeErrorToString.call(object) !== 'true') return true;
2958 }
2959 // FF10- does not properly handle non-strings
2960 return nativeErrorToString.call({ message: 1, name: 2 }) !== '2: 1'
2961 // IE8 does not properly handle defaults
2962 || nativeErrorToString.call({}) !== 'Error';
2963 });
2964
2965 errorToString = INCORRECT_TO_STRING ? function toString() {
2966 var O = anObject(this);
2967 var name = normalizeStringArgument(O.name, 'Error');
2968 var message = normalizeStringArgument(O.message);
2969 return !name ? message : !message ? name : name + ': ' + message;
2970 } : nativeErrorToString;
2971 return errorToString;
2972 }
2973
2974 var domExceptionConstants;
2975 var hasRequiredDomExceptionConstants;
2976
2977 function requireDomExceptionConstants () {
2978 if (hasRequiredDomExceptionConstants) return domExceptionConstants;
2979 hasRequiredDomExceptionConstants = 1;
2980 domExceptionConstants = {
2981 IndexSizeError: { s: 'INDEX_SIZE_ERR', c: 1, m: 1 },
2982 DOMStringSizeError: { s: 'DOMSTRING_SIZE_ERR', c: 2, m: 0 },
2983 HierarchyRequestError: { s: 'HIERARCHY_REQUEST_ERR', c: 3, m: 1 },
2984 WrongDocumentError: { s: 'WRONG_DOCUMENT_ERR', c: 4, m: 1 },
2985 InvalidCharacterError: { s: 'INVALID_CHARACTER_ERR', c: 5, m: 1 },
2986 NoDataAllowedError: { s: 'NO_DATA_ALLOWED_ERR', c: 6, m: 0 },
2987 NoModificationAllowedError: { s: 'NO_MODIFICATION_ALLOWED_ERR', c: 7, m: 1 },
2988 NotFoundError: { s: 'NOT_FOUND_ERR', c: 8, m: 1 },
2989 NotSupportedError: { s: 'NOT_SUPPORTED_ERR', c: 9, m: 1 },
2990 InUseAttributeError: { s: 'INUSE_ATTRIBUTE_ERR', c: 10, m: 1 },
2991 InvalidStateError: { s: 'INVALID_STATE_ERR', c: 11, m: 1 },
2992 SyntaxError: { s: 'SYNTAX_ERR', c: 12, m: 1 },
2993 InvalidModificationError: { s: 'INVALID_MODIFICATION_ERR', c: 13, m: 1 },
2994 NamespaceError: { s: 'NAMESPACE_ERR', c: 14, m: 1 },
2995 InvalidAccessError: { s: 'INVALID_ACCESS_ERR', c: 15, m: 1 },
2996 ValidationError: { s: 'VALIDATION_ERR', c: 16, m: 0 },
2997 TypeMismatchError: { s: 'TYPE_MISMATCH_ERR', c: 17, m: 1 },
2998 SecurityError: { s: 'SECURITY_ERR', c: 18, m: 1 },
2999 NetworkError: { s: 'NETWORK_ERR', c: 19, m: 1 },
3000 AbortError: { s: 'ABORT_ERR', c: 20, m: 1 },
3001 URLMismatchError: { s: 'URL_MISMATCH_ERR', c: 21, m: 1 },
3002 QuotaExceededError: { s: 'QUOTA_EXCEEDED_ERR', c: 22, m: 1 },
3003 TimeoutError: { s: 'TIMEOUT_ERR', c: 23, m: 1 },
3004 InvalidNodeTypeError: { s: 'INVALID_NODE_TYPE_ERR', c: 24, m: 1 },
3005 DataCloneError: { s: 'DATA_CLONE_ERR', c: 25, m: 1 }
3006 };
3007 return domExceptionConstants;
3008 }
3009
3010 var hasRequiredWeb_domException_constructor;
3011
3012 function requireWeb_domException_constructor () {
3013 if (hasRequiredWeb_domException_constructor) return web_domException_constructor;
3014 hasRequiredWeb_domException_constructor = 1;
3015 var $ = require_export();
3016 var getBuiltIn = requireGetBuiltIn();
3017 var getBuiltInNodeModule = requireGetBuiltInNodeModule();
3018 var fails = requireFails();
3019 var create = requireObjectCreate();
3020 var createPropertyDescriptor = requireCreatePropertyDescriptor();
3021 var defineProperty = requireObjectDefineProperty().f;
3022 var defineBuiltIn = requireDefineBuiltIn();
3023 var defineBuiltInAccessor = requireDefineBuiltInAccessor();
3024 var hasOwn = requireHasOwnProperty();
3025 var anInstance = requireAnInstance();
3026 var anObject = requireAnObject();
3027 var errorToString = requireErrorToString();
3028 var normalizeStringArgument = requireNormalizeStringArgument();
3029 var DOMExceptionConstants = requireDomExceptionConstants();
3030 var clearErrorStack = requireErrorStackClear();
3031 var InternalStateModule = requireInternalState();
3032 var DESCRIPTORS = requireDescriptors();
3033 var IS_PURE = requireIsPure();
3034
3035 var DOM_EXCEPTION = 'DOMException';
3036 var DATA_CLONE_ERR = 'DATA_CLONE_ERR';
3037 var Error = getBuiltIn('Error');
3038 // NodeJS < 17.0 does not expose `DOMException` to global
3039 var NativeDOMException = getBuiltIn(DOM_EXCEPTION) || (function () {
3040 try {
3041 // NodeJS < 15.0 does not expose `MessageChannel` to global
3042 var MessageChannel = getBuiltIn('MessageChannel') || getBuiltInNodeModule('worker_threads').MessageChannel;
3043 // eslint-disable-next-line es/no-weak-map, unicorn/require-post-message-target-origin -- safe
3044 new MessageChannel().port1.postMessage(new WeakMap());
3045 } catch (error) {
3046 if (error.name === DATA_CLONE_ERR && error.code === 25) return error.constructor;
3047 }
3048 })();
3049 var NativeDOMExceptionPrototype = NativeDOMException && NativeDOMException.prototype;
3050 var ErrorPrototype = Error.prototype;
3051 var setInternalState = InternalStateModule.set;
3052 var getInternalState = InternalStateModule.getterFor(DOM_EXCEPTION);
3053 var HAS_STACK = 'stack' in new Error(DOM_EXCEPTION);
3054
3055 var codeFor = function (name) {
3056 return hasOwn(DOMExceptionConstants, name) && DOMExceptionConstants[name].m ? DOMExceptionConstants[name].c : 0;
3057 };
3058
3059 var $DOMException = function DOMException() {
3060 anInstance(this, DOMExceptionPrototype);
3061 var argumentsLength = arguments.length;
3062 var message = normalizeStringArgument(argumentsLength < 1 ? undefined : arguments[0]);
3063 var name = normalizeStringArgument(argumentsLength < 2 ? undefined : arguments[1], 'Error');
3064 var code = codeFor(name);
3065 setInternalState(this, {
3066 type: DOM_EXCEPTION,
3067 name: name,
3068 message: message,
3069 code: code
3070 });
3071 if (!DESCRIPTORS) {
3072 this.name = name;
3073 this.message = message;
3074 this.code = code;
3075 }
3076 if (HAS_STACK) {
3077 var error = new Error(message);
3078 error.name = DOM_EXCEPTION;
3079 defineProperty(this, 'stack', createPropertyDescriptor(1, clearErrorStack(error.stack, 1)));
3080 }
3081 };
3082
3083 var DOMExceptionPrototype = $DOMException.prototype = create(ErrorPrototype);
3084
3085 var createGetterDescriptor = function (get) {
3086 return { enumerable: true, configurable: true, get: get };
3087 };
3088
3089 var getterFor = function (key) {
3090 return createGetterDescriptor(function () {
3091 return getInternalState(this)[key];
3092 });
3093 };
3094
3095 if (DESCRIPTORS) {
3096 // `DOMException.prototype.code` getter
3097 defineBuiltInAccessor(DOMExceptionPrototype, 'code', getterFor('code'));
3098 // `DOMException.prototype.message` getter
3099 defineBuiltInAccessor(DOMExceptionPrototype, 'message', getterFor('message'));
3100 // `DOMException.prototype.name` getter
3101 defineBuiltInAccessor(DOMExceptionPrototype, 'name', getterFor('name'));
3102 }
3103
3104 defineProperty(DOMExceptionPrototype, 'constructor', createPropertyDescriptor(1, $DOMException));
3105
3106 // FF36- DOMException is a function, but can't be constructed
3107 var INCORRECT_CONSTRUCTOR = fails(function () {
3108 return !(new NativeDOMException() instanceof Error);
3109 });
3110
3111 // Safari 10.1 / Chrome 32- / IE8- DOMException.prototype.toString bugs
3112 var INCORRECT_TO_STRING = INCORRECT_CONSTRUCTOR || fails(function () {
3113 return ErrorPrototype.toString !== errorToString || String(new NativeDOMException(1, 2)) !== '2: 1';
3114 });
3115
3116 // Deno 1.6.3- DOMException.prototype.code just missed
3117 var INCORRECT_CODE = INCORRECT_CONSTRUCTOR || fails(function () {
3118 return new NativeDOMException(1, 'DataCloneError').code !== 25;
3119 });
3120
3121 // Deno 1.6.3- DOMException constants just missed
3122 var MISSED_CONSTANTS = INCORRECT_CONSTRUCTOR
3123 || NativeDOMException[DATA_CLONE_ERR] !== 25
3124 || NativeDOMExceptionPrototype[DATA_CLONE_ERR] !== 25;
3125
3126 var FORCED_CONSTRUCTOR = IS_PURE ? INCORRECT_TO_STRING || INCORRECT_CODE || MISSED_CONSTANTS : INCORRECT_CONSTRUCTOR;
3127
3128 // `DOMException` constructor
3129 // https://webidl.spec.whatwg.org/#idl-DOMException
3130 $({ global: true, constructor: true, forced: FORCED_CONSTRUCTOR }, {
3131 DOMException: FORCED_CONSTRUCTOR ? $DOMException : NativeDOMException
3132 });
3133
3134 var PolyfilledDOMException = getBuiltIn(DOM_EXCEPTION);
3135 var PolyfilledDOMExceptionPrototype = PolyfilledDOMException.prototype;
3136
3137 if (INCORRECT_TO_STRING && (IS_PURE || NativeDOMException === PolyfilledDOMException)) {
3138 defineBuiltIn(PolyfilledDOMExceptionPrototype, 'toString', errorToString);
3139 }
3140
3141 if (INCORRECT_CODE && DESCRIPTORS && NativeDOMException === PolyfilledDOMException) {
3142 defineBuiltInAccessor(PolyfilledDOMExceptionPrototype, 'code', createGetterDescriptor(function () {
3143 return codeFor(anObject(this).name);
3144 }));
3145 }
3146
3147 // `DOMException` constants
3148 for (var key in DOMExceptionConstants) if (hasOwn(DOMExceptionConstants, key)) {
3149 var constant = DOMExceptionConstants[key];
3150 var constantName = constant.s;
3151 var descriptor = createPropertyDescriptor(6, constant.c);
3152 if (!hasOwn(PolyfilledDOMException, constantName)) {
3153 defineProperty(PolyfilledDOMException, constantName, descriptor);
3154 }
3155 if (!hasOwn(PolyfilledDOMExceptionPrototype, constantName)) {
3156 defineProperty(PolyfilledDOMExceptionPrototype, constantName, descriptor);
3157 }
3158 }
3159 return web_domException_constructor;
3160 }
3161
3162 requireWeb_domException_constructor();
3163
3164 var web_domException_stack = {};
3165
3166 var hasRequiredWeb_domException_stack;
3167
3168 function requireWeb_domException_stack () {
3169 if (hasRequiredWeb_domException_stack) return web_domException_stack;
3170 hasRequiredWeb_domException_stack = 1;
3171 var $ = require_export();
3172 var globalThis = requireGlobalThis();
3173 var getBuiltIn = requireGetBuiltIn();
3174 var createPropertyDescriptor = requireCreatePropertyDescriptor();
3175 var defineProperty = requireObjectDefineProperty().f;
3176 var hasOwn = requireHasOwnProperty();
3177 var anInstance = requireAnInstance();
3178 var inheritIfRequired = requireInheritIfRequired();
3179 var normalizeStringArgument = requireNormalizeStringArgument();
3180 var DOMExceptionConstants = requireDomExceptionConstants();
3181 var clearErrorStack = requireErrorStackClear();
3182 var DESCRIPTORS = requireDescriptors();
3183 var IS_PURE = requireIsPure();
3184
3185 var DOM_EXCEPTION = 'DOMException';
3186 var Error = getBuiltIn('Error');
3187 var NativeDOMException = getBuiltIn(DOM_EXCEPTION);
3188
3189 var $DOMException = function DOMException() {
3190 anInstance(this, DOMExceptionPrototype);
3191 var argumentsLength = arguments.length;
3192 var message = normalizeStringArgument(argumentsLength < 1 ? undefined : arguments[0]);
3193 var name = normalizeStringArgument(argumentsLength < 2 ? undefined : arguments[1], 'Error');
3194 var that = new NativeDOMException(message, name);
3195 var error = new Error(message);
3196 error.name = DOM_EXCEPTION;
3197 defineProperty(that, 'stack', createPropertyDescriptor(1, clearErrorStack(error.stack, 1)));
3198 inheritIfRequired(that, this, $DOMException);
3199 return that;
3200 };
3201
3202 var DOMExceptionPrototype = $DOMException.prototype = NativeDOMException.prototype;
3203
3204 var ERROR_HAS_STACK = 'stack' in new Error(DOM_EXCEPTION);
3205 var DOM_EXCEPTION_HAS_STACK = 'stack' in new NativeDOMException(1, 2);
3206
3207 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
3208 var descriptor = NativeDOMException && DESCRIPTORS && Object.getOwnPropertyDescriptor(globalThis, DOM_EXCEPTION);
3209
3210 // Bun ~ 0.1.1 DOMException have incorrect descriptor and we can't redefine it
3211 // https://github.com/Jarred-Sumner/bun/issues/399
3212 var BUGGY_DESCRIPTOR = !!descriptor && !(descriptor.writable && descriptor.configurable);
3213
3214 var FORCED_CONSTRUCTOR = ERROR_HAS_STACK && !BUGGY_DESCRIPTOR && !DOM_EXCEPTION_HAS_STACK;
3215
3216 // `DOMException` constructor patch for `.stack` where it's required
3217 // https://webidl.spec.whatwg.org/#es-DOMException-specialness
3218 $({ global: true, constructor: true, forced: IS_PURE || FORCED_CONSTRUCTOR }, { // TODO: fix export logic
3219 DOMException: FORCED_CONSTRUCTOR ? $DOMException : NativeDOMException
3220 });
3221
3222 var PolyfilledDOMException = getBuiltIn(DOM_EXCEPTION);
3223 var PolyfilledDOMExceptionPrototype = PolyfilledDOMException.prototype;
3224
3225 if (PolyfilledDOMExceptionPrototype.constructor !== PolyfilledDOMException) {
3226 if (!IS_PURE) {
3227 defineProperty(PolyfilledDOMExceptionPrototype, 'constructor', createPropertyDescriptor(1, PolyfilledDOMException));
3228 }
3229
3230 for (var key in DOMExceptionConstants) if (hasOwn(DOMExceptionConstants, key)) {
3231 var constant = DOMExceptionConstants[key];
3232 var constantName = constant.s;
3233 if (!hasOwn(PolyfilledDOMException, constantName)) {
3234 defineProperty(PolyfilledDOMException, constantName, createPropertyDescriptor(6, constant.c));
3235 }
3236 }
3237 }
3238 return web_domException_stack;
3239 }
3240
3241 requireWeb_domException_stack();
3242
3243 var web_domException_toStringTag = {};
3244
3245 var setToStringTag;
3246 var hasRequiredSetToStringTag;
3247
3248 function requireSetToStringTag () {
3249 if (hasRequiredSetToStringTag) return setToStringTag;
3250 hasRequiredSetToStringTag = 1;
3251 var defineProperty = requireObjectDefineProperty().f;
3252 var hasOwn = requireHasOwnProperty();
3253 var wellKnownSymbol = requireWellKnownSymbol();
3254
3255 var TO_STRING_TAG = wellKnownSymbol('toStringTag');
3256
3257 setToStringTag = function (target, TAG, STATIC) {
3258 if (target && !STATIC) target = target.prototype;
3259 if (target && !hasOwn(target, TO_STRING_TAG)) {
3260 defineProperty(target, TO_STRING_TAG, { configurable: true, value: TAG });
3261 }
3262 };
3263 return setToStringTag;
3264 }
3265
3266 var hasRequiredWeb_domException_toStringTag;
3267
3268 function requireWeb_domException_toStringTag () {
3269 if (hasRequiredWeb_domException_toStringTag) return web_domException_toStringTag;
3270 hasRequiredWeb_domException_toStringTag = 1;
3271 var getBuiltIn = requireGetBuiltIn();
3272 var setToStringTag = requireSetToStringTag();
3273
3274 var DOM_EXCEPTION = 'DOMException';
3275
3276 // `DOMException.prototype[@@toStringTag]` property
3277 setToStringTag(getBuiltIn(DOM_EXCEPTION), DOM_EXCEPTION);
3278 return web_domException_toStringTag;
3279 }
3280
3281 requireWeb_domException_toStringTag();
3282
3283 var web_structuredClone = {};
3284
3285 var isConstructor;
3286 var hasRequiredIsConstructor;
3287
3288 function requireIsConstructor () {
3289 if (hasRequiredIsConstructor) return isConstructor;
3290 hasRequiredIsConstructor = 1;
3291 var uncurryThis = requireFunctionUncurryThis();
3292 var fails = requireFails();
3293 var isCallable = requireIsCallable();
3294 var classof = requireClassof();
3295 var getBuiltIn = requireGetBuiltIn();
3296 var inspectSource = requireInspectSource();
3297
3298 var noop = function () { /* empty */ };
3299 var construct = getBuiltIn('Reflect', 'construct');
3300 var constructorRegExp = /^\s*(?:class|function)\b/;
3301 var exec = uncurryThis(constructorRegExp.exec);
3302 var INCORRECT_TO_STRING = !constructorRegExp.test(noop);
3303
3304 var isConstructorModern = function isConstructor(argument) {
3305 if (!isCallable(argument)) return false;
3306 try {
3307 construct(noop, [], argument);
3308 return true;
3309 } catch (error) {
3310 return false;
3311 }
3312 };
3313
3314 var isConstructorLegacy = function isConstructor(argument) {
3315 if (!isCallable(argument)) return false;
3316 switch (classof(argument)) {
3317 case 'AsyncFunction':
3318 case 'GeneratorFunction':
3319 case 'AsyncGeneratorFunction': return false;
3320 }
3321 try {
3322 // we can't check .prototype since constructors produced by .bind haven't it
3323 // `Function#toString` throws on some built-it function in some legacy engines
3324 // (for example, `DOMQuad` and similar in FF41-)
3325 return INCORRECT_TO_STRING || !!exec(constructorRegExp, inspectSource(argument));
3326 } catch (error) {
3327 return true;
3328 }
3329 };
3330
3331 isConstructorLegacy.sham = true;
3332
3333 // `IsConstructor` abstract operation
3334 // https://tc39.es/ecma262/#sec-isconstructor
3335 isConstructor = !construct || fails(function () {
3336 var called;
3337 return isConstructorModern(isConstructorModern.call)
3338 || !isConstructorModern(Object)
3339 || !isConstructorModern(function () { called = true; })
3340 || called;
3341 }) ? isConstructorLegacy : isConstructorModern;
3342 return isConstructor;
3343 }
3344
3345 var validateArgumentsLength;
3346 var hasRequiredValidateArgumentsLength;
3347
3348 function requireValidateArgumentsLength () {
3349 if (hasRequiredValidateArgumentsLength) return validateArgumentsLength;
3350 hasRequiredValidateArgumentsLength = 1;
3351 var $TypeError = TypeError;
3352
3353 validateArgumentsLength = function (passed, required) {
3354 if (passed < required) throw new $TypeError('Not enough arguments');
3355 return passed;
3356 };
3357 return validateArgumentsLength;
3358 }
3359
3360 var regexpFlags;
3361 var hasRequiredRegexpFlags;
3362
3363 function requireRegexpFlags () {
3364 if (hasRequiredRegexpFlags) return regexpFlags;
3365 hasRequiredRegexpFlags = 1;
3366 var anObject = requireAnObject();
3367
3368 // `RegExp.prototype.flags` getter implementation
3369 // https://tc39.es/ecma262/#sec-get-regexp.prototype.flags
3370 regexpFlags = function () {
3371 var that = anObject(this);
3372 var result = '';
3373 if (that.hasIndices) result += 'd';
3374 if (that.global) result += 'g';
3375 if (that.ignoreCase) result += 'i';
3376 if (that.multiline) result += 'm';
3377 if (that.dotAll) result += 's';
3378 if (that.unicode) result += 'u';
3379 if (that.unicodeSets) result += 'v';
3380 if (that.sticky) result += 'y';
3381 return result;
3382 };
3383 return regexpFlags;
3384 }
3385
3386 var regexpGetFlags;
3387 var hasRequiredRegexpGetFlags;
3388
3389 function requireRegexpGetFlags () {
3390 if (hasRequiredRegexpGetFlags) return regexpGetFlags;
3391 hasRequiredRegexpGetFlags = 1;
3392 var call = requireFunctionCall();
3393 var hasOwn = requireHasOwnProperty();
3394 var isPrototypeOf = requireObjectIsPrototypeOf();
3395 var regExpFlags = requireRegexpFlags();
3396
3397 var RegExpPrototype = RegExp.prototype;
3398
3399 regexpGetFlags = function (R) {
3400 var flags = R.flags;
3401 return flags === undefined && !('flags' in RegExpPrototype) && !hasOwn(R, 'flags') && isPrototypeOf(RegExpPrototype, R)
3402 ? call(regExpFlags, R) : flags;
3403 };
3404 return regexpGetFlags;
3405 }
3406
3407 var mapHelpers;
3408 var hasRequiredMapHelpers;
3409
3410 function requireMapHelpers () {
3411 if (hasRequiredMapHelpers) return mapHelpers;
3412 hasRequiredMapHelpers = 1;
3413 var uncurryThis = requireFunctionUncurryThis();
3414
3415 // eslint-disable-next-line es/no-map -- safe
3416 var MapPrototype = Map.prototype;
3417
3418 mapHelpers = {
3419 // eslint-disable-next-line es/no-map -- safe
3420 Map: Map,
3421 set: uncurryThis(MapPrototype.set),
3422 get: uncurryThis(MapPrototype.get),
3423 has: uncurryThis(MapPrototype.has),
3424 remove: uncurryThis(MapPrototype['delete']),
3425 proto: MapPrototype
3426 };
3427 return mapHelpers;
3428 }
3429
3430 var setHelpers;
3431 var hasRequiredSetHelpers;
3432
3433 function requireSetHelpers () {
3434 if (hasRequiredSetHelpers) return setHelpers;
3435 hasRequiredSetHelpers = 1;
3436 var uncurryThis = requireFunctionUncurryThis();
3437
3438 // eslint-disable-next-line es/no-set -- safe
3439 var SetPrototype = Set.prototype;
3440
3441 setHelpers = {
3442 // eslint-disable-next-line es/no-set -- safe
3443 Set: Set,
3444 add: uncurryThis(SetPrototype.add),
3445 has: uncurryThis(SetPrototype.has),
3446 remove: uncurryThis(SetPrototype['delete']),
3447 proto: SetPrototype
3448 };
3449 return setHelpers;
3450 }
3451
3452 var iterateSimple;
3453 var hasRequiredIterateSimple;
3454
3455 function requireIterateSimple () {
3456 if (hasRequiredIterateSimple) return iterateSimple;
3457 hasRequiredIterateSimple = 1;
3458 var call = requireFunctionCall();
3459
3460 iterateSimple = function (record, fn, ITERATOR_INSTEAD_OF_RECORD) {
3461 var iterator = ITERATOR_INSTEAD_OF_RECORD ? record : record.iterator;
3462 var next = record.next;
3463 var step, result;
3464 while (!(step = call(next, iterator)).done) {
3465 result = fn(step.value);
3466 if (result !== undefined) return result;
3467 }
3468 };
3469 return iterateSimple;
3470 }
3471
3472 var setIterate;
3473 var hasRequiredSetIterate;
3474
3475 function requireSetIterate () {
3476 if (hasRequiredSetIterate) return setIterate;
3477 hasRequiredSetIterate = 1;
3478 var uncurryThis = requireFunctionUncurryThis();
3479 var iterateSimple = requireIterateSimple();
3480 var SetHelpers = requireSetHelpers();
3481
3482 var Set = SetHelpers.Set;
3483 var SetPrototype = SetHelpers.proto;
3484 var forEach = uncurryThis(SetPrototype.forEach);
3485 var keys = uncurryThis(SetPrototype.keys);
3486 var next = keys(new Set()).next;
3487
3488 setIterate = function (set, fn, interruptible) {
3489 return interruptible ? iterateSimple({ iterator: keys(set), next: next }, fn) : forEach(set, fn);
3490 };
3491 return setIterate;
3492 }
3493
3494 var structuredCloneProperTransfer;
3495 var hasRequiredStructuredCloneProperTransfer;
3496
3497 function requireStructuredCloneProperTransfer () {
3498 if (hasRequiredStructuredCloneProperTransfer) return structuredCloneProperTransfer;
3499 hasRequiredStructuredCloneProperTransfer = 1;
3500 var globalThis = requireGlobalThis();
3501 var fails = requireFails();
3502 var V8 = requireEnvironmentV8Version();
3503 var ENVIRONMENT = requireEnvironment();
3504
3505 var structuredClone = globalThis.structuredClone;
3506
3507 structuredCloneProperTransfer = !!structuredClone && !fails(function () {
3508 // prevent V8 ArrayBufferDetaching protector cell invalidation and performance degradation
3509 // https://github.com/zloirock/core-js/issues/679
3510 if ((ENVIRONMENT === 'DENO' && V8 > 92) || (ENVIRONMENT === 'NODE' && V8 > 94) || (ENVIRONMENT === 'BROWSER' && V8 > 97)) return false;
3511 var buffer = new ArrayBuffer(8);
3512 var clone = structuredClone(buffer, { transfer: [buffer] });
3513 return buffer.byteLength !== 0 || clone.byteLength !== 8;
3514 });
3515 return structuredCloneProperTransfer;
3516 }
3517
3518 var detachTransferable;
3519 var hasRequiredDetachTransferable;
3520
3521 function requireDetachTransferable () {
3522 if (hasRequiredDetachTransferable) return detachTransferable;
3523 hasRequiredDetachTransferable = 1;
3524 var globalThis = requireGlobalThis();
3525 var getBuiltInNodeModule = requireGetBuiltInNodeModule();
3526 var PROPER_STRUCTURED_CLONE_TRANSFER = requireStructuredCloneProperTransfer();
3527
3528 var structuredClone = globalThis.structuredClone;
3529 var $ArrayBuffer = globalThis.ArrayBuffer;
3530 var $MessageChannel = globalThis.MessageChannel;
3531 var detach = false;
3532 var WorkerThreads, channel, buffer, $detach;
3533
3534 if (PROPER_STRUCTURED_CLONE_TRANSFER) {
3535 detach = function (transferable) {
3536 structuredClone(transferable, { transfer: [transferable] });
3537 };
3538 } else if ($ArrayBuffer) try {
3539 if (!$MessageChannel) {
3540 WorkerThreads = getBuiltInNodeModule('worker_threads');
3541 if (WorkerThreads) $MessageChannel = WorkerThreads.MessageChannel;
3542 }
3543
3544 if ($MessageChannel) {
3545 channel = new $MessageChannel();
3546 buffer = new $ArrayBuffer(2);
3547
3548 $detach = function (transferable) {
3549 channel.port1.postMessage(null, [transferable]);
3550 };
3551
3552 if (buffer.byteLength === 2) {
3553 $detach(buffer);
3554 if (buffer.byteLength === 0) detach = $detach;
3555 }
3556 }
3557 } catch (error) { /* empty */ }
3558
3559 detachTransferable = detach;
3560 return detachTransferable;
3561 }
3562
3563 var hasRequiredWeb_structuredClone;
3564
3565 function requireWeb_structuredClone () {
3566 if (hasRequiredWeb_structuredClone) return web_structuredClone;
3567 hasRequiredWeb_structuredClone = 1;
3568 var IS_PURE = requireIsPure();
3569 var $ = require_export();
3570 var globalThis = requireGlobalThis();
3571 var getBuiltIn = requireGetBuiltIn();
3572 var uncurryThis = requireFunctionUncurryThis();
3573 var fails = requireFails();
3574 var uid = requireUid();
3575 var isCallable = requireIsCallable();
3576 var isConstructor = requireIsConstructor();
3577 var isNullOrUndefined = requireIsNullOrUndefined();
3578 var isObject = requireIsObject();
3579 var isSymbol = requireIsSymbol();
3580 var iterate = requireIterate();
3581 var anObject = requireAnObject();
3582 var classof = requireClassof();
3583 var hasOwn = requireHasOwnProperty();
3584 var createProperty = requireCreateProperty();
3585 var createNonEnumerableProperty = requireCreateNonEnumerableProperty();
3586 var lengthOfArrayLike = requireLengthOfArrayLike();
3587 var validateArgumentsLength = requireValidateArgumentsLength();
3588 var getRegExpFlags = requireRegexpGetFlags();
3589 var MapHelpers = requireMapHelpers();
3590 var SetHelpers = requireSetHelpers();
3591 var setIterate = requireSetIterate();
3592 var detachTransferable = requireDetachTransferable();
3593 var ERROR_STACK_INSTALLABLE = requireErrorStackInstallable();
3594 var PROPER_STRUCTURED_CLONE_TRANSFER = requireStructuredCloneProperTransfer();
3595
3596 var Object = globalThis.Object;
3597 var Array = globalThis.Array;
3598 var Date = globalThis.Date;
3599 var Error = globalThis.Error;
3600 var TypeError = globalThis.TypeError;
3601 var PerformanceMark = globalThis.PerformanceMark;
3602 var DOMException = getBuiltIn('DOMException');
3603 var Map = MapHelpers.Map;
3604 var mapHas = MapHelpers.has;
3605 var mapGet = MapHelpers.get;
3606 var mapSet = MapHelpers.set;
3607 var Set = SetHelpers.Set;
3608 var setAdd = SetHelpers.add;
3609 var setHas = SetHelpers.has;
3610 var objectKeys = getBuiltIn('Object', 'keys');
3611 var push = uncurryThis([].push);
3612 var thisBooleanValue = uncurryThis(true.valueOf);
3613 var thisNumberValue = uncurryThis(1.0.valueOf);
3614 var thisStringValue = uncurryThis(''.valueOf);
3615 var thisTimeValue = uncurryThis(Date.prototype.getTime);
3616 var PERFORMANCE_MARK = uid('structuredClone');
3617 var DATA_CLONE_ERROR = 'DataCloneError';
3618 var TRANSFERRING = 'Transferring';
3619
3620 var checkBasicSemantic = function (structuredCloneImplementation) {
3621 return !fails(function () {
3622 var set1 = new globalThis.Set([7]);
3623 var set2 = structuredCloneImplementation(set1);
3624 var number = structuredCloneImplementation(Object(7));
3625 return set2 === set1 || !set2.has(7) || !isObject(number) || +number !== 7;
3626 }) && structuredCloneImplementation;
3627 };
3628
3629 var checkErrorsCloning = function (structuredCloneImplementation, $Error) {
3630 return !fails(function () {
3631 var error = new $Error();
3632 var test = structuredCloneImplementation({ a: error, b: error });
3633 return !(test && test.a === test.b && test.a instanceof $Error && test.a.stack === error.stack);
3634 });
3635 };
3636
3637 // https://github.com/whatwg/html/pull/5749
3638 var checkNewErrorsCloningSemantic = function (structuredCloneImplementation) {
3639 return !fails(function () {
3640 var test = structuredCloneImplementation(new globalThis.AggregateError([1], PERFORMANCE_MARK, { cause: 3 }));
3641 return test.name !== 'AggregateError' || test.errors[0] !== 1 || test.message !== PERFORMANCE_MARK || test.cause !== 3;
3642 });
3643 };
3644
3645 // FF94+, Safari 15.4+, Chrome 98+, NodeJS 17.0+, Deno 1.13+
3646 // FF<103 and Safari implementations can't clone errors
3647 // https://bugzilla.mozilla.org/show_bug.cgi?id=1556604
3648 // FF103 can clone errors, but `.stack` of clone is an empty string
3649 // https://bugzilla.mozilla.org/show_bug.cgi?id=1778762
3650 // FF104+ fixed it on usual errors, but not on DOMExceptions
3651 // https://bugzilla.mozilla.org/show_bug.cgi?id=1777321
3652 // Chrome <102 returns `null` if cloned object contains multiple references to one error
3653 // https://bugs.chromium.org/p/v8/issues/detail?id=12542
3654 // NodeJS implementation can't clone DOMExceptions
3655 // https://github.com/nodejs/node/issues/41038
3656 // only FF103+ supports new (html/5749) error cloning semantic
3657 var nativeStructuredClone = globalThis.structuredClone;
3658
3659 var FORCED_REPLACEMENT = IS_PURE
3660 || !checkErrorsCloning(nativeStructuredClone, Error)
3661 || !checkErrorsCloning(nativeStructuredClone, DOMException)
3662 || !checkNewErrorsCloningSemantic(nativeStructuredClone);
3663
3664 // Chrome 82+, Safari 14.1+, Deno 1.11+
3665 // Chrome 78-81 implementation swaps `.name` and `.message` of cloned `DOMException`
3666 // Chrome returns `null` if cloned object contains multiple references to one error
3667 // Safari 14.1 implementation doesn't clone some `RegExp` flags, so requires a workaround
3668 // Safari implementation can't clone errors
3669 // Deno 1.2-1.10 implementations too naive
3670 // NodeJS 16.0+ does not have `PerformanceMark` constructor
3671 // NodeJS <17.2 structured cloning implementation from `performance.mark` is too naive
3672 // and can't clone, for example, `RegExp` or some boxed primitives
3673 // https://github.com/nodejs/node/issues/40840
3674 // no one of those implementations supports new (html/5749) error cloning semantic
3675 var structuredCloneFromMark = !nativeStructuredClone && checkBasicSemantic(function (value) {
3676 return new PerformanceMark(PERFORMANCE_MARK, { detail: value }).detail;
3677 });
3678
3679 var nativeRestrictedStructuredClone = checkBasicSemantic(nativeStructuredClone) || structuredCloneFromMark;
3680
3681 var throwUncloneable = function (type) {
3682 throw new DOMException('Uncloneable type: ' + type, DATA_CLONE_ERROR);
3683 };
3684
3685 var throwUnpolyfillable = function (type, action) {
3686 throw new DOMException((action || 'Cloning') + ' of ' + type + ' cannot be properly polyfilled in this engine', DATA_CLONE_ERROR);
3687 };
3688
3689 var tryNativeRestrictedStructuredClone = function (value, type) {
3690 if (!nativeRestrictedStructuredClone) throwUnpolyfillable(type);
3691 return nativeRestrictedStructuredClone(value);
3692 };
3693
3694 var createDataTransfer = function () {
3695 var dataTransfer;
3696 try {
3697 dataTransfer = new globalThis.DataTransfer();
3698 } catch (error) {
3699 try {
3700 dataTransfer = new globalThis.ClipboardEvent('').clipboardData;
3701 } catch (error2) { /* empty */ }
3702 }
3703 return dataTransfer && dataTransfer.items && dataTransfer.files ? dataTransfer : null;
3704 };
3705
3706 var cloneBuffer = function (value, map, $type) {
3707 if (mapHas(map, value)) return mapGet(map, value);
3708
3709 var type = $type || classof(value);
3710 var clone, length, options, source, target, i;
3711
3712 if (type === 'SharedArrayBuffer') {
3713 if (nativeRestrictedStructuredClone) clone = nativeRestrictedStructuredClone(value);
3714 // SharedArrayBuffer should use shared memory, we can't polyfill it, so return the original
3715 else clone = value;
3716 } else {
3717 var DataView = globalThis.DataView;
3718
3719 // `ArrayBuffer#slice` is not available in IE10
3720 // `ArrayBuffer#slice` and `DataView` are not available in old FF
3721 if (!DataView && !isCallable(value.slice)) throwUnpolyfillable('ArrayBuffer');
3722 // detached buffers throws in `DataView` and `.slice`
3723 try {
3724 if (isCallable(value.slice) && !value.resizable) {
3725 clone = value.slice(0);
3726 } else {
3727 length = value.byteLength;
3728 options = 'maxByteLength' in value ? { maxByteLength: value.maxByteLength } : undefined;
3729 // eslint-disable-next-line es/no-resizable-and-growable-arraybuffers -- safe
3730 clone = new ArrayBuffer(length, options);
3731 source = new DataView(value);
3732 target = new DataView(clone);
3733 for (i = 0; i < length; i++) {
3734 target.setUint8(i, source.getUint8(i));
3735 }
3736 }
3737 } catch (error) {
3738 throw new DOMException('ArrayBuffer is detached', DATA_CLONE_ERROR);
3739 }
3740 }
3741
3742 mapSet(map, value, clone);
3743
3744 return clone;
3745 };
3746
3747 var cloneView = function (value, type, offset, length, map) {
3748 var C = globalThis[type];
3749 // in some old engines like Safari 9, typeof C is 'object'
3750 // on Uint8ClampedArray or some other constructors
3751 if (!isObject(C)) throwUnpolyfillable(type);
3752 return new C(cloneBuffer(value.buffer, map), offset, length);
3753 };
3754
3755 var structuredCloneInternal = function (value, map) {
3756 if (isSymbol(value)) throwUncloneable('Symbol');
3757 if (!isObject(value)) return value;
3758 // effectively preserves circular references
3759 if (map) {
3760 if (mapHas(map, value)) return mapGet(map, value);
3761 } else map = new Map();
3762
3763 var type = classof(value);
3764 var C, name, cloned, dataTransfer, i, length, keys, key;
3765
3766 switch (type) {
3767 case 'Array':
3768 cloned = Array(lengthOfArrayLike(value));
3769 break;
3770 case 'Object':
3771 cloned = {};
3772 break;
3773 case 'Map':
3774 cloned = new Map();
3775 break;
3776 case 'Set':
3777 cloned = new Set();
3778 break;
3779 case 'RegExp':
3780 // in this block because of a Safari 14.1 bug
3781 // old FF does not clone regexes passed to the constructor, so get the source and flags directly
3782 cloned = new RegExp(value.source, getRegExpFlags(value));
3783 break;
3784 case 'Error':
3785 name = value.name;
3786 switch (name) {
3787 case 'AggregateError':
3788 cloned = new (getBuiltIn(name))([]);
3789 break;
3790 case 'EvalError':
3791 case 'RangeError':
3792 case 'ReferenceError':
3793 case 'SuppressedError':
3794 case 'SyntaxError':
3795 case 'TypeError':
3796 case 'URIError':
3797 cloned = new (getBuiltIn(name))();
3798 break;
3799 case 'CompileError':
3800 case 'LinkError':
3801 case 'RuntimeError':
3802 cloned = new (getBuiltIn('WebAssembly', name))();
3803 break;
3804 default:
3805 cloned = new Error();
3806 }
3807 break;
3808 case 'DOMException':
3809 cloned = new DOMException(value.message, value.name);
3810 break;
3811 case 'ArrayBuffer':
3812 case 'SharedArrayBuffer':
3813 cloned = cloneBuffer(value, map, type);
3814 break;
3815 case 'DataView':
3816 case 'Int8Array':
3817 case 'Uint8Array':
3818 case 'Uint8ClampedArray':
3819 case 'Int16Array':
3820 case 'Uint16Array':
3821 case 'Int32Array':
3822 case 'Uint32Array':
3823 case 'Float16Array':
3824 case 'Float32Array':
3825 case 'Float64Array':
3826 case 'BigInt64Array':
3827 case 'BigUint64Array':
3828 length = type === 'DataView' ? value.byteLength : value.length;
3829 cloned = cloneView(value, type, value.byteOffset, length, map);
3830 break;
3831 case 'DOMQuad':
3832 try {
3833 cloned = new DOMQuad(
3834 structuredCloneInternal(value.p1, map),
3835 structuredCloneInternal(value.p2, map),
3836 structuredCloneInternal(value.p3, map),
3837 structuredCloneInternal(value.p4, map)
3838 );
3839 } catch (error) {
3840 cloned = tryNativeRestrictedStructuredClone(value, type);
3841 }
3842 break;
3843 case 'File':
3844 if (nativeRestrictedStructuredClone) try {
3845 cloned = nativeRestrictedStructuredClone(value);
3846 // NodeJS 20.0.0 bug, https://github.com/nodejs/node/issues/47612
3847 if (classof(cloned) !== type) cloned = undefined;
3848 } catch (error) { /* empty */ }
3849 if (!cloned) try {
3850 cloned = new File([value], value.name, value);
3851 } catch (error) { /* empty */ }
3852 if (!cloned) throwUnpolyfillable(type);
3853 break;
3854 case 'FileList':
3855 dataTransfer = createDataTransfer();
3856 if (dataTransfer) {
3857 for (i = 0, length = lengthOfArrayLike(value); i < length; i++) {
3858 dataTransfer.items.add(structuredCloneInternal(value[i], map));
3859 }
3860 cloned = dataTransfer.files;
3861 } else cloned = tryNativeRestrictedStructuredClone(value, type);
3862 break;
3863 case 'ImageData':
3864 // Safari 9 ImageData is a constructor, but typeof ImageData is 'object'
3865 try {
3866 cloned = new ImageData(
3867 structuredCloneInternal(value.data, map),
3868 value.width,
3869 value.height,
3870 { colorSpace: value.colorSpace }
3871 );
3872 } catch (error) {
3873 cloned = tryNativeRestrictedStructuredClone(value, type);
3874 } break;
3875 default:
3876 if (nativeRestrictedStructuredClone) {
3877 cloned = nativeRestrictedStructuredClone(value);
3878 } else switch (type) {
3879 case 'BigInt':
3880 // can be a 3rd party polyfill
3881 cloned = Object(value.valueOf());
3882 break;
3883 case 'Boolean':
3884 cloned = Object(thisBooleanValue(value));
3885 break;
3886 case 'Number':
3887 cloned = Object(thisNumberValue(value));
3888 break;
3889 case 'String':
3890 cloned = Object(thisStringValue(value));
3891 break;
3892 case 'Date':
3893 cloned = new Date(thisTimeValue(value));
3894 break;
3895 case 'Blob':
3896 try {
3897 cloned = value.slice(0, value.size, value.type);
3898 } catch (error) {
3899 throwUnpolyfillable(type);
3900 } break;
3901 case 'DOMPoint':
3902 case 'DOMPointReadOnly':
3903 C = globalThis[type];
3904 try {
3905 cloned = C.fromPoint
3906 ? C.fromPoint(value)
3907 : new C(value.x, value.y, value.z, value.w);
3908 } catch (error) {
3909 throwUnpolyfillable(type);
3910 } break;
3911 case 'DOMRect':
3912 case 'DOMRectReadOnly':
3913 C = globalThis[type];
3914 try {
3915 cloned = C.fromRect
3916 ? C.fromRect(value)
3917 : new C(value.x, value.y, value.width, value.height);
3918 } catch (error) {
3919 throwUnpolyfillable(type);
3920 } break;
3921 case 'DOMMatrix':
3922 case 'DOMMatrixReadOnly':
3923 C = globalThis[type];
3924 try {
3925 cloned = C.fromMatrix
3926 ? C.fromMatrix(value)
3927 : new C(value);
3928 } catch (error) {
3929 throwUnpolyfillable(type);
3930 } break;
3931 case 'AudioData':
3932 case 'VideoFrame':
3933 if (!isCallable(value.clone)) throwUnpolyfillable(type);
3934 try {
3935 cloned = value.clone();
3936 } catch (error) {
3937 throwUncloneable(type);
3938 } break;
3939 case 'CropTarget':
3940 case 'CryptoKey':
3941 case 'FileSystemDirectoryHandle':
3942 case 'FileSystemFileHandle':
3943 case 'FileSystemHandle':
3944 case 'GPUCompilationInfo':
3945 case 'GPUCompilationMessage':
3946 case 'ImageBitmap':
3947 case 'RTCCertificate':
3948 case 'WebAssembly.Module':
3949 throwUnpolyfillable(type);
3950 // break omitted
3951 default:
3952 throwUncloneable(type);
3953 }
3954 }
3955
3956 mapSet(map, value, cloned);
3957
3958 switch (type) {
3959 case 'Array':
3960 case 'Object':
3961 keys = objectKeys(value);
3962 for (i = 0, length = lengthOfArrayLike(keys); i < length; i++) {
3963 key = keys[i];
3964 createProperty(cloned, key, structuredCloneInternal(value[key], map));
3965 } break;
3966 case 'Map':
3967 value.forEach(function (v, k) {
3968 mapSet(cloned, structuredCloneInternal(k, map), structuredCloneInternal(v, map));
3969 });
3970 break;
3971 case 'Set':
3972 value.forEach(function (v) {
3973 setAdd(cloned, structuredCloneInternal(v, map));
3974 });
3975 break;
3976 case 'Error':
3977 createNonEnumerableProperty(cloned, 'message', structuredCloneInternal(value.message, map));
3978 if (hasOwn(value, 'cause')) {
3979 createNonEnumerableProperty(cloned, 'cause', structuredCloneInternal(value.cause, map));
3980 }
3981 if (name === 'AggregateError') {
3982 cloned.errors = structuredCloneInternal(value.errors, map);
3983 } else if (name === 'SuppressedError') {
3984 cloned.error = structuredCloneInternal(value.error, map);
3985 cloned.suppressed = structuredCloneInternal(value.suppressed, map);
3986 } // break omitted
3987 case 'DOMException':
3988 if (ERROR_STACK_INSTALLABLE) {
3989 createNonEnumerableProperty(cloned, 'stack', structuredCloneInternal(value.stack, map));
3990 }
3991 }
3992
3993 return cloned;
3994 };
3995
3996 var tryToTransfer = function (rawTransfer, map) {
3997 if (!isObject(rawTransfer)) throw new TypeError('Transfer option cannot be converted to a sequence');
3998
3999 var transfer = [];
4000
4001 iterate(rawTransfer, function (value) {
4002 push(transfer, anObject(value));
4003 });
4004
4005 var i = 0;
4006 var length = lengthOfArrayLike(transfer);
4007 var buffers = new Set();
4008 var value, type, C, transferred, canvas, context;
4009
4010 while (i < length) {
4011 value = transfer[i++];
4012
4013 type = classof(value);
4014
4015 if (type === 'ArrayBuffer' ? setHas(buffers, value) : mapHas(map, value)) {
4016 throw new DOMException('Duplicate transferable', DATA_CLONE_ERROR);
4017 }
4018
4019 if (type === 'ArrayBuffer') {
4020 setAdd(buffers, value);
4021 continue;
4022 }
4023
4024 if (PROPER_STRUCTURED_CLONE_TRANSFER) {
4025 transferred = nativeStructuredClone(value, { transfer: [value] });
4026 } else switch (type) {
4027 case 'ImageBitmap':
4028 C = globalThis.OffscreenCanvas;
4029 if (!isConstructor(C)) throwUnpolyfillable(type, TRANSFERRING);
4030 try {
4031 canvas = new C(value.width, value.height);
4032 context = canvas.getContext('bitmaprenderer');
4033 context.transferFromImageBitmap(value);
4034 transferred = canvas.transferToImageBitmap();
4035 } catch (error) { /* empty */ }
4036 break;
4037 case 'AudioData':
4038 case 'VideoFrame':
4039 if (!isCallable(value.clone) || !isCallable(value.close)) throwUnpolyfillable(type, TRANSFERRING);
4040 try {
4041 transferred = value.clone();
4042 value.close();
4043 } catch (error) { /* empty */ }
4044 break;
4045 case 'MediaSourceHandle':
4046 case 'MessagePort':
4047 case 'MIDIAccess':
4048 case 'OffscreenCanvas':
4049 case 'ReadableStream':
4050 case 'RTCDataChannel':
4051 case 'TransformStream':
4052 case 'WebTransportReceiveStream':
4053 case 'WebTransportSendStream':
4054 case 'WritableStream':
4055 throwUnpolyfillable(type, TRANSFERRING);
4056 }
4057
4058 if (transferred === undefined) throw new DOMException('This object cannot be transferred: ' + type, DATA_CLONE_ERROR);
4059
4060 mapSet(map, value, transferred);
4061 }
4062
4063 return buffers;
4064 };
4065
4066 var detachBuffers = function (buffers) {
4067 setIterate(buffers, function (buffer) {
4068 if (PROPER_STRUCTURED_CLONE_TRANSFER) {
4069 nativeRestrictedStructuredClone(buffer, { transfer: [buffer] });
4070 } else if (isCallable(buffer.transfer)) {
4071 buffer.transfer();
4072 } else if (detachTransferable) {
4073 detachTransferable(buffer);
4074 } else {
4075 throwUnpolyfillable('ArrayBuffer', TRANSFERRING);
4076 }
4077 });
4078 };
4079
4080 // `structuredClone` method
4081 // https://html.spec.whatwg.org/multipage/structured-data.html#dom-structuredclone
4082 $({ global: true, enumerable: true, sham: !PROPER_STRUCTURED_CLONE_TRANSFER, forced: FORCED_REPLACEMENT }, {
4083 structuredClone: function structuredClone(value /* , { transfer } */) {
4084 var options = validateArgumentsLength(arguments.length, 1) > 1 && !isNullOrUndefined(arguments[1]) ? anObject(arguments[1]) : undefined;
4085 var transfer = options ? options.transfer : undefined;
4086 var map, buffers;
4087
4088 if (transfer !== undefined) {
4089 map = new Map();
4090 buffers = tryToTransfer(transfer, map);
4091 }
4092
4093 var clone = structuredCloneInternal(value, map);
4094
4095 // since of an issue with cloning views of transferred buffers, we a forced to detach them later
4096 // https://github.com/zloirock/core-js/issues/1265
4097 if (buffers) detachBuffers(buffers);
4098
4099 return clone;
4100 }
4101 });
4102 return web_structuredClone;
4103 }
4104
4105 requireWeb_structuredClone();
4106
4107 /** @import { Matrix3x3, Vector3 } from "./types.js" */
4108
4109 /**
4110 * A is m x n. B is n x p. product is m x p.
4111 *
4112 * Array arguments are treated like vectors:
4113 * - A becomes 1 x n
4114 * - B becomes n x 1
4115 *
4116 * Returns Matrix m x p or equivalent array or number
4117 *
4118 * @overload
4119 * @param {number[]} A Vector 1 x n
4120 * @param {number[]} B Vector n x 1
4121 * @returns {number} Scalar number
4122 *
4123 * @overload
4124 * @param {number[][]} A Matrix m x n
4125 * @param {number[]} B Vector n x 1
4126 * @returns {number[]} Array with length m
4127 *
4128 * @overload
4129 * @param {number[]} A Vector 1 x n
4130 * @param {number[][]} B Matrix n x p
4131 * @returns {number[]} Array with length p
4132 *
4133 * @overload
4134 * @param {number[][]} A Matrix m x n
4135 * @param {number[][]} B Matrix n x p
4136 * @returns {number[][]} Matrix m x p
4137 *
4138 * @param {number[] | number[][]} A Matrix m x n or a vector
4139 * @param {number[] | number[][]} B Matrix n x p or a vector
4140 * @returns {number | number[] | number[][]} Matrix m x p or equivalent array or number
4141 */
4142 function multiplyMatrices(A, B) {
4143 let m = A.length;
4144 /** @type {number[][]} */
4145 let AM;
4146 /** @type {number[][]} */
4147 let BM;
4148 let aVec = false;
4149 let bVec = false;
4150 if (!Array.isArray(A[0])) {
4151 // A is vector, convert to [[a, b, c, ...]]
4152 AM = [(/** @type {number[]} */A)];
4153 m = AM.length;
4154 aVec = true;
4155 } else {
4156 AM = /** @type {number[][]} */A;
4157 }
4158 if (!Array.isArray(B[0])) {
4159 // B is vector, convert to [[a], [b], [c], ...]]
4160 BM = B.length > 0 ? B.map(x => [x]) : [[]]; // Avoid mapping empty array
4161 bVec = true;
4162 } else {
4163 BM = /** @type {number[][]} */B;
4164 }
4165 let p = BM[0].length;
4166 let BM_cols = BM[0].map((_, i) => BM.map(x => x[i])); // transpose B
4167 /** @type {number[] | number[][]} */
4168 let product = AM.map(row => BM_cols.map(col => {
4169 let ret = 0;
4170 if (!Array.isArray(row)) {
4171 for (let c of col) {
4172 ret += row * c;
4173 }
4174 return ret;
4175 }
4176 for (let i = 0; i < row.length; i++) {
4177 ret += row[i] * (col[i] || 0);
4178 }
4179 return ret;
4180 }));
4181 if (m === 1 && aVec) {
4182 product = product[0]; // Avoid [[a, b, c, ...]]
4183 }
4184 if (p === 1 && bVec) {
4185 if (m === 1 && aVec) {
4186 return product[0]; // Avoid [[a]], return a number
4187 } else {
4188 return product.map(x => x[0]); // Avoid [[a], [b], [c], ...]]
4189 }
4190 }
4191 return product;
4192 }
4193
4194 // dot3 and transform functions adapted from https://github.com/texel-org/color/blob/9793c7d4d02b51f068e0f3fd37131129a4270396/src/core.js
4195 //
4196 // The MIT License (MIT)
4197 // Copyright (c) 2024 Matt DesLauriers
4198
4199 // Permission is hereby granted, free of charge, to any person obtaining a copy
4200 // of this software and associated documentation files (the "Software"), to deal
4201 // in the Software without restriction, including without limitation the rights
4202 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4203 // copies of the Software, and to permit persons to whom the Software is
4204 // furnished to do so, subject to the following conditions:
4205
4206 // The above copyright notice and this permission notice shall be included in all
4207 // copies or substantial portions of the Software.
4208
4209 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
4210 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4211 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
4212 // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4213 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4214 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
4215 // OR OTHER DEALINGS IN THE SOFTWARE.
4216
4217 /**
4218 * Returns the dot product of two vectors each with a length of 3.
4219 *
4220 * @param {Vector3} a
4221 * @param {Vector3} b
4222 * @returns {number}
4223 */
4224 function dot3(a, b) {
4225 return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
4226 }
4227
4228 /**
4229 * Transforms a vector of length 3 by a 3x3 matrix. Specify the same input and output
4230 * vector to transform in place.
4231 *
4232 * @param {Vector3} input
4233 * @param {Matrix3x3} matrix
4234 * @param {Vector3} [out]
4235 * @returns {Vector3}
4236 */
4237 function multiply_v3_m3x3(input, matrix, out = [0, 0, 0]) {
4238 const x = dot3(input, matrix[0]);
4239 const y = dot3(input, matrix[1]);
4240 const z = dot3(input, matrix[2]);
4241 out[0] = x;
4242 out[1] = y;
4243 out[2] = z;
4244 return out;
4245 }
4246
4247 /**
4248 * Check if a value is a string (including a String object)
4249 * @param {any} str - Value to check
4250 * @returns {str is string}
4251 */
4252 function isString(str) {
4253 return type(str) === "string";
4254 }
4255
4256 /**
4257 * Determine the internal JavaScript [[Class]] of an object.
4258 * @param {any} o - Value to check
4259 * @returns {string}
4260 */
4261 function type(o) {
4262 let str = Object.prototype.toString.call(o);
4263 return (str.match(/^\[object\s+(.*?)\]$/)[1] || "").toLowerCase();
4264 }
4265
4266 /**
4267 * @param {number} n
4268 * @param {{ precision?: number | undefined, unit?: string | undefined }} options
4269 * @returns {string}
4270 */
4271 function serializeNumber(n, {
4272 precision = 16,
4273 unit
4274 }) {
4275 if (isNone(n)) {
4276 return "none";
4277 }
4278 n = +toPrecision(n, precision);
4279 return n + (unit !== null && unit !== void 0 ? unit : "");
4280 }
4281
4282 /**
4283 * Check if a value corresponds to a none argument
4284 * @param {any} n - Value to check
4285 * @returns {n is null}
4286 */
4287 function isNone(n) {
4288 return n === null;
4289 }
4290
4291 /**
4292 * Replace none values with 0
4293 * @param {number | null} n
4294 * @returns {number}
4295 */
4296 function skipNone(n) {
4297 return isNone(n) ? 0 : n;
4298 }
4299
4300 /**
4301 * Round a number to a certain number of significant digits
4302 * @param {number} n - The number to round
4303 * @param {number} precision - Number of significant digits
4304 */
4305 function toPrecision(n, precision) {
4306 if (n === 0) {
4307 return 0;
4308 }
4309 let integer = ~~n;
4310 let digits = 0;
4311 if (integer && precision) {
4312 digits = ~~Math.log10(Math.abs(integer)) + 1;
4313 }
4314 const multiplier = 10.0 ** (precision - digits);
4315 return Math.floor(n * multiplier + 0.5) / multiplier;
4316 }
4317
4318 /**
4319 * Interpolate between two values, either of which may be a `none` value.
4320 * A `none` endpoint is treated as having the other endpoint's value;
4321 * if both are `none`, the result is `none` as well.
4322 * @param {number | null} start
4323 * @param {number | null} end
4324 * @param {number} p
4325 * @returns {number | null}
4326 */
4327 function interpolate(start, end, p) {
4328 if (isNone(start) || isNaN(start)) {
4329 return end;
4330 }
4331 if (isNone(end) || isNaN(end)) {
4332 return start;
4333 }
4334 return start + (end - start) * p;
4335 }
4336
4337 /**
4338 * @param {number} start
4339 * @param {number} end
4340 * @param {number} value
4341 */
4342 function interpolateInv(start, end, value) {
4343 return (value - start) / (end - start);
4344 }
4345
4346 /**
4347 * @param {[number, number]} from
4348 * @param {[number, number]} to
4349 * @param {number} value
4350 */
4351 function mapRange(from, to, value) {
4352 if (!from || !to || from === to || from[0] === to[0] && from[1] === to[1] || isNaN(value) || value === null) {
4353 // Ranges missing or the same
4354 return value;
4355 }
4356 return interpolate(to[0], to[1], interpolateInv(from[0], from[1], value));
4357 }
4358
4359 /**
4360 * Clamp value between the minimum and maximum
4361 * @param {number} min minimum value to return
4362 * @param {number} val the value to return if it is between min and max
4363 * @param {number} max maximum value to return
4364 */
4365 function clamp(min, val, max) {
4366 return Math.max(Math.min(max, val), min);
4367 }
4368
4369 /**
4370 * Copy sign of one value to another.
4371 * @param {number} to - Number to copy sign to
4372 * @param {number} from - Number to copy sign from
4373 */
4374 function copySign(to, from) {
4375 return Math.sign(to) === Math.sign(from) ? to : -to;
4376 }
4377
4378 /**
4379 * Perform pow on a signed number and copy sign to result
4380 * @param {number} base The base number
4381 * @param {number} exp The exponent
4382 */
4383 function spow(base, exp) {
4384 return copySign(Math.abs(base) ** exp, base);
4385 }
4386
4387 /**
4388 * Perform a divide, but return zero if the denominator is zero
4389 * @param {number} n The numerator
4390 * @param {number} d The denominator
4391 */
4392 function zdiv(n, d) {
4393 return d === 0 ? 0 : n / d;
4394 }
4395
4396 /**
4397 * Perform a bisect on a sorted list and locate the insertion point for
4398 * a value in arr to maintain sorted order.
4399 * @param {number[]} arr - array of sorted numbers
4400 * @param {number} value - value to find insertion point for
4401 * @param {number} lo - used to specify a the low end of a subset of the list
4402 * @param {number} hi - used to specify a the high end of a subset of the list
4403 */
4404 function bisectLeft(arr, value, lo = 0, hi = arr.length) {
4405 while (lo < hi) {
4406 const mid = lo + hi >> 1;
4407 if (arr[mid] < value) {
4408 lo = mid + 1;
4409 } else {
4410 hi = mid;
4411 }
4412 }
4413 return lo;
4414 }
4415
4416 /**
4417 * Determines whether an argument is an instance of a constructor, including subclasses.
4418 * This is done by first just checking `instanceof`,
4419 * and then comparing the string names of the constructors if that fails.
4420 * @param {any} arg
4421 * @param {C} constructor
4422 * @template {new (...args: any) => any} C
4423 * @returns {arg is InstanceType<C>}
4424 */
4425 function isInstance(arg, constructor) {
4426 if (arg instanceof constructor) {
4427 return true;
4428 }
4429 const targetName = constructor.name;
4430 while (arg) {
4431 var _proto$constructor;
4432 const proto = Object.getPrototypeOf(arg);
4433 const constructorName = proto === null || proto === void 0 || (_proto$constructor = proto.constructor) === null || _proto$constructor === void 0 ? void 0 : _proto$constructor.name;
4434 if (constructorName === targetName) {
4435 return true;
4436 }
4437 if (!constructorName || constructorName === "Object") {
4438 return false;
4439 }
4440 arg = proto;
4441 }
4442 return false;
4443 }
4444
4445 /**
4446 * Generate a matrix of size NxN with the given diagonal values of length N.
4447 *
4448 * @param {number[]} values
4449 * @returns {number[][]}
4450 */
4451 function diag(values) {
4452 const n = values.length;
4453 const matrix = [];
4454 for (let i = 0; i < n; i++) {
4455 matrix[i] = [];
4456 for (let j = 0; j < n; j++) {
4457 matrix[i][j] = i === j ? values[i] : 0;
4458 }
4459 }
4460 return matrix;
4461 }
4462
4463 /**
4464 * Calculate the LU decomposition of an NxN matrix.
4465 *
4466 * P is returned as PA = UL or A = P'UL which follows Matlab and Octave opposed to Scipy which returns P as
4467 * A = PUL or P'A = UL. For matrix inverse, we need P such that PA = UL and it is faster not having to invert
4468 * P, even if we can invert it fairly fast as it is just a shuffled identity matrix.
4469 *
4470 * P is returned as a permutation matrix unless pIndices is true, in which case P would be returned as
4471 * a vector containing the indexes such that A[P,:] = L*U.
4472 *
4473 * Reference:
4474 * - https://www.statlect.com/matrix-algebra/Gaussian-elimination
4475 * - https://www.sciencedirect.com/topics/mathematics/partial-pivoting
4476 *
4477 * @overload
4478 * @param {number[][]} matrix
4479 * @param {{ pIndices?: false | undefined }} [options]
4480 * @returns {[number[][], number[][], number[][]]}
4481 */
4482 /**
4483 * @overload
4484 * @param {number[][]} matrix
4485 * @param {{ pIndices?: true }} [options]
4486 * @returns {[number[], number[][], number[][]]}
4487 */
4488 /**
4489 * @param {number[][]} matrix
4490 * @param {{ pIndices?: boolean | undefined }} [options]
4491 * @returns {[number[] | number[][], number[][], number[][]]}
4492 */
4493 function lu(matrix, {
4494 pIndices = false
4495 } = {}) {
4496 let p1, p2, l, u;
4497 const n = matrix.length;
4498
4499 // Initialize the triangle matrices along with the permutation matrix.
4500 if (pIndices) {
4501 p1 = Array.from({
4502 length: n
4503 }, (_, index) => index);
4504 l = diag(new Array(n).fill(1));
4505 } else {
4506 p2 = diag(new Array(n).fill(1));
4507 l = structuredClone(p2);
4508 }
4509 u = structuredClone(matrix);
4510
4511 // Create upper and lower triangle in 'u' and 'l'. 'p' tracks the permutation (relative position of rows)
4512 for (let i = 0; i < n - 1; i++) {
4513 // Partial pivoting: identify the row with the maximal value in the column
4514 let j = i;
4515 let maximum = Math.abs(u[i][i]);
4516 for (let k = i + 1; k < n; k++) {
4517 const a = Math.abs(u[k][i]);
4518 if (a > maximum) {
4519 j = k;
4520 maximum = a;
4521 }
4522 }
4523
4524 // Partial pivoting: Swap rows
4525 if (j != i) {
4526 // Exchange current upper triangle row with row with maximal value at pivot
4527 // Update permutation matrix as well
4528 [u[i], u[j]] = [u[j], u[i]];
4529 if (pIndices) {
4530 [p1[i], p1[j]] = [p1[j], p1[i]];
4531 } else {
4532 [p2[i], p2[j]] = [p2[j], p2[i]];
4533 }
4534
4535 // Only swap columns up to the pivot for the lower triangle,
4536 // if on first row, there is nothing to swap
4537 if (i) {
4538 for (let k = 0; k < i; k++) {
4539 [l[i][k], l[j][k]] = [l[j][k], l[i][k]];
4540 }
4541 }
4542 }
4543
4544 // Zero at pivot point, nothing to do
4545 else if (!maximum) {
4546 continue;
4547 }
4548
4549 // We have a pivot point, let's zero out everything above and below
4550 // the 'l' and 'u' diagonal respectively
4551 for (let j = i + 1; j < n; j++) {
4552 const scalar = u[j][i] / u[i][i];
4553 for (let k = i; k < n; k++) {
4554 u[j][k] += -u[i][k] * scalar;
4555 l[j][k] += l[i][k] * scalar;
4556 }
4557 }
4558 }
4559 if (pIndices) {
4560 return [p1, l, u];
4561 }
4562 return [p2, l, u];
4563 }
4564
4565 /**
4566 * Forward substitution for solution of ax = b where a and b are matricies.
4567 *
4568 * @param {number[][]} a
4569 * @param {number[][]} b
4570 * @param {number} n
4571 * @returns {number[][]}
4572 */
4573 function forwardSubMatrix(a, b, n) {
4574 for (let i = 0; i < n; i++) {
4575 const v = b[i];
4576 for (let j = 0; j < i; j++) {
4577 for (let k = 0; k < n; k++) {
4578 v[k] -= a[i][j] * b[j][k];
4579 }
4580 }
4581 for (let j = 0; j < n; j++) {
4582 v[j] /= a[i][i];
4583 }
4584 }
4585 return b;
4586 }
4587
4588 /**
4589 * Back substitution for solution of ax = b where a and b are matricies.
4590 *
4591 * @param {number[][]} a
4592 * @param {number[][]} b
4593 * @param {number} n
4594 * @returns {number[][]}
4595 */
4596 function backSubMatrix(a, b, n) {
4597 for (let i = n - 1; i > -1; i--) {
4598 const v = b[i];
4599 for (let j = i + 1; j < n; j++) {
4600 for (var k = 0; k < n; k++) {
4601 v[k] -= a[i][j] * b[j][k];
4602 }
4603 }
4604 for (let j = 0; j < n; j++) {
4605 b[i][j] /= a[i][i];
4606 }
4607 }
4608 return b;
4609 }
4610
4611 /**
4612 * Forward substitution for solution of ax = b where a is a matrix and b is a vector.
4613 *
4614 * @param {number[][]} a
4615 * @param {number[]} b
4616 * @param {number} n
4617 * @returns {number[]}
4618 */
4619 function forwardSubVector(a, b, n) {
4620 for (let i = 0; i < n; i++) {
4621 let v = b[i];
4622 for (let j = 0; j < i; j++) {
4623 v -= a[i][j] * b[j];
4624 }
4625 b[i] = v / a[i][i];
4626 }
4627 return b;
4628 }
4629
4630 /**
4631 * Back substitution for solution of ax = b where a is a matrix and b is a vector.
4632 *
4633 * @param {number[][]} a
4634 * @param {number[]} b
4635 * @param {number} n
4636 * @returns {number[]}
4637 */
4638 function backSubVector(a, b, n) {
4639 for (let i = n - 1; i > -1; i--) {
4640 let v = b[i];
4641 for (let j = i + 1; j < n; j++) {
4642 v -= a[i][j] * b[j];
4643 }
4644 b[i] = v / a[i][i];
4645 }
4646 return b;
4647 }
4648
4649 /**
4650 * Invert a NxN matrix.
4651 *
4652 * @param {number[][]} matrix
4653 * @returns {number[][]}
4654 */
4655 function inv(matrix) {
4656 // Calculate the LU decomposition.
4657 const [p, l, u] = lu(matrix);
4658 const n = l.length;
4659
4660 // Floating point math can produce very small, non-zero determinants for singular matrices.
4661 // This seems to happen in Numpy as well.
4662 // Don't bother calculating sign as we only care about how close to zero we are.
4663 if (l.map((row, i) => row[i] * u[i][i]).reduce((acc, val) => acc * val, 1) === 0.0) {
4664 throw new Error("Matrix is singular");
4665 }
4666
4667 // Solve for the identity matrix (will give us inverse)
4668 // Permutation matrix is the identity matrix, even if shuffled.
4669 return backSubMatrix(u, forwardSubMatrix(l, p, n), n);
4670 }
4671
4672 /**
4673 * Solve a NxN matrix representing a system of equations.
4674 *
4675 * @param {number[][]} matrix
4676 * @param {number[]} vector
4677 * @returns {number[]}
4678 */
4679 function solve(matrix, vector) {
4680 // Calculate the LU decomposition.
4681 const [p, l, u] = lu(matrix, {
4682 pIndices: true
4683 });
4684 const n = l.length;
4685
4686 // If determinant is zero, we can't solve.
4687 if (l.map((row, i) => row[i] * u[i][i]).reduce((acc, val) => acc * val, 1) === 0.0) {
4688 throw new Error("Matrix is singular");
4689 }
4690 return backSubVector(u, forwardSubVector(l, p.map(i => vector[i]), n), n);
4691 }
4692
4693 var util = /*#__PURE__*/Object.freeze({
4694 __proto__: null,
4695 bisectLeft: bisectLeft,
4696 clamp: clamp,
4697 copySign: copySign,
4698 diag: diag,
4699 interpolate: interpolate,
4700 interpolateInv: interpolateInv,
4701 inv: inv,
4702 isInstance: isInstance,
4703 isNone: isNone,
4704 isString: isString,
4705 lu: lu,
4706 mapRange: mapRange,
4707 multiplyMatrices: multiplyMatrices,
4708 multiply_v3_m3x3: multiply_v3_m3x3,
4709 serializeNumber: serializeNumber,
4710 skipNone: skipNone,
4711 solve: solve,
4712 spow: spow,
4713 toPrecision: toPrecision,
4714 type: type,
4715 zdiv: zdiv
4716 });
4717
4718 var esnext_iterator_forEach = {};
4719
4720 var es_iterator_forEach = {};
4721
4722 var hasRequiredEs_iterator_forEach;
4723
4724 function requireEs_iterator_forEach () {
4725 if (hasRequiredEs_iterator_forEach) return es_iterator_forEach;
4726 hasRequiredEs_iterator_forEach = 1;
4727 var $ = require_export();
4728 var iterate = requireIterate();
4729 var aCallable = requireACallable();
4730 var anObject = requireAnObject();
4731 var getIteratorDirect = requireGetIteratorDirect();
4732
4733 // `Iterator.prototype.forEach` method
4734 // https://tc39.es/ecma262/#sec-iterator.prototype.foreach
4735 $({ target: 'Iterator', proto: true, real: true }, {
4736 forEach: function forEach(fn) {
4737 anObject(this);
4738 aCallable(fn);
4739 var record = getIteratorDirect(this);
4740 var counter = 0;
4741 iterate(record, function (value) {
4742 fn(value, counter++);
4743 }, { IS_RECORD: true });
4744 }
4745 });
4746 return es_iterator_forEach;
4747 }
4748
4749 var hasRequiredEsnext_iterator_forEach;
4750
4751 function requireEsnext_iterator_forEach () {
4752 if (hasRequiredEsnext_iterator_forEach) return esnext_iterator_forEach;
4753 hasRequiredEsnext_iterator_forEach = 1;
4754 // TODO: Remove from `core-js@4`
4755 requireEs_iterator_forEach();
4756 return esnext_iterator_forEach;
4757 }
4758
4759 requireEsnext_iterator_forEach();
4760
4761 /**
4762 * A class for adding deep extensibility to any piece of JS code
4763 */
4764 class Hooks {
4765 add(name, callback, first) {
4766 if (typeof arguments[0] != "string") {
4767 // Multiple hooks
4768 for (var name in arguments[0]) {
4769 this.add(name, arguments[0][name], arguments[1]);
4770 }
4771 return;
4772 }
4773 (Array.isArray(name) ? name : [name]).forEach(function (name) {
4774 this[name] = this[name] || [];
4775 if (callback) {
4776 this[name][first ? "unshift" : "push"](callback);
4777 }
4778 }, this);
4779 }
4780 run(name, env) {
4781 this[name] = this[name] || [];
4782 this[name].forEach(function (callback) {
4783 callback.call(env && env.context ? env.context : env, env);
4784 });
4785 }
4786 }
4787
4788 /**
4789 * The instance of {@link Hooks} used throughout Color.js
4790 */
4791 const hooks = new Hooks();
4792
4793 var _globalThis$process;
4794 // Global defaults one may want to configure
4795 var defaults = {
4796 gamut_mapping: "css",
4797 precision: 5,
4798 deltaE: "76",
4799 // Default deltaE method
4800 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",
4801 warn: function warn(msg) {
4802 if (this.verbose) {
4803 var _globalThis$console, _globalThis$console$w;
4804 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);
4805 }
4806 }
4807 };
4808
4809 var es_array_push = {};
4810
4811 var isArray;
4812 var hasRequiredIsArray;
4813
4814 function requireIsArray () {
4815 if (hasRequiredIsArray) return isArray;
4816 hasRequiredIsArray = 1;
4817 var classof = requireClassofRaw();
4818
4819 // `IsArray` abstract operation
4820 // https://tc39.es/ecma262/#sec-isarray
4821 // eslint-disable-next-line es/no-array-isarray -- safe
4822 isArray = Array.isArray || function isArray(argument) {
4823 return classof(argument) === 'Array';
4824 };
4825 return isArray;
4826 }
4827
4828 var arraySetLength;
4829 var hasRequiredArraySetLength;
4830
4831 function requireArraySetLength () {
4832 if (hasRequiredArraySetLength) return arraySetLength;
4833 hasRequiredArraySetLength = 1;
4834 var DESCRIPTORS = requireDescriptors();
4835 var isArray = requireIsArray();
4836
4837 var $TypeError = TypeError;
4838 // eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
4839 var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
4840
4841 // Safari < 13 does not throw an error in this case
4842 var SILENT_ON_NON_WRITABLE_LENGTH_SET = DESCRIPTORS && !function () {
4843 // makes no sense without proper strict mode support
4844 if (this !== undefined) return true;
4845 try {
4846 // eslint-disable-next-line es/no-object-defineproperty -- safe
4847 Object.defineProperty([], 'length', { writable: false }).length = 1;
4848 } catch (error) {
4849 return error instanceof TypeError;
4850 }
4851 }();
4852
4853 arraySetLength = SILENT_ON_NON_WRITABLE_LENGTH_SET ? function (O, length) {
4854 if (isArray(O) && !getOwnPropertyDescriptor(O, 'length').writable) {
4855 throw new $TypeError('Cannot set read only .length');
4856 } return O.length = length;
4857 } : function (O, length) {
4858 return O.length = length;
4859 };
4860 return arraySetLength;
4861 }
4862
4863 var doesNotExceedSafeInteger;
4864 var hasRequiredDoesNotExceedSafeInteger;
4865
4866 function requireDoesNotExceedSafeInteger () {
4867 if (hasRequiredDoesNotExceedSafeInteger) return doesNotExceedSafeInteger;
4868 hasRequiredDoesNotExceedSafeInteger = 1;
4869 var $TypeError = TypeError;
4870 var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; // 2 ** 53 - 1 == 9007199254740991
4871
4872 doesNotExceedSafeInteger = function (it) {
4873 if (it > MAX_SAFE_INTEGER) throw $TypeError('Maximum allowed index exceeded');
4874 return it;
4875 };
4876 return doesNotExceedSafeInteger;
4877 }
4878
4879 var hasRequiredEs_array_push;
4880
4881 function requireEs_array_push () {
4882 if (hasRequiredEs_array_push) return es_array_push;
4883 hasRequiredEs_array_push = 1;
4884 var $ = require_export();
4885 var toObject = requireToObject();
4886 var lengthOfArrayLike = requireLengthOfArrayLike();
4887 var setArrayLength = requireArraySetLength();
4888 var doesNotExceedSafeInteger = requireDoesNotExceedSafeInteger();
4889 var fails = requireFails();
4890
4891 var INCORRECT_TO_LENGTH = fails(function () {
4892 return [].push.call({ length: 0x100000000 }, 1) !== 4294967297;
4893 });
4894
4895 // V8 <= 121 and Safari <= 15.4; FF < 23 throws InternalError
4896 // https://bugs.chromium.org/p/v8/issues/detail?id=12681
4897 var properErrorOnNonWritableLength = function () {
4898 try {
4899 // eslint-disable-next-line es/no-object-defineproperty -- safe
4900 Object.defineProperty([], 'length', { writable: false }).push();
4901 } catch (error) {
4902 return error instanceof TypeError;
4903 }
4904 };
4905
4906 var FORCED = INCORRECT_TO_LENGTH || !properErrorOnNonWritableLength();
4907
4908 // `Array.prototype.push` method
4909 // https://tc39.es/ecma262/#sec-array.prototype.push
4910 $({ target: 'Array', proto: true, arity: 1, forced: FORCED }, {
4911 // eslint-disable-next-line no-unused-vars -- required for `.length`
4912 push: function push(item) {
4913 var O = toObject(this);
4914 var len = lengthOfArrayLike(O);
4915 var argCount = arguments.length;
4916 doesNotExceedSafeInteger(len + argCount);
4917 for (var i = 0; i < argCount; i++) {
4918 O[len] = arguments[i];
4919 len++;
4920 }
4921 setArrayLength(O, len);
4922 return len;
4923 }
4924 });
4925 return es_array_push;
4926 }
4927
4928 requireEs_array_push();
4929
4930 var esnext_iterator_every = {};
4931
4932 var es_iterator_every = {};
4933
4934 var hasRequiredEs_iterator_every;
4935
4936 function requireEs_iterator_every () {
4937 if (hasRequiredEs_iterator_every) return es_iterator_every;
4938 hasRequiredEs_iterator_every = 1;
4939 var $ = require_export();
4940 var iterate = requireIterate();
4941 var aCallable = requireACallable();
4942 var anObject = requireAnObject();
4943 var getIteratorDirect = requireGetIteratorDirect();
4944
4945 // `Iterator.prototype.every` method
4946 // https://tc39.es/ecma262/#sec-iterator.prototype.every
4947 $({ target: 'Iterator', proto: true, real: true }, {
4948 every: function every(predicate) {
4949 anObject(this);
4950 aCallable(predicate);
4951 var record = getIteratorDirect(this);
4952 var counter = 0;
4953 return !iterate(record, function (value, stop) {
4954 if (!predicate(value, counter++)) return stop();
4955 }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
4956 }
4957 });
4958 return es_iterator_every;
4959 }
4960
4961 var hasRequiredEsnext_iterator_every;
4962
4963 function requireEsnext_iterator_every () {
4964 if (hasRequiredEsnext_iterator_every) return esnext_iterator_every;
4965 hasRequiredEsnext_iterator_every = 1;
4966 // TODO: Remove from `core-js@4`
4967 requireEs_iterator_every();
4968 return esnext_iterator_every;
4969 }
4970
4971 requireEsnext_iterator_every();
4972
4973 var esnext_iterator_some = {};
4974
4975 var es_iterator_some = {};
4976
4977 var hasRequiredEs_iterator_some;
4978
4979 function requireEs_iterator_some () {
4980 if (hasRequiredEs_iterator_some) return es_iterator_some;
4981 hasRequiredEs_iterator_some = 1;
4982 var $ = require_export();
4983 var iterate = requireIterate();
4984 var aCallable = requireACallable();
4985 var anObject = requireAnObject();
4986 var getIteratorDirect = requireGetIteratorDirect();
4987
4988 // `Iterator.prototype.some` method
4989 // https://tc39.es/ecma262/#sec-iterator.prototype.some
4990 $({ target: 'Iterator', proto: true, real: true }, {
4991 some: function some(predicate) {
4992 anObject(this);
4993 aCallable(predicate);
4994 var record = getIteratorDirect(this);
4995 var counter = 0;
4996 return iterate(record, function (value, stop) {
4997 if (predicate(value, counter++)) return stop();
4998 }, { IS_RECORD: true, INTERRUPTED: true }).stopped;
4999 }
5000 });
5001 return es_iterator_some;
5002 }
5003
5004 var hasRequiredEsnext_iterator_some;
5005
5006 function requireEsnext_iterator_some () {
5007 if (hasRequiredEsnext_iterator_some) return esnext_iterator_some;
5008 hasRequiredEsnext_iterator_some = 1;
5009 // TODO: Remove from `core-js@4`
5010 requireEs_iterator_some();
5011 return esnext_iterator_some;
5012 }
5013
5014 requireEsnext_iterator_some();
5015
5016 var esnext_set_difference_v2 = {};
5017
5018 var es_set_difference_v2 = {};
5019
5020 var aSet;
5021 var hasRequiredASet;
5022
5023 function requireASet () {
5024 if (hasRequiredASet) return aSet;
5025 hasRequiredASet = 1;
5026 var has = requireSetHelpers().has;
5027
5028 // Perform ? RequireInternalSlot(M, [[SetData]])
5029 aSet = function (it) {
5030 has(it);
5031 return it;
5032 };
5033 return aSet;
5034 }
5035
5036 var setClone;
5037 var hasRequiredSetClone;
5038
5039 function requireSetClone () {
5040 if (hasRequiredSetClone) return setClone;
5041 hasRequiredSetClone = 1;
5042 var SetHelpers = requireSetHelpers();
5043 var iterate = requireSetIterate();
5044
5045 var Set = SetHelpers.Set;
5046 var add = SetHelpers.add;
5047
5048 setClone = function (set) {
5049 var result = new Set();
5050 iterate(set, function (it) {
5051 add(result, it);
5052 });
5053 return result;
5054 };
5055 return setClone;
5056 }
5057
5058 var setSize;
5059 var hasRequiredSetSize;
5060
5061 function requireSetSize () {
5062 if (hasRequiredSetSize) return setSize;
5063 hasRequiredSetSize = 1;
5064 var uncurryThisAccessor = requireFunctionUncurryThisAccessor();
5065 var SetHelpers = requireSetHelpers();
5066
5067 setSize = uncurryThisAccessor(SetHelpers.proto, 'size', 'get') || function (set) {
5068 return set.size;
5069 };
5070 return setSize;
5071 }
5072
5073 var getSetRecord;
5074 var hasRequiredGetSetRecord;
5075
5076 function requireGetSetRecord () {
5077 if (hasRequiredGetSetRecord) return getSetRecord;
5078 hasRequiredGetSetRecord = 1;
5079 var aCallable = requireACallable();
5080 var anObject = requireAnObject();
5081 var call = requireFunctionCall();
5082 var toIntegerOrInfinity = requireToIntegerOrInfinity();
5083 var getIteratorDirect = requireGetIteratorDirect();
5084
5085 var INVALID_SIZE = 'Invalid size';
5086 var $RangeError = RangeError;
5087 var $TypeError = TypeError;
5088 var max = Math.max;
5089
5090 var SetRecord = function (set, intSize) {
5091 this.set = set;
5092 this.size = max(intSize, 0);
5093 this.has = aCallable(set.has);
5094 this.keys = aCallable(set.keys);
5095 };
5096
5097 SetRecord.prototype = {
5098 getIterator: function () {
5099 return getIteratorDirect(anObject(call(this.keys, this.set)));
5100 },
5101 includes: function (it) {
5102 return call(this.has, this.set, it);
5103 }
5104 };
5105
5106 // `GetSetRecord` abstract operation
5107 // https://tc39.es/proposal-set-methods/#sec-getsetrecord
5108 getSetRecord = function (obj) {
5109 anObject(obj);
5110 var numSize = +obj.size;
5111 // NOTE: If size is undefined, then numSize will be NaN
5112 // eslint-disable-next-line no-self-compare -- NaN check
5113 if (numSize !== numSize) throw new $TypeError(INVALID_SIZE);
5114 var intSize = toIntegerOrInfinity(numSize);
5115 if (intSize < 0) throw new $RangeError(INVALID_SIZE);
5116 return new SetRecord(obj, intSize);
5117 };
5118 return getSetRecord;
5119 }
5120
5121 var setDifference;
5122 var hasRequiredSetDifference;
5123
5124 function requireSetDifference () {
5125 if (hasRequiredSetDifference) return setDifference;
5126 hasRequiredSetDifference = 1;
5127 var aSet = requireASet();
5128 var SetHelpers = requireSetHelpers();
5129 var clone = requireSetClone();
5130 var size = requireSetSize();
5131 var getSetRecord = requireGetSetRecord();
5132 var iterateSet = requireSetIterate();
5133 var iterateSimple = requireIterateSimple();
5134
5135 var has = SetHelpers.has;
5136 var remove = SetHelpers.remove;
5137
5138 // `Set.prototype.difference` method
5139 // https://github.com/tc39/proposal-set-methods
5140 setDifference = function difference(other) {
5141 var O = aSet(this);
5142 var otherRec = getSetRecord(other);
5143 var result = clone(O);
5144 if (size(O) <= otherRec.size) iterateSet(O, function (e) {
5145 if (otherRec.includes(e)) remove(result, e);
5146 });
5147 else iterateSimple(otherRec.getIterator(), function (e) {
5148 if (has(O, e)) remove(result, e);
5149 });
5150 return result;
5151 };
5152 return setDifference;
5153 }
5154
5155 var setMethodAcceptSetLike;
5156 var hasRequiredSetMethodAcceptSetLike;
5157
5158 function requireSetMethodAcceptSetLike () {
5159 if (hasRequiredSetMethodAcceptSetLike) return setMethodAcceptSetLike;
5160 hasRequiredSetMethodAcceptSetLike = 1;
5161 var getBuiltIn = requireGetBuiltIn();
5162
5163 var createSetLike = function (size) {
5164 return {
5165 size: size,
5166 has: function () {
5167 return false;
5168 },
5169 keys: function () {
5170 return {
5171 next: function () {
5172 return { done: true };
5173 }
5174 };
5175 }
5176 };
5177 };
5178
5179 setMethodAcceptSetLike = function (name) {
5180 var Set = getBuiltIn('Set');
5181 try {
5182 new Set()[name](createSetLike(0));
5183 try {
5184 // late spec change, early WebKit ~ Safari 17.0 beta implementation does not pass it
5185 // https://github.com/tc39/proposal-set-methods/pull/88
5186 new Set()[name](createSetLike(-1));
5187 return false;
5188 } catch (error2) {
5189 return true;
5190 }
5191 } catch (error) {
5192 return false;
5193 }
5194 };
5195 return setMethodAcceptSetLike;
5196 }
5197
5198 var hasRequiredEs_set_difference_v2;
5199
5200 function requireEs_set_difference_v2 () {
5201 if (hasRequiredEs_set_difference_v2) return es_set_difference_v2;
5202 hasRequiredEs_set_difference_v2 = 1;
5203 var $ = require_export();
5204 var difference = requireSetDifference();
5205 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
5206
5207 // `Set.prototype.difference` method
5208 // https://tc39.es/ecma262/#sec-set.prototype.difference
5209 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('difference') }, {
5210 difference: difference
5211 });
5212 return es_set_difference_v2;
5213 }
5214
5215 var hasRequiredEsnext_set_difference_v2;
5216
5217 function requireEsnext_set_difference_v2 () {
5218 if (hasRequiredEsnext_set_difference_v2) return esnext_set_difference_v2;
5219 hasRequiredEsnext_set_difference_v2 = 1;
5220 // TODO: Remove from `core-js@4`
5221 requireEs_set_difference_v2();
5222 return esnext_set_difference_v2;
5223 }
5224
5225 requireEsnext_set_difference_v2();
5226
5227 var esnext_set_intersection_v2 = {};
5228
5229 var es_set_intersection_v2 = {};
5230
5231 var setIntersection;
5232 var hasRequiredSetIntersection;
5233
5234 function requireSetIntersection () {
5235 if (hasRequiredSetIntersection) return setIntersection;
5236 hasRequiredSetIntersection = 1;
5237 var aSet = requireASet();
5238 var SetHelpers = requireSetHelpers();
5239 var size = requireSetSize();
5240 var getSetRecord = requireGetSetRecord();
5241 var iterateSet = requireSetIterate();
5242 var iterateSimple = requireIterateSimple();
5243
5244 var Set = SetHelpers.Set;
5245 var add = SetHelpers.add;
5246 var has = SetHelpers.has;
5247
5248 // `Set.prototype.intersection` method
5249 // https://github.com/tc39/proposal-set-methods
5250 setIntersection = function intersection(other) {
5251 var O = aSet(this);
5252 var otherRec = getSetRecord(other);
5253 var result = new Set();
5254
5255 if (size(O) > otherRec.size) {
5256 iterateSimple(otherRec.getIterator(), function (e) {
5257 if (has(O, e)) add(result, e);
5258 });
5259 } else {
5260 iterateSet(O, function (e) {
5261 if (otherRec.includes(e)) add(result, e);
5262 });
5263 }
5264
5265 return result;
5266 };
5267 return setIntersection;
5268 }
5269
5270 var hasRequiredEs_set_intersection_v2;
5271
5272 function requireEs_set_intersection_v2 () {
5273 if (hasRequiredEs_set_intersection_v2) return es_set_intersection_v2;
5274 hasRequiredEs_set_intersection_v2 = 1;
5275 var $ = require_export();
5276 var fails = requireFails();
5277 var intersection = requireSetIntersection();
5278 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
5279
5280 var INCORRECT = !setMethodAcceptSetLike('intersection') || fails(function () {
5281 // eslint-disable-next-line es/no-array-from, es/no-set -- testing
5282 return String(Array.from(new Set([1, 2, 3]).intersection(new Set([3, 2])))) !== '3,2';
5283 });
5284
5285 // `Set.prototype.intersection` method
5286 // https://tc39.es/ecma262/#sec-set.prototype.intersection
5287 $({ target: 'Set', proto: true, real: true, forced: INCORRECT }, {
5288 intersection: intersection
5289 });
5290 return es_set_intersection_v2;
5291 }
5292
5293 var hasRequiredEsnext_set_intersection_v2;
5294
5295 function requireEsnext_set_intersection_v2 () {
5296 if (hasRequiredEsnext_set_intersection_v2) return esnext_set_intersection_v2;
5297 hasRequiredEsnext_set_intersection_v2 = 1;
5298 // TODO: Remove from `core-js@4`
5299 requireEs_set_intersection_v2();
5300 return esnext_set_intersection_v2;
5301 }
5302
5303 requireEsnext_set_intersection_v2();
5304
5305 var esnext_set_isDisjointFrom_v2 = {};
5306
5307 var es_set_isDisjointFrom_v2 = {};
5308
5309 var setIsDisjointFrom;
5310 var hasRequiredSetIsDisjointFrom;
5311
5312 function requireSetIsDisjointFrom () {
5313 if (hasRequiredSetIsDisjointFrom) return setIsDisjointFrom;
5314 hasRequiredSetIsDisjointFrom = 1;
5315 var aSet = requireASet();
5316 var has = requireSetHelpers().has;
5317 var size = requireSetSize();
5318 var getSetRecord = requireGetSetRecord();
5319 var iterateSet = requireSetIterate();
5320 var iterateSimple = requireIterateSimple();
5321 var iteratorClose = requireIteratorClose();
5322
5323 // `Set.prototype.isDisjointFrom` method
5324 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isDisjointFrom
5325 setIsDisjointFrom = function isDisjointFrom(other) {
5326 var O = aSet(this);
5327 var otherRec = getSetRecord(other);
5328 if (size(O) <= otherRec.size) return iterateSet(O, function (e) {
5329 if (otherRec.includes(e)) return false;
5330 }, true) !== false;
5331 var iterator = otherRec.getIterator();
5332 return iterateSimple(iterator, function (e) {
5333 if (has(O, e)) return iteratorClose(iterator, 'normal', false);
5334 }) !== false;
5335 };
5336 return setIsDisjointFrom;
5337 }
5338
5339 var hasRequiredEs_set_isDisjointFrom_v2;
5340
5341 function requireEs_set_isDisjointFrom_v2 () {
5342 if (hasRequiredEs_set_isDisjointFrom_v2) return es_set_isDisjointFrom_v2;
5343 hasRequiredEs_set_isDisjointFrom_v2 = 1;
5344 var $ = require_export();
5345 var isDisjointFrom = requireSetIsDisjointFrom();
5346 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
5347
5348 // `Set.prototype.isDisjointFrom` method
5349 // https://tc39.es/ecma262/#sec-set.prototype.isdisjointfrom
5350 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isDisjointFrom') }, {
5351 isDisjointFrom: isDisjointFrom
5352 });
5353 return es_set_isDisjointFrom_v2;
5354 }
5355
5356 var hasRequiredEsnext_set_isDisjointFrom_v2;
5357
5358 function requireEsnext_set_isDisjointFrom_v2 () {
5359 if (hasRequiredEsnext_set_isDisjointFrom_v2) return esnext_set_isDisjointFrom_v2;
5360 hasRequiredEsnext_set_isDisjointFrom_v2 = 1;
5361 // TODO: Remove from `core-js@4`
5362 requireEs_set_isDisjointFrom_v2();
5363 return esnext_set_isDisjointFrom_v2;
5364 }
5365
5366 requireEsnext_set_isDisjointFrom_v2();
5367
5368 var esnext_set_isSubsetOf_v2 = {};
5369
5370 var es_set_isSubsetOf_v2 = {};
5371
5372 var setIsSubsetOf;
5373 var hasRequiredSetIsSubsetOf;
5374
5375 function requireSetIsSubsetOf () {
5376 if (hasRequiredSetIsSubsetOf) return setIsSubsetOf;
5377 hasRequiredSetIsSubsetOf = 1;
5378 var aSet = requireASet();
5379 var size = requireSetSize();
5380 var iterate = requireSetIterate();
5381 var getSetRecord = requireGetSetRecord();
5382
5383 // `Set.prototype.isSubsetOf` method
5384 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSubsetOf
5385 setIsSubsetOf = function isSubsetOf(other) {
5386 var O = aSet(this);
5387 var otherRec = getSetRecord(other);
5388 if (size(O) > otherRec.size) return false;
5389 return iterate(O, function (e) {
5390 if (!otherRec.includes(e)) return false;
5391 }, true) !== false;
5392 };
5393 return setIsSubsetOf;
5394 }
5395
5396 var hasRequiredEs_set_isSubsetOf_v2;
5397
5398 function requireEs_set_isSubsetOf_v2 () {
5399 if (hasRequiredEs_set_isSubsetOf_v2) return es_set_isSubsetOf_v2;
5400 hasRequiredEs_set_isSubsetOf_v2 = 1;
5401 var $ = require_export();
5402 var isSubsetOf = requireSetIsSubsetOf();
5403 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
5404
5405 // `Set.prototype.isSubsetOf` method
5406 // https://tc39.es/ecma262/#sec-set.prototype.issubsetof
5407 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isSubsetOf') }, {
5408 isSubsetOf: isSubsetOf
5409 });
5410 return es_set_isSubsetOf_v2;
5411 }
5412
5413 var hasRequiredEsnext_set_isSubsetOf_v2;
5414
5415 function requireEsnext_set_isSubsetOf_v2 () {
5416 if (hasRequiredEsnext_set_isSubsetOf_v2) return esnext_set_isSubsetOf_v2;
5417 hasRequiredEsnext_set_isSubsetOf_v2 = 1;
5418 // TODO: Remove from `core-js@4`
5419 requireEs_set_isSubsetOf_v2();
5420 return esnext_set_isSubsetOf_v2;
5421 }
5422
5423 requireEsnext_set_isSubsetOf_v2();
5424
5425 var esnext_set_isSupersetOf_v2 = {};
5426
5427 var es_set_isSupersetOf_v2 = {};
5428
5429 var setIsSupersetOf;
5430 var hasRequiredSetIsSupersetOf;
5431
5432 function requireSetIsSupersetOf () {
5433 if (hasRequiredSetIsSupersetOf) return setIsSupersetOf;
5434 hasRequiredSetIsSupersetOf = 1;
5435 var aSet = requireASet();
5436 var has = requireSetHelpers().has;
5437 var size = requireSetSize();
5438 var getSetRecord = requireGetSetRecord();
5439 var iterateSimple = requireIterateSimple();
5440 var iteratorClose = requireIteratorClose();
5441
5442 // `Set.prototype.isSupersetOf` method
5443 // https://tc39.github.io/proposal-set-methods/#Set.prototype.isSupersetOf
5444 setIsSupersetOf = function isSupersetOf(other) {
5445 var O = aSet(this);
5446 var otherRec = getSetRecord(other);
5447 if (size(O) < otherRec.size) return false;
5448 var iterator = otherRec.getIterator();
5449 return iterateSimple(iterator, function (e) {
5450 if (!has(O, e)) return iteratorClose(iterator, 'normal', false);
5451 }) !== false;
5452 };
5453 return setIsSupersetOf;
5454 }
5455
5456 var hasRequiredEs_set_isSupersetOf_v2;
5457
5458 function requireEs_set_isSupersetOf_v2 () {
5459 if (hasRequiredEs_set_isSupersetOf_v2) return es_set_isSupersetOf_v2;
5460 hasRequiredEs_set_isSupersetOf_v2 = 1;
5461 var $ = require_export();
5462 var isSupersetOf = requireSetIsSupersetOf();
5463 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
5464
5465 // `Set.prototype.isSupersetOf` method
5466 // https://tc39.es/ecma262/#sec-set.prototype.issupersetof
5467 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('isSupersetOf') }, {
5468 isSupersetOf: isSupersetOf
5469 });
5470 return es_set_isSupersetOf_v2;
5471 }
5472
5473 var hasRequiredEsnext_set_isSupersetOf_v2;
5474
5475 function requireEsnext_set_isSupersetOf_v2 () {
5476 if (hasRequiredEsnext_set_isSupersetOf_v2) return esnext_set_isSupersetOf_v2;
5477 hasRequiredEsnext_set_isSupersetOf_v2 = 1;
5478 // TODO: Remove from `core-js@4`
5479 requireEs_set_isSupersetOf_v2();
5480 return esnext_set_isSupersetOf_v2;
5481 }
5482
5483 requireEsnext_set_isSupersetOf_v2();
5484
5485 var esnext_set_symmetricDifference_v2 = {};
5486
5487 var es_set_symmetricDifference_v2 = {};
5488
5489 var setSymmetricDifference;
5490 var hasRequiredSetSymmetricDifference;
5491
5492 function requireSetSymmetricDifference () {
5493 if (hasRequiredSetSymmetricDifference) return setSymmetricDifference;
5494 hasRequiredSetSymmetricDifference = 1;
5495 var aSet = requireASet();
5496 var SetHelpers = requireSetHelpers();
5497 var clone = requireSetClone();
5498 var getSetRecord = requireGetSetRecord();
5499 var iterateSimple = requireIterateSimple();
5500
5501 var add = SetHelpers.add;
5502 var has = SetHelpers.has;
5503 var remove = SetHelpers.remove;
5504
5505 // `Set.prototype.symmetricDifference` method
5506 // https://github.com/tc39/proposal-set-methods
5507 setSymmetricDifference = function symmetricDifference(other) {
5508 var O = aSet(this);
5509 var keysIter = getSetRecord(other).getIterator();
5510 var result = clone(O);
5511 iterateSimple(keysIter, function (e) {
5512 if (has(O, e)) remove(result, e);
5513 else add(result, e);
5514 });
5515 return result;
5516 };
5517 return setSymmetricDifference;
5518 }
5519
5520 var hasRequiredEs_set_symmetricDifference_v2;
5521
5522 function requireEs_set_symmetricDifference_v2 () {
5523 if (hasRequiredEs_set_symmetricDifference_v2) return es_set_symmetricDifference_v2;
5524 hasRequiredEs_set_symmetricDifference_v2 = 1;
5525 var $ = require_export();
5526 var symmetricDifference = requireSetSymmetricDifference();
5527 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
5528
5529 // `Set.prototype.symmetricDifference` method
5530 // https://tc39.es/ecma262/#sec-set.prototype.symmetricdifference
5531 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('symmetricDifference') }, {
5532 symmetricDifference: symmetricDifference
5533 });
5534 return es_set_symmetricDifference_v2;
5535 }
5536
5537 var hasRequiredEsnext_set_symmetricDifference_v2;
5538
5539 function requireEsnext_set_symmetricDifference_v2 () {
5540 if (hasRequiredEsnext_set_symmetricDifference_v2) return esnext_set_symmetricDifference_v2;
5541 hasRequiredEsnext_set_symmetricDifference_v2 = 1;
5542 // TODO: Remove from `core-js@4`
5543 requireEs_set_symmetricDifference_v2();
5544 return esnext_set_symmetricDifference_v2;
5545 }
5546
5547 requireEsnext_set_symmetricDifference_v2();
5548
5549 var esnext_set_union_v2 = {};
5550
5551 var es_set_union_v2 = {};
5552
5553 var setUnion;
5554 var hasRequiredSetUnion;
5555
5556 function requireSetUnion () {
5557 if (hasRequiredSetUnion) return setUnion;
5558 hasRequiredSetUnion = 1;
5559 var aSet = requireASet();
5560 var add = requireSetHelpers().add;
5561 var clone = requireSetClone();
5562 var getSetRecord = requireGetSetRecord();
5563 var iterateSimple = requireIterateSimple();
5564
5565 // `Set.prototype.union` method
5566 // https://github.com/tc39/proposal-set-methods
5567 setUnion = function union(other) {
5568 var O = aSet(this);
5569 var keysIter = getSetRecord(other).getIterator();
5570 var result = clone(O);
5571 iterateSimple(keysIter, function (it) {
5572 add(result, it);
5573 });
5574 return result;
5575 };
5576 return setUnion;
5577 }
5578
5579 var hasRequiredEs_set_union_v2;
5580
5581 function requireEs_set_union_v2 () {
5582 if (hasRequiredEs_set_union_v2) return es_set_union_v2;
5583 hasRequiredEs_set_union_v2 = 1;
5584 var $ = require_export();
5585 var union = requireSetUnion();
5586 var setMethodAcceptSetLike = requireSetMethodAcceptSetLike();
5587
5588 // `Set.prototype.union` method
5589 // https://tc39.es/ecma262/#sec-set.prototype.union
5590 $({ target: 'Set', proto: true, real: true, forced: !setMethodAcceptSetLike('union') }, {
5591 union: union
5592 });
5593 return es_set_union_v2;
5594 }
5595
5596 var hasRequiredEsnext_set_union_v2;
5597
5598 function requireEsnext_set_union_v2 () {
5599 if (hasRequiredEsnext_set_union_v2) return esnext_set_union_v2;
5600 hasRequiredEsnext_set_union_v2 = 1;
5601 // TODO: Remove from `core-js@4`
5602 requireEs_set_union_v2();
5603 return esnext_set_union_v2;
5604 }
5605
5606 requireEsnext_set_union_v2();
5607
5608 var esnext_iterator_find = {};
5609
5610 var es_iterator_find = {};
5611
5612 var hasRequiredEs_iterator_find;
5613
5614 function requireEs_iterator_find () {
5615 if (hasRequiredEs_iterator_find) return es_iterator_find;
5616 hasRequiredEs_iterator_find = 1;
5617 var $ = require_export();
5618 var iterate = requireIterate();
5619 var aCallable = requireACallable();
5620 var anObject = requireAnObject();
5621 var getIteratorDirect = requireGetIteratorDirect();
5622
5623 // `Iterator.prototype.find` method
5624 // https://tc39.es/ecma262/#sec-iterator.prototype.find
5625 $({ target: 'Iterator', proto: true, real: true }, {
5626 find: function find(predicate) {
5627 anObject(this);
5628 aCallable(predicate);
5629 var record = getIteratorDirect(this);
5630 var counter = 0;
5631 return iterate(record, function (value, stop) {
5632 if (predicate(value, counter++)) return stop(value);
5633 }, { IS_RECORD: true, INTERRUPTED: true }).result;
5634 }
5635 });
5636 return es_iterator_find;
5637 }
5638
5639 var hasRequiredEsnext_iterator_find;
5640
5641 function requireEsnext_iterator_find () {
5642 if (hasRequiredEsnext_iterator_find) return esnext_iterator_find;
5643 hasRequiredEsnext_iterator_find = 1;
5644 // TODO: Remove from `core-js@4`
5645 requireEs_iterator_find();
5646 return esnext_iterator_find;
5647 }
5648
5649 requireEsnext_iterator_find();
5650
5651 class Type {
5652 // Class properties - declared here so that type inference works
5653 type;
5654 coordMeta;
5655 coordRange;
5656 /** @type {[number, number]} */
5657 range;
5658
5659 /**
5660 * @param {any} type
5661 * @param {import("./types.js").CoordMeta} coordMeta
5662 */
5663 constructor(type, coordMeta) {
5664 if (typeof type === "object") {
5665 this.coordMeta = type;
5666 }
5667 if (coordMeta) {
5668 var _coordMeta$range;
5669 this.coordMeta = coordMeta;
5670 this.coordRange = (_coordMeta$range = coordMeta.range) !== null && _coordMeta$range !== void 0 ? _coordMeta$range : coordMeta.refRange;
5671 }
5672 if (typeof type === "string") {
5673 let params = type.trim().match(/^(?<type><[a-z]+>)(\[(?<min>-?[.\d]+),\s*(?<max>-?[.\d]+)\])?$/);
5674 if (!params) {
5675 throw new TypeError(`Cannot parse ${type} as a type definition.`);
5676 }
5677 this.type = params.groups.type;
5678 let {
5679 min,
5680 max
5681 } = params.groups;
5682 if (min || max) {
5683 this.range = [+min, +max];
5684 }
5685 }
5686 }
5687
5688 /** @returns {[number, number]} */
5689 get computedRange() {
5690 if (this.range) {
5691 return this.range;
5692 }
5693 if (this.type === "<percentage>") {
5694 return this.percentageRange();
5695 } else if (this.type === "<angle>") {
5696 return [0, 360];
5697 }
5698 return null;
5699 }
5700 get unit() {
5701 if (this.type === "<percentage>") {
5702 return "%";
5703 } else if (this.type === "<angle>") {
5704 return "deg";
5705 }
5706 return "";
5707 }
5708
5709 /**
5710 * Map a number to the internal representation
5711 * @param {number} number
5712 */
5713 resolve(number) {
5714 if (this.type === "<angle>") {
5715 return number;
5716 }
5717 let fromRange = this.computedRange;
5718 let toRange = this.coordRange;
5719 if (this.type === "<percentage>") {
5720 var _toRange;
5721 (_toRange = toRange) !== null && _toRange !== void 0 ? _toRange : toRange = this.percentageRange();
5722 }
5723 return mapRange(fromRange, toRange, number);
5724 }
5725
5726 /**
5727 * Serialize a number from the internal representation to a string
5728 * @param {number} number
5729 * @param {number} [precision]
5730 */
5731 serialize(number, precision) {
5732 let toRange = this.type === "<percentage>" ? this.percentageRange(100) : this.computedRange;
5733 let unit = this.unit;
5734 number = mapRange(this.coordRange, toRange, number);
5735 return serializeNumber(number, {
5736 unit,
5737 precision
5738 });
5739 }
5740 toString() {
5741 let ret = this.type;
5742 if (this.range) {
5743 let [min = "", max = ""] = this.range;
5744 ret += `[${min},${max}]`;
5745 }
5746 return ret;
5747 }
5748
5749 /**
5750 * Returns a percentage range for values of this type
5751 * @param {number} scale
5752 * @returns {[number, number]}
5753 */
5754 percentageRange(scale = 1) {
5755 let range;
5756 if (this.coordMeta && this.coordMeta.range || this.coordRange && this.coordRange[0] >= 0) {
5757 range = [0, 1];
5758 } else {
5759 range = [-1, 1];
5760 }
5761 return [range[0] * scale, range[1] * scale];
5762 }
5763 static get(type, coordMeta) {
5764 if (isInstance(type, this)) {
5765 return type;
5766 }
5767 return new this(type, coordMeta);
5768 }
5769 }
5770
5771 /** @import { ColorSpace, Coords } from "./types.js" */
5772
5773 // Type re-exports
5774 /** @typedef {import("./types.js").Format} FormatInterface */
5775
5776 /**
5777 * @internal
5778 * Used to index {@link FormatInterface Format} objects and store an instance.
5779 * Not meant for external use
5780 */
5781 const instance = Symbol("instance");
5782
5783 /**
5784 * Remove the first element of an array type
5785 * @template {any[]} T
5786 * @typedef {T extends [any, ...infer R] ? R : T[number][]} RemoveFirstElement
5787 */
5788
5789 /**
5790 * @class Format
5791 * @implements {Omit<FormatInterface, "coords" | "serializeCoords">}
5792 * Class to hold a color serialization format
5793 */
5794 class Format {
5795 // Class properties - declared here so that type inference works
5796 type;
5797 name;
5798 spaceCoords;
5799 /** @type {Type[][]} */
5800 coords;
5801 /** @type {string | undefined} */
5802 id;
5803 /** @type {boolean | undefined} */
5804 alpha;
5805
5806 /**
5807 * @param {FormatInterface} format
5808 * @param {ColorSpace} space
5809 */
5810 constructor(format, space = format.space) {
5811 format[instance] = this;
5812 this.type = "function";
5813 this.name = "color";
5814 Object.assign(this, format);
5815 this.space = space;
5816 if (this.type === "custom") {
5817 // Nothing else to do here
5818 return;
5819 }
5820 this.spaceCoords = Object.values(space.coords);
5821 if (!this.coords) {
5822 // @ts-expect-error Strings are converted to the correct type later
5823 this.coords = this.spaceCoords.map(coordMeta => {
5824 let ret = ["<number>", "<percentage>"];
5825 if (coordMeta.type === "angle") {
5826 ret.push("<angle>");
5827 }
5828 return ret;
5829 });
5830 }
5831 this.coords = this.coords.map(/** @param {string | string[] | Type[]} types */(types, i) => {
5832 let coordMeta = this.spaceCoords[i];
5833 if (typeof types === "string") {
5834 types = types.trim().split(/\s*\|\s*/);
5835 }
5836 return types.map(type => Type.get(type, coordMeta));
5837 });
5838 }
5839
5840 /**
5841 * @param {Coords} coords
5842 * @param {number} precision
5843 * @param {Type[]} types
5844 */
5845 serializeCoords(coords, precision, types) {
5846 types = coords.map((_, i) => {
5847 var _types$i, _types;
5848 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]);
5849 });
5850 return coords.map((c, i) => types[i].serialize(c, precision));
5851 }
5852
5853 /**
5854 * Validates the coordinates of a color against a format's coord grammar and
5855 * maps the coordinates to the range or refRange of the coordinates.
5856 * @param {Coords} coords
5857 * @param {[string, string, string]} types
5858 */
5859 coerceCoords(coords, types) {
5860 return Object.entries(this.space.coords).map(([id, coordMeta], i) => {
5861 let arg = coords[i];
5862 if (isNone(arg) || isNaN(arg)) {
5863 // Nothing to do here
5864 return arg;
5865 }
5866
5867 // Find grammar alternative that matches the provided type
5868 // Non-strict equals is intentional because we are comparing w/ string objects
5869 let providedType = types[i];
5870 let type = this.coords[i].find(c => c.type == providedType);
5871
5872 // Check that each coord conforms to its grammar
5873 if (!type) {
5874 var _ref, _arg;
5875 // Type does not exist in the grammar, throw
5876 let coordName = coordMeta.name || id;
5877 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}()`);
5878 }
5879 arg = type.resolve(arg);
5880 if (type.range) {
5881 // Adjust type to include range
5882 types[i] = type.toString();
5883 }
5884 return arg;
5885 });
5886 }
5887
5888 /**
5889 * @returns {boolean | Required<FormatInterface>["serialize"]}
5890 */
5891 canSerialize() {
5892 return this.type === "function" || /** @type {any} */this.serialize;
5893 }
5894
5895 /**
5896 * @param {string} str
5897 * @returns {(import("./types.js").ColorConstructor) | undefined | null}
5898 */
5899 parse(str) {
5900 return null;
5901 }
5902
5903 /**
5904 * @param {Format | FormatInterface} format
5905 * @param {RemoveFirstElement<ConstructorParameters<typeof Format>>} args
5906 * @returns {Format}
5907 */
5908 static get(format, ...args) {
5909 if (!format || isInstance(format, this)) {
5910 return /** @type {Format} */format;
5911 }
5912 if (format[instance]) {
5913 return format[instance];
5914 }
5915 return new Format(format, ...args);
5916 }
5917 }
5918
5919 // Type re-exports
5920 /** @typedef {import("./types.js").White} White */
5921
5922 /** @type {Record<string, White>} */
5923 // prettier-ignore
5924 const WHITES = {
5925 // for compatibility, the four-digit chromaticity-derived ones everyone else uses
5926 D50: [0.3457 / 0.3585, 1.00000, (1.0 - 0.3457 - 0.3585) / 0.3585],
5927 D65: [0.3127 / 0.3290, 1.00000, (1.0 - 0.3127 - 0.3290) / 0.3290]
5928 };
5929
5930 /**
5931 *
5932 * @param {string | White} name
5933 * @returns {White}
5934 */
5935 function getWhite(name) {
5936 if (Array.isArray(name)) {
5937 return name;
5938 }
5939 return WHITES[name];
5940 }
5941
5942 /**
5943 * Adapt XYZ from white point W1 to W2
5944 * @param {White | string} W1
5945 * @param {White | string} W2
5946 * @param {[number, number, number]} XYZ
5947 * @param {{ method?: string | undefined }} options
5948 * @returns {[number, number, number]}
5949 */
5950 function adapt$2(W1, W2, XYZ, options = {}) {
5951 W1 = getWhite(W1);
5952 W2 = getWhite(W2);
5953 if (!W1 || !W2) {
5954 throw new TypeError(`Missing white point to convert ${!W1 ? "from" : ""}${!W1 && !W2 ? "/" : ""}${!W2 ? "to" : ""}`);
5955 }
5956 if (W1 === W2) {
5957 // Same whitepoints, no conversion needed
5958 return XYZ;
5959 }
5960 let env = {
5961 W1,
5962 W2,
5963 XYZ,
5964 options
5965 };
5966 hooks.run("chromatic-adaptation-start", env);
5967 if (!env.M) {
5968 if (env.W1 === WHITES.D65 && env.W2 === WHITES.D50) {
5969 // prettier-ignore
5970 env.M = [[1.0479297925449969, 0.022946870601609652, -0.05019226628920524], [0.02962780877005599, 0.9904344267538799, -0.017073799063418826], [-0.009243040646204504, 0.015055191490298152, 0.7518742814281371]];
5971 } else if (env.W1 === WHITES.D50 && env.W2 === WHITES.D65) {
5972 // prettier-ignore
5973 env.M = [[0.955473421488075, -0.02309845494876471, 0.06325924320057072], [-0.0283697093338637, 1.0099953980813041, 0.021041441191917323], [0.012314014864481998, -0.020507649298898964, 1.330365926242124]];
5974 }
5975 }
5976 hooks.run("chromatic-adaptation-end", env);
5977 if (env.M) {
5978 return multiply_v3_m3x3(env.XYZ, env.M);
5979 } else {
5980 throw new TypeError("Only Bradford CAT with white points D50 and D65 supported for now.");
5981 }
5982 }
5983
5984 /** @import { ColorConstructor } from "./types.js" */
5985
5986 // Type re-exports
5987 /** @typedef {import("./types.js").ArgumentMeta} ArgumentMeta */
5988 /** @typedef {import("./types.js").ParseFunctionReturn} ParseFunctionReturn */
5989 /** @typedef {import("./types.js").ParseOptions} ParseOptions */
5990
5991 /**
5992 * Convert a CSS Color string to a color object
5993 * @param {string} str
5994 * @param {ParseOptions} [options]
5995 * @returns {ColorConstructor}
5996 */
5997 function parse(str, options) {
5998 var _String, _env$options$parseMet;
5999 let env = {
6000 str: (_String = String(str)) === null || _String === void 0 ? void 0 : _String.trim(),
6001 options
6002 };
6003 hooks.run("parse-start", env);
6004 if (env.color) {
6005 return env.color;
6006 }
6007 env.parsed = parseFunction(env.str);
6008 let ret;
6009 let meta = env.options ? (_env$options$parseMet = env.options.parseMeta) !== null && _env$options$parseMet !== void 0 ? _env$options$parseMet : env.options.meta : null;
6010 if (env.parsed) {
6011 // Is a functional syntax
6012 let name = env.parsed.name;
6013 let format;
6014 let space;
6015 let coords = env.parsed.args;
6016 let types = coords.map((c, i) => {
6017 var _env$parsed$argMeta$i;
6018 return (_env$parsed$argMeta$i = env.parsed.argMeta[i]) === null || _env$parsed$argMeta$i === void 0 ? void 0 : _env$parsed$argMeta$i.type;
6019 });
6020 if (name === "color") {
6021 // color() function
6022 let id = coords.shift();
6023 types.shift();
6024 // Check against both <dashed-ident> and <ident> versions
6025 let alternateId = id.startsWith("--") ? id.substring(2) : `--${id}`;
6026 let ids = [id, alternateId];
6027 format = ColorSpace.findFormat({
6028 name,
6029 id: ids,
6030 type: "function"
6031 });
6032 if (!format) {
6033 var _didYouMean;
6034 // Not found
6035 let didYouMean;
6036 let registryId = id in ColorSpace.registry ? id : alternateId;
6037 if (registryId in ColorSpace.registry) {
6038 var _ColorSpace$registry$;
6039 // Used color space id instead of color() id, these are often different
6040 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;
6041 if (cssId) {
6042 let altColor = str.replace("color(" + id, "color(" + cssId);
6043 didYouMean = `Did you mean ${altColor}?`;
6044 }
6045 }
6046 throw new TypeError(`Cannot parse ${env.str}. ` + ((_didYouMean = didYouMean) !== null && _didYouMean !== void 0 ? _didYouMean : "Missing a plugin?"));
6047 }
6048 space = format.space;
6049 if (format.id.startsWith("--") && !id.startsWith("--")) {
6050 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}).`);
6051 }
6052 if (id.startsWith("--") && !format.id.startsWith("--")) {
6053 defaults.warn(`${space.name} is a standard space and supported in the CSS spec. ` + `Use color(${format.id}) instead of prefixed color(${id}).`);
6054 }
6055 } else {
6056 format = ColorSpace.findFormat({
6057 name,
6058 type: "function"
6059 });
6060 space = format.space;
6061 }
6062 if (meta) {
6063 Object.assign(meta, {
6064 format,
6065 formatId: format.name,
6066 types,
6067 commas: env.parsed.commas
6068 });
6069 }
6070 let alpha = 1;
6071 if (env.parsed.lastAlpha) {
6072 alpha = env.parsed.args.pop();
6073 if (meta) {
6074 meta.alphaType = types.pop();
6075 }
6076 }
6077 let coordCount = format.coords.length;
6078 if (coords.length !== coordCount) {
6079 throw new TypeError(`Expected ${coordCount} coordinates for ${space.id} in ${env.str}), got ${coords.length}`);
6080 }
6081 coords = format.coerceCoords(coords, types);
6082 ret = {
6083 spaceId: space.id,
6084 coords,
6085 alpha
6086 };
6087 } else {
6088 // Custom, colorspace-specific format
6089 spaceloop: for (let space of ColorSpace.all) {
6090 for (let formatId in space.formats) {
6091 let format = space.formats[formatId];
6092 if (format.type !== "custom") {
6093 continue;
6094 }
6095 if (format.test && !format.test(env.str)) {
6096 continue;
6097 }
6098
6099 // Convert to Format object
6100 let formatObject = space.getFormat(format);
6101 let color = formatObject.parse(env.str);
6102 if (color) {
6103 if (meta) {
6104 Object.assign(meta, {
6105 format: formatObject,
6106 formatId
6107 });
6108 }
6109 ret = color;
6110 break spaceloop;
6111 }
6112 }
6113 }
6114 }
6115 if (!ret) {
6116 // If we're here, we couldn't parse
6117 throw new TypeError(`Could not parse ${str} as a color. Missing a plugin?`);
6118 }
6119
6120 // Clamp alpha to [0, 1]
6121 ret.alpha = isNone(ret.alpha) ? ret.alpha : ret.alpha === undefined ? 1 : clamp(0, ret.alpha, 1);
6122 return ret;
6123 }
6124
6125 /**
6126 * Units and multiplication factors for the internally stored numbers
6127 */
6128 const units = {
6129 "%": 0.01,
6130 deg: 1,
6131 grad: 0.9,
6132 rad: 180 / Math.PI,
6133 turn: 360
6134 };
6135 const regex = {
6136 // Need to list calc(NaN) explicitly as otherwise its ending paren would terminate the function call
6137 function: /^([a-z]+)\(((?:calc\(NaN\)|.)+?)\)$/i,
6138 number: /^([-+]?(?:[0-9]*\.)?[0-9]+(e[-+]?[0-9]+)?)$/i,
6139 unitValue: RegExp(`(${Object.keys(units).join("|")})$`),
6140 // NOTE The -+ are not just for prefix, but also for idents, and e+N notation!
6141 singleArgument: /\/?\s*(none|NaN|calc\(NaN\)|[-+\w.]+(?:%|deg|g?rad|turn)?)/g
6142 };
6143
6144 /**
6145 * Parse a single function argument
6146 * @param {string} rawArg
6147 * @returns {{value: number, meta: ArgumentMeta}}
6148 */
6149 function parseArgument(rawArg) {
6150 var _rawArg$match;
6151 /** @type {Partial<ArgumentMeta>} */
6152 let meta = {};
6153 let unit = (_rawArg$match = rawArg.match(regex.unitValue)) === null || _rawArg$match === void 0 ? void 0 : _rawArg$match[0];
6154 /** @type {string | number} */
6155 let value = meta.raw = rawArg;
6156 if (unit) {
6157 // It’s a dimension token
6158 meta.type = unit === "%" ? "<percentage>" : "<angle>";
6159 meta.unit = unit;
6160 meta.unitless = Number(value.slice(0, -unit.length)); // unitless number
6161
6162 value = meta.unitless * units[unit];
6163 } else if (regex.number.test(value)) {
6164 // It's a number
6165 // Convert numerical args to numbers
6166 value = Number(value);
6167 meta.type = "<number>";
6168 } else if (value === "none") {
6169 value = null;
6170 } else if (value === "NaN" || value === "calc(NaN)") {
6171 value = NaN;
6172 meta.type = "<number>";
6173 } else {
6174 meta.type = "<ident>";
6175 }
6176 return {
6177 value: (/** @type {number} */value),
6178 meta: (/** @type {ArgumentMeta} */meta)
6179 };
6180 }
6181
6182 /**
6183 * Parse a CSS function, regardless of its name and arguments
6184 * @param {string} str String to parse
6185 * @return {ParseFunctionReturn | void}
6186 */
6187 function parseFunction(str) {
6188 if (!str) {
6189 return;
6190 }
6191 str = str.trim();
6192 let parts = str.match(regex.function);
6193 if (parts) {
6194 // It is a function, parse args
6195 let args = [];
6196 let argMeta = [];
6197 let lastAlpha = false;
6198 let name = parts[1].toLowerCase();
6199 let separators = parts[2].replace(regex.singleArgument, ($0, rawArg) => {
6200 let {
6201 value,
6202 meta
6203 } = parseArgument(rawArg);
6204 if (
6205 // If there's a slash here, it's modern syntax
6206 $0.startsWith("/") ||
6207 // 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)"
6208 name !== "color" && args.length === 3) {
6209 // It's alpha
6210 lastAlpha = true;
6211 }
6212 args.push(value);
6213 argMeta.push(meta);
6214 return "";
6215 });
6216 return {
6217 name,
6218 args,
6219 argMeta,
6220 lastAlpha,
6221 commas: separators.includes(","),
6222 rawName: parts[1],
6223 rawArgs: parts[2]
6224 };
6225 }
6226 }
6227
6228 /** @import { ColorTypes, ParseOptions as GetColorOptions, PlainColorObject } from "./types.js" */
6229
6230 /**
6231 * Resolves a color reference (object or string) to a plain color object
6232 * @overload
6233 * @param {ColorTypes} color
6234 * @param {GetColorOptions} [options]
6235 * @returns {PlainColorObject}
6236 */
6237 /**
6238 * @overload
6239 * @param {ColorTypes[]} color
6240 * @param {GetColorOptions} [options]
6241 * @returns {PlainColorObject[]}
6242 */
6243 function getColor(color, options) {
6244 if (Array.isArray(color)) {
6245 return color.map(c => getColor(c, options));
6246 }
6247 if (!color) {
6248 throw new TypeError("Empty color reference");
6249 }
6250 if (isString(color)) {
6251 color = parse(color, options);
6252 }
6253
6254 // Object fixup
6255 let space = color.space || color.spaceId;
6256 if (typeof space === "string") {
6257 // Convert string id to color space object
6258 color.space = ColorSpace.get(space);
6259 }
6260 if (color.alpha === undefined) {
6261 color.alpha = 1;
6262 }
6263 return color;
6264 }
6265
6266 const ε$7 = 0.000075;
6267
6268 /**
6269 * Class to represent a color space
6270 */
6271 class ColorSpace {
6272 constructor(options) {
6273 var _options$displaySpace, _options$coords, _ref, _options$white, _options$formats, _this$formats$color, _options$M;
6274 this.id = options.id;
6275 this.name = options.name;
6276 this.base = options.base ? ColorSpace.get(options.base) : null;
6277 this.aliases = options.aliases;
6278 this.displaySpaces = (_options$displaySpace = options.displaySpaces) === null || _options$displaySpace === void 0 ? void 0 : _options$displaySpace.map(space => ColorSpace.get(space));
6279
6280 // This space's ancestors, closest first (immediate base → root), excluding the space itself.
6281 this.bases = [];
6282 for (let base = this.base; base; base = base.base) {
6283 this.bases.push(base);
6284 }
6285 if (options.rgbGamut) {
6286 this.rgbGamut = options.rgbGamut;
6287 }
6288 if (options.linearGamut) {
6289 this.linearGamut = options.linearGamut;
6290 }
6291 if (this.base) {
6292 // Keep a subclass's own methods if the options don't override them
6293 if (options.fromBase) {
6294 this.fromBase = options.fromBase;
6295 }
6296 if (options.toBase) {
6297 this.toBase = options.toBase;
6298 }
6299 }
6300
6301 // Coordinate metadata
6302
6303 let coords = (_options$coords = options.coords) !== null && _options$coords !== void 0 ? _options$coords : this.base.coords;
6304 for (let name in coords) {
6305 if (!("name" in coords[name])) {
6306 coords[name].name = name;
6307 }
6308 }
6309 this.coords = coords;
6310
6311 // White point
6312
6313 let white = (_ref = (_options$white = options.white) !== null && _options$white !== void 0 ? _options$white : this.base.white) !== null && _ref !== void 0 ? _ref : "D65";
6314 this.white = getWhite(white);
6315
6316 // Sort out formats
6317
6318 this.formats = (_options$formats = options.formats) !== null && _options$formats !== void 0 ? _options$formats : {};
6319 for (let name in this.formats) {
6320 let format = this.formats[name];
6321 format.type || (format.type = "function");
6322 format.name || (format.name = name);
6323 }
6324 if (!((_this$formats$color = this.formats.color) !== null && _this$formats$color !== void 0 && _this$formats$color.id)) {
6325 var _this$formats$color2;
6326 this.formats.color = {
6327 ...((_this$formats$color2 = this.formats.color) !== null && _this$formats$color2 !== void 0 ? _this$formats$color2 : {}),
6328 id: options.cssId || this.id
6329 };
6330 }
6331
6332 // Gamut space
6333
6334 if (options.gamutSpace) {
6335 // Gamut space explicitly specified
6336 this.gamutSpace = options.gamutSpace === "self" ? this : ColorSpace.get(options.gamutSpace);
6337 } else {
6338 // No gamut space specified, calculate a sensible default
6339 if (this.isPolar) {
6340 // Do not check gamut through polar coordinates
6341 this.gamutSpace = this.base;
6342 } else {
6343 this.gamutSpace = this;
6344 }
6345 }
6346
6347 // Optimize inGamut for unbounded spaces
6348 if (this.gamutSpace.isUnbounded) {
6349 this.inGamut = (coords, options) => {
6350 return true;
6351 };
6352 }
6353
6354 // Matrices used by this color space, exposed so that consumer code
6355 // can reuse them instead of duplicating the data. E.g. `this.M.toXYZ`.
6356 this.M = (_options$M = options.M) !== null && _options$M !== void 0 ? _options$M : {};
6357
6358 // Other stuff
6359 this.referred = options.referred;
6360
6361 // Compute ancestors and store them, since they will never change
6362 Object.defineProperty(this, "path", {
6363 value: getPath(this).reverse(),
6364 writable: false,
6365 enumerable: true,
6366 configurable: true
6367 });
6368 hooks.run("colorspace-init-end", this);
6369 }
6370 inGamut(coords, {
6371 epsilon = ε$7
6372 } = {}) {
6373 if (!this.equals(this.gamutSpace)) {
6374 coords = this.to(this.gamutSpace, coords);
6375 return this.gamutSpace.inGamut(coords, {
6376 epsilon
6377 });
6378 }
6379 let coordMeta = Object.values(this.coords);
6380 return coords.every((c, i) => {
6381 let meta = coordMeta[i];
6382 if (meta.type !== "angle" && meta.range) {
6383 if (isNone(c)) {
6384 // NaN is always in gamut
6385 return true;
6386 }
6387 let [min, max] = meta.range;
6388 return (min === undefined || c >= min - epsilon) && (max === undefined || c <= max + epsilon);
6389 }
6390 return true;
6391 });
6392 }
6393 get isUnbounded() {
6394 return Object.values(this.coords).every(coord => !("range" in coord));
6395 }
6396 get cssId() {
6397 var _this$formats;
6398 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;
6399 }
6400
6401 /**
6402 * The id of this space's hue coordinate, or null if the space is not polar
6403 * @returns {string | null}
6404 */
6405 get hueId() {
6406 for (let id in this.coords) {
6407 if (this.coords[id].type === "angle") {
6408 return id;
6409 }
6410 }
6411 return null;
6412 }
6413
6414 /**
6415 * The index of this space's hue coordinate within its coords array, or -1 if the space is not polar
6416 * @returns {number}
6417 */
6418 get hueIndex() {
6419 return Object.keys(this.coords).findIndex(id => this.coords[id].type === "angle");
6420 }
6421 get isPolar() {
6422 return this.hueId !== null;
6423 }
6424
6425 /**
6426 * Lookup a format in this color space
6427 * @param {string | object | Format} format - Format id if string. If object, it's converted to a `Format` object and returned.
6428 * @returns {Format}
6429 */
6430 getFormat(format) {
6431 if (!format) {
6432 return null;
6433 }
6434 if (format === "default") {
6435 format = Object.values(this.formats)[0];
6436 } else if (typeof format === "string") {
6437 format = this.formats[format];
6438 }
6439 let ret = Format.get(format, this);
6440 if (ret !== format && format.name in this.formats) {
6441 // Update the format we have on file so we can find it more quickly next time
6442 this.formats[format.name] = ret;
6443 }
6444 return ret;
6445 }
6446
6447 /**
6448 * Check if this color space is the same as another color space reference.
6449 * Allows proxying color space objects and comparing color spaces with ids.
6450 * @param {string | ColorSpace} space ColorSpace object or id to compare to
6451 * @returns {boolean}
6452 */
6453 equals(space) {
6454 if (!space) {
6455 return false;
6456 }
6457 return this === space || this.id === space || this.id === space.id;
6458 }
6459 to(space, coords) {
6460 if (arguments.length === 1) {
6461 const color = getColor(space);
6462 [space, coords] = [color.space, color.coords];
6463 }
6464 space = ColorSpace.get(space);
6465 if (this.equals(space)) {
6466 // Same space, no change needed
6467 return coords;
6468 }
6469
6470 // Convert NaN to 0, which seems to be valid in every coordinate of every color space
6471 coords = coords.map(c => isNone(c) ? 0 : c);
6472
6473 // Find connection space = lowest common ancestor in the base tree
6474 let myPath = this.path;
6475 let otherPath = space.path;
6476 let connectionSpace, connectionSpaceIndex;
6477 for (let i = 0; i < myPath.length; i++) {
6478 if (myPath[i].equals(otherPath[i])) {
6479 connectionSpace = myPath[i];
6480 connectionSpaceIndex = i;
6481 } else {
6482 break;
6483 }
6484 }
6485 if (!connectionSpace) {
6486 // This should never happen
6487 throw new Error(`Cannot convert between color spaces ${this} and ${space}: no connection space was found`);
6488 }
6489
6490 // Go up from current space to connection space
6491 for (let i = myPath.length - 1; i > connectionSpaceIndex; i--) {
6492 coords = myPath[i].toBase(coords);
6493 }
6494
6495 // Go down from connection space to target space
6496 for (let i = connectionSpaceIndex + 1; i < otherPath.length; i++) {
6497 coords = otherPath[i].fromBase(coords);
6498 }
6499 return coords;
6500 }
6501 from(space, coords) {
6502 if (arguments.length === 1) {
6503 const color = getColor(space);
6504 [space, coords] = [color.space, color.coords];
6505 }
6506 space = ColorSpace.get(space);
6507 return space.to(this, coords);
6508 }
6509 toString() {
6510 return `${this.name} (${this.id})`;
6511 }
6512 getMinCoords() {
6513 let ret = [];
6514 for (let id in this.coords) {
6515 var _range$min;
6516 let meta = this.coords[id];
6517 let range = meta.range || meta.refRange;
6518 ret.push((_range$min = range === null || range === void 0 ? void 0 : range.min) !== null && _range$min !== void 0 ? _range$min : 0);
6519 }
6520 return ret;
6521 }
6522 static registry = {};
6523
6524 // Returns array of unique color spaces
6525 static get all() {
6526 return [...new Set(Object.values(ColorSpace.registry))];
6527 }
6528 static register(id, space) {
6529 if (arguments.length === 1) {
6530 space = arguments[0];
6531 id = space.id;
6532 }
6533 space = this.get(space);
6534 if (this.registry[id] && this.registry[id] !== space) {
6535 throw new Error(`Duplicate color space registration: '${id}'`);
6536 }
6537 this.registry[id] = space;
6538
6539 // Register aliases when called without an explicit ID.
6540 if (arguments.length === 1 && space.aliases) {
6541 for (let alias of space.aliases) {
6542 this.register(alias, space);
6543 }
6544 }
6545 return space;
6546 }
6547
6548 /**
6549 * Lookup ColorSpace object by name
6550 * @param {ColorSpace | string} name
6551 */
6552 static get(space, ...alternatives) {
6553 if (!space || isInstance(space, this)) {
6554 return space;
6555 }
6556 let argType = type(space);
6557 if (argType === "string") {
6558 // It's a color space id
6559 let ret = ColorSpace.registry[space.toLowerCase()];
6560 if (!ret) {
6561 throw new TypeError(`No color space found with id = "${space}"`);
6562 }
6563 return ret;
6564 }
6565 if (alternatives.length) {
6566 return ColorSpace.get(...alternatives);
6567 }
6568 throw new TypeError(`${space} is not a valid color space`);
6569 }
6570
6571 /**
6572 * Look up all color spaces for a format that matches certain criteria
6573 * @param {object | string} filters
6574 * @param {Array<ColorSpace>} [spaces=ColorSpace.all]
6575 * @returns {Format | null}
6576 */
6577 static findFormat(filters, spaces = ColorSpace.all) {
6578 if (!filters) {
6579 return null;
6580 }
6581 if (typeof filters === "string") {
6582 filters = {
6583 name: filters
6584 };
6585 }
6586 for (let space of spaces) {
6587 for (let [name, format] of Object.entries(space.formats)) {
6588 var _format$name, _format$type;
6589 (_format$name = format.name) !== null && _format$name !== void 0 ? _format$name : format.name = name;
6590 (_format$type = format.type) !== null && _format$type !== void 0 ? _format$type : format.type = "function";
6591 let matches = (!filters.name || format.name === filters.name) && (!filters.type || format.type === filters.type);
6592 if (filters.id) {
6593 let ids = format.ids || [format.id];
6594 let filterIds = Array.isArray(filters.id) ? filters.id : [filters.id];
6595 matches && (matches = filterIds.some(id => ids.includes(id)));
6596 }
6597 if (matches) {
6598 let ret = Format.get(format, space);
6599 if (ret !== format) {
6600 space.formats[format.name] = ret;
6601 }
6602 return ret;
6603 }
6604 }
6605 }
6606 return null;
6607 }
6608
6609 /**
6610 * Get metadata about a coordinate of a color space
6611 *
6612 * @static
6613 * @param {Array | string} ref
6614 * @param {ColorSpace | string} [workingSpace]
6615 * @return {Object}
6616 */
6617 static resolveCoord(ref, workingSpace) {
6618 let coordType = type(ref);
6619 let space, coord;
6620 if (coordType === "string") {
6621 if (ref.includes(".")) {
6622 // Absolute coordinate
6623 [space, coord] = ref.split(".");
6624 } else {
6625 // Relative coordinate
6626 [space, coord] = [, ref];
6627 }
6628 } else if (Array.isArray(ref)) {
6629 [space, coord] = ref;
6630 } else {
6631 // Object
6632 space = ref.space;
6633 coord = ref.coordId;
6634 }
6635 space = ColorSpace.get(space);
6636 if (!space) {
6637 space = workingSpace;
6638 }
6639 if (!space) {
6640 throw new TypeError(`Cannot resolve coordinate reference ${ref}: No color space specified and relative references are not allowed here`);
6641 }
6642 coordType = type(coord);
6643 if (coordType === "number" || coordType === "string" && coord >= 0) {
6644 // Resolve numerical coord
6645 let meta = Object.entries(space.coords)[coord];
6646 if (meta) {
6647 return {
6648 space,
6649 id: meta[0],
6650 index: coord,
6651 ...meta[1]
6652 };
6653 }
6654 }
6655 space = ColorSpace.get(space);
6656 let normalizedCoord = coord.toLowerCase();
6657 let i = 0;
6658 for (let id in space.coords) {
6659 var _meta$name;
6660 let meta = space.coords[id];
6661 if (id.toLowerCase() === normalizedCoord || ((_meta$name = meta.name) === null || _meta$name === void 0 ? void 0 : _meta$name.toLowerCase()) === normalizedCoord) {
6662 return {
6663 space,
6664 id,
6665 index: i,
6666 ...meta
6667 };
6668 }
6669 i++;
6670 }
6671 throw new TypeError(`No "${coord}" coordinate found in ${space.name}. Its coordinates are: ${Object.keys(space.coords).join(", ")}`);
6672 }
6673 static DEFAULT_FORMAT = {
6674 type: "functions",
6675 name: "color"
6676 };
6677 }
6678 function getPath(space) {
6679 let ret = [space];
6680 for (let s = space; s = s.base;) {
6681 ret.push(s);
6682 }
6683 return ret;
6684 }
6685
6686 var XYZ_D65 = new ColorSpace({
6687 id: "xyz-d65",
6688 name: "XYZ D65",
6689 coords: {
6690 x: {
6691 refRange: [0, 1],
6692 name: "X"
6693 },
6694 y: {
6695 refRange: [0, 1],
6696 name: "Y"
6697 },
6698 z: {
6699 refRange: [0, 1],
6700 name: "Z"
6701 }
6702 },
6703 white: "D65",
6704 formats: {
6705 color: {
6706 ids: ["xyz-d65", "xyz"]
6707 }
6708 },
6709 aliases: ["xyz"]
6710 });
6711
6712 // Type re-exports
6713 /** @typedef {import("./types.js").RGBOptions} RGBOptions */
6714
6715 /** Convenience class for RGB color spaces */
6716 class RGBColorSpace extends ColorSpace {
6717 /**
6718 * Creates a new RGB ColorSpace.
6719 * If coords are not specified, they will use the default RGB coords.
6720 * Instead of `fromBase()` and `toBase()` functions,
6721 * you can specify to/from XYZ matrices and have the default `toBase()` and `fromBase()`
6722 * methods use them via `this.M.toXYZ` and `this.M.fromXYZ`.
6723 * @param {RGBOptions} options
6724 */
6725 constructor(options) {
6726 var _options$toXYZ_M, _options$M, _options$fromXYZ_M, _options$M2, _options$referred;
6727 if (!options.coords) {
6728 options.coords = {
6729 r: {
6730 range: [0, 1],
6731 name: "Red"
6732 },
6733 g: {
6734 range: [0, 1],
6735 name: "Green"
6736 },
6737 b: {
6738 range: [0, 1],
6739 name: "Blue"
6740 }
6741 };
6742 }
6743 if (!options.base) {
6744 options.base = XYZ_D65;
6745 }
6746
6747 // Accept matrices either as dedicated options or via the generic `M` object
6748 let toXYZ = (_options$toXYZ_M = options.toXYZ_M) !== null && _options$toXYZ_M !== void 0 ? _options$toXYZ_M : (_options$M = options.M) === null || _options$M === void 0 ? void 0 : _options$M.toXYZ;
6749 let fromXYZ = (_options$fromXYZ_M = options.fromXYZ_M) !== null && _options$fromXYZ_M !== void 0 ? _options$fromXYZ_M : (_options$M2 = options.M) === null || _options$M2 === void 0 ? void 0 : _options$M2.fromXYZ;
6750 (_options$referred = options.referred) !== null && _options$referred !== void 0 ? _options$referred : options.referred = "display";
6751 super(options);
6752
6753 // Expose the matrices on the color space (via `this.M`) so consumers can reuse them.
6754 if (toXYZ && fromXYZ) {
6755 this.M.toXYZ = toXYZ;
6756 this.M.fromXYZ = fromXYZ;
6757 }
6758 }
6759 toBase(rgb) {
6760 let xyz = multiply_v3_m3x3(rgb, this.M.toXYZ);
6761 if (this.white !== this.base.white) {
6762 // Perform chromatic adaptation
6763 xyz = adapt$2(this.white, this.base.white, xyz);
6764 }
6765 return xyz;
6766 }
6767 fromBase(xyz) {
6768 xyz = adapt$2(this.base.white, this.white, xyz);
6769 return multiply_v3_m3x3(xyz, this.M.fromXYZ);
6770 }
6771 }
6772
6773 var XYZ_D50 = new ColorSpace({
6774 id: "xyz-d50",
6775 name: "XYZ D50",
6776 white: "D50",
6777 base: XYZ_D65,
6778 fromBase: coords => adapt$2(XYZ_D65.white, "D50", coords),
6779 toBase: coords => adapt$2("D50", XYZ_D65.white, coords)
6780 });
6781
6782 // κ * ε = 2^3 = 8
6783 const ε$6 = 216 / 24389; // 6^3/29^3 == (24/116)^3
6784 const ε3$1 = 24 / 116;
6785 const κ$4 = 24389 / 27; // 29^3/3^3
6786
6787 let white$4 = WHITES.D50;
6788 var lab = new ColorSpace({
6789 id: "lab",
6790 name: "Lab",
6791 coords: {
6792 l: {
6793 refRange: [0, 100],
6794 name: "Lightness"
6795 },
6796 a: {
6797 refRange: [-125, 125]
6798 },
6799 b: {
6800 refRange: [-125, 125]
6801 }
6802 },
6803 // Assuming XYZ is relative to D50, convert to CIE Lab
6804 // from CIE standard, which now defines these as a rational fraction
6805 white: white$4,
6806 base: XYZ_D50,
6807 // Convert D50-adapted XYX to Lab
6808 // CIE 15.3:2004 section 8.2.1.1
6809 fromBase(XYZ) {
6810 // XYZ scaled relative to reference white
6811 let xyz = XYZ.map((value, i) => value / white$4[i]);
6812 let f = xyz.map(value => value > ε$6 ? Math.cbrt(value) : (κ$4 * value + 16) / 116);
6813 let L = 116 * f[1] - 16;
6814 let a = 500 * (f[0] - f[1]);
6815 let b = 200 * (f[1] - f[2]);
6816 return [L, a, b];
6817 },
6818 // Convert Lab to D50-adapted XYZ
6819 // Same result as CIE 15.3:2004 Appendix D although the derivation is different
6820 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
6821 toBase(Lab) {
6822 // compute f, starting with the luminance-related term
6823 let [L, a, b] = Lab;
6824 let f = [];
6825 f[1] = (L + 16) / 116;
6826 f[0] = a / 500 + f[1];
6827 f[2] = f[1] - b / 200;
6828
6829 // compute xyz
6830 // prettier-ignore
6831 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];
6832
6833 // Compute XYZ by scaling xyz by reference white
6834 return xyz.map((value, i) => value * white$4[i]);
6835 },
6836 formats: {
6837 lab: {
6838 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
6839 }
6840 }
6841 });
6842
6843 /**
6844 * Constrain an angle to 360 degrees
6845 * @param {number} angle
6846 * @returns {number}
6847 */
6848 function constrain(angle) {
6849 if (typeof angle !== "number") {
6850 return angle;
6851 }
6852 return (angle % 360 + 360) % 360;
6853 }
6854
6855 /**
6856 * @param {"raw" | "increasing" | "decreasing" | "longer" | "shorter"} arc
6857 * @param {[number, number]} angles
6858 * @returns {[number, number]}
6859 */
6860 function adjust(arc, angles) {
6861 let [a1, a2] = angles;
6862 let none1 = isNone(a1);
6863 let none2 = isNone(a2);
6864 if (none1 && none2) {
6865 return [a1, a2];
6866 } else if (none1) {
6867 a1 = a2;
6868 } else if (none2) {
6869 a2 = a1;
6870 }
6871 if (arc === "raw") {
6872 return angles;
6873 }
6874 a1 = constrain(a1);
6875 a2 = constrain(a2);
6876 let angleDiff = a2 - a1;
6877 if (arc === "increasing") {
6878 if (angleDiff < 0) {
6879 a2 += 360;
6880 }
6881 } else if (arc === "decreasing") {
6882 if (angleDiff > 0) {
6883 a1 += 360;
6884 }
6885 } else if (arc === "longer") {
6886 if (-180 < angleDiff && angleDiff < 180) {
6887 if (angleDiff > 0) {
6888 a1 += 360;
6889 } else {
6890 a2 += 360;
6891 }
6892 }
6893 } else if (arc === "shorter") {
6894 if (angleDiff > 180) {
6895 a1 += 360;
6896 } else if (angleDiff < -180) {
6897 a2 += 360;
6898 }
6899 }
6900 return [a1, a2];
6901 }
6902
6903 var lch = new ColorSpace({
6904 id: "lch",
6905 name: "LCH",
6906 coords: {
6907 l: {
6908 refRange: [0, 100],
6909 name: "Lightness"
6910 },
6911 c: {
6912 refRange: [0, 150],
6913 name: "Chroma"
6914 },
6915 h: {
6916 refRange: [0, 360],
6917 type: "angle",
6918 name: "Hue"
6919 }
6920 },
6921 base: lab,
6922 fromBase(Lab) {
6923 // These methods are used for other polar forms as well, so we can't hardcode the ε
6924 if (this.ε === undefined) {
6925 // @ts-expect-error Property 'coords' does not exist on type 'string | ColorSpace'
6926 let range = Object.values(this.base.coords)[1].refRange;
6927 let extent = range[1] - range[0];
6928 this.ε = extent / 100000;
6929 }
6930
6931 // Convert to polar form
6932 let [L, a, b] = Lab;
6933 let isAchromatic = Math.abs(a) < this.ε && Math.abs(b) < this.ε;
6934 let h = isAchromatic ? null : constrain(Math.atan2(b, a) * 180 / Math.PI);
6935 let C = isAchromatic ? 0 : Math.sqrt(a ** 2 + b ** 2);
6936 return [L, C, h];
6937 },
6938 toBase(lch) {
6939 // Convert from polar form
6940 let [L, C, h] = lch;
6941 let a = null,
6942 b = null;
6943 if (!isNone(h)) {
6944 C = C < 0 ? 0 : C; // Clamp negative Chroma
6945 a = C * Math.cos(h * Math.PI / 180);
6946 b = C * Math.sin(h * Math.PI / 180);
6947 }
6948 return [L, a, b];
6949 },
6950 formats: {
6951 lch: {
6952 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"]
6953 }
6954 }
6955 });
6956
6957 // deltaE2000 is a statistically significant improvement
6958 // and is recommended by the CIE and Idealliance
6959 // especially for color differences less than 10 deltaE76
6960 // but is wicked complicated
6961 // and many implementations have small errors!
6962 // DeltaE2000 is also discontinuous; in case this
6963 // matters to you, use deltaECMC instead.
6964
6965 const Gfactor = 25 ** 7;
6966 const π$1 = Math.PI;
6967 const r2d = 180 / π$1;
6968 const d2r$1 = π$1 / 180;
6969 function pow7(x) {
6970 // Faster than x ** 7 or Math.pow(x, 7)
6971
6972 const x2 = x * x;
6973 const x7 = x2 * x2 * x2 * x;
6974 return x7;
6975 }
6976
6977 /**
6978 * @param {import("../types.js").ColorTypes} color
6979 * @param {import("../types.js").ColorTypes} sample
6980 * @param {{ kL?: number | undefined; kC?: number | undefined; kH?: number | undefined }} options
6981 * @returns {number}
6982 */
6983 function deltaE2000 (color, sample, {
6984 kL = 1,
6985 kC = 1,
6986 kH = 1
6987 } = {}) {
6988 [color, sample] = getColor([color, sample]);
6989
6990 // Given this color as the reference
6991 // and the function parameter as the sample,
6992 // calculate deltaE 2000.
6993
6994 // This implementation assumes the parametric
6995 // weighting factors kL, kC and kH
6996 // for the influence of viewing conditions
6997 // are all 1, as sadly seems typical.
6998 // kL should be increased for lightness texture or noise
6999 // and kC increased for chroma noise
7000
7001 let [L1, a1, b1] = lab.from(color);
7002 let C1 = lch.from(lab, [L1, a1, b1])[1];
7003 let [L2, a2, b2] = lab.from(sample);
7004 let C2 = lch.from(lab, [L2, a2, b2])[1];
7005
7006 // Check for negative Chroma,
7007 // which might happen through
7008 // direct user input of LCH values
7009
7010 if (C1 < 0) {
7011 C1 = 0;
7012 }
7013 if (C2 < 0) {
7014 C2 = 0;
7015 }
7016 let Cbar = (C1 + C2) / 2; // mean Chroma
7017
7018 // calculate a-axis asymmetry factor from mean Chroma
7019 // this turns JND ellipses for near-neutral colors back into circles
7020 let C7 = pow7(Cbar);
7021 let G = 0.5 * (1 - Math.sqrt(C7 / (C7 + Gfactor)));
7022
7023 // scale a axes by asymmetry factor
7024 // this by the way is why there is no Lab2000 colorspace
7025 let adash1 = (1 + G) * a1;
7026 let adash2 = (1 + G) * a2;
7027
7028 // calculate new Chroma from scaled a and original b axes
7029 let Cdash1 = Math.sqrt(adash1 ** 2 + b1 ** 2);
7030 let Cdash2 = Math.sqrt(adash2 ** 2 + b2 ** 2);
7031
7032 // calculate new hues, with zero hue for true neutrals
7033 // and in degrees, not radians
7034
7035 let h1 = adash1 === 0 && b1 === 0 ? 0 : Math.atan2(b1, adash1);
7036 let h2 = adash2 === 0 && b2 === 0 ? 0 : Math.atan2(b2, adash2);
7037 if (h1 < 0) {
7038 h1 += 2 * π$1;
7039 }
7040 if (h2 < 0) {
7041 h2 += 2 * π$1;
7042 }
7043 h1 *= r2d;
7044 h2 *= r2d;
7045
7046 // Lightness and Chroma differences; sign matters
7047 let ΔL = L2 - L1;
7048 let ΔC = Cdash2 - Cdash1;
7049
7050 // Hue difference, getting the sign correct
7051 let hdiff = h2 - h1;
7052 let hsum = h1 + h2;
7053 let habs = Math.abs(hdiff);
7054 let Δh;
7055 if (Cdash1 * Cdash2 === 0) {
7056 Δh = 0;
7057 } else if (habs <= 180) {
7058 Δh = hdiff;
7059 } else if (hdiff > 180) {
7060 Δh = hdiff - 360;
7061 } else if (hdiff < -180) {
7062 Δh = hdiff + 360;
7063 } else {
7064 defaults.warn("the unthinkable has happened");
7065 }
7066
7067 // weighted Hue difference, more for larger Chroma
7068 let ΔH = 2 * Math.sqrt(Cdash2 * Cdash1) * Math.sin(Δh * d2r$1 / 2);
7069
7070 // calculate mean Lightness and Chroma
7071 let Ldash = (L1 + L2) / 2;
7072 let Cdash = (Cdash1 + Cdash2) / 2;
7073 let Cdash7 = pow7(Cdash);
7074
7075 // Compensate for non-linearity in the blue region of Lab.
7076 // Four possibilities for hue weighting factor,
7077 // depending on the angles, to get the correct sign
7078 let hdash;
7079 if (Cdash1 * Cdash2 === 0) {
7080 hdash = hsum; // which should be zero
7081 } else if (habs <= 180) {
7082 hdash = hsum / 2;
7083 } else if (hsum < 360) {
7084 hdash = (hsum + 360) / 2;
7085 } else {
7086 hdash = (hsum - 360) / 2;
7087 }
7088
7089 // positional corrections to the lack of uniformity of CIELAB
7090 // These are all trying to make JND ellipsoids more like spheres
7091
7092 // SL Lightness crispening factor
7093 // a background with L=50 is assumed
7094 let lsq = (Ldash - 50) ** 2;
7095 let SL = 1 + 0.015 * lsq / Math.sqrt(20 + lsq);
7096
7097 // SC Chroma factor, similar to those in CMC and deltaE 94 formulae
7098 let SC = 1 + 0.045 * Cdash;
7099
7100 // Cross term T for blue non-linearity
7101 let T = 1;
7102 T -= 0.17 * Math.cos((hdash - 30) * d2r$1);
7103 T += 0.24 * Math.cos(2 * hdash * d2r$1);
7104 T += 0.32 * Math.cos((3 * hdash + 6) * d2r$1);
7105 T -= 0.2 * Math.cos((4 * hdash - 63) * d2r$1);
7106
7107 // SH Hue factor depends on Chroma,
7108 // as well as adjusted hue angle like deltaE94.
7109 let SH = 1 + 0.015 * Cdash * T;
7110
7111 // RT Hue rotation term compensates for rotation of JND ellipses
7112 // and Munsell constant hue lines
7113 // in the medium-high Chroma blue region
7114 // (Hue 225 to 315)
7115 let Δθ = 30 * Math.exp(-1 * ((hdash - 275) / 25) ** 2);
7116 let RC = 2 * Math.sqrt(Cdash7 / (Cdash7 + Gfactor));
7117 let RT = -1 * Math.sin(2 * Δθ * d2r$1) * RC;
7118
7119 // Finally calculate the deltaE, term by term as root sume of squares
7120 let dE = (ΔL / (kL * SL)) ** 2;
7121 dE += (ΔC / (kC * SC)) ** 2;
7122 dE += (ΔH / (kH * SH)) ** 2;
7123 dE += RT * (ΔC / (kC * SC)) * (ΔH / (kH * SH));
7124 return Math.sqrt(dE);
7125 // Yay!!!
7126 }
7127
7128 /** @import { Matrix3x3 } from "../types.js" */
7129
7130 /**
7131 * Matrices used by this color space, also available as `Oklab.M`.
7132 * Recalculated for consistent reference white,
7133 * see https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-943521484
7134 * @type {Record<string, Matrix3x3>}
7135 */
7136 // prettier-ignore
7137 const M$d = {
7138 XYZtoLMS: [[0.8190224379967030, 0.3619062600528904, -0.1288737815209879], [0.0329836539323885, 0.9292868615863434, 0.0361446663506424], [0.0481771893596242, 0.2642395317527308, 0.6335478284694309]],
7139 // inverse of XYZtoLMS
7140 LMStoXYZ: [[1.2268798758459243, -0.5578149944602171, 0.2813910456659647], [-0.0405757452148008, 1.1122868032803170, -0.0717110580655164], [-0.0763729366746601, -0.4214933324022432, 1.5869240198367816]],
7141 LMStoLab: [[0.2104542683093140, 0.7936177747023054, -0.0040720430116193], [1.9779985324311684, -2.4285922420485799, 0.4505937096174110], [0.0259040424655478, 0.7827717124575296, -0.8086757549230774]],
7142 // LMStoLab inverted
7143 LabtoLMS: [[1.0000000000000000, 0.3963377773761749, 0.2158037573099136], [1.0000000000000000, -0.1055613458156586, -0.0638541728258133], [1.0000000000000000, -0.0894841775298119, -1.2914855480194092]]
7144 };
7145 var Oklab = new ColorSpace({
7146 id: "oklab",
7147 name: "Oklab",
7148 coords: {
7149 l: {
7150 refRange: [0, 1],
7151 name: "Lightness"
7152 },
7153 a: {
7154 refRange: [-0.4, 0.4]
7155 },
7156 b: {
7157 refRange: [-0.4, 0.4]
7158 }
7159 },
7160 // Note that XYZ is relative to D65
7161 white: "D65",
7162 base: XYZ_D65,
7163 M: M$d,
7164 fromBase(XYZ) {
7165 // move to LMS cone domain
7166 let LMS = multiply_v3_m3x3(XYZ, M$d.XYZtoLMS);
7167
7168 // non-linearity
7169 LMS[0] = Math.cbrt(LMS[0]);
7170 LMS[1] = Math.cbrt(LMS[1]);
7171 LMS[2] = Math.cbrt(LMS[2]);
7172 return multiply_v3_m3x3(LMS, M$d.LMStoLab, LMS);
7173 },
7174 toBase(OKLab) {
7175 // move to LMS cone domain
7176 let LMSg = multiply_v3_m3x3(OKLab, M$d.LabtoLMS);
7177
7178 // restore linearity
7179 LMSg[0] = LMSg[0] ** 3;
7180 LMSg[1] = LMSg[1] ** 3;
7181 LMSg[2] = LMSg[2] ** 3;
7182 return multiply_v3_m3x3(LMSg, M$d.LMStoXYZ, LMSg);
7183 },
7184 formats: {
7185 oklab: {
7186 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
7187 }
7188 }
7189 });
7190
7191 /**
7192 * More accurate color-difference formulae
7193 * than the simple 1976 Euclidean distance in CIE Lab
7194 * @param {import("../types.js").ColorTypes} color
7195 * @param {import("../types.js").ColorTypes} sample
7196 * @returns {number}
7197 */
7198 function deltaEOK (color, sample) {
7199 [color, sample] = getColor([color, sample]);
7200
7201 // Given this color as the reference
7202 // and a sample,
7203 // calculate deltaEOK, term by term as root sum of squares
7204 let [L1, a1, b1] = Oklab.from(color);
7205 let [L2, a2, b2] = Oklab.from(sample);
7206 let ΔL = L1 - L2;
7207 let Δa = a1 - a2;
7208 let Δb = b1 - b2;
7209 return Math.sqrt(ΔL ** 2 + Δa ** 2 + Δb ** 2);
7210 }
7211
7212 /** @import { ColorTypes } from "./types.js" */
7213
7214 const ε$5 = 0.000075;
7215
7216 /**
7217 * Check if a color is in gamut of either its own or another color space
7218 * @param {ColorTypes} color
7219 * @param {string | ColorSpace} [space]
7220 * @param {{ epsilon?: number | undefined }} [param2]
7221 * @returns {boolean}
7222 */
7223 function inGamut(color, space, {
7224 epsilon = ε$5
7225 } = {}) {
7226 color = getColor(color);
7227 if (!space) {
7228 space = color.space;
7229 }
7230 space = ColorSpace.get(space);
7231 let coords = color.coords;
7232 if (space !== color.space) {
7233 coords = space.from(color);
7234 }
7235 return space.inGamut(coords, {
7236 epsilon
7237 });
7238 }
7239
7240 /** @import { ColorTypes, PlainColorObject, ToGamutOptions } from "./types.js" */
7241
7242 /**
7243 * Convert to color space and return a new color
7244 * @param {ColorTypes} color
7245 * @param {string | ColorSpace} space
7246 * @param {{ inGamut?: boolean | ToGamutOptions | undefined }} options
7247 * @returns {PlainColorObject}
7248 */
7249 function to(color, space, {
7250 inGamut
7251 } = {}) {
7252 color = getColor(color);
7253 space = ColorSpace.get(space);
7254 let coords = space.from(color);
7255 let ret = {
7256 space,
7257 coords,
7258 alpha: color.alpha
7259 };
7260 if (inGamut) {
7261 ret = toGamut(ret, inGamut === true ? undefined : inGamut);
7262 }
7263 return ret;
7264 }
7265
7266 /** @type {"color"} */
7267 to.returns = "color";
7268
7269 /** @import { ColorTypes, Coords } from "./types.js" */
7270
7271 /**
7272 * Options for {@link getAll}
7273 * @typedef GetAllOptions
7274 * @property {string | ColorSpace | undefined} [space]
7275 * The color space to convert to. Defaults to the color's current space
7276 * @property {number | undefined} [precision]
7277 * The number of significant digits to round the coordinates to
7278 */
7279
7280 /**
7281 * Get the coordinates of a color in any color space
7282 * @overload
7283 * @param {ColorTypes} color
7284 * @param {string | ColorSpace} [options=color.space] The color space to convert to. Defaults to the color's current space
7285 * @returns {Coords} The color coordinates in the given color space
7286 */
7287 /**
7288 * @overload
7289 * @param {ColorTypes} color
7290 * @param {GetAllOptions} [options]
7291 * @returns {Coords} The color coordinates in the given color space
7292 */
7293 function getAll(color, options) {
7294 color = getColor(color);
7295 let space = ColorSpace.get(options, options === null || options === void 0 ? void 0 : options.space);
7296 let precision = options === null || options === void 0 ? void 0 : options.precision;
7297 let coords;
7298 if (!space || color.space.equals(space)) {
7299 // No conversion needed
7300 coords = color.coords.slice();
7301 } else {
7302 coords = space.from(color);
7303 }
7304 return precision === undefined ? coords : coords.map(coord => toPrecision(coord, precision));
7305 }
7306
7307 /** @import { ColorTypes, Ref } from "./types.js" */
7308
7309 /**
7310 * @param {ColorTypes} color
7311 * @param {Ref} prop
7312 * @returns {number}
7313 */
7314 function get(color, prop) {
7315 color = getColor(color);
7316 if (prop === "alpha") {
7317 var _color$alpha;
7318 return (_color$alpha = color.alpha) !== null && _color$alpha !== void 0 ? _color$alpha : 1;
7319 }
7320 let {
7321 space,
7322 index
7323 } = ColorSpace.resolveCoord(prop, color.space);
7324 let coords = getAll(color, space);
7325 return coords[index];
7326 }
7327
7328 var OKLCH = new ColorSpace({
7329 id: "oklch",
7330 name: "OkLCh",
7331 coords: {
7332 l: {
7333 refRange: [0, 1],
7334 name: "Lightness"
7335 },
7336 c: {
7337 refRange: [0, 0.4],
7338 name: "Chroma"
7339 },
7340 h: {
7341 refRange: [0, 360],
7342 type: "angle",
7343 name: "Hue"
7344 }
7345 },
7346 white: "D65",
7347 base: Oklab,
7348 fromBase: lch.fromBase,
7349 toBase: lch.toBase,
7350 formats: {
7351 oklch: {
7352 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"]
7353 }
7354 }
7355 });
7356
7357 /** @import { ColorTypes, Coords, PlainColorObject } from "./types.js" */
7358
7359 /**
7360 * Set all coordinates of a color at once, in its own color space or another.
7361 * Modifies the color in place.
7362 * @overload
7363 * @param {ColorTypes} color
7364 * @param {Coords} coords Array of coordinates
7365 * @param {number} [alpha]
7366 * @returns {PlainColorObject}
7367 */
7368 /**
7369 * @overload
7370 * @param {ColorTypes} color
7371 * @param {string | ColorSpace} space The color space of the provided coordinates.
7372 * @param {Coords} coords Array of coordinates
7373 * @param {number} [alpha]
7374 * @returns {PlainColorObject}
7375 */
7376 function setAll(color, space, coords, alpha) {
7377 color = getColor(color);
7378 if (Array.isArray(space)) {
7379 // Space is omitted
7380 [space, coords, alpha] = [color.space, space, coords];
7381 }
7382 space = ColorSpace.get(space); // Make sure we have a ColorSpace object
7383 color.coords = space === color.space ? coords.slice() : space.to(color.space, coords);
7384 if (alpha !== undefined) {
7385 color.alpha = alpha;
7386 }
7387 return color;
7388 }
7389
7390 /** @type {"color"} */
7391 setAll.returns = "color";
7392
7393 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
7394
7395 /**
7396 * Set properties and return current instance
7397 * @overload
7398 * @param {ColorTypes} color
7399 * @param {Ref} prop
7400 * @param {number | ((coord: number) => number)} value
7401 * @returns {PlainColorObject}
7402 */
7403 /**
7404 * @overload
7405 * @param {ColorTypes} color
7406 * @param {Record<string, number | ((coord: number) => number)>} props
7407 * @returns {PlainColorObject}
7408 */
7409 function set(color, prop, value) {
7410 color = getColor(color);
7411 if (arguments.length === 2 && type(arguments[1]) === "object") {
7412 // Argument is an object literal
7413 let object = arguments[1];
7414 for (let p in object) {
7415 set(color, p, object[p]);
7416 }
7417 } else {
7418 if (typeof value === "function") {
7419 value = value(get(color, prop));
7420 }
7421 if (prop === "alpha") {
7422 color.alpha = value;
7423 } else {
7424 let {
7425 space,
7426 index
7427 } = ColorSpace.resolveCoord(prop, color.space);
7428 let coords = getAll(color, space);
7429 coords[index] = value;
7430 setAll(color, space, coords);
7431 }
7432 }
7433 return color;
7434 }
7435
7436 /** @type {"color"} */
7437 set.returns = "color";
7438
7439 /** @import { Coords, PlainColorObject } from "./types.js" */
7440
7441 /**
7442 * @param {PlainColorObject} color
7443 * @returns {PlainColorObject}
7444 */
7445 function clone(color) {
7446 return {
7447 space: color.space,
7448 coords: (/** @type {Coords} */color.coords.slice()),
7449 alpha: color.alpha
7450 };
7451 }
7452
7453 /** @import { ColorTypes } from "./types.js" */
7454
7455 /**
7456 * Euclidean distance of colors in an arbitrary color space
7457 * @param {ColorTypes} color1
7458 * @param {ColorTypes} color2
7459 * @param {string | ColorSpace} space
7460 * @returns {number}
7461 */
7462 function distance(color1, color2, space = "lab") {
7463 space = ColorSpace.get(space);
7464
7465 // Assume getColor() is called on color in space.from()
7466 let coords1 = space.from(color1);
7467 let coords2 = space.from(color2);
7468 return Math.sqrt(coords1.reduce((acc, c1, i) => {
7469 let c2 = coords2[i];
7470 if (isNone(c1) || isNone(c2)) {
7471 return acc;
7472 }
7473 return acc + (c2 - c1) ** 2;
7474 }, 0));
7475 }
7476
7477 /**
7478 * @param {import("../types.js").ColorTypes} color
7479 * @param {import("../types.js").ColorTypes} sample
7480 * @returns {number}
7481 */
7482 function deltaE76(color, sample) {
7483 // Assume getColor() is called in the distance function
7484 return distance(color, sample, "lab");
7485 }
7486
7487 // More accurate color-difference formulae
7488 // than the simple 1976 Euclidean distance in Lab
7489
7490 // CMC by the Color Measurement Committee of the
7491 // Bradford Society of Dyeists and Colorsts, 1994.
7492 // Uses LCH rather than Lab,
7493 // with different weights for L, C and H differences
7494 // A nice increase in accuracy for modest increase in complexity
7495 const π = Math.PI;
7496 const d2r = π / 180;
7497
7498 /**
7499 * @param {import("../types.js").ColorTypes} color
7500 * @param {import("../types.js").ColorTypes} sample
7501 * @param {{ l?: number | undefined; c?: number | undefined }} options
7502 * @returns {number}
7503 */
7504 function deltaECMC (color, sample, {
7505 l = 2,
7506 c = 1
7507 } = {}) {
7508 [color, sample] = getColor([color, sample]);
7509
7510 // Given this color as the reference
7511 // and a sample,
7512 // calculate deltaE CMC.
7513
7514 // This implementation assumes the parametric
7515 // weighting factors l:c are 2:1
7516 // which is typical for non-textile uses.
7517
7518 let [L1, a1, b1] = lab.from(color);
7519 let [, C1, H1] = lch.from(lab, [L1, a1, b1]);
7520 let [L2, a2, b2] = lab.from(sample);
7521 let C2 = lch.from(lab, [L2, a2, b2])[1];
7522
7523 // let [L1, a1, b1] = color.getAll(lab);
7524 // let C1 = color.get("lch.c");
7525 // let H1 = color.get("lch.h");
7526 // let [L2, a2, b2] = sample.getAll(lab);
7527 // let C2 = sample.get("lch.c");
7528
7529 // Check for negative Chroma,
7530 // which might happen through
7531 // direct user input of LCH values
7532
7533 if (C1 < 0) {
7534 C1 = 0;
7535 }
7536 if (C2 < 0) {
7537 C2 = 0;
7538 }
7539
7540 // we don't need H2 as ΔH is calculated from Δa, Δb and ΔC
7541
7542 // Lightness and Chroma differences
7543 // These are (color - sample), unlike deltaE2000
7544 let ΔL = L1 - L2;
7545 let ΔC = C1 - C2;
7546 let Δa = a1 - a2;
7547 let Δb = b1 - b2;
7548
7549 // weighted Hue difference, less for larger Chroma difference
7550
7551 let H2 = Δa ** 2 + Δb ** 2 - ΔC ** 2;
7552 // due to roundoff error it is possible that, for zero a and b,
7553 // ΔC > Δa + Δb is 0, resulting in attempting
7554 // to take the square root of a negative number
7555
7556 // trying instead the equation from Industrial Color Physics
7557 // By Georg A. Klein
7558
7559 // let ΔH = ((a1 * b2) - (a2 * b1)) / Math.sqrt(0.5 * ((C2 * C1) + (a2 * a1) + (b2 * b1)));
7560 // console.log({ΔH});
7561 // This gives the same result to 12 decimal places
7562 // except it sometimes NaNs when trying to root a negative number
7563
7564 // let ΔH = Math.sqrt(H2); we never actually use the root, it gets squared again!!
7565
7566 // positional corrections to the lack of uniformity of CIELAB
7567 // These are all trying to make JND ellipsoids more like spheres
7568
7569 // SL Lightness crispening factor, depends entirely on L1 not L2
7570 let SL = 0.511; // linear portion of the Y to L transfer function
7571 if (L1 >= 16) {
7572 // cubic portion
7573 SL = 0.040975 * L1 / (1 + 0.01765 * L1);
7574 }
7575
7576 // SC Chroma factor
7577 let SC = 0.0638 * C1 / (1 + 0.0131 * C1) + 0.638;
7578
7579 // Cross term T for blue non-linearity
7580 let T;
7581 if (isNone(H1)) {
7582 H1 = 0;
7583 }
7584 if (H1 >= 164 && H1 <= 345) {
7585 T = 0.56 + Math.abs(0.2 * Math.cos((H1 + 168) * d2r));
7586 } else {
7587 T = 0.36 + Math.abs(0.4 * Math.cos((H1 + 35) * d2r));
7588 }
7589 // console.log({T});
7590
7591 // SH Hue factor also depends on C1,
7592 let C4 = Math.pow(C1, 4);
7593 let F = Math.sqrt(C4 / (C4 + 1900));
7594 let SH = SC * (F * T + 1 - F);
7595
7596 // Finally calculate the deltaE, term by term as root sume of squares
7597 let dE = (ΔL / (l * SL)) ** 2;
7598 dE += (ΔC / (c * SC)) ** 2;
7599 dE += H2 / SH ** 2;
7600 // dE += (ΔH / SH) ** 2;
7601 return Math.sqrt(dE);
7602 // Yay!!!
7603 }
7604
7605 const Yw$1 = 203; // absolute luminance of media white
7606
7607 var XYZ_Abs_D65 = new ColorSpace({
7608 // Absolute CIE XYZ, with a D65 whitepoint,
7609 // as used in most HDR colorspaces as a starting point.
7610 // SDR spaces are converted per BT.2048
7611 // so that diffuse, media white is 203 cd/m²
7612 id: "xyz-abs-d65",
7613 cssId: "--xyz-abs-d65",
7614 name: "Absolute XYZ D65",
7615 coords: {
7616 x: {
7617 refRange: [0, 9504.7],
7618 name: "Xa"
7619 },
7620 y: {
7621 refRange: [0, 10000],
7622 name: "Ya"
7623 },
7624 z: {
7625 refRange: [0, 10888.3],
7626 name: "Za"
7627 }
7628 },
7629 base: XYZ_D65,
7630 fromBase(XYZ) {
7631 // Make XYZ absolute, not relative to media white
7632 // Maximum luminance in PQ is 10,000 cd/m²
7633 // Relative XYZ has Y=1 for media white
7634 return XYZ.map(v => v * Yw$1);
7635 },
7636 toBase(AbsXYZ) {
7637 // Convert to media-white relative XYZ
7638 return AbsXYZ.map(v => v / Yw$1);
7639 }
7640 });
7641
7642 /** @import { Matrix3x3, Vector3 } from "../types.js" */
7643
7644 const b$1 = 1.15;
7645 const g = 0.66;
7646 const n$1 = 2610 / 2 ** 14;
7647 const ninv$1 = 2 ** 14 / 2610;
7648 const c1$2 = 3424 / 2 ** 12;
7649 const c2$2 = 2413 / 2 ** 7;
7650 const c3$2 = 2392 / 2 ** 7;
7651 const p$1 = 1.7 * 2523 / 2 ** 5;
7652 const pinv = 2 ** 5 / (1.7 * 2523);
7653 const d = -0.56;
7654 const d0 = 1.6295499532821566e-11;
7655
7656 /**
7657 * Matrices used by this color space, also available as `Jzazbz.M`
7658 * @type {Record<string, Matrix3x3>}
7659 */
7660 // prettier-ignore
7661 const M$c = {
7662 XYZtoCone: [[0.41478972, 0.579999, 0.0146480], [-0.2015100, 1.120649, 0.0531008], [-0.0166008, 0.264800, 0.6684799]],
7663 // XYZtoCone inverted
7664 ConetoXYZ: [[1.9242264357876067, -1.0047923125953657, 0.037651404030618], [0.35031676209499907, 0.7264811939316552, -0.06538442294808501], [-0.09098281098284752, -0.3127282905230739, 1.5227665613052603]],
7665 ConetoIab: [[0.5, 0.5, 0], [3.524000, -4.066708, 0.542708], [0.199076, 1.096799, -1.295875]],
7666 // ConetoIab inverted
7667 IabtoCone: [[1, 0.13860504327153927, 0.05804731615611883], [1, -0.1386050432715393, -0.058047316156118904], [1, -0.09601924202631895, -0.81189189605603900]]
7668 };
7669 var Jzazbz = new ColorSpace({
7670 id: "jzazbz",
7671 name: "Jzazbz",
7672 coords: {
7673 jz: {
7674 refRange: [0, 1],
7675 name: "Jz"
7676 },
7677 az: {
7678 refRange: [-0.21, 0.21]
7679 },
7680 bz: {
7681 refRange: [-0.21, 0.21]
7682 }
7683 },
7684 base: XYZ_Abs_D65,
7685 M: M$c,
7686 fromBase(XYZ) {
7687 // First make XYZ absolute, not relative to media white
7688 // Maximum luminance in PQ is 10,000 cd/m²
7689 // Relative XYZ has Y=1 for media white
7690 // BT.2048 says media white Y=203 at PQ 58
7691
7692 let [Xa, Ya, Za] = XYZ;
7693
7694 // modify X and Y to minimize blue curvature
7695 let Xm = b$1 * Xa - (b$1 - 1) * Za;
7696 let Ym = g * Ya - (g - 1) * Xa;
7697
7698 // move to LMS cone domain
7699 let LMS = multiply_v3_m3x3([Xm, Ym, Za], M$c.XYZtoCone);
7700
7701 // PQ-encode LMS
7702 let PQLMS = /** @type {Vector3} } */
7703 LMS.map(function (val) {
7704 let num = c1$2 + c2$2 * spow(val / 10000, n$1);
7705 let denom = 1 + c3$2 * spow(val / 10000, n$1);
7706 return spow(num / denom, p$1);
7707 });
7708
7709 // almost there, calculate Iz az bz
7710 let [Iz, az, bz] = multiply_v3_m3x3(PQLMS, M$c.ConetoIab);
7711 // console.log({Iz, az, bz});
7712
7713 let Jz = (1 + d) * Iz / (1 + d * Iz) - d0;
7714 return [Jz, az, bz];
7715 },
7716 toBase(Jzazbz) {
7717 let [Jz, az, bz] = Jzazbz;
7718 let Iz = (Jz + d0) / (1 + d - d * (Jz + d0));
7719
7720 // bring into LMS cone domain
7721 let PQLMS = multiply_v3_m3x3([Iz, az, bz], M$c.IabtoCone);
7722
7723 // convert from PQ-coded to linear-light
7724 let LMS = /** @type {Vector3} } */
7725 PQLMS.map(function (val) {
7726 let num = c1$2 - spow(val, pinv);
7727 let denom = c3$2 * spow(val, pinv) - c2$2;
7728 let x = 10000 * spow(num / denom, ninv$1);
7729 return x; // luminance relative to diffuse white, [0, 70 or so].
7730 });
7731
7732 // modified abs XYZ
7733 let [Xm, Ym, Za] = multiply_v3_m3x3(LMS, M$c.ConetoXYZ);
7734
7735 // un-modify X and Y to get D65 XYZ, relative to media white
7736 let Xa = (Xm + (b$1 - 1) * Za) / b$1;
7737 let Ya = (Ym + (g - 1) * Xa) / g;
7738 return [Xa, Ya, Za];
7739 },
7740 formats: {
7741 // https://drafts.csswg.org/css-color-hdr/#Jzazbz
7742 jzazbz: {
7743 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
7744 }
7745 }
7746 });
7747
7748 var jzczhz = new ColorSpace({
7749 id: "jzczhz",
7750 name: "JzCzHz",
7751 coords: {
7752 jz: {
7753 refRange: [0, 1],
7754 name: "Jz"
7755 },
7756 cz: {
7757 refRange: [0, 0.26],
7758 name: "Chroma"
7759 },
7760 hz: {
7761 refRange: [0, 360],
7762 type: "angle",
7763 name: "Hue"
7764 }
7765 },
7766 base: Jzazbz,
7767 fromBase: lch.fromBase,
7768 toBase: lch.toBase,
7769 formats: {
7770 // https://drafts.csswg.org/css-color-hdr/#JzCzhz
7771 jzczhz: {
7772 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <angle>"]
7773 }
7774 }
7775 });
7776
7777 /**
7778 * More accurate color-difference formulae
7779 * than the simple 1976 Euclidean distance in Lab
7780 *
7781 * Uses JzCzHz, which has improved perceptual uniformity
7782 * and thus a simple Euclidean root-sum of ΔL² ΔC² ΔH²
7783 * gives good results.
7784 * @param {import("../types.js").ColorTypes} color
7785 * @param {import("../types.js").ColorTypes} sample
7786 * @returns {number}
7787 */
7788 function deltaEJz (color, sample) {
7789 [color, sample] = getColor([color, sample]);
7790
7791 // Given this color as the reference
7792 // and a sample,
7793 // calculate deltaE in JzCzHz.
7794 let [Jz1, Cz1, Hz1] = jzczhz.from(color);
7795 let [Jz2, Cz2, Hz2] = jzczhz.from(sample);
7796
7797 // Lightness and Chroma differences
7798 // sign does not matter as they are squared.
7799 let ΔJ = Jz1 - Jz2;
7800 let ΔC = Cz1 - Cz2;
7801
7802 // length of chord for ΔH
7803 if (isNone(Hz1) && isNone(Hz2)) {
7804 // both undefined hues
7805 Hz1 = 0;
7806 Hz2 = 0;
7807 } else if (isNone(Hz1)) {
7808 // one undefined, set to the defined hue
7809 Hz1 = Hz2;
7810 } else if (isNone(Hz2)) {
7811 Hz2 = Hz1;
7812 }
7813 let Δh = Hz1 - Hz2;
7814 let ΔH = 2 * Math.sqrt(Cz1 * Cz2) * Math.sin(Δh / 2 * (Math.PI / 180));
7815 return Math.sqrt(ΔJ ** 2 + ΔC ** 2 + ΔH ** 2);
7816 }
7817
7818 /** @import { Matrix3x3, Vector3 } from "../types.js" */
7819
7820 const c1$1 = 3424 / 4096;
7821 const c2$1 = 2413 / 128;
7822 const c3$1 = 2392 / 128;
7823 const m1 = 2610 / 16384;
7824 const m2 = 2523 / 32;
7825 const im1 = 16384 / 2610;
7826 const im2 = 32 / 2523;
7827
7828 // Reference (rational-form) matrices, kept for documentation but not used directly:
7829 // linear-light Rec.2020 to LMS (with crosstalk) and its inverse
7830 // rational terms from Jan Fröhlich, Encoding High Dynamic Range
7831 // and Wide Color Gamut Imagery, p.97 and ITU-R BT.2124-0 pp.2-3
7832 /*
7833 const Rec2020toLMS = [
7834 [ 1688 / 4096, 2146 / 4096, 262 / 4096 ],
7835 [ 683 / 4096, 2951 / 4096, 462 / 4096 ],
7836 [ 99 / 4096, 309 / 4096, 3688 / 4096 ]
7837 ];
7838 const LMStoRec2020 = [
7839 [ 3.4375568932814012112, -2.5072112125095058195, 0.069654319228104608382],
7840 [-0.79142868665644156125, 1.9838372198740089874, -0.19240853321756742626 ],
7841 [-0.025646662911506476363, -0.099240248643945566751, 1.1248869115554520431 ]
7842 ];
7843 */
7844
7845 /**
7846 * Matrices used by this color space, also available as `ICTCP.M`
7847 * @type {Record<string, Matrix3x3>}
7848 */
7849 // prettier-ignore
7850 const M$b = {
7851 // includes the 4% crosstalk components, from the Dolby "What is ICtCp" paper
7852 XYZtoLMS: [[0.3592832590121217, 0.6976051147779502, -0.0358915932320290], [-0.1920808463704993, 1.1004767970374321, 0.0753748658519118], [0.0070797844607479, 0.0748396662186362, 0.8433265453898765]],
7853 // includes the Ebner LMS coefficients, the rotation,
7854 // and the scaling to the [-0.5,0.5] range
7855 LMStoIPT: [[2048 / 4096, 2048 / 4096, 0], [6610 / 4096, -13613 / 4096, 7003 / 4096], [17933 / 4096, -17390 / 4096, -543 / 4096]],
7856 // inverted matrices, calculated from the above
7857 IPTtoLMS: [[0.9999999999999998, 0.0086090370379328, 0.1110296250030260], [0.9999999999999998, -0.0086090370379328, -0.1110296250030259], [0.9999999999999998, 0.5600313357106791, -0.3206271749873188]],
7858 LMStoXYZ: [[2.0701522183894223, -1.3263473389671563, 0.2066510476294053], [0.3647385209748072, 0.6805660249472273, -0.0453045459220347], [-0.0497472075358123, -0.0492609666966131, 1.1880659249923042]]
7859 };
7860
7861 // Only the PQ form of ICtCp is implemented here. There is also an HLG form.
7862 // from Dolby, "WHAT IS ICTCP?"
7863 // https://professional.dolby.com/siteassets/pdfs/ictcp_dolbywhitepaper_v071.pdf
7864 // and
7865 // Dolby, "Perceptual Color Volume
7866 // Measuring the Distinguishable Colors of HDR and WCG Displays"
7867 // https://professional.dolby.com/siteassets/pdfs/dolby-vision-measuring-perceptual-color-volume-v7.1.pdf
7868 var ictcp = new ColorSpace({
7869 id: "ictcp",
7870 name: "ICTCP",
7871 // From BT.2100-2 page 7:
7872 // During production, signal values are expected to exceed the
7873 // range E′ = [0.0 : 1.0]. This provides processing headroom and avoids
7874 // signal degradation during cascaded processing. Such values of E′,
7875 // below 0.0 or exceeding 1.0, should not be clipped during production
7876 // and exchange.
7877 // Values below 0.0 should not be clipped in reference displays (even
7878 // though they represent “negative” light) to allow the black level of
7879 // the signal (LB) to be properly set using test signals known as “PLUGE”
7880 coords: {
7881 i: {
7882 refRange: [0, 1],
7883 // Constant luminance,
7884 name: "I"
7885 },
7886 ct: {
7887 refRange: [-0.5, 0.5],
7888 // Full BT.2020 gamut in range [-0.5, 0.5]
7889 name: "CT"
7890 },
7891 cp: {
7892 refRange: [-0.5, 0.5],
7893 name: "CP"
7894 }
7895 },
7896 base: XYZ_Abs_D65,
7897 M: M$b,
7898 fromBase(XYZ) {
7899 // move to LMS cone domain
7900 let LMS = multiply_v3_m3x3(XYZ, M$b.XYZtoLMS);
7901 return LMStoICtCp(LMS);
7902 },
7903 toBase(ICtCp) {
7904 let LMS = ICtCptoLMS(ICtCp);
7905 return multiply_v3_m3x3(LMS, M$b.LMStoXYZ);
7906 },
7907 formats: {
7908 ictcp: {
7909 coords: ["<percentage> | <number>", "<number> | <percentage>", "<number> | <percentage>"]
7910 }
7911 }
7912 });
7913
7914 /**
7915 *
7916 * @param {Vector3} LMS
7917 * @returns {Vector3}
7918 */
7919 function LMStoICtCp(LMS) {
7920 // apply the PQ EOTF
7921 // we can't ever be dividing by zero because of the "1 +" in the denominator
7922 let PQLMS = /** @type {Vector3} */
7923 LMS.map(function (val) {
7924 let num = c1$1 + c2$1 * (val / 10000) ** m1;
7925 let denom = 1 + c3$1 * (val / 10000) ** m1;
7926 return (num / denom) ** m2;
7927 });
7928
7929 // LMS to IPT, with rotation for Y'C'bC'r compatibility
7930 return multiply_v3_m3x3(PQLMS, M$b.LMStoIPT);
7931 }
7932
7933 /**
7934 *
7935 * @param {Vector3} ICtCp
7936 * @returns {Vector3}
7937 */
7938 function ICtCptoLMS(ICtCp) {
7939 let PQLMS = multiply_v3_m3x3(ICtCp, M$b.IPTtoLMS);
7940
7941 // From BT.2124-0 Annex 2 Conversion 3
7942 let LMS = /** @type {Vector3} */
7943 PQLMS.map(function (val) {
7944 let num = Math.max(val ** im2 - c1$1, 0);
7945 let denom = c2$1 - c3$1 * val ** im2;
7946 return 10000 * (num / denom) ** im1;
7947 });
7948 return LMS;
7949 }
7950
7951 /**
7952 * Delta E in ICtCp space,
7953 * which the ITU calls Delta E ITP, which is shorter.
7954 * Formulae from ITU Rec. ITU-R BT.2124-0
7955 * @param {import("../types.js").ColorTypes} color
7956 * @param {import("../types.js").ColorTypes} sample
7957 * @returns {number}
7958 */
7959 function deltaEITP (color, sample) {
7960 [color, sample] = getColor([color, sample]);
7961
7962 // Given this color as the reference
7963 // and a sample,
7964 // calculate deltaE in ICtCp
7965 // which is simply the Euclidean distance
7966
7967 let [I1, T1, P1] = ictcp.from(color);
7968 let [I2, T2, P2] = ictcp.from(sample);
7969
7970 // the 0.25 factor is to undo the encoding scaling in Ct
7971 // the 720 is so that 1 deltaE = 1 JND
7972 // per ITU-R BT.2124-0 p.3
7973
7974 return 720 * Math.sqrt((I1 - I2) ** 2 + 0.25 * (T1 - T2) ** 2 + (P1 - P2) ** 2);
7975 }
7976
7977 /**
7978 * More accurate color-difference formulae
7979 * than the simple 1976 Euclidean distance in CIE Lab
7980 * The Oklab a and b axes are scaled relative to the L axis, for better uniformity
7981 * Björn Ottosson said:
7982 * "I've recently done some tests with color distance datasets as implemented
7983 * in Colorio and on both the Combvd dataset and the OSA-UCS dataset a
7984 * scale factor of slightly more than 2 for a and b would give the best results
7985 * (2.016 works best for Combvd and 2.045 for the OSA-UCS dataset)."
7986 * @see {@link <https://github.com/w3c/csswg-drafts/issues/6642#issuecomment-945714988>}
7987 * @param {import("../types.js").ColorTypes} color
7988 * @param {import("../types.js").ColorTypes} sample
7989 * @returns {number}
7990 */
7991 function deltaEOK2 (color, sample) {
7992 [color, sample] = getColor([color, sample]);
7993
7994 // Given this color as the reference
7995 // and a sample,
7996 // calculate deltaEOK2, term by term as root sum of squares
7997 let abscale = 2;
7998 let [L1, a1, b1] = Oklab.from(color);
7999 let [L2, a2, b2] = Oklab.from(sample);
8000 let ΔL = L1 - L2;
8001 let Δa = abscale * (a1 - a2);
8002 let Δb = abscale * (b1 - b2);
8003 return Math.sqrt(ΔL ** 2 + Δa ** 2 + Δb ** 2);
8004 }
8005
8006 /** @import { Coords, Matrix3x3, Vector3 } from "../types.js" */
8007
8008 // Type re-exports
8009 /** @typedef {import("../types.js").Cam16Object} Cam16Object */
8010 /** @typedef {import("../types.js").Cam16Input} Cam16Input */
8011 /** @typedef {import("../types.js").Cam16Environment} Cam16Environment */
8012
8013 const white$3 = WHITES.D65;
8014 const adaptedCoef = 0.42;
8015 const adaptedCoefInv = 1 / adaptedCoef;
8016 const tau$1 = 2 * Math.PI;
8017
8018 /**
8019 * Matrices used by this color space, also available as `CAM16_JMh.M`
8020 * @type {Record<string, Matrix3x3>}
8021 */
8022 // prettier-ignore
8023 const M$a = {
8024 cat16: [[0.401288, 0.650173, -0.051461], [-0.250268, 1.204414, 0.045854], [-0.002079, 0.048952, 0.953127]],
8025 cat16Inv: [[1.8620678550872327, -1.0112546305316843, 0.14918677544445175], [0.38752654323613717, 0.6214474419314753, -0.008973985167612518], [-0.015841498849333856, -0.03412293802851557, 1.0499644368778496]],
8026 m1: [[460.0, 451.0, 288.0], [460.0, -891.0, -261.0], [460.0, -220.0, -6300.0]]
8027 };
8028 const surroundMap = {
8029 dark: [0.8, 0.525, 0.8],
8030 dim: [0.9, 0.59, 0.9],
8031 average: [1, 0.69, 1]
8032 };
8033 const hueQuadMap = {
8034 // Red, Yellow, Green, Blue, Red
8035 h: [20.14, 90.0, 164.25, 237.53, 380.14],
8036 e: [0.8, 0.7, 1.0, 1.2, 0.8],
8037 H: [0.0, 100.0, 200.0, 300.0, 400.0]
8038 };
8039 const rad2deg = 180 / Math.PI;
8040 const deg2rad$1 = Math.PI / 180;
8041
8042 /**
8043 * @param {Coords} coords
8044 * @param {number} fl
8045 * @returns {[number, number, number]}
8046 */
8047 function adapt$1(coords, fl) {
8048 const temp = /** @type {[number, number, number]} */
8049 coords.map(c => {
8050 const x = spow(fl * Math.abs(c) * 0.01, adaptedCoef);
8051 return 400 * copySign(x, c) / (x + 27.13);
8052 });
8053 return temp;
8054 }
8055
8056 /**
8057 * @param {Coords} adapted
8058 * @param {number} fl
8059 * @returns {[number, number, number]}
8060 */
8061 function unadapt(adapted, fl) {
8062 const constant = 100 / fl * 27.13 ** adaptedCoefInv;
8063 return /** @type {[number, number, number]} */adapted.map(c => {
8064 const cabs = Math.abs(c);
8065 return copySign(constant * spow(cabs / (400 - cabs), adaptedCoefInv), c);
8066 });
8067 }
8068
8069 /**
8070 * @param {number} h
8071 */
8072 function hueQuadrature(h) {
8073 let hp = constrain(h);
8074 if (hp <= hueQuadMap.h[0]) {
8075 hp += 360;
8076 }
8077 const i = bisectLeft(hueQuadMap.h, hp) - 1;
8078 const [hi, hii] = hueQuadMap.h.slice(i, i + 2);
8079 const [ei, eii] = hueQuadMap.e.slice(i, i + 2);
8080 const Hi = hueQuadMap.H[i];
8081 const t = (hp - hi) / ei;
8082 return Hi + 100 * t / (t + (hii - hp) / eii);
8083 }
8084
8085 /**
8086 * @param {number} H
8087 */
8088 function invHueQuadrature(H) {
8089 let Hp = (H % 400 + 400) % 400;
8090 const i = Math.floor(0.01 * Hp);
8091 Hp = Hp % 100;
8092 const [hi, hii] = hueQuadMap.h.slice(i, i + 2);
8093 const [ei, eii] = hueQuadMap.e.slice(i, i + 2);
8094 return constrain((Hp * (eii * hi - ei * hii) - 100 * hi * eii) / (Hp * (eii - ei) - 100 * eii));
8095 }
8096
8097 /**
8098 * @param {[number, number, number]} refWhite
8099 * @param {number} adaptingLuminance
8100 * @param {number} backgroundLuminance
8101 * @param {keyof typeof surroundMap} surround
8102 * @param {boolean} discounting
8103 * @returns {Cam16Environment}
8104 */
8105 function environment(refWhite, adaptingLuminance, backgroundLuminance, surround, discounting) {
8106 const env = {};
8107 env.discounting = discounting;
8108 env.refWhite = refWhite;
8109 env.surround = surround;
8110 const xyzW = /** @type {Vector3} */
8111 refWhite.map(c => {
8112 return c * 100;
8113 });
8114
8115 // The average luminance of the environment in `cd/m^2cd/m` (a.k.a. nits)
8116 env.la = adaptingLuminance;
8117 // The relative luminance of the nearby background
8118 env.yb = backgroundLuminance;
8119 // Absolute luminance of the reference white.
8120 const yw = xyzW[1];
8121
8122 // Cone response for reference white
8123 const rgbW = multiply_v3_m3x3(xyzW, M$a.cat16);
8124
8125 // Surround: dark, dim, and average
8126 let values = surroundMap[env.surround];
8127 const f = values[0];
8128 env.c = values[1];
8129 env.nc = values[2];
8130 const k = 1 / (5 * env.la + 1);
8131 const k4 = k ** 4;
8132
8133 // Factor of luminance level adaptation
8134 env.fl = k4 * env.la + 0.1 * (1 - k4) * (1 - k4) * Math.cbrt(5 * env.la);
8135 env.flRoot = env.fl ** 0.25;
8136 env.n = env.yb / yw;
8137 env.z = 1.48 + Math.sqrt(env.n);
8138 env.nbb = 0.725 * env.n ** -0.2;
8139 env.ncb = env.nbb;
8140
8141 // Degree of adaptation calculating if not discounting
8142 // illuminant (assumed eye is fully adapted)
8143 const d = Math.max(Math.min(f * (1 - 1 / 3.6 * Math.exp((-env.la - 42) / 92)), 1), 0);
8144 env.dRgb = /** @type {[number, number, number]} */
8145 rgbW.map(c => {
8146 return interpolate(1, yw / c, d);
8147 });
8148 env.dRgbInv = /** @type {[number, number, number]} */
8149 env.dRgb.map(c => {
8150 return 1 / c;
8151 });
8152
8153 // Achromatic response
8154 const rgbCW = /** @type {[number, number, number]} */
8155 rgbW.map((c, i) => {
8156 return c * env.dRgb[i];
8157 });
8158 const rgbAW = adapt$1(rgbCW, env.fl);
8159 env.aW = env.nbb * (2 * rgbAW[0] + rgbAW[1] + 0.05 * rgbAW[2]);
8160
8161 // console.log(env);
8162
8163 return env;
8164 }
8165
8166 // Pre-calculate everything we can with the viewing conditions
8167 const viewingConditions$1 = environment(white$3, 64 / Math.PI * 0.2, 20, "average", false);
8168
8169 /**
8170 * @param {Cam16Input} cam16
8171 * @param {Cam16Environment} env
8172 * @returns {[number, number, number]}
8173 */
8174 function fromCam16(cam16, env) {
8175 // These check ensure one, and only one attribute for a
8176 // given category is provided.
8177 // @ts-expect-error The '^` operator is not allowed for boolean types
8178 if (!(cam16.J !== undefined ^ cam16.Q !== undefined)) {
8179 throw new Error("Conversion requires one and only one: 'J' or 'Q'");
8180 }
8181
8182 // @ts-expect-error - The '^` operator is not allowed for boolean types
8183 if (!(cam16.C !== undefined ^ cam16.M !== undefined ^ cam16.s !== undefined)) {
8184 throw new Error("Conversion requires one and only one: 'C', 'M' or 's'");
8185 }
8186
8187 // Hue is absolutely required
8188 // @ts-expect-error - The '^` operator is not allowed for boolean types
8189 if (!(cam16.h !== undefined ^ cam16.H !== undefined)) {
8190 throw new Error("Conversion requires one and only one: 'h' or 'H'");
8191 }
8192
8193 // Black
8194 if (cam16.J === 0.0 || cam16.Q === 0.0) {
8195 return [0.0, 0.0, 0.0];
8196 }
8197
8198 // Break hue into Cartesian components
8199 let hRad = 0.0;
8200 if (cam16.h !== undefined) {
8201 hRad = constrain(cam16.h) * deg2rad$1;
8202 } else {
8203 hRad = invHueQuadrature(cam16.H) * deg2rad$1;
8204 }
8205 const cosh = Math.cos(hRad);
8206 const sinh = Math.sin(hRad);
8207
8208 // Calculate `Jroot` from one of the lightness derived coordinates.
8209 let Jroot = 0.0;
8210 if (cam16.J !== undefined) {
8211 Jroot = spow(cam16.J, 1 / 2) * 0.1;
8212 } else if (cam16.Q !== undefined) {
8213 Jroot = 0.25 * env.c * cam16.Q / ((env.aW + 4) * env.flRoot);
8214 }
8215
8216 // Calculate the `t` value from one of the chroma derived coordinates
8217 let alpha = 0.0;
8218 if (cam16.C !== undefined) {
8219 alpha = cam16.C / Jroot;
8220 } else if (cam16.M !== undefined) {
8221 alpha = cam16.M / env.flRoot / Jroot;
8222 } else if (cam16.s !== undefined) {
8223 alpha = 0.0004 * cam16.s ** 2 * (env.aW + 4) / env.c;
8224 }
8225 const t = spow(alpha * Math.pow(1.64 - Math.pow(0.29, env.n), -0.73), 10 / 9);
8226
8227 // Eccentricity
8228 const et = 0.25 * (Math.cos(hRad + 2) + 3.8);
8229
8230 // Achromatic response
8231 const A = env.aW * spow(Jroot, 2 / env.c / env.z);
8232
8233 // Calculate red-green and yellow-blue components
8234 const p1 = 5e4 / 13 * env.nc * env.ncb * et;
8235 const p2 = A / env.nbb;
8236 const r = 23 * (p2 + 0.305) * zdiv(t, 23 * p1 + t * (11 * cosh + 108 * sinh));
8237 const a = r * cosh;
8238 const b = r * sinh;
8239
8240 // Calculate back from cone response to XYZ
8241 const rgb_c = unadapt(/** @type {Vector3} */
8242
8243 multiply_v3_m3x3([p2, a, b], M$a.m1).map(c => {
8244 return c * 1 / 1403;
8245 }), env.fl);
8246 return /** @type {Vector3} */multiply_v3_m3x3(/** @type {Vector3} */
8247 rgb_c.map((c, i) => {
8248 return c * env.dRgbInv[i];
8249 }), M$a.cat16Inv).map(c => {
8250 return c / 100;
8251 });
8252 }
8253
8254 /**
8255 * @param {[number, number, number]} xyzd65
8256 * @param {Cam16Environment} env
8257 * @returns {Cam16Object}
8258 */
8259 function toCam16(xyzd65, env) {
8260 // Cone response
8261 const xyz100 = /** @type {Vector3} */
8262 xyzd65.map(c => {
8263 return c * 100;
8264 });
8265 const rgbA = adapt$1(/** @type {[number, number, number]} */
8266
8267 multiply_v3_m3x3(xyz100, M$a.cat16).map((c, i) => {
8268 return c * env.dRgb[i];
8269 }), env.fl);
8270
8271 // Calculate hue from red-green and yellow-blue components
8272 const a = rgbA[0] + (-12 * rgbA[1] + rgbA[2]) / 11;
8273 const b = (rgbA[0] + rgbA[1] - 2 * rgbA[2]) / 9;
8274 const hRad = (Math.atan2(b, a) % tau$1 + tau$1) % tau$1;
8275
8276 // Eccentricity
8277 const et = 0.25 * (Math.cos(hRad + 2) + 3.8);
8278 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);
8279 const alpha = spow(t, 0.9) * Math.pow(1.64 - Math.pow(0.29, env.n), 0.73);
8280
8281 // Achromatic response
8282 const A = env.nbb * (2 * rgbA[0] + rgbA[1] + 0.05 * rgbA[2]);
8283 const Jroot = spow(A / env.aW, 0.5 * env.c * env.z);
8284
8285 // Lightness
8286 const J = 100 * spow(Jroot, 2);
8287
8288 // Brightness
8289 const Q = 4 / env.c * Jroot * (env.aW + 4) * env.flRoot;
8290
8291 // Chroma
8292 const C = alpha * Jroot;
8293
8294 // Colorfulness
8295 const colorfulness = C * env.flRoot;
8296
8297 // Hue
8298 const h = constrain(hRad * rad2deg);
8299
8300 // Hue quadrature
8301 const H = hueQuadrature(h);
8302
8303 // Saturation
8304 const s = 50 * spow(env.c * alpha / (env.aW + 4), 1 / 2);
8305
8306 // console.log({J: J, C: C, h: h, s: s, Q: Q, M: colorfulness, H: H});
8307
8308 return {
8309 J: J,
8310 C: C,
8311 h: h,
8312 s: s,
8313 Q: Q,
8314 M: colorfulness,
8315 H: H
8316 };
8317 }
8318
8319 // Provided as a way to directly evaluate the CAM16 model
8320 // https://observablehq.com/@jrus/cam16: reference implementation
8321 // https://arxiv.org/pdf/1802.06067.pdf: Nico Schlömer
8322 // https://onlinelibrary.wiley.com/doi/pdf/10.1002/col.22324: hue quadrature
8323 // https://www.researchgate.net/publication/318152296_Comprehensive_color_solutions_CAM16_CAT16_and_CAM16-UCS
8324 // Results compared against: https://github.com/colour-science/colour
8325 var cam16 = new ColorSpace({
8326 id: "cam16-jmh",
8327 cssId: "--cam16-jmh",
8328 name: "CAM16-JMh",
8329 coords: {
8330 j: {
8331 refRange: [0, 100],
8332 name: "J"
8333 },
8334 m: {
8335 refRange: [0, 105.0],
8336 name: "Colorfulness"
8337 },
8338 h: {
8339 refRange: [0, 360],
8340 type: "angle",
8341 name: "Hue"
8342 }
8343 },
8344 base: XYZ_D65,
8345 M: M$a,
8346 fromBase(xyz) {
8347 // If another derivation is created, ε could vary, so we can't hardcode
8348 if (this.ε === undefined) {
8349 this.ε = Object.values(this.coords)[1].refRange[1] / 100000;
8350 }
8351 const cam16 = toCam16(xyz, viewingConditions$1);
8352 const isAchromatic = Math.abs(cam16.M) < this.ε;
8353 return [cam16.J, isAchromatic ? 0 : cam16.M, isAchromatic ? null : cam16.h];
8354 },
8355 toBase(cam16) {
8356 return fromCam16({
8357 J: cam16[0],
8358 M: cam16[1],
8359 h: cam16[2]
8360 }, viewingConditions$1);
8361 }
8362 });
8363
8364 const white$2 = WHITES.D65;
8365 const ε$4 = 216 / 24389; // 6^3/29^3 == (24/116)^3
8366 const κ$3 = 24389 / 27; // 29^3/3^3
8367
8368 function toLstar(y) {
8369 // Convert XYZ Y to L*
8370
8371 const fy = y > ε$4 ? Math.cbrt(y) : (κ$3 * y + 16) / 116;
8372 return 116.0 * fy - 16.0;
8373 }
8374 function fromLstar(lstar) {
8375 // Convert L* back to XYZ Y
8376
8377 return lstar > 8 ? Math.pow((lstar + 16) / 116, 3) : lstar / κ$3;
8378 }
8379 function fromHct(coords, env) {
8380 // Use Newton's method to try and converge as quick as possible or
8381 // converge as close as we can. While the requested precision is achieved
8382 // most of the time, it may not always be achievable. Especially past the
8383 // visible spectrum, the algorithm will likely struggle to get the same
8384 // precision. If, for whatever reason, we cannot achieve the accuracy we
8385 // seek in the allotted iterations, just return the closest we were able to
8386 // get.
8387
8388 let [h, c, t] = coords;
8389 let xyz = [];
8390 let j = 0;
8391
8392 // Shortcut out for black
8393 if (t === 0) {
8394 return [0.0, 0.0, 0.0];
8395 }
8396
8397 // Calculate the Y we need to target
8398 let y = fromLstar(t);
8399
8400 // A better initial guess yields better results. Polynomials come from
8401 // curve fitting the T vs J response.
8402 if (t > 0) {
8403 j = 0.00379058511492914 * t ** 2 + 0.608983189401032 * t + 0.9155088574762233;
8404 } else {
8405 j = 9.514440756550361e-6 * t ** 2 + 0.08693057439788597 * t - 21.928975842194614;
8406 }
8407
8408 // Threshold of how close is close enough, and max number of attempts.
8409 // More precision and more attempts means more time spent iterating. Higher
8410 // required precision gives more accuracy but also increases the chance of
8411 // not hitting the goal. 2e-12 allows us to convert round trip with
8412 // reasonable accuracy of six decimal places or more.
8413 const threshold = 2e-12;
8414 const max_attempts = 15;
8415 let attempt = 0;
8416 let last = Infinity;
8417 let best = [0, 0, 0];
8418
8419 // Try to find a J such that the returned y matches the returned y of the L*
8420 while (attempt <= max_attempts) {
8421 xyz = fromCam16({
8422 J: j,
8423 C: c,
8424 h: h
8425 }, env);
8426
8427 // If we are within range, return XYZ
8428 // If we are closer than last time, save the values
8429 const delta = Math.abs(xyz[1] - y);
8430 if (delta < last) {
8431 if (delta <= threshold) {
8432 return xyz;
8433 }
8434 best = xyz;
8435 last = delta;
8436 }
8437
8438 // f(j_root) = (j ** (1 / 2)) * 0.1
8439 // f(j) = ((f(j_root) * 100) ** 2) / j - 1 = 0
8440 // f(j_root) = Y = y / 100
8441 // f(j) = (y ** 2) / j - 1
8442 // f'(j) = (2 * y) / j
8443 j = j - (xyz[1] - y) * j / (2 * xyz[1]);
8444 attempt += 1;
8445 }
8446
8447 // We could not acquire the precision we desired,
8448 // return our closest attempt.
8449 return best;
8450 }
8451 function toHct(xyz, env) {
8452 // Calculate HCT by taking the L* of CIE LCh D65 and CAM16 chroma and hue.
8453
8454 const t = toLstar(xyz[1]);
8455 if (t === 0.0) {
8456 return [0.0, 0.0, 0.0];
8457 }
8458 const cam16 = toCam16(xyz, viewingConditions);
8459 return [constrain(cam16.h), cam16.C, t];
8460 }
8461
8462 // Pre-calculate everything we can with the viewing conditions
8463 const viewingConditions = environment(white$2, 200 / Math.PI * fromLstar(50.0), fromLstar(50.0) * 100, "average", false);
8464
8465 // https://material.io/blog/science-of-color-design
8466 // This is not a port of the material-color-utilities,
8467 // but instead implements the full color space as described,
8468 // combining CAM16 JCh and Lab D65. This does not clamp conversion
8469 // to HCT to specific chroma bands and provides support for wider
8470 // gamuts than Google currently supports and does so at a greater
8471 // precision (> 8 bits back to sRGB).
8472 // This implementation comes from https://github.com/facelessuser/coloraide
8473 // which is licensed under MIT.
8474 var hct = new ColorSpace({
8475 id: "hct",
8476 name: "HCT",
8477 coords: {
8478 h: {
8479 refRange: [0, 360],
8480 type: "angle",
8481 name: "Hue"
8482 },
8483 c: {
8484 refRange: [0, 145],
8485 name: "Colorfulness"
8486 },
8487 t: {
8488 refRange: [0, 100],
8489 name: "Tone"
8490 }
8491 },
8492 base: XYZ_D65,
8493 fromBase(xyz) {
8494 if (this.ε === undefined) {
8495 this.ε = Object.values(this.coords)[1].refRange[1] / 100000;
8496 }
8497 let hct = toHct(xyz);
8498 if (hct[1] < this.ε) {
8499 hct[1] = 0.0;
8500 hct[0] = null;
8501 }
8502 return hct;
8503 },
8504 toBase(hct) {
8505 return fromHct(hct, viewingConditions);
8506 },
8507 formats: {
8508 color: {
8509 id: "--hct",
8510 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
8511 }
8512 }
8513 });
8514
8515 const deg2rad = Math.PI / 180;
8516 const ucsCoeff = [1.0, 0.007, 0.0228];
8517
8518 /**
8519 * Convert HCT chroma and hue (CAM16 JMh colorfulness and hue) using UCS logic for a and b.
8520 * @param {Coords} coords - HCT coordinates.
8521 * @return {number[]}
8522 */
8523 function convertUcsAb(coords) {
8524 // We want the distance between the actual color.
8525 // If chroma is negative, it will throw off our calculations.
8526 // Normally, converting back to the base and forward will correct it.
8527 // If we have a negative chroma after this, then we have a color that
8528 // cannot resolve to positive chroma.
8529 if (coords[1] < 0) {
8530 coords = hct.fromBase(hct.toBase(coords));
8531 }
8532
8533 // Only in extreme cases (usually outside the visible spectrum)
8534 // can the input value for log become negative.
8535 // Avoid domain error by forcing a zero result via "max" if necessary.
8536 const M = Math.log(Math.max(1 + ucsCoeff[2] * coords[1] * viewingConditions.flRoot, 1.0)) / ucsCoeff[2];
8537 const hrad = coords[0] * deg2rad;
8538 const a = M * Math.cos(hrad);
8539 const b = M * Math.sin(hrad);
8540 return [coords[2], a, b];
8541 }
8542
8543 /**
8544 * Color distance using HCT.
8545 * @param {import("../types.js").ColorTypes} color
8546 * @param {import("../types.js").ColorTypes} sample
8547 * @returns {number}
8548 */
8549 function deltaEHCT (color, sample) {
8550 [color, sample] = getColor([color, sample]);
8551 let [t1, a1, b1] = convertUcsAb(hct.from(color));
8552 let [t2, a2, b2] = convertUcsAb(hct.from(sample));
8553
8554 // Use simple euclidean distance with a and b using UCS conversion
8555 // and LCh lightness (HCT tone).
8556 return Math.sqrt((t1 - t2) ** 2 + (a1 - a2) ** 2 + (b1 - b2) ** 2);
8557 }
8558
8559 /**
8560 * Helmlab MetricSpace — 13-stage perceptual color space.
8561 *
8562 * A data-driven analytical color space fit on COMBVD (3,813 paired human
8563 * color-difference judgments aggregating BFD-P, Witt 1999, RIT-DuPont, and
8564 * Leeds). Used internally by `deltaEHelmlab` and exposed as the CSS
8565 * color space `helmlab-metric` for inspectability. Its coordinate system
8566 * (asymmetric ab plane, L > 1 from H-K modeling, achromatic axis offset
8567 * from origin) is shaped for ΔE accuracy rather than author-facing
8568 * coordinates — for general CSS authoring use HelmGen (`helmgen`).
8569 *
8570 * Measured in this branch: ~24% lower STRESS than CIEDE2000 on COMBVD.
8571 *
8572 * Pipeline: XYZ → M1 → γ → M2 → hue correction → H-K → cubic L → dark L
8573 * → hue-dep chroma scale → chroma power → L-dep chroma scale
8574 * → HLC interaction → hue-dep lightness → rotation
8575 *
8576 * Reference: arXiv:2602.23010
8577 * @see https://github.com/Grkmyldz148/helmlab
8578 */
8579
8580 /** @import { Matrix3x3 } from "../types.js" */
8581
8582 const {
8583 cos,
8584 sin,
8585 sqrt,
8586 atan2,
8587 exp,
8588 abs,
8589 pow,
8590 PI
8591 } = Math;
8592
8593 /** Bradford CAT: Color.js D65 → Helmlab D65 (apply in fromBase before M1) */
8594 /** @type {Matrix3x3} */
8595 // prettier-ignore
8596 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]];
8597
8598 /** Bradford CAT: Helmlab D65 → Color.js D65 (apply in toBase after M1_INV) */
8599 /** @type {Matrix3x3} */
8600 // prettier-ignore
8601 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]];
8602
8603 // ── Utility functions ──────────────────────────────────────────────
8604
8605 // ── Core parameters (v21, 72 params) ──────────────────────────────
8606
8607 /** @type {Matrix3x3} */
8608 // prettier-ignore
8609 const M1 = [[0.72129864331134985189, 0.45344826541531813024, -0.19288975751942616377], [-0.78821186949557897616, 1.79524137675723594043, 0.08761724511817850503], [-0.09177005999121559676, 0.45765588659459255361, 1.29220455139176770842]];
8610 /** @type {Matrix3x3} */
8611 // prettier-ignore
8612 const M1_INV = [[1.06510729580885898926, -0.31500440753011210715, 0.18034923817410389302], [0.47211077138377960383, 0.42719957659624552271, 0.04150680489380984689], [-0.09156391926309541407, -0.17367093631949789834, 0.77197903825582936399]];
8613 const GAMMA = [0.47229813098762524, 0.5149184096354483, 0.5113233386366979];
8614 const INV_GAMMA = [2.1173067060606283, 1.9420552485353544, 1.9557096741686448];
8615
8616 /** @type {Matrix3x3} */
8617 // prettier-ignore
8618 const M2 = [[-0.26355622180094095963, 0.41683228837031738312, 0.49267631416564028335], [1.88975705087773215851, -3.12122320342057735232, 1.04216669210603840590], [0.35851086179620561545, 1.76940281937903676202, -1.41206260676953720967]];
8619 /** @type {Matrix3x3} */
8620 // prettier-ignore
8621 const M2_INV = [[0.91838978228150214278, 0.52320512370886662623, 0.70658045980908557038], [1.08990905744330257576, 0.07005324849041903723, 0.43197768747870440853], [1.59889572926420897581, 0.22061850068770233468, 0.01250603735522095097]];
8622
8623 /** Matrices used by this color space, also available as `Helmlab.M` */
8624 const M$9 = {
8625 CAT_TO_HELM,
8626 CAT_FROM_HELM,
8627 M1,
8628 M1_INV,
8629 M2,
8630 M2_INV
8631 };
8632
8633 // Enrichment parameters
8634 const hue_cos1 = -0.02833024015436984,
8635 hue_sin1 = -0.21131429516166544;
8636 const hue_cos2 = 0.2189784817615645,
8637 hue_sin2 = -0.06871898981942523;
8638 const hue_cos3 = 0.005506053349515315,
8639 hue_sin3 = -0.0641329861299175;
8640 const hue_cos4 = -0.053592461436994296,
8641 hue_sin4 = -0.00954137464208059;
8642 const hk_weight = 0.2676231133101982,
8643 hk_power = 0.8934892185255707;
8644 const hk_hue_mod = 0.7173169828841472;
8645 const hk_sin1 = 0.6915224124600773,
8646 hk_cos2 = 0.48647127559605596,
8647 hk_sin2 = 0.9853124591201782;
8648 const L_corr_p1 = 0.5385456675962418,
8649 L_corr_p2 = 0.12508858146241716,
8650 L_corr_p3 = 0.6768950256217603;
8651 const Lh_cos1 = -0.4963251525324449,
8652 Lh_sin1 = -0.09564696283240552;
8653 const lp_dark = -0.029053748937210654,
8654 lp_dark_hcos = 1.3346761652952872,
8655 lp_dark_hsin = -0.1698908144723919;
8656 const cs_cos1 = -0.195370576218515,
8657 cs_sin1 = 0.5330819227283227;
8658 const cs_cos2 = 0.08863325582067766,
8659 cs_sin2 = 0.9365540137751136;
8660 const cs_cos3 = 0.13789738139719568,
8661 cs_sin3 = 0.061650260197979936;
8662 const cs_cos4 = 0.0641970862504494,
8663 cs_sin4 = -0.027401052793571013;
8664 const cp_cos1 = -0.09900209889026965,
8665 cp_sin1 = 0.059635520647228726;
8666 const cp_cos2 = -0.013586499967803128,
8667 cp_sin2 = 0.2253393118474472;
8668 const lc1 = -1.5239477450767043,
8669 lc2 = -1.751157310240011;
8670 const hlc_cos1 = -0.43576378069144767,
8671 hlc_sin1 = 1.060094063845983;
8672 const hlc_cos2 = 0.47931193034584496,
8673 hlc_sin2 = -0.2622579649434462;
8674 const hl_cos1 = 0.13610794232685908,
8675 hl_sin1 = 0.1168702235362288;
8676 const hl_cos2 = -0.01617739641422492,
8677 hl_sin2 = 0.038145638815030566;
8678
8679 // Rigid rotation φ = −28.2°
8680 const PHI = -28.2 * PI / 180;
8681 const ROT_COS = cos(PHI);
8682 const ROT_SIN = sin(PHI);
8683
8684 // ── Pipeline helper functions ──────────────────────────────────────
8685
8686 function hueDelta(h) {
8687 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);
8688 }
8689 function hueDeltaDeriv(h) {
8690 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);
8691 }
8692 function chromaScaleH(h) {
8693 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);
8694 return exp(logS);
8695 }
8696 function lChromaScale(L) {
8697 let dL = L - 0.5;
8698 return exp(clamp(-30, lc1 * dL + lc2 * dL * dL, 30));
8699 }
8700 function hlcScale(h, L) {
8701 let hueFactor = hlc_cos1 * cos(h) + hlc_sin1 * sin(h) + hlc_cos2 * cos(2 * h) + hlc_sin2 * sin(2 * h);
8702 return exp(clamp(-30, (L - 0.5) * hueFactor, 30));
8703 }
8704 function hueLightnessScale(h) {
8705 let logS = hl_cos1 * cos(h) + hl_sin1 * sin(h) + hl_cos2 * cos(2 * h) + hl_sin2 * sin(2 * h);
8706 return exp(logS);
8707 }
8708 function chromaPowerH(h) {
8709 return 1 + cp_cos1 * cos(h) + cp_sin1 * sin(h) + cp_cos2 * cos(2 * h) + cp_sin2 * sin(2 * h);
8710 }
8711 function lCorrectFwd(L, h) {
8712 let t = L * (1 - L);
8713 let result = L + L_corr_p1 * t + L_corr_p2 * t * (0.5 - L) + L_corr_p3 * t * t;
8714 result += t * (Lh_cos1 * cos(h) + Lh_sin1 * sin(h));
8715 return result;
8716 }
8717 function lCorrectInv(L1, h) {
8718 let Lh = Lh_cos1 * cos(h) + Lh_sin1 * sin(h);
8719 let L = L1;
8720 for (let i = 0; i < 15; i++) {
8721 let t = L * (1 - L);
8722 let dt = 1 - 2 * L;
8723 let f = L + (L_corr_p1 + Lh) * t + L_corr_p2 * t * (0.5 - L) + L_corr_p3 * t * t - L1;
8724 let dfdL = 1 + (L_corr_p1 + Lh) * dt + L_corr_p2 * (dt * (0.5 - L) - t) + L_corr_p3 * 2 * t * dt;
8725 if (abs(dfdL) < 1e-10) {
8726 dfdL = 1;
8727 }
8728 L -= f / dfdL;
8729 }
8730 return L;
8731 }
8732 function darkLFwd(L, h) {
8733 let coeff = lp_dark + lp_dark_hcos * cos(h) + lp_dark_hsin * sin(h);
8734 let oml = L < 1 ? 1 - L : 0; // clamp at L=1: identity for L≥1
8735 let g = coeff * L * oml * oml;
8736 return L * exp(clamp(-30, g, 30));
8737 }
8738 function darkLInv(Ln, h) {
8739 let coeff = lp_dark + lp_dark_hcos * cos(h) + lp_dark_hsin * sin(h);
8740 let L = Ln;
8741 for (let i = 0; i < 12; i++) {
8742 let oml = L < 1 ? 1 - L : 0;
8743 let g = coeff * L * oml * oml;
8744 let eg = exp(clamp(-30, g, 30));
8745 let f = L * eg - Ln;
8746 let gp = coeff * oml * (1 - 3 * L);
8747 let fp = eg * (1 + L * gp);
8748 if (abs(fp) < 1e-10) {
8749 fp = 1;
8750 }
8751 L -= f / fp;
8752 }
8753 return L;
8754 }
8755
8756 // ── Color space definition ─────────────────────────────────────────
8757 // Helmlab MetricSpace is the perceptual forward space behind `deltaEHelmlab`.
8758 // Its coordinate system is shaped to maximize ΔE prediction accuracy on
8759 // visual-difference datasets (COMBVD: BFD-P, Witt 1999, RIT-DuPont, Leeds),
8760 // not author convenience. As a result:
8761 // - the ab plane is asymmetric (the metric was fit to directionally
8762 // asymmetric human discrimination thresholds);
8763 // - the L axis exceeds 1 for highly chromatic colors because the
8764 // Helmholtz–Kohlrausch boost is modeled explicitly (high-chroma colors
8765 // appear brighter than equiluminant neutrals);
8766 // - the achromatic axis is not pinned to (0, 0) — the gray axis sits
8767 // slightly off-origin in this coordinate system. Distance is
8768 // translation-invariant, so this does not affect ΔE quality.
8769 //
8770 // For CSS-author-facing color authoring (palettes, gradients, gamut
8771 // mapping), use HelmGen (`helmgen`) instead. This space (`helmlab-metric`)
8772 // is exposed primarily so the metric forward is inspectable for
8773 // debugging, color-science exploration, and as the internal forward used
8774 // by `deltaEHelmlab`.
8775
8776 const fromXYZ = function (xyz) {
8777 // Stage 0: Chromatic adaptation (Color.js D65 → Helmlab D65)
8778 let adapted = multiply_v3_m3x3(xyz, M$9.CAT_TO_HELM);
8779
8780 // Stage 1: XYZ → LMS (M1)
8781 let [lms0, lms1, lms2] = multiply_v3_m3x3(adapted, M$9.M1);
8782
8783 // Stage 2: Power compression (signed)
8784 let c0 = spow(lms0, GAMMA[0]);
8785 let c1 = spow(lms1, GAMMA[1]);
8786 let c2 = spow(lms2, GAMMA[2]);
8787
8788 // Stage 3: LMS_c → Lab_raw (M2)
8789 let [L, a, b] = multiply_v3_m3x3([c0, c1, c2], M$9.M2);
8790
8791 // Stage 3.5: Hue correction (4-harmonic Fourier)
8792 let h = atan2(b, a);
8793 let C = sqrt(a * a + b * b);
8794 let delta = hueDelta(h);
8795 let hNew = h + delta;
8796 a = C * cos(hNew);
8797 b = C * sin(hNew);
8798
8799 // Stage 3.7: Helmholtz-Kohlrausch correction
8800 let Cr = sqrt(a * a + b * b);
8801 let hkBoost = hk_weight * pow(Cr, clamp(0.01, hk_power, 10));
8802 let hr = atan2(b, a);
8803 let factor = 1 + hk_hue_mod * cos(hr) + hk_sin1 * sin(hr) + hk_cos2 * cos(2 * hr) + hk_sin2 * sin(2 * hr);
8804 L += hkBoost * factor;
8805
8806 // Stage 4: Cubic L correction (with hue modulation)
8807 h = atan2(b, a);
8808 L = lCorrectFwd(L, h);
8809
8810 // Stage 4.5: Dark L compression
8811 h = atan2(b, a);
8812 L = darkLFwd(L, h);
8813
8814 // Stage 5: Hue-dependent chroma scaling
8815 h = atan2(b, a);
8816 let cs = chromaScaleH(h);
8817 a *= cs;
8818 b *= cs;
8819
8820 // Stage 5.5: Nonlinear chroma power
8821 h = atan2(b, a);
8822 C = sqrt(a * a + b * b);
8823 let p = chromaPowerH(h);
8824 let Cn = C > 0 ? pow(C, p) : 0;
8825 a = Cn * cos(h);
8826 b = Cn * sin(h);
8827
8828 // Stage 6: L-dependent chroma scaling
8829 let T = lChromaScale(L);
8830 a *= T;
8831 b *= T;
8832
8833 // Stage 6.5: HLC interaction
8834 h = atan2(b, a);
8835 let hlcS = hlcScale(h, L);
8836 a *= hlcS;
8837 b *= hlcS;
8838
8839 // Stage 8: Hue-dependent lightness scaling
8840 h = atan2(b, a);
8841 L *= hueLightnessScale(h);
8842
8843 // Stage 11: Rigid rotation (φ = −28.2°)
8844 let aRot = a * ROT_COS - b * ROT_SIN;
8845 let bRot = a * ROT_SIN + b * ROT_COS;
8846 return [L, aRot, bRot];
8847 };
8848 const toXYZ = function (lab) {
8849 let [L, a, b] = lab;
8850
8851 // Undo Stage 11: rotation
8852 let aUn = a * ROT_COS + b * ROT_SIN;
8853 let bUn = -a * ROT_SIN + b * ROT_COS;
8854 a = aUn;
8855 b = bUn;
8856
8857 // Undo Stage 8: hue-dep lightness
8858 let h = atan2(b, a);
8859 L /= hueLightnessScale(h);
8860
8861 // Undo Stage 6.5: HLC
8862 h = atan2(b, a);
8863 let hlcS = hlcScale(h, L);
8864 a /= hlcS;
8865 b /= hlcS;
8866
8867 // Undo Stage 6: L-dep chroma
8868 let T = lChromaScale(L);
8869 a /= T;
8870 b /= T;
8871
8872 // Undo Stage 5.5: chroma power
8873 h = atan2(b, a);
8874 let C = sqrt(a * a + b * b);
8875 let p = chromaPowerH(h);
8876 let Co = C > 0 ? pow(C, 1 / p) : 0;
8877 a = Co * cos(h);
8878 b = Co * sin(h);
8879
8880 // Undo Stage 5: chroma scaling
8881 h = atan2(b, a);
8882 let cs = chromaScaleH(h);
8883 a /= cs;
8884 b /= cs;
8885
8886 // Undo Stage 4.5: dark L
8887 h = atan2(b, a);
8888 L = darkLInv(L, h);
8889
8890 // Undo Stage 4: cubic L
8891 h = atan2(b, a);
8892 L = lCorrectInv(L, h);
8893
8894 // Undo Stage 3.7: H-K
8895 let Cr = sqrt(a * a + b * b);
8896 let hkBoost = hk_weight * pow(Cr, clamp(0.01, hk_power, 10));
8897 let hr = atan2(b, a);
8898 let factor = 1 + hk_hue_mod * cos(hr) + hk_sin1 * sin(hr) + hk_cos2 * cos(2 * hr) + hk_sin2 * sin(2 * hr);
8899 L -= hkBoost * factor;
8900
8901 // Undo Stage 3.5: hue correction (Newton iteration)
8902 let hOut = atan2(b, a);
8903 C = sqrt(a * a + b * b);
8904 let hRaw = hOut;
8905 for (let i = 0; i < 8; i++) {
8906 let f = hRaw + hueDelta(hRaw) - hOut;
8907 let fp = 1 + hueDeltaDeriv(hRaw);
8908 if (abs(fp) < 1e-10) {
8909 fp = 1;
8910 }
8911 hRaw -= f / fp;
8912 }
8913 a = C * cos(hRaw);
8914 b = C * sin(hRaw);
8915
8916 // Undo Stage 3: Lab → LMS_c (M2_inv)
8917 let [lc0, lc1, lc2] = multiply_v3_m3x3([L, a, b], M$9.M2_INV);
8918
8919 // Undo Stage 2: power compression
8920 let l0 = spow(lc0, INV_GAMMA[0]);
8921 let l1 = spow(lc1, INV_GAMMA[1]);
8922 let l2 = spow(lc2, INV_GAMMA[2]);
8923
8924 // Undo Stage 1: LMS → XYZ (M1_inv)
8925 let xyz = multiply_v3_m3x3([l0, l1, l2], M$9.M1_INV);
8926
8927 // Undo Stage 0: Chromatic adaptation (Helmlab D65 → Color.js D65)
8928 return multiply_v3_m3x3(xyz, M$9.CAT_FROM_HELM);
8929 };
8930 var helmlab = new ColorSpace({
8931 id: "helmlab-metric",
8932 name: "Helmlab MetricSpace",
8933 cssId: "--helmlab-metric",
8934 coords: {
8935 l: {
8936 refRange: [0, 1.6],
8937 name: "Lightness"
8938 },
8939 a: {
8940 refRange: [-1.5, 1.5]
8941 },
8942 b: {
8943 refRange: [-1.5, 1.5]
8944 }
8945 },
8946 white: "D65",
8947 base: XYZ_D65,
8948 M: M$9,
8949 fromBase(xyz) {
8950 return fromXYZ(xyz);
8951 },
8952 toBase(lab) {
8953 return toXYZ(lab);
8954 }
8955 });
8956
8957 // Helmlab MetricSpace weighted distance (v21, 72 params).
8958 // Optimized on COMBVD human color-difference judgments.
8959 //
8960 // Formula:
8961 // SL = 1 + sl * (L_avg - 0.5)²
8962 // SC = 1 + sc * C_avg
8963 // raw = (ΔL²/SL² + wC * Δab²/SC²) ^ (p/2)
8964 // compressed = raw / (1 + c * raw)
8965 // ΔE = compressed ^ q
8966
8967 const sl = -0.9155125151657894;
8968 const sc = 2.9268353744941558;
8969 const wC = 3.966003089807536;
8970 const p = 1.9737081170404969;
8971 const compress = 52.473130649294724;
8972 const q = 0.47897301074925214;
8973
8974 /**
8975 * @param {import("../types.js").ColorTypes} color
8976 * @param {import("../types.js").ColorTypes} sample
8977 * @returns {number}
8978 */
8979 function deltaEHelmlab (color, sample) {
8980 [color, sample] = getColor([color, sample]);
8981 let [L1, a1, b1] = helmlab.from(color);
8982 let [L2, a2, b2] = helmlab.from(sample);
8983 let ΔL = L1 - L2;
8984 let Δa = a1 - a2;
8985 let Δb = b1 - b2;
8986
8987 // Pair-dependent weighting
8988 let Lavg = (L1 + L2) * 0.5;
8989 let SL = 1 + sl * (Lavg - 0.5) ** 2;
8990 let C1 = Math.sqrt(a1 ** 2 + b1 ** 2);
8991 let C2 = Math.sqrt(a2 ** 2 + b2 ** 2);
8992 let Cavg = (C1 + C2) * 0.5;
8993 let SC = 1 + sc * Cavg;
8994
8995 // Weighted Minkowski distance
8996 let raw = (ΔL ** 2 / SL ** 2 + wC * (Δa ** 2 + Δb ** 2) / SC ** 2) ** (p / 2);
8997
8998 // Monotonic compression
8999 let compressed = raw / (1 + compress * raw);
9000 return compressed ** q;
9001 }
9002
9003 /**
9004 * @packageDocumentation
9005 * This module defines all the builtin deltaE methods.
9006 */
9007 var deltaEMethods = {
9008 deltaE76,
9009 deltaECMC,
9010 deltaE2000,
9011 deltaEJz,
9012 deltaEITP,
9013 deltaEOK,
9014 deltaEOK2,
9015 deltaEHCT,
9016 deltaEHelmlab
9017 };
9018
9019 /** @typedef {keyof typeof import("./index.js").default extends `deltaE${infer Method}` ? Method : string} Methods */
9020
9021 /** @import { ColorTypes, PlainColorObject } from "./types.js" */
9022
9023 // Type re-exports
9024 /** @typedef {import("./types.js").ToGamutOptions} ToGamutOptions */
9025
9026 /**
9027 * Calculate the epsilon to 2 degrees smaller than the specified JND.
9028 * @param {number} jnd The target "just noticeable difference".
9029 * @returns {number}
9030 */
9031 function calcEpsilon(jnd) {
9032 // Calculate the epsilon to 2 degrees smaller than the specified JND.
9033
9034 const order = !jnd ? 0 : Math.floor(Math.log10(Math.abs(jnd)));
9035 // Limit to an arbitrary value to ensure value is never too small and causes infinite loops.
9036 return Math.max(parseFloat(`1e${order - 2}`), 1e-6);
9037 }
9038 const GMAPPRESET = {
9039 hct: {
9040 method: "hct.c",
9041 jnd: 2,
9042 deltaEMethod: "hct",
9043 blackWhiteClamp: {}
9044 },
9045 "hct-tonal": {
9046 method: "hct.c",
9047 jnd: 0,
9048 deltaEMethod: "hct",
9049 blackWhiteClamp: {
9050 channel: "hct.t",
9051 min: 0,
9052 max: 100
9053 }
9054 }
9055 };
9056
9057 /**
9058 * Force coordinates to be in gamut of a certain color space.
9059 * Mutates the color it is passed.
9060 * @overload
9061 * @param {ColorTypes} color
9062 * @param {ToGamutOptions} [options]
9063 * @returns {PlainColorObject}
9064 */
9065 /**
9066 * @overload
9067 * @param {ColorTypes} color
9068 * @param {string} [space]
9069 * @returns {PlainColorObject}
9070 */
9071 /**
9072 * @param {ColorTypes} color
9073 * @param {string & Partial<ToGamutOptions> | ToGamutOptions} [space]
9074 * @returns {PlainColorObject}
9075 */
9076 function toGamut(color, {
9077 method = defaults.gamut_mapping,
9078 space = undefined,
9079 deltaEMethod = "",
9080 jnd = 2,
9081 blackWhiteClamp = undefined
9082 } = {}) {
9083 color = getColor(color);
9084 if (isString(arguments[1])) {
9085 space = arguments[1];
9086 } else if (!space) {
9087 space = color.space;
9088 }
9089 space = ColorSpace.get(space);
9090
9091 // 3 spaces:
9092 // color.space: current color space
9093 // space: space whose gamut we are mapping to
9094 // mapSpace: space with the coord we're reducing
9095
9096 if (inGamut(color, space, {
9097 epsilon: 0
9098 })) {
9099 return /** @type {PlainColorObject} */color;
9100 }
9101 let spaceColor;
9102 if (method === "css") {
9103 spaceColor = toGamutCSS(color, {
9104 space
9105 });
9106 } else if (method === "raytrace") {
9107 spaceColor = toGamutRayTrace(color, {
9108 space
9109 });
9110 } else {
9111 if (method !== "clip") {
9112 if (Object.prototype.hasOwnProperty.call(GMAPPRESET, method)) {
9113 ({
9114 method,
9115 jnd,
9116 deltaEMethod,
9117 blackWhiteClamp
9118 } = GMAPPRESET[method]);
9119 }
9120
9121 // Get the correct delta E method
9122 let de = deltaE2000;
9123 if (deltaEMethod !== "") {
9124 for (let m in deltaEMethods) {
9125 if ("deltae" + deltaEMethod.toLowerCase() === m.toLowerCase()) {
9126 de = deltaEMethods[m];
9127 break;
9128 }
9129 }
9130 }
9131 if (jnd === 0) {
9132 jnd = 1e-16;
9133 }
9134 let clipped = toGamut(to(color, space), {
9135 method: "clip",
9136 space
9137 });
9138 if (de(color, clipped) > jnd) {
9139 // Clamp to SDR white and black if required
9140 if (blackWhiteClamp && Object.keys(blackWhiteClamp).length === 3) {
9141 let channelMeta = ColorSpace.resolveCoord(blackWhiteClamp.channel);
9142 let channel = get(to(color, channelMeta.space), channelMeta.id);
9143 if (isNone(channel)) {
9144 channel = 0;
9145 }
9146 if (channel >= blackWhiteClamp.max) {
9147 return to({
9148 space: "xyz-d65",
9149 coords: WHITES["D65"]
9150 }, color.space);
9151 } else if (channel <= blackWhiteClamp.min) {
9152 return to({
9153 space: "xyz-d65",
9154 coords: [0, 0, 0]
9155 }, color.space);
9156 }
9157 }
9158
9159 // Reduce a coordinate of a certain color space until the color is in gamut
9160 let coordMeta = ColorSpace.resolveCoord(method);
9161 let mapSpace = coordMeta.space;
9162 let coordId = coordMeta.id;
9163 let mappedColor = to(color, mapSpace);
9164 // If we were already in the mapped color space, we need to resolve undefined channels
9165 mappedColor.coords.forEach((c, i) => {
9166 if (isNone(c)) {
9167 mappedColor.coords[i] = 0;
9168 }
9169 });
9170 let bounds = coordMeta.range || coordMeta.refRange;
9171 let min = bounds[0];
9172 let ε = calcEpsilon(jnd);
9173 let low = min;
9174 let high = get(mappedColor, coordId);
9175 while (high - low > ε) {
9176 let clipped = clone(mappedColor);
9177 clipped = toGamut(clipped, {
9178 space,
9179 method: "clip"
9180 });
9181 let deltaE = de(mappedColor, clipped);
9182 if (deltaE - jnd < ε) {
9183 low = get(mappedColor, coordId);
9184 } else {
9185 high = get(mappedColor, coordId);
9186 }
9187 set(mappedColor, coordId, (low + high) / 2);
9188 }
9189 spaceColor = to(mappedColor, space);
9190 } else {
9191 spaceColor = clipped;
9192 }
9193 } else {
9194 spaceColor = to(color, space);
9195 }
9196 if (method === "clip" ||
9197 // Dumb coord clipping
9198 // finish off smarter gamut mapping with clip to get rid of ε, see #17
9199 !inGamut(spaceColor, space, {
9200 epsilon: 0
9201 })) {
9202 let bounds = Object.values(space.coords).map(c => c.range || []);
9203 spaceColor.coords = /** @type {[number, number, number]} */
9204 spaceColor.coords.map((c, i) => {
9205 let [min, max] = bounds[i];
9206 if (min !== undefined) {
9207 c = Math.max(min, c);
9208 }
9209 if (max !== undefined) {
9210 c = Math.min(c, max);
9211 }
9212 return c;
9213 });
9214 }
9215 }
9216 if (space !== color.space) {
9217 spaceColor = to(spaceColor, color.space);
9218 }
9219 color.coords = spaceColor.coords;
9220 return /** @type {PlainColorObject} */color;
9221 }
9222
9223 /** @type {"color"} */
9224 toGamut.returns = "color";
9225
9226 /**
9227 * The reference colors to be used if lightness is out of the range 0-1 in the
9228 * `Oklch` space. These are created in the `Oklab` space, as it is used by the
9229 * DeltaEOK calculation, so it is guaranteed to be imported.
9230 * @satisfies {Record<string, ColorTypes>}
9231 */
9232 const COLORS = {
9233 WHITE: {
9234 space: Oklab,
9235 coords: [1, 0, 0],
9236 alpha: 1
9237 },
9238 BLACK: {
9239 space: Oklab,
9240 coords: [0, 0, 0],
9241 alpha: 1
9242 }
9243 };
9244
9245 /**
9246 * Given a color `origin`, returns a new color that is in gamut using
9247 * the CSS Gamut Mapping Algorithm. If `space` is specified, it will be in gamut
9248 * in `space`, and returned in `space`. Otherwise, it will be in gamut and
9249 * returned in the color space of `origin`.
9250 * @param {ColorTypes} origin
9251 * @param {{ space?: string | ColorSpace | undefined }} options
9252 * @returns {PlainColorObject}
9253 */
9254 function toGamutCSS(origin, {
9255 space
9256 } = {}) {
9257 const JND = 0.02;
9258 const ε = 0.0001;
9259 origin = getColor(origin);
9260 if (!space) {
9261 space = origin.space;
9262 }
9263 space = ColorSpace.get(space);
9264 if (space.isUnbounded) {
9265 return to(origin, space);
9266 }
9267 const origin_OKLCH = to(origin, OKLCH);
9268 let L = origin_OKLCH.coords[0];
9269
9270 // return media white or black, if lightness is out of range
9271 if (L >= 1) {
9272 const white = to(COLORS.WHITE, space);
9273 white.alpha = origin.alpha;
9274 return to(white, space);
9275 }
9276 if (L <= 0) {
9277 const black = to(COLORS.BLACK, space);
9278 black.alpha = origin.alpha;
9279 return to(black, space);
9280 }
9281 if (inGamut(origin_OKLCH, space, {
9282 epsilon: 0
9283 })) {
9284 return to(origin_OKLCH, space);
9285 }
9286 function clip(_color) {
9287 const destColor = to(_color, space);
9288 const spaceCoords = Object.values(/** @type {ColorSpace} */space.coords);
9289 destColor.coords = /** @type {[number, number, number]} */
9290 destColor.coords.map((coord, index) => {
9291 if ("range" in spaceCoords[index]) {
9292 const [min, max] = spaceCoords[index].range;
9293 return clamp(min, coord, max);
9294 }
9295 return coord;
9296 });
9297 return destColor;
9298 }
9299 let min = 0;
9300 let max = origin_OKLCH.coords[1];
9301 let min_inGamut = true;
9302 let current = clone(origin_OKLCH);
9303 let clipped = clip(current);
9304 let E = deltaEOK(clipped, current);
9305 if (E < JND) {
9306 return clipped;
9307 }
9308 while (max - min > ε) {
9309 const chroma = (min + max) / 2;
9310 current.coords[1] = chroma;
9311 if (min_inGamut && inGamut(current, space, {
9312 epsilon: 0
9313 })) {
9314 min = chroma;
9315 } else {
9316 clipped = clip(current);
9317 E = deltaEOK(clipped, current);
9318 if (E < JND) {
9319 if (JND - E < ε) {
9320 break;
9321 } else {
9322 min_inGamut = false;
9323 min = chroma;
9324 }
9325 } else {
9326 max = chroma;
9327 }
9328 }
9329 }
9330 return clipped;
9331 }
9332
9333 /**
9334 * Given `start` and `end` coordinates of a 3D ray and a `bmin` and `bmax` bounding box,
9335 * find the intersection of the ray and box. Return an empty list if no intersect is found.`
9336 * @param {[number, number, number]} start
9337 * @param {[number, number, number]} end
9338 * @param {[number, number, number]} bmin
9339 * @param {[number, number, number]} bmax
9340 * @returns {[number, number, number] | []}
9341 */
9342 function raytrace_box(start, end, bmin = [0, 0, 0], bmax = [1, 1, 1]) {
9343 // Use slab method to detect intersection of ray and box and return intersect.
9344 // https://en.wikipedia.org/wiki/Slab_method
9345
9346 // Calculate whether there was a hit
9347 let tfar = Infinity;
9348 let tnear = -Infinity;
9349 let direction = [];
9350 for (let i = 0; i < 3; i++) {
9351 const a = start[i];
9352 const b = end[i];
9353 const d = b - a;
9354 const bn = bmin[i];
9355 const bx = bmax[i];
9356 direction.push(d);
9357
9358 // Non parallel cases
9359 // 1e-12 for 64 bit unit types and 1e-6 for 32 bit unit types
9360 if (Math.abs(d) > 1e-12) {
9361 const inv_d = 1 / d;
9362 const t1 = (bn - a) * inv_d;
9363 const t2 = (bx - a) * inv_d;
9364 tnear = Math.max(Math.min(t1, t2), tnear);
9365 tfar = Math.min(Math.max(t1, t2), tfar);
9366 }
9367
9368 // Impossible parallel case
9369 else if (a < bn || a > bx) {
9370 return [];
9371 }
9372 }
9373
9374 // No hit
9375 if (tnear > tfar || tfar < 0) {
9376 return [];
9377 }
9378
9379 // Favor the intersection first in the direction start -> end
9380 if (tnear < 0) {
9381 tnear = tfar;
9382 }
9383
9384 // A point, or something approaching a single point where start and end are the same.
9385 if (!isFinite(tnear)) {
9386 return [];
9387 }
9388
9389 // Calculate nearest intersection via interpolation
9390 return [start[0] + direction[0] * tnear, start[1] + direction[1] * tnear, start[2] + direction[2] * tnear];
9391 }
9392
9393 /**
9394 * Given a color `origin`, returns a new color that is in gamut using
9395 * the CSS Ray Trace Gamut Mapping Algorithm. If `space` is specified,
9396 * it will be in gamut `space`, and returned in `space`. Otherwise,
9397 * it will be in gamut and returned in the color space of `origin`.
9398 * @param {ColorTypes} origin
9399 * @param {{ space?: string | ColorSpace | undefined }} options
9400 * @returns {PlainColorObject}
9401 */
9402 function toGamutRayTrace(origin, {
9403 space
9404 } = {}) {
9405 origin = getColor(origin);
9406 if (!space) {
9407 space = origin.space;
9408 }
9409 space = ColorSpace.get(space);
9410
9411 // If the space is already in gamut, stop.
9412 if (space.isUnbounded) {
9413 return to(origin, space);
9414 }
9415
9416 // Get the OkLCh coordinates.
9417 let oklchOrigin = to(origin, OKLCH);
9418 let [lightness, chroma, hue] = oklchOrigin.coords;
9419
9420 // Return white or black if color's lightness exceeds the SDR range.
9421 if (lightness >= 1) {
9422 const white = to(COLORS.WHITE, space);
9423 white.alpha = origin.alpha;
9424 return to(white, space);
9425 } else if (lightness <= 0) {
9426 const black = to(COLORS.BLACK, space);
9427 black.alpha = origin.alpha;
9428 return to(black, space);
9429 }
9430
9431 // Get a copy of the origin color as the RGB target space.
9432 const originSpace = space;
9433 const rGamut = space.rgbGamut;
9434 if (rGamut !== undefined) {
9435 space = rGamut;
9436 }
9437 if (!isInstance(space, RGBColorSpace)) {
9438 throw Error('An RGB gamut is required');
9439 }
9440
9441 // Get SDR bounds. Some HDR spaces have headroom, so reduce max to SDR range.
9442 let [mn, mx] = Object.values(space.coords)[0].range;
9443 let max = /** @type {[number, number, number]} */[mx, mx, mx];
9444
9445 // See if we have a linear version of the color space
9446 const lGamut = space.linearGamut;
9447 if (lGamut !== undefined) {
9448 // Recalculate minimum and maximum relative to the linear space
9449 let temp = to({
9450 space: space,
9451 coords: max,
9452 alpha: origin.alpha
9453 }, lGamut);
9454 mx = temp.coords[0];
9455 max = /** @type {[number, number, number]} */[mx, mx, mx];
9456 space = lGamut;
9457 mn = Object.values(space.coords)[0].range[0];
9458 }
9459 let min = /** @type {[number, number, number]} */[mn, mn, mn];
9460 let rgbOrigin = to(oklchOrigin, space);
9461 if (!rgbOrigin.coords.every(x => mn <= x && x <= mx)) {
9462 // If this were performed within a perceptual space like CAM16, which has achromatics that do not align
9463 // with the RGB achromatic line, projecting the color onto the RGB achromatic line may be preferable,
9464 // but since OkLCh's achromatics align with all CSS RGB spaces, just set chroma to zero.
9465 let anchor = to({
9466 space: OKLCH,
9467 coords: [lightness, 0, hue]
9468 }, space).coords;
9469
9470 // Calculate bounds to adjust the anchor closer to the gamut surface.
9471 // We don't want to make the ray too short, so offset some amount from the low and high range.
9472 // 1e-12 for 64 bit unit types and 1e-6 for 32 bit unit types.
9473 const low = mn + 1e-12;
9474 const high = mx - 1e-12;
9475
9476 // Cast a ray from the zero chroma color to the target color.
9477 // Trace the line to the RGB cube edge and find where it intersects.
9478 // Correct L and h within the perceptual OkLCh after each attempt.
9479 let last = rgbOrigin.coords;
9480 for (let i = 0; i < 4; i++) {
9481 if (i) {
9482 // For constant luminance, we correct the color by simply setting lightness and hue to
9483 // match the original color. In a non constant luminance reduction, it is better to
9484 // project the color onto the reduction path vector.
9485 const oklchColor = to(rgbOrigin, OKLCH);
9486 oklchColor.coords[0] = lightness;
9487 oklchColor.coords[2] = hue;
9488 rgbOrigin = to(oklchColor, space);
9489 }
9490 // Cast a ray from the achromatic anchor to the RGB target and find the gamut intersection.
9491 const intersection = raytrace_box(anchor, rgbOrigin.coords, min, max);
9492
9493 // If we cannot find an intersection, reset to last successful iteration of the color.
9494 // In OkLCh, this is only likely to happen if our ray gets too small, in that case, it is time to stop.
9495 if (intersection.length === 0) {
9496 rgbOrigin.coords = [...last];
9497 break;
9498 }
9499
9500 // Adjust anchor point closer to surface, when possible, to improve results for some spaces.
9501 if (i && rgbOrigin.coords.every(x => low < x && x < high)) {
9502 anchor = [...rgbOrigin.coords];
9503 }
9504
9505 // If we have an intersection, update the color.
9506 last = /** @type {[number, number, number]} */intersection;
9507 rgbOrigin.coords = [...intersection];
9508 }
9509 }
9510
9511 // Convert to the original, specified gamut
9512 rgbOrigin = to(rgbOrigin, originSpace);
9513 const spaceCoords = Object.values(/** @type {ColorSpace} */originSpace.coords);
9514
9515 // Remove noise from floating point math by clipping
9516 rgbOrigin.coords = /** @type {[number, number, number]} */
9517 rgbOrigin.coords.map((coord, index) => {
9518 if ("range" in spaceCoords[index]) {
9519 const [lower, upper] = spaceCoords[index].range;
9520 return clamp(lower, coord, upper);
9521 }
9522 return coord;
9523 });
9524 return rgbOrigin;
9525 }
9526
9527 /** @import { SpaceOptions } from "./ColorSpace.js" */
9528
9529 /**
9530 * A color space whose chroma-like coordinate is expressed relative to an RGB gamut: chroma = 1 is
9531 * the most colorful in-gamut color for the rest of the coordinates, so any chroma in [0, 1] stays
9532 * in gamut. The reduced coordinate (`chroma`, default `"c"`) is rescaled against `gamutSpace`; every
9533 * other coordinate is inherited unchanged from `base`. Works for any base whose chroma coordinate
9534 * brings the color into gamut as it is reduced (e.g. OKLCh, LCH).
9535 */
9536 class GamutRelativeColorSpace extends ColorSpace {
9537 /**
9538 * @param {SpaceOptions & { gamutSpace: string | ColorSpace, chroma?: string }} options
9539 * Requires `base` (the source space) and `gamutSpace` (the RGB gamut). `chroma` names the
9540 * coordinate to rescale (default `"c"`).
9541 */
9542 constructor(options) {
9543 var _options$chroma, _options$coords, _options$formats;
9544 let base = ColorSpace.get(options.base);
9545 let chroma = (_options$chroma = options.chroma) !== null && _options$chroma !== void 0 ? _options$chroma : "c";
9546 let ids = Object.keys(base.coords);
9547 let chromaIndex = ids.indexOf(chroma);
9548 if (chromaIndex === -1) {
9549 throw new TypeError(`GamutRelativeColorSpace needs a "${chroma}" coordinate, got ${base.id}`);
9550 }
9551
9552 // Inherit the base's coords; the reduced coordinate becomes a 0–1 fraction of its gamut maximum
9553 let coords = Object.fromEntries(Object.entries(base.coords).map(([id, meta]) => [id, {
9554 ...meta
9555 }]));
9556 coords[chroma].range = [0, 1];
9557 delete coords[chroma].refRange;
9558 (_options$coords = options.coords) !== null && _options$coords !== void 0 ? _options$coords : options.coords = coords;
9559
9560 // Serialize the reduced coordinate and any other 0–1 coordinate as percentages; angles as angles
9561 (_options$formats = options.formats) !== null && _options$formats !== void 0 ? _options$formats : options.formats = {
9562 color: {
9563 coords: ids.map(id => {
9564 var _ref, _base$coords$id$range;
9565 if (base.coords[id].type === "angle") {
9566 return "<number> | <angle>";
9567 }
9568 let [min, max] = (_ref = (_base$coords$id$range = base.coords[id].range) !== null && _base$coords$id$range !== void 0 ? _base$coords$id$range : base.coords[id].refRange) !== null && _ref !== void 0 ? _ref : [];
9569 let pctFirst = id === chroma || min === 0 && max === 1;
9570 return pctFirst ? "<percentage> | <number>" : "<number> | <percentage>";
9571 })
9572 }
9573 };
9574 super(options);
9575 this.chromaIndex = chromaIndex;
9576 this.method = `${base.id}.${chroma}`;
9577
9578 // A chroma that is out of gamut at every lightness and hue: the gamut's most saturated corner
9579 // (its primaries/secondaries are its chroma maxima) plus headroom. Seeding the gamut search
9580 // from here lands on the first in-gamut crossing — the highest contiguous in-gamut chroma —
9581 // and avoids clamping wide gamuts (e.g. Rec.2020 exceeds OKLCh's nominal 0.4 chroma).
9582 // prettier-ignore
9583 let corners = /** @type {[number, number, number][]} */
9584 [[0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0]];
9585 this.oogChroma = 1.01 * Math.max(...corners.map(rgb => base.from(this.gamutSpace, rgb)[this.chromaIndex] || 0));
9586 }
9587
9588 /**
9589 * The highest in-gamut value of the reduced coordinate for the given coordinates. The reduced
9590 * coordinate's own value is ignored; the others determine the result.
9591 * @param {number[]} coords
9592 * @returns {number}
9593 */
9594 maxChroma(coords) {
9595 let seed = /** @type {[number, number, number]} */[...coords];
9596 seed[this.chromaIndex] = this.oogChroma;
9597 return toGamut({
9598 space: this.base,
9599 coords: seed
9600 },
9601 // deltaE OK stays sensitive near black, where deltaE 2000 is too forgiving of excess chroma
9602 {
9603 space: this.gamutSpace,
9604 method: this.method,
9605 deltaEMethod: "OK",
9606 jnd: 0
9607 }).coords[this.chromaIndex];
9608 }
9609 toBase(coords) {
9610 coords = [...coords];
9611 if (coords.some((c, i) => i !== this.chromaIndex && isNone(c))) {
9612 // chroma is a fraction of maxChroma(the other coords); without them all it is undefined
9613 if (coords[this.chromaIndex] !== 0) {
9614 coords[this.chromaIndex] = null;
9615 }
9616 } else if (!isNone(coords[this.chromaIndex])) {
9617 coords[this.chromaIndex] *= this.maxChroma(coords);
9618 }
9619 return coords;
9620 }
9621 fromBase(coords) {
9622 coords = [...coords];
9623 if (coords.some((c, i) => i !== this.chromaIndex && isNone(c))) {
9624 if (coords[this.chromaIndex] !== 0) {
9625 coords[this.chromaIndex] = null;
9626 }
9627 } else if (!isNone(coords[this.chromaIndex])) {
9628 let cMax = this.maxChroma(coords);
9629 coords[this.chromaIndex] = cMax ? coords[this.chromaIndex] / cMax : 0;
9630 }
9631 return coords;
9632 }
9633 }
9634
9635 /** @import { ColorTypes, PlainColorObject } from "./types.js" */
9636
9637 // Type re-exports
9638 /** @typedef {import("./types.js").TryColorOptions} TryColorOptions */
9639
9640 /**
9641 * Resolves a color reference (object or string) to a plain color object, or `null` if resolution fails.
9642 * Can resolve more complex CSS colors (e.g. relative colors, `calc()`, CSS variables, `color-mix()`, etc.) through the DOM.
9643 *
9644 * @overload
9645 * @param {ColorTypes} color
9646 * @param {TryColorOptions} [options]
9647 * @returns {PlainColorObject | null}
9648 */
9649 /**
9650 * @overload
9651 * @param {ColorTypes[]} color
9652 * @param {TryColorOptions} [options]
9653 * @returns {(PlainColorObject | null)[]}
9654 */
9655 function tryColor(color, options = {}) {
9656 if (Array.isArray(color)) {
9657 return color.map(c => tryColor(c, options));
9658 }
9659 let {
9660 cssProperty = "background-color",
9661 element,
9662 ...getColorOptions
9663 } = options;
9664 let error = null;
9665 try {
9666 return getColor(color, getColorOptions);
9667 } catch (e) {
9668 error = e;
9669 }
9670 let {
9671 CSS,
9672 getComputedStyle
9673 } = globalThis;
9674 if (isString(color) && element && CSS && getComputedStyle) {
9675 // Try resolving the color using the DOM, if supported in CSS
9676 if (CSS.supports(cssProperty, color)) {
9677 let previousValue = element.style[cssProperty];
9678 if (color !== previousValue) {
9679 element.style[cssProperty] = color;
9680 }
9681 let computedColor = getComputedStyle(element).getPropertyValue(cssProperty);
9682 if (color !== previousValue) {
9683 element.style[cssProperty] = previousValue;
9684 }
9685 if (computedColor !== color) {
9686 // getComputedStyle() changed the color, try again
9687 try {
9688 return getColor(computedColor, getColorOptions);
9689 } catch (e) {
9690 error = e;
9691 }
9692 } else {
9693 // Still not resolved
9694 error = {
9695 message: "Color value is a valid CSS color, but it could not be resolved :("
9696 };
9697 }
9698 }
9699 }
9700
9701 // If we're here, we failed to resolve the color
9702 if (options.errorMeta) {
9703 options.errorMeta.error = error;
9704 }
9705 return null;
9706 }
9707
9708 /** @import { ColorTypes, ParseOptions, PlainColorObject } from "./types.js" */
9709
9710 // Type re-exports
9711 /** @typedef {import("./types.js").SerializeOptions} SerializeOptions */
9712
9713 /**
9714 * Generic toString() method, outputs a color(spaceId ...coords) function, a functional syntax, or custom formats defined by the color space
9715 * @param {ColorTypes} color
9716 * @param {SerializeOptions & Record<string, any>} options
9717 * @returns {string}
9718 */
9719 function serialize(color, options = {}) {
9720 let {
9721 precision = defaults.precision,
9722 format,
9723 inGamut: inGamut$1 = true,
9724 coords: coordFormat,
9725 alpha: alphaFormat,
9726 commas
9727 } = options;
9728 let ret;
9729 let colorWithMeta = /** @type {PlainColorObject & ParseOptions} */getColor(color);
9730 let formatId = format;
9731 let parseMeta = colorWithMeta.parseMeta;
9732 if (parseMeta && !format) {
9733 var _coordFormat, _alphaFormat, _commas;
9734 if (parseMeta.format.canSerialize()) {
9735 format = parseMeta.format;
9736 formatId = parseMeta.formatId;
9737 }
9738 (_coordFormat = coordFormat) !== null && _coordFormat !== void 0 ? _coordFormat : coordFormat = parseMeta.types;
9739 (_alphaFormat = alphaFormat) !== null && _alphaFormat !== void 0 ? _alphaFormat : alphaFormat = parseMeta.alphaType;
9740 (_commas = commas) !== null && _commas !== void 0 ? _commas : commas = parseMeta.commas;
9741 }
9742 if (formatId) {
9743 var _colorWithMeta$space$;
9744 // A format is explicitly specified
9745 format = (_colorWithMeta$space$ = colorWithMeta.space.getFormat(format)) !== null && _colorWithMeta$space$ !== void 0 ? _colorWithMeta$space$ : ColorSpace.findFormat(formatId);
9746 }
9747 if (!format) {
9748 var _colorWithMeta$space$2;
9749 // No format specified, or format not found
9750 format = (_colorWithMeta$space$2 = colorWithMeta.space.getFormat("default")) !== null && _colorWithMeta$space$2 !== void 0 ? _colorWithMeta$space$2 : ColorSpace.DEFAULT_FORMAT;
9751 formatId = format.name;
9752 }
9753 if (format && format.space && format.space !== colorWithMeta.space) {
9754 // Format specified belongs to a different color space,
9755 // need to convert to it first
9756 colorWithMeta = to(colorWithMeta, format.space);
9757 }
9758
9759 // The assignment to coords and inGamut needs to stay in the order they are now
9760 // The order of the assignment was changed as a workaround for a bug in Next.js
9761 // See this issue for details: https://github.com/color-js/color.js/issues/260
9762
9763 let coords = colorWithMeta.coords.slice(); // clone so we can manipulate it
9764
9765 inGamut$1 || (inGamut$1 = format.toGamut);
9766 if (inGamut$1 && !inGamut(colorWithMeta)) {
9767 // FIXME what happens if the color contains none values?
9768 coords = toGamut(clone(colorWithMeta), inGamut$1 === true ? undefined : inGamut$1).coords;
9769 }
9770 if (format.type === "custom") {
9771 if (format.serialize) {
9772 ret = format.serialize(coords, colorWithMeta.alpha, options);
9773 } else {
9774 throw new TypeError(`format ${formatId} can only be used to parse colors, not for serialization`);
9775 }
9776 } else {
9777 var _alphaFormat$type, _alphaFormat2, _alphaFormat3, _alphaFormat4, _commas2;
9778 // Functional syntax
9779 let name = format.name || "color";
9780 let args = format.serializeCoords(coords, precision, coordFormat);
9781 if (name === "color") {
9782 var _format$ids;
9783 // If output is a color() function, add colorspace id as first argument
9784 let cssId = format.id || ((_format$ids = format.ids) === null || _format$ids === void 0 ? void 0 : _format$ids[0]) || colorWithMeta.space.cssId || colorWithMeta.space.id;
9785 args.unshift(cssId);
9786 }
9787
9788 // Serialize alpha?
9789 /** @type {string | number} */
9790 let alpha = colorWithMeta.alpha;
9791 if (alphaFormat !== undefined && !(typeof alphaFormat === "object")) {
9792 alphaFormat = typeof alphaFormat === "string" ? {
9793 type: alphaFormat
9794 } : {
9795 include: alphaFormat
9796 };
9797 }
9798 let alphaType = (_alphaFormat$type = (_alphaFormat2 = alphaFormat) === null || _alphaFormat2 === void 0 ? void 0 : _alphaFormat2.type) !== null && _alphaFormat$type !== void 0 ? _alphaFormat$type : "<number>";
9799 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;
9800 let strAlpha = "";
9801 (_commas2 = commas) !== null && _commas2 !== void 0 ? _commas2 : commas = format.commas;
9802 if (serializeAlpha) {
9803 if (precision !== null) {
9804 let unit;
9805 if (alphaType === "<percentage>") {
9806 unit = "%";
9807 alpha *= 100;
9808 }
9809 alpha = serializeNumber(alpha, {
9810 precision,
9811 unit
9812 });
9813 }
9814 strAlpha = `${commas ? "," : " /"} ${alpha}`;
9815 }
9816 ret = `${name}(${args.join(commas ? ", " : " ")}${strAlpha})`;
9817 }
9818 return ret;
9819 }
9820
9821 var esnext_iterator_filter = {};
9822
9823 var es_iterator_filter = {};
9824
9825 var hasRequiredEs_iterator_filter;
9826
9827 function requireEs_iterator_filter () {
9828 if (hasRequiredEs_iterator_filter) return es_iterator_filter;
9829 hasRequiredEs_iterator_filter = 1;
9830 var $ = require_export();
9831 var call = requireFunctionCall();
9832 var aCallable = requireACallable();
9833 var anObject = requireAnObject();
9834 var getIteratorDirect = requireGetIteratorDirect();
9835 var createIteratorProxy = requireIteratorCreateProxy();
9836 var callWithSafeIterationClosing = requireCallWithSafeIterationClosing();
9837 var IS_PURE = requireIsPure();
9838
9839 var IteratorProxy = createIteratorProxy(function () {
9840 var iterator = this.iterator;
9841 var predicate = this.predicate;
9842 var next = this.next;
9843 var result, done, value;
9844 while (true) {
9845 result = anObject(call(next, iterator));
9846 done = this.done = !!result.done;
9847 if (done) return;
9848 value = result.value;
9849 if (callWithSafeIterationClosing(iterator, predicate, [value, this.counter++], true)) return value;
9850 }
9851 });
9852
9853 // `Iterator.prototype.filter` method
9854 // https://tc39.es/ecma262/#sec-iterator.prototype.filter
9855 $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
9856 filter: function filter(predicate) {
9857 anObject(this);
9858 aCallable(predicate);
9859 return new IteratorProxy(getIteratorDirect(this), {
9860 predicate: predicate
9861 });
9862 }
9863 });
9864 return es_iterator_filter;
9865 }
9866
9867 var hasRequiredEsnext_iterator_filter;
9868
9869 function requireEsnext_iterator_filter () {
9870 if (hasRequiredEsnext_iterator_filter) return esnext_iterator_filter;
9871 hasRequiredEsnext_iterator_filter = 1;
9872 // TODO: Remove from `core-js@4`
9873 requireEs_iterator_filter();
9874 return esnext_iterator_filter;
9875 }
9876
9877 requireEsnext_iterator_filter();
9878
9879 /** @import { Matrix3x3 } from "../types.js" */
9880
9881 /**
9882 * Matrices used by this color space, also available as `REC_2020_Linear.M`.
9883 * Uses D65 (no chromatic adaptation).
9884 * http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
9885 * @type {Record<string, Matrix3x3>}
9886 */
9887 // prettier-ignore
9888 const M$8 = {
9889 // 0 is actually calculated as 4.994106574466076e-17
9890 toXYZ: [[0.6369580483012914, 0.14461690358620832, 0.1688809751641721], [0.2627002120112671, 0.6779980715188708, 0.05930171646986196], [0.000000000000000, 0.028072693049087428, 1.060985057710791]],
9891 // from ITU-R BT.2124-0 Annex 2 p.3
9892 fromXYZ: [[1.716651187971268, -0.355670783776392, -0.253366281373660], [-0.666684351832489, 1.616481236634939, 0.0157685458139111], [0.017639857445311, -0.042770613257809, 0.942103121235474]]
9893 };
9894 var REC2020Linear = new RGBColorSpace({
9895 id: "rec2020-linear",
9896 cssId: "--rec2020-linear",
9897 name: "Linear REC.2020",
9898 white: "D65",
9899 M: M$8
9900 });
9901
9902 // import sRGB from "./srgb.js";
9903
9904 var REC2020 = new RGBColorSpace({
9905 id: "rec2020",
9906 name: "REC.2020",
9907 base: REC2020Linear,
9908 linearGamut: REC2020Linear,
9909 // Reference electro-optical transfer function from Rec. ITU-R BT.1886 Annex 1
9910 // with b (black lift) = 0 and a (user gain) = 1
9911 // defined over the extended range, not clamped
9912 toBase(RGB) {
9913 return RGB.map(function (val) {
9914 let sign = val < 0 ? -1 : 1;
9915 let abs = val * sign;
9916 return sign * Math.pow(abs, 2.4);
9917 });
9918 },
9919 fromBase(RGB) {
9920 return RGB.map(function (val) {
9921 let sign = val < 0 ? -1 : 1;
9922 let abs = val * sign;
9923 return sign * Math.pow(abs, 1 / 2.4);
9924 });
9925 }
9926 });
9927
9928 /** @import { Matrix3x3 } from "../types.js" */
9929
9930 /**
9931 * Matrices used by this color space, also available as `P3_Linear.M`
9932 * @type {Record<string, Matrix3x3>}
9933 */
9934 // prettier-ignore
9935 const M$7 = {
9936 toXYZ: [[0.4865709486482162, 0.26566769316909306, 0.1982172852343625], [0.2289745640697488, 0.6917385218365064, 0.079286914093745], [0.0000000000000000, 0.04511338185890264, 1.043944368900976]],
9937 fromXYZ: [[2.493496911941425, -0.9313836179191239, -0.40271078445071684], [-0.8294889695615747, 1.7626640603183463, 0.023624685841943577], [0.03584583024378447, -0.07617238926804182, 0.9568845240076872]]
9938 };
9939 var P3Linear = new RGBColorSpace({
9940 id: "p3-linear",
9941 cssId: "display-p3-linear",
9942 name: "Linear P3",
9943 white: "D65",
9944 M: M$7
9945 });
9946
9947 /** @import { Matrix3x3 } from "../types.js" */
9948
9949 // This is the linear-light version of sRGB
9950 // as used for example in SVG filters
9951 // or in Canvas
9952
9953 /**
9954 * Matrices used by this color space, also available as `sRGB_Linear.M`
9955 * @type {Record<string, Matrix3x3>}
9956 */
9957 // prettier-ignore
9958 const M$6 = {
9959 // calculated directly from the RGB and white chromaticities; when rounded to
9960 // 8 decimal places, agrees completely with the official matrix
9961 // see https://github.com/w3c/csswg-drafts/issues/5922
9962 toXYZ: [[0.41239079926595934, 0.357584339383878, 0.1804807884018343], [0.21263900587151027, 0.715168678767756, 0.07219231536073371], [0.01933081871559182, 0.11919477979462598, 0.9505321522496607]],
9963 // the inverse of the above; again agrees with the official definition
9964 // when rounded to 8 decimal places
9965 fromXYZ: [[3.2409699419045226, -1.537383177570094, -0.4986107602930034], [-0.9692436362808796, 1.8759675015077202, 0.04155505740717559], [0.05563007969699366, -0.20397695888897652, 1.0569715142428786]]
9966 };
9967 var sRGBLinear = new RGBColorSpace({
9968 id: "srgb-linear",
9969 name: "Linear sRGB",
9970 white: "D65",
9971 M: M$6
9972 });
9973
9974 // To produce: Visit https://www.w3.org/TR/css-color-4/#named-colors
9975 // and run in the console:
9976 // 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"))
9977
9978 /** List of CSS color keywords
9979 * Note that this does not include currentColor, transparent,
9980 * or system colors
9981 *
9982 * @type {Record<string, [number, number, number]>}
9983 */
9984 var KEYWORDS = {
9985 aliceblue: [240 / 255, 248 / 255, 1],
9986 antiquewhite: [250 / 255, 235 / 255, 215 / 255],
9987 aqua: [0, 1, 1],
9988 aquamarine: [127 / 255, 1, 212 / 255],
9989 azure: [240 / 255, 1, 1],
9990 beige: [245 / 255, 245 / 255, 220 / 255],
9991 bisque: [1, 228 / 255, 196 / 255],
9992 black: [0, 0, 0],
9993 blanchedalmond: [1, 235 / 255, 205 / 255],
9994 blue: [0, 0, 1],
9995 blueviolet: [138 / 255, 43 / 255, 226 / 255],
9996 brown: [165 / 255, 42 / 255, 42 / 255],
9997 burlywood: [222 / 255, 184 / 255, 135 / 255],
9998 cadetblue: [95 / 255, 158 / 255, 160 / 255],
9999 chartreuse: [127 / 255, 1, 0],
10000 chocolate: [210 / 255, 105 / 255, 30 / 255],
10001 coral: [1, 127 / 255, 80 / 255],
10002 cornflowerblue: [100 / 255, 149 / 255, 237 / 255],
10003 cornsilk: [1, 248 / 255, 220 / 255],
10004 crimson: [220 / 255, 20 / 255, 60 / 255],
10005 cyan: [0, 1, 1],
10006 darkblue: [0, 0, 139 / 255],
10007 darkcyan: [0, 139 / 255, 139 / 255],
10008 darkgoldenrod: [184 / 255, 134 / 255, 11 / 255],
10009 darkgray: [169 / 255, 169 / 255, 169 / 255],
10010 darkgreen: [0, 100 / 255, 0],
10011 darkgrey: [169 / 255, 169 / 255, 169 / 255],
10012 darkkhaki: [189 / 255, 183 / 255, 107 / 255],
10013 darkmagenta: [139 / 255, 0, 139 / 255],
10014 darkolivegreen: [85 / 255, 107 / 255, 47 / 255],
10015 darkorange: [1, 140 / 255, 0],
10016 darkorchid: [153 / 255, 50 / 255, 204 / 255],
10017 darkred: [139 / 255, 0, 0],
10018 darksalmon: [233 / 255, 150 / 255, 122 / 255],
10019 darkseagreen: [143 / 255, 188 / 255, 143 / 255],
10020 darkslateblue: [72 / 255, 61 / 255, 139 / 255],
10021 darkslategray: [47 / 255, 79 / 255, 79 / 255],
10022 darkslategrey: [47 / 255, 79 / 255, 79 / 255],
10023 darkturquoise: [0, 206 / 255, 209 / 255],
10024 darkviolet: [148 / 255, 0, 211 / 255],
10025 deeppink: [1, 20 / 255, 147 / 255],
10026 deepskyblue: [0, 191 / 255, 1],
10027 dimgray: [105 / 255, 105 / 255, 105 / 255],
10028 dimgrey: [105 / 255, 105 / 255, 105 / 255],
10029 dodgerblue: [30 / 255, 144 / 255, 1],
10030 firebrick: [178 / 255, 34 / 255, 34 / 255],
10031 floralwhite: [1, 250 / 255, 240 / 255],
10032 forestgreen: [34 / 255, 139 / 255, 34 / 255],
10033 fuchsia: [1, 0, 1],
10034 gainsboro: [220 / 255, 220 / 255, 220 / 255],
10035 ghostwhite: [248 / 255, 248 / 255, 1],
10036 gold: [1, 215 / 255, 0],
10037 goldenrod: [218 / 255, 165 / 255, 32 / 255],
10038 gray: [128 / 255, 128 / 255, 128 / 255],
10039 green: [0, 128 / 255, 0],
10040 greenyellow: [173 / 255, 1, 47 / 255],
10041 grey: [128 / 255, 128 / 255, 128 / 255],
10042 honeydew: [240 / 255, 1, 240 / 255],
10043 hotpink: [1, 105 / 255, 180 / 255],
10044 indianred: [205 / 255, 92 / 255, 92 / 255],
10045 indigo: [75 / 255, 0, 130 / 255],
10046 ivory: [1, 1, 240 / 255],
10047 khaki: [240 / 255, 230 / 255, 140 / 255],
10048 lavender: [230 / 255, 230 / 255, 250 / 255],
10049 lavenderblush: [1, 240 / 255, 245 / 255],
10050 lawngreen: [124 / 255, 252 / 255, 0],
10051 lemonchiffon: [1, 250 / 255, 205 / 255],
10052 lightblue: [173 / 255, 216 / 255, 230 / 255],
10053 lightcoral: [240 / 255, 128 / 255, 128 / 255],
10054 lightcyan: [224 / 255, 1, 1],
10055 lightgoldenrodyellow: [250 / 255, 250 / 255, 210 / 255],
10056 lightgray: [211 / 255, 211 / 255, 211 / 255],
10057 lightgreen: [144 / 255, 238 / 255, 144 / 255],
10058 lightgrey: [211 / 255, 211 / 255, 211 / 255],
10059 lightpink: [1, 182 / 255, 193 / 255],
10060 lightsalmon: [1, 160 / 255, 122 / 255],
10061 lightseagreen: [32 / 255, 178 / 255, 170 / 255],
10062 lightskyblue: [135 / 255, 206 / 255, 250 / 255],
10063 lightslategray: [119 / 255, 136 / 255, 153 / 255],
10064 lightslategrey: [119 / 255, 136 / 255, 153 / 255],
10065 lightsteelblue: [176 / 255, 196 / 255, 222 / 255],
10066 lightyellow: [1, 1, 224 / 255],
10067 lime: [0, 1, 0],
10068 limegreen: [50 / 255, 205 / 255, 50 / 255],
10069 linen: [250 / 255, 240 / 255, 230 / 255],
10070 magenta: [1, 0, 1],
10071 maroon: [128 / 255, 0, 0],
10072 mediumaquamarine: [102 / 255, 205 / 255, 170 / 255],
10073 mediumblue: [0, 0, 205 / 255],
10074 mediumorchid: [186 / 255, 85 / 255, 211 / 255],
10075 mediumpurple: [147 / 255, 112 / 255, 219 / 255],
10076 mediumseagreen: [60 / 255, 179 / 255, 113 / 255],
10077 mediumslateblue: [123 / 255, 104 / 255, 238 / 255],
10078 mediumspringgreen: [0, 250 / 255, 154 / 255],
10079 mediumturquoise: [72 / 255, 209 / 255, 204 / 255],
10080 mediumvioletred: [199 / 255, 21 / 255, 133 / 255],
10081 midnightblue: [25 / 255, 25 / 255, 112 / 255],
10082 mintcream: [245 / 255, 1, 250 / 255],
10083 mistyrose: [1, 228 / 255, 225 / 255],
10084 moccasin: [1, 228 / 255, 181 / 255],
10085 navajowhite: [1, 222 / 255, 173 / 255],
10086 navy: [0, 0, 128 / 255],
10087 oldlace: [253 / 255, 245 / 255, 230 / 255],
10088 olive: [128 / 255, 128 / 255, 0],
10089 olivedrab: [107 / 255, 142 / 255, 35 / 255],
10090 orange: [1, 165 / 255, 0],
10091 orangered: [1, 69 / 255, 0],
10092 orchid: [218 / 255, 112 / 255, 214 / 255],
10093 palegoldenrod: [238 / 255, 232 / 255, 170 / 255],
10094 palegreen: [152 / 255, 251 / 255, 152 / 255],
10095 paleturquoise: [175 / 255, 238 / 255, 238 / 255],
10096 palevioletred: [219 / 255, 112 / 255, 147 / 255],
10097 papayawhip: [1, 239 / 255, 213 / 255],
10098 peachpuff: [1, 218 / 255, 185 / 255],
10099 peru: [205 / 255, 133 / 255, 63 / 255],
10100 pink: [1, 192 / 255, 203 / 255],
10101 plum: [221 / 255, 160 / 255, 221 / 255],
10102 powderblue: [176 / 255, 224 / 255, 230 / 255],
10103 purple: [128 / 255, 0, 128 / 255],
10104 rebeccapurple: [102 / 255, 51 / 255, 153 / 255],
10105 red: [1, 0, 0],
10106 rosybrown: [188 / 255, 143 / 255, 143 / 255],
10107 royalblue: [65 / 255, 105 / 255, 225 / 255],
10108 saddlebrown: [139 / 255, 69 / 255, 19 / 255],
10109 salmon: [250 / 255, 128 / 255, 114 / 255],
10110 sandybrown: [244 / 255, 164 / 255, 96 / 255],
10111 seagreen: [46 / 255, 139 / 255, 87 / 255],
10112 seashell: [1, 245 / 255, 238 / 255],
10113 sienna: [160 / 255, 82 / 255, 45 / 255],
10114 silver: [192 / 255, 192 / 255, 192 / 255],
10115 skyblue: [135 / 255, 206 / 255, 235 / 255],
10116 slateblue: [106 / 255, 90 / 255, 205 / 255],
10117 slategray: [112 / 255, 128 / 255, 144 / 255],
10118 slategrey: [112 / 255, 128 / 255, 144 / 255],
10119 snow: [1, 250 / 255, 250 / 255],
10120 springgreen: [0, 1, 127 / 255],
10121 steelblue: [70 / 255, 130 / 255, 180 / 255],
10122 tan: [210 / 255, 180 / 255, 140 / 255],
10123 teal: [0, 128 / 255, 128 / 255],
10124 thistle: [216 / 255, 191 / 255, 216 / 255],
10125 tomato: [1, 99 / 255, 71 / 255],
10126 turquoise: [64 / 255, 224 / 255, 208 / 255],
10127 violet: [238 / 255, 130 / 255, 238 / 255],
10128 wheat: [245 / 255, 222 / 255, 179 / 255],
10129 white: [1, 1, 1],
10130 whitesmoke: [245 / 255, 245 / 255, 245 / 255],
10131 yellow: [1, 1, 0],
10132 yellowgreen: [154 / 255, 205 / 255, 50 / 255]
10133 };
10134
10135 /** @import { Coords } from "../types.js" */
10136
10137 let coordGrammar = Array(3).fill("<percentage> | <number>[0, 255]");
10138 let coordGrammarNumber = Array(3).fill("<number>[0, 255]");
10139 var sRGB = new RGBColorSpace({
10140 id: "srgb",
10141 name: "sRGB",
10142 base: sRGBLinear,
10143 linearGamut: sRGBLinear,
10144 fromBase: rgb => {
10145 // convert an array of linear-light sRGB values in the range 0.0-1.0
10146 // to gamma corrected form
10147 // https://en.wikipedia.org/wiki/SRGB
10148 return rgb.map(val => {
10149 let sign = val < 0 ? -1 : 1;
10150 let abs = val * sign;
10151 if (abs > 0.0031308) {
10152 return sign * (1.055 * abs ** (1 / 2.4) - 0.055);
10153 }
10154 return 12.92 * val;
10155 });
10156 },
10157 toBase: rgb => {
10158 // convert an array of sRGB values in the range 0.0 - 1.0
10159 // to linear light (un-companded) form.
10160 // https://en.wikipedia.org/wiki/SRGB
10161 return rgb.map(val => {
10162 let sign = val < 0 ? -1 : 1;
10163 let abs = val * sign;
10164 if (abs <= 0.04045) {
10165 return val / 12.92;
10166 }
10167 return sign * ((abs + 0.055) / 1.055) ** 2.4;
10168 });
10169 },
10170 formats: {
10171 rgb: {
10172 coords: coordGrammar
10173 },
10174 rgb_number: {
10175 name: "rgb",
10176 commas: true,
10177 coords: coordGrammarNumber,
10178 alpha: false
10179 },
10180 color: {
10181 /* use defaults */
10182 },
10183 rgba: {
10184 coords: coordGrammar,
10185 commas: true,
10186 alpha: true
10187 },
10188 rgba_number: {
10189 name: "rgba",
10190 commas: true,
10191 coords: coordGrammarNumber
10192 },
10193 hex: {
10194 type: "custom",
10195 toGamut: true,
10196 test: str => /^#(([a-f0-9]{2}){3,4}|[a-f0-9]{3,4})$/i.test(str),
10197 parse(str) {
10198 if (str.length <= 5) {
10199 // #rgb or #rgba, duplicate digits
10200 str = str.replace(/[a-f0-9]/gi, "$&$&");
10201 }
10202
10203 /** @type {number[]} */
10204 let rgba = [];
10205 // @ts-expect-error Type 'void' is not assignable to type 'string'
10206 str.replace(/[a-f0-9]{2}/gi, component => {
10207 rgba.push(parseInt(component, 16) / 255);
10208 });
10209 return {
10210 spaceId: "srgb",
10211 coords: (/** @type {Coords} */rgba.slice(0, 3)),
10212 alpha: (/** @type {number} */rgba.slice(3)[0])
10213 };
10214 },
10215 serialize: (coords, alpha, {
10216 collapse = true,
10217 // collapse to 3-4 digit hex when possible?
10218 alpha: alphaFormat
10219 } = {}) => {
10220 if (alphaFormat !== false && alpha < 1 || alphaFormat === true) {
10221 coords.push(alpha);
10222 }
10223 coords = /** @type {[number, number, number]} */
10224 coords.map(c => Math.round(c * 255));
10225 let collapsible = collapse && coords.every(c => c % 17 === 0);
10226 let hex = coords.map(c => {
10227 if (collapsible) {
10228 return (c / 17).toString(16);
10229 }
10230 return c.toString(16).padStart(2, "0");
10231 }).join("");
10232 return "#" + hex;
10233 }
10234 },
10235 keyword: {
10236 type: "custom",
10237 test: str => /^[a-z]+$/i.test(str),
10238 parse(str) {
10239 str = str.toLowerCase();
10240 let ret = {
10241 spaceId: "srgb",
10242 coords: null,
10243 alpha: 1
10244 };
10245 if (str === "transparent") {
10246 ret.coords = KEYWORDS.black;
10247 ret.alpha = 0;
10248 } else {
10249 ret.coords = KEYWORDS[str];
10250 }
10251 if (ret.coords) {
10252 return ret;
10253 }
10254 }
10255 }
10256 }
10257 });
10258
10259 var P3 = new RGBColorSpace({
10260 id: "p3",
10261 cssId: "display-p3",
10262 name: "P3",
10263 base: P3Linear,
10264 linearGamut: P3Linear,
10265 // Gamma encoding/decoding is the same as sRGB
10266 fromBase: sRGB.fromBase,
10267 toBase: sRGB.toBase
10268 });
10269
10270 /** @import ColorSpace from "./ColorSpace.js" */
10271 /** @import { ColorTypes, PlainColorObject, DisplayOptions } from "./types.js" */
10272
10273 // Type re-exports
10274 /** @typedef {import("./types.js").Display} Display */
10275
10276 // Default space for CSS output. Code in Color.js makes this wider if there's a DOM available
10277 defaults.display_space = sRGB;
10278 let supportsNone;
10279 if (typeof CSS !== "undefined" && CSS.supports) {
10280 // Find widest supported color space for CSS
10281 for (let space of [lab, REC2020, P3]) {
10282 let coords = space.getMinCoords();
10283 let color = {
10284 space,
10285 coords,
10286 alpha: 1
10287 };
10288 let str = serialize(color);
10289 if (CSS.supports("color", str)) {
10290 defaults.display_space = space;
10291 break;
10292 }
10293 }
10294 }
10295
10296 /**
10297 * Returns a serialization of the color that can actually be displayed in the browser.
10298 * If the default serialization can be displayed, it is returned.
10299 * Otherwise, if a `space` is given, the color is converted directly to it.
10300 * If not, the color is converted to the first supported of its space's `displaySpaces` (if any),
10301 * else the closest supported space in its base color space chain (which preserves its gamut),
10302 * else the default fallback space (Lab, REC2020, or P3, whichever is the widest supported).
10303 * In Node.js, this is basically equivalent to `serialize()` but returns a `String` object instead.
10304 * @param {ColorTypes} color
10305 * @param {DisplayOptions} [options] Options. Any properties beyond `space` and `supports` are passed to `serialize()`.
10306 * @returns {Display} String object containing the serialized color
10307 * with a color property containing the converted color (or the original, if no conversion was necessary)
10308 */
10309 function display(color, {
10310 space,
10311 supports = (_globalThis$CSS => (_globalThis$CSS = globalThis.CSS) === null || _globalThis$CSS === void 0 ? void 0 : _globalThis$CSS.supports)(),
10312 ...options
10313 } = {}) {
10314 color = getColor(color);
10315 let ret = /** @type {Display} */serialize(color, options);
10316 if (!supports || supports("color", /** @type {string} */ret) || !defaults.display_space) {
10317 ret = /** @type {Display} */new String(ret);
10318 ret.color = /** @type {PlainColorObject} */color;
10319 } else {
10320 // If we're here, what we were about to output is not supported
10321 let fallbackColor = /** @type {PlainColorObject} */color;
10322
10323 // First, check if the culprit is none values
10324 let hasNone = color.coords.some(isNone) || isNone(color.alpha);
10325 if (hasNone) {
10326 var _supportsNone;
10327 // Does the browser support none values?
10328 if (!((_supportsNone = supportsNone) !== null && _supportsNone !== void 0 ? _supportsNone : supportsNone = supports("color", "hsl(none 50% 50%)"))) {
10329 // Nope, try again without none
10330 fallbackColor = clone(/** @type {PlainColorObject} */color);
10331 fallbackColor.coords = /** @type {[number, number, number]} */
10332 fallbackColor.coords.map(skipNone);
10333 fallbackColor.alpha = skipNone(fallbackColor.alpha);
10334
10335 // @ts-expect-error This is set to the correct type later
10336 ret = serialize(fallbackColor, options);
10337 if (supports("color", /** @type {string} */ret)) {
10338 // We're done, now it's supported
10339 ret = /** @type {Display} */new String(ret);
10340 ret.color = fallbackColor;
10341 return ret;
10342 }
10343 }
10344 }
10345
10346 // If we're here, the color function is not supported.
10347 // With no explicit space, try the color's own `displaySpaces`, or else walk up its base
10348 // color space chain (closest first, skipping XYZ connection spaces), and use the first
10349 // space the browser supports, before falling back to the default space.
10350 if (space === undefined) {
10351 var _space$displaySpaces;
10352 space = fallbackColor.space;
10353 let candidates = (_space$displaySpaces = space.displaySpaces) !== null && _space$displaySpaces !== void 0 ? _space$displaySpaces : space.bases;
10354
10355 // Skip XYZ connection spaces (unless the space itself is one, so it still has a fallback).
10356 if (!space.displaySpaces && !space.id.startsWith("xyz-")) {
10357 candidates = candidates.filter(space => !space.id.startsWith("xyz-"));
10358 }
10359 for (let candidate of candidates) {
10360 let candidateColor = to(fallbackColor, candidate);
10361 let str = serialize(candidateColor, options);
10362 if (supports("color", /** @type {string} */str)) {
10363 ret = /** @type {Display} */new String(str);
10364 ret.color = candidateColor;
10365 return ret;
10366 }
10367 }
10368 space = defaults.display_space;
10369 }
10370
10371 // Fall back to fallback space
10372 fallbackColor = to(fallbackColor, /** @type {string | ColorSpace} */space);
10373 ret = /** @type {Display} */new String(serialize(fallbackColor, options));
10374 ret.color = fallbackColor;
10375 }
10376 return ret;
10377 }
10378
10379 /** @import { ColorTypes } from "./types.js" */
10380
10381 // Type re-exports
10382 /** @typedef {import("./types.js").DeltasReturn} DeltasReturn */
10383
10384 /**
10385 * Get color differences per-component, on any color space
10386 * @param {ColorTypes} c1
10387 * @param {ColorTypes} c2
10388 * @param {object} options
10389 * @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.
10390 * @param {Parameters<typeof adjust>[0]} [options.hue="shorter"] - How to handle hue differences. Same as hue interpolation option.
10391 * @returns {DeltasReturn}
10392 */
10393 function deltas(c1, c2, {
10394 space,
10395 hue = "shorter"
10396 } = {}) {
10397 c1 = getColor(c1);
10398 space || (space = c1.space);
10399 space = ColorSpace.get(space);
10400 let spaceCoords = Object.values(space.coords);
10401 [c1, c2] = [c1, c2].map(c => to(c, space));
10402 let [coords1, coords2] = [c1, c2].map(c => c.coords);
10403 let coords = /** @type {[number, number, number]} */
10404 coords1.map((coord1, i) => {
10405 let coordMeta = spaceCoords[i];
10406 let coord2 = coords2[i];
10407 if (coordMeta.type === "angle") {
10408 [coord1, coord2] = adjust(hue, [coord1, coord2]);
10409 }
10410 return subtractCoords(coord1, coord2);
10411 });
10412 let alpha = subtractCoords(c1.alpha, c2.alpha);
10413 return {
10414 space: (/** @type {ColorSpace} */space),
10415 coords,
10416 alpha
10417 };
10418 }
10419 function subtractCoords(c1, c2) {
10420 if (isNone(c1) || isNone(c2)) {
10421 return c1 === c2 ? null : 0;
10422 }
10423 return c1 - c2;
10424 }
10425
10426 /** @import { ColorTypes } from "./types.js" */
10427
10428 /**
10429 * @param {ColorTypes} color1
10430 * @param {ColorTypes} color2
10431 * @returns {boolean}
10432 */
10433 function equals(color1, color2) {
10434 color1 = getColor(color1);
10435 color2 = getColor(color2);
10436 return color1.space === color2.space && color1.alpha === color2.alpha && color1.coords.every((c, i) => c === color2.coords[i]);
10437 }
10438
10439 /**
10440 * Relative luminance
10441 */
10442
10443 /** @import { ColorTypes } from "./types.js" */
10444
10445 /**
10446 *
10447 * @param {ColorTypes} color
10448 * @returns {number}
10449 */
10450 function getLuminance(color) {
10451 // Assume getColor() is called on color in get()
10452 return get(color, [XYZ_D65, "y"]);
10453 }
10454
10455 /**
10456 * @param {ColorTypes} color
10457 * @param {number | ((coord: number) => number)} value
10458 */
10459 function setLuminance(color, value) {
10460 // Assume getColor() is called on color in set()
10461 set(color, [XYZ_D65, "y"], value);
10462 }
10463
10464 /**
10465 * @param {typeof import("./color.js").default} Color
10466 */
10467 function register$2(Color) {
10468 Object.defineProperty(Color.prototype, "luminance", {
10469 get() {
10470 return getLuminance(this);
10471 },
10472 set(value) {
10473 setLuminance(this, value);
10474 }
10475 });
10476 }
10477
10478 var luminance = /*#__PURE__*/Object.freeze({
10479 __proto__: null,
10480 getLuminance: getLuminance,
10481 register: register$2,
10482 setLuminance: setLuminance
10483 });
10484
10485 // WCAG 2.0 contrast https://www.w3.org/TR/WCAG20-TECHS/G18.html
10486 // Simple contrast, with fixed 5% viewing flare contribution
10487 // Symmetric, does not matter which is foreground and which is background
10488
10489
10490 /**
10491 * @param {import("../types.js").ColorTypes} color1
10492 * @param {import("../types.js").ColorTypes} color2
10493 * @returns {number}
10494 */
10495 function contrastWCAG21(color1, color2) {
10496 color1 = getColor(color1);
10497 color2 = getColor(color2);
10498 let Y1 = Math.max(getLuminance(color1), 0);
10499 let Y2 = Math.max(getLuminance(color2), 0);
10500 if (Y2 > Y1) {
10501 [Y1, Y2] = [Y2, Y1];
10502 }
10503 return (Y1 + 0.05) / (Y2 + 0.05);
10504 }
10505
10506 // exponents
10507 const normBG = 0.56;
10508 const normTXT = 0.57;
10509 const revTXT = 0.62;
10510 const revBG = 0.65;
10511
10512 // clamps
10513 const blkThrs = 0.022;
10514 const blkClmp = 1.414;
10515 const loClip = 0.1;
10516 const deltaYmin = 0.0005;
10517
10518 // scalers
10519 // see https://github.com/w3c/silver/issues/645
10520 const scaleBoW = 1.14;
10521 const loBoWoffset = 0.027;
10522 const scaleWoB = 1.14;
10523 function fclamp(Y) {
10524 if (Y >= blkThrs) {
10525 return Y;
10526 }
10527 return Y + (blkThrs - Y) ** blkClmp;
10528 }
10529 function linearize(val) {
10530 let sign = val < 0 ? -1 : 1;
10531 let abs = Math.abs(val);
10532 return sign * Math.pow(abs, 2.4);
10533 }
10534
10535 /**
10536 * Not symmetric, requires a foreground (text) color, and a background color
10537 * @param {import("../types.js").ColorTypes} background
10538 * @param {import("../types.js").ColorTypes} foreground
10539 * @returns {number}
10540 */
10541 function contrastAPCA(background, foreground) {
10542 foreground = getColor(foreground);
10543 background = getColor(background);
10544 let S;
10545 let C;
10546 let Sapc;
10547
10548 // Myndex as-published, assumes sRGB inputs
10549 let R, G, B;
10550 foreground = to(foreground, "srgb");
10551 // Should these be clamped to in-gamut values?
10552
10553 // Calculates "screen luminance" with non-standard simple gamma EOTF
10554 // weights should be from CSS Color 4, not the ones here which are via Myndex and copied from Lindbloom
10555 [R, G, B] = foreground.coords.map(c => {
10556 return isNone(c) ? 0 : c;
10557 });
10558 let lumTxt = linearize(R) * 0.2126729 + linearize(G) * 0.7151522 + linearize(B) * 0.072175;
10559 background = to(background, "srgb");
10560 [R, G, B] = background.coords.map(c => {
10561 return isNone(c) ? 0 : c;
10562 });
10563 let lumBg = linearize(R) * 0.2126729 + linearize(G) * 0.7151522 + linearize(B) * 0.072175;
10564
10565 // toe clamping of very dark values to account for flare
10566 let Ytxt = fclamp(lumTxt);
10567 let Ybg = fclamp(lumBg);
10568
10569 // are we "Black on White" (dark on light), or light on dark?
10570 let BoW = Ybg > Ytxt;
10571
10572 // why is this a delta, when Y is not perceptually uniform?
10573 // Answer: it is a noise gate, see
10574 // https://github.com/LeaVerou/color.js/issues/208
10575 if (Math.abs(Ybg - Ytxt) < deltaYmin) {
10576 C = 0;
10577 } else {
10578 if (BoW) {
10579 // dark text on light background
10580 S = Ybg ** normBG - Ytxt ** normTXT;
10581 C = S * scaleBoW;
10582 } else {
10583 // light text on dark background
10584 S = Ybg ** revBG - Ytxt ** revTXT;
10585 C = S * scaleWoB;
10586 }
10587 }
10588 if (Math.abs(C) < loClip) {
10589 Sapc = 0;
10590 } else if (C > 0) {
10591 // not clear whether Woffset is loBoWoffset or loWoBoffset
10592 // but they have the same value
10593 Sapc = C - loBoWoffset;
10594 } else {
10595 Sapc = C + loBoWoffset;
10596 }
10597 return Sapc * 100;
10598 }
10599
10600 // Michelson luminance contrast
10601 // the relation between the spread and the sum of the two luminances
10602 // Symmetric, does not matter which is foreground and which is background
10603 // No black level compensation for flare.
10604
10605
10606 /**
10607 * @param {import("../types.js").ColorTypes} color1
10608 * @param {import("../types.js").ColorTypes} color2
10609 * @returns {number}
10610 */
10611 function contrastMichelson(color1, color2) {
10612 color1 = getColor(color1);
10613 color2 = getColor(color2);
10614 let Y1 = Math.max(getLuminance(color1), 0);
10615 let Y2 = Math.max(getLuminance(color2), 0);
10616 if (Y2 > Y1) {
10617 [Y1, Y2] = [Y2, Y1];
10618 }
10619 let denom = Y1 + Y2;
10620 return denom === 0 ? 0 : (Y1 - Y2) / denom;
10621 }
10622
10623 // Weber luminance contrast
10624 // The difference between the two luminances divided by the lower luminance
10625 // Symmetric, does not matter which is foreground and which is background
10626 // No black level compensation for flare.
10627
10628
10629 // the darkest sRGB color above black is #000001 and this produces
10630 // a plain Weber contrast of ~45647.
10631 // So, setting the divide-by-zero result at 50000 is a reasonable
10632 // max clamp for the plain Weber
10633 const max = 50000;
10634
10635 /**
10636 * @param {import("../types.js").ColorTypes} color1
10637 * @param {import("../types.js").ColorTypes} color2
10638 * @returns {number}
10639 */
10640 function contrastWeber(color1, color2) {
10641 color1 = getColor(color1);
10642 color2 = getColor(color2);
10643 let Y1 = Math.max(getLuminance(color1), 0);
10644 let Y2 = Math.max(getLuminance(color2), 0);
10645 if (Y2 > Y1) {
10646 [Y1, Y2] = [Y2, Y1];
10647 }
10648 return Y2 === 0 ? max : (Y1 - Y2) / Y2;
10649 }
10650
10651 // CIE Lightness difference, as used by Google Material Design
10652 // Google HCT Tone is the same as CIE Lightness
10653 // https://material.io/blog/science-of-color-design
10654
10655
10656 /**
10657 * @param {import("../types.js").ColorTypes} color1
10658 * @param {import("../types.js").ColorTypes} color2
10659 * @returns {number}
10660 */
10661 function contrastLstar(color1, color2) {
10662 color1 = getColor(color1);
10663 color2 = getColor(color2);
10664 let L1 = get(color1, [lab, "l"]);
10665 let L2 = get(color2, [lab, "l"]);
10666 return Math.abs(L1 - L2);
10667 }
10668
10669 // κ * ε = 2^3 = 8
10670 const ε$3 = 216 / 24389; // 6^3/29^3 == (24/116)^3
10671 const ε3 = 24 / 116;
10672 const κ$2 = 24389 / 27; // 29^3/3^3
10673
10674 let white$1 = WHITES.D65;
10675 var lab_d65 = new ColorSpace({
10676 id: "lab-d65",
10677 name: "Lab D65",
10678 coords: {
10679 l: {
10680 refRange: [0, 100],
10681 name: "Lightness"
10682 },
10683 a: {
10684 refRange: [-125, 125]
10685 },
10686 b: {
10687 refRange: [-125, 125]
10688 }
10689 },
10690 // Assuming XYZ is relative to D65, convert to CIE Lab
10691 // from CIE standard, which now defines these as a rational fraction
10692 white: white$1,
10693 base: XYZ_D65,
10694 // Convert D65-adapted XYZ to Lab
10695 // CIE 15.3:2004 section 8.2.1.1
10696 fromBase(XYZ) {
10697 // compute xyz, which is XYZ scaled relative to reference white
10698 let xyz = XYZ.map((value, i) => value / white$1[i]);
10699
10700 // now compute f
10701 let f = xyz.map(value => value > ε$3 ? Math.cbrt(value) : (κ$2 * value + 16) / 116);
10702 return [116 * f[1] - 16,
10703 // L
10704 500 * (f[0] - f[1]),
10705 // a
10706 200 * (f[1] - f[2]) // b
10707 ];
10708 },
10709 // Convert Lab to D65-adapted XYZ
10710 // Same result as CIE 15.3:2004 Appendix D although the derivation is different
10711 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
10712 toBase(Lab) {
10713 // compute f, starting with the luminance-related term
10714 let f = [];
10715 f[1] = (Lab[0] + 16) / 116;
10716 f[0] = Lab[1] / 500 + f[1];
10717 f[2] = f[1] - Lab[2] / 200;
10718
10719 // compute xyz
10720 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];
10721
10722 // Compute XYZ by scaling xyz by reference white
10723 return xyz.map((value, i) => value * white$1[i]);
10724 },
10725 formats: {
10726 "lab-d65": {
10727 coords: ["<number> | <percentage>", "<number> | <percentage>", "<number> | <percentage>"]
10728 }
10729 }
10730 });
10731
10732 // Delta Phi Star perceptual lightness contrast
10733 // See https://github.com/Myndex/deltaphistar
10734 // The (difference between two Lstars each raised to phi) raised to (1/phi)
10735 // Symmetric, does not matter which is foreground and which is background
10736
10737 const phi = Math.pow(5, 0.5) * 0.5 + 0.5; // Math.phi can be used if Math.js
10738
10739 /**
10740 * @param {import("../types.js").ColorTypes} color1
10741 * @param {import("../types.js").ColorTypes} color2
10742 * @returns {number}
10743 */
10744 function contrastDeltaPhi(color1, color2) {
10745 color1 = getColor(color1);
10746 color2 = getColor(color2);
10747 let Lstr1 = get(color1, [lab_d65, "l"]);
10748 let Lstr2 = get(color2, [lab_d65, "l"]);
10749 let deltaPhiStar = Math.abs(Math.pow(Lstr1, phi) - Math.pow(Lstr2, phi));
10750 let contrast = Math.pow(deltaPhiStar, 1 / phi) * Math.SQRT2 - 40;
10751 return contrast < 7.5 ? 0.0 : contrast;
10752 }
10753
10754 /** @typedef {keyof typeof import("./index.js") extends `contrast${infer Alg}` ? Alg : string} Algorithms */
10755
10756 var contrastMethods = /*#__PURE__*/Object.freeze({
10757 __proto__: null,
10758 contrastAPCA: contrastAPCA,
10759 contrastDeltaPhi: contrastDeltaPhi,
10760 contrastLstar: contrastLstar,
10761 contrastMichelson: contrastMichelson,
10762 contrastWCAG21: contrastWCAG21,
10763 contrastWeber: contrastWeber
10764 });
10765
10766 /** @import { ColorTypes } from "./types.js" */
10767
10768 // Type re-exports
10769 /** @typedef {import("./types.js").Algorithms} Algorithms */
10770
10771 /**
10772 *
10773 * @param {ColorTypes} background
10774 * @param {ColorTypes} foreground
10775 * @param {Algorithms | ({ algorithm: Algorithms } & Record<string, any>)} o
10776 * Algorithm to use as well as any other options to pass to the contrast function
10777 * @returns {number}
10778 * @throws {TypeError} Unknown or unspecified algorithm
10779 */
10780 function contrast(background, foreground, o) {
10781 if (isString(o)) {
10782 o = {
10783 algorithm: o
10784 };
10785 }
10786 let {
10787 algorithm,
10788 ...rest
10789 } = o || {};
10790 if (!algorithm) {
10791 let algorithms = Object.keys(contrastMethods).map(a => a.replace(/^contrast/, "")).join(", ");
10792 throw new TypeError(`contrast() function needs a contrast algorithm. Please specify one of: ${algorithms}`);
10793 }
10794 background = getColor(background);
10795 foreground = getColor(foreground);
10796 for (let a in contrastMethods) {
10797 if ("contrast" + algorithm.toLowerCase() === a.toLowerCase()) {
10798 return contrastMethods[a](background, foreground, rest);
10799 }
10800 }
10801 throw new TypeError(`Unknown contrast algorithm: ${algorithm}`);
10802 }
10803
10804 /** @import Color, { ColorTypes } from "./color.js" */
10805
10806 // Chromaticity coordinates
10807 /**
10808 * @param {ColorTypes} color
10809 * @returns {[number, number]}
10810 */
10811 function uv(color) {
10812 // Assumes getAll() calls getColor() on color
10813 let [X, Y, Z] = getAll(color, XYZ_D65);
10814 let denom = X + 15 * Y + 3 * Z;
10815 return [4 * X / denom, 9 * Y / denom];
10816 }
10817
10818 /**
10819 * @param {ColorTypes} color
10820 * @returns {[number, number]}
10821 */
10822 function xy(color) {
10823 // Assumes getAll() calls getColor() on color
10824 let [X, Y, Z] = getAll(color, XYZ_D65);
10825 let sum = X + Y + Z;
10826 return [X / sum, Y / sum];
10827 }
10828
10829 /**
10830 * @param {typeof Color} Color
10831 */
10832 function register$1(Color) {
10833 // no setters, as lightness information is lost
10834 // when converting color to chromaticity
10835 Object.defineProperty(Color.prototype, "uv", {
10836 get() {
10837 return uv(this);
10838 }
10839 });
10840 Object.defineProperty(Color.prototype, "xy", {
10841 get() {
10842 return xy(this);
10843 }
10844 });
10845 }
10846
10847 var chromaticity = /*#__PURE__*/Object.freeze({
10848 __proto__: null,
10849 register: register$1,
10850 uv: uv,
10851 xy: xy
10852 });
10853
10854 /** @import { ColorTypes } from "./types.js" */
10855
10856 // Type re-exports
10857 /** @typedef {import("./types.js").Methods} Methods */
10858
10859 /**
10860 *
10861 * @param {ColorTypes} c1
10862 * @param {ColorTypes} c2
10863 * @param {Methods | ({ method?: Methods | undefined } & Record<string, any>)} [o]
10864 * deltaE method to use as well as any other options to pass to the deltaE function
10865 * @returns {number}
10866 * @throws {TypeError} Unknown or unspecified method
10867 */
10868 function deltaE(c1, c2, o = {}) {
10869 if (isString(o)) {
10870 o = {
10871 method: o
10872 };
10873 }
10874 let {
10875 method = defaults.deltaE,
10876 ...rest
10877 } = o;
10878 for (let m in deltaEMethods) {
10879 if ("deltae" + method.toLowerCase() === m.toLowerCase()) {
10880 return deltaEMethods[m](c1, c2, rest);
10881 }
10882 }
10883 throw new TypeError(`Unknown deltaE method: ${method}`);
10884 }
10885
10886 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
10887
10888 /**
10889 * @param {ColorTypes} color
10890 * @param {number} amount
10891 * @returns {PlainColorObject}
10892 */
10893 function lighten(color, amount = 0.25) {
10894 let space = ColorSpace.get("oklch", "lch");
10895 let /** @type {Ref} */lightness = [space, "l"];
10896 return set(color, lightness, l => l * (1 + amount));
10897 }
10898
10899 /**
10900 * @param {ColorTypes} color
10901 * @param {number} amount
10902 * @returns {PlainColorObject}
10903 */
10904 function darken(color, amount = 0.25) {
10905 let space = ColorSpace.get("oklch", "lch");
10906 let /** @type {Ref} */lightness = [space, "l"];
10907 return set(color, lightness, l => l * (1 - amount));
10908 }
10909
10910 /** @type {"color"} */
10911 lighten.returns = "color";
10912
10913 /** @type {"color"} */
10914 darken.returns = "color";
10915
10916 var variations = /*#__PURE__*/Object.freeze({
10917 __proto__: null,
10918 darken: darken,
10919 lighten: lighten
10920 });
10921
10922 /** @import { ColorTypes, PlainColorObject, Ref } from "./types.js" */
10923
10924 // Type re-exports
10925 /** @typedef {import("./types.js").MixOptions} MixOptions */
10926 /** @typedef {import("./types.js").Range} Range */
10927 /** @typedef {import("./types.js").RangeOptions} RangeOptions */
10928 /** @typedef {import("./types.js").StepsOptions} StepsOptions */
10929
10930 /**
10931 * Return an intermediate color between two colors
10932 * @overload
10933 * @param {ColorTypes} c1
10934 * @param {ColorTypes} c2
10935 * @param {MixOptions} [options]
10936 * @returns {PlainColorObject}
10937 */
10938 /**
10939 * @overload
10940 * @param {ColorTypes} c1
10941 * @param {ColorTypes} c2
10942 * @param {number} [p=0.5]
10943 * @param {MixOptions} [options]
10944 * @returns {PlainColorObject}
10945 */
10946 function mix(c1, c2, p, o = {}) {
10947 var _p;
10948 [c1, c2] = [getColor(c1), getColor(c2)];
10949 if (type(p) === "object") {
10950 [p, o] = [0.5, p];
10951 }
10952 let r = range(c1, c2, o);
10953 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
10954 }
10955
10956 /**
10957 * Get an array of discrete steps
10958 * @overload
10959 * @param {ColorTypes} c1
10960 * @param {ColorTypes} c2
10961 * @param {StepsOptions} [options]
10962 * @returns {PlainColorObject[]}
10963 */
10964 /**
10965 * @overload
10966 * @param {Range} range
10967 * @param {StepsOptions} [options]
10968 * @returns {PlainColorObject[]}
10969 */
10970 function steps(c1, c2, options = {}) {
10971 let colorRange;
10972 if (isRange(c1)) {
10973 // Tweaking existing range
10974 [colorRange, options] = [c1, c2];
10975 [c1, c2] = colorRange.rangeArgs.colors;
10976 }
10977 let {
10978 maxDeltaE,
10979 deltaEMethod,
10980 steps = 2,
10981 maxSteps = 1000,
10982 ...rangeOptions
10983 } = options;
10984 if (!colorRange) {
10985 [c1, c2] = [getColor(c1), getColor(c2)];
10986 colorRange = range(c1, c2, rangeOptions);
10987 }
10988 let totalDelta = deltaE(c1, c2, deltaEMethod);
10989 let actualSteps = maxDeltaE > 0 ? Math.max(steps, Math.ceil(totalDelta / maxDeltaE) + 1) : steps;
10990 let ret = [];
10991 if (maxSteps !== undefined) {
10992 actualSteps = Math.min(actualSteps, maxSteps);
10993 }
10994 if (actualSteps === 1) {
10995 ret = [{
10996 p: 0.5,
10997 color: colorRange(0.5)
10998 }];
10999 } else {
11000 let step = 1 / (actualSteps - 1);
11001 ret = Array.from({
11002 length: actualSteps
11003 }, (_, i) => {
11004 let p = i * step;
11005 return {
11006 p,
11007 color: colorRange(p)
11008 };
11009 });
11010 }
11011 if (maxDeltaE > 0) {
11012 // Iterate over all stops and find max deltaE
11013 let maxDelta = ret.reduce((acc, cur, i) => {
11014 if (i === 0) {
11015 return 0;
11016 }
11017 let ΔΕ = deltaE(cur.color, ret[i - 1].color, deltaEMethod);
11018 return Math.max(acc, ΔΕ);
11019 }, 0);
11020 while (maxDelta > maxDeltaE) {
11021 // Insert intermediate stops and measure maxDelta again
11022 // We need to do this for all pairs, otherwise the midpoint shifts
11023 maxDelta = 0;
11024 for (let i = 1; i < ret.length && ret.length < maxSteps; i++) {
11025 let prev = ret[i - 1];
11026 let cur = ret[i];
11027 let p = (cur.p + prev.p) / 2;
11028 let color = colorRange(p);
11029 maxDelta = Math.max(maxDelta, deltaE(color, prev.color, deltaEMethod), deltaE(color, cur.color, deltaEMethod));
11030 ret.splice(i, 0, {
11031 p,
11032 color: colorRange(p)
11033 });
11034 i++;
11035 }
11036 }
11037 }
11038 ret = ret.map(a => a.color);
11039 return ret;
11040 }
11041
11042 /**
11043 * Creates a function that accepts a number and returns a color.
11044 * For numbers in the range 0 to 1, the function interpolates;
11045 * for numbers outside that range, the function extrapolates
11046 * (and thus may not return the results you expect)
11047 * @overload
11048 * @param {Range} range
11049 * @param {RangeOptions} [options]
11050 * @returns {Range}
11051 */
11052 /**
11053 * @overload
11054 * @param {ColorTypes} color1
11055 * @param {ColorTypes} color2
11056 * @param {RangeOptions & Record<string, any>} [options]
11057 * @returns {Range}
11058 */
11059 function range(color1, color2, options = {}) {
11060 if (isRange(color1)) {
11061 // Tweaking existing range
11062 let [r, options] = [color1, color2];
11063 return range(...r.rangeArgs.colors, {
11064 ...r.rangeArgs.options,
11065 ...options
11066 });
11067 }
11068 let {
11069 space,
11070 outputSpace,
11071 progression,
11072 premultiplied
11073 } = options;
11074 color1 = getColor(color1);
11075 color2 = getColor(color2);
11076
11077 // Make sure we're working on copies of these colors
11078 color1 = clone(color1);
11079 color2 = clone(color2);
11080 let rangeArgs = {
11081 colors: [color1, color2],
11082 options
11083 };
11084 if (space) {
11085 space = ColorSpace.get(space);
11086 } else {
11087 space = ColorSpace.registry[defaults.interpolationSpace] || color1.space;
11088 }
11089 outputSpace = outputSpace ? ColorSpace.get(outputSpace) : space;
11090 color1 = to(color1, space);
11091 color2 = to(color2, space);
11092
11093 // Gamut map to avoid areas of flat color
11094 color1 = toGamut(color1);
11095 color2 = toGamut(color2);
11096
11097 // The hue coordinate is not always called "h" (e.g. it's "hz" in Jzczhz)
11098 let hueId = space.hueId;
11099 let hueIndex = space.hueIndex;
11100
11101 // Handle hue interpolation
11102 // See https://github.com/w3c/csswg-drafts/issues/4735#issuecomment-635741840
11103 if (hueId) {
11104 let arc = options.hue = options.hue || "shorter";
11105 let /** @type {Ref} */hue = [space, hueId];
11106 let [θ1, θ2] = [get(color1, hue), get(color2, hue)];
11107 // Undefined hues must be evaluated before hue fix-up to properly
11108 // calculate hue arcs between undefined and defined hues.
11109 // See https://github.com/w3c/csswg-drafts/issues/9436#issuecomment-1746957545
11110 if (isNone(θ1) && !isNone(θ2)) {
11111 θ1 = θ2;
11112 } else if (isNone(θ2) && !isNone(θ1)) {
11113 θ2 = θ1;
11114 }
11115 [θ1, θ2] = adjust(arc, [θ1, θ2]);
11116 set(color1, hue, θ1);
11117 set(color2, hue, θ2);
11118 }
11119
11120 // An undefined alpha takes the other color's alpha, and premultiplication must use
11121 // that carried forward value, rather than the zero it would otherwise be treated as.
11122 // If both alphas are undefined, they stay that way, and no premultiplication happens.
11123 // See https://drafts.csswg.org/css-color-4/#interpolation-missing
11124 if (isNone(color1.alpha) && !isNone(color2.alpha)) {
11125 color1.alpha = color2.alpha;
11126 } else if (isNone(color2.alpha) && !isNone(color1.alpha)) {
11127 color2.alpha = color1.alpha;
11128 }
11129 if (premultiplied) {
11130 color1.coords = premultiply(color1.coords, color1.alpha, hueIndex);
11131 color2.coords = premultiply(color2.coords, color2.alpha, hueIndex);
11132 }
11133 return Object.assign(p => {
11134 p = progression ? progression(p) : p;
11135 let coords = color1.coords.map((start, i) => {
11136 let end = color2.coords[i];
11137 return interpolate(start, end, p);
11138 });
11139 let alpha = interpolate(color1.alpha, color2.alpha, p);
11140 let ret = {
11141 space,
11142 coords,
11143 alpha
11144 };
11145 if (premultiplied) {
11146 // Undo premultiplication, again leaving any hue angle untouched
11147 ret.coords = premultiply(ret.coords, alpha, hueIndex, true);
11148 }
11149 if (outputSpace !== space) {
11150 ret = to(ret, outputSpace);
11151 }
11152 return ret;
11153 }, {
11154 rangeArgs
11155 });
11156 }
11157
11158 /**
11159 * Premultiply a color's coordinates by its alpha, or undo premultiplication by dividing by it.
11160 * Per CSS Color 4, the hue angle of a polar space is never premultiplied,
11161 * `none` components stay `none`, a `none` alpha means no (un)premultiplication happens at all,
11162 * and un-premultiplying by a zero alpha leaves the coords as they are, rather than dividing by zero.
11163 * See https://drafts.csswg.org/css-color-4/#interpolation-alpha
11164 * @param {(number | null)[]} coords
11165 * @param {number | null} alpha
11166 * @param {number} hueIndex - Index of the hue coordinate, or -1 if the space has none
11167 * @param {boolean} [undo=false] - Divide by alpha instead of multiplying by it
11168 * @returns {[number, number, number]}
11169 */
11170 function premultiply(coords, alpha, hueIndex, undo = false) {
11171 if (isNone(alpha) || undo && alpha === 0) {
11172 // The (un-)premultiplied value is the value itself
11173 return /** @type {[number, number, number]} */coords;
11174 }
11175 return /** @type {[number, number, number]} */coords.map((c, i) => {
11176 if (i === hueIndex || isNone(c)) {
11177 return c;
11178 }
11179 return undo ? c / alpha : c * alpha;
11180 });
11181 }
11182
11183 /**
11184 * @param {any} val
11185 * @returns {val is Range}
11186 */
11187 function isRange(val) {
11188 return type(val) === "function" && !!val.rangeArgs;
11189 }
11190 defaults.interpolationSpace = "lab";
11191
11192 /**
11193 * @param {typeof import("./color.js").default} Color
11194 */
11195 function register(Color) {
11196 Color.defineFunction("mix", mix, {
11197 returns: "color"
11198 });
11199 Color.defineFunction("range", range, {
11200 returns: "function<color>"
11201 });
11202 Color.defineFunction("steps", steps, {
11203 returns: "array<color>"
11204 });
11205 }
11206
11207 var interpolation = /*#__PURE__*/Object.freeze({
11208 __proto__: null,
11209 isRange: isRange,
11210 mix: mix,
11211 range: range,
11212 register: register,
11213 steps: steps
11214 });
11215
11216 var HSL = new ColorSpace({
11217 id: "hsl",
11218 name: "HSL",
11219 coords: {
11220 h: {
11221 refRange: [0, 360],
11222 type: "angle",
11223 name: "Hue"
11224 },
11225 s: {
11226 range: [0, 100],
11227 name: "Saturation"
11228 },
11229 l: {
11230 range: [0, 100],
11231 name: "Lightness"
11232 }
11233 },
11234 base: sRGB,
11235 rgbGamut: sRGB,
11236 // Adapted from https://drafts.csswg.org/css-color-4/better-rgbToHsl.js
11237 fromBase: rgb => {
11238 let max = Math.max(...rgb);
11239 let min = Math.min(...rgb);
11240 let [r, g, b] = rgb;
11241 let [h, s, l] = [null, 0, (min + max) / 2];
11242 let d = max - min;
11243 if (d !== 0) {
11244 s = l === 0 || l === 1 ? 0 : (max - l) / Math.min(l, 1 - l);
11245 switch (max) {
11246 case r:
11247 h = (g - b) / d + (g < b ? 6 : 0);
11248 break;
11249 case g:
11250 h = (b - r) / d + 2;
11251 break;
11252 case b:
11253 h = (r - g) / d + 4;
11254 }
11255 h = h * 60;
11256 }
11257
11258 // Very out of gamut colors can produce negative saturation
11259 // If so, just rotate the hue by 180 and use a positive saturation
11260 // see https://github.com/w3c/csswg-drafts/issues/9222
11261 if (s < 0) {
11262 h += 180;
11263 s = Math.abs(s);
11264 }
11265 if (h >= 360) {
11266 h -= 360;
11267 }
11268 return [h, s * 100, l * 100];
11269 },
11270 // Adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSL_to_RGB_alternative
11271 toBase: hsl => {
11272 let [h, s, l] = hsl;
11273 h = h % 360;
11274 if (h < 0) {
11275 h += 360;
11276 }
11277 s /= 100;
11278 l /= 100;
11279 function f(n) {
11280 let k = (n + h / 30) % 12;
11281 let a = s * Math.min(l, 1 - l);
11282 return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));
11283 }
11284 return [f(0), f(8), f(4)];
11285 },
11286 formats: {
11287 hsl: {
11288 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
11289 },
11290 hsla: {
11291 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"],
11292 commas: true,
11293 alpha: true
11294 }
11295 }
11296 });
11297
11298 var hslP3 = new ColorSpace({
11299 id: "hsl-p3",
11300 cssId: "--hsl-p3",
11301 name: "HSL P3",
11302 coords: {
11303 h: {
11304 refRange: [0, 360],
11305 type: "angle",
11306 name: "Hue"
11307 },
11308 s: {
11309 range: [0, 100],
11310 name: "Saturation"
11311 },
11312 l: {
11313 range: [0, 100],
11314 name: "Lightness"
11315 }
11316 },
11317 base: P3,
11318 rgbGamut: P3,
11319 fromBase: HSL.fromBase,
11320 toBase: HSL.toBase
11321 });
11322
11323 var hslRec2020 = new ColorSpace({
11324 id: "hsl-rec2020",
11325 cssId: "--hsl-rec2020",
11326 name: "HSL Rec.2020",
11327 coords: {
11328 h: {
11329 refRange: [0, 360],
11330 type: "angle",
11331 name: "Hue"
11332 },
11333 s: {
11334 range: [0, 100],
11335 name: "Saturation"
11336 },
11337 l: {
11338 range: [0, 100],
11339 name: "Lightness"
11340 }
11341 },
11342 base: REC2020,
11343 rgbGamut: REC2020,
11344 fromBase: HSL.fromBase,
11345 toBase: HSL.toBase
11346 });
11347
11348 // Note that, like HSL, calculations are done directly on
11349 // gamma-corrected sRGB values rather than linearising them first.
11350
11351 var HSV = new ColorSpace({
11352 id: "hsv",
11353 name: "HSV",
11354 coords: {
11355 h: {
11356 refRange: [0, 360],
11357 type: "angle",
11358 name: "Hue"
11359 },
11360 s: {
11361 range: [0, 100],
11362 name: "Saturation"
11363 },
11364 v: {
11365 range: [0, 100],
11366 name: "Value"
11367 }
11368 },
11369 base: sRGB,
11370 rgbGamut: sRGB,
11371 // https://en.wikipedia.org/wiki/HSL_and_HSV#Formal_derivation
11372 fromBase(rgb) {
11373 let max = Math.max(...rgb);
11374 let min = Math.min(...rgb);
11375 let [r, g, b] = rgb;
11376 let [h, s, v] = [null, 0, max];
11377 let d = max - min;
11378 if (d !== 0) {
11379 switch (max) {
11380 case r:
11381 h = (g - b) / d + (g < b ? 6 : 0);
11382 break;
11383 case g:
11384 h = (b - r) / d + 2;
11385 break;
11386 case b:
11387 h = (r - g) / d + 4;
11388 }
11389 h = h * 60;
11390 }
11391 if (v) {
11392 s = d / v;
11393 }
11394 if (h >= 360) {
11395 h -= 360;
11396 }
11397 return [h, s * 100, v * 100];
11398 },
11399 // Adapted from https://en.wikipedia.org/wiki/HSL_and_HSV#HSV_to_RGB_alternative
11400 toBase(hsv) {
11401 let [h, s, v] = hsv;
11402 h = h % 360;
11403 if (h < 0) {
11404 h += 360;
11405 }
11406 s /= 100;
11407 v /= 100;
11408 function f(n) {
11409 let k = (n + h / 60) % 6;
11410 return v - v * s * Math.max(0, Math.min(k, 4 - k, 1));
11411 }
11412 return [f(5), f(3), f(1)];
11413 },
11414 formats: {
11415 color: {
11416 id: "--hsv",
11417 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
11418 }
11419 }
11420 });
11421
11422 // The Hue, Whiteness Blackness (HWB) colorspace
11423 // See https://drafts.csswg.org/css-color-4/#the-hwb-notation
11424 // Note that, like HSL, calculations are done directly on
11425 // gamma-corrected sRGB values rather than linearising them first.
11426
11427 var hwb = new ColorSpace({
11428 id: "hwb",
11429 name: "HWB",
11430 coords: {
11431 h: {
11432 refRange: [0, 360],
11433 type: "angle",
11434 name: "Hue"
11435 },
11436 w: {
11437 range: [0, 100],
11438 name: "Whiteness"
11439 },
11440 b: {
11441 range: [0, 100],
11442 name: "Blackness"
11443 }
11444 },
11445 base: HSV,
11446 rgbGamut: sRGB,
11447 fromBase(hsv) {
11448 let [h, s, v] = hsv;
11449 return [h, v * (100 - s) / 100, 100 - v];
11450 },
11451 toBase(hwb) {
11452 let [h, w, b] = hwb;
11453
11454 // Now convert percentages to [0..1]
11455 w /= 100;
11456 b /= 100;
11457
11458 // Achromatic check (white plus black >= 1)
11459 let sum = w + b;
11460 if (sum >= 1) {
11461 let gray = w / sum;
11462 return [h, 0, gray * 100];
11463 }
11464 let v = 1 - b;
11465 let s = v === 0 ? 0 : 1 - w / v;
11466 return [h, s * 100, v * 100];
11467 },
11468 formats: {
11469 hwb: {
11470 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
11471 }
11472 }
11473 });
11474
11475 /** @import { Matrix3x3 } from "../types.js" */
11476
11477 // convert an array of linear-light a98-rgb values to CIE XYZ
11478 // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
11479 // has greater numerical precision than section 4.3.5.3 of
11480 // https://www.adobe.com/digitalimag/pdfs/AdobeRGB1998.pdf
11481 // but the values below were calculated from first principles
11482 // from the chromaticity coordinates of R G B W
11483
11484 /**
11485 * Matrices used by this color space, also available as `A98RGB_Linear.M`
11486 * @type {Record<string, Matrix3x3>}
11487 */
11488 // prettier-ignore
11489 const M$5 = {
11490 toXYZ: [[0.5766690429101305, 0.1855582379065463, 0.1882286462349947], [0.29734497525053605, 0.6273635662554661, 0.07529145849399788], [0.02703136138641234, 0.07068885253582723, 0.9913375368376388]],
11491 fromXYZ: [[2.0415879038107465, -0.5650069742788596, -0.34473135077832956], [-0.9692436362808795, 1.8759675015077202, 0.04155505740717557], [0.013444280632031142, -0.11836239223101838, 1.0151749943912054]]
11492 };
11493 var A98Linear = new RGBColorSpace({
11494 id: "a98rgb-linear",
11495 cssId: "--a98-rgb-linear",
11496 name: "Linear Adobe® 98 RGB compatible",
11497 white: "D65",
11498 M: M$5
11499 });
11500
11501 var a98rgb = new RGBColorSpace({
11502 id: "a98rgb",
11503 cssId: "a98-rgb",
11504 name: "Adobe® 98 RGB compatible",
11505 base: A98Linear,
11506 linearGamut: A98Linear,
11507 toBase: RGB => RGB.map(val => Math.pow(Math.abs(val), 563 / 256) * Math.sign(val)),
11508 fromBase: RGB => RGB.map(val => Math.pow(Math.abs(val), 256 / 563) * Math.sign(val))
11509 });
11510
11511 /** @import { Matrix3x3 } from "../types.js" */
11512
11513 /**
11514 * Matrices used by this color space, also available as `ProPhoto_Linear.M`.
11515 * Uses D50 (so no chromatic adaptation needed afterwards). The matrix cannot
11516 * be expressed in rational form, but is calculated to 64 bit accuracy.
11517 * see https://github.com/w3c/csswg-drafts/issues/7675
11518 * @type {Record<string, Matrix3x3>}
11519 */
11520 // prettier-ignore
11521 const M$4 = {
11522 toXYZ: [[0.79776664490064230, 0.13518129740053308, 0.03134773412839220], [0.28807482881940130, 0.71183523424187300, 0.00008993693872564], [0.00000000000000000, 0.00000000000000000, 0.82510460251046020]],
11523 fromXYZ: [[1.34578688164715830, -0.25557208737979464, -0.05110186497554526], [-0.54463070512490190, 1.50824774284514680, 0.02052744743642139], [0.00000000000000000, 0.00000000000000000, 1.21196754563894520]]
11524 };
11525 var ProPhotoLinear = new RGBColorSpace({
11526 id: "prophoto-linear",
11527 cssId: "--prophoto-rgb-linear",
11528 name: "Linear ProPhoto",
11529 white: "D50",
11530 base: XYZ_D50,
11531 M: M$4
11532 });
11533
11534 const Et = 1 / 512;
11535 const Et2 = 16 / 512;
11536 var prophoto = new RGBColorSpace({
11537 id: "prophoto",
11538 cssId: "prophoto-rgb",
11539 name: "ProPhoto",
11540 base: ProPhotoLinear,
11541 linearGamut: ProPhotoLinear,
11542 toBase(RGB) {
11543 // Transfer curve is gamma 1.8 with a small linear portion
11544 return RGB.map(v => {
11545 let sign = v < 0 ? -1 : 1;
11546 let abs = v * sign;
11547 if (abs < Et2) {
11548 return v / 16;
11549 }
11550 return sign * abs ** 1.8;
11551 });
11552 },
11553 fromBase(RGB) {
11554 return RGB.map(v => {
11555 let sign = v < 0 ? -1 : 1;
11556 let abs = v * sign;
11557 if (abs >= Et) {
11558 return sign * abs ** (1 / 1.8);
11559 }
11560 return 16 * v;
11561 });
11562 }
11563 });
11564
11565 // import sRGB from "./srgb.js";
11566
11567 const α = 1.09929682680944;
11568 const β = 0.018053968510807;
11569 var rec2020Oetf = new RGBColorSpace({
11570 id: "--rec2020-oetf",
11571 name: "REC.2020_Scene_Referred",
11572 base: REC2020Linear,
11573 linearGamut: REC2020Linear,
11574 referred: "scene",
11575 // Non-linear transfer function from Rec. ITU-R BT.2020-2 table 4
11576 toBase(RGB) {
11577 return RGB.map(function (val) {
11578 let sign = val < 0 ? -1 : 1;
11579 let abs = val * sign;
11580 if (abs < β * 4.5) {
11581 return val / 4.5;
11582 }
11583 return sign * Math.pow((abs + α - 1) / α, 1 / 0.45);
11584 });
11585 },
11586 fromBase(RGB) {
11587 return RGB.map(function (val) {
11588 let sign = val < 0 ? -1 : 1;
11589 let abs = val * sign;
11590 if (abs >= β) {
11591 return sign * (α * Math.pow(abs, 0.45) - (α - 1));
11592 }
11593 return 4.5 * val;
11594 });
11595 }
11596 });
11597
11598 var oklchP3 = new GamutRelativeColorSpace({
11599 id: "oklch-p3",
11600 cssId: "--oklch-p3",
11601 name: "OKLCh P3",
11602 base: OKLCH,
11603 gamutSpace: P3
11604 });
11605
11606 var oklchSrgb = new GamutRelativeColorSpace({
11607 id: "oklch-srgb",
11608 cssId: "--oklch-srgb",
11609 name: "OKLCh sRGB",
11610 base: OKLCH,
11611 gamutSpace: sRGB
11612 });
11613
11614 var oklchRec2020 = new GamutRelativeColorSpace({
11615 id: "oklch-rec2020",
11616 cssId: "--oklch-rec2020",
11617 name: "OKLCh Rec.2020",
11618 base: OKLCH,
11619 gamutSpace: REC2020
11620 });
11621
11622 var lchP3 = new GamutRelativeColorSpace({
11623 id: "lch-p3",
11624 cssId: "--lch-p3",
11625 name: "LCH P3",
11626 base: lch,
11627 gamutSpace: P3
11628 });
11629
11630 var lchSrgb = new GamutRelativeColorSpace({
11631 id: "lch-srgb",
11632 cssId: "--lch-srgb",
11633 name: "LCH sRGB",
11634 base: lch,
11635 gamutSpace: sRGB
11636 });
11637
11638 var lchRec2020 = new GamutRelativeColorSpace({
11639 id: "lch-rec2020",
11640 cssId: "--lch-rec2020",
11641 name: "LCH Rec.2020",
11642 base: lch,
11643 gamutSpace: REC2020
11644 });
11645
11646 /** @import { Matrix3x3, Vector3 } from "../types.js" */
11647
11648 // Type re-exports
11649 /** @typedef {import("../types.js").OKCoeff} OKCoeff */
11650
11651 const tau = 2 * Math.PI;
11652
11653 /**
11654 * Matrices used by this color space (Oklab's, plus its own),
11655 * also available as `Okhsl.M`
11656 * @type {Record<string, Matrix3x3>}
11657 */
11658 // prettier-ignore
11659 const M$3 = {
11660 ...Oklab.M,
11661 toLMS: [[0.4122214694707629, 0.5363325372617349, 0.0514459932675022], [0.2119034958178251, 0.6806995506452344, 0.1073969535369405], [0.0883024591900564, 0.2817188391361215, 0.6299787016738222]],
11662 toSRGBLinear: [[4.0767416360759583, -3.3077115392580629, 0.2309699031821043], [-1.2684379732850315, 2.6097573492876882, -0.3413193760026570], [-0.0041960761386756, -0.7034186179359362, 1.7076146940746117]]
11663 };
11664
11665 /** @type {OKCoeff} */
11666 const RGBCoeff = [
11667 // Red
11668 [
11669 // Limit
11670 [-1.8817031, -0.80936501],
11671 // `Kn` coefficients
11672 [1.19086277, 1.76576728, 0.59662641, 0.75515197, 0.56771245]],
11673 // Green
11674 [
11675 // Limit
11676 [1.8144408, -1.19445267],
11677 // `Kn` coefficients
11678 [0.73956515, -0.45954404, 0.08285427, 0.12541073, -0.14503204]],
11679 // Blue
11680 [
11681 // Limit
11682 [0.13110758, 1.81333971],
11683 // `Kn` coefficients
11684 [1.35733652, -0.00915799, -1.1513021, -0.50559606, 0.00692167]]];
11685 const floatMax = Number.MAX_VALUE;
11686 const K1 = 0.206;
11687 const K2 = 0.03;
11688 const K3 = (1.0 + K1) / (1.0 + K2);
11689 function vdot(a, b) {
11690 // Dot two vectors
11691
11692 let l = a.length;
11693 if (l !== b.length) {
11694 throw new Error(`Vectors of size ${l} and ${b.length} are not aligned`);
11695 }
11696 let s = 0.0;
11697 a.forEach((c, i) => {
11698 s += c * b[i];
11699 });
11700 return s;
11701 }
11702
11703 /**
11704 * Toe function for L_r
11705 * @param {number} x
11706 */
11707 function toe(x) {
11708 return 0.5 * (K3 * x - K1 + Math.sqrt((K3 * x - K1) * (K3 * x - K1) + 4 * K2 * K3 * x));
11709 }
11710
11711 /**
11712 * Inverse toe function for L_r
11713 * @param {number} x
11714 */
11715 function toeInv(x) {
11716 return (x ** 2 + K1 * x) / (K3 * (x + K2));
11717 }
11718
11719 /**
11720 * @param {readonly [number, number]} cusp
11721 * @returns {[number, number]}
11722 */
11723 function toSt(cusp) {
11724 // To ST.
11725
11726 let [l, c] = cusp;
11727 return [c / l, c / (1 - l)];
11728 }
11729 function getStMid(a, b) {
11730 // Returns a smooth approximation of the location of the cusp.
11731 //
11732 // This polynomial was created by an optimization process.
11733 // It has been designed so that S_mid < S_max and T_mid < T_max.
11734
11735 // prettier-ignore
11736 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))));
11737
11738 // prettier-ignore
11739 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))));
11740 return [s, t];
11741 }
11742
11743 /**
11744 * @param {Vector3} lab
11745 * @param {Matrix3x3} lmsToRgb
11746 */
11747 function oklabToLinearRGB(lab, lmsToRgb) {
11748 // Convert from Oklab to linear RGB.
11749 //
11750 // Can be any gamut as long as `lmsToRgb` is a matrix
11751 // that transform the LMS values to the linear RGB space.
11752
11753 let lms = multiply_v3_m3x3(lab, M$3.LabtoLMS);
11754 lms[0] = lms[0] ** 3;
11755 lms[1] = lms[1] ** 3;
11756 lms[2] = lms[2] ** 3;
11757 return multiply_v3_m3x3(lms, lmsToRgb, lms);
11758 }
11759
11760 /**
11761 * @param {number} a
11762 * @param {number} b
11763 * @param {Matrix3x3} lmsToRgb
11764 * @param {OKCoeff} okCoeff
11765 * @returns {[number, number]}
11766 * @todo Could probably make these types more specific/better-documented if desired
11767 */
11768 function findCusp(a, b, lmsToRgb, okCoeff) {
11769 // Finds L_cusp and C_cusp for a given hue.
11770 //
11771 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
11772
11773 // First, find the maximum saturation (saturation `S = C/L`)
11774 let sCusp = computeMaxSaturation(a, b, lmsToRgb, okCoeff);
11775
11776 // Convert to linear RGB to find the first point where at least one of r, g or b >= 1:
11777 let rgb = oklabToLinearRGB([1, sCusp * a, sCusp * b], lmsToRgb);
11778 let lCusp = spow(1.0 / Math.max(...rgb), 1 / 3);
11779 let cCusp = lCusp * sCusp;
11780 return [lCusp, cCusp];
11781 }
11782
11783 /**
11784 * @param {number} a
11785 * @param {number} b
11786 * @param {number} l1
11787 * @param {number} c1
11788 * @param {number} l0
11789 * @param {Matrix3x3} lmsToRgb
11790 * @param {OKCoeff} okCoeff
11791 * @param {[number, number]} cusp
11792 * @returns {Number}
11793 * @todo Could probably make these types more specific/better-documented if desired
11794 */
11795 function findGamutIntersection(a, b, l1, c1, l0, lmsToRgb, okCoeff, cusp) {
11796 // Finds intersection of the line.
11797 //
11798 // Defined by the following:
11799 //
11800 // ```
11801 // L = L0 * (1 - t) + t * L1
11802 // C = t * C1
11803 // ```
11804 //
11805 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
11806
11807 let t;
11808 if (cusp === undefined) {
11809 cusp = findCusp(a, b, lmsToRgb, okCoeff);
11810 }
11811
11812 // Find the intersection for upper and lower half separately
11813 if ((l1 - l0) * cusp[1] - (cusp[0] - l0) * c1 <= 0.0) {
11814 // Lower half
11815 t = cusp[1] * l0 / (c1 * cusp[0] + cusp[1] * (l0 - l1));
11816 } else {
11817 // Upper half
11818
11819 // First intersect with triangle
11820 t = cusp[1] * (l0 - 1.0) / (c1 * (cusp[0] - 1.0) + cusp[1] * (l0 - l1));
11821
11822 // Then one step Halley's method
11823 let dl = l1 - l0;
11824 let dc = c1;
11825 let kl = vdot(M$3.LabtoLMS[0].slice(1), [a, b]);
11826 let km = vdot(M$3.LabtoLMS[1].slice(1), [a, b]);
11827 let ks = vdot(M$3.LabtoLMS[2].slice(1), [a, b]);
11828 let ldt_ = dl + dc * kl;
11829 let mdt_ = dl + dc * km;
11830 let sdt_ = dl + dc * ks;
11831
11832 // If higher accuracy is required, 2 or 3 iterations of the following block can be used:
11833 let L = l0 * (1.0 - t) + t * l1;
11834 let C = t * c1;
11835 let l_ = L + C * kl;
11836 let m_ = L + C * km;
11837 let s_ = L + C * ks;
11838 let l = l_ ** 3;
11839 let m = m_ ** 3;
11840 let s = s_ ** 3;
11841 let ldt = 3 * ldt_ * l_ ** 2;
11842 let mdt = 3 * mdt_ * m_ ** 2;
11843 let sdt = 3 * sdt_ * s_ ** 2;
11844 let ldt2 = 6 * ldt_ ** 2 * l_;
11845 let mdt2 = 6 * mdt_ ** 2 * m_;
11846 let sdt2 = 6 * sdt_ ** 2 * s_;
11847 let r_ = vdot(lmsToRgb[0], [l, m, s]) - 1;
11848 let r1 = vdot(lmsToRgb[0], [ldt, mdt, sdt]);
11849 let r2 = vdot(lmsToRgb[0], [ldt2, mdt2, sdt2]);
11850 let ur = r1 / (r1 * r1 - 0.5 * r_ * r2);
11851 let tr = -r_ * ur;
11852 let g_ = vdot(lmsToRgb[1], [l, m, s]) - 1;
11853 let g1 = vdot(lmsToRgb[1], [ldt, mdt, sdt]);
11854 let g2 = vdot(lmsToRgb[1], [ldt2, mdt2, sdt2]);
11855 let ug = g1 / (g1 * g1 - 0.5 * g_ * g2);
11856 let tg = -g_ * ug;
11857 let b_ = vdot(lmsToRgb[2], [l, m, s]) - 1;
11858 let b1 = vdot(lmsToRgb[2], [ldt, mdt, sdt]);
11859 let b2 = vdot(lmsToRgb[2], [ldt2, mdt2, sdt2]);
11860 let ub = b1 / (b1 * b1 - 0.5 * b_ * b2);
11861 let tb = -b_ * ub;
11862 tr = ur >= 0.0 ? tr : floatMax;
11863 tg = ug >= 0.0 ? tg : floatMax;
11864 tb = ub >= 0.0 ? tb : floatMax;
11865 t += Math.min(tr, Math.min(tg, tb));
11866 }
11867 return t;
11868 }
11869 function getCs(lab, lmsToRgb, okCoeff) {
11870 // Get Cs
11871
11872 let [l, a, b] = lab;
11873 let cusp = findCusp(a, b, lmsToRgb, okCoeff);
11874 let cMax = findGamutIntersection(a, b, l, 1, l, lmsToRgb, okCoeff, cusp);
11875 let stMax = toSt(cusp);
11876
11877 // Scale factor to compensate for the curved part of gamut shape:
11878 let k = cMax / Math.min(l * stMax[0], (1 - l) * stMax[1]);
11879 let stMid = getStMid(a, b);
11880
11881 // Use a soft minimum function, instead of a sharp triangle shape to get a smooth value for chroma.
11882 let ca = l * stMid[0];
11883 let cb = (1.0 - l) * stMid[1];
11884 let cMid = 0.9 * k * Math.sqrt(Math.sqrt(1.0 / (1.0 / ca ** 4 + 1.0 / cb ** 4)));
11885
11886 // For `C_0`, the shape is independent of hue, so `ST` are constant.
11887 // Values picked to roughly be the average values of `ST`.
11888 ca = l * 0.4;
11889 cb = (1.0 - l) * 0.8;
11890
11891 // Use a soft minimum function, instead of a sharp triangle shape to get a smooth value for chroma.
11892 let c0 = Math.sqrt(1.0 / (1.0 / ca ** 2 + 1.0 / cb ** 2));
11893 return [c0, cMid, cMax];
11894 }
11895 function computeMaxSaturation(a, b, lmsToRgb, okCoeff) {
11896 // Finds the maximum saturation possible for a given hue that fits in RGB.
11897 //
11898 // Saturation here is defined as `S = C/L`.
11899 // `a` and `b` must be normalized so `a^2 + b^2 == 1`.
11900
11901 // Max saturation will be when one of r, g or b goes below zero.
11902
11903 // Select different coefficients depending on which component goes below zero first.
11904
11905 let k0, k1, k2, k3, k4, wl, wm, ws;
11906 if (vdot(okCoeff[0][0], [a, b]) > 1) {
11907 // Red component
11908 [k0, k1, k2, k3, k4] = okCoeff[0][1];
11909 [wl, wm, ws] = lmsToRgb[0];
11910 } else if (vdot(okCoeff[1][0], [a, b]) > 1) {
11911 // Green component
11912 [k0, k1, k2, k3, k4] = okCoeff[1][1];
11913 [wl, wm, ws] = lmsToRgb[1];
11914 } else {
11915 // Blue component
11916 [k0, k1, k2, k3, k4] = okCoeff[2][1];
11917 [wl, wm, ws] = lmsToRgb[2];
11918 }
11919
11920 // Approximate max saturation using a polynomial:
11921 let sat = k0 + k1 * a + k2 * b + k3 * a ** 2 + k4 * a * b;
11922
11923 // Do one step Halley's method to get closer.
11924 // This gives an error less than 10e6, except for some blue hues where the `dS/dh` is close to infinite.
11925 // This should be sufficient for most applications, otherwise do two/three steps.
11926
11927 let kl = vdot(M$3.LabtoLMS[0].slice(1), [a, b]);
11928 let km = vdot(M$3.LabtoLMS[1].slice(1), [a, b]);
11929 let ks = vdot(M$3.LabtoLMS[2].slice(1), [a, b]);
11930 let l_ = 1.0 + sat * kl;
11931 let m_ = 1.0 + sat * km;
11932 let s_ = 1.0 + sat * ks;
11933 let l = l_ ** 3;
11934 let m = m_ ** 3;
11935 let s = s_ ** 3;
11936 let lds = 3.0 * kl * l_ ** 2;
11937 let mds = 3.0 * km * m_ ** 2;
11938 let sds = 3.0 * ks * s_ ** 2;
11939 let lds2 = 6.0 * kl ** 2 * l_;
11940 let mds2 = 6.0 * km ** 2 * m_;
11941 let sds2 = 6.0 * ks ** 2 * s_;
11942 let f = wl * l + wm * m + ws * s;
11943 let f1 = wl * lds + wm * mds + ws * sds;
11944 let f2 = wl * lds2 + wm * mds2 + ws * sds2;
11945 sat = sat - f * f1 / (f1 ** 2 - 0.5 * f * f2);
11946 return sat;
11947 }
11948 function okhslToOklab(hsl, lmsToRgb, okCoeff) {
11949 // Convert Okhsl to Oklab.
11950
11951 let [h, s, l] = hsl;
11952 let L = toeInv(l);
11953 let a = null;
11954 let b = null;
11955 h = constrain(h) / 360.0;
11956 if (L !== 0.0 && L !== 1.0 && s !== 0) {
11957 let a_ = Math.cos(tau * h);
11958 let b_ = Math.sin(tau * h);
11959 let [c0, cMid, cMax] = getCs([L, a_, b_], lmsToRgb, okCoeff);
11960
11961 // Interpolate the three values for C so that:
11962 // ```
11963 // At s=0: dC/ds = C_0, C=0
11964 // At s=0.8: C=C_mid
11965 // At s=1.0: C=C_max
11966 // ```
11967
11968 let mid = 0.8;
11969 let midInv = 1.25;
11970 let t, k0, k1, k2;
11971 if (s < mid) {
11972 t = midInv * s;
11973 k0 = 0.0;
11974 k1 = mid * c0;
11975 k2 = 1.0 - k1 / cMid;
11976 } else {
11977 t = 5 * (s - 0.8);
11978 k0 = cMid;
11979 k1 = 0.2 * cMid ** 2 * 1.25 ** 2 / c0;
11980 k2 = 1.0 - k1 / (cMax - cMid);
11981 }
11982 let c = k0 + t * k1 / (1.0 - k2 * t);
11983 a = c * a_;
11984 b = c * b_;
11985 }
11986 return [L, a, b];
11987 }
11988 function oklabToOkhsl(lab, lmsToRgb, okCoeff) {
11989 // Oklab to Okhsl.
11990
11991 // Epsilon for lightness should approach close to 32 bit lightness
11992 // Epsilon for saturation just needs to be sufficiently close when denoting achromatic
11993 let εL = 1e-7;
11994 let εS = 1e-4;
11995 let L = lab[0];
11996 let s = 0.0;
11997 let l = toe(L);
11998 let c = Math.sqrt(lab[1] ** 2 + lab[2] ** 2);
11999 let h = 0.5 + Math.atan2(-lab[2], -lab[1]) / tau;
12000 if (l !== 0.0 && l !== 1.0 && c !== 0) {
12001 let a_ = lab[1] / c;
12002 let b_ = lab[2] / c;
12003 let [c0, cMid, cMax] = getCs([L, a_, b_], lmsToRgb, okCoeff);
12004 let mid = 0.8;
12005 let midInv = 1.25;
12006 let k0, k1, k2, t;
12007 if (c < cMid) {
12008 k1 = mid * c0;
12009 k2 = 1.0 - k1 / cMid;
12010 t = c / (k1 + k2 * c);
12011 s = t * mid;
12012 } else {
12013 k0 = cMid;
12014 k1 = 0.2 * cMid ** 2 * midInv ** 2 / c0;
12015 k2 = 1.0 - k1 / (cMax - cMid);
12016 t = (c - k0) / (k1 + k2 * (c - k0));
12017 s = mid + 0.2 * t;
12018 }
12019 }
12020 const achromatic = Math.abs(s) < εS;
12021 if (achromatic || l === 0.0 || Math.abs(1 - l) < εL) {
12022 h = null;
12023 // Due to floating point imprecision near lightness of 1, we can end up
12024 // with really high around white, this is to provide consistency as
12025 // saturation can be really high for white due this imprecision.
12026 if (!achromatic) {
12027 s = 0.0;
12028 }
12029 } else {
12030 h = constrain(h * 360);
12031 }
12032 return [h, s, l];
12033 }
12034 const Okhsl = new ColorSpace({
12035 id: "okhsl",
12036 name: "Okhsl",
12037 coords: {
12038 h: {
12039 refRange: [0, 360],
12040 type: "angle",
12041 name: "Hue"
12042 },
12043 s: {
12044 range: [0, 1],
12045 name: "Saturation"
12046 },
12047 l: {
12048 range: [0, 1],
12049 name: "Lightness"
12050 }
12051 },
12052 base: Oklab,
12053 gamutSpace: "self",
12054 M: M$3,
12055 // Convert Oklab to Okhsl
12056 fromBase(lab) {
12057 return oklabToOkhsl(lab, M$3.toSRGBLinear, RGBCoeff);
12058 },
12059 // Convert Okhsl to Oklab
12060 toBase(hsl) {
12061 return okhslToOklab(hsl, M$3.toSRGBLinear, RGBCoeff);
12062 },
12063 formats: {
12064 color: {
12065 id: "--okhsl",
12066 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
12067 }
12068 }
12069 });
12070 Okhsl.rgbGamut = new RGBColorSpace({
12071 id: "okhsl-prism",
12072 cssId: "--okhsl-prism",
12073 name: "Okhsl Prism",
12074 base: Okhsl,
12075 fromBase(hsl) {
12076 return HSL.toBase([hsl[0], hsl[1] * 100, hsl[2] * 100]);
12077 },
12078 toBase(rgb) {
12079 const hsl = HSL.fromBase(rgb);
12080 hsl[1] /= 100;
12081 hsl[2] /= 100;
12082 return hsl;
12083 }
12084 });
12085
12086 var OKLrab = new ColorSpace({
12087 id: "oklrab",
12088 name: "Oklrab",
12089 coords: {
12090 l: {
12091 refRange: [0, 1],
12092 name: "Lightness"
12093 },
12094 a: {
12095 refRange: [-0.4, 0.4]
12096 },
12097 b: {
12098 refRange: [-0.4, 0.4]
12099 }
12100 },
12101 // Note that XYZ is relative to D65
12102 white: "D65",
12103 base: Oklab,
12104 fromBase(oklab) {
12105 return [toe(oklab[0]), oklab[1], oklab[2]];
12106 },
12107 toBase(oklrab) {
12108 return [toeInv(oklrab[0]), oklrab[1], oklrab[2]];
12109 },
12110 formats: {
12111 color: {
12112 coords: ["<percentage> | <number>", "<number> | <percentage>[-1,1]", "<number> | <percentage>[-1,1]"]
12113 }
12114 }
12115 });
12116
12117 var oklrch = new ColorSpace({
12118 id: "oklrch",
12119 name: "Oklrch",
12120 coords: {
12121 l: {
12122 refRange: [0, 1],
12123 name: "Lightness"
12124 },
12125 c: {
12126 refRange: [0, 0.4],
12127 name: "Chroma"
12128 },
12129 h: {
12130 refRange: [0, 360],
12131 type: "angle",
12132 name: "Hue"
12133 }
12134 },
12135 white: "D65",
12136 base: OKLrab,
12137 fromBase: lch.fromBase,
12138 toBase: lch.toBase,
12139 formats: {
12140 color: {
12141 coords: ["<percentage> | <number>", "<number> | <percentage>[0,1]", "<number> | <angle>"]
12142 }
12143 }
12144 });
12145
12146 // Okhsv class.
12147 //
12148 // ---- License ----
12149 //
12150 // Copyright (c) 2021 Björn Ottosson
12151 //
12152 // Permission is hereby granted, free of charge, to any person obtaining a copy of
12153 // this software and associated documentation files (the "Software"), to deal in
12154 // the Software without restriction, including without limitation the rights to
12155 // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
12156 // of the Software, and to permit persons to whom the Software is furnished to do
12157 // so, subject to the following conditions:
12158 //
12159 // The above copyright notice and this permission notice shall be included in all
12160 // copies or substantial portions of the Software.
12161 //
12162 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12163 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12164 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
12165 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
12166 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
12167 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
12168 // SOFTWARE.
12169
12170 /**
12171 * Matrices used by this color space (reused from Okhsl), also available as `Okhsv.M`
12172 * @type {Record<string, Matrix3x3>}
12173 */
12174 const M$2 = {
12175 toSRGBLinear: Okhsl.M.toSRGBLinear
12176 };
12177
12178 /** @import { Coords, Matrix3x3, OKCoeff, Vector3 } from "../types.js" */
12179
12180 /**
12181 *
12182 * @param {Vector3} hsv
12183 * @param {Matrix3x3} lmsToRgb
12184 * @param {OKCoeff} okCoeff
12185 * @returns {Coords}
12186 */
12187 function okhsvToOklab(hsv, lmsToRgb, okCoeff) {
12188 // Convert from Okhsv to Oklab."""
12189
12190 let [h, s, v] = hsv;
12191 h = constrain(h) / 360.0;
12192 let l = toeInv(v);
12193 let a = null;
12194 let b = null;
12195
12196 // Avoid processing gray or colors with undefined hues
12197 if (l !== 0.0 && s !== 0.0) {
12198 let a_ = Math.cos(tau * h);
12199 let b_ = Math.sin(tau * h);
12200 let cusp = findCusp(a_, b_, lmsToRgb, okCoeff);
12201 let [sMax, tMax] = toSt(cusp);
12202 let s0 = 0.5;
12203 let k = 1 - s0 / sMax;
12204
12205 // first we compute L and V as if the gamut is a perfect triangle:
12206
12207 // L, C when v==1:
12208 let lv = 1 - s * s0 / (s0 + tMax - tMax * k * s);
12209 let cv = s * tMax * s0 / (s0 + tMax - tMax * k * s);
12210 l = v * lv;
12211 let c = v * cv;
12212
12213 // then we compensate for both toe and the curved top part of the triangle:
12214 let lvt = toeInv(lv);
12215 let cvt = cv * lvt / lv;
12216 let lNew = toeInv(l);
12217 c = c * lNew / l;
12218 l = lNew;
12219
12220 // RGB scale
12221 let [rs, gs, bs] = oklabToLinearRGB([lvt, a_ * cvt, b_ * cvt], lmsToRgb);
12222 let scaleL = spow(1.0 / Math.max(Math.max(rs, gs), Math.max(bs, 0.0)), 1 / 3);
12223 l = l * scaleL;
12224 c = c * scaleL;
12225 a = c * a_;
12226 b = c * b_;
12227 }
12228 return [l, a, b];
12229 }
12230
12231 /**
12232 *
12233 * @param {Vector3} lab
12234 * @param {Matrix3x3} lmsToRgb
12235 * @param {OKCoeff} okCoeff
12236 * @returns {Coords}
12237 */
12238 function oklabToOkhsv(lab, lmsToRgb, okCoeff) {
12239 // Oklab to Okhsv.
12240
12241 // Epsilon for saturation just needs to be sufficiently close when denoting achromatic
12242 let ε = 1e-4;
12243 let l = lab[0];
12244 let s = 0.0;
12245 let v = toe(l);
12246 let c = Math.sqrt(lab[1] ** 2 + lab[2] ** 2);
12247 let h = 0.5 + Math.atan2(-lab[2], -lab[1]) / tau;
12248 if (l !== 0.0 && l !== 1 && c !== 0.0) {
12249 let a_ = lab[1] / c;
12250 let b_ = lab[2] / c;
12251 let cusp = findCusp(a_, b_, lmsToRgb, okCoeff);
12252 let [sMax, tMax] = toSt(cusp);
12253 let s0 = 0.5;
12254 let k = 1 - s0 / sMax;
12255
12256 // first we find `L_v`, `C_v`, `L_vt` and `C_vt`
12257 let t = tMax / (c + l * tMax);
12258 let lv = t * l;
12259 let cv = t * c;
12260 let lvt = toeInv(lv);
12261 let cvt = cv * lvt / lv;
12262
12263 // we can then use these to invert the step that compensates
12264 // for the toe and the curved top part of the triangle:
12265 let [rs, gs, bs] = oklabToLinearRGB([lvt, a_ * cvt, b_ * cvt], lmsToRgb);
12266 let scaleL = spow(1.0 / Math.max(Math.max(rs, gs), Math.max(bs, 0.0)), 1 / 3);
12267 l = l / scaleL;
12268 c = c / scaleL;
12269 c = c * toe(l) / l;
12270 l = toe(l);
12271
12272 // we can now compute v and s:
12273 v = l / lv;
12274 s = (s0 + tMax) * cv / (tMax * s0 + tMax * k * cv);
12275 }
12276 if (Math.abs(s) < ε || v === 0.0) {
12277 h = null;
12278 } else {
12279 h = constrain(h * 360);
12280 }
12281 return [h, s, v];
12282 }
12283 const Okhsv = new ColorSpace({
12284 id: "okhsv",
12285 name: "Okhsv",
12286 coords: {
12287 h: {
12288 refRange: [0, 360],
12289 type: "angle",
12290 name: "Hue"
12291 },
12292 s: {
12293 range: [0, 1],
12294 name: "Saturation"
12295 },
12296 v: {
12297 range: [0, 1],
12298 name: "Value"
12299 }
12300 },
12301 base: Oklab,
12302 gamutSpace: "self",
12303 M: M$2,
12304 // Convert Oklab to Okhsl
12305 fromBase(lab) {
12306 return oklabToOkhsv(lab, M$2.toSRGBLinear, RGBCoeff);
12307 },
12308 // Convert Okhsl to Oklab
12309 toBase(hsl) {
12310 return okhsvToOklab(hsl, M$2.toSRGBLinear, RGBCoeff);
12311 },
12312 formats: {
12313 color: {
12314 id: "--okhsv",
12315 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
12316 }
12317 }
12318 });
12319 Okhsv.rgbGamut = new RGBColorSpace({
12320 id: "okhsv-prism",
12321 cssId: "--okhsv-prism",
12322 name: "Okhsv Prism",
12323 base: Okhsv,
12324 fromBase(hsl) {
12325 return HSL.toBase([hsl[0], hsl[1] * 100, hsl[2] * 100]);
12326 },
12327 toBase(rgb) {
12328 const hsl = HSL.fromBase(rgb);
12329 hsl[1] /= 100;
12330 hsl[2] /= 100;
12331 return hsl;
12332 }
12333 });
12334
12335 let white = WHITES.D65;
12336 const ε$2 = 216 / 24389; // 6^3/29^3 == (24/116)^3
12337 const κ$1 = 24389 / 27; // 29^3/3^3
12338 const [U_PRIME_WHITE, V_PRIME_WHITE] = uv({
12339 space: XYZ_D65,
12340 coords: white
12341 });
12342 var Luv = new ColorSpace({
12343 id: "luv",
12344 name: "Luv",
12345 coords: {
12346 l: {
12347 refRange: [0, 100],
12348 name: "Lightness"
12349 },
12350 // Reference ranges from https://facelessuser.github.io/coloraide/colors/luv/
12351 u: {
12352 refRange: [-215, 215]
12353 },
12354 v: {
12355 refRange: [-215, 215]
12356 }
12357 },
12358 white: white,
12359 base: XYZ_D65,
12360 // Convert D65-adapted XYZ to Luv
12361 // https://en.wikipedia.org/wiki/CIELUV#The_forward_transformation
12362 fromBase(XYZ) {
12363 let xyz = /** @type {[number, number, number]} */[skipNone(XYZ[0]), skipNone(XYZ[1]), skipNone(XYZ[2])];
12364 let y = xyz[1];
12365 let [up, vp] = uv({
12366 space: XYZ_D65,
12367 coords: xyz
12368 });
12369
12370 // Protect against XYZ of [0, 0, 0]
12371 if (!Number.isFinite(up) || !Number.isFinite(vp)) {
12372 return [0, 0, 0];
12373 }
12374 let L = y <= ε$2 ? κ$1 * y : 116 * Math.cbrt(y) - 16;
12375 return [L, 13 * L * (up - U_PRIME_WHITE), 13 * L * (vp - V_PRIME_WHITE)];
12376 },
12377 // Convert Luv to D65-adapted XYZ
12378 // https://en.wikipedia.org/wiki/CIELUV#The_reverse_transformation
12379 toBase(Luv) {
12380 let [L, u, v] = Luv;
12381
12382 // Protect against division by zero and none Lightness
12383 if (L === 0 || isNone(L)) {
12384 return [0, 0, 0];
12385 }
12386 u = skipNone(u);
12387 v = skipNone(v);
12388 let up = u / (13 * L) + U_PRIME_WHITE;
12389 let vp = v / (13 * L) + V_PRIME_WHITE;
12390 let y = L <= 8 ? L / κ$1 : Math.pow((L + 16) / 116, 3);
12391 return [y * (9 * up / (4 * vp)), y, y * ((12 - 3 * up - 20 * vp) / (4 * vp))];
12392 },
12393 formats: {
12394 color: {
12395 id: "--luv",
12396 coords: ["<number> | <percentage>", "<number> | <percentage>", "<number> | <percentage>"]
12397 }
12398 }
12399 });
12400
12401 var LCHuv = new ColorSpace({
12402 id: "lchuv",
12403 name: "LChuv",
12404 coords: {
12405 l: {
12406 refRange: [0, 100],
12407 name: "Lightness"
12408 },
12409 c: {
12410 refRange: [0, 220],
12411 name: "Chroma"
12412 },
12413 h: {
12414 refRange: [0, 360],
12415 type: "angle",
12416 name: "Hue"
12417 }
12418 },
12419 base: Luv,
12420 fromBase: lch.fromBase,
12421 toBase: lch.toBase,
12422 formats: {
12423 color: {
12424 id: "--lchuv",
12425 coords: ["<number> | <percentage>", "<number> | <percentage>", "<number> | <angle>"]
12426 }
12427 }
12428 });
12429
12430 /*
12431 Adapted from: https://github.com/hsluv/hsluv-javascript/blob/14b49e6cf9a9137916096b8487a5372626b57ba4/src/hsluv.ts
12432
12433 Copyright (c) 2012-2022 Alexei Boronine
12434
12435 Permission is hereby granted, free of charge, to any person obtaining a copy
12436 of this software and associated documentation files (the "Software"), to deal
12437 in the Software without restriction, including without limitation the rights
12438 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12439 copies of the Software, and to permit persons to whom the Software is
12440 furnished to do so, subject to the following conditions:
12441
12442 The above copyright notice and this permission notice shall be included in all
12443 copies or substantial portions of the Software.
12444
12445 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12446 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12447 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
12448 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
12449 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
12450 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
12451 SOFTWARE.
12452 */
12453
12454 const ε$1 = 216 / 24389; // 6^3/29^3 == (24/116)^3
12455 const κ = 24389 / 27; // 29^3/3^3
12456
12457 const fromXYZ_M$1 = M$6.fromXYZ;
12458 const m_r0 = fromXYZ_M$1[0][0];
12459 const m_r1 = fromXYZ_M$1[0][1];
12460 const m_r2 = fromXYZ_M$1[0][2];
12461 const m_g0 = fromXYZ_M$1[1][0];
12462 const m_g1 = fromXYZ_M$1[1][1];
12463 const m_g2 = fromXYZ_M$1[1][2];
12464 const m_b0 = fromXYZ_M$1[2][0];
12465 const m_b1 = fromXYZ_M$1[2][1];
12466 const m_b2 = fromXYZ_M$1[2][2];
12467 function distanceFromOriginAngle(slope, intercept, angle) {
12468 const d = intercept / (Math.sin(angle) - slope * Math.cos(angle));
12469 return d < 0 ? Infinity : d;
12470 }
12471
12472 /**
12473 * @param {number} l
12474 */
12475 function calculateBoundingLines(l) {
12476 const sub1 = Math.pow(l + 16, 3) / 1560896;
12477 const sub2 = sub1 > ε$1 ? sub1 : l / κ;
12478 const s1r = sub2 * (284517 * m_r0 - 94839 * m_r2);
12479 const s2r = sub2 * (838422 * m_r2 + 769860 * m_r1 + 731718 * m_r0);
12480 const s3r = sub2 * (632260 * m_r2 - 126452 * m_r1);
12481 const s1g = sub2 * (284517 * m_g0 - 94839 * m_g2);
12482 const s2g = sub2 * (838422 * m_g2 + 769860 * m_g1 + 731718 * m_g0);
12483 const s3g = sub2 * (632260 * m_g2 - 126452 * m_g1);
12484 const s1b = sub2 * (284517 * m_b0 - 94839 * m_b2);
12485 const s2b = sub2 * (838422 * m_b2 + 769860 * m_b1 + 731718 * m_b0);
12486 const s3b = sub2 * (632260 * m_b2 - 126452 * m_b1);
12487 return {
12488 r0s: s1r / s3r,
12489 r0i: s2r * l / s3r,
12490 r1s: s1r / (s3r + 126452),
12491 r1i: (s2r - 769860) * l / (s3r + 126452),
12492 g0s: s1g / s3g,
12493 g0i: s2g * l / s3g,
12494 g1s: s1g / (s3g + 126452),
12495 g1i: (s2g - 769860) * l / (s3g + 126452),
12496 b0s: s1b / s3b,
12497 b0i: s2b * l / s3b,
12498 b1s: s1b / (s3b + 126452),
12499 b1i: (s2b - 769860) * l / (s3b + 126452)
12500 };
12501 }
12502 function calcMaxChromaHsluv(lines, h) {
12503 const hueRad = h / 360 * Math.PI * 2;
12504 const r0 = distanceFromOriginAngle(lines.r0s, lines.r0i, hueRad);
12505 const r1 = distanceFromOriginAngle(lines.r1s, lines.r1i, hueRad);
12506 const g0 = distanceFromOriginAngle(lines.g0s, lines.g0i, hueRad);
12507 const g1 = distanceFromOriginAngle(lines.g1s, lines.g1i, hueRad);
12508 const b0 = distanceFromOriginAngle(lines.b0s, lines.b0i, hueRad);
12509 const b1 = distanceFromOriginAngle(lines.b1s, lines.b1i, hueRad);
12510 return Math.min(r0, r1, g0, g1, b0, b1);
12511 }
12512 var hsluv = new ColorSpace({
12513 id: "hsluv",
12514 name: "HSLuv",
12515 coords: {
12516 h: {
12517 refRange: [0, 360],
12518 type: "angle",
12519 name: "Hue"
12520 },
12521 s: {
12522 range: [0, 100],
12523 name: "Saturation"
12524 },
12525 l: {
12526 range: [0, 100],
12527 name: "Lightness"
12528 }
12529 },
12530 base: LCHuv,
12531 gamutSpace: sRGB,
12532 rgbGamut: sRGB,
12533 // Convert LCHuv to HSLuv
12534 fromBase(lch) {
12535 let [l, c, h] = [skipNone(lch[0]), skipNone(lch[1]), skipNone(lch[2])];
12536 let s;
12537 if (l > 99.9999999) {
12538 s = 0;
12539 l = 100;
12540 } else if (l < 0.00000001) {
12541 s = 0;
12542 l = 0;
12543 } else {
12544 let lines = calculateBoundingLines(l);
12545 let max = calcMaxChromaHsluv(lines, h);
12546 s = c / max * 100;
12547 }
12548 return [h, s, l];
12549 },
12550 // Convert HSLuv to LCHuv
12551 toBase(hsl) {
12552 let [h, s, l] = [skipNone(hsl[0]), skipNone(hsl[1]), skipNone(hsl[2])];
12553 let c;
12554 if (l > 99.9999999) {
12555 l = 100;
12556 c = 0;
12557 } else if (l < 0.00000001) {
12558 l = 0;
12559 c = 0;
12560 } else {
12561 let lines = calculateBoundingLines(l);
12562 let max = calcMaxChromaHsluv(lines, h);
12563 c = max / 100 * s;
12564 }
12565 return [l, c, h];
12566 },
12567 formats: {
12568 color: {
12569 id: "--hsluv",
12570 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
12571 }
12572 }
12573 });
12574
12575 /*
12576 Adapted from: https://github.com/hsluv/hsluv-javascript/blob/14b49e6cf9a9137916096b8487a5372626b57ba4/src/hsluv.ts
12577
12578 Copyright (c) 2012-2022 Alexei Boronine
12579
12580 Permission is hereby granted, free of charge, to any person obtaining a copy
12581 of this software and associated documentation files (the "Software"), to deal
12582 in the Software without restriction, including without limitation the rights
12583 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12584 copies of the Software, and to permit persons to whom the Software is
12585 furnished to do so, subject to the following conditions:
12586
12587 The above copyright notice and this permission notice shall be included in all
12588 copies or substantial portions of the Software.
12589
12590 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12591 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12592 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
12593 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
12594 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
12595 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
12596 SOFTWARE.
12597 */
12598
12599
12600 const fromXYZ_M = M$6.fromXYZ;
12601 fromXYZ_M[0][0];
12602 fromXYZ_M[0][1];
12603 fromXYZ_M[0][2];
12604 fromXYZ_M[1][0];
12605 fromXYZ_M[1][1];
12606 fromXYZ_M[1][2];
12607 fromXYZ_M[2][0];
12608 fromXYZ_M[2][1];
12609 fromXYZ_M[2][2];
12610 function distanceFromOrigin(slope, intercept) {
12611 return Math.abs(intercept) / Math.sqrt(Math.pow(slope, 2) + 1);
12612 }
12613 function calcMaxChromaHpluv(lines) {
12614 let r0 = distanceFromOrigin(lines.r0s, lines.r0i);
12615 let r1 = distanceFromOrigin(lines.r1s, lines.r1i);
12616 let g0 = distanceFromOrigin(lines.g0s, lines.g0i);
12617 let g1 = distanceFromOrigin(lines.g1s, lines.g1i);
12618 let b0 = distanceFromOrigin(lines.b0s, lines.b0i);
12619 let b1 = distanceFromOrigin(lines.b1s, lines.b1i);
12620 return Math.min(r0, r1, g0, g1, b0, b1);
12621 }
12622 const HPLuv = new ColorSpace({
12623 id: "hpluv",
12624 name: "HPLuv",
12625 coords: {
12626 h: {
12627 refRange: [0, 360],
12628 type: "angle",
12629 name: "Hue"
12630 },
12631 s: {
12632 range: [0, 100],
12633 name: "Saturation"
12634 },
12635 l: {
12636 range: [0, 100],
12637 name: "Lightness"
12638 }
12639 },
12640 base: LCHuv,
12641 gamutSpace: "self",
12642 // Convert LCHuv to HPLuv
12643 fromBase(lch) {
12644 let [l, c, h] = [skipNone(lch[0]), skipNone(lch[1]), skipNone(lch[2])];
12645 let s;
12646 if (l > 99.9999999) {
12647 s = 0;
12648 l = 100;
12649 } else if (l < 0.00000001) {
12650 s = 0;
12651 l = 0;
12652 } else {
12653 let lines = calculateBoundingLines(l);
12654 let max = calcMaxChromaHpluv(lines);
12655 s = c / max * 100;
12656 }
12657 return [h, s, l];
12658 },
12659 // Convert HPLuv to LCHuv
12660 toBase(hsl) {
12661 let [h, s, l] = [skipNone(hsl[0]), skipNone(hsl[1]), skipNone(hsl[2])];
12662 let c;
12663 if (l > 99.9999999) {
12664 l = 100;
12665 c = 0;
12666 } else if (l < 0.00000001) {
12667 l = 0;
12668 c = 0;
12669 } else {
12670 let lines = calculateBoundingLines(l);
12671 let max = calcMaxChromaHpluv(lines);
12672 c = max / 100 * s;
12673 }
12674 return [l, c, h];
12675 },
12676 formats: {
12677 color: {
12678 id: "--hpluv",
12679 coords: ["<number> | <angle>", "<percentage> | <number>", "<percentage> | <number>"]
12680 }
12681 }
12682 });
12683 HPLuv.rgbGamut = new RGBColorSpace({
12684 id: "hpluv-prism",
12685 cssId: "--hpluv-prism",
12686 name: "HPLuv Prism",
12687 base: HPLuv,
12688 fromBase(hsl) {
12689 return HSL.toBase(hsl);
12690 },
12691 toBase(rgb) {
12692 return HSL.fromBase(rgb);
12693 }
12694 });
12695
12696 /**
12697 * Helmlab GenSpace — generation-optimized color space for interpolation.
12698 *
12699 * Pipeline (v0.11.1, depressed cubic + chroma power + L-gated enrichment):
12700 * XYZ → M1 → depcubic(α=0.021) → M2 → chroma_power(0.978) →
12701 * PW_L → L-gated hue enrichment → Lab
12702 *
12703 * Optimized for perceptually uniform gradients, palette generation,
12704 * and color-mix. 59-8 vs OKLab in head-to-head benchmarks (83 metrics,
12705 * 3038 gradient pairs, sRGB/P3/Rec.2020). 360/360/360 cusps.
12706 *
12707 * Key properties:
12708 * - Depressed cubic: y³ + αy = x, finite derivative at zero
12709 * - Chroma power (0.978): improves gradient CV uniformity
12710 * - L-gated hue enrichment: fixes blue→white purple shift
12711 * - Structurally achromatic: a=b≈0 for all grays
12712 *
12713 * Note on blue-region gamut fold:
12714 * All M1→f→M2 spaces (OKLab, IPT, HelmGen) exhibit a tiny non-contiguous
12715 * gamut region near h≈260° in sRGB. This is a mathematical consequence of
12716 * mixing LMS channels before applying a power-like transfer: the inverse
12717 * creates a cubic polynomial that can have two positive roots in the blue
12718 * region. OKLab has 46 such holes; HelmGen has 5, each ~0.001 chroma wide
12719 * (sub-pixel, invisible). See: color.js#81, csswg-drafts#7071.
12720 *
12721 * Reference: arXiv:2602.23010
12722 * @see https://github.com/Grkmyldz148/helmlab
12723 */
12724
12725 /** @import { Matrix3x3 } from "../types.js" */
12726
12727 // ── Depressed cubic parameter ──────────────────────────────────────
12728 const ALPHA = 0.021;
12729 const S = Math.sqrt(ALPHA / 3);
12730 const S3 = S * S * S;
12731
12732 // ── Chroma power ───────────────────────────────────────────────────
12733 const CP = 0.978;
12734
12735 // ── L-gated hue enrichment parameters ──────────────────────────────
12736 const ENR_AMP = 0.058;
12737 const ENR_CENTER = 264.5 * Math.PI / 180; // radians
12738 const ENR_SIGMA = 0.7;
12739 const ENR_LLO = 0.37;
12740 const ENR_LHI = 1.0;
12741
12742 // ── Core matrices (v0.11.1) ────────────────────────────────────────
12743
12744 /**
12745 * Matrices used by this color space, also available as `HelmGen.M`
12746 * @type {Record<string, Matrix3x3>}
12747 */
12748 // prettier-ignore
12749 const M$1 = {
12750 // M1 = M1_orig @ CAT_TO_HELM (Bradford CAT baked in: Color.js D65 → Helmlab D65 → LMS)
12751 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]],
12752 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]],
12753 M2: [[0.21193779684470104, 0.7992121834263127, -0.00410075161564345], [2.4672018828033475, -2.9877348024830788, 0.520532919679731], [-0.11390787868068575, 1.3932982808117473, -1.279390402131062]],
12754 M2_INV: [[0.9930001151336143, 0.32599327253052285, 0.12945085631713921], [0.9930001151336139, -0.08708353111074627, -0.03861361743004929], [0.9930001151336136, -0.12386097008215022, -0.8351991365871061]]
12755 };
12756
12757 // ── Piecewise-linear L correction (21 breakpoints, v0.11.1) ───────
12758 // prettier-ignore
12759 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];
12760 // prettier-ignore
12761 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];
12762 const PW_N = PW_L_IN.length;
12763
12764 // ── Depressed cubic: y³ + αy = x ──────────────────────────────────
12765
12766 function depcubicFwd(x) {
12767 let t = x / (2 * S3);
12768 let y = 2 * S * Math.sinh(Math.asinh(t) / 3);
12769 // Halley refinement
12770 let f = y * y * y + ALPHA * y - x;
12771 let fp = 3 * y * y + ALPHA;
12772 let fpp = 6 * y;
12773 let denom = 2 * fp * fp - f * fpp;
12774 if (Math.abs(denom) > 1e-30) {
12775 y -= 2 * f * fp / denom;
12776 }
12777 return y;
12778 }
12779 function depcubicInv(y) {
12780 return y * y * y + ALPHA * y;
12781 }
12782
12783 // ── L-gated hue enrichment ─────────────────────────────────────────
12784
12785 function enrichGate(L) {
12786 let t = Math.max(0, Math.min(1, (L - ENR_LLO) / (ENR_LHI - ENR_LLO)));
12787 return Math.sin(Math.PI * t) ** 2;
12788 }
12789 function enrichFwd(L, a, b) {
12790 let C = Math.sqrt(a * a + b * b);
12791 if (C < 1e-12) {
12792 return [a, b];
12793 }
12794 let gate = enrichGate(L);
12795 if (gate < 1e-12) {
12796 return [a, b];
12797 }
12798 let h = Math.atan2(b, a);
12799 let dh = h - ENR_CENTER;
12800 dh = dh - Math.round(dh / (2 * Math.PI)) * 2 * Math.PI;
12801 let gauss = Math.exp(-0.5 * (dh / ENR_SIGMA) ** 2);
12802 let hNew = h + ENR_AMP * gate * gauss;
12803 return [C * Math.cos(hNew), C * Math.sin(hNew)];
12804 }
12805 function enrichInv(L, a, b) {
12806 let C = Math.sqrt(a * a + b * b);
12807 if (C < 1e-12) {
12808 return [a, b];
12809 }
12810 let gate = enrichGate(L);
12811 if (gate < 1e-12) {
12812 return [a, b];
12813 }
12814 let hTarget = Math.atan2(b, a);
12815 let sig2 = ENR_SIGMA * ENR_SIGMA;
12816 let ag = ENR_AMP * gate;
12817 let h = hTarget;
12818 for (let i = 0; i < 8; i++) {
12819 let dh = h - ENR_CENTER;
12820 dh = dh - Math.round(dh / (2 * Math.PI)) * 2 * Math.PI;
12821 let gauss = Math.exp(-0.5 * dh * dh / sig2);
12822 let F = h + ag * gauss - hTarget;
12823 let Fp = 1 + ag * gauss * (-dh / sig2);
12824 let Fpp = ag * gauss * (-1 / sig2 + dh * dh / (sig2 * sig2));
12825 let den = 2 * Fp * Fp - F * Fpp;
12826 if (Math.abs(den) > 1e-30) {
12827 h -= 2 * F * Fp / den;
12828 }
12829 }
12830 return [C * Math.cos(h), C * Math.sin(h)];
12831 }
12832
12833 // ── PW L correction ───────────────────────────────────────────────
12834
12835 function pwLForward(L) {
12836 if (L <= 0 || L >= 1) {
12837 return L;
12838 }
12839 let lo = 0,
12840 hi = PW_N - 1;
12841 while (hi - lo > 1) {
12842 let mid = lo + hi >> 1;
12843 if (PW_L_IN[mid] <= L) {
12844 lo = mid;
12845 } else {
12846 hi = mid;
12847 }
12848 }
12849 let t = (L - PW_L_IN[lo]) / (PW_L_IN[hi] - PW_L_IN[lo]);
12850 return PW_L_OUT[lo] + t * (PW_L_OUT[hi] - PW_L_OUT[lo]);
12851 }
12852 function pwLInverse(L) {
12853 if (L <= PW_L_OUT[0] || L >= PW_L_OUT[PW_N - 1]) {
12854 return L;
12855 }
12856 let lo = 0,
12857 hi = PW_N - 1;
12858 while (hi - lo > 1) {
12859 let mid = lo + hi >> 1;
12860 if (PW_L_OUT[mid] <= L) {
12861 lo = mid;
12862 } else {
12863 hi = mid;
12864 }
12865 }
12866 let t = (L - PW_L_OUT[lo]) / (PW_L_OUT[hi] - PW_L_OUT[lo]);
12867 return PW_L_IN[lo] + t * (PW_L_IN[hi] - PW_L_IN[lo]);
12868 }
12869
12870 // ── Color space definition ─────────────────────────────────────────
12871
12872 var HelmGen = new ColorSpace({
12873 id: "helmgen",
12874 name: "HelmGen",
12875 cssId: "--helmgen",
12876 coords: {
12877 l: {
12878 refRange: [0, 1],
12879 name: "Lightness"
12880 },
12881 a: {
12882 refRange: [-0.6, 0.6]
12883 },
12884 b: {
12885 refRange: [-0.6, 0.6]
12886 }
12887 },
12888 white: "D65",
12889 base: XYZ_D65,
12890 M: M$1,
12891 fromBase(xyz) {
12892 // Stage 1: XYZ → LMS (M1)
12893 let lms = multiply_v3_m3x3(xyz, M$1.M1);
12894
12895 // Stage 2: Depressed cubic transfer (y³ + αy = x)
12896 let c0 = depcubicFwd(Math.max(lms[0], 0));
12897 let c1 = depcubicFwd(Math.max(lms[1], 0));
12898 let c2 = depcubicFwd(Math.max(lms[2], 0));
12899
12900 // Stage 2.5: Smooth neutral blend (C∞ correction for achromatic precision)
12901 {
12902 let mean = (c0 + c1 + c2) / 3;
12903 let mx = Math.max(c0, c1, c2);
12904 let mn = Math.min(c0, c1, c2);
12905 let spread = (mx - mn) / Math.max(Math.abs(mean), 1e-30);
12906 let w = Math.exp(-((spread / 1e-5) ** 2));
12907 c0 += w * (mean - c0);
12908 c1 += w * (mean - c1);
12909 c2 += w * (mean - c2);
12910 }
12911
12912 // Stage 3: LMS_c → Lab (M2)
12913 let [L, a, b] = multiply_v3_m3x3([c0, c1, c2], M$1.M2);
12914
12915 // Stage 3.5: Chroma power (cp=0.978)
12916 {
12917 let C = Math.sqrt(a * a + b * b);
12918 if (C > 1e-12) {
12919 let Cnew = Math.pow(C, CP);
12920 let s = Cnew / C;
12921 a *= s;
12922 b *= s;
12923 }
12924 }
12925
12926 // Stage 4: Piecewise-linear L correction
12927 L = pwLForward(L);
12928
12929 // Stage 5: L-gated hue enrichment
12930 [a, b] = enrichFwd(L, a, b);
12931 return [L, a, b];
12932 },
12933 toBase(lab) {
12934 let [L, a, b] = lab;
12935
12936 // Undo Stage 5: L-gated hue enrichment
12937 [a, b] = enrichInv(L, a, b);
12938
12939 // Undo Stage 4: PW L correction
12940 L = pwLInverse(L);
12941
12942 // Undo Stage 3.5: Chroma power inverse (C^(1/cp))
12943 {
12944 let C = Math.sqrt(a * a + b * b);
12945 if (C > 1e-12) {
12946 let Corig = Math.pow(C, 1 / CP);
12947 let s = Corig / C;
12948 a *= s;
12949 b *= s;
12950 }
12951 }
12952
12953 // Undo Stage 3: Lab → LMS_c (M2_inv)
12954 let [lc0, lc1, lc2] = multiply_v3_m3x3([L, a, b], M$1.M2_INV);
12955
12956 // Undo Stage 2.5: Smooth neutral blend
12957 {
12958 let mean = (lc0 + lc1 + lc2) / 3;
12959 let mx = Math.max(lc0, lc1, lc2);
12960 let mn = Math.min(lc0, lc1, lc2);
12961 let spread = (mx - mn) / Math.max(Math.abs(mean), 1e-30);
12962 let w = Math.exp(-((spread / 1e-5) ** 2));
12963 lc0 += w * (mean - lc0);
12964 lc1 += w * (mean - lc1);
12965 lc2 += w * (mean - lc2);
12966 }
12967
12968 // Undo Stage 2: Inverse depressed cubic (x = y³ + αy)
12969 let l0 = depcubicInv(lc0);
12970 let l1 = depcubicInv(lc1);
12971 let l2 = depcubicInv(lc2);
12972
12973 // Undo Stage 1: LMS → XYZ (M1_inv)
12974 return multiply_v3_m3x3([l0, l1, l2], M$1.M1_INV);
12975 }
12976 });
12977
12978 /**
12979 * HelmGenLCh — cylindrical form of Helmlab GenSpace.
12980 *
12981 * Converts GenSpace's rectangular (L, a, b) coordinates to
12982 * cylindrical (L, C, h). Ideal for CSS interpolation contexts
12983 * like gradients and color-mix where hue angle matters.
12984 *
12985 * @see https://github.com/Grkmyldz148/helmlab
12986 */
12987 var helmgenlch = new ColorSpace({
12988 id: "helmgenlch",
12989 name: "HelmGenLCh",
12990 cssId: "--helmgenlch",
12991 coords: {
12992 l: {
12993 refRange: [0, 1],
12994 name: "Lightness"
12995 },
12996 c: {
12997 refRange: [0, 0.65],
12998 name: "Chroma"
12999 },
13000 h: {
13001 refRange: [0, 360],
13002 type: "angle",
13003 name: "Hue"
13004 }
13005 },
13006 white: "D65",
13007 base: HelmGen,
13008 fromBase: lch.fromBase,
13009 toBase: lch.toBase
13010 });
13011
13012 var REC_2100_Linear = new RGBColorSpace({
13013 id: "rec2100-linear",
13014 name: "Linear REC.2100",
13015 white: "D65",
13016 M: M$8
13017 });
13018
13019 const Yw = 203; // absolute luminance of media white, cd/m²
13020 const n = 2610 / 2 ** 14;
13021 const ninv = 2 ** 14 / 2610;
13022 const m = 2523 / 2 ** 5;
13023 const minv = 2 ** 5 / 2523;
13024 const c1 = 3424 / 2 ** 12;
13025 const c2 = 2413 / 2 ** 7;
13026 const c3 = 2392 / 2 ** 7;
13027 var rec2100Pq = new RGBColorSpace({
13028 id: "rec2100pq",
13029 cssId: "rec2100-pq",
13030 name: "REC.2100-PQ",
13031 base: REC_2100_Linear,
13032 linearGamut: REC_2100_Linear,
13033 toBase(RGB) {
13034 // given PQ encoded component in range [0, 1]
13035 // return media-white relative linear-light
13036 return RGB.map(function (val) {
13037 let x = (Math.max(val ** minv - c1, 0) / (c2 - c3 * val ** minv)) ** ninv;
13038 return x * 10000 / Yw; // luminance relative to diffuse white, [0, 70 or so].
13039 });
13040 },
13041 fromBase(RGB) {
13042 // given media-white relative linear-light
13043 // returnPQ encoded component in range [0, 1]
13044 return RGB.map(function (val) {
13045 let x = Math.max(val * Yw / 10000, 0); // absolute luminance of peak white is 10,000 cd/m².
13046 let num = c1 + c2 * x ** n;
13047 let denom = 1 + c3 * x ** n;
13048 return (num / denom) ** m;
13049 });
13050 }
13051 });
13052
13053 const a = 0.17883277;
13054 const b = 0.28466892; // 1 - (4 * a)
13055 const c = 0.55991073; // 0.5 - a * Math.log(4 *a)
13056
13057 const scale = 3.7743; // Place 18% grey at HLG 0.38, so media white at 0.75
13058
13059 var rec2100Hlg = new RGBColorSpace({
13060 id: "rec2100hlg",
13061 cssId: "rec2100-hlg",
13062 name: "REC.2100-HLG",
13063 referred: "scene",
13064 base: REC_2100_Linear,
13065 linearGamut: REC_2100_Linear,
13066 toBase(RGB) {
13067 // given HLG encoded component in range [0, 1]
13068 // return media-white relative linear-light
13069 return RGB.map(function (val) {
13070 // first the HLG EOTF
13071 // ITU-R BT.2390-10 p.30 section
13072 // 6.3 The hybrid log-gamma electro-optical transfer function (EOTF)
13073 // Then scale by 3 so media white is 1.0
13074 if (val <= 0.5) {
13075 return val ** 2 / 3 * scale;
13076 }
13077 return (Math.exp((val - c) / a) + b) / 12 * scale;
13078 });
13079 },
13080 fromBase(RGB) {
13081 // given media-white relative linear-light
13082 // where diffuse white is 1.0,
13083 // return HLG encoded component in range [0, 1]
13084 return RGB.map(function (val) {
13085 // first scale to put linear-light media white at 1/3
13086 val /= scale;
13087 // now the HLG OETF
13088 // ITU-R BT.2390-10 p.23
13089 // 6.1 The hybrid log-gamma opto-electronic transfer function (OETF)
13090 if (val <= 1 / 12) {
13091 return spow(3 * val, 0.5);
13092 }
13093 return a * Math.log(12 * val - b) + c;
13094 });
13095 }
13096 });
13097
13098 /** @import { White } from "./types.js" */
13099
13100 // Type re-exports
13101 /** @typedef {import("./types.js").CAT} CAT */
13102
13103 /** @type {Record<string, CAT>} */
13104 const CATs = {};
13105 hooks.add("chromatic-adaptation-start", env => {
13106 if (env.options.method) {
13107 env.M = adapt(env.W1, env.W2, env.options.method);
13108 }
13109 });
13110 hooks.add("chromatic-adaptation-end", env => {
13111 if (!env.M) {
13112 env.M = adapt(env.W1, env.W2, env.options.method);
13113 }
13114 });
13115 function defineCAT(/** @type {CAT} */{
13116 id,
13117 toCone_M,
13118 fromCone_M
13119 }) {
13120 // Use id, toCone_M, fromCone_M like variables
13121 CATs[id] = arguments[0];
13122 }
13123
13124 /**
13125 *
13126 * @param {White} W1
13127 * @param {White} W2
13128 * @param {string} id
13129 * @returns {number[][]}
13130 */
13131 function adapt(W1, W2, id = "Bradford") {
13132 // adapt from a source whitepoint or illuminant W1
13133 // to a destination whitepoint or illuminant W2,
13134 // using the given chromatic adaptation transform (CAT)
13135 // debugger;
13136 let method = CATs[id];
13137 let [ρs, γs, βs] = multiplyMatrices(method.toCone_M, W1);
13138 let [ρd, γd, βd] = multiplyMatrices(method.toCone_M, W2);
13139
13140 // all practical illuminants have non-zero XYZ so no division by zero can occur below
13141 // prettier-ignore
13142 let scale = [[ρd / ρs, 0, 0], [0, γd / γs, 0], [0, 0, βd / βs]];
13143 // console.log({scale});
13144
13145 let scaled_cone_M = multiplyMatrices(scale, method.toCone_M);
13146 let adapt_M = multiplyMatrices(method.fromCone_M, scaled_cone_M);
13147 // console.log({scaled_cone_M, adapt_M});
13148 return adapt_M;
13149 }
13150
13151 // prettier-ignore
13152 defineCAT({
13153 id: "von Kries",
13154 toCone_M: [[0.4002400, 0.7076000, -0.0808100], [-0.2263000, 1.1653200, 0.0457000], [0.0000000, 0.0000000, 0.9182200]],
13155 fromCone_M: [[1.8599363874558397, -1.1293816185800916, 0.21989740959619328], [0.3611914362417676, 0.6388124632850422, -0.000006370596838649899], [0, 0, 1.0890636230968613]]
13156 });
13157
13158 // prettier-ignore
13159 defineCAT({
13160 id: "Bradford",
13161 // Convert an array of XYZ values in the range 0.0 - 1.0
13162 // to cone fundamentals
13163 toCone_M: [[0.8951000, 0.2664000, -0.1614000], [-0.7502000, 1.7135000, 0.0367000], [0.0389000, -0.0685000, 1.0296000]],
13164 // and back
13165 fromCone_M: [[0.9869929054667121, -0.14705425642099013, 0.15996265166373122], [0.4323052697233945, 0.5183602715367774, 0.049291228212855594], [-0.00852866457517732, 0.04004282165408486, 0.96848669578755]]
13166 });
13167
13168 // prettier-ignore
13169 defineCAT({
13170 id: "CAT02",
13171 // with complete chromatic adaptation to W2, so D = 1.0
13172 toCone_M: [[0.7328000, 0.4296000, -0.1624000], [-0.7036000, 1.6975000, 0.0061000], [0.0030000, 0.0136000, 0.9834000]],
13173 fromCone_M: [[1.0961238208355142, -0.27886900021828726, 0.18274517938277307], [0.4543690419753592, 0.4735331543074117, 0.07209780371722911], [-0.009627608738429355, -0.00569803121611342, 1.0153256399545427]]
13174 });
13175
13176 // prettier-ignore
13177 defineCAT({
13178 id: "CAT16",
13179 toCone_M: [[0.401288, 0.650173, -0.051461], [-0.250268, 1.204414, 0.045854], [-0.002079, 0.048952, 0.953127]],
13180 // the extra precision is needed to avoid roundtripping errors
13181 fromCone_M: [[1.862067855087233, -1.0112546305316845, 0.14918677544445172], [0.3875265432361372, 0.6214474419314753, -0.008973985167612521], [-0.01584149884933386, -0.03412293802851557, 1.0499644368778496]]
13182 });
13183
13184 // prettier-ignore
13185 Object.assign(WHITES, {
13186 // whitepoint values from ASTM E308-01 with 10nm spacing, 1931 2 degree observer
13187 // all normalized to Y (luminance) = 1.00000
13188 // Illuminant A is a tungsten electric light, giving a very warm, orange light.
13189 A: [1.09850, 1.00000, 0.35585],
13190 // Illuminant C was an early approximation to daylight: illuminant A with a blue filter.
13191 C: [0.98074, 1.000000, 1.18232],
13192 // The daylight series of illuminants simulate natural daylight.
13193 // The color temperature (in degrees Kelvin/100) ranges from
13194 // cool, overcast daylight (D50) to bright, direct sunlight (D65).
13195 D55: [0.95682, 1.00000, 0.92149],
13196 D75: [0.94972, 1.00000, 1.22638],
13197 // Equal-energy illuminant, used in two-stage CAT16
13198 E: [1.00000, 1.00000, 1.00000],
13199 // The F series of illuminants represent fluorescent lights
13200 F2: [0.99186, 1.00000, 0.67393],
13201 F7: [0.95041, 1.00000, 1.08747],
13202 F11: [1.00962, 1.00000, 0.64350]
13203 });
13204
13205 /** @import { Matrix3x3 } from "../types.js" */
13206
13207 // The ACES whitepoint
13208 // see TB-2018-001 Derivation of the ACES White Point CIE Chromaticity Coordinates
13209 // also https://github.com/ampas/aces-dev/blob/master/documents/python/TB-2018-001/aces_wp.py
13210 // Similar to D60
13211 WHITES.ACES = [0.32168 / 0.33767, 1.0, (1.0 - 0.32168 - 0.33767) / 0.33767];
13212
13213 /**
13214 * Matrices used by this color space, also available as `ACEScg.M`
13215 * @type {Record<string, Matrix3x3>}
13216 */
13217 // prettier-ignore
13218 const M = {
13219 // convert an array of linear-light ACEScg values to CIE XYZ
13220 toXYZ: [[0.6624541811085053, 0.13400420645643313, 0.1561876870049078], [0.27222871678091454, 0.6740817658111484, 0.05368951740793705], [-0.005574649490394108, 0.004060733528982826, 1.0103391003129971]],
13221 fromXYZ: [[1.6410233796943257, -0.32480329418479, -0.23642469523761225], [-0.6636628587229829, 1.6153315916573379, 0.016756347685530137], [0.011721894328375376, -0.008284441996237409, 0.9883948585390215]]
13222 };
13223 var ACEScg = new RGBColorSpace({
13224 id: "acescg",
13225 cssId: "--acescg",
13226 name: "ACEScg",
13227 // ACEScg – A scene-referred, linear-light encoding of ACES Data
13228 // https://docs.acescentral.com/specifications/acescg/
13229 // uses the AP1 primaries, see section 4.3.1 Color primaries
13230 coords: {
13231 r: {
13232 range: [0, 65504],
13233 name: "Red"
13234 },
13235 g: {
13236 range: [0, 65504],
13237 name: "Green"
13238 },
13239 b: {
13240 range: [0, 65504],
13241 name: "Blue"
13242 }
13243 },
13244 referred: "scene",
13245 white: WHITES.ACES,
13246 M
13247 });
13248
13249 // export default Color;
13250
13251 const ε = 2 ** -16;
13252
13253 // the smallest value which, in the 32bit IEEE 754 float encoding,
13254 // decodes as a non-negative value
13255 const ACES_min_nonzero = -0.35828683;
13256
13257 // brightest encoded value, decodes to 65504
13258 const ACES_cc_max = (Math.log2(65504) + 9.72) / 17.52; // 1.468
13259
13260 var acescc = new RGBColorSpace({
13261 id: "acescc",
13262 cssId: "--acescc",
13263 name: "ACEScc",
13264 // see S-2014-003 ACEScc – A Logarithmic Encoding of ACES Data
13265 // https://docs.acescentral.com/specifications/acescc/
13266 // uses the AP1 primaries, see section 4.3.1 Color primaries
13267
13268 // Appendix A: "Very small ACES scene referred values below 7 1/4 stops
13269 // below 18% middle gray are encoded as negative ACEScc values.
13270 // These values should be preserved per the encoding in Section 4.4
13271 // so that all positive ACES values are maintained."
13272 coords: {
13273 r: {
13274 range: [ACES_min_nonzero, ACES_cc_max],
13275 name: "Red"
13276 },
13277 g: {
13278 range: [ACES_min_nonzero, ACES_cc_max],
13279 name: "Green"
13280 },
13281 b: {
13282 range: [ACES_min_nonzero, ACES_cc_max],
13283 name: "Blue"
13284 }
13285 },
13286 referred: "scene",
13287 base: ACEScg,
13288 linearGamut: ACEScg,
13289 // from section 4.4.2 Decoding Function
13290 toBase(RGB) {
13291 const low = (9.72 - 15) / 17.52; // -0.3014
13292
13293 return RGB.map(function (val) {
13294 if (val <= low) {
13295 return (2 ** (val * 17.52 - 9.72) - ε) * 2; // very low values, below -0.3014
13296 } else if (val < ACES_cc_max) {
13297 return 2 ** (val * 17.52 - 9.72);
13298 } else {
13299 // val >= ACES_cc_max
13300 return 65504;
13301 }
13302 });
13303 },
13304 // Non-linear encoding function from S-2014-003, section 4.4.1 Encoding Function
13305 fromBase(RGB) {
13306 return RGB.map(function (val) {
13307 if (val <= 0) {
13308 return (Math.log2(ε) + 9.72) / 17.52; // -0.3584
13309 } else if (val < ε) {
13310 return (Math.log2(ε + val * 0.5) + 9.72) / 17.52;
13311 } else {
13312 // val >= ε
13313 return (Math.log2(val) + 9.72) / 17.52;
13314 }
13315 });
13316 }
13317 // encoded media white (rgb 1,1,1) => linear [ 222.861, 222.861, 222.861 ]
13318 // encoded media black (rgb 0,0,0) => linear [ 0.0011857, 0.0011857, 0.0011857]
13319 });
13320
13321 /**
13322 * @packageDocumentation
13323 * Re-exports all the spaces built into Color.js.
13324 */
13325
13326 var spaces = /*#__PURE__*/Object.freeze({
13327 __proto__: null,
13328 A98RGB: a98rgb,
13329 A98RGB_Linear: A98Linear,
13330 ACEScc: acescc,
13331 ACEScg: ACEScg,
13332 CAM16_JMh: cam16,
13333 HCT: hct,
13334 HPLuv: HPLuv,
13335 HSL: HSL,
13336 HSL_P3: hslP3,
13337 HSL_REC2020: hslRec2020,
13338 HSLuv: hsluv,
13339 HSV: HSV,
13340 HWB: hwb,
13341 HelmGen: HelmGen,
13342 HelmGenLCh: helmgenlch,
13343 Helmlab: helmlab,
13344 ICTCP: ictcp,
13345 JzCzHz: jzczhz,
13346 Jzazbz: Jzazbz,
13347 LCH: lch,
13348 LCH_P3: lchP3,
13349 LCH_REC_2020: lchRec2020,
13350 LCH_sRGB: lchSrgb,
13351 LCHuv: LCHuv,
13352 Lab: lab,
13353 Lab_D65: lab_d65,
13354 Luv: Luv,
13355 OKLCH: OKLCH,
13356 OKLCH_P3: oklchP3,
13357 OKLCH_REC_2020: oklchRec2020,
13358 OKLCH_sRGB: oklchSrgb,
13359 OKLab: Oklab,
13360 OKLrCH: oklrch,
13361 OKLrab: OKLrab,
13362 Okhsl: Okhsl,
13363 Okhsv: Okhsv,
13364 P3: P3,
13365 P3_Linear: P3Linear,
13366 ProPhoto: prophoto,
13367 ProPhoto_Linear: ProPhotoLinear,
13368 REC_2020: REC2020,
13369 REC_2020_Linear: REC2020Linear,
13370 REC_2020_Scene_Referred: rec2020Oetf,
13371 REC_2100_HLG: rec2100Hlg,
13372 REC_2100_Linear: REC_2100_Linear,
13373 REC_2100_PQ: rec2100Pq,
13374 XYZ_ABS_D65: XYZ_Abs_D65,
13375 XYZ_D50: XYZ_D50,
13376 XYZ_D65: XYZ_D65,
13377 sRGB: sRGB,
13378 sRGB_Linear: sRGBLinear
13379 });
13380
13381 class Color {
13382 /**
13383 * Creates an instance of Color.
13384 * Signatures:
13385 * - `new Color(stringToParse)`
13386 * - `new Color(otherColor)`
13387 * - `new Color({space, coords, alpha})`
13388 * - `new Color(space, coords, alpha)`
13389 * - `new Color(spaceId, coords, alpha)`
13390 */
13391 constructor(...args) {
13392 let color;
13393 if (args.length === 1) {
13394 let parseMeta = {};
13395 // Clone simple objects to avoid mutating original in getColor
13396 if (typeof args[0] === "object" && Object.getPrototypeOf(args[0]).constructor === Object) {
13397 args[0] = {
13398 ...args[0]
13399 };
13400 }
13401 color = getColor(args[0], {
13402 parseMeta
13403 });
13404 if (parseMeta.format) {
13405 // Color actually came from a string
13406 this.parseMeta = parseMeta;
13407 }
13408 }
13409 let space, coords, alpha;
13410 if (color) {
13411 space = color.space || color.spaceId;
13412 coords = color.coords;
13413 alpha = color.alpha;
13414 } else {
13415 // default signature new Color(ColorSpace, array [, alpha])
13416 [space, coords, alpha] = args;
13417 }
13418 Object.defineProperty(this, "space", {
13419 value: ColorSpace.get(space),
13420 writable: false,
13421 enumerable: true,
13422 configurable: true // see note in https://262.ecma-international.org/8.0/#sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver
13423 });
13424 this.coords = coords ? coords.slice() : [0, 0, 0];
13425
13426 // Clamp alpha to [0, 1]
13427 this.alpha = isNone(alpha) ? alpha : alpha === undefined ? 1 : clamp(0, alpha, 1);
13428
13429 // Define getters and setters for each coordinate
13430 for (let id in this.space.coords) {
13431 Object.defineProperty(this, id, {
13432 get: () => this.get(id),
13433 set: value => this.set(id, value)
13434 });
13435 }
13436 }
13437 get spaceId() {
13438 return this.space.id;
13439 }
13440 clone() {
13441 return new Color(this.space, this.coords, this.alpha);
13442 }
13443 toJSON() {
13444 return {
13445 spaceId: this.spaceId,
13446 coords: this.coords,
13447 alpha: this.alpha
13448 };
13449 }
13450 display(...args) {
13451 let ret = display(this, ...args);
13452
13453 // Convert color object to Color instance
13454 ret.color = new Color(ret.color);
13455 return ret;
13456 }
13457
13458 /**
13459 * Get a color from the argument(s) passed
13460 * Basically gets us the same result as new Color(color) but doesn't clone an existing color object
13461 */
13462 static get(color, ...args) {
13463 if (isInstance(color, this)) {
13464 return color;
13465 }
13466 return new Color(color, ...args);
13467 }
13468
13469 /**
13470 * Get a color instance from the argument passed or `null` if resolution fails (instead of throwing an error).
13471 * Additionally, it supports passing an element to resolve complex CSS colors through the DOM (slow).
13472 * @see {@link tryColor} for more details
13473 */
13474 static try(color, options) {
13475 if (isInstance(color, this)) {
13476 return color;
13477 }
13478 let ret = tryColor(color, options);
13479 if (ret) {
13480 return new Color(ret);
13481 }
13482 return null;
13483 }
13484 static defineFunction(name, code, o = code) {
13485 let {
13486 instance = true,
13487 returns
13488 } = o;
13489 let func = function (...args) {
13490 let ret = code(...args);
13491 if (returns === "color") {
13492 ret = Color.get(ret);
13493 } else if (returns === "function<color>") {
13494 let f = ret;
13495 ret = function (...args) {
13496 let ret = f(...args);
13497 return Color.get(ret);
13498 };
13499 // Copy any function metadata
13500 Object.assign(ret, f);
13501 } else if (returns === "array<color>") {
13502 ret = ret.map(c => Color.get(c));
13503 }
13504 return ret;
13505 };
13506 if (!(name in Color)) {
13507 Color[name] = func;
13508 }
13509 if (instance) {
13510 Color.prototype[name] = function (...args) {
13511 return func(this, ...args);
13512 };
13513 }
13514 }
13515 static defineFunctions(o) {
13516 for (let name in o) {
13517 Color.defineFunction(name, o[name], o[name]);
13518 }
13519 }
13520 static extend(exports) {
13521 if (exports.register) {
13522 exports.register(Color);
13523 } else {
13524 // No register method, just add the module's functions
13525 for (let name in exports) {
13526 Color.defineFunction(name, exports[name]);
13527 }
13528 }
13529 }
13530 }
13531 Color.defineFunctions({
13532 get,
13533 getAll,
13534 set,
13535 setAll,
13536 to,
13537 equals,
13538 inGamut,
13539 toGamut,
13540 distance,
13541 deltas,
13542 toString: serialize
13543 });
13544 Object.assign(Color, {
13545 util,
13546 hooks,
13547 WHITES,
13548 Space: ColorSpace,
13549 spaces: ColorSpace.registry,
13550 parse,
13551 // Global defaults one may want to configure
13552 defaults
13553 });
13554
13555 /**
13556 * @packageDocumentation
13557 * This module contains {@link spaces a namespace} with all the spaces built into Color.js.
13558 */
13559 for (let key of Object.keys(spaces)) {
13560 ColorSpace.register(spaces[key]);
13561 }
13562
13563 // Add space accessors to existing color spaces
13564 for (let id in ColorSpace.registry) {
13565 addSpaceAccessors(id, ColorSpace.registry[id]);
13566 }
13567
13568 // Add space accessors to color spaces not yet created
13569 hooks.add("colorspace-init-end", space => {
13570 var _space$aliases;
13571 addSpaceAccessors(space.id, space);
13572 (_space$aliases = space.aliases) === null || _space$aliases === void 0 || _space$aliases.forEach(alias => {
13573 addSpaceAccessors(alias, space);
13574 });
13575 });
13576 function addSpaceAccessors(id, space) {
13577 let propId = id.replace(/-/g, "_");
13578 Object.defineProperty(Color.prototype, propId, {
13579 // Convert coords to coords in another colorspace and return them
13580 // Source colorspace: this.spaceId
13581 // Target colorspace: id
13582 get() {
13583 let ret = this.getAll(id);
13584 if (typeof Proxy === "undefined") {
13585 // If proxies are not supported, just return a static array
13586 return ret;
13587 }
13588
13589 // Enable color.spaceId.coordName syntax
13590 let proxy = new Proxy(ret, {
13591 has: /** @param {string} property */(obj, property) => {
13592 try {
13593 ColorSpace.resolveCoord([space, property]);
13594 return true;
13595 } catch (e) {}
13596 return Reflect.has(obj, property);
13597 },
13598 get: (obj, property, receiver) => {
13599 if (property && typeof property !== "symbol" && !(property in obj) && property in proxy) {
13600 let {
13601 index
13602 } = ColorSpace.resolveCoord([space, property]);
13603 if (index >= 0) {
13604 return obj[index];
13605 }
13606 }
13607 return Reflect.get(obj, property, receiver);
13608 },
13609 set: (obj, property, value, receiver) => {
13610 if (property && typeof property !== "symbol" && !(property in obj) || Number(property) >= 0) {
13611 let {
13612 index
13613 } = ColorSpace.resolveCoord([space, (/** @type {string} */property)]);
13614 if (index >= 0) {
13615 obj[index] = value;
13616
13617 // Update color.coords
13618 this.setAll(id, obj);
13619 return true;
13620 }
13621 }
13622 return Reflect.set(obj, property, value, receiver);
13623 }
13624 });
13625 return proxy;
13626 },
13627 // Convert coords in another colorspace to internal coords and set them
13628 // Target colorspace: this.spaceId
13629 // Source colorspace: id
13630 set(coords) {
13631 this.setAll(id, coords);
13632 },
13633 configurable: true,
13634 enumerable: true
13635 });
13636 }
13637
13638 /**
13639 * Entry point for the OOP flavor of the API
13640 * Import as `colorjs.io`
13641 */
13642 Color.extend(deltaEMethods);
13643 Color.extend({
13644 deltaE
13645 });
13646 Object.assign(Color, {
13647 deltaEMethods
13648 });
13649 Color.extend(variations);
13650 Color.extend({
13651 contrast
13652 });
13653 Color.extend(chromaticity);
13654 Color.extend(luminance);
13655 Color.extend(interpolation);
13656 Color.extend(contrastMethods);
13657
13658 return Color;
13659
13660 })();
13661 //# sourceMappingURL=color.global.legacy.js.map